Merge main into #6295

# Conflicts:
#	docs/gaps.md
#	docs/roadmap.md
#	docs/target-app-parity.md
This commit is contained in:
bflatastic committed 2026-11-19 14:50:17 +07:00
commit c528513911
103 files changed
+3678 -359

No files matched your search

+70 -25
View File
@@ -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 (<https://developer.apple.com/documentation/appkit/nsevent/tangentialpressure>).
/// 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();
+56 -14
View File
@@ -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
//! (<https://github.com/mirror/xserver/blob/master/hw/xwayland/xwayland-input.c>), 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<u16, Device>,
last: HashMap<u16, [Option<f32>; 4]>,
last: HashMap<u16, [Option<f32>; 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 })));
}
+7 -6
View File
@@ -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);
}
+34 -12
View File
@@ -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> {
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<Variation>,
/// 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<f64>,
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;
}
+66 -4
View File
@@ -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<f64> =
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<f64>, bearing: Option<f64>, rotation: Option<f64>) -> 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.
+13 -3
View File
@@ -198,14 +198,24 @@ pub fn export(doc: &Document, opts: &HpglOptions) -> Result<HpglOutput, String>
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<Vec<HpglOutput>, String> {
let regions: Vec<Rect> = 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<Rect> = 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());
}
+3 -2
View File
@@ -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
+6
View File
@@ -113,6 +113,11 @@ pub struct StrokeLayer {
/// pressure, it stays with this path.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rotation: Option<AngleProfile>,
/// 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<PressureProfile>,
}
/// 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
+3 -2
View File
@@ -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)>,
+5 -3
View File
@@ -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.
+52 -9
View File
@@ -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::<f32>(),
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)| {
+23 -1
View File
@@ -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::<usize>()
+ [&s.bearing, &s.rotation].into_iter().flatten().map(|p| vec_bytes(&p.points)).sum::<usize>()
+ 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);
+15
View File
@@ -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",
+1 -1
View File
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
+145 -16
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<super::fonts::UsedFont, usize>, t: &vectorcraft_doc::TextObject) {
let own: BTreeSet<super::fonts::UsedFont> = 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<String>);
@@ -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<super::fonts::UsedFont>,
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<Value> {
// 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<super::fonts::UsedFont, usize> = BTreeMap::new();
let mut images: BTreeMap<String, Value> = BTreeMap::new();
let mut image_rows: Vec<ImageRow> = 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<Value> {
}
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<Value> {
}
}
// 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<String> = fonts.iter().map(super::fonts::font_label).collect();
let (font_entries, font_rows): (Vec<Value>, Vec<(String, String)>) = fonts.iter().map(font_detail).unzip();
let font_names: Vec<String> = fonts.keys().map(super::fonts::font_label).collect();
let (font_uses, font_use_rows): (Vec<Value>, Vec<(String, String)>) = fonts.iter().map(|(f, n)| font_use(f, *n)).unzip();
let (font_entries, font_rows): (Vec<Value>, 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<Value> {
"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<Value> {
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]
+2 -2
View File
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<CommandSpec> {
"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
),
+37 -16
View File
@@ -22,15 +22,17 @@ pub(super) struct Sample {
tilt: Option<[f64; 2]>,
/// Barrel rotation, degrees clockwise.
rotation: Option<f64>,
/// The airbrush finger wheel, 0..1.
wheel: Option<f64>,
}
/// 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<Point> {
}
/// [`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<Vec<Sample>> {
let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?;
let pts: Vec<Sample> = a
@@ -79,7 +81,7 @@ pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Sampl
let key = format!("{key}[{at}]");
return Err(bad(cmd, format!("`{key}` must be an array of at most {MAX_ITEMS} entries")));
}
let mut pen = [None; 4];
let mut pen = [None; PEN_KEYS.len()];
for (i, ((key, range), slot)) in PEN_KEYS.iter().zip(PEN_RANGES).zip(&mut pen).enumerate() {
let given = match v {
Value::Array(xy) => xy.get(i + 2),
@@ -91,9 +93,9 @@ pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Sampl
Some(v) => 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::<Result<_>>()?;
if pts.is_empty() {
@@ -126,6 +128,15 @@ fn stroke_pressure(samples: &[Sample]) -> Option<PressureProfile> {
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<PressureProfile> {
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<PressureProfile>, Option<AngleProf
(tilt.flatten(), bearing.flatten(), rotation.flatten())
}
/// What a pen recorded along a stroke ([`StrokeLayer`]'s `pressure`, `tilt`, `bearing` and
/// `rotation`).
/// What a pen recorded along a stroke ([`StrokeLayer`]'s `pressure`, `tilt`, `bearing`,
/// `rotation` and `wheel`).
#[derive(Clone, Debug, Default, PartialEq)]
pub(super) struct PenRecord {
pressure: Option<PressureProfile>,
tilt: Option<PressureProfile>,
bearing: Option<AngleProfile>,
rotation: Option<AngleProfile>,
wheel: Option<PressureProfile>,
}
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;
}
}
+1 -1
View File
@@ -438,7 +438,7 @@ fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
/// 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`
+1 -1
View File
@@ -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;
+1 -1
View File
@@ -878,7 +878,7 @@ fn without_nodes(n: &Arc<Node>, 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<Option<Rect>> {
pub(super) fn page_rect(f: &Format, p: &Value) -> Result<Option<Rect>> {
let v = match p.get("rect") {
None | Some(Value::Null) => return Ok(None),
Some(v) => v,
+68 -7
View File
@@ -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<bool>) -> Result<Encoded> {
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<Vec<String>, String> {
let run = || -> Result<Vec<[u8; 3]>> {
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, &regions).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<T>(doc: &Document, p: &Value, f: impl FnOnce(&Document, Vec<Rect>) -> Result<T>) -> Result<T> {
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<bool>) -> Result<(Vec<usize>, Vec<Rect>)> {
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<bool>) ->
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::<Result<Vec<_>>>()?;
// The writer's own region check, so a dialog's check refuses what the writer refuses.
for r in &regions {
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<bool>) -> Result<Encoded> {
let opts = parse(p)?;
let (boards, regions) = boards(doc, p, use_artboards)?;
let plots = vectorcraft_cad::hpgl::export_regions(doc, &opts, &regions).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<bool>) ->
}
enc.add_setting_notes(out.setting_notes);
}
if enc.files.is_empty() {
return Err(bad(C, "the document has no artboard"));
}
let regions: Vec<vectorcraft_geom::Rect> = 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(&regions)));
Ok(enc)
@@ -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.
+45
View File
@@ -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);
}
+3 -2
View File
@@ -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.
+74 -1
View File
@@ -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<PressureProfile> {
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<f32>| {
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);
+21 -12
View File
@@ -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<bool> {
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],
+3 -1
View File
@@ -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}");
}
+156
View File
@@ -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::<Vec<_>>(), [(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<f64> = 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);
}
}
+17 -4
View File
@@ -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);
@@ -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,
+2 -1
View File
@@ -209,12 +209,13 @@ fn numbers(s: &str) -> Option<Vec<f64>> {
s.split_whitespace().map(|w| w.parse::<f64>().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<Variation> {
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),
+6 -5
View File
@@ -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
+27 -1
View File
@@ -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<Node> {
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<Node> {
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<Node> {
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
+102 -11
View File
@@ -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<NodeId> =
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<NodeId> = 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<Arc<Node>>| !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<Content>, 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<NodeId>)> {
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<Arc<Story>>], threads: &[(u32, Vec<NodeId>)]) -> BTreeSet<NodeId> {
let blank: BTreeSet<u32> =
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<NodeId>)>, frames: &BTreeSet<NodeId>, replaced: bool) -> BTreeSet<NodeId> {
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<Arc<Story>>],
template: Option<(f64, f64)>,
to_doc: Affine,
content: &mut [Content],
notes: &mut Vec<String>,
) {
// 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
+52 -18
View File
@@ -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<Made> {
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<Rect>) {
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<Made>]) -> bool {
@@ -122,7 +137,13 @@ pub(super) fn readable_all(infos: &[SlotInfo], made: &[Option<Made>]) -> 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<Option<Made>>, pages: [&[Vec<Arc<Node>>]; 2], warn: &mut Vec<String>) -> Vec<Content> {
pub(super) fn made_only(
infos: &[SlotInfo],
stories: &[Option<Arc<Story>>],
made: Vec<Option<Made>>,
pages: [&[Vec<Arc<Node>>]; 2],
warn: &mut Vec<String>,
) -> Vec<Content> {
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<Option<Made>>, 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<usize> =
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<Arc<Story>>], open: Vec<usize>) -> Vec<usize> {
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<Arc<Node>>]) {
let unread: Vec<usize> =
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<Arc<Story>>], content: &mut [Content], hidden: &[Vec<Arc<Node>>]) {
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;
}
+3 -2
View File
@@ -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<Arc<Node>>),
/// 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<Node>, Option<Rect>, bool),
/// Nothing the file lets this read.
Empty,
+269 -1
View File
@@ -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, &notes);
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, &notes);
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);
+1
View File
@@ -219,6 +219,7 @@ pub fn tool_definitions() -> Vec<Value> {
"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"]),
},
+6
View File
@@ -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)…",
+3 -2
View File
@@ -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()
+22 -3
View File
@@ -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();
+63 -1
View File
@@ -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);
}
+1 -1
View File
@@ -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"))]
+50
View File
@@ -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<OutlineFormat> {
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<OutlineFormat> {
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));
}
}
+4 -3
View File
@@ -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};
+9 -8
View File
@@ -102,17 +102,18 @@ pub(crate) fn pen_bearing(q: PenPose) -> Option<f64> {
(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<PenPose>, bearing: Option<f64>) -> [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<PenPose>, bearing: Option<f64>) -> [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).
+125 -22
View File
@@ -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<NodeId>,
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<Overlay>,
snap: HandleSnap,
/// Scissors uses the drawing tools' targets; Anchor Point keeps its own handle snap above.
scissors_snap: DrawSnap,
scissors_hover: Option<ScissorsHover>,
/// 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<Action> {
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<Action> {
fn key(&mut self, _cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec<Action> {
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<Action> {
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<Action> {
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,
+354
View File
@@ -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::<Vec<_>>());
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
+28 -15
View File
@@ -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<f32>,
/// 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<Option<PenPose>>,
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 {
+63 -18
View File
@@ -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<f32>| Some(PenPose { tilt: Some([x, -10.0]), rotation: r });
let leaning = |x: f32, r: Option<f32>| 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<f32>| 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<PenPose>, 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<PenPose>, 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));
}
+6
View File
@@ -384,6 +384,12 @@ pub(super) fn visible(cx: &ToolContext) -> Option<Rect> {
}
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 {
+34 -14
View File
@@ -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<PenPose>,
}
@@ -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<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wheel: Option<f32>,
}
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<PenPose> {
let num = |k: &str| e.get(k).and_then(Value::as_f64).filter(|f| f.is_finite());
let tilt = |v: Option<f64>| 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.
+270 -8
View File
@@ -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::<Vec<_>>());
}
/// 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::<Vec<_>>()})).unwrap();
let st = app.session.active().unwrap();
assert_eq!(st.doc.text_threads, threads.iter().map(|t| t.to_vec()).collect::<Vec<_>>());
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::<Vec<_>>());
}
/// 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::<Vec<_>>()})).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::<Vec<_>>()})).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]
+25 -1
View File
@@ -446,13 +446,37 @@ pub(super) type Underlines = std::sync::Arc<Vec<(Point, Point)>>;
/// [`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<Overlay> {
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<HashSet<NodeId>> = 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::<HashSet<_>>()).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]);
+2
View File
@@ -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,
@@ -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()));
}
+3 -2
View File
@@ -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:"));
+7 -3
View File
@@ -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, &params);
return Ok(Value::Null);
}
if f.id == "hpgl" {
hpgl_options::open(app, &params);
return Ok(Value::Null);
}
return io::export(app, Some(f.id), Some(path), &params);
}
};
+265
View File
@@ -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<String, Value> {
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<Vec<String>, String> {
let st = app.session.active().ok_or("no document")?;
let (doc, params) = source(st, d)?;
fileio::hpgl::automatic_pens(&doc, &params)
}
/// 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, &params).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<Vec<String>, 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<String> {
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<Value, String> {
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
}
+245 -7
View File
@@ -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<String, serde_json::Value> = 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<Vec<String>, 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"));
}
+13
View File
@@ -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 липсва
Can't render this file because it is too large.
+13
View File
@@ -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
Can't render this file because it contains an unexpected character in line 2 and column 73.
+13
View File
@@ -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
Can't render this file because it is too large.
+13
View File
@@ -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í
Can't render this file because it is too large.
+13
View File
@@ -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
Can't render this file because it is too large.
+13
View File
@@ -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
Can't render this file because it is too large.
+13
View File
@@ -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 λείπει
Can't render this file because it is too large.
+13
View File
@@ -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
Can't render this file because it is too large.
+13
View File
@@ -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
Can't render this file because it contains an unexpected character in line 2 and column 73.
+13
View File
@@ -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
Can't render this file because it is too large.
+3
View File
@@ -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 ગુમ
Can't render this file because it contains an unexpected character in line 72 and column 5.
+13
View File
@@ -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 अनुपलब्ध
Can't render this file because it is too large.
+13
View File
@@ -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
Can't render this file because it is too large.
+13
View File
@@ -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
Can't render this file because it contains an unexpected character in line 2572 and column 5.
+13
View File
@@ -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
Can't render this file because it is too large.
+13
View File
@@ -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 見つかりません
Can't render this file because it is too large.
+13
View File
@@ -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 აკლია
Can't render this file because it is too large.
+13
View File
@@ -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 없음
Can't render this file because it is too large.
+13
View File
@@ -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
Can't render this file because it is too large.
+13
View File
@@ -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
Can't render this file because it is too large.
+13
View File
@@ -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:
Can't render this file because it is too large.
+13
View File
@@ -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 отсутствует
Can't render this file because it is too large.
+13
View File
@@ -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
Can't render this file because it is too large.
+17 -4
View File
@@ -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]
+13
View File
@@ -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
Can't render this file because it is too large.
+13
View File
@@ -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 відсутній
Can't render this file because it is too large.
+13
View File
@@ -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
Can't render this file because it is too large.
+13
View File
@@ -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 缺失
Can't render this file because it is too large.
+13
View File
@@ -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 遺失
Can't render this file because it is too large.
+5
View File
@@ -1070,6 +1070,11 @@ fn run_ui_part12(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result
crate::dialogs::eps_options::open(app, p);
Ok(Value::Null)
}
"ui.hpglOptionsDialog" if app.session.active().is_none() => 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()),
+1 -1
View File
@@ -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(),
+6
View File
@@ -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)…",
+4 -2
View File
@@ -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<Document> {
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<Docu
st.tilt = Some(PressureProfile::sample());
st.bearing = Some(AngleProfile::sample());
st.rotation = Some(AngleProfile::sample());
st.wheel = Some(PressureProfile::sample());
// A gentle S-curve across the swatch (square tiles keep a quarter of it either side).
let mut bp = vectorcraft_geom::BezPath::new();
let margin = (h * 0.5).min(w * 0.25);
+59 -2
View File
@@ -107,7 +107,7 @@ fn brush_value(value: &str) -> &str {
/// Row `k` of Document Info section `id` (`label` and `value` as `document.info` gives them, the
/// label a name when `named`) with its value in the interface language, built from what
/// `document.info` (`info`) gives as values: the
/// units, the raster effects resolution, each brush's type, each font's file, match and
/// units, the raster effects resolution, each brush's type, each font's type and uses, each font's file, match and
/// embedding permission, each image's size and file, each Repeat object's kind and counts, and the
/// kinds of the gradients no swatch names. Names (fonts, files, faces, swatches) stay as they are.
/// None when the row's value is shown as `document.info` gives it, or the values do not match the
@@ -130,6 +130,7 @@ fn shown_value(info: &Value, id: &str, k: usize, (label, value): (&str, &str), n
_ => None,
},
"brushes" => Some(brush_value(value).to_string()),
"fonts" => font_use_value(entry("fontUses")?),
"fontDetails" => font_detail_value(entry("fontDetails")?),
"linkedImages" | "embeddedImages" => {
let linked = id == "linkedImages";
@@ -181,6 +182,19 @@ fn fill(template: &str, args: &[(&str, &str)]) -> String {
crate::i18n::fill_once(template, args)
}
/// A `fontUses` entry as Fonts shows it: the font's type (the format names TrueType and OpenType
/// stay as they are) and its number of uses in the language's plural forms.
fn font_use_value(e: &Value) -> Option<String> {
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.
+4
View File
@@ -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,
+15 -9
View File
@@ -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() });
}
+14 -2
View File
@@ -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`,
+2 -2
View File
@@ -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-supporLine truncated
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-supporLine truncated
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 `<title>`, 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) |
+19 -4
View File
@@ -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; estimLine truncated
> **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 dLine truncated
> 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. |
+51 -24
View File
@@ -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
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more