Merge main into fix/dynamic-text-leading-line-gap

This commit is contained in:
dotCooCoo committed 2026-11-26 10:17:11 -08:00
commit 6edde5c696
189 files changed
+12921 -634

No files matched your search

+9
View File
@@ -16,6 +16,15 @@
| `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT (selected option) | Unmodified; full license in file |
## Printing-condition characterization data
Fogra's terms (https://fogra.org/en/downloads/work-tools/characterisation-data): "Free use and redistribution of the Fogra characterisation data is permitted, including redistribution as part of commercial and non-commercial software, provided that the data are distributed unmodified and Fogra is identified as the source. The designation FOGRAxx may be used solely to identify the respective reference data. Such use does not imply certification, approval or endorsement by Fogra." VectorCraft computes its Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52) working spaces from these files at run time; the files themselves are not changed.
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `crates/color/data/FOGRA51.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5`, checked by a test) |
| `crates/color/data/FOGRA52.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6`, checked by a test) |
Every non-code asset in this repository (icons, images, fonts, example art, colour profiles, presets) is listed here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if an asset file is missing from this table.
**Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Generated
+1
View File
@@ -8480,6 +8480,7 @@ dependencies = [
"proptest",
"serde",
"serde_json",
"sha2 0.10.9",
"thiserror 2.0.21",
]
+11
View File
@@ -152,6 +152,17 @@ Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option.
Original copyright and full license notices are preserved in each hyph-*.tex file.
Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5.
FOGRA51 and FOGRA52 characterization data (crates/color/data/):
Source: Fogra Forschungsgesellschaft Druck e.V., www.fogra.org,
https://fogra.org/en/downloads/work-tools/characterisation-data. The files are distributed
unmodified. Fogra's terms: "Free use and redistribution of the Fogra characterisation data is
permitted, including redistribution as part of commercial and non-commercial software, provided
that the data are distributed unmodified and Fogra is identified as the source. The designation
FOGRAxx may be used solely to identify the respective reference data. Such use does not imply
certification, approval or endorsement by Fogra." VectorCraft's Coated CMYK (FOGRA51) and
Uncoated CMYK (FOGRA52) working spaces are computed from this data by VectorCraft's own code;
they are not Fogra profiles.
JPEG encoder dependency notices
+2
View File
@@ -142,8 +142,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-19: Set Fold Angle in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and a Fold Angle field with Reset in the Fold Lines panel): a crease, partial cut or perforation line can fold at its own angle, from -180° to 180°, instead of its role's 90° away from or toward the print; native files keep the angle, and the Fold Preview folds each hinge at the angle of the line with the most length in it (`addon.packaging.setFoldAngle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
- 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-20: Curvature Circle Tool Options (double-click the Curvature Circle tool): Snap Tolerance sets how near a path pulls the pointer, Snap with Smart Guides Off unchecked keeps it within the selection tolerance while Smart Guides are off, Annotate Radius hides the radius label, Anchors at Standard Positions off puts an anchor where the circle touches the path and one every 90° from there, and Use the Radius of Circular Arcs off gives a circular arc's own cubic curvature (`tool.setOption {tool: "curvatureCircle"}`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged.
+4
View File
@@ -189,6 +189,10 @@ pub(crate) fn services(window: Parent) -> Services {
open_in_application: Some(Box::new(open_in_application)),
// File → Print: the system's printers and print queue.
print: Some(Box::new(printing::SystemPrint)),
// The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens
// only while the active tool uses the wheel.
#[cfg(all(windows, not(target_vendor = "win7")))]
stylus_wheel: Some(Box::new(super::windows_wintab::set_wheel_used)),
..Default::default()
}
}
+1
View File
@@ -74,6 +74,7 @@ mod windows_cores;
mod windows_display_size;
mod windows_stylus;
mod windows_symbol_chars;
mod windows_wintab;
mod xwayland;
use std::sync::{Arc, Mutex};
+134 -15
View File
@@ -1,7 +1,8 @@
//! Windows pen tablets: with Windows Ink, winit reports a pen in contact as a touch and drops its
//! barrel button and which end of the pen is down. For each pointer message of a pen,
//! [`msg_hook`] reads the pen's `POINTER_PEN_INFO` before winit handles the message and writes its
//! pressure, end, tilt and rotation into the framework's [`PenSource`] ([`start`]):
//! pressure, end, tilt and rotation, and an airbrush pen's finger wheel, into the framework's
//! [`PenSource`] ([`start`]):
//! `PEN_FLAG_INVERTED` ("The pen is inverted") or `PEN_FLAG_ERASER` ("The eraser button is
//! pressed") is the eraser end
//! (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/pen-flags-constants>). Pointer
@@ -24,9 +25,12 @@
//! `rotation` in degrees 0..359 clockwise
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-pointer_pen_info>).
//! Toward the user is down the screen, so they are the sample's axes and direction as they come,
//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel.
//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel, which
//! comes from the tablet driver's Wintab interface instead, when it has one
//! ([`crate::windows_wintab`]).
#![cfg_attr(not(windows), allow(dead_code))]
use std::cell::Cell;
use std::sync::OnceLock;
use craft::behavior::PointerSample;
@@ -38,6 +42,8 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020;
/// `POINTER_MESSAGE_FLAG_INRANGE` (`winuser.h`): not set on the message of a pointer that has left
/// detection range.
const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002;
/// `POINTER_MESSAGE_FLAG_CANCELED` (`winuser.h`): the pointer's input was canceled.
const POINTER_MESSAGE_FLAG_CANCELED: usize = 0x8000;
/// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`.
const PEN_FLAG_INVERTED: u32 = 0x0002;
const PEN_FLAG_ERASER: u32 = 0x0004;
@@ -65,6 +71,13 @@ const WM_POINTERLEAVE: u32 = 0x024A;
/// A pen's tilt along x and y and its barrel rotation, in radians.
type Pose = ([f32; 2], f32);
thread_local! {
/// The pointer id of the pen whose leaving starts the Wintab wheel readings afresh: the pen that
/// took them, or the pen whose message last asked for the wheel when none has
/// ([`crate::windows_wintab::wheel_pen`]).
static WHEEL_PEN: Cell<Option<u32>> = const { Cell::new(None) };
}
/// The pen source [`msg_hook`] writes, once [`start`] has made it.
static FEED: OnceLock<PenSource> = OnceLock::new();
@@ -89,14 +102,22 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
let Some(pen) = FEED.get() else {
return false;
};
crate::windows_wintab::msg_hook(msg);
if forgets_wheel(msg.message, msg.wParam.0, WHEEL_PEN.get()) {
crate::windows_wintab::forget();
}
let read_pen = || {
let mut info = POINTER_PEN_INFO::default();
let id = (msg.wParam.0 & 0xffff) as u32;
// SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a
// pointer that is not a pen.
unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?;
unsafe { GetPointerPenInfo(id, &mut info) }.ok()?;
let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0;
let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0;
let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, id, eraser);
WHEEL_PEN.set(Some(crate::windows_wintab::wheel_pen(id)));
let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation);
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose))
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose, wheel))
};
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
@@ -111,8 +132,10 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags`
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
/// in contact that reports none; the eraser end while it is inverted or its eraser button is
/// pressed; and how it is held, `pose` ([`pen_pose`]).
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose) -> PointerSample {
/// pressed; how it is held, `pose` ([`pen_pose`]); and `wheel`, the airbrush finger wheel the tablet
/// driver's Wintab interface reported for the message, if any ([`crate::windows_wintab`]), kept
/// within 0..1 and none when it is not a number.
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose, wheel: Option<f32>) -> PointerSample {
let pressure = match pressure {
1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
_ if in_contact => 1.0,
@@ -122,6 +145,7 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (t
sample.tilt = tilt;
sample.rotation = rotation;
sample.eraser = pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0;
sample.wheel = wheel.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 1.0));
sample
}
@@ -134,6 +158,43 @@ fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> Pose {
([along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)], turn)
}
/// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message
/// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the
/// window, when the pointer is `pen`, the pen whose leaving starts them afresh. A touch or another
/// pen leaving keeps the readings.
fn forgets_wheel(message: u32, wparam: usize, pen: Option<u32>) -> bool {
if pen != Some((wparam & 0xffff) as u32) {
return false;
}
let flags = wparam >> 16;
match message {
WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => {
flags & POINTER_MESSAGE_FLAG_INRANGE == 0 || flags & POINTER_MESSAGE_FLAG_CANCELED != 0
}
WM_POINTERLEAVE => true,
_ => false,
}
}
/// Whether a pointer message that Windows sends to the window procedure, so that winit's message hook
/// never sees it, starts the Wintab wheel readings afresh ([`forgets_wheel`]): `WM_POINTERENTER` and
/// `WM_POINTERLEAVE` are sent
/// (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/wm-pointerleave>); the posted pointer
/// messages are left to [`msg_hook`].
fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option<u32>) -> bool {
matches!(message, WM_POINTERENTER | WM_POINTERLEAVE) && forgets_wheel(message, wparam, pen)
}
/// A message Windows sent to a window procedure of the thread, from the Wintab reader's hook on
/// them ([`crate::windows_wintab`]): a pen leaving the window starts the wheel readings afresh, as
/// [`msg_hook`] does for the messages it sees.
#[cfg(windows)]
pub fn sent_message(message: u32, wparam: usize) {
if sent_forgets_wheel(message, wparam, WHEEL_PEN.get()) {
crate::windows_wintab::forget();
}
}
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
/// not from a pen or a touch.
fn is_mouse(extra_info: u32) -> bool {
@@ -175,7 +236,7 @@ mod tests {
#[test]
fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() {
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT).eraser;
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT, None).eraser;
assert!(!eraser(0), "the tip");
assert!(!eraser(PEN_FLAG_BARREL), "the barrel button");
assert!(eraser(PEN_FLAG_INVERTED), "turned over");
@@ -194,19 +255,77 @@ mod tests {
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), ([0.0, 0.0], deg(359.0)), "a 6D Art Pen's barrel");
assert_eq!(pen_pose(all, 400, i32::MIN, 720), ([deg(90.0), deg(-90.0)], 0.0), "kept within the ranges");
let pose = pen_pose(all, 10, 20, 180);
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose);
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, None);
assert_eq!((sample.tilt, sample.rotation), pose);
}
#[test]
fn an_airbrush_wheel_goes_into_the_sample() {
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, Some(0.25)).wheel, Some(0.25));
let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION;
let pose = pen_pose(all, 10, 20, 180);
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, Some(0.75));
assert_eq!((sample.tilt, sample.rotation, sample.wheel), (pose.0, pose.1, Some(0.75)), "with the tilt and rotation");
assert_eq!(sample.pressure, 0.5, "the pressure as before");
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).wheel, None, "no wheel");
assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(f32::NAN)).wheel, None, "not a number");
assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(1.5)).wheel, Some(1.0), "kept within 0..1");
}
#[test]
fn leaving_range_or_the_window_and_a_cancel_forget_the_wheel() {
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
let canceled = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 7;
let pen = Some(7);
for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] {
assert!(!forgets_wheel(m, in_range, pen), "{m:#x}");
assert!(forgets_wheel(m, 7, pen), "out of range: {m:#x}");
assert!(forgets_wheel(m, canceled, pen), "canceled: {m:#x}");
}
assert!(forgets_wheel(WM_POINTERLEAVE, in_range, pen));
// WM_MOUSEMOVE and WT_PACKET.
assert!(!forgets_wheel(0x0200, 0, Some(0)));
assert!(!forgets_wheel(0x7FF0, 7, pen));
}
#[test]
fn another_pointer_leaving_keeps_the_wheel() {
// A touch, pointer 9, leaves the window and detection range while pen 7 hovers.
let touch_leaves = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9;
assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, Some(7)));
assert!(!forgets_wheel(WM_POINTERUPDATE, 9, Some(7)), "out of range");
let canceled = (POINTER_MESSAGE_FLAG_CANCELED << 16) | 9;
assert!(!forgets_wheel(WM_POINTERUP, canceled, Some(7)), "canceled");
assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, None), "no pen has read the wheel");
assert!(forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7, Some(7)), "the pen itself");
}
#[test]
fn the_sent_leave_of_the_wheel_pen_forgets_the_wheel() {
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
let pen = Some(7);
assert!(sent_forgets_wheel(WM_POINTERLEAVE, in_range, pen), "the pen leaves the window");
assert!(sent_forgets_wheel(WM_POINTERLEAVE, 7, pen), "or detection range");
assert!(!sent_forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9, pen), "another pointer leaves");
assert!(!sent_forgets_wheel(WM_POINTERLEAVE, in_range, None), "no pen has read the wheel");
assert!(!sent_forgets_wheel(WM_POINTERENTER, in_range, pen), "the pen comes over the window");
// Posted messages, which the message hook already sees.
for m in [WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] {
assert!(!sent_forgets_wheel(m, 7, pen), "{m:#x}");
}
// WT_CTXCLOSE.
assert!(!sent_forgets_wheel(0x7FF2, 7, pen));
}
#[test]
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 0.5);
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0);
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT), eraser_sample(0.0), "hovering");
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT).pressure, 1.0, "a pressure without the pressure mask is not one");
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0, "as winit, which gives no force for 0");
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT).pressure, 0.0);
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 0.5);
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0);
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT, None), eraser_sample(0.0), "hovering");
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pressure without the pressure mask is not one");
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0, "as winit, which gives no force for 0");
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT, None).pressure, 0.0);
}
#[test]
File diff suppressed because it is too large. Load diff
+1
View File
@@ -22,3 +22,4 @@ moxcms = "0.8"
[dev-dependencies]
proptest = { workspace = true }
serde_json = { workspace = true }
sha2 = { version = "0.10", default-features = false }
+2
View File
@@ -0,0 +1,2 @@
# The characterization data files are kept byte for byte as published (CRLF line endings).
*.txt -text
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+41 -6
View File
@@ -5,7 +5,9 @@
//! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB;
//! the desktop canvas converts it into the display's own profile last, in the app.
//! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model
//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers);
//! ([`generic`]); [`FOGRA51_CMYK`] and [`FOGRA52_CMYK`] are the same model computed from
//! Fogra's published characterization data ([`measured`]); [`DEVICE_CMYK`] is the old
//! profile-free formula (kept for exact legacy numbers);
//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
//! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with
//! the profiles [`use_document_profiles`] last put in place of the working spaces;
@@ -16,6 +18,7 @@
pub mod generic;
pub mod icc;
pub mod lab;
pub mod measured;
use std::cell::{Cell, RefCell};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -36,6 +39,12 @@ pub const DISPLAY_P3: &str = "Display P3";
pub const PROPHOTO_RGB: &str = "ProPhoto RGB";
/// Our parametric press model (see [`generic`]). Not an Adobe/ECI profile.
pub const GENERIC_CMYK: &str = "VectorCraft Generic CMYK (SWOP-like)";
/// VectorCraft's own press model computed from Fogra's FOGRA51 characterization data (offset on
/// premium coated paper, see [`measured`]).
pub const FOGRA51_CMYK: &str = "VectorCraft Coated CMYK (FOGRA51)";
/// VectorCraft's own press model computed from Fogra's FOGRA52 characterization data (offset on
/// wood-free uncoated paper, see [`measured`]).
pub const FOGRA52_CMYK: &str = "VectorCraft Uncoated CMYK (FOGRA52)";
/// Profile-free CMYK (`rgb = (1−c)(1−k)` …): uncalibrated, kept for legacy numbers.
pub const DEVICE_CMYK: &str = "Device CMYK (uncalibrated)";
/// The grey space greyscale exports are written in: sRGB's tone curve (a grey shows as on screen).
@@ -43,7 +52,7 @@ pub const GRAY: &str = "Gray (sRGB tone curve)";
/// Built-in RGB and CMYK working spaces, in menu order.
const BUILTIN_RGB: [&str; 4] = [SRGB, WIDE_GAMUT_RGB, DISPLAY_P3, PROPHOTO_RGB];
const BUILTIN_CMYK: [&str; 2] = [GENERIC_CMYK, DEVICE_CMYK];
const BUILTIN_CMYK: [&str; 4] = [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK];
/// Names earlier versions gave built-in profiles: (old name, current name). Settings, documents
/// and commands that still use an old name get the current profile.
@@ -239,6 +248,21 @@ fn generic() -> Arc<GenericCmyk> {
G.get_or_init(|| Arc::new(GenericCmyk::new(generic::swop_like()))).clone()
}
/// The working space of `condition`, computed from its data once and kept.
fn measured_space(condition: &measured::Condition) -> Result<Arc<GenericCmyk>, CmsError> {
static SPACES: [OnceLock<Option<Arc<GenericCmyk>>>; measured::CONDITIONS.len()] = [const { OnceLock::new() }; measured::CONDITIONS.len()];
let slot = measured::CONDITIONS.iter().position(|c| c.name == condition.name).and_then(|i| SPACES.get(i));
slot.and_then(|s| s.get_or_init(|| measured::model(condition).map(Arc::new)).clone())
.ok_or_else(|| CmsError::BadProfile(format!("{}: the {} data does not give a press model", condition.name, condition.reference)))
}
/// The registered printing condition a built-in CMYK working space characterizes: its reference
/// name, the `/OutputConditionIdentifier` of a PDF/X output intent, and the registry it belongs
/// to (by its current or legacy name). `None` for every other profile.
pub fn characterization(name: &str) -> Option<(&'static str, &'static str)> {
measured::condition(canonical_name(name)).map(|c| (c.reference, measured::REGISTRY))
}
static USER: RwLock<Vec<Arc<IccProfile>>> = RwLock::new(Vec::new());
/// Counts the profiles [`register_icc`] has registered ([`profiles_generation`]).
static PROFILES_GENERATION: AtomicU64 = AtomicU64::new(0);
@@ -259,7 +283,11 @@ fn user_profile(name: &str) -> Option<Arc<IccProfile>> {
}
fn cmyk_space(name: &str) -> Result<CmykSpace, CmsError> {
match canonical_name(name) {
let canonical = canonical_name(name);
if let Some(c) = measured::condition(canonical) {
return measured_space(c).map(CmykSpace::Generic);
}
match canonical {
GENERIC_CMYK => Ok(CmykSpace::Generic(generic())),
DEVICE_CMYK => Ok(CmykSpace::Device),
_ => match user_profile(name) {
@@ -382,9 +410,13 @@ pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
CmykSpace::Generic(g) => g.paper_xyz(),
CmykSpace::Device | CmykSpace::Icc(_) => lab::D50,
};
let copyright = match measured::condition(name) {
Some(c) => format!("Computed by VectorCraft from the {} characterization data. Data source: Fogra, www.fogra.org", c.reference),
None => icc::NO_COPYRIGHT.to_string(),
};
let to_lab = |c| cms.cmyk_to_lab(c);
let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric);
icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
icc::encode(&icc::cmyk_profile(name, paper, &copyright, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
} else {
icc::builtin_rgb_bytes(name)?
}
@@ -496,7 +528,8 @@ impl Cms {
/// directly into the RGB profile: not through display sRGB, which would clip colours a wider
/// RGB space holds (Wide Gamut RGB keeps CMYK cyan that sRGB can't show), and with the
/// settings' black-point compensation. The built-in CMYK spaces go through sRGB as before
/// (Generic CMYK compensates in its own model).
/// (Generic CMYK compensates in its own model); with the absolute colorimetric intent the
/// paper colour shows.
pub fn cmyk_to_rgb(&self, cmyk: [f32; 4], intent: Intent) -> [f32; 3] {
let cmyk = cmyk.map(|v| v.clamp(0.0, 1.0));
let src = match &self.cmyk {
@@ -509,7 +542,7 @@ impl Cms {
};
src.zip(dest)
.and_then(|(s, d)| s.to_rgb_of(&d, &cmyk, intent, self.settings.bpc))
.unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, false)))
.unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, intent == Intent::AbsoluteColorimetric)))
}
/// Display sRGB → working CMYK with `intent`.
pub fn srgb_to_cmyk(&self, srgb: [f32; 3], intent: Intent) -> [f32; 4] {
@@ -1315,3 +1348,5 @@ pub(crate) fn cmyk_is_device() -> bool {
mod tests;
#[cfg(test)]
mod tests_icc;
#[cfg(test)]
mod tests_measured;
+30 -2
View File
@@ -30,6 +30,7 @@ use std::sync::OnceLock;
use super::Intent;
use super::lab::{D50, Lab, delta_e2000, lab_to_xyz, srgb_to_lab, xyz_to_lab, xyz_to_srgb};
use super::measured::Lattice;
/// Black generation.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -129,6 +130,9 @@ pub struct GenericCmyk {
paper_xyz: [f32; 3],
/// Media-relative XYZ of the black point (for black-point compensation).
black_rel: [f32; 3],
/// A media-relative Lab correction added to the model, fitted to measured data
/// ([`super::measured`]).
correction: Option<Lattice>,
gbd: OnceLock<Gbd>,
}
@@ -139,6 +143,15 @@ impl GenericCmyk {
}
pub fn new(params: GenericCmykParams) -> Self {
Self::build(params, None)
}
/// The model of `params` with `correction` added to its media-relative Lab.
pub fn with_correction(params: GenericCmykParams, correction: Lattice) -> Self {
Self::build(params, Some(correction))
}
fn build(params: GenericCmykParams, correction: Option<Lattice>) -> Self {
let paper_xyz = lab_to_xyz(params.paper);
let mut prim = [D50; 16];
for (p, lab) in prim[1..].iter_mut().zip(params.primaries.iter()) {
@@ -149,7 +162,7 @@ impl GenericCmyk {
let g = params.tvi50[i];
if g > 1e-6 { (1.0 - params.tvi40[i] / (0.96 * g)) / 0.2 } else { 0.0 }
});
let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() };
let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], correction, gbd: OnceLock::new() };
g.black_rel = g.to_xyz_rel(g.black_point_build());
g
}
@@ -218,6 +231,14 @@ impl GenericCmyk {
/// Media-relative XYZ (paper = D50 white).
pub fn to_xyz_rel(&self, cmyk: [f32; 4]) -> [f32; 3] {
match &self.correction {
Some(_) => lab_to_xyz(self.to_lab_rel(cmyk)),
None => self.neugebauer(cmyk),
}
}
/// Media-relative XYZ of the Neugebauer model alone.
fn neugebauer(&self, cmyk: [f32; 4]) -> [f32; 3] {
let e = [0, 1, 2, 3].map(|i| self.gain(i, cmyk[i]));
let mut out = [0.0f32; 3];
for (i, p) in self.prim.iter().enumerate() {
@@ -236,7 +257,14 @@ impl GenericCmyk {
}
pub fn to_lab_rel(&self, cmyk: [f32; 4]) -> Lab {
xyz_to_lab(self.to_xyz_rel(cmyk))
let lab = xyz_to_lab(self.neugebauer(cmyk));
match &self.correction {
Some(c) => {
let d = c.at(cmyk);
Lab::new((lab.l + d[0]).max(0.0), lab.a + d[1], lab.b + d[2])
}
None => lab,
}
}
pub fn to_lab_abs(&self, cmyk: [f32; 4]) -> Lab {
xyz_to_lab(self.to_xyz(cmyk))
+12 -4
View File
@@ -432,10 +432,17 @@ fn text_tag(s: &str) -> Option<ProfileText> {
Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), s.into())]))
}
/// The copyright text of profiles made here: they carry no copyright claim.
pub(super) const NO_COPYRIGHT: &str = "No copyright, use freely";
/// Profiles made here carry their name and no copyright claim.
fn labelled(mut p: ColorProfile, name: &str) -> ColorProfile {
fn labelled(p: ColorProfile, name: &str) -> ColorProfile {
with_copyright(p, name, NO_COPYRIGHT)
}
fn with_copyright(mut p: ColorProfile, name: &str, copyright: &str) -> ColorProfile {
p.description = text_tag(name);
p.copyright = text_tag("No copyright, use freely");
p.copyright = text_tag(copyright);
p
}
@@ -452,10 +459,11 @@ const GAMUT_GRID: usize = 9;
/// It carries every tag ICC.1 requires of an output profile: the tables for all three intents
/// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK
/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which
/// the ICC-absolute colorimetric intent reproduces.
/// the ICC-absolute colorimetric intent reproduces; the copyright tag holds `copyright`.
pub(super) fn cmyk_profile(
name: &str,
paper: [f32; 3],
copyright: &str,
to_lab: impl Fn([f32; 4]) -> lab::Lab,
mapped: impl Fn(lab::Lab) -> [f32; 4],
colorimetric: impl Fn(lab::Lab) -> [f32; 4],
@@ -520,7 +528,7 @@ pub(super) fn cmyk_profile(
p.lut_b_to_a_saturation = Some(b2a_mapped);
p.lut_b_to_a_colorimetric = Some(b2a);
p.gamut = Some(gamut);
labelled(p, name)
with_copyright(p, name, copyright)
}
/// The grey space of greyscale exports: sRGB's tone curve, D50 white.
+378
View File
@@ -0,0 +1,378 @@
//! CMYK working spaces computed from published characterization data.
//!
//! Fogra publishes the measured colors of its reference printing conditions
//! (<https://fogra.org/en/downloads/work-tools/characterisation-data>) and allows the data to be
//! redistributed unmodified, with Fogra named as the source. VectorCraft embeds the FOGRA51 and
//! FOGRA52 files byte for byte (`crates/color/data/`) and computes each press model from them the
//! first time it is used:
//!
//! * The paper is the measured blank patch. The 15 solids and overprints of the
//! [`super::generic`] model are the measured patches of those builds, and each ink's tone curve
//! is fitted to its single-ink ramp.
//! * What that model still misses at each patch (in media-relative Lab) is fitted with a smoothed
//! lattice over CMYK ([`Lattice`]), which [`GenericCmyk::to_xyz_rel`] adds to the model. The
//! smoothing carries the fit into regions the patch set does not sample, such as dark builds
//! with more than 60% black.
//!
//! The total ink limit and the black generation are VectorCraft's own values.
use super::generic::{GenericCmyk, GenericCmykParams, swop_like};
use super::lab::{D50, Lab, lab_to_xyz, xyz_to_lab};
/// A printing condition with published characterization data.
#[derive(Clone, Copy, Debug)]
pub struct Condition {
/// The working space's name.
pub name: &'static str,
/// The reference name of the characterization data, which a PDF/X output intent uses as
/// its `/OutputConditionIdentifier`.
pub reference: &'static str,
/// The characterization data file, as published.
pub data: &'static [u8],
/// Total area coverage limit (sum of inks, 1.0 = 100%): VectorCraft's own value.
pub tac: f32,
}
/// The registry that the reference names of [`CONDITIONS`] belong to
/// (<https://registry.color.org/cmyk-registry/>).
pub const REGISTRY: &str = "http://www.color.org";
/// The printing conditions VectorCraft computes working spaces for.
pub const CONDITIONS: [Condition; 2] = [
Condition { name: super::FOGRA51_CMYK, reference: "FOGRA51", data: include_bytes!("../../data/FOGRA51.txt"), tac: 3.0 },
Condition { name: super::FOGRA52_CMYK, reference: "FOGRA52", data: include_bytes!("../../data/FOGRA52.txt"), tac: 3.0 },
];
/// The condition a working space of [`CONDITIONS`] is computed for.
pub fn condition(name: &str) -> Option<&'static Condition> {
CONDITIONS.iter().find(|c| c.name == name)
}
/// One measured patch: nominal inks (0..1) and absolute Lab (D50).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Patch {
pub cmyk: [f32; 4],
pub lab: Lab,
}
/// The most patches [`parse`] reads.
const MAX_PATCHES: usize = 20_000;
/// The patches of a CGATS / ISO 28178 characterization data file with `CMYK_C`, `CMYK_M`,
/// `CMYK_Y`, `CMYK_K`, `LAB_L`, `LAB_A` and `LAB_B` fields. `None` when a field is missing, a
/// row is short or holds a value that is not a finite number, an ink is outside 0 to 100, the
/// file has no rows, the rows do not end with `END_DATA`, or a `NUMBER_OF_SETS` in the header is
/// not the number of rows.
pub fn parse(data: &[u8]) -> Option<Vec<Patch>> {
let text = std::str::from_utf8(data).ok()?;
let sets = text.lines().map(str::trim).take_while(|l| *l != "BEGIN_DATA").find_map(|l| {
let mut words = l.split_whitespace();
(words.next() == Some("NUMBER_OF_SETS")).then(|| words.next().map(|n| n.trim_matches('"')))
});
let sets = match sets {
Some(n) => Some(n?.parse::<usize>().ok()?),
None => None,
};
let mut lines = text.lines().map(str::trim);
lines.by_ref().find(|l| *l == "BEGIN_DATA_FORMAT")?;
let mut fields = vec![];
for line in lines.by_ref() {
if line == "END_DATA_FORMAT" {
break;
}
fields.extend(line.split_whitespace());
}
let at = |f: &str| fields.iter().position(|x| *x == f);
let cols = [at("CMYK_C")?, at("CMYK_M")?, at("CMYK_Y")?, at("CMYK_K")?, at("LAB_L")?, at("LAB_A")?, at("LAB_B")?];
lines.by_ref().find(|l| *l == "BEGIN_DATA")?;
let mut out = vec![];
let mut ended = false;
for line in lines {
if line == "END_DATA" {
ended = true;
break;
}
if line.is_empty() {
continue;
}
if out.len() >= MAX_PATCHES {
return None;
}
let row: Vec<&str> = line.split_whitespace().collect();
let mut v = [0f32; 7];
for (slot, &col) in v.iter_mut().zip(&cols) {
*slot = row.get(col)?.parse::<f32>().ok().filter(|x| x.is_finite())?;
}
if v[..4].iter().any(|x| !(0.0..=100.0).contains(x)) {
return None;
}
out.push(Patch { cmyk: [v[0], v[1], v[2], v[3]].map(|x| x / 100.0), lab: Lab::new(v[4], v[5], v[6]) });
}
(ended && !out.is_empty() && sets.is_none_or(|n| n == out.len())).then_some(out)
}
/// Absolute Lab → media-relative Lab (`paper` maps to the D50 white).
fn relative(lab: Lab, paper: [f32; 3]) -> Lab {
let x = lab_to_xyz(lab);
xyz_to_lab([0, 1, 2].map(|i| x[i] * D50[i] / paper[i]))
}
/// The mean of the Lab values of the patches whose inks are `inks`, in XYZ.
fn mean_lab(patches: &[Patch], inks: [f32; 4]) -> Option<Lab> {
let mut sum = [0f32; 3];
let mut n = 0;
for p in patches.iter().filter(|p| p.cmyk.iter().zip(&inks).all(|(a, b)| (a - b).abs() < 1e-4)) {
let x = lab_to_xyz(p.lab);
for i in 0..3 {
sum[i] += x[i];
}
n += 1;
}
(n > 0).then(|| xyz_to_lab(sum.map(|v| v / n as f32)))
}
/// The tone value increase at 50% and 40% of ink `ink`, fitted to its single-ink ramp with the
/// curve of [`super::generic`]: the effective area is `a + u·4a(1−a) + v·4a(1−a)(2a−1)`, so the
/// 50% increase is `u` and the 40% increase is `0.96·u − 0.192·v`. Each patch's effective area
/// comes from the Murray–Davies formula in the media-relative XYZ channel the ink darkens most
/// (`paper` is the paper's absolute XYZ, `solid` the solid's media-relative XYZ).
fn tone_increase(patches: &[Patch], ink: usize, paper: [f32; 3], solid: [f32; 3]) -> Option<(f32, f32)> {
let ch = (0..3).max_by(|&a, &b| (D50[a] - solid[a]).abs().total_cmp(&(D50[b] - solid[b]).abs()))?;
let span = D50[ch] - solid[ch];
if span.abs() < 1e-4 {
return None;
}
let (mut s11, mut s12, mut s22, mut r1, mut r2) = (0f64, 0f64, 0f64, 0f64, 0f64);
for p in patches {
let a = p.cmyk[ink];
let alone = p.cmyk.iter().enumerate().all(|(i, v)| i == ink || *v == 0.0);
if !alone || a <= 0.0 || a >= 1.0 {
continue;
}
let e = (D50[ch] - relative_xyz(p.lab, paper)[ch]) / span;
let (b1, b2) = (f64::from(4.0 * a * (1.0 - a)), f64::from(4.0 * a * (1.0 - a) * (2.0 * a - 1.0)));
let d = f64::from(e - a);
s11 += b1 * b1;
s12 += b1 * b2;
s22 += b2 * b2;
r1 += b1 * d;
r2 += b2 * d;
}
let det = s11 * s22 - s12 * s12;
if det.abs() < 1e-12 {
return None;
}
let u = ((r1 * s22 - r2 * s12) / det) as f32;
let v = ((s11 * r2 - s12 * r1) / det) as f32;
let tvi50 = u.clamp(0.0, 0.45);
let tvi40 = (0.96 * u - 0.192 * v).clamp(0.0, 0.45);
Some((tvi50, tvi40))
}
/// Absolute Lab → media-relative XYZ.
fn relative_xyz(lab: Lab, paper: [f32; 3]) -> [f32; 3] {
let x = lab_to_xyz(lab);
[0, 1, 2].map(|i| x[i] * D50[i] / paper[i])
}
/// The press model of `condition`, computed from its data. `None` when the data does not parse,
/// lacks the paper, a solid or overprint, or a single-ink ramp, or gives a paper whose XYZ is not
/// positive and finite.
pub fn model(condition: &Condition) -> Option<GenericCmyk> {
fit(condition, &parse(condition.data)?, SMOOTHING)
}
/// The press model of `condition` fitted to `patches`, with the lattice's `smoothing` (`None` in
/// the cases [`model`] lists).
pub(crate) fn fit(condition: &Condition, patches: &[Patch], smoothing: f64) -> Option<GenericCmyk> {
let paper = mean_lab(patches, [0.0; 4])?;
let paper_xyz = lab_to_xyz(paper);
if paper_xyz.iter().any(|v| !v.is_finite() || *v <= 0.0) {
return None;
}
let mut primaries = [Lab::new(0.0, 0.0, 0.0); 15];
for (i, slot) in primaries.iter_mut().enumerate() {
let bits = i + 1;
let inks = [0, 1, 2, 3].map(|b| if bits & (1 << b) != 0 { 1.0 } else { 0.0 });
*slot = relative(mean_lab(patches, inks)?, paper_xyz);
}
let mut tvi50 = [0f32; 4];
let mut tvi40 = [0f32; 4];
for ink in 0..4 {
let solid = lab_to_xyz(primaries[(1 << ink) - 1]);
(tvi50[ink], tvi40[ink]) = tone_increase(patches, ink, paper_xyz, solid)?;
}
let params = GenericCmykParams { name: condition.name, paper, primaries, tvi50, tvi40, tac: condition.tac, bg: swop_like().bg };
let base = GenericCmyk::new(params.clone());
let points: Vec<([f32; 4], [f32; 3])> = patches
.iter()
.map(|p| {
let want = relative(p.lab, paper_xyz);
let got = base.to_lab_rel(p.cmyk);
(p.cmyk, [want.l - got.l, want.a - got.a, want.b - got.b])
})
.collect();
Some(GenericCmyk::with_correction(params, Lattice::fit(&points, smoothing)))
}
/// Weight of the lattice's smoothness against its fit to the patches.
pub(crate) const SMOOTHING: f64 = 0.02;
/// Knots of each ink's axis of the [`Lattice`]: the steps of the published single-ink ramps.
const KNOTS: [f32; 9] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.55, 0.7, 0.85, 1.0];
const N: usize = KNOTS.len();
const NODES: usize = N * N * N * N;
/// A Lab correction over CMYK, read by multilinear interpolation between nodes at [`KNOTS`].
#[derive(Clone, Debug)]
pub struct Lattice {
values: Vec<[f32; 3]>,
}
/// The cell of `v` along an axis and its position in it.
fn locate(v: f32) -> (usize, f32) {
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
let i = KNOTS.iter().skip(1).position(|k| v <= *k).unwrap_or(N - 2).min(N - 2);
let (lo, hi) = (KNOTS[i], KNOTS[i + 1]);
(i, ((v - lo) / (hi - lo)).clamp(0.0, 1.0))
}
/// The 16 nodes around `cmyk` with their interpolation weights.
fn corners(cmyk: [f32; 4]) -> [(usize, f32); 16] {
let cells = cmyk.map(locate);
let mut out = [(0, 0.0); 16];
for (corner, slot) in out.iter_mut().enumerate() {
let mut index = 0;
let mut w = 1.0;
for (axis, (cell, t)) in cells.iter().enumerate() {
let up = corner & (1 << axis) != 0;
index = index * N + cell + usize::from(up);
w *= if up { *t } else { 1.0 - t };
}
*slot = (index, w);
}
out
}
/// Index strides of the four axes (C is the slowest).
const STRIDES: [usize; 4] = [N * N * N, N * N, N, 1];
impl Lattice {
/// The correction at `cmyk`.
pub fn at(&self, cmyk: [f32; 4]) -> [f32; 3] {
let mut out = [0f32; 3];
for (i, w) in corners(cmyk) {
if w == 0.0 {
continue;
}
let v = self.values.get(i).copied().unwrap_or_default();
for c in 0..3 {
out[c] += w * v[c];
}
}
out
}
/// The lattice that best fits `points` (inks, correction) in the least-squares sense, with
/// `smoothing` times the squared second differences of the nodes along each axis added to the
/// error. The node at no ink stays 0, so the paper keeps the model's color (white, media-
/// relative). Solved by conjugate gradients, one Lab channel at a time.
pub fn fit(points: &[([f32; 4], [f32; 3])], smoothing: f64) -> Lattice {
let weights: Vec<[(usize, f32); 16]> = points.iter().map(|(cmyk, _)| corners(*cmyk)).collect();
// The divided second difference at interior knot j, scaled to a unit spacing of 1/8.
let curvature: Vec<[f64; 3]> = (1..N - 1)
.map(|j| {
let (h1, h2) = (f64::from(KNOTS[j] - KNOTS[j - 1]), f64::from(KNOTS[j + 1] - KNOTS[j]));
let s = 0.125f64 * 0.125;
[2.0 / (h1 * (h1 + h2)) * s, -2.0 / (h1 * h2) * s, 2.0 / (h2 * (h1 + h2)) * s]
})
.collect();
let apply = |x: &[f64], out: &mut [f64]| {
out.fill(0.0);
for w in &weights {
let v: f64 = w.iter().map(|(i, w)| f64::from(*w) * x.get(*i).copied().unwrap_or(0.0)).sum();
for (i, w) in w {
if let Some(o) = out.get_mut(*i) {
*o += f64::from(*w) * v;
}
}
}
for node in 0..NODES {
let mut rest = node;
for stride in STRIDES {
let j = rest / stride;
rest %= stride;
// Only interior knots (1 to N − 2) have a second difference.
let Some(c) = j.checked_sub(1).and_then(|k| curvature.get(k)) else { continue };
let idx = [node - stride, node, node + stride];
let d: f64 = idx.iter().zip(c).map(|(i, c)| c * x.get(*i).copied().unwrap_or(0.0)).sum();
for (i, c) in idx.iter().zip(c) {
if let Some(o) = out.get_mut(*i) {
*o += smoothing * c * d;
}
}
}
}
for (o, v) in out.iter_mut().zip(x) {
*o += 1e-9 * v;
}
// The paper's node is held: with its right-hand side 0 it stays 0 in every iterate.
if let (Some(o), Some(v)) = (out.first_mut(), x.first()) {
*o = *v;
}
};
let mut values = vec![[0f32; 3]; NODES];
for ch in 0..3 {
let mut b = vec![0f64; NODES];
for (w, (_, r)) in weights.iter().zip(points) {
for (i, w) in w {
if let Some(o) = b.get_mut(*i) {
*o += f64::from(*w) * f64::from(r[ch]);
}
}
}
if let Some(o) = b.first_mut() {
*o = 0.0;
}
let x = conjugate_gradients(&apply, &b, 4000);
for (v, x) in values.iter_mut().zip(&x) {
v[ch] = *x as f32;
}
}
Lattice { values }
}
}
/// Solve `A x = b` for the symmetric positive definite `A` that `apply` multiplies by.
fn conjugate_gradients(apply: &dyn Fn(&[f64], &mut [f64]), b: &[f64], max_iterations: usize) -> Vec<f64> {
let n = b.len();
let mut x = vec![0f64; n];
let mut r = b.to_vec();
let mut p = r.clone();
let mut ap = vec![0f64; n];
let dot = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(a, b)| a * b).sum::<f64>();
let mut rr = dot(&r, &r);
let stop = rr * 1e-20;
for _ in 0..max_iterations {
if rr <= stop || rr == 0.0 {
break;
}
apply(&p, &mut ap);
let pap = dot(&p, &ap);
if pap <= 0.0 || !pap.is_finite() {
break;
}
let alpha = rr / pap;
for i in 0..n {
x[i] += alpha * p[i];
r[i] -= alpha * ap[i];
}
let next = dot(&r, &r);
let beta = next / rr;
rr = next;
for i in 0..n {
p[i] = r[i] + beta * p[i];
}
}
x
}
+250
View File
@@ -0,0 +1,250 @@
use super::*;
use sha2::{Digest, Sha256};
fn hex(bytes: &[u8]) -> String {
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
}
/// The data files ship exactly as Fogra publishes them in
/// https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip.
#[test]
fn characterization_data_is_the_published_files() {
let want = [
("FOGRA51", "ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5", 57_111),
("FOGRA52", "be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6", 56_781),
];
for (c, (reference, sha, len)) in measured::CONDITIONS.iter().zip(want) {
assert_eq!(c.reference, reference);
assert_eq!((c.data.len(), hex(c.data).as_str()), (len, sha), "{reference}");
}
}
#[test]
fn the_data_parses_into_its_patches() {
for c in &measured::CONDITIONS {
let patches = measured::parse(c.data).unwrap();
assert_eq!(patches.len(), 1617, "{}", c.reference);
assert_eq!(patches[0].cmyk, [0.0; 4]);
}
let p = measured::parse(measured::CONDITIONS[0].data).unwrap();
assert_eq!(p[0].lab, Lab::new(95.0, 1.5, -6.0));
assert_eq!(p[1].cmyk, [0.0, 0.1, 0.0, 0.0]);
assert_eq!(p[1].lab, Lab::new(90.08, 8.15, -7.42));
}
#[test]
fn malformed_data_is_refused() {
let file = |format: &str, rows: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{format}\nEND_DATA_FORMAT\nBEGIN_DATA\n{rows}\nEND_DATA\n");
let fields = "SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B";
let good = file(fields, "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50");
assert_eq!(measured::parse(good.as_bytes()).map(|p| p.len()), Some(2));
for bad in [
file("SAMPLE_ID CMYK_C CMYK_M CMYK_Y LAB_L LAB_A LAB_B", "1 0 0 0 95 1 -6"),
file(fields, "1 0 0 0 0 95 1"),
file(fields, "1 0 0 0 0 95 NaN -6"),
file(fields, "1 0 0 0 0 95 x -6"),
file(fields, "1 0 0 0 101 95 1 -6"),
file(fields, "1 -1 0 0 0 95 1 -6"),
file(fields, ""),
"BEGIN_DATA\n1 0 0 0 0 95 1 -6\nEND_DATA\n".into(),
] {
assert_eq!(measured::parse(bad.as_bytes()), None, "{bad}");
}
assert_eq!(measured::parse(&[0xff, 0xfe, 0x00]), None);
// The rows end with END_DATA, and a NUMBER_OF_SETS in the header counts them.
let rows = "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50";
let header = |sets: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{fields}\nEND_DATA_FORMAT\n{sets}\nBEGIN_DATA\n{rows}\n");
assert_eq!(measured::parse(header("NUMBER_OF_SETS\t2").as_bytes()), None, "no END_DATA");
for (sets, len) in [
("NUMBER_OF_SETS\t2", Some(2)),
("NUMBER_OF_SETS\t3", None),
("NUMBER_OF_SETS\t1", None),
("NUMBER_OF_SETS\tx", None),
("NUMBER_OF_SETS", None),
] {
assert_eq!(measured::parse(format!("{}END_DATA\n", header(sets)).as_bytes()).map(|p| p.len()), len, "{sets}");
}
}
/// A paper measured as black has no XYZ to make the other patches relative to.
#[test]
fn a_paper_without_light_is_refused() {
let c = &measured::CONDITIONS[0];
let mut patches = measured::parse(c.data).unwrap();
for p in patches.iter_mut().filter(|p| p.cmyk == [0.0; 4]) {
p.lab = Lab::new(0.0, 0.0, 0.0);
}
assert!(measured::fit(c, &patches, measured::SMOOTHING).is_none());
}
/// ΔE2000 between each measured patch and the model's absolute Lab for its inks: (mean, max).
fn accuracy(g: &GenericCmyk, patches: &[measured::Patch]) -> (f32, f32) {
let errors: Vec<f32> = patches.iter().map(|p| delta_e2000(g.to_lab_abs(p.cmyk), p.lab)).collect();
(errors.iter().sum::<f32>() / errors.len() as f32, errors.iter().copied().fold(0.0, f32::max))
}
#[test]
fn the_working_spaces_reproduce_the_measured_patches() {
for c in &measured::CONDITIONS {
let patches = measured::parse(c.data).unwrap();
let start = std::time::Instant::now();
let g = measured::model(c).unwrap();
let took = start.elapsed();
let (mean, max) = accuracy(&g, &patches);
println!("{}: computed in {took:?}, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference);
assert!(mean < 0.1 && max < 0.6, "{}: mean {mean}, max {max}", c.reference);
// The paper is the measured blank patch.
assert!(delta_e2000(g.to_lab_abs([0.0; 4]), patches[0].lab) < 0.05);
}
}
/// A model fitted without every fourth patch (the paper and the solids and overprints stay in)
/// predicts the patches it left out. The data repeats some builds, and every row of a build is
/// on the side of the build's first row, so the fit never sees a left-out build.
#[test]
fn the_fit_predicts_patches_it_left_out() {
for c in &measured::CONDITIONS {
let patches = measured::parse(c.data).unwrap();
let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0);
let first = |p: &measured::Patch| patches.iter().position(|q| q.cmyk == p.cmyk).unwrap_or(0);
let (kept, left): (Vec<&measured::Patch>, Vec<_>) = patches.iter().partition(|p| first(p) % 4 != 3 || corner(p));
assert!(left.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference);
let kept: Vec<measured::Patch> = kept.into_iter().copied().collect();
let left: Vec<measured::Patch> = left.into_iter().copied().collect();
let g = measured::fit(c, &kept, measured::SMOOTHING).unwrap();
let (mean, max) = accuracy(&g, &left);
println!("{}: {} patches left out, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference, left.len());
assert!(mean < 0.3 && max < 2.5, "{}: mean {mean}, max {max}", c.reference);
}
}
/// More of any ink makes a build lighter by less than 0.3 L*, also where the data has few patches
/// (black above 60%, and builds over the ink limit).
#[test]
fn more_ink_lightens_a_build_by_less_than_0_3_l() {
let steps: Vec<f32> = (0..=20).map(|i| i as f32 / 20.0).collect();
let coarse = [0.0, 0.25, 0.5, 0.75, 1.0];
for c in &measured::CONDITIONS {
let g = measured::model(c).unwrap();
let mut worst = 0f32;
for ink in 0..4 {
for a in coarse {
for b in coarse {
for d in coarse {
let mut others = [a, b, d].into_iter();
let mut build = [0f32; 4];
for (i, slot) in build.iter_mut().enumerate() {
if i != ink {
*slot = others.next().unwrap();
}
}
let mut last = f32::INFINITY;
for &v in &steps {
build[ink] = v;
let l = g.to_lab_rel(build).l;
worst = worst.max(l - last);
last = l;
}
}
}
}
}
println!("{}: largest L* rise with more ink {worst:.3}", c.reference);
assert!(worst < 0.3, "{}: {worst}", c.reference);
}
}
#[test]
fn the_working_spaces_follow_generic_cmyk_in_the_list() {
let cmyk: Vec<String> = profiles().into_iter().filter(|p| p.kind == ProfileKind::Cmyk && p.builtin).map(|p| p.name).collect();
assert_eq!(cmyk, [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK]);
assert_eq!(ColorSettings::default().cmyk, GENERIC_CMYK);
assert_eq!(characterization(FOGRA51_CMYK), Some(("FOGRA51", "http://www.color.org")));
assert_eq!(characterization(FOGRA52_CMYK), Some(("FOGRA52", "http://www.color.org")));
assert_eq!(characterization(GENERIC_CMYK), None);
assert!(matches!(register_icc(&icc_bytes(FOGRA51_CMYK).unwrap(), None), Err(CmsError::Unsupported(_))));
}
#[test]
fn colors_separate_and_come_back_in_the_measured_spaces() {
for name in [FOGRA51_CMYK, FOGRA52_CMYK] {
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap();
// A 50% gray (L* 53) lies well inside both measured gamuts (the darkest patches measure
// L* 11.43 and 26.36), so it comes back whatever the gamut check says.
let gray = [0.5, 0.5, 0.5];
for srgb in [[0.8, 0.3, 0.2], [0.2, 0.5, 0.7], gray, [0.9, 0.85, 0.6], [0.1, 0.1, 0.1]] {
let inks = cms.srgb_to_cmyk(srgb, Intent::RelativeColorimetric);
assert!(inks.iter().sum::<f32>() <= 3.0 + 1e-3, "{name} {srgb:?}: {inks:?}");
if srgb == gray || cms.gamut_error(&Color::Rgb { r: srgb[0], g: srgb[1], b: srgb[2] }) < GAMUT_THRESHOLD {
let back = cms.cmyk_to_srgb(inks, false);
let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(back));
assert!(de < 1.5, "{name} {srgb:?}: {inks:?} -> {back:?} (ΔE {de})");
}
}
// White is paper with no ink, and black is the darkest build within the ink limit.
assert_eq!(cms.srgb_to_cmyk([1.0; 3], Intent::RelativeColorimetric), [0.0; 4]);
let black = cms.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
assert!(black[3] > 0.8 && black.iter().sum::<f32>() <= 3.0 + 1e-3, "{name}: {black:?}");
}
// The coated paper prints a larger gamut than the uncoated one.
let blue = Color::Rgb { r: 0.1, g: 0.2, b: 0.6 };
let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap();
let uncoated = Cms::new(&ColorSettings { cmyk: FOGRA52_CMYK.into(), ..ColorSettings::default() }).unwrap();
assert!(coated.gamut_error(&blue) < uncoated.gamut_error(&blue));
}
/// Absolute Lab of `cmyk` in a context whose CMYK space is one of the Generic-type spaces.
fn absolute_lab(cms: &Cms, cmyk: [f32; 4]) -> Lab {
match &cms.cmyk {
CmykSpace::Generic(g) => g.to_lab_abs(cmyk),
CmykSpace::Device | CmykSpace::Icc(_) => panic!("not a Generic-type CMYK space"),
}
}
#[test]
fn absolute_cmyk_to_rgb_shows_the_paper() {
for name in [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK] {
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap();
let paper = cms.cmyk_to_rgb([0.0; 4], Intent::AbsoluteColorimetric);
assert_eq!(paper, cms.srgb_to_rgb(cms.cmyk_to_srgb([0.0; 4], true)), "{name}");
assert_ne!(paper, cms.cmyk_to_rgb([0.0; 4], Intent::RelativeColorimetric), "{name}");
}
}
#[test]
fn absolute_cmyk_conversion_keeps_the_source_paper() {
// Generic CMYK's paper (L* 93, b* 2.5) is darker and yellower than FOGRA51's (L* 95, b* -6),
// so printing it on FOGRA51 paper takes ink.
let generic = Cms::new(&ColorSettings { cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap();
let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap();
let Color::Cmyk { c, m, y, k } = generic.convert_into(&coated, &Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 }, Intent::AbsoluteColorimetric)
else {
panic!("a CMYK colour converts to CMYK");
};
let inks = [c, m, y, k];
assert!(inks.iter().sum::<f32>() > 0.01, "{inks:?}");
let de = delta_e2000(absolute_lab(&coated, inks), absolute_lab(&generic, [0.0; 4]));
assert!(de < 2.0, "{inks:?}: ΔE {de}");
}
#[test]
fn the_profiles_carry_the_paper_and_the_data_source() {
for c in &measured::CONDITIONS {
let start = std::time::Instant::now();
let bytes = icc_bytes(c.name).unwrap();
println!("{}: {} bytes in {:?}", c.reference, bytes.len(), start.elapsed());
let p = moxcms::ColorProfile::new_from_slice(&bytes).unwrap();
assert_eq!(
(p.profile_class, p.color_space, p.pcs),
(moxcms::ProfileClass::OutputDevice, moxcms::DataColorSpace::Cmyk, moxcms::DataColorSpace::Lab)
);
assert!(p.lut_a_to_b_perceptual.is_some() && p.lut_b_to_a_perceptual.is_some() && p.lut_a_to_b_colorimetric.is_some());
let paper = lab::lab_to_xyz(measured::parse(c.data).unwrap()[0].lab);
let white = p.media_white_point.unwrap();
for (got, want) in [white.x, white.y, white.z].iter().zip(paper) {
assert!((*got - f64::from(want)).abs() < 2e-3, "{}: {white:?} vs {paper:?}", c.reference);
}
let text = format!("{:?}", p.copyright);
assert!(text.contains(c.reference) && text.contains("Fogra"), "{text}");
}
}
+27 -5
View File
@@ -131,6 +131,13 @@ impl Node {
matches!(self.kind, NodeKind::Layer { template: true, .. })
}
/// Whether a view that hides template layers (`templates`) or guides (`guides`) leaves this
/// object out: a template layer while templates are hidden, or a path made into a guide while
/// guides are hidden. The canvas draws ruler guides apart from the art.
pub fn hidden_by_view(&self, templates: bool, guides: bool) -> bool {
(templates && self.is_template()) || (guides && matches!(self.kind, NodeKind::Path { guide: true, .. }))
}
/// The art objects of this container: its children, looking through sublayers, which are not
/// objects (bottom first). With `editable`, only the visible, unlocked objects in visible,
/// unlocked, non-template sublayers.
@@ -360,17 +367,32 @@ impl Node {
self.geometric(Some(symbols))
}
/// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a
/// hidden bitmap for re-tracing/release; only source-image views measure that bitmap.
/// Children that contribute to a container's editing bounds. A live trace retains a hidden bitmap for
/// re-tracing/release; only source-image views measure that bitmap. Selection highlights outline
/// [`Node::drawn_children`].
pub fn editing_children(&self) -> &[Arc<Node>] {
let children = self.children().map(Vec::as_slice).unwrap_or_default();
let trace_source = self.extras().trace.is_some()
&& !self.trace_view().shows_source()
&& children.first().is_some_and(|n| !n.visible && matches!(n.kind, NodeKind::Image(_)));
let trace_source = !self.trace_view().shows_source() && self.trace_source().is_some_and(|n| !n.visible);
let skip = usize::from(self.extras().shaper.is_some() || trace_source);
children.get(skip..).unwrap_or_default()
}
/// The children a selection highlight outlines: [`Node::editing_children`] without the hidden
/// members, which the canvas does not draw. An Image Trace object's hidden source image stays
/// when the object's view shows it, and every path of a compound path stays, since the compound
/// path draws all of them.
pub fn drawn_children(&self) -> impl Iterator<Item = &Arc<Node>> {
let members = !matches!(self.kind, NodeKind::Compound { .. });
let source = self.trace_source().filter(|_| self.trace_view().shows_source());
self.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)))
}
/// The first child of an Image Trace object when it is an image: the bitmap the trace keeps.
fn trace_source(&self) -> Option<&Arc<Node>> {
self.extras().trace.as_ref()?;
self.children()?.first().filter(|n| matches!(n.kind, NodeKind::Image(_)))
}
/// The box of [`Node::geometric_bounds`], or of [`Node::geometric_bounds_with`] when `symbols`
/// is given.
pub(crate) fn geometric(&self, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
+3 -3
View File
@@ -326,21 +326,21 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"stylize.dropShadow",
"Drop Shadow…",
STYLIZE,
"{mode: blend mode (\"multiply\"), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)",
"{mode: blend mode (\"multiply\"; normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color or luminosity, in any letter case), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)",
json!({"mode": "multiply", "opacity": 75.0, "x": 7.0, "y": 7.0, "blur": 5.0, "shade": "color", "color": "#000000", "darkness": 100.0}),
),
r(
"stylize.innerGlow",
"Inner Glow…",
STYLIZE,
"{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}",
"{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}",
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffffff", "source": "edge"}),
),
r(
"stylize.outerGlow",
"Outer Glow…",
STYLIZE,
"{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}",
"{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}",
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}),
),
r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})),
+3 -2
View File
@@ -82,11 +82,12 @@ pub use group::{
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use params::{blend_mode_id, parse_blend_mode, takes_blend_mode};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use placement::pinned_gradient_item;
pub use raster::{
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
without_geometry,
RASTERIZE, RasterFx, Rasterize, blend_mode, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps,
staged_effects, without_geometry,
};
pub use reshape::{
SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster,
+22
View File
@@ -1,6 +1,28 @@
use vectorcraft_doc::color::BlendMode;
use super::catalog::{catalog_index, plugin_info};
use super::{CROP_MARKS, Effect, Map, Node, PIXEL_EFFECTS, RASTERIZE, Value, is_adjustment, is_pathfinder, is_three_d, json, util};
/// Whether parameter `key` of effect `effect` is the blend mode the effect draws in.
pub fn takes_blend_mode(effect: &str, key: &str) -> bool {
key == "mode" && matches!(effect, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow")
}
/// Read a blend mode name as the effect renderer does. Case and punctuation do not change the mode.
pub fn parse_blend_mode(s: &str) -> Option<BlendMode> {
let name: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
BlendMode::parse(&name)
}
/// The name an effect stores for blend mode `mode`, such as `normal`, `multiply`, or `colorBurn`.
pub fn blend_mode_id(mode: BlendMode) -> String {
let mut name = format!("{mode:?}");
if let Some(first) = name.get_mut(..1) {
first.make_ascii_lowercase();
}
name
}
/// Dialog defaults for `id` (`None` for unknown effects).
pub fn default_params(id: &str) -> Option<Value> {
match catalog_index().get(id) {
+1 -1
View File
@@ -845,7 +845,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
pub use addons::{fold_source, print_hidden};
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
/// Document Info's category titles, the Objects category's count labels, and how its image rows
/// write a resolution and a number of bytes.
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
+1 -1
View File
@@ -17,7 +17,7 @@ mod typetools;
mod units;
pub(crate) use image::{DecodedImages, refresh_color_masks};
pub use packaging::{fold_source, print_hidden};
pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
use super::CommandSpec;
+6 -2
View File
@@ -2,13 +2,16 @@
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Set
//! Fold Angle ([`angle`]) gives a fold line its own angle. Its submenu (Object › Plug-ins ›
//! Packaging Tools) and its Fold Lines panel are the UI's.
mod angle;
mod check;
mod fold;
mod roles;
pub use angle::{FoldAngles, selection_fold_angles, selection_fold_lines};
pub use fold::{fold_source, print_hidden};
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
@@ -17,6 +20,7 @@ use super::super::CommandSpec;
pub fn specs() -> Vec<CommandSpec> {
let mut v = roles::specs();
v.extend(check::specs());
v.extend(angle::specs());
v.extend(fold::specs());
v
}
@@ -0,0 +1,266 @@
//! Set Fold Angle (`addon.packaging.setFoldAngle`): the angle each fold line folds at. A Crease,
//! Partial Cut or Perforation line keeps its own angle in its data under [`KEY`], as a number of
//! degrees from -180 to 180; without one it folds at its role's angle (90° for a Crease or a
//! Perforation, -90° for a Partial Cut). A positive angle folds away from the printed side.
use std::collections::HashSet;
use std::sync::{Arc, Weak};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_three_d::fold::kept_angle;
use super::super::super::edit::refuse_symbol_part;
use super::super::super::overprint::edit_counted;
use super::super::super::pathops::number_given;
use super::super::super::{CommandSpec, bad, cmd, switch_or};
use super::check::kind;
use super::roles::{Role, RoleTable, editable_members, role_targets, taken_roots};
use crate::{Result, Session};
/// Object data key: a fold line's own fold angle, in degrees. Native save keeps it; SVG export
/// leaves `vc-` keys out.
pub(crate) const KEY: &str = "vc-fold-angle";
const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle";
/// The range a fold angle may take, in degrees.
const RANGE: std::ops::RangeInclusive<f64> = -180.0..=180.0;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.packaging.setFoldAngle",
"Set Fold Angle…",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{angle?: degrees -180..180, reset?: bool (false), ids?: [id…] (default: the selection)} give each Crease, Partial Cut and Perforation line among the objects (addon.packaging.roles; through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) its own fold angle, rounded to the millionth of a degree, or with reset: true take it away, so the line folds at its role's angle again: 90° for a Crease or a Perforation, -90° for a Partial Cut. A positive angle folds the panel away from the printed side, a negative one toward it; addon.packaging.fold and the Fold Preview window fold each hinge at the angle of the line with the most length in it. Cut lines and objects without a role are skipped and counted. Give exactly one of angle and reset: true. One undo step, none when nothing changes → {ids (the fold lines changed or kept), changed, skipped}",
has_fold_line,
set_fold_angle
)]
}
/// Why Set Fold Angle has nothing to change.
const NO_FOLD_LINE: &str = "select a crease, partial cut or perforation line that is neither locked nor hidden";
/// The last answer of [`has_fold_line`], with what it was for.
struct Answer {
/// The document (a weak reference keeps another document from taking the same address).
doc: Weak<Document>,
revision: u64,
/// The objects looked at: the selection, or the `ids` a command was given in its place.
objects: Vec<NodeId>,
found: bool,
}
thread_local! {
/// Menus ask [`has_fold_line`] on every refresh, and its answer changes only with the
/// document, its revision and the objects looked at.
static LAST_ANSWER: std::cell::RefCell<Option<Answer>> = const { std::cell::RefCell::new(None) };
}
/// The selection holds a line that folds and that Set Fold Angle can change, or an id of no object.
fn has_fold_line(s: &Session) -> std::result::Result<(), String> {
refuse_symbol_part(s).map_err(|e| e.to_string())?;
let st = s.doc().map_err(|e| e.to_string())?;
let objects = &st.selection.objects;
let kept = LAST_ANSWER.with_borrow(|last| match last {
Some(a) if a.revision == st.revision && a.objects == *objects && Weak::ptr_eq(&a.doc, &Arc::downgrade(&st.doc)) => Some(a.found),
_ => None,
});
let found = kept.unwrap_or_else(|| {
// An id of no object (given as `ids`) is left to the command, which names it.
let found = objects.iter().any(|id| st.doc.node(*id).is_none()) || any_fold_line(&st.doc, objects);
LAST_ANSWER.set(Some(Answer { doc: Arc::downgrade(&st.doc), revision: st.revision, objects: objects.clone(), found }));
found
});
if found { Ok(()) } else { Err(NO_FOLD_LINE.into()) }
}
/// Whether the objects `roots` of `d` hold a line that folds and can be changed, looking through
/// groups and clip groups as [`role_targets`] does and stopping at the first. As [`taken_roots`]
/// takes them, an object inside another one given is left out (a crease in a selected layer counts
/// no more than the layer does), a layer is left out, and a path of a compound path stands for the
/// compound path, which holds its role, unless it is locked or hidden.
fn any_fold_line(d: &Document, roots: &[NodeId]) -> bool {
fn find(n: &Node, hit: &dyn Fn(&Node) -> bool) -> bool {
match &n.kind {
// A group's clipping path draws no stroke.
NodeKind::Group { children, .. } => children.iter().any(|c| !matches!(c.kind, NodeKind::Path { clipping: true, .. }) && find(c, hit)),
_ => hit(n),
}
}
let table = RoleTable::of(d);
let editable = d.editable();
let hit = |n: &Node| table.role_of(n).is_some_and(folds) && editable(n.id);
let given: HashSet<NodeId> = roots.iter().copied().collect();
// Each object's place, from the document's lookup of ids.
let outer = |id: NodeId| -> Option<NodeId> {
let a = d.ancestry(id)?;
let (_, up) = a.split_last()?;
if up.iter().any(|p| given.contains(p)) {
return None;
}
match up.last().copied().filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))) {
// A locked or hidden path of a compound path is left out, as `editable_members` leaves it.
Some(_) if !editable(id) => None,
Some(compound) => Some(compound),
None => Some(id),
}
};
// An object given twice is looked through once.
let mut seen = HashSet::new();
roots
.iter()
.filter_map(|id| outer(*id))
.filter(|id| seen.insert(*id))
.filter_map(|id| d.node(id))
.filter(|n| !n.is_layer())
.any(|n| find(n, &hit))
}
/// The text `n`'s data holds under [`KEY`], if any.
fn stored(n: &Node) -> Option<&str> {
n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str())
}
/// `n`'s own fold angle: the number its data holds under [`KEY`], when it is a finite number from
/// -180 to 180, to the millionth of a degree it folds at ([`kept_angle`]). Anything else reads as
/// no angle of its own.
pub(super) fn own_angle(n: &Node) -> Option<f64> {
stored(n)?.trim().parse::<f64>().ok().filter(|a| a.is_finite() && RANGE.contains(a)).map(kept_angle)
}
/// Whether a line with `role` folds: every role but Cut.
pub(super) fn folds(role: Role) -> bool {
kind(role).fold_angle().is_some()
}
/// Writes `angle` (`None`: takes it away) into object `id`'s data → whether its data changed.
fn store(d: &mut Document, id: NodeId, angle: Option<f64>) -> bool {
// `+ 0.0` turns -0 into 0, so a line set to 0° reads "0".
let text = angle.map(|a| format!("{}", a + 0.0));
// Read first: taking the node to change it copies it, its geometry included. An angle stored
// as other text for the same number ("45.0") is kept; a reset removes any stored text.
let same = |n: &Node| match angle {
Some(a) => own_angle(n) == Some(a),
None => stored(n).is_none(),
};
if d.node(id).is_none_or(same) {
return false;
}
let Some(n) = d.node_mut(id) else { return false };
n.edit_attrs(|a| match text {
Some(text) => match a.data.iter_mut().find(|(k, _)| k == KEY) {
Some(e) => e.1 = text,
None => a.data.push((KEY.into(), text)),
},
None => a.data.retain(|(k, _)| k != KEY),
});
true
}
fn set_fold_angle(s: &mut Session, p: &Value) -> Result<Value> {
let angle = number_given(p, "angle", SET_FOLD_ANGLE)?;
let reset = switch_or(p, "reset", false, SET_FOLD_ANGLE)?;
let angle = match (angle, reset) {
(Some(_), true) => return Err(bad(SET_FOLD_ANGLE, "give `angle` or `reset: true`, not both")),
(None, false) => return Err(bad(SET_FOLD_ANGLE, "missing `angle`")),
(Some(a), false) if !RANGE.contains(&a) => return Err(bad(SET_FOLD_ANGLE, "`angle` must be from -180 to 180 degrees")),
// Kept to the millionth of a degree, the angle the line folds at.
(a, _) => a.map(kept_angle),
};
let (roots, named) = taken_roots(s, p, SET_FOLD_ANGLE)?;
let d = &s.doc()?.doc;
let (targets, skipped) = role_targets(d, &roots, false);
let mut skipped = skipped + named;
let mut ids = folding(d, &RoleTable::of(d), &targets);
{
let editable = d.editable();
ids.retain(|id| editable(*id));
}
skipped += targets.len() - ids.len();
if ids.is_empty() {
return Err(bad(SET_FOLD_ANGLE, NO_FOLD_LINE));
}
let label = if angle.is_some() { "Set Fold Angle" } else { "Reset Fold Angle" };
let changed = edit_counted(s, label, |d| Ok(ids.iter().filter(|id| store(d, **id, angle)).count()))?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed, "skipped": skipped }))
}
/// The lines among `ids` of `d` that fold (Crease, Partial Cut, Perforation), in order.
fn folding(d: &Document, table: &RoleTable, ids: &[NodeId]) -> Vec<NodeId> {
ids.iter().copied().filter(|id| d.node(*id).and_then(|n| table.role_of(n)).is_some_and(folds)).collect()
}
/// What Set Fold Angle can change among the objects `roots` of `d` (through groups and clip
/// groups, leaving out what is locked or hidden, as `addon.packaging.setFoldAngle` does).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FoldAngles {
/// How many lines that fold it can change.
pub lines: usize,
/// The angle they all fold at (their own or their role's); `None` when they differ or there
/// are none.
pub angle: Option<f64>,
/// How many of them have an angle of their own.
pub own: usize,
/// How many of them hold text under [`KEY`], an angle or not: what `reset: true` takes away.
pub stored: usize,
}
/// The [`FoldAngles`] of the selected objects of the active document, as Set Fold Angle reads them
/// with no `ids` (nothing, while it would refuse the selection).
pub fn selection_fold_angles(s: &Session) -> FoldAngles {
match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) {
(Ok((roots, _)), Ok(st)) => fold_angles(&st.doc, &roots),
_ => FoldAngles::default(),
}
}
/// The lines Set Fold Angle changes among the selected objects of the active document, as it takes
/// them with no `ids` (none, while it would refuse the selection). Given back as `ids`, they are the
/// lines it changes.
pub fn selection_fold_lines(s: &Session) -> Vec<NodeId> {
match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) {
(Ok((roots, _)), Ok(st)) => changeable(&st.doc, &roots).into_iter().map(|(n, _)| n.id).collect(),
_ => Vec::new(),
}
}
/// The [`FoldAngles`] of the outermost objects `roots` of `d`.
pub(super) fn fold_angles(d: &Document, roots: &[NodeId]) -> FoldAngles {
let mut f = FoldAngles::default();
for (n, role) in changeable(d, roots) {
f.add(n, role);
}
f
}
/// The lines that fold among the outermost objects `roots` of `d` that Set Fold Angle can change,
/// with their roles, in order.
fn changeable<'a>(d: &'a Document, roots: &[NodeId]) -> Vec<(&'a Node, Role)> {
let table = RoleTable::of(d);
let editable = d.editable();
let targets = role_targets(d, &editable_members(d, roots.to_vec()).0, false).0;
// The role first: whether an object can be edited can take its bounds to find out.
targets
.iter()
.filter_map(|id| d.node(*id))
.filter_map(|n| table.role_of(n).filter(|r| folds(*r)).filter(|_| editable(n.id)).map(|r| (n, r)))
.collect()
}
impl FoldAngles {
/// Counts line `n`, which has `role` and can be changed; a line that does not fold is left out.
pub(super) fn add(&mut self, n: &Node, role: Role) {
let Some(default) = kind(role).fold_angle() else { return };
let own = own_angle(n);
let a = own.unwrap_or(default);
self.angle = if self.lines == 0 { Some(a) } else { self.angle.filter(|b| *b == a) };
self.lines += 1;
self.own += usize::from(own.is_some());
self.stored += usize::from(stored(n).is_some());
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,409 @@
//! Tests for Set Fold Angle: a fold line's own angle, where it is kept, and how the fold uses it.
use serde_json::{Value, json};
use super::{KEY, fold_angles, own_angle};
use crate::*;
const SET: &str = "addon.packaging.setFoldAngle";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
s
}
fn path(s: &mut Session, d: &str) -> u64 {
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
}
fn role(s: &mut Session, role: &str, ids: &[u64]) {
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn err(s: &mut Session, p: Value) -> String {
s.execute(SET, &p).unwrap_err().to_string()
}
/// The text object `id`'s data holds under the fold angle key.
fn stored(s: &Session, id: u64) -> Option<String> {
let d = &s.doc().unwrap().doc;
let n = d.node(NodeId(id)).unwrap();
n.extras().attrs.as_deref().and_then(|a| a.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.clone()))
}
/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side →
/// (outline, creases: top, right, bottom, left).
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
role(s, "cut", &[outline]);
role(s, "crease", &creases);
s.execute("select.none", &json!({})).unwrap();
(outline, creases)
}
/// Whether panel `p` of a fold is the tray's top wall (y 100 to 140): the middle of the bounds of
/// its outline's points (absolute moves and lines only) is above the base.
fn top_wall(p: &Value) -> bool {
let d = p["outline"].as_str().unwrap();
let n: Vec<f64> = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect();
let ys = n.iter().skip(1).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t)));
(ys.0 + ys.1) / 2.0 < 140.0
}
fn vector(v: &Value) -> [f64; 3] {
let a = v.as_array().unwrap();
[a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()]
}
#[test]
fn set_fold_angle_keeps_the_angle_on_the_line_and_reset_takes_it_away() {
let mut s = session();
let (_, creases) = tray(&mut s);
let before = steps(&s);
let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(0), &json!([creases[0]])), "{r}");
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
assert_eq!(steps(&s), before + 1, "one undo step");
// The same angle again changes nothing and records no undo step.
let r = s.execute(SET, &json!({"angle": 45.0, "ids": [creases[0]]})).unwrap();
assert_eq!(r["changed"].as_u64(), Some(0));
assert_eq!(steps(&s), before + 1);
// An angle is kept to the millionth of a degree, so one closer to 45 than that is 45.
let r = s.execute(SET, &json!({"angle": 45.00000001, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before + 1), "{r}");
s.execute(SET, &json!({"angle": 179.99999998, "ids": [creases[3]]})).unwrap();
assert_eq!(stored(&s, creases[3]).as_deref(), Some("180"));
s.execute("edit.undo", &json!({})).unwrap();
// A number as text, and the selection when ids is left out; -0 is kept as 0.
s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap();
let r = s.execute(SET, &json!({"angle": "-0"})).unwrap();
assert_eq!(r["changed"].as_u64(), Some(2), "{r}");
assert_eq!(stored(&s, creases[1]).as_deref(), Some("0"));
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0], creases[1], creases[3]]})).unwrap();
assert_eq!(r["changed"].as_u64(), Some(2), "the line without an angle of its own is unchanged: {r}");
assert_eq!((stored(&s, creases[0]), stored(&s, creases[1])), (None, None));
// Nothing left to reset: no undo step.
let at = steps(&s);
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), at));
// Undo brings the angle back.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
}
#[test]
fn bad_angles_and_targets_are_refused() {
let mut s = session();
let (outline, creases) = tray(&mut s);
let plain = path(&mut s, "M10 10 L50 50");
let before = steps(&s);
let ids = json!([creases[0]]);
assert!(err(&mut s, json!({"ids": ids})).contains("missing `angle`"));
assert!(err(&mut s, json!({"angle": 30, "reset": true, "ids": ids})).contains("not both"));
assert!(err(&mut s, json!({"angle": 180.5, "ids": ids})).contains("from -180 to 180"));
assert!(err(&mut s, json!({"angle": -181, "ids": ids})).contains("from -180 to 180"));
assert!(err(&mut s, json!({"angle": "wide", "ids": ids})).contains("must be a number"));
assert!(err(&mut s, json!({"angle": true, "ids": ids})).contains("must be a number"));
assert!(err(&mut s, json!({"reset": "yes", "ids": ids})).contains("true or false"));
// A cut line and a path without a role do not fold.
assert!(err(&mut s, json!({"angle": 30, "ids": [outline, plain]})).contains("crease, partial cut or perforation"));
// An id of no object is named as such, alone or beside a crease.
assert!(err(&mut s, json!({"angle": 30, "ids": [999_999]})).contains("no such object id 999999"));
assert!(err(&mut s, json!({"angle": 30, "ids": [creases[0], 999_999]})).contains("no such object id 999999"));
assert_eq!(steps(&s), before, "no refusal records an undo step");
// The ends of the range are allowed; cut lines and plain paths among fold lines are skipped.
let r = s.execute(SET, &json!({"angle": -180, "ids": [creases[0], outline, plain]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(2), &json!([creases[0]])), "{r}");
s.execute(SET, &json!({"angle": 180, "ids": [creases[0]]})).unwrap();
assert_eq!(stored(&s, creases[0]).as_deref(), Some("180"));
assert_eq!(stored(&s, outline), None);
}
#[test]
fn set_fold_angle_is_dimmed_without_a_line_it_can_change() {
let mut s = session();
let (outline, creases) = tray(&mut s);
let enabled = |s: &Session| (find_command(SET).unwrap().enabled)(s).is_ok();
assert!(!enabled(&s), "nothing selected");
s.execute("select.set", &json!({"ids": [outline]})).unwrap();
assert!(!enabled(&s), "a cut line does not fold");
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
s.execute("select.set", &json!({"ids": [creases[0]]})).unwrap();
assert!(enabled(&s));
s.execute("object.lock", &json!({})).unwrap();
assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(creases[0])]).lines, 0, "a locked crease can't be changed");
// A group holding a crease is enough.
s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
assert!(enabled(&s));
// A layer selected with a crease in it: the crease is inside the layer, which is left out, as
// Set Fold Angle itself leaves them out.
let layer = s.doc().unwrap().doc.layer_of(NodeId(creases[3])).unwrap();
s.execute("select.set", &json!({"ids": [layer.0, creases[3]]})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "both are selected");
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
assert!(!enabled(&s), "dimmed as the command refuses it");
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}");
// With nothing selected the counts are the document's, but Set Fold Angle takes no line.
s.execute("select.set", &json!({"ids": []})).unwrap();
assert!(s.execute(SET, &json!({"angle": 30})).is_err());
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!(r["scope"].as_str(), Some("document"), "{r}");
assert_eq!(r["roles"][1]["count"].as_u64(), Some(4), "{r}");
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}");
}
#[test]
fn a_crease_named_in_ids_is_set_after_the_menu_found_none_in_the_selection() {
let mut s = session();
let (outline, creases) = tray(&mut s);
s.execute("select.set", &json!({"ids": [outline]})).unwrap();
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "a cut line does not fold");
let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap();
assert_eq!(r["changed"].as_u64(), Some(1), "{r}");
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "the selection is still the cut line");
}
#[test]
fn the_selection_s_fold_angles_count_a_crease_and_its_selected_group_once() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let group = s.doc().unwrap().selection.objects[0].0;
s.execute("select.set", &json!({"ids": [group, creases[0]]})).unwrap();
let f = crate::cmd::selection_fold_angles(&s);
assert_eq!((f.lines, f.angle, f.own), (2, None, 1), "{f:?}");
}
#[test]
fn a_locked_crease_is_skipped() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0], creases[1]]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)), "{r}");
assert_eq!(stored(&s, creases[1]), None);
}
#[test]
fn a_locked_path_of_a_compound_crease_named_by_id_is_skipped() {
let mut s = session();
let (_, creases) = tray(&mut s);
let (a, b) = (path(&mut s, "M300 300 L400 300"), path(&mut s, "M300 320 L400 320"));
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
role(&mut s, "crease", &[compound]);
s.edit("Test", |d, _| {
if let Some(n) = d.node_mut(NodeId(a)) {
n.locked = true;
}
Ok(())
})
.unwrap();
assert!(err(&mut s, json!({"angle": 30, "ids": [a]})).contains("crease, partial cut or perforation"));
// Named twice, it is skipped once.
let r = s.execute(SET, &json!({"angle": 30, "ids": [a, a, creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(1), &json!([creases[0]])), "{r}");
assert_eq!(stored(&s, compound), None);
assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(a)]).lines, 0);
let r = s.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap();
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}");
// The same with the locked path selected.
s.execute("select.set", &json!({"ids": [a]})).unwrap();
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "dimmed");
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
assert_eq!(crate::cmd::selection_fold_angles(&s).lines, 0);
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}");
assert_eq!(stored(&s, compound), None);
// With its compound, given or selected, the locked path is part of the compound, not skipped.
let r = s.execute(SET, &json!({"angle": 20, "ids": [compound, a]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}");
s.execute("select.set", &json!({"ids": [compound, a]})).unwrap();
let r = s.execute(SET, &json!({"angle": 25})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}");
s.execute(SET, &json!({"reset": true, "ids": [compound]})).unwrap();
// The compound named by id takes the angle; its other path, not locked, names it too.
let r = s.execute(SET, &json!({"angle": 30, "ids": [b]})).unwrap();
assert_eq!((r["changed"].as_u64(), &r["ids"]), (Some(1), &json!([compound])), "{r}");
assert_eq!(stored(&s, compound).as_deref(), Some("30"));
}
#[test]
fn a_damaged_angle_reads_as_none_of_its_own() {
let mut s = session();
let (_, creases) = tray(&mut s);
let mut n = s.doc().unwrap().doc.node(NodeId(creases[0])).cloned().unwrap();
for (text, want) in [("45", Some(45.0)), (" -30.5 ", Some(-30.5)), ("wide", None), ("NaN", None), ("inf", None), ("181", None), ("", None)] {
n.edit_attrs(|a| {
a.data.retain(|(k, _)| k != KEY);
a.data.push((KEY.into(), text.into()));
});
assert_eq!(own_angle(&n), want, "{text:?}");
}
}
#[test]
fn an_angle_stored_as_other_text_for_the_same_number_is_unchanged() {
let mut s = session();
let (_, creases) = tray(&mut s);
let id = NodeId(creases[0]);
s.edit("Test", |d, _| {
if let Some(n) = d.node_mut(id) {
n.edit_attrs(|a| a.data.push((KEY.into(), "45.0".into())));
}
Ok(())
})
.unwrap();
let before = steps(&s);
let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before), "{r}");
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45.0"));
s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
assert_eq!(stored(&s, creases[0]), None);
// A reset also removes text that is not an angle.
s.edit("Test", |d, _| {
if let Some(n) = d.node_mut(id) {
n.edit_attrs(|a| a.data.push((KEY.into(), "wide".into())));
}
Ok(())
})
.unwrap();
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), stored(&s, creases[0])), (Some(1), None), "{r}");
}
#[test]
fn a_line_keeps_its_own_angle_through_a_role_change() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
role(&mut s, "partialCut", &[creases[0]]);
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}");
role(&mut s, "none", &[creases[0]]);
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
role(&mut s, "crease", &[creases[0]]);
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}");
}
#[test]
fn native_save_and_preserve_editing_keep_the_angle_and_svg_leaves_it_out() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": 120, "ids": [creases[0]]})).unwrap();
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
let svg = svg["text"]
.as_str()
.map(str::to_string)
.unwrap_or_else(|| String::from_utf8_lossy(&vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).into_owned());
assert!(svg.contains("<svg"), "{svg}");
assert!(!svg.contains("fold-angle"), "{svg}");
// An SVG with Preserve Editing reopens as the document it carries, the angle with it.
let editing = s.execute("document.serialize", &json!({"format": "svg", "preserveEditing": true})).unwrap();
let editing = editing["text"].as_str().unwrap().to_string();
let mut t = Session::new();
t.execute("document.open", &json!({"name": "box.svg", "dataBase64": vectorcraft_format::base64_encode(editing.as_bytes())})).unwrap();
assert_eq!(stored(&t, creases[0]).as_deref(), Some("120"));
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap();
s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert_eq!(stored(&s, creases[0]).as_deref(), Some("120"));
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
let angles: Vec<f64> = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect();
assert!(angles.contains(&120.0), "{r}");
}
#[test]
fn a_tray_wall_with_its_own_angle_stands_at_that_angle() {
let mut s = session();
let (_, creases) = tray(&mut s);
// The top wall (y 100 to 140) folds at 45°.
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
let base = r["base"].as_u64().unwrap() as usize;
let mut angles: Vec<f64> = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect();
angles.sort_by(f64::total_cmp);
assert_eq!(angles, [45.0, 90.0, 90.0, 90.0]);
for (i, p) in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base) {
let z = vector(&p["frame"]["z"]);
let top = top_wall(p);
let tilt = if top { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 };
assert!((z[2] - tilt).abs() < 1e-9, "panel {i}: {p}");
}
}
#[test]
fn a_negative_angle_folds_a_crease_toward_the_print() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": -90, "ids": [creases[0]]})).unwrap();
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
let base = r["base"].as_u64().unwrap() as usize;
let mut up = 0;
for p in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base).map(|(_, p)| p) {
// The top wall folds toward the print, so its printed side faces back over the base
// (toward -y in the y-up frame); the other walls stand square to the base as before.
let top = top_wall(p);
let z = vector(&p["frame"]["z"]);
if top {
assert!((z[1] + 1.0).abs() < 1e-9, "the top wall's print faces the base: {p}");
up += 1;
} else {
assert!(z[2].abs() < 1e-9, "{p}");
}
}
assert_eq!(up, 1);
}
#[test]
fn roles_reports_the_angle_the_selected_fold_lines_share() {
let mut s = session();
let (outline, creases) = tray(&mut s);
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "the role's angle: {r}");
s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap();
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap();
assert_eq!((r["foldAngle"].clone(), r["ownAngles"].as_u64()), (Value::Null, Some(1)), "they differ: {r}");
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], outline]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(30.0), Some(1)), "a cut line has no angle: {r}");
let r = s.execute("addon.packaging.roles", &json!({"ids": [outline]})).unwrap();
assert!(r["foldAngle"].is_null(), "{r}");
// A partial cut folds at -90° unless it has an angle of its own.
role(&mut s, "partialCut", &[creases[2]]);
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[2]]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["foldLines"].as_u64()), (Some(-90.0), Some(1)), "{r}");
}
#[test]
fn roles_leaves_locked_fold_lines_out_of_the_angle_as_set_fold_angle_does() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": 45, "ids": [creases[1]]})).unwrap();
s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let group = s.doc().unwrap().selection.objects[0].0;
s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let r = s.execute("addon.packaging.roles", &json!({"ids": [group]})).unwrap();
assert_eq!(r["roles"][1]["count"].as_u64(), Some(2), "both are counted: {r}");
assert_eq!((r["foldLines"].as_u64(), r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(1), Some(90.0), Some(0)), "{r}");
// So Reset has nothing to change, as the panel shows it.
let r = s.execute(SET, &json!({"reset": true, "ids": [group]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}");
let (lines, angle, own) = {
let f = fold_angles(&s.doc().unwrap().doc, &[NodeId(group)]);
(f.lines, f.angle, f.own)
};
assert_eq!((lines, angle, own), (1, Some(90.0), 0));
}
@@ -8,6 +8,7 @@ use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX
use super::super::super::pathops::length_given;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
use super::angle::own_angle;
use super::roles::{Role, RoleTable, can_carry, role_targets};
use crate::{Result, Session};
@@ -92,7 +93,8 @@ fn on_non_printing_layer(d: &Document, id: NodeId) -> bool {
d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. }))
}
fn kind(role: Role) -> LineKind {
/// The kind of fold line a line with `role` is.
pub(super) fn kind(role: Role) -> LineKind {
match role {
Role::Cut => LineKind::Cut,
Role::Crease => LineKind::Crease,
@@ -155,7 +157,7 @@ fn lines_of(d: &Document, scope: &'static str, targets: Vec<NodeId>) -> Lines {
non_printing.push(id.0);
}
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
lines.push(FoldLine { path, kind: kind(role), key: id.0, angle: own_angle(n) });
}
Lines { scope, lines, non_printing }
}
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fold",
[],
None,
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true when the gap is within the larger of tolerance and 0.5% of the distance between the hinge's two ends. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
has_doc,
fold_command
)]
@@ -10,6 +10,7 @@ use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use super::super::super::edit::{outermost, refuse_symbol_part, roots_of};
use super::super::super::overprint::edit_counted;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
use crate::{Result, Session};
@@ -194,6 +195,41 @@ pub(super) fn can_carry(n: &Node) -> bool {
}
}
/// The objects a command that changes roles or angles takes for params `p`: `ids` (the outermost of
/// them), or else the selection (as `selected_roots` takes it), with a path of a compound path that
/// is locked or hidden, or in a locked or hidden group or layer, or on a locked artboard, left out
/// before it stands for its compound, and how many such paths were left out, each once.
pub(super) fn taken_roots(s: &Session, p: &Value, command: &str) -> Result<(Vec<NodeId>, usize)> {
if p.get("ids").is_some_and(|v| !v.is_null()) {
let roots = checked_ids_or_selection(s, p, command)?;
return Ok(editable_members(&s.doc()?.doc, roots));
}
refuse_symbol_part(s)?;
let st = s.doc()?;
// An object inside another selected one is left out first, as it is from `ids`.
let (kept, left) = editable_members(&st.doc, outermost(&st.doc, st.selection.in_paint_order(&st.doc)));
Ok((roots_of(&st.doc, kept), left))
}
/// `ids` less the paths of compound paths among them that are locked or hidden (or in a locked or
/// hidden group or layer, or on a locked artboard), and how many different ones were left out.
pub(super) fn editable_members(d: &Document, ids: Vec<NodeId>) -> (Vec<NodeId>, usize) {
let ok = d.editable();
let member = |id: NodeId| d.parent_of(id).is_some_and(|p| matches!(d.node(p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
let mut left = std::collections::HashSet::new();
let kept = ids
.into_iter()
.filter(|id| {
let out = member(*id) && !ok(*id);
if out {
left.insert(*id);
}
!out
})
.collect();
(kept, left.len())
}
/// The objects under the outermost objects `roots` that can carry a role, through groups and clip
/// groups, each once, and
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
@@ -257,7 +293,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make Fold Line",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. A line keeps its own fold angle (addon.packaging.setFoldAngle) through a role change and through none. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
has_selection,
set_role
),
@@ -266,7 +302,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fold Lines",
[],
None,
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out",
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected), foldLines, foldAngle, ownAngles, storedAngles}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out. foldLines is how many of the Crease, Partial Cut and Perforation lines among them addon.packaging.setFoldAngle can change (those not locked or hidden; none while nothing is selected and ids is left out, or while the selection holds only a layer and objects in it), foldAngle the angle in degrees they all fold at (their own or their role's), null when they fold at different angles or there are none, ownAngles how many of them have an angle of their own, and storedAngles how many hold stored angle text, an angle or not, which setFoldAngle's reset: true removes",
has_doc,
roles
),
@@ -382,8 +418,9 @@ fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Pai
fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
let role = role_param(p, SET_ROLE, true)?;
let overprint = switch_or(p, "overprint", true, SET_ROLE)?;
let roots = checked_ids_or_selection(s, p, SET_ROLE)?;
let (roots, left) = taken_roots(s, p, SET_ROLE)?;
let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true);
let skipped = skipped + left;
if ids.is_empty() {
return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role"));
}
@@ -403,19 +440,38 @@ fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
fn roles(s: &mut Session, p: &Value) -> Result<Value> {
let given = p.get("ids").is_some_and(|v| !v.is_null());
let roots = checked_ids_or_selection(s, p, ROLES)?;
let d = &s.doc()?.doc;
// The objects Set Fold Angle takes: a locked or hidden path of a compound path does not stand
// for its compound there. They are the objects the counts are of unless such a path was left
// out, and only then are those found apart.
let (taken, left) = taken_roots(s, p, ROLES)?;
let (roots, angle_roots) = if left == 0 { (taken, vec![]) } else { (checked_ids_or_selection(s, p, ROLES)?, taken) };
let st = s.doc()?;
let d = &st.doc;
let (scope, ids) = match (given, roots.is_empty()) {
(true, _) => ("ids", role_targets(d, &roots, false).0),
(false, false) => ("selection", role_targets(d, &roots, false).0),
(false, true) => ("document", document_targets(d)),
};
let whole = scope == "document";
// The lines Set Fold Angle can change are those of the objects it takes: with nothing selected,
// or a selection that holds no such object (only a layer and what is in it), it takes none,
// though the counts are the document's.
let angles_of_all = given || !roots.is_empty();
let table = RoleTable::of(d);
let mut counts = [0usize; 4];
for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) {
let editable = d.editable();
let mut angles = super::angle::FoldAngles::default();
for n in ids.iter().filter_map(|id| d.node(*id)) {
let Some(r) = table.role_of(n) else { continue };
if let Some(c) = counts.get_mut(r.index()) {
*c += 1;
}
if left == 0 && angles_of_all && super::angle::folds(r) && editable(n.id) {
angles.add(n, r);
}
}
if !whole && left > 0 {
angles = super::angle::fold_angles(d, &angle_roots);
}
let rows: Vec<Value> = Role::ALL
.into_iter()
@@ -425,7 +481,10 @@ fn roles(s: &mut Session, p: &Value) -> Result<Value> {
json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count })
})
.collect();
Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() }))
Ok(json!({
"roles": rows, "scope": scope, "selected": roots.len(),
"foldLines": angles.lines, "foldAngle": angles.angle, "ownAngles": angles.own, "storedAngles": angles.stored,
}))
}
fn set_role_swatch(s: &mut Session, p: &Value) -> Result<Value> {
@@ -537,4 +537,20 @@ fn compound_paths_carry_a_role() {
let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]}));
assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1)));
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
// A locked member named by id is skipped, and its compound keeps its role.
s.edit("Test", |d, _| {
if let Some(n) = d.node_mut(a) {
n.locked = true;
}
Ok(())
})
.unwrap();
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0]})).contains("neither locked nor hidden"));
// The same with the locked path selected.
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut"})).contains("neither locked nor hidden"));
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
// Named twice, it is skipped once.
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, a.0, b.0]}));
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([c.0]), Some(1)), "{r}");
}
@@ -1172,6 +1172,64 @@ fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() {
assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn");
}
/// With Add Points to Existing Paths on, the Tangent Circle tool's circle and an anchor point where
/// it touches each line are one undo step; the lines keep their shape, and one Undo takes all of it
/// back.
#[test]
fn the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step() {
let mut s = session();
let a = line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
let b = line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
s.select_tool("tangentCircle", view).unwrap();
s.set_tool_option("addPoints", &json!(true));
let n = steps(&s);
for (kind, x, y) in
[(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)]
{
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
}
assert_eq!(steps(&s), n + 1, "one undo step");
let points = |s: &Session, id| path(s, id).subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::<Vec<_>>();
let near = |got: Vec<(f64, f64)>, want: &[(f64, f64)]| {
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6)
};
assert!(near(points(&s, a), &[(100.0, 100.0), (150.0, 100.0), (300.0, 100.0)]), "{:?}", points(&s, a));
assert!(near(points(&s, b), &[(100.0, 140.0), (150.0, 140.0), (300.0, 140.0)]), "{:?}", points(&s, b));
let st = s.doc().unwrap();
let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) };
let r = st.doc.node(circle).and_then(|c| c.path_data()).and_then(|pd| pd.bounds()).unwrap();
assert!((r.x0 - 130.0).abs() < 1e-6 && (r.y0 - 100.0).abs() < 1e-6 && (r.width() - 40.0).abs() < 1e-6, "{r:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((steps(&s), points(&s, a).len(), points(&s, b).len()), (n, 2, 2));
assert!(s.doc().unwrap().doc.node(circle).is_none(), "the circle is gone too");
}
/// In Draw Behind, the Tangent Circle tool's circle goes behind the object selected before the
/// clicks, also when Add Points to Existing Paths adds anchors to lines that were not selected.
#[test]
fn the_tangent_circle_tool_adding_points_draws_behind_the_selection() {
let mut s = session();
line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
let other = line(&mut s, &[(100.0, 400.0), (300.0, 400.0)], false);
select(&mut s, &[other]);
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
s.select_tool("tangentCircle", view).unwrap();
s.set_tool_option("addPoints", &json!(true));
for (kind, x, y) in
[(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)]
{
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
}
let st = s.doc().unwrap();
let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) };
let at = |id| st.doc.position(id).map(|(parent, index, _)| (parent, index));
let (Some((p, c)), Some((q, o))) = (at(circle), at(other)) else { panic!("not placed") };
assert!(p == q && c + 1 == o, "the circle is right behind the selected line: {c} and {o}");
}
fn ids(v: &Value) -> Vec<NodeId> {
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
}
+1 -1
View File
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Color Settings…",
["Edit"],
Some("Cmd+Shift+K"),
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
"{rgb?: profile, cmyk?: profile (built in: \"VectorCraft Generic CMYK (SWOP-like)\" (default), \"VectorCraft Coated CMYK (FOGRA51)\" and \"VectorCraft Uncoated CMYK (FOGRA52)\" (computed from Fogra's characterization data), \"Device CMYK (uncalibrated)\"), intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
always,
color_settings
),
+21 -6
View File
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Curvature Circle",
[],
None,
"{id, subpath?=0, segment, t: 0..1, convex?=false} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn",
"{id, subpath?=0, segment, t: 0..1, convex?=false, constantRadius?=true, anchors?: \"standard\"|\"touch\" (default standard: a live ellipse with four anchors at 0°, 90°, 180° and 270°; touch: a path with an anchor where the circle touches the path and one every 90° from there)} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; with constantRadius, a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle, and with constantRadius false the cubic's own curvature at `t`; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn",
has_doc,
curvature_circle
),
@@ -548,7 +548,8 @@ fn selected_anchor_points(s: &Session) -> Result<Option<Vec<Point>>> {
}
/// A live ellipse that touches a path at a point with the path's curvature there
/// ([`curvature::curvature_circle_on`]). One undo step, named as an Ellipse tool drag is.
/// ([`curvature::curvature_circle_on_with`]); with `anchors: "touch"`, a plain path with an anchor
/// at the point it touches and one every 90° from there ([`shapes::circle_with_anchors_at`]). One undo step, named as an Ellipse tool drag is.
fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "shape.curvatureCircle";
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
@@ -559,6 +560,13 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "`t` must be from 0 to 1"));
}
let convex = switch_or(p, "convex", false, C)?;
let arcs = switch_or(p, "constantRadius", true, C)?;
let key = "anchors";
let at_touch = match p.get(key).map(Value::as_str) {
None | Some(Some("standard")) => false,
Some(Some("touch")) => true,
Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, touch"))),
};
let found = {
let st = s.doc()?;
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
@@ -570,7 +578,7 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
if seg >= sp.segment_count() {
return Err(bad(C, "no such segment"));
}
curvature::curvature_circle_on(sp, seg, t, convex)
curvature::curvature_circle_on_with(sp, seg, t, convex, arcs)
};
let circle = found.map_err(|e| match e {
NoCircle::Straight => bad(C, "the path is straight there, so no circle matches its curvature"),
@@ -579,12 +587,19 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
})?;
let (center, radius) = (circle.center, circle.radius);
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.abs() <= MAX_COORD) {
let (path, live) = if at_touch {
(shapes::circle_with_anchors_at(center, radius, &[circle.at]), None)
} else {
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
(live.to_path(), Some(live))
};
// The bounds of the path drawn: started where it touches, its cubics reach a little past the
// circle.
if path.bounds().is_none_or(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) {
return Err(bad(C, "the circle that matches the path there would reach past the canvas"));
}
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
// Not pixel-aligned: the circle stays on the path.
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
let mut out = add_art_unaligned(s, "Ellipse", path_kind(path, live))?;
out["cx"] = json!(center.x);
out["cy"] = json!(center.y);
out["radius"] = json!(radius);
+8 -3
View File
@@ -453,12 +453,17 @@ pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOption
}
}
/// The effect an apply request names, including the older `id` parameter.
pub(crate) fn requested_effect(p: &Value) -> Option<&str> {
str_param(p, "effect").or_else(|| str_param(p, "id"))
}
/// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the
/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one;
/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`.
/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one.
/// A Pathfinder effect on loose objects groups them first. → `{ids, index, item}`.
pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "effect.apply";
let id = str_param(p, "effect").or_else(|| str_param(p, "id")).ok_or_else(|| bad(C, "missing `effect` id"))?;
let id = requested_effect(p).ok_or_else(|| bad(C, "missing `effect` id"))?;
// An effect given as `id` names no objects: the targets are read with that `id` as null.
let effect_as_id;
let p = if str_param(p, "effect").is_none() {
+1 -1
View File
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in Line truncated
has_doc,
export_pdf
),
+1 -1
View File
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Shape Properties",
[],
None,
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
has_selection,
set_live_shape
),
+17 -4
View File
@@ -99,6 +99,12 @@ fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> {
list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::<Result<_>>().map(Some)
}
/// Whether `relativeRadii` applies to a path with live shape `live`: a live rectangle, a live
/// polygon or a path with Live Corners. A plain path, an ellipse and a line stay as they are.
fn takes_rounding(live: Option<&LiveShape>) -> bool {
matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. }))
}
/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about
/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it.
fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<LiveShape> {
@@ -277,7 +283,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false,
_ => {}
}
if relative_radii.is_some_and(|on| live.as_deref().map(|l| l.radii_relative()) != Some(on)) {
if relative_radii.is_some_and(|on| takes_rounding(live.as_deref()) && live.as_deref().is_some_and(LiveShape::radii_relative) != on) {
return false;
}
if radius.is_none() && kind.is_none() {
@@ -291,10 +297,17 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
&& picked.iter().all(|k| {
*k < c.base.anchor_count()
// A radius stored in document units can be larger than it draws; a relative
// one is a fraction, so it is compared as drawn.
// one is compared as the fraction `set_corners` would store for it, to a
// precision of 1e-9 pt on a corner whose maximum is 1 pt or more.
&& radius.is_none_or(|r| {
let now = if c.radii_relative() { c.drawn_radius(*k) } else { c.radius(*k) };
(now - r.max(0.0)).abs() < 1e-9
let r = r.max(0.0);
if c.radii_relative() {
let max = c.corner(*k).map_or(0.0, |c| c.max_radius());
let fraction = if max > 1e-12 { (r / max).clamp(0.0, 1.0) } else { 0.0 };
(c.radius(*k) - fraction).abs() * max.max(1.0) < 1e-9
} else {
(c.radius(*k) - r).abs() < 1e-9
}
})
&& kind.is_none_or(|kd| c.kind(*k) == kd)
})
+20 -3
View File
@@ -34,7 +34,8 @@
//! plays. A key a schema doesn't name passes there too, and the values of the parameters it names
//! are still checked. Even there, an effect's `color` that the effect can't read and a Levels or Curves
//! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams`
//! themselves ([`check_effect_color`], [`check_effect_channel`]).
//! themselves ([`check_effect_color`], [`check_effect_channel`]). A saved step may keep an unknown
//! shadow or glow blend mode, which the effect draws as Normal.
use std::collections::HashMap;
use std::sync::OnceLock;
@@ -456,7 +457,8 @@ fn check_member_keys(id: &str, params: &Value) -> Result<()> {
/// `params` of built-in effect `effect`, as command `id` was given them (#1592): only keys the
/// effect takes (those of its dialog defaults and of its params description), each of the type
/// the effect reads ([`check_effect_types`]), a `color` the effect can draw ([`check_effect_color`])
/// and a Levels or Curves `channel` the effect has ([`check_effect_channel`]). Numbers out of range
/// a Levels or Curves `channel` the effect has ([`check_effect_channel`]) and a Drop Shadow's or
/// glow's `mode` that names a blend mode ([`check_effect_blend`]). Numbers out of range
/// pass: the effect clamps them when it draws. An installed effect plug-in's are checked against its
/// manifest, and an unknown effect is the command's to report.
pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> {
@@ -476,6 +478,7 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
if let Some(key) = given.keys().find(|k| !keys.contains(&k.as_str())) {
return Err(unknown(id, key, &keys));
}
check_effect_blend(id, effect, params)?;
check_effect_types(id, effect, params)?;
// An SVG filter's XML is one drawable <filter> element.
if effect == vectorcraft_render::effects::SVG_FILTER
@@ -661,6 +664,20 @@ pub(crate) fn check_effect_channel(id: &str, effect: &str, params: &Value) -> Re
Err(bad(id, format!("`{key}` must be one of {}", vectorcraft_render::effects::CHANNELS.join(", "))))
}
/// The `mode` in `params` of Drop Shadow, Inner Glow or Outer Glow (`effect`), as command `id` was
/// given it: a parameter error naming the blend modes unless the effect reads it as one
/// ([`vectorcraft_render::effects::parse_blend_mode`]); an older step with another value still replays in Normal.
fn check_effect_blend(id: &str, effect: &str, params: &Value) -> Result<()> {
use vectorcraft_render::effects;
let key = "mode";
let Some(v) = params.get(key) else { return Ok(()) };
if !effects::takes_blend_mode(effect, key) || v.as_str().and_then(effects::parse_blend_mode).is_some() {
return Ok(());
}
let modes: Vec<String> = vectorcraft_color::BlendMode::ALL.into_iter().map(effects::blend_mode_id).collect();
Err(bad(id, format!("`{key}` must be one of {}", modes.join(", "))))
}
/// The Blur Center (`centerX`, `centerY`) in `params` of Radial Blur (`effect`), as command `id`
/// was given it: a parameter error unless each is a number from 0 to 1 (a share of the object's
/// bounds). `effect.apply` and `effect.setParams` run this themselves before they edit, as they
@@ -1067,7 +1084,7 @@ pub fn check_params(id: &str, params: &Value) -> Result<()> {
fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
let Some(spec) = find_command(id) else { return Ok(()) };
if let ("effect.apply" | "appearance.addEffect", Some(effect), Some(given)) =
(id, params.get("effect").or_else(|| params.get("id")).and_then(Value::as_str), params.get("params"))
(id, super::effectcmd::requested_effect(params), params.get("params"))
{
check_effect_params(id, effect, given)?;
}
@@ -43,6 +43,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.packaging.check",
"addon.packaging.fold",
"addon.packaging.roles",
"addon.packaging.setFoldAngle",
"addon.packaging.setRole",
"addon.packaging.setRoleSwatch",
"addon.pathtools.addPoints",
+23 -12
View File
@@ -1599,16 +1599,23 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// Refuses a change to the item's appearance, place, stacking order or size while a layer it is in
/// is hidden or locked. Its name and note may still change.
fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> {
/// Refuses appearance, place, stacking order and size changes in hidden or locked layers and on
/// locked artboards. Names and notes may still change.
fn refuse_protected_edit(h: &Host, item: Item) -> std::result::Result<(), HostError> {
let refused = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked));
d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item"))
let why = if d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)) {
Some("a layer it is in is hidden or locked")
} else if on_locked_artboard(h, st, item.id) {
Some("it is on a locked artboard")
} else {
None
};
why.map(|why| (d.node(item.id).and_then(typename).unwrap_or("page item"), why))
});
match refused {
Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))),
Some((name, why)) => Err(HostError::Error(format!("Cannot edit {name} {}: {why}", item.id.0))),
None => Ok(()),
}
}
@@ -1619,7 +1626,7 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer {
fn item_set_hidden(h: &Host, a: &[Data]) -> Answer {
let hidden = boolean(arg(a, 1), "hidden")?;
refuse_in_closed_layer(h, this_item(h, a)?)?;
refuse_protected_edit(h, this_item(h, a)?)?;
set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden}))
}
@@ -1629,7 +1636,7 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer {
fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
let locked = boolean(arg(a, 1), "locked")?;
refuse_in_closed_layer(h, this_item(h, a)?)?;
refuse_protected_edit(h, this_item(h, a)?)?;
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
}
@@ -1657,7 +1664,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
(now, keeps_other)
});
if now.is_none() || keeps_other {
refuse_in_closed_layer(h, item)?;
refuse_protected_edit(h, item)?;
}
set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)}))
}
@@ -1741,7 +1748,8 @@ fn item_height(h: &Host, a: &[Data]) -> Answer {
/// stays).
fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
let item = this_item(h, a)?;
refuse_in_closed_layer(h, item)?;
refuse_protected_edit(h, item)?;
selection_ids(h, item.doc, arg(a, 0))?;
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
let c = h.dom.coords.get();
let now = f.to_script(c, Point::new(r.x0, r.y0));
@@ -1778,7 +1786,8 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points")));
}
let item = this_item(h, a)?;
refuse_in_closed_layer(h, item)?;
refuse_protected_edit(h, item)?;
selection_ids(h, item.doc, arg(a, 0))?;
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
let now = if width { r.width() } else { r.height() };
if now <= 0.0 {
@@ -2024,7 +2033,8 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
}
/// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a
/// compound path is refused, and so is an object in a hidden or locked layer.
/// compound path is refused. The item must be selectable and outside hidden or locked layers and
/// locked artboards.
fn item_z_order(h: &Host, a: &[Data]) -> Answer {
let id = match arg(a, 1) {
Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront",
@@ -2037,7 +2047,8 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
if in_compound(h, item) {
return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into()));
}
refuse_in_closed_layer(h, item)?;
refuse_protected_edit(h, item)?;
selection_ids(h, item.doc, arg(a, 0))?;
let (before, after) = with_doc(h, item.doc, |_, st| {
let at = st.doc.position(item.id);
let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0);
@@ -254,3 +254,86 @@ fn after_deselect_the_pointer_reaches_the_circle_the_tool_drew() {
assert_eq!(drawn_on(&s), first, "the click hit the circle drawn first ({reselect})");
}
}
/// The anchors of `id`'s path.
fn anchors_of(s: &Session, id: NodeId) -> Vec<Point> {
let doc = &s.doc().unwrap().doc;
doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect()
}
/// With `anchors: "touch"` the circle is a plain path with an anchor where it touches the path;
/// with the default, its anchors stay at 0°, 90°, 180° and 270° whatever General › Constrain Angle
/// is; anything else is an error that draws nothing.
#[test]
fn the_anchors_go_where_the_circle_touches_or_at_standard_positions() {
let mut s = session();
let path = parabola(&mut s);
let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "anchors": "touch"})).unwrap();
let id = id_of(&v);
let node = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(matches!(node.kind, vectorcraft_doc::NodeKind::Path { live: None, .. }), "{node:?}");
let anchors = anchors_of(&s, id);
assert_eq!(anchors.len(), 4);
assert!(anchors.iter().any(|a| a.distance(Point::new(200.0, 200.0)) < 1e-6), "{anchors:?}");
assert!(bounds_are(&s, id, Rect::new(100.0, 200.0, 300.0, 400.0)));
let upright = id_of(&s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap());
let upright = anchors_of(&s, upright);
s.execute("prefs.set", &json!({"key": "constrainAngle", "value": 30})).unwrap();
let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap();
assert_eq!(anchors_of(&s, id_of(&v)), upright);
let count = object_count(&s);
for bad in [json!("points"), json!(4), json!(true)] {
assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "anchors": bad})).is_err());
}
assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "constantRadius": "no"})).is_err());
assert_eq!(object_count(&s), count);
}
/// Near the edge of the canvas, the circle is refused only when the path drawn reaches past it: the
/// circle with standard anchors, or with its anchors where it touches at a standard position, fits,
/// while with an anchor where it touches about 20° from the right one, a cubic bulges past the edge.
#[test]
fn the_canvas_check_measures_the_path_drawn() {
let mut s = session();
let edge = vectorcraft_doc::MAX_COORD - 0.05;
let v = s.execute("shape.ellipse", &json!({"x": edge - 2000.0, "y": 0, "width": 2000, "height": 2000})).unwrap();
let path = id_of(&v);
let count = object_count(&s);
let near_right = json!({"id": path.0, "segment": 1, "t": 0.79});
assert!(s.execute(C, &near_right).is_ok());
assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.0, "anchors": "touch"})).is_ok());
let e = s.execute(C, &json!({"id": path.0, "segment": 1, "t": 0.79, "anchors": "touch"})).unwrap_err();
assert!(e.to_string().contains("past the canvas"), "{e}");
assert_eq!(object_count(&s), count + 2);
}
/// The tool's options are saved with the preferences and come back in the next session.
#[test]
fn the_tool_options_are_saved_with_the_preferences() {
let mut s = session();
s.select_tool(vectorcraft_tools::curvature_circle::ID, ViewInfo::default()).unwrap();
let changed =
json!({"snapTolerance": 12.0, "snapWithoutGuides": false, "annotateRadius": false, "standardAnchors": false, "constantRadius": false});
for (k, v) in changed.as_object().unwrap() {
s.set_tool_option(k, v);
}
s.select_tool("selection", ViewInfo::default()).unwrap();
let saved = serde_json::to_string(&s.prefs).unwrap();
let mut next = session();
next.apply_prefs(serde_json::from_str(&saved).unwrap());
next.select_tool(vectorcraft_tools::curvature_circle::ID, ViewInfo::default()).unwrap();
assert_eq!(next.tool_options(), changed);
}
/// With `constantRadius: false`, a circle's segment gives the cubic's own curvature, smaller than
/// the circle's at an anchor, so a larger radius, and the result is not nominal.
#[test]
fn without_constant_radius_an_arc_gives_its_own_curvature() {
let mut s = session();
let path = circle(&mut s);
let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.0, "constantRadius": false})).unwrap();
assert_eq!(v["nominal"], json!(false));
assert!(v["radius"].as_f64().unwrap() > 100.5, "{v}");
}
+48
View File
@@ -910,6 +910,54 @@ fn relative_corner_rounding_keeps_fraction_on_resize() {
assert!((c.drawn_radius(0) / drawn - 2.0).abs() < 0.05, "drawn radius doubled with the shape");
}
/// `relativeRadii` on a plain path or an ellipse, which have no Live Corners record, leaves them
/// as they are and adds no undo step.
#[test]
fn relative_rounding_without_live_corners_adds_no_undo_step() {
let (mut s, id) = session();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.expandShape", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "a plain path");
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let n = steps(&s);
run(&mut s, json!({"ids": [id.0], "relativeRadii": false}));
run(&mut s, json!({"ids": [id.0], "relativeRadii": true}));
assert_eq!(steps(&s), n, "a plain path: no change");
assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "still a plain path");
let e = s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap();
let n = steps(&s);
run(&mut s, json!({"ids": [e], "relativeRadii": true}));
assert_eq!(steps(&s), n, "an ellipse: no change");
}
/// With Relative rounding, a radius is compared as the fraction it would store: a radius past the
/// corner's maximum, typed again, and the maximum the field then shows add no undo step, while a
/// smaller one adds one.
#[test]
fn a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step() {
let (mut s, id) = session();
run(&mut s, json!({"relativeRadii": true}));
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let max = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().corner(0).unwrap().max_radius();
let n = steps(&s);
run(&mut s, json!({"corners": [0], "radius": max + 20.0}));
assert_eq!(steps(&s), n + 1, "past the maximum: one undo step");
let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
assert!((c.radius(0) - 1.0).abs() < 1e-9, "stored as the whole maximum: {}", c.radius(0));
run(&mut s, json!({"corners": [0], "radius": max + 20.0}));
assert_eq!(steps(&s), n + 1, "the same radius again: no undo step");
run(&mut s, json!({"corners": [0], "radius": max}));
assert_eq!(steps(&s), n + 1, "the maximum, as shown: no undo step");
run(&mut s, json!({"corners": [0], "radius": max / 2.0}));
assert_eq!(steps(&s), n + 2, "a smaller radius: one undo step");
// On a large shape a small radius is a fraction below 1e-9, and still a change.
let big = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 3_000_000, "height": 3_000_000})).unwrap()["id"].as_u64().unwrap();
run(&mut s, json!({"ids": [big], "relativeRadii": true}));
let n = steps(&s);
run(&mut s, json!({"ids": [big], "corners": [0], "radius": 0.001}));
assert_eq!(steps(&s), n + 1, "a small radius on a large shape: one undo step");
}
/// #2898: while a corner widget is pressed or dragged, Up and Down step the corners' kind (round,
/// inverted round, chamfer, in turn) along with the radius, as one undo step with the drag.
#[test]
+54 -6
View File
@@ -1325,6 +1325,54 @@ fn duplicate_refuses_hidden_or_locked_art() {
assert!(order.contains(&a) && order.contains(&b));
}
#[test]
fn setters_refuse_art_on_a_locked_artboard() {
let (mut s, _, _) = doc();
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s));
let out = log(
&mut s,
"var p = app.activeDocument.pageItems[0], refused = [];\
var setters = [function(){p.position=[5,5]},function(){p.left=5},function(){p.top=5},\
function(){p.width=10},function(){p.height=10},function(){p.opacity=50},\
function(){p.hidden=true},function(){p.locked=true},function(){p.zOrder(ZOrderMethod.SENDTOBACK)}];\
for(var i=0;i<setters.length;i++){try{setters[i]();refused.push(false)}catch(e){refused.push(e.name==='Error')}}\
vc.log(refused);",
);
assert_eq!(out, vec![json!(vec![true; 9])]);
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
assert_eq!(undo_steps(&s), steps);
assert_eq!(log(&mut s, "var p=app.activeDocument.pageItems[0];p.opacity=p.opacity;vc.log(p.opacity);"), vec![json!(100)]);
}
#[test]
fn geometry_setters_refuse_locked_guide_paths() {
let (mut s, _, b) = doc();
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.execute("view.guides.make", &json!({})).unwrap();
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s));
let out = log(
&mut s,
"var p=app.activeDocument.pageItems[0],refused=[];\
var setters=[function(){p.position=[5,5]},function(){p.left=5},function(){p.top=5},\
function(){p.width=10},function(){p.height=10},function(){p.zOrder(ZOrderMethod.SENDTOBACK)}];\
for(var i=0;i<setters.length;i++){try{setters[i]();refused.push(false)}catch(e){refused.push(e.name==='Error')}}\
vc.log(refused);",
);
assert_eq!(out, vec![json!(vec![true; 6])]);
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
assert_eq!(undo_steps(&s), steps);
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
log(&mut s, "var p=app.activeDocument.pageItems[0];p.left=5;p.width=10;");
let bounds = s.active().unwrap().doc.bounds_of(&[b], false).unwrap();
assert!((bounds.x0 - 5.0).abs() < 1e-9 && (bounds.width() - 10.0).abs() < 1e-9);
}
/// Reading `editable` on every member of a group on a locked artboard measures the group once.
#[test]
fn editable_measures_a_group_on_a_locked_artboard_once() {
@@ -1347,24 +1395,24 @@ fn editable_measures_a_group_on_a_locked_artboard_once() {
#[test]
fn get_is_file_open_cannot_probe_outside_script_scope() {
let (mut s, _, _) = doc();
let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id()));
let fixture = vectorcraft_testkit::TempDir::new("script-file-open-quoting");
let path = fixture.join("quote's open.svg");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let p = path.to_string_lossy().replace('\\', "\\\\");
let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));");
let p = serde_json::to_string(&path.to_string_lossy()).unwrap();
let other = serde_json::to_string(&format!("{}.other", path.to_string_lossy())).unwrap();
let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));");
let out = log(&mut s, &query);
assert_eq!(out, vec![json!(true), json!(false)]);
// Read roots that leave out the document's file: the same path does not count.
let elsewhere = std::env::temp_dir().join(format!("vc-dom-roots-{}", std::process::id()));
let elsewhere = fixture.join("elsewhere");
std::fs::create_dir_all(&elsewhere).unwrap();
let roots = crate::file_access::AutomationRoots::new(&[&elsewhere], &[]).unwrap().unwrap();
let out = crate::file_access::confine(Some(&roots), || log(&mut s, &query));
assert_eq!(out, vec![json!(false), json!(false)]);
let _ = std::fs::remove_dir_all(&elsewhere);
for bad in ["../x.svg", "a/../b.svg", "\\\\\\\\host\\\\share\\\\x.svg", "//host/share/x.svg", "a\\u0000b", ""] {
assert!(failure(&mut s, &format!("app.getIsFileOpen('{bad}');")).contains("cannot check"), "{bad}");
}
assert!(failure(&mut s, "app.getIsFileOpen(new Array(5000).join('a'));").contains("too long"));
let _ = std::fs::remove_file(path);
}
#[test]
@@ -6,6 +6,7 @@ use crate::command_specs;
/// Params that are angles but not a turn, with why.
const NOT_A_TURN: &[(&str, &str, &str)] = &[
("addon.packaging.setFoldAngle", "angle", "a fold out of the page: the description says which side the panel folds to"),
("addon.pathtools.cornerSet", "maxAngle", "the angle a corner's sides meet at"),
("addon.pathtools.cornerSet", "minAngle", "the angle a corner's sides meet at"),
("addon.shapes.box3d", "angleX", "a tilt out of the page: the description says which side turns away"),
+6
View File
@@ -1069,6 +1069,12 @@ impl Session {
self.tool.wants_samples()
}
/// Does a stroke the active tool draws now vary with an airbrush pen's finger wheel
/// ([`vectorcraft_tools::Tool::reads_wheel`])? False with no document open.
pub fn tool_reads_wheel(&mut self, view: ViewInfo) -> bool {
self.with_tool_cx(view, |t, cx| t.reads_wheel(cx))
}
/// Is the active tool waiting for work it runs on another thread ([`Tool::waiting`]), is input
/// held until an edit it computes is applied, or are requests for the UI left from making it?
pub fn tool_waiting(&self) -> bool {
+50
View File
@@ -263,6 +263,56 @@ fn a_tone_curve_channel_it_does_not_have_is_refused() {
assert_eq!(back.layers[0].children().unwrap()[0].appearance.effects[0].params["channel"], json!("alpha"));
}
/// A Drop Shadow's or glow's `mode` that names no blend mode (which it drew as Normal) is refused
/// in new calls to `effect.apply`, `appearance.addEffect` and `effect.setParams`, with the modes it
/// takes, and the document and its undo history stay as they were. Blend-mode names in any
/// spelling pass, an omitted `mode` keeps the default, and an older saved step still plays.
#[test]
fn a_shadow_or_glow_mode_that_is_no_blend_mode_is_refused() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].clone();
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"opacity": 50}})).unwrap();
let state = |s: &Session| {
let st = s.active().unwrap();
(st.doc.clone(), st.history.undo.len())
};
let before = state(&s);
let why = "`mode` must be one of normal, darken, multiply, colorBurn";
for bad in [json!("multipy"), json!(""), json!("passThrough"), json!(null), json!(["multiply"]), json!(1), json!(false)] {
for (cmd, params) in [
("effect.setParams", json!({"index": 0, "params": {"mode": bad}})),
("effect.apply", json!({"effect": "stylize.innerGlow", "params": {"mode": bad}})),
("effect.apply", json!({"effect": null, "id": "stylize.dropShadow", "ids": [id], "params": {"mode": bad}})),
("appearance.addEffect", json!({"effect": "stylize.outerGlow", "params": {"mode": bad}})),
] {
let e = s.execute(cmd, &params).unwrap_err().to_string();
assert!(e.contains(why), "{cmd} {params}: {e}");
let checked = s.check_params(cmd, &params).unwrap_err().to_string();
assert!(checked.contains(why), "{cmd} {params}: {checked}");
assert!(state(&s) == before, "{cmd} {params} changed the document or its undo history");
}
}
let effect = |s: &Session| s.active().unwrap().doc.layers[0].children().unwrap()[0].appearance.effects[0].clone();
let shadow = effect(&s);
let drawn = vectorcraft_render::effects::merged_params(&shadow.id, &shadow.params);
assert_eq!(drawn["mode"], json!("multiply"), "an omitted mode keeps the default");
for good in ["screen", "Color Burn", "color-burn", "COlor!!Burn#", "softLight", "LUMINOSITY"] {
let params = json!({"index": 0, "params": {"mode": good}});
s.check_params("effect.setParams", &params).unwrap_or_else(|e| panic!("{good}: {e}"));
s.execute("effect.setParams", &params).unwrap_or_else(|e| panic!("{good}: {e}"));
assert_eq!(effect(&s).params["mode"], json!(good));
}
s.replay("effect.setParams", &json!({"index": 0, "params": {"mode": "multipy"}})).unwrap();
assert_eq!(effect(&s).params["mode"], json!("multipy"));
assert_eq!(vectorcraft_render::effects::blend_mode("multipy"), vectorcraft_color::BlendMode::Normal);
for mode in vectorcraft_color::BlendMode::ALL {
let id = vectorcraft_render::effects::blend_mode_id(mode);
assert_eq!(vectorcraft_render::effects::parse_blend_mode(&id), Some(mode));
assert_eq!(vectorcraft_render::effects::blend_mode(&id), mode);
}
}
/// What a command adds to its own journal entry passes the check, so a recorded journal can be
/// sent back through the control channel or MCP.
#[test]
+26 -2
View File
@@ -51,12 +51,18 @@ const SMOOTH_TURN: f64 = 0.5 * std::f64::consts::PI / 180.0;
/// side it touches `c` at `t`, its center one radius out from there. A `t` outside 0 to
/// 1 and a segment whose points are not finite give [`NoCircle::Cusp`].
pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result<CurvatureCircle, NoCircle> {
curvature_circle_with(c, t, convex, true)
}
/// [`curvature_circle`], with `arcs` off giving the cubic's own curvature at `t` on the cubic of a
/// circular arc too.
pub fn curvature_circle_with(c: CubicBez, t: f64, convex: bool, arcs: bool) -> Result<CurvatureCircle, NoCircle> {
let finite = [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite());
if !finite || !(0.0..=1.0).contains(&t) {
return Err(NoCircle::Cusp);
}
let at = c.eval(t);
let (center, radius, nominal) = match circular_arc(c) {
let (center, radius, nominal) = match circular_arc(c).filter(|_| arcs) {
Some((center, radius)) => {
let out = at - center;
let len = out.hypot();
@@ -89,6 +95,11 @@ pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result<CurvatureCi
/// length passed over to reach it, and the path turns there by less than 90°, or when
/// the two segments leave it within [`SMOOTH_TURN`] of one direction.
pub fn curvature_circle_on(sp: &SubPath, seg: usize, t: f64, convex: bool) -> Result<CurvatureCircle, NoCircle> {
curvature_circle_on_with(sp, seg, t, convex, true)
}
/// [`curvature_circle_on`] with [`curvature_circle_with`]'s `arcs`.
pub fn curvature_circle_on_with(sp: &SubPath, seg: usize, t: f64, convex: bool, arcs: bool) -> Result<CurvatureCircle, NoCircle> {
let n = sp.segment_count();
if seg >= n {
return Err(NoCircle::Cusp);
@@ -106,7 +117,7 @@ pub fn curvature_circle_on(sp: &SubPath, seg: usize, t: f64, convex: bool) -> Re
if corner {
return Err(NoCircle::Corner);
}
curvature_circle(c, t, convex)
curvature_circle_with(c, t, convex, arcs)
}
/// The nearest segment with length before (or with `forward`, after) segment `seg`, and whether
@@ -260,6 +271,19 @@ mod tests {
}
}
/// With `arcs` off, a quarter circle's segment gives the cubic's own curvature, which is smaller
/// than the circle's at its ends: the circle is not nominal and is larger than the arc's.
#[test]
fn without_arcs_a_circle_segment_gives_its_own_curvature() {
let pd = shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0));
let sp = &pd.subpaths[0];
let arc = curvature_circle_on_with(sp, 0, 0.0, false, true).unwrap();
let own = curvature_circle_on_with(sp, 0, 0.0, false, false).unwrap();
assert!(arc.nominal && !own.nominal, "{arc:?} {own:?}");
assert!(own.radius > arc.radius && own.center != arc.center, "{arc:?} {own:?}");
assert_eq!(own.at, sp.segment(0).eval(0.0));
}
/// On the parabola y = x² / 200, the curvature at its vertex is 1/100: drawn as a cubic from
/// (-100, 50) to (100, 50), the circle at the middle has radius 100 and center (0, 100), above
/// the curve on the side it bends toward; Shift's other side puts the center at (0, -100).
+59 -70
View File
@@ -18,9 +18,9 @@
//! 25.6.1.9); one that still has none when the run ends successfully is reported by
//! [`crate::Realm::unhandled_rejections`], with the place it was rejected at when known.
//!
//! Until the language has iterators, `all`, `allSettled` and `race` read an array or another object
//! whose `length` is a whole number by index, and a string by code point; other values reject the
//! promise they return with a `TypeError`. The statics need a constructor as `this`, and the
//! `all`, `allSettled` and `race` read their input through `Symbol.iterator` and close the iterator
//! when processing a yielded value throws. Noniterable values reject the promise they return
//! with a `TypeError`. The statics need a constructor as `this`, and the
//! promises they and `then` make are always built-in promises: subclasses and `Symbol.species`
//! are not read.
@@ -32,7 +32,6 @@ use crate::LimitKind;
use crate::bytecode::Code;
use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key};
use crate::interp::{Abrupt, ErrorType, Interp, JsResult};
use crate::string_builtins::flat_charged;
use crate::value::Value;
/// Where a promise was rejected: the code and the instruction.
@@ -140,7 +139,7 @@ enum Job {
/// What happens when the running job's call ends.
enum Then {
/// The result resolves this promise, and an exception rejects it.
Settle(ObjId),
Settle(ObjId, Option<Site>),
/// An exception rejects through this resolving record.
Reject(ObjId),
/// The call was a `finally` callback that a reaction job runs in place of the Then Finally or
@@ -214,7 +213,11 @@ impl Promises {
roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected));
roots.values.extend(self.completion.iter());
match &self.running {
Some(Then::Settle(o) | Then::Reject(o)) => roots.objects.push(*o),
Some(Then::Settle(o, site)) => {
roots.objects.push(*o);
roots.codes.extend(site.iter().map(|(code, _)| &**code));
}
Some(Then::Reject(o)) => roots.objects.push(*o),
Some(Then::Finally { derived, value, .. }) => {
roots.objects.push(*derived);
roots.values.push(value);
@@ -662,7 +665,7 @@ impl Interp {
interp.temp_roots.extend([handler, argument.clone()]);
(on_finally, Value::Undefined, Vec::new(), Then::Finally { derived, value: argument, throws })
}
None => (handler, Value::Undefined, vec![argument], Then::Settle(derived)),
None => (handler, Value::Undefined, vec![argument], Then::Settle(derived, site)),
}
}
Job::Thenable { promise, thenable, then } => {
@@ -689,8 +692,8 @@ impl Interp {
let site = if r.is_err() { caught(self) } else { None };
let Some(then) = self.promises.running.take() else { return Err(Abrupt::Internal("no promise job is running".into())) };
match (then, r) {
(Then::Settle(d), Ok(v)) => resolve_promise(self, d, v),
(Then::Settle(d), Err(e)) => reject_promise(self, d, e, site),
(Then::Settle(d, _), Ok(v)) => resolve_promise(self, d, v),
(Then::Settle(d, _), Err(e)) => reject_promise(self, d, e, site),
(Then::Reject(_), Ok(_)) => Ok(()),
(Then::Reject(rec), Err(e)) => scoped(self, |interp| {
root(interp, &Value::Object(rec));
@@ -731,6 +734,7 @@ impl Interp {
pub(crate) fn take_unhandled(&mut self) -> (Vec<crate::Rejection>, usize) {
let rejected = std::mem::take(&mut self.promises.rejected);
let mut out = Vec::new();
let mut attribution = Vec::new();
let mut count = 0;
for p in rejected {
let (reason, site) = match self.heap.object(p).map(|o| &o.class) {
@@ -748,7 +752,17 @@ impl Interp {
message.truncate(cut);
message.push('…');
}
let authored = self.thrown_by_script(&reason);
let authored = if let Some(object) = reason.as_object() {
if let Some((_, authored)) = attribution.iter().find(|(seen, _)| *seen == object) {
*authored
} else {
let authored = self.thrown_by_script(&reason);
attribution.push((object, authored));
authored
}
} else {
self.thrown_by_script(&reason)
};
let (tag, (line, column)) = site.map_or((crate::UNKNOWN_SOURCE, (0, 0)), |(code, pc)| (code.source.tag, code.line_column(pc)));
out.push(crate::Rejection { message, line, column, tag, authored });
}
@@ -796,7 +810,10 @@ fn resolve_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J
/// A promise's reject function (section 25.6.1.3.1).
fn reject_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a reject function lost its record".into()))?;
let site = here(interp);
let site = here(interp).or_else(|| match &interp.promises.running {
Some(Then::Settle(_, site)) => site.clone(),
_ => None,
});
reject_through(interp, rec, arg(args, 1), site)?;
Ok(Value::Undefined)
}
@@ -1010,67 +1027,41 @@ fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsRe
})
}
/// Where the inputs of `Promise.all`, `allSettled` and `race` come from. An array is read up to
/// its length at each step, as an array iterator reads it, and another object up to the `length`
/// it had at the start.
enum Inputs {
Indexed { object: ObjId, length: f64 },
CodePoints(Rc<[u16]>),
}
impl Inputs {
fn new(interp: &mut Interp, input: &Value, how: Combine) -> JsResult<Self> {
match input {
Value::Object(o) => match interp.get_from(*o, &key("length"), input)? {
Value::Number(length) if length >= 0.0 && length.fract() == 0.0 && length <= 9_007_199_254_740_991.0 => {
Ok(Inputs::Indexed { object: *o, length })
}
_ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))),
},
Value::String(s) => Ok(Inputs::CodePoints(flat_charged(interp, s)?)),
_ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))),
}
}
/// The input at `index`, which counts code units for a string; `None` past the end.
fn get(&self, interp: &mut Interp, index: &mut f64) -> JsResult<Option<Value>> {
match self {
Inputs::Indexed { object, length } => {
let end = match interp.heap.object(*object).map(|o| &o.class) {
Some(Class::Array { length, .. }) => f64::from(*length),
_ => *length,
};
if *index >= end {
return Ok(None);
}
let v = super::get_at(interp, *object, *index)?;
*index += 1.0;
Ok(Some(v))
}
Inputs::CodePoints(units) => {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let i = *index as usize;
let Some(&first) = units.get(i) else { return Ok(None) };
let pair = (0xD800..0xDC00).contains(&first) && units.get(i + 1).is_some_and(|u| (0xDC00..0xE000).contains(u));
let n = if pair { 2 } else { 1 };
let piece = units.get(i..i + n).unwrap_or_default().to_vec();
*index += n as f64;
let bytes = crate::heap::string_bytes(piece.len());
interp.reserve_heap(bytes)?;
interp.heap.bytes = interp.heap.bytes.saturating_add(bytes);
Ok(Some(Value::String(crate::value::Str::from_units(piece))))
}
}
}
}
fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine, rec: ObjId, resolve: &Value, reject: &Value) -> JsResult<()> {
let resolve_fn = interp.get_value(this, &key("resolve"))?;
if !interp.is_callable(&resolve_fn) {
return Err(interp.type_error(&format!("Promise.{}: the constructor's resolve is not a function", how.name())));
}
root(interp, &resolve_fn);
let inputs = Inputs::new(interp, input, how)?;
let iterator = interp.get_iterator(input)?;
root(interp, &Value::Object(iterator));
let result = combine_iterator(interp, this, iterator, how, rec, &resolve_fn, (resolve, reject));
if let Err(Abrupt::Throw(reason)) = &result {
root(interp, reason);
let site = interp.throw_site.clone();
let mark = interp.thrown_mark;
match interp.iter_close(iterator) {
Ok(()) | Err(Abrupt::Throw(_)) => {
interp.throw_site = site;
interp.thrown_mark = mark;
interp.passing = reason.clone();
}
Err(other) => return Err(other),
}
}
result
}
fn combine_iterator(
interp: &mut Interp,
this: &Value,
iterator: ObjId,
how: Combine,
rec: ObjId,
resolve_fn: &Value,
handlers: (&Value, &Value),
) -> JsResult<()> {
let (resolve, reject) = handlers;
let combinator = if how == Combine::Race {
None
} else {
@@ -1080,14 +1071,12 @@ fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine
root(interp, &Value::Object(c));
Some((c, values))
};
let mut position = 0.0;
let mut index: u32 = 0;
loop {
interp.use_fuel()?;
let mark = interp.temp_roots.len();
let Some(next) = inputs.get(interp, &mut position)? else { break };
let Some(next) = interp.iter_next(iterator)? else { break };
root(interp, &next);
let next_promise = interp.call(&resolve_fn, this, &[next])?;
let next_promise = interp.call(resolve_fn, this, &[next])?;
root(interp, &next_promise);
match combinator {
None => {
+90
View File
@@ -75,6 +75,96 @@ fn an_ended_run_leaves_the_realm_ready_for_the_next() {
r.end();
}
fn paused_for_replacement(promise: bool) -> Realm {
let mut r = Realm::with_options(Options { es2015: promise, ..Options::default() }, Limits::default());
let pause = r.pause_flag();
r.define_function("pauseNow", move |_| {
pause.set(true);
Ok(JsValue::Undefined)
});
let source = if promise {
"var kept = 'yes', after = false, queued = false;\n\
Promise.resolve().then(function () { pauseNow(); after = true; });\n\
Promise.resolve().then(function () { queued = true; }); 'old'"
} else {
"var kept = 'yes', after = false, queued = false; pauseNow(); after = true; 'old'"
};
r.start(source).unwrap();
assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused);
assert!(r.is_running());
if promise {
assert!(r.interp().promises.draining);
}
r
}
fn replacement(r: &mut Realm, sliced: bool, source: &str) -> Result<JsValue, RunError> {
if sliced {
r.start(source)?;
finish(r, 1_000).0
} else {
r.run(source)
}
}
#[test]
fn replacing_a_paused_promise_run_discards_its_reaction_and_queued_jobs() {
for sliced in [false, true] {
let mut r = paused_for_replacement(true);
assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into()));
assert!(!r.is_running());
assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into()));
}
}
#[test]
fn replacing_a_paused_script_discards_its_remaining_code() {
for sliced in [false, true] {
let mut r = paused_for_replacement(false);
assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into()));
assert!(!r.is_running());
assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into()));
}
}
#[test]
fn replacing_a_waiting_run_discards_its_host_call() {
for sliced in [false, true] {
let mut r = realm(1_000_000);
let calls = with_ask(&mut r);
r.start("var after = false; ask('old'); after = true").unwrap();
assert_eq!(r.advance(1_000).unwrap(), Progress::Paused);
assert!(r.waits());
assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into()));
assert!(!r.waits());
assert_eq!(r.run("after").unwrap(), JsValue::Bool(false));
assert_eq!(calls.get(), 1);
assert!(r.answer(Data::Null).is_err());
}
}
#[test]
fn replacing_a_paused_run_with_invalid_source_still_ends_it() {
for promise in [false, true] {
for sliced in [false, true] {
let mut r = paused_for_replacement(promise);
assert_eq!(replacement(&mut r, sliced, "(").unwrap_err().kind, RunErrorKind::Syntax);
assert!(!r.is_running());
assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into()));
}
}
}
#[test]
fn replacing_a_paused_run_applies_its_pending_language_setting() {
for sliced in [false, true] {
let mut r = paused_for_replacement(false);
r.set_es2015(true);
assert_eq!(replacement(&mut r, sliced, "let fresh = 7; fresh").unwrap(), JsValue::Number(7.0));
assert_eq!(r.run("after").unwrap(), JsValue::Bool(false));
}
}
/// Setting `Folder.current` back for the next run drops what only the last run's uncaught
/// exception held, so a full heap from that exception does not stop the next run.
#[test]
+4 -1
View File
@@ -2830,9 +2830,12 @@ impl Interp {
return Err(self.type_error("apply was called on a value that is not a function"));
}
let list = args.get(1).cloned().unwrap_or(Value::Undefined);
let mut roots = vec![f.clone(), this.clone()];
roots.extend(args.iter().cloned());
let expanded = self.rooted(&roots, |i| i.list_from_array_like(&list))?;
f = this;
this = args.first().cloned().unwrap_or(Value::Undefined);
args = self.list_from_array_like(&list)?;
args = expanded;
}
Func::Bound { target, this: bound_this, args: bound_args } => {
self.use_fuel()?;
+20
View File
@@ -613,6 +613,26 @@ fn apply_keeps_its_arguments_alive_while_a_native_function_runs() {
assert_eq!(realm.run(src), Ok(JsValue::Number(42.0)));
}
#[test]
fn successive_apply_expansions_keep_getter_receivers_alive() {
for queued in [false, true] {
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 1 << 20, ..Limits::default() });
let src = "var result; function callback(a) { result = this.kept + a; } \
var inner = {length: 1, get 0() { for (var i = 0; i < 20000; i++) ({i: i}); return 2; }}; \
var outer = {length: 2, get 0() { return {kept: 40}; }, get 1() { return inner; }};";
realm.run(src).unwrap();
let collections = realm.interp().heap.collections;
let call = if queued {
"Promise.resolve(outer).then(Function.prototype.apply.bind(Function.prototype.apply, callback));"
} else {
"Function.prototype.apply.apply(callback, outer);"
};
realm.run(call).unwrap();
assert!(realm.interp().heap.collections > collections);
assert_eq!(realm.run("result"), Ok(JsValue::Number(42.0)), "queued: {queued}");
}
}
#[test]
fn to_number_skips_the_white_space_the_lexer_skips() {
let mut realm = small(Limits::default());
+1 -1
View File
@@ -162,7 +162,7 @@ impl Interp {
/// IteratorClose (section 7.4.6) with a normal completion: calls the iterator's `return`
/// method, unless it is done, and checks that it gives an object.
fn iter_close(&mut self, rec: ObjId) -> JsResult<()> {
pub(crate) fn iter_close(&mut self, rec: ObjId) -> JsResult<()> {
let r = self.record(rec)?;
if r.done {
return Ok(());
+93 -4
View File
@@ -144,7 +144,73 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() {
}
#[test]
fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_to_its_first_length() {
fn promise_combinator_iterators_use_custom_values_and_boxed_string_code_points() {
let src = "var input = {}; input[Symbol.iterator] = function () {\n\
var n = 0; return { next: function () { return n < 2 ? { value: ++n, done: false } : { done: true }; } };\n\
};\n\
Promise.all(input).then(function (v) { log.push('all ' + v.join(',')); });\n\
Promise.allSettled(input).then(function (v) { log.push('settled ' + v[0].value + ',' + v[1].value); });\n\
Promise.race(input).then(function (v) { log.push('race ' + v); });\n\
var a = [99]; a[Symbol.iterator] = input[Symbol.iterator];\n\
Promise.all(a).then(function (v) { log.push('array ' + v.join(',')); });\n\
Promise.all(new String('\u{1d306}x')).then(function (v) { log.push('string ' + v.length + ',' + v[0].length); });";
let out = log(src);
for expected in ["all 1,2", "settled 1,2", "race 1", "array 1,2", "string 2,2"] {
assert!(out.contains(expected), "{expected} in {out}");
}
}
#[test]
fn promise_combinator_iterators_close_after_resolve_or_then_throws() {
let src = "function check(name, failure) {\n\
var closed = 0, input = {};\n\
input[Symbol.iterator] = function () { return {\n\
next: function () { return { value: 1, done: false }; },\n\
return: function () { closed++; throw 'close'; }\n\
}; };\n\
Promise.resolve = failure === 'resolve' ? function () { throw 'resolve'; } :\n\
function () { return { get then() { throw 'then'; } }; };\n\
Promise[name](input).then(null, function (e) { log.push(name + ':' + failure + ':' + e + ':' + closed); });\n\
}\n\
var original = Promise.resolve;\n\
for (var i = 0; i < 3; i++) { var name = ['all', 'allSettled', 'race'][i]; check(name, 'resolve'); check(name, 'then'); }\n\
Promise.resolve = original;";
let out = log(src);
for name in ["all", "allSettled", "race"] {
for failure in ["resolve", "then"] {
let expected = format!("{name}:{failure}:{failure}:1");
assert!(out.contains(&expected), "{expected} in {out}");
}
}
}
#[test]
fn promise_combinator_iterators_do_not_close_when_the_step_throws_or_finishes() {
let src = "var closed = 0;\n\
function input(failure) { var o = {}; o[Symbol.iterator] = function () { return {\n\
next: function () { if (failure === 'next') throw failure;\n\
return { get done() { if (failure === 'done') throw failure; return false; },\n\
get value() { throw failure; } }; },\n\
return: function () { closed++; return {}; }\n\
}; }; return o; }\n\
for (var i = 0; i < 3; i++) {\n\
Promise.all(input(['next', 'done', 'value'][i])).then(null, function (e) { log.push(e); });\n\
}\n\
var empty = {}; empty[Symbol.iterator] = function () { return {\n\
next: function () { return { done: true }; }, return: function () { closed++; return {}; }\n\
}; };\n\
Promise.all(empty).then(function (v) { log.push('empty ' + v.length); });\n\
Promise.race(empty).then(function () { log.push('race settled'); });\n\
log.push('closed ' + closed);";
let out = log(src);
for expected in ["next", "done", "value", "empty 0", "closed 0"] {
assert!(out.contains(expected), "{expected} in {out}");
}
assert!(!out.contains("race settled"), "{out}");
}
#[test]
fn the_combinators_read_an_array_to_its_changing_length_and_reject_noniterable_array_likes() {
// `Promise.resolve` runs once for each input and appends to the input while it is read.
let src = "var resolve = Promise.resolve; var input;\n\
Promise.resolve = function (x) {\n\
@@ -152,11 +218,10 @@ fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_t
return resolve.call(this, x);\n\
};\n\
input = [1]; Promise.all(input).then(function (v) { log.push('array ' + v.join(',')); });\n\
input = { length: 1, 0: 1 }; Promise.all(input).then(function (v) { log.push('object ' + v.join(',')); });";
input = { length: 1, 0: 1 }; Promise.all(input).then(null, function (e) { log.push('object ' + (e instanceof TypeError)); });";
let out = log(src);
assert!(out.contains("array 1,2,3"), "{out}");
assert!(out.contains("object 1"), "{out}");
assert!(!out.contains("object 1,"), "{out}");
assert!(out.contains("object true"), "{out}");
}
#[test]
@@ -226,6 +291,30 @@ fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() {
assert_eq!(got, want);
}
#[test]
fn combinator_rejection_relays_keep_the_input_location() {
for method in ["all", "race"] {
let mut r = realm();
r.run(&format!("var input =\n Promise.reject('lost');\nPromise.{method}([input]);")).unwrap();
let reported = r.unhandled_rejections();
assert_eq!(reported.len(), 1, "{method}: {reported:?}");
assert_eq!(reported[0].line, 2, "{method}: {:?}", reported[0]);
assert!(reported[0].column > 0);
assert_eq!(reported[0].tag, r.script_tag());
}
let mut r = realm();
r.run("var reject; new Promise(function (_, no) { reject = no; });\nPromise.reject('handled').catch(function () {\n reject('lost');\n});")
.unwrap();
assert_eq!(r.unhandled_rejections().len(), 1);
assert_eq!(r.unhandled_rejections()[0].line, 3);
assert!(r.unhandled_rejections()[0].column > 0);
let mut r = realm();
r.run("eval(\"Promise.reject('eval')\"); Function(\"Promise.reject('function')\")();").unwrap();
let reported = r.unhandled_rejections();
assert_eq!(reported.len(), 2);
assert!(reported.iter().all(|r| r.tag == UNKNOWN_SOURCE), "{reported:?}");
}
#[test]
fn an_interpreter_error_given_a_long_message_is_reported_as_the_scripts_text_without_copying_it() {
let mut r = realm();
+3
View File
@@ -277,6 +277,7 @@ impl Realm {
/// Runs `source` as a script in the global environment, then the promise jobs it queued, and
/// returns its completion value (the value of the last expression statement that ran). A realm
/// whose built-ins could not be installed runs nothing and gives an internal error.
/// A paused or waiting run ends first; its globals remain available.
pub fn run(&mut self, source: &str) -> Result<JsValue, RunError> {
let code = self.compile(source)?;
let result = self.interp.run_global(code, false).and_then(|v| self.interp.drain_jobs(v));
@@ -285,6 +286,7 @@ impl Realm {
/// Compiles `source` and readies the realm for a run.
fn compile(&mut self, source: &str) -> Result<std::rc::Rc<crate::bytecode::Code>, RunError> {
self.end();
self.script_tag = UNKNOWN_SOURCE;
self.rejections = (Vec::new(), 0);
let interp = &mut self.interp;
@@ -391,6 +393,7 @@ impl Realm {
}
/// Begins a run that [`Realm::advance`] carries on: compiles `source` and enters it.
/// A paused or waiting run ends first; its globals remain available.
pub fn start(&mut self, source: &str) -> Result<(), RunError> {
let code = self.compile(source)?;
match self.interp.enter_global(code, false) {
+2 -2
View File
@@ -1174,7 +1174,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"tool.options",
"Tool Options…",
"",
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's To Line truncated
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, Line truncated
),
(
"ui.colorGuideOptions",
@@ -1513,7 +1513,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.menuDialog",
"Menu Dialog",
"",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)",
),
(
"ui.widthPointEdit",
+11 -7
View File
@@ -615,6 +615,10 @@ impl Dest {
/// The catalog entries `set` asks for (none in PDF/A files, which carry their own); a PDF/X file's
/// output intent profile is `cmyk_profile` (the CMYK profile in effect) unless `set` names one.
/// When the settings leave the condition identifier blank, a profile computed for a registered
/// printing condition ([`cms::characterization`]) gives the condition's name as the identifier,
/// and its registry when the settings leave the registry blank too. An identifier set in the
/// settings is written as given, with the settings' registry.
fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option<Catalog> {
let o = &set.output;
if set.standard == Standard::PdfA2b {
@@ -631,13 +635,13 @@ fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option<Catalog> {
ProfileKind::Gray => None,
});
let text = |s: &str| s.trim().chars().take(MAX_TEXT).collect::<String>();
OutputIntent {
id: text(if id.is_empty() { name } else { id }),
condition: text(&o.output_condition),
registry: text(&o.registry),
info: text(name),
profile,
}
// Without a condition identifier, a profile computed for a registered printing condition
// names that condition and, unless the settings name one, the registry it belongs to.
let (id, registry) = match cms::characterization(name) {
Some((reference, registry)) if id.is_empty() => (reference, if o.registry.trim().is_empty() { registry } else { o.registry.as_str() }),
_ => (if id.is_empty() { name } else { id }, o.registry.as_str()),
};
OutputIntent { id: text(id), condition: text(&o.output_condition), registry: text(registry), info: text(name), profile }
});
let trapped = (o.trapped || intent.is_some()).then_some(o.trapped);
(intent.is_some() || trapped.is_some()).then_some(Catalog { intent, trapped })
+69
View File
@@ -151,6 +151,75 @@ fn each_standard_writes_its_header_output_intent_boxes_and_identification() {
assert!(matches!(e, Err(PdfError::BadSetting(m)) if m.contains("embeds")));
}
/// The ICC tag signatures of `icc`'s tag table.
fn icc_tags(icc: &[u8]) -> Vec<String> {
let count = u32::from_be_bytes(icc[128..132].try_into().unwrap()) as usize;
(0..count).map(|i| String::from_utf8_lossy(&icc[132 + 12 * i..136 + 12 * i]).into_owned()).collect()
}
#[test]
fn a_registered_condition_profile_names_its_condition_and_embeds_itself() {
use std::io::Read;
let d = doc(&[Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::cmyk(0.6, 0.0, 0.2, 0.1)]);
for (profile, reference) in [(cms::FOGRA51_CMYK, "FOGRA51"), (cms::FOGRA52_CMYK, "FOGRA52")] {
let r = export_with_report(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = profile.into())).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let t = text(&r.bytes);
let info = profile.replace('(', r"\(").replace(')', r"\)");
for want in [
"/S/GTS_PDFX".to_string(),
format!("/OutputConditionIdentifier({reference})"),
"/RegistryName(http://www.color.org)".into(),
format!("/Info({info})"),
] {
assert!(t.contains(&want), "{profile}: {want}");
}
// The embedded profile is the working space's: a CMYK output profile with Lab tables both
// ways, read from the file's bytes.
let oi: u32 = t.split("/DestOutputProfile ").nth(1).unwrap().split(' ').next().unwrap().parse().unwrap();
let (start, end) = crate::patch::Xref::read(&r.bytes).unwrap().dict(&r.bytes, oi).unwrap();
let obj = &r.bytes[start..end];
let at = crate::lab_spot::find(obj, b"/Length", 0).unwrap();
let (length, _) = crate::patch::number(obj, at + b"/Length".len()).unwrap();
let mut data = crate::lab_spot::find(obj, b"stream", at).unwrap() + b"stream".len();
data += obj[data..].iter().take(2).take_while(|b| matches!(b, b'\r' | b'\n')).count();
let raw = &obj[data..data + length];
let mut icc = vec![];
if crate::lab_spot::find(&obj[..data], b"/FlateDecode", 0).is_some() {
flate2::read::ZlibDecoder::new(raw).read_to_end(&mut icc).unwrap();
} else {
icc = raw.to_vec();
}
assert_eq!(icc.as_slice(), &*cms::icc_bytes(profile).unwrap());
assert_eq!((&icc[12..16], &icc[16..20], &icc[20..24], &icc[36..40]), (&b"prtr"[..], &b"CMYK"[..], &b"Lab "[..], &b"acsp"[..]));
assert!(matches!(icc[8], 2 | 4), "ICC version {}", icc[8]);
let tags = icc_tags(&icc);
for tag in ["A2B0", "B2A0", "A2B1", "B2A1", "gamt", "wtpt", "desc", "cprt"] {
assert!(tags.iter().any(|t| t == tag), "{profile}: {tag} in {tags:?}");
}
let back = cms::IccProfile::from_bytes(None, &icc).unwrap();
assert_eq!((back.name.as_str(), back.kind), (profile, cms::ProfileKind::Cmyk));
assert!(import(&r.bytes).is_ok());
}
// A condition identifier or registry the settings give stays.
let o = opts(Standard::PdfX4, |s| {
s.output.output_intent = cms::FOGRA51_CMYK.into();
s.output.output_condition_id = "Press 2".into();
});
let t = text(&export(&d, &o).unwrap());
assert!(t.contains("/OutputConditionIdentifier(Press 2)") && !t.contains("/RegistryName"), "{t}");
let o = opts(Standard::PdfX4, |s| {
s.output.output_intent = cms::FOGRA51_CMYK.into();
s.output.registry = "https://example.com/registry".into();
});
let t = text(&export(&d, &o).unwrap());
assert!(t.contains("/OutputConditionIdentifier(FOGRA51)") && t.contains("/RegistryName(https://example.com/registry)"));
// Other profiles keep their name as the identifier, with no registry.
let t = text(&export(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = GENERIC_CMYK.into())).unwrap());
let id = GENERIC_CMYK.replace('(', r"\(").replace(')', r"\)");
assert!(t.contains(&format!("/OutputConditionIdentifier({id})")) && !t.contains("/RegistryName"), "{t}");
}
#[test]
fn pdfx_1a_files_have_no_rgb() {
let mut d = doc(&[Color::rgb(0.9, 0.1, 0.1), Color::Lab { l: 50.0, a: 40.0, b: -20.0 }, Color::gray(0.5), Color::cmyk(0.1, 0.2, 0.3, 0.4)]);
+1 -3
View File
@@ -112,9 +112,7 @@ pub(crate) fn holds_instance(n: &Node) -> bool {
/// guide the view hides, a ruler guide (the canvas draws those), drawn hidden, or the instance its
/// symbol is being edited from?
pub(crate) fn left_out(opts: &crate::RenderOptions, doc: &vectorcraft_doc::Document, a: &Node) -> bool {
let view_item = a.is_ruler_guide()
|| (opts.skip_templates || opts.hide_templates) && matches!(a.kind, NodeKind::Layer { template: true, .. })
|| (opts.skip_templates || opts.hide_guides) && matches!(a.kind, NodeKind::Path { guide: true, .. });
let view_item = a.is_ruler_guide() || a.hidden_by_view(opts.skip_templates || opts.hide_templates, opts.skip_templates || opts.hide_guides);
!a.visible || view_item || opts.hidden.contains(&a.id) || edited_instance(opts, doc, a.id)
}
+11 -1
View File
@@ -73,6 +73,10 @@ pub(crate) fn colour_glyph(
return (None, false);
}
let used = tree.foreground_used;
// Over the budget nothing is drawn, not even the raster fallback: it would replay the graph.
if tree.too_large {
return (None, used);
}
if tree.unsupported.is_some() {
// What it paints, y up, for a glyph without a clip box.
let painted = tree.painted.map(|b| FLIP.transform_rect_bbox(b));
@@ -114,7 +118,7 @@ fn outline(font: &skrifa::FontRef<'_>, location: LocationRef<'_>, gid: GlyphId)
if let Some(g) = font.outline_glyphs().get(gid) {
let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), location), &mut pen);
}
let mut path = pen.0;
let mut path = pen.finish();
path.apply_affine(FLIP);
path
}
@@ -507,6 +511,9 @@ impl ColorPainter for Tree<'_> {
self.unsupported.get_or_insert("a fill outside any glyph");
return;
};
if self.too_large {
return;
}
let Some(clip) = self.groups.get(at).and_then(|g| g.clip.clone()) else { return };
let innermost = at + 1 == self.groups.len();
let before = self.groups.last().map_or(0, |g| g.children.len());
@@ -523,6 +530,9 @@ impl ColorPainter for Tree<'_> {
/// The glyph's outline filled, the brush moved by `brush_transform` (the glyph stays).
fn fill_glyph(&mut self, glyph_id: GlyphId, brush_transform: Option<Transform>, brush: Brush<'_>) {
if self.too_large {
return;
}
let path = self.layer_outline(glyph_id);
let brush_xf = self.transform() * brush_transform.as_ref().map_or(Affine::IDENTITY, affine);
self.transforms.push(brush_xf);
+17 -6
View File
@@ -7,14 +7,20 @@ pub(super) fn svg_drawn(face: &FontFace, font: &skrifa::FontRef<'_>, gid: u32) -
face.svg_glyphs && !crate::colr::has_colour_glyph(font, gid)
}
/// The most path elements one glyph outline keeps. Real outlines have hundreds; a variable
/// composite glyph can repeat a big base outline into millions. Elements past it are dropped.
/// Most path elements one glyph outline may have: a glyph that needs more (a variable font's
/// composite glyph repeating a large component many times) is drawn as nothing, not kept.
pub(crate) const MAX_OUTLINE_ELEMENTS: usize = 1 << 20;
/// A pen drawing outlines y down, as text space has them.
/// A pen drawing outlines y down, as text space has them. It stops taking segments once the path
/// holds [`MAX_OUTLINE_ELEMENTS`], and [`Self::finish`] then gives an empty path.
pub(crate) struct FlipPen(pub(crate) BezPath);
impl FlipPen {
/// The outline drawn, or an empty path when it passed [`MAX_OUTLINE_ELEMENTS`].
pub(crate) fn finish(self) -> BezPath {
if self.0.elements().len() >= MAX_OUTLINE_ELEMENTS { BezPath::new() } else { self.0 }
}
fn full(&self) -> bool {
self.0.elements().len() >= MAX_OUTLINE_ELEMENTS
}
@@ -77,12 +83,17 @@ mod tests {
use super::*;
#[test]
fn a_pen_keeps_at_most_the_element_cap() {
fn a_pen_past_the_cap_gives_nothing() {
let mut pen = FlipPen(BezPath::new());
pen.move_to(0.0, 0.0);
for i in 0..MAX_OUTLINE_ELEMENTS + 10 {
pen.line_to(i as f32, 0.0);
pen.line_to(i as f32, 1.0);
}
assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS);
assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS, "it stops taking segments");
assert!(pen.finish().elements().is_empty());
let mut small = FlipPen(BezPath::new());
small.move_to(0.0, 0.0);
small.line_to(1.0, 1.0);
assert_eq!(small.finish().elements().len(), 2);
}
}
+2 -1
View File
@@ -725,7 +725,8 @@ impl FontDb {
// As before, keep the prefix emitted before a malformed glyph reports an error.
let _ = font.draw_to(gid, &mut pen);
}
pen.0
// An outline past MAX_OUTLINE_ELEMENTS comes back empty.
pen.finish()
}
/// Glyph `gid`'s colour bitmap (`sbix`, `CBDT`) in `face`, cached per (face, glyph).
+22
View File
@@ -714,3 +714,25 @@ fn a_colour_glyph_on_a_path_turns_with_it() {
assert!((b.width() - upright.height()).abs() < 1.0 && (b.height() - upright.width()).abs() < 1.0, "on its side: {b:?}");
assert!(b.y0 >= -1.0 && b.y1 <= 400.0, "along the path: {b:?}");
}
/// A layer list that reuses one run of layers many times grows the tree past its node cap: the
/// glyph is then no colour glyph (it draws its outline), and the layers after the cap are not drawn.
#[test]
fn layers_repeating_a_run_of_layers_pass_the_cap() {
use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList};
use write_fonts::types::GlyphId16;
let bytes = colr_font(false).unwrap();
let o = skrifa::FontRef::new(&bytes).unwrap().charmap().map(COLOUR_CHAR).unwrap().to_u32();
let o = GlyphId16::new(u16::try_from(o).unwrap());
let font = |runs: u8| {
// 255 glyph layers, then `runs` layers that each repeat all of them.
let mut layers: Vec<ColrPaint> = (0..255).map(|_| ColrPaint::glyph(solid(0), o)).collect();
layers.extend((0..runs).map(|_| ColrPaint::colr_layers(255, 0)));
let mut colr = Colr::new(0, None, None, 0);
colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(o, ColrPaint::colr_layers(runs, 255))])).into();
colr.layer_list = Some(LayerList::new(layers.len() as u32, layers)).into();
crate::test_fonts::colr_font_with(&format!("Colrtest Runs {runs}"), &colr).unwrap()
};
assert!(matches!(content(&font(2), COLOUR_CHAR), Some(ColourContent::Art(_))), "510 layers fit");
assert!(content(&font(100), COLOUR_CHAR).is_none(), "25,500 layers do not");
}
+55 -8
View File
@@ -46,12 +46,31 @@ impl LineKind {
}
}
/// A fold line: the path (document coordinates), its kind, and a key the issues name it by.
/// A fold line: the path (document coordinates), its kind, a key the issues name it by, and its
/// own fold angle (degrees), which a line that folds takes instead of its kind's.
#[derive(Clone, Debug)]
pub struct FoldLine {
pub path: PathData,
pub kind: LineKind,
pub key: u64,
pub angle: Option<f64>,
}
/// `angle` (degrees) to the whole millionth of a degree, the finest fold angle a line keeps. A fold
/// that close to flat is flat: the preview tells panels in one plane from panels a millionth of a
/// degree apart, but not from panels closer than that.
pub fn kept_angle(angle: f64) -> f64 {
(angle * 1e6).round() / 1e6 + 0.0
}
impl FoldLine {
/// The angle (degrees) the line folds at: its own angle when it has one from -180 to 180, to the
/// millionth of a degree ([`kept_angle`]), else its kind's ([`LineKind::fold_angle`]); none for
/// a Cut, whatever its own angle.
pub fn fold_angle(&self) -> Option<f64> {
let own = self.angle.filter(|a| (-180.0..=180.0).contains(a)).map(kept_angle);
self.kind.fold_angle().map(|default| own.unwrap_or(default))
}
}
/// One blank: its panels, the hinges between them, and its holes.
@@ -79,14 +98,17 @@ impl Panel {
/// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight
/// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on
/// one straight line within the tolerance; `from` and `to` are then on the line through its longest
/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is
/// ([`LineKind::fold_angle`]).
/// piece. `angle` (degrees) is the fold angle ([`FoldLine::fold_angle`]) of the line with the most
/// length in the hinge, the one with the lowest key among lines of equal length. `on` is the middle
/// of its longest piece, a point where the two panels meet, which a hinge with gaps between its
/// pieces may not have at the middle of `from` to `to`.
#[derive(Clone, Debug)]
pub struct Hinge {
pub a: usize,
pub b: usize,
pub from: Point,
pub to: Point,
pub on: Point,
pub keys: Vec<u64>,
pub straight: bool,
pub angle: f64,
@@ -1297,9 +1319,34 @@ impl Context<'_> {
let sp = p.path.subpaths.first()?;
Some((sp.anchors.first()?.p, sp.anchors.last()?.p))
};
let ((p0, p1), longest) =
let ((p0, p1), _) =
group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?;
let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0);
let lengths: Vec<f64> = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::<f64>()).collect();
// The angle of the line with the most length in the hinge, the one with the lowest key on a
// tie: a line the planar map split into several pieces counts whole.
let mut by_line: HashMap<usize, f64> = HashMap::new();
for (p, len) in group.iter().zip(&lengths) {
// Subpaths of one line on top of each other count once.
let mut lines = p.lines.clone();
lines.sort_unstable();
lines.dedup();
for l in lines {
*by_line.entry(l).or_default() += len;
}
}
let folding: Vec<(f64, f64, u64)> = by_line
.iter()
.filter_map(|(&l, &len)| {
let line = self.lines.get(l)?;
Some((line.fold_angle()?, len, line.key))
})
.collect();
// Lengths summed from pieces in another order differ in their last bits: a few epsilons per
// piece, and no more, so a line measurably longer still wins.
let most = folding.iter().map(|f| f.1).fold(0.0, f64::max);
let pieces = f64::from(u32::try_from(group.len()).unwrap_or(u32::MAX));
let rounding = 8.0 * f64::EPSILON * (pieces + 1.0) * most;
let angle = folding.iter().filter(|f| f.1 >= most - rounding).min_by_key(|f| f.2).map_or(90.0, |f| f.0);
let len = p0.distance(p1);
// The longest piece only sets the direction; the length check is on the whole hinge below.
if len.is_nan() || len <= 1e-9 {
@@ -1321,7 +1368,7 @@ impl Context<'_> {
}
// The pieces' own length, not the span from the first to the last, which takes in the gaps
// between pieces that lie apart.
let length: f64 = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::<f64>()).sum();
let length: f64 = lengths.iter().sum();
if !(lo.is_finite() && hi.is_finite()) || hi - lo < self.tolerance || length.is_nan() || length < self.tolerance {
return None;
}
@@ -1331,7 +1378,7 @@ impl Context<'_> {
let mut keys = self.keys(lines);
keys.sort_unstable();
keys.dedup();
Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle })
Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, on: p0.midpoint(p1), keys, straight, angle })
}
/// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a
@@ -1465,7 +1512,7 @@ pub fn base_panel(panels: &[Panel]) -> Option<usize> {
mod pose;
pub mod raster;
pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon};
pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, Stack, fold, panel_at, pick, polygon};
#[cfg(test)]
mod tests;
+135 -22
View File
@@ -19,6 +19,11 @@ use super::{Blank, base_panel, point_in};
/// test and the preview.
pub const MAX_POLYGON_POINTS: usize = 1 << 16;
/// How far apart two placements of a panel may turn a unit direction and still be one placement:
/// above the rounding of up to [`super::MAX_PANELS`] turns, below the turn of a hinge a millionth
/// of a degree from another ([`super::kept_angle`], 1.7e-8).
const TURNED: f64 = 1e-10;
type V3 = [f64; 3];
fn sub(a: V3, b: V3) -> V3 {
@@ -105,14 +110,24 @@ impl Pose {
let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)];
Pose { m, t: add(self.turn(sub(at, r_at)), self.t) }
}
/// This pose, taken about `origin` (a point less `origin` to its place less `origin`), in the
/// flat blank's own terms.
fn about(&self, origin: V3) -> Pose {
Pose { m: self.m, t: add(sub(self.t, self.turn(origin)), origin) }
}
}
/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no
/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it
/// and the base.
/// A folded panel: where it is, the same about [`Folded::origin`] (`local`), its parent in the fold
/// tree (`None` for the base and for a panel no chain of hinges joins to it, which stays flat where
/// it is) and how many hinges lie between it and the base.
#[derive(Clone, Debug)]
pub struct FoldedPanel {
pub pose: Pose,
/// Where the panel is with the flat blank moved so `origin` is at 0: it takes a flat point less
/// `origin` to its place less `origin`. Worked out in these terms, it keeps the rounding of a
/// blank far from the document's origin to the size of the blank.
pub local: Pose,
pub parent: Option<usize>,
pub depth: usize,
}
@@ -141,6 +156,28 @@ pub struct Folded {
pub hinges: Vec<FoldedHinge>,
/// Pairs of panels (`a` < `b`) that pass through each other.
pub collisions: Vec<(usize, usize)>,
/// The fold tree that panels folded flat onto each other stack by.
pub stack: Stack,
/// The middle of the blank's bounds (flat, see [`flat`]), which [`FoldedPanel::local`] is about.
pub origin: [f64; 3],
}
/// The fold tree that panels in one plane stack by: the tree from the blank's largest panel (its
/// `root`), whichever panel is the base, so choosing another base moves the folded blank without
/// changing which panel shows where they lie flat on each other. The base's own tree when the two
/// join different panels.
#[derive(Clone, Debug, Default)]
pub struct Stack {
pub root: usize,
/// Each panel's parent in this tree.
pub parent: Vec<Option<usize>>,
/// The panels in breadth-first order from `root`, the panels not joined to it last.
pub order: Vec<usize>,
/// For each panel, the way from the hinge it is folded on into its parent, as folded: a vector
/// in the parent's plane, across the hinge to the side the fold took the parent to be on, as
/// long as the corners of the parent's bounds reach that way. `None` for `root` and the
/// panels not joined to it.
pub toward_parent: Vec<Option<[f64; 3]>>,
}
/// The panel of `blank` that `p` (document coordinates) lies in.
@@ -204,10 +241,25 @@ pub fn fold(blank: &Blank, base: Option<usize>, amount: f64, tolerance: f64) ->
});
}
let centers: Vec<Option<V3>> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect();
let (panels, tree, order) = place(blank, &by_panel, &centers, base, amount);
// The corners of each panel's bounds (flat).
let corners: Vec<Option<[V3; 4]>> = blank
.panels
.iter()
.map(|p| p.outline.bounds().map(|b| [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1)].map(|(x, y)| flat(Point::new(x, y)))))
.collect();
let origin = corners
.iter()
.flatten()
.flatten()
.fold(None, |b: Option<(V3, V3)>, c| {
Some(b.map_or((*c, *c), |(lo, hi)| ([lo[0].min(c[0]), lo[1].min(c[1]), 0.0], [hi[0].max(c[0]), hi[1].max(c[1]), 0.0])))
})
.map_or([0.0; 3], |(lo, hi)| scale(add(lo, hi), 0.5));
let placing = Placing { blank, by_panel: &by_panel, centers: &centers, corners: &corners, origin };
let (panels, tree, order, toward_parent) = place(&placing, base, amount);
// Closing hinges are measured with every hinge at its full angle, so a blank that closes when
// folded is not reported open part of the way there.
let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, &centers, base, 1.0).0) };
let full = if amount == 1.0 { None } else { Some(place(&placing, base, 1.0).0) };
let measured = full.as_deref().unwrap_or(&panels);
let hinges = blank
.hinges
@@ -224,15 +276,64 @@ pub fn fold(blank: &Blank, base: Option<usize>, amount: f64, tolerance: f64) ->
})
.collect();
let collisions = collisions(blank, &panels, tolerance);
Some(Folded { base, panels, order, hinges, collisions })
let own = Stack { root: base, parent: panels.iter().map(|p| p.parent).collect(), order: order.clone(), toward_parent };
let stack = match base_panel(&blank.panels) {
Some(root) if root != base => {
let (placed, root_tree, root_order, toward) = place(&placing, root, amount);
// Whether the root's tree puts every panel where the base's does, moved with the root
// (which lies at the identity in its own): the same hinges do, and around a loop of
// panels another tree can leave out a fold that placed them. Each panel's turn is
// compared to within `TURNED` whatever its size or place, and its inside point by the
// poses about `origin` (`local`), to rounding at that distance from it.
let agrees = |r: &FoldedPanel| {
let near = |a: V3, b: V3| length(sub(a, b)) <= 1e-9 * (1.0 + length(a).max(length(b)));
placed.iter().zip(&panels).enumerate().all(|(i, (p, q))| {
let joined = (i == root || p.parent.is_some(), i == base || q.parent.is_some());
let at = centers.get(i).copied().flatten().map_or([0.0; 3], |c| sub(c, origin));
let turned = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
.into_iter()
.all(|e| length(sub(r.local.turn(p.local.turn(e)), q.local.turn(e))) <= TURNED);
joined.0 == joined.1 && (!joined.0 || (turned && near(r.local.apply(p.local.apply(at)), q.local.apply(at))))
})
};
match panels.get(root) {
// The root's tree in the base's terms.
Some(r) if root_tree == tree || agrees(r) => Stack {
root,
parent: placed.iter().map(|p| p.parent).collect(),
order: root_order,
toward_parent: toward.into_iter().map(|v| v.map(|v| r.pose.turn(v))).collect(),
},
_ => own,
}
}
_ => own,
};
Some(Folded { base, panels, order, hinges, collisions, stack, origin })
}
/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its
/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not
/// joined to the base last).
fn place(blank: &Blank, by_panel: &[Vec<usize>], centers: &[Option<V3>], base: usize, amount: f64) -> (Vec<FoldedPanel>, Vec<bool>, Vec<usize>) {
/// What [`place`] gives: the placed panels, which hinges are in the tree, the panels' order and
/// [`Stack::toward_parent`].
type Tree = (Vec<FoldedPanel>, Vec<bool>, Vec<usize>, Vec<Option<V3>>);
/// What [`place`] places: the blank, each panel's hinges in order, each panel's inside point and
/// bounds corners (flat), and the point the panels' local poses are about.
struct Placing<'a> {
blank: &'a Blank,
by_panel: &'a [Vec<usize>],
centers: &'a [Option<V3>],
corners: &'a [Option<[V3; 4]>],
origin: V3,
}
/// The panels of the blank placed by the fold tree from `base` with each hinge at `amount` of its
/// angle, which hinges are in the tree, the panels in breadth-first order (the panels not joined
/// to the base last), and [`Stack::toward_parent`].
fn place(placing: &Placing, base: usize, amount: f64) -> Tree {
let Placing { blank, by_panel, centers, corners, origin } = *placing;
let n = blank.panels.len();
let mut panels: Vec<FoldedPanel> = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n];
let mut panels: Vec<FoldedPanel> = vec![FoldedPanel { pose: Pose::IDENTITY, local: Pose::IDENTITY, parent: None, depth: 0 }; n];
let mut toward_parent: Vec<Option<V3>> = vec![None; n];
let mut reached = vec![false; n];
let mut tree = vec![false; blank.hinges.len()];
let mut order = Vec::with_capacity(n);
@@ -257,7 +358,7 @@ fn place(blank: &Blank, by_panel: &[Vec<usize>], centers: &[Option<V3>], base: u
// The parent on the left of the hinge's direction, the child on its right. The side is
// read next to the hinge, so a parent with a notch or an arm past the hinge's line still
// turns the child the right way; the panel's inside point is the fallback.
let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) {
let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len, flat(h.on))) {
Some(left) => left,
None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0),
};
@@ -270,7 +371,15 @@ fn place(blank: &Blank, by_panel: &[Vec<usize>], centers: &[Option<V3>], base: u
continue;
}
if let Some(slot) = panels.get_mut(child) {
*slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 };
let local = parent.local.turned_about(sub(from, origin), axis, theta);
*slot = FoldedPanel { pose: local.about(origin), local, parent: Some(p), depth: parent.depth + 1 };
}
// Across the hinge, to its left: into the parent, as far as the corners of its bounds
// reach that way.
let into = [-axis[1], axis[0], 0.0];
let reach = corners.get(p).copied().flatten().map_or(0.0, |c| c.into_iter().map(|c| dot(sub(c, from), into)).fold(0.0, f64::max));
if let Some(slot) = toward_parent.get_mut(child) {
*slot = Some(parent.pose.turn(scale(into, reach)));
}
if let Some(r) = reached.get_mut(child) {
*r = true;
@@ -282,23 +391,27 @@ fn place(blank: &Blank, by_panel: &[Vec<usize>], centers: &[Option<V3>], base: u
}
}
order.extend((0..n).filter(|&i| reached.get(i) == Some(&false)));
(panels, tree, order)
(panels, tree, order, toward_parent)
}
/// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart)
/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and
/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset
/// tells them apart. The nearest offset is tried first.
fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option<bool> {
/// next to it: `true` when a point just off the line on the left is inside it and the matching
/// point on the right is not, `false` the other way round. `on` (a point of the line where the
/// panels meet: [`super::Hinge::on`]) is tried first, then the middle and points a quarter and an
/// eighth of the way along, each with the nearest offset first; `None` when no point tells the
/// sides apart.
fn side_of(outline: &PathData, from: V3, to: V3, len: f64, on: V3) -> Option<bool> {
let bp = outline.to_bezpath();
let mid = scale(add(from, to), 0.5);
let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0];
let doc = |v: V3| Point::new(v[0], -v[1]);
let mut offsets = [1e-3, 0.25, len * 0.01];
offsets.sort_by(f64::total_cmp);
offsets.into_iter().find_map(|off| {
let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0);
(l != r).then_some(l)
let along = [0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875].map(|t| add(from, scale(sub(to, from), t)));
std::iter::once(on).chain(along).find_map(|at| {
offsets.into_iter().find_map(|off| {
let (l, r) = (bp.winding(doc(add(at, scale(left, off)))) != 0, bp.winding(doc(sub(at, scale(left, off)))) != 0);
(l != r).then_some(l)
})
})
}
+236 -12
View File
@@ -16,8 +16,18 @@ pub const MAX_SIDE: u32 = 4096;
pub const MAX_PIXELS: u32 = 1 << 21;
/// The share of the eye's distance a panel is cut at in front of the eye.
const NEAREST: f64 = 1e-3;
/// How far apart (points of view depth) two panels may be and still tie.
/// How far apart (points of view depth) two panels in one plane may be and still tie.
const TIE: f64 = 1e-4;
/// How far apart (the sine of the angle) two panels' normals may be for the panels to lie in one
/// plane.
const PARALLEL: f64 = 1e-9;
/// How far apart two parallel panels' planes may be for the panels to lie in one plane: rounding,
/// as this many times the precision of a number at their distance from the origin for each hinge
/// that placed them.
const COPLANAR: f64 = 16.0 * f64::EPSILON;
/// How far across a panel's plane (the cosine to its normal) a fold's step may go and still count
/// as along it.
const ALONG: f64 = 1e-6;
/// The light's direction: above, to the left of and toward the viewer.
const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74];
@@ -278,11 +288,11 @@ fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
inv.iter().flatten().all(|v| v.is_finite()).then_some(inv)
}
fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option<Mapped> {
fn map_panel(camera: &Camera, pose: &super::Pose) -> Option<Mapped> {
let r = camera.rotation();
let turn = |v: V3| mul(&r, f.pose.turn(v));
let turn = |v: V3| mul(&r, pose.turn(v));
let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0]));
let o = camera.to_view(f.pose.t);
let o = camera.to_view(pose.t);
let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]);
let normal = turn([0.0, 0.0, 1.0]);
let (w, k, printed) = match camera.eye() {
@@ -326,18 +336,23 @@ struct Target {
panel: Vec<u16>,
}
/// One panel's fill: its map, rank (for ties), panel number and colors.
/// One panel's fill: its map, rank and plane (for ties: the plane of every panel by its index, as
/// [`planes`] gives them), panel number and colors.
struct Fill<'a> {
mapped: &'a Mapped,
rank: u16,
planes: &'a [u16],
panel: u16,
print: Option<&'a Print>,
/// The flat point the map is about ([`Folded::origin`]): a flat point less it is what
/// `mapped` maps.
origin: [f64; 2],
inside: [f32; 4],
outside: [f32; 4],
}
impl Fill<'_> {
/// The document point under pixel center `(x, y)`, or `None` behind the eye.
/// The flat point (less [`Fill::origin`]) under pixel center `(x, y)`, or `None` behind the eye.
fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> {
let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]);
(w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite())
@@ -346,7 +361,7 @@ impl Fill<'_> {
/// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel.
fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] {
let base = if self.mapped.printed {
let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint));
let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u + self.origin[0], -(v + self.origin[1])), footprint));
let under = 1.0 - p[3] / 255.0;
[p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0]
} else {
@@ -370,8 +385,12 @@ impl Fill<'_> {
let [a, b, c] = self.mapped.depth;
let z = u * a + v * b + c;
let i = row * target.width + col;
let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue };
let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb);
let (Some(&zb), Some(&rb), Some(&pb)) = (target.depth.get(i), target.rank.get(i), target.panel.get(i)) else { continue };
// Panels in one plane tie within `TIE` and stack by rank; panels in different planes
// that pass this close go by depth alone. Panel numbers count from 1.
let plane = |p: u16| usize::from(p).checked_sub(1).and_then(|p| self.planes.get(p));
let one_plane = plane(self.panel).is_some_and(|a| plane(pb) == Some(a));
let wins = if one_plane { z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb) } else { z > zb };
if !wins {
continue;
}
@@ -442,6 +461,161 @@ fn flat_rings(panel: &Panel, scale: f64) -> Option<Vec<Vec<[f64; 2]>>> {
Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect())
}
/// The rank (from 1) each panel of `folded.order` takes in a depth tie, the higher one drawn. Each
/// fold puts a panel in a layer next to its parent in [`Folded::stack`]: behind the parent's printed
/// side for a positive angle, in front of it for a negative one, level with it for 0°. Layers are
/// compared fold by fold from the stack's root (the largest panel, whichever panel is the base), so
/// a panel folded back over its parent's parent lands between the two at any depth. A tie, between
/// panels in one plane, goes to the panel whose layer is nearer the viewer across that plane (the
/// side of the plane `camera` sees). Two folds into one layer stack by the stack's order, the later
/// one nearer seen from one side of their plane and the earlier one seen
/// from the other, and the panels folded on from each stay with it. Two panels folded flat onto each other
/// (±180°) tie in depth everywhere they overlap. A panel that comes back onto the plane of a panel
/// it branched from, after leaving it, takes the side of that plane it came back from for every
/// step up to the one it left by: the side the nearest panel out of the plane lies on from the
/// hinge it joins the plane at ([`super::Stack::toward_parent`]). `planes` gives each panel's plane, as
/// [`planes`] does.
fn tie_ranks(folded: &Folded, camera: &Camera, planes: &[u16]) -> Vec<u16> {
let n = folded.panels.len();
// Each panel's layer holds a step per fold up to the base: past the panels a blank can have,
// the order alone decides. So it does when every panel lies where it lies flat (a fold amount
// of 0), as panels there do not overlap.
if n > super::MAX_PANELS || folded.order.len() > super::MAX_PANELS || folded.panels.iter().all(|f| f.pose == super::Pose::IDENTITY) {
return (1..=folded.order.len()).map(|r| u16::try_from(r).unwrap_or(u16::MAX)).collect();
}
// The step each panel takes off its parent: the parent's printed side, negated for a positive
// angle; none for a 0° hinge or a panel without a parent.
// The parents are those of [`Folded::stack`], so the panels stack the same about any base.
let stack = &folded.stack;
let parent_of = |c: usize| stack.parent.get(c).copied().flatten();
let mut step: Vec<Option<V3>> = vec![None; n];
for c in 0..n {
let Some(p) = parent_of(c) else { continue };
let Some(h) = folded.hinges.iter().find(|h| (h.a, h.b) == (p, c) || (h.a, h.b) == (c, p)) else { continue };
let (Some(parent), Some(slot)) = (folded.panels.get(p), step.get_mut(c)) else { continue };
let [x, y, z] = parent.pose.normal();
*slot = match h.angle {
a if a > 0.0 => Some([-x, -y, -z]),
a if a < 0.0 => Some([x, y, z]),
_ => None,
};
}
// Each panel's layer, from the base out: +1 for a step toward the viewer across the panel's
// plane, -1 for one away from it, 0 for one along it. Comparing these in order puts a panel next
// to its parent, before any later step, however many folds deep.
// Each panel's place in the stack's order.
let mut place = vec![0usize; n];
for (i, &pi) in stack.order.iter().enumerate() {
if let Some(slot) = place.get_mut(pi) {
*slot = i;
}
}
// Each step also carries the place in `folded.order` of the panel that took it, so panels whose
// steps match up to a fold that branches stack by that branch: the later panel nearer seen from
// one side of their plane, the earlier one seen from the other, so the two sides show opposite
// panels. The rest of a branch stays with it.
// Whether the view sees each panel's printed side.
let sees_print: Vec<bool> = folded.panels.iter().map(|f| map_panel(camera, &f.pose).is_none_or(|m| m.printed)).collect();
// The nearest panel out of `pi`'s plane on its way to the base, and the side of that plane it
// lies on from the hinge it joins the panels in the plane at: 1 the side `n_view` points to, -1
// the other; `None` when every panel on the way lies in the plane. The plane is the one
// [`planes`] gives, the same that decides which panels tie, so a ramp however shallow leaves it
// and a stack folded a hair short of flat goes by depth instead.
let approach = |pi: usize, n_view: V3| -> Option<(usize, i8)> {
let (mut child, mut up) = (pi, parent_of(pi));
for _ in 0..n {
let c = up?;
if planes.get(c) != planes.get(pi)
&& let Some(Some(way)) = stack.toward_parent.get(child)
{
let d = dot(*way, n_view);
if d != 0.0 {
return Some((c, if d > 0.0 { 1 } else { -1 }));
}
}
(child, up) = (c, parent_of(c));
}
None
};
let layer = |pi: usize| -> Vec<(i8, i64)> {
let Some(f) = folded.panels.get(pi) else { return vec![] };
let printed = sees_print.get(pi).copied().unwrap_or(true);
let n_view = {
let [x, y, z] = f.pose.normal();
if printed { [x, y, z] } else { [-x, -y, -z] }
};
let mut out = vec![];
let mut at = Some(pi);
// From the nearest panel out of the plane on the way to the base, every step counts as on
// the side of the plane that panel lies on: a panel that comes round onto the plane of a
// panel it branched from lies on the side it came back from, whatever its folds before.
let (back_at, back_side) = approach(pi, n_view).map_or((None, 0), |(c, s)| (Some(c), s));
let mut returned = false;
// A panel's chain to the base is at most the panel count long.
for _ in 0..n {
let Some(c) = at else { break };
returned |= Some(c) == back_at;
if let Some(Some(s)) = step.get(c) {
let d = if returned { f64::from(back_side) } else { dot(*s, n_view) };
// Branches off one panel stack one way seen from that panel's printed side and the
// other way from its back, so the panels of one plane that compare a step off one
// parent agree, however the parent is turned.
let branch = place.get(c).map_or(i64::MAX, |&p| i64::try_from(p).unwrap_or(i64::MAX));
// A parent seen edge on gives no side: the panel that took the step gives it, and
// when that is edge on too, the largest part of the view's normal does. Each choice
// gives two panels of one plane the same sign however an edge-on dot rounds, and
// each turns over with the side of the plane the view is on.
let faces = |f: &super::FoldedPanel| {
let d = dot(f.pose.normal(), n_view);
(d.abs() > ALONG).then_some(d >= 0.0)
};
// The view's normal in the root's flat terms, so this too is the same about any base.
let largest = || {
let m = folded.panels.get(stack.root).map_or(super::Pose::IDENTITY.m, |r| r.pose.m);
let local = [0, 1, 2].map(|j| (0..3).map(|i| m[i][j] * n_view[i]).sum::<f64>());
local.into_iter().max_by(|a, b| a.abs().total_cmp(&b.abs())).is_none_or(|v| v >= 0.0)
};
let parent = parent_of(c).and_then(|p| folded.panels.get(p));
let parent_faces = parent.map_or(Some(true), faces).or_else(|| folded.panels.get(c).and_then(faces)).unwrap_or_else(largest);
let branch = if parent_faces { branch } else { -branch };
// Any step that is not along the plane counts whole, so a step seen from two panels
// of one plane counts the same for both.
out.push((i8::from(d > ALONG) - i8::from(d < -ALONG), branch));
}
at = parent_of(c);
}
out.reverse();
out
};
// Layers compared step by step, a missing step as none.
let compare = |a: &[(i8, i64)], b: &[(i8, i64)]| {
(0..a.len().max(b.len()))
.map(|k| a.get(k).copied().unwrap_or((0, 0)).cmp(&b.get(k).copied().unwrap_or((0, 0))))
.find(|o| o.is_ne())
.unwrap_or(std::cmp::Ordering::Equal)
};
// A panel alone in its plane ties with no other, so its layer is not worked out.
let mut in_plane = vec![0usize; planes.iter().map(|&p| usize::from(p) + 1).max().unwrap_or(0)];
for &p in planes {
if let Some(c) = in_plane.get_mut(usize::from(p)) {
*c += 1;
}
}
let alone = |pi: usize| planes.get(pi).and_then(|&p| in_plane.get(usize::from(p))).is_some_and(|&c| c <= 1);
let mut keys: Vec<(Vec<(i8, i64)>, usize)> =
folded.order.iter().enumerate().map(|(i, &pi)| (if alone(pi) { vec![] } else { layer(pi) }, i)).collect();
// Then by the stack's order, for panels that stack as one.
let placed = |i: usize| folded.order.get(i).and_then(|&pi| place.get(pi)).copied().unwrap_or(usize::MAX);
keys.sort_by(|a, b| compare(&a.0, &b.0).then(placed(a.1).cmp(&placed(b.1))).then(a.1.cmp(&b.1)));
let mut ranks = vec![0u16; folded.order.len()];
for (r, &(_, i)) in keys.iter().enumerate() {
if let Some(slot) = ranks.get_mut(i) {
*slot = u16::try_from(r + 1).unwrap_or(u16::MAX);
}
}
ranks
}
/// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more
/// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than
/// [`super::MAX_POLYGON_POINTS`] points, are left out.
@@ -456,10 +630,17 @@ pub fn render(scene: &Scene) -> Option<Image> {
Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] };
let (inside, outside) = (opaque(scene.inside), opaque(scene.outside));
let near = camera.eye().map(|(eye, _)| eye * NEAREST);
for (rank, &pi) in scene.folded.order.iter().enumerate() {
let planes = planes(scene.folded, scene.blank);
let ranks = tie_ranks(scene.folded, &camera, &planes);
// Panels are drawn by their poses about the blank's middle (`FoldedPanel::local`), with the flat
// points and the view's center moved to match.
let o = scene.folded.origin;
let local = Camera { center: [camera.center[0] - o[0], camera.center[1] - o[1], camera.center[2] - o[2]], ..camera };
for (&pi, &rank) in scene.folded.order.iter().zip(&ranks) {
let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue };
let Some(mapped) = map_panel(&camera, f) else { continue };
let Some(mapped) = map_panel(&local, &f.local) else { continue };
let Some(rings) = flat_rings(panel, camera.scale) else { continue };
let rings: Vec<Vec<[f64; 2]>> = rings.into_iter().map(|r| r.into_iter().map(|[u, v]| [u - o[0], v - o[1]]).collect()).collect();
let projected: Vec<Vec<[f64; 2]>> = rings
.iter()
.map(|r| match near {
@@ -480,9 +661,11 @@ pub fn render(scene: &Scene) -> Option<Image> {
.collect();
let fill = Fill {
mapped: &mapped,
rank: u16::try_from(rank + 1).unwrap_or(u16::MAX),
rank,
planes: &planes,
panel: u16::try_from(pi + 1).unwrap_or(u16::MAX),
print: scene.print,
origin: [o[0], o[1]],
inside,
outside,
};
@@ -491,5 +674,46 @@ pub fn render(scene: &Scene) -> Option<Image> {
Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel })
}
/// The plane each panel of `folded` lies in, as a number shared by the panels in one plane: their
/// normals parallel to within [`PARALLEL`] and their planes as far apart as rounding leaves them
/// ([`COPLANAR`] at their distance from [`Folded::origin`] for each hinge between them and the
/// base), so a parallel panel any measurable way behind another goes by depth. Each panel is
/// measured at the middle of its bounds in `blank`, by its pose about [`Folded::origin`]
/// ([`super::FoldedPanel::local`]), so where the blank lies in the document does not change the
/// planes. Past [`super::MAX_PANELS`] panels, one plane for all.
fn planes(folded: &Folded, blank: &Blank) -> Vec<u16> {
let n = folded.panels.len();
if n > super::MAX_PANELS {
return vec![0; n];
}
let length = |v: V3| dot(v, v).sqrt();
// Each plane's normal, a point of it, the size of the coordinates that point came from and the
// hinges that placed it.
let mut kinds: Vec<(V3, V3, f64, usize)> = vec![];
folded
.panels
.iter()
.enumerate()
.map(|(i, f)| {
let o = folded.origin;
let middle = blank.panels.get(i).and_then(|p| p.outline.bounds()).map_or([0.0; 3], |b| [b.center().x - o[0], -b.center().y - o[1], 0.0]);
let (normal, at) = (f.local.normal(), f.local.apply(middle));
let size = length(at).max(length(middle));
let same = |(m, p, s, d): &(V3, V3, f64, usize)| {
let c = [normal[1] * m[2] - normal[2] * m[1], normal[2] * m[0] - normal[0] * m[2], normal[0] * m[1] - normal[1] * m[0]];
let apart = dot(*m, [at[0] - p[0], at[1] - p[1], at[2] - p[2]]).abs();
// Saturating: a `Folded` built by a caller may carry any depth.
let hinges = f64::from(u32::try_from(f.depth.saturating_add(*d).saturating_add(1)).unwrap_or(u32::MAX));
length(c) <= PARALLEL && apart <= COPLANAR * hinges * (1.0 + size.max(*s))
};
let k = kinds.iter().position(same).unwrap_or_else(|| {
kinds.push((normal, at, size, f.depth));
kinds.len() - 1
});
u16::try_from(k).unwrap_or(u16::MAX)
})
.collect()
}
#[cfg(test)]
mod tests;
File diff suppressed because it is too large. Load diff
+203 -4
View File
@@ -13,7 +13,7 @@ fn poly(points: &[(f64, f64)], closed: bool) -> PathData {
}
fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine {
FoldLine { path: poly(points, closed), kind, key }
FoldLine { path: poly(points, closed), kind, key, angle: None }
}
fn cut(points: &[(f64, f64)], key: u64) -> FoldLine {
@@ -188,7 +188,7 @@ fn a_round_tuck_flap_folds_like_any_panel() {
bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0));
bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0));
bp.close_path();
let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)];
let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1, angle: None }, crease((0.0, 40.0), (100.0, 40.0), 2)];
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].panels.len(), 2);
@@ -353,7 +353,7 @@ fn an_outline_drawn_twice_keeps_its_material() {
// The same two squares as the subpaths of one compound path.
let mut twice = poly(&square, true);
twice.subpaths.extend(poly(&square, true).subpaths);
let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1 }]);
let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1, angle: None }]);
assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}");
assert_eq!(issues[0].keys, vec![1]);
assert_eq!(areas(&b[0]), vec![10_000_000]);
@@ -549,7 +549,7 @@ fn a_curved_crease_is_measured_at_its_farthest_point_from_its_line() {
bp.curve_to(p(10000.0 / 3.0 - off, 10000.0 / 3.0 + off), p(20000.0 / 3.0 + off, 20000.0 / 3.0 - off), p(10000.0, 10000.0));
let lines = vec![
cut(&[(0.0, 0.0), (10000.0, 0.0), (10000.0, 10000.0), (0.0, 10000.0)], 1),
FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2 },
FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2, angle: None },
];
let (b, issues) = blanks(&lines, 10.0);
assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}");
@@ -1233,3 +1233,202 @@ fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() {
assert_eq!(b[0].hinges.len(), 1);
assert_eq!(b[0].hinges[0].angle, 90.0);
}
#[test]
fn a_line_s_own_angle_takes_the_place_of_its_kind_s() {
let own = |kind, angle| FoldLine { path: poly(&[(0.0, 0.0), (1.0, 0.0)], false), kind, key: 1, angle };
assert_eq!(own(LineKind::Crease, Some(45.0)).fold_angle(), Some(45.0));
assert_eq!(own(LineKind::PartialCut, Some(30.0)).fold_angle(), Some(30.0));
assert_eq!(own(LineKind::Perforation, Some(-120.0)).fold_angle(), Some(-120.0));
assert_eq!(own(LineKind::PartialCut, None).fold_angle(), Some(-90.0));
// An angle that is not a number folds at the kind's; a cut never folds.
assert_eq!(own(LineKind::Crease, Some(f64::NAN)).fold_angle(), Some(90.0));
assert_eq!(own(LineKind::Crease, Some(f64::INFINITY)).fold_angle(), Some(90.0));
assert_eq!(own(LineKind::Crease, Some(f64::MAX)).fold_angle(), Some(90.0));
// Past -180 to 180, before rounding, as for an angle the engine stores.
assert_eq!(own(LineKind::Crease, Some(360.0)).fold_angle(), Some(90.0));
assert_eq!(own(LineKind::PartialCut, Some(-180.0000001)).fold_angle(), Some(-90.0));
assert_eq!(own(LineKind::Crease, Some(-180.0)).fold_angle(), Some(-180.0));
assert_eq!(own(LineKind::Cut, Some(45.0)).fold_angle(), None);
// To the millionth of a degree: closer to flat than that is flat.
assert_eq!(own(LineKind::Crease, Some(-179.99999998)).fold_angle(), Some(-180.0));
assert_eq!(own(LineKind::Crease, Some(179.9999994)).fold_angle(), Some(179.999999));
assert_eq!(own(LineKind::Crease, Some(-0.0000001)).fold_angle().map(f64::to_bits), Some(0.0f64.to_bits()));
}
#[test]
fn a_tray_wall_with_its_own_angle_stands_at_that_angle() {
let mut lines = tray();
// The wall below the base (y 90 to 120) folds at 45°, the others at 90°.
for l in lines.iter_mut().filter(|l| l.key == 12) {
l.angle = Some(45.0);
}
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
let b = &b[0];
let f = fold(b, None, 1.0, TOL).expect("folds");
for (i, panel) in b.panels.iter().enumerate().filter(|(i, _)| *i != f.base) {
let n = f.panels[i].pose.normal();
// The cosine of the angle between the wall's print and the base's.
let lower = panel.outline.bounds().is_some_and(|r| r.y0 > 89.0);
let want = if lower { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 };
assert!((n[2] - want).abs() < 1e-9, "panel {i} ({lower}): {n:?}");
}
let h = b.hinges.iter().find(|h| h.keys == [12]).expect("the lower wall's hinge");
assert_eq!(h.angle, 45.0);
}
#[test]
fn a_hinge_takes_the_angle_of_its_longest_line_however_the_map_splits_it() {
// One hinge along y = 60: a 60 pt crease at 30° and a 40 pt crease at 120°. A crease that
// stops inside the panel above meets the first at x = 30, splitting it into two 30 pt pieces.
let mut lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1),
crease((0.0, 60.0), (60.0, 60.0), 2),
crease((60.0, 60.0), (100.0, 60.0), 3),
crease((30.0, 60.0), (30.0, 90.0), 4),
];
lines[1].angle = Some(30.0);
lines[2].angle = Some(120.0);
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}");
let hinges: Vec<_> = b[0].hinges.iter().filter(|h| h.keys.contains(&2)).collect();
assert_eq!(hinges.len(), 1, "{:?}", b[0].hinges);
assert_eq!((hinges[0].keys.clone(), hinges[0].angle), (vec![2, 3], 30.0));
}
#[test]
fn a_line_s_subpaths_on_top_of_each_other_count_once_toward_the_hinge_angle() {
// One hinge along y = 60: a 40 pt crease at 30° drawn as two subpaths on top of each other,
// and a 60 pt crease at 120°.
let mut twice = poly(&[(0.0, 60.0), (40.0, 60.0)], false);
twice.subpaths.extend(poly(&[(0.0, 60.0), (40.0, 60.0)], false).subpaths);
let lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1),
FoldLine { path: twice, kind: LineKind::Crease, key: 2, angle: Some(30.0) },
FoldLine { path: poly(&[(40.0, 60.0), (100.0, 60.0)], false), kind: LineKind::Crease, key: 3, angle: Some(120.0) },
];
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}");
assert_eq!(b[0].hinges.len(), 1, "{:?}", b[0].hinges);
assert_eq!(b[0].hinges[0].angle, 120.0);
}
#[test]
fn lines_of_equal_length_on_one_hinge_give_the_lowest_key_s_angle_in_any_order() {
let mut a = crease((0.0, 60.0), (50.0, 60.0), 5);
a.angle = Some(30.0);
let mut b = crease((50.0, 60.0), (100.0, 60.0), 3);
b.angle = Some(120.0);
let outline = cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1);
for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline.clone(), b.clone(), a.clone()]] {
let (blanks, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(blanks[0].hinges.len(), 1);
assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::<Vec<_>>());
}
// The same along a diagonal, with the line of the higher key split in two by a crease that
// stops inside a panel: its pieces' lengths (2√2 and 10√2) add up to a little more than the
// other line's (12√2) in floating point.
let mut a = crease((0.0, 0.0), (12.0, 12.0), 5);
a.angle = Some(30.0);
let mut b = crease((12.0, 12.0), (24.0, 24.0), 3);
b.angle = Some(120.0);
let outline = cut(&[(0.0, 0.0), (24.0, 0.0), (24.0, 24.0), (0.0, 24.0)], 1);
let dangling = crease((2.0, 2.0), (6.0, 3.0), 4);
for lines in [vec![outline.clone(), a.clone(), b.clone(), dangling.clone()], vec![outline, dangling, b, a]] {
let (blanks, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}");
assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges);
assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::<Vec<_>>());
}
// A line 0.0005 pt longer than the other at 1,000,000 pt is longer, not a tie: its angle wins
// over the lower key's.
let mut a = crease((0.0, 60.0), (1_000_000.0, 60.0), 3);
a.angle = Some(30.0);
let end = 2_000_000.000_5;
let mut b = crease((1_000_000.0, 60.0), (end, 60.0), 5);
b.angle = Some(120.0);
let outline = cut(&[(0.0, 0.0), (end, 0.0), (end, 160.0), (0.0, 160.0)], 1);
for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline, b, a]] {
let (blanks, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges);
assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::<Vec<_>>());
}
}
#[test]
fn a_loop_folded_about_another_panel_stacks_by_the_same_tree_wherever_it_lies() {
// A 100 × 100 blank cut into four 50 pt squares, its creases at 0° but for the one that closes
// the loop about the largest panel, at 0.001°: folded about a panel on that crease, the largest
// panel's tree places the panels up to 0.0009 pt from where the fold's own does. The same at the
// origin and 3,000,000 pt to the right.
let own_tree = |dx: f64| {
let lines = |closing: Option<u64>| {
let crease = |a: (f64, f64), b: (f64, f64), key: u64| {
let mut l = crease((a.0 + dx, a.1), (b.0 + dx, b.1), key);
l.angle = Some(if Some(key) == closing { 0.001 } else { 0.0 });
l
};
vec![
cut(&[(dx, 0.0), (100.0 + dx, 0.0), (100.0 + dx, 100.0), (dx, 100.0)], 1),
crease((50.0, 0.0), (50.0, 50.0), 2),
crease((50.0, 50.0), (50.0, 100.0), 3),
crease((0.0, 50.0), (50.0, 50.0), 4),
crease((50.0, 50.0), (100.0, 50.0), 5),
]
};
let (b, issues) = check(&lines(None));
assert!(issues.is_empty(), "{issues:?}");
let level = fold(&b[0], None, 1.0, TOL).expect("folds");
let closing = level.hinges.iter().position(|h| !h.tree).expect("a hinge closes the loop");
let key = b[0].hinges[closing].keys[0];
let (b, issues) = check(&lines(Some(key)));
assert!(issues.is_empty(), "{issues:?}");
let f = fold(&b[0], Some(b[0].hinges[closing].a), 1.0, TOL).expect("folds");
f.stack.root == f.base
};
assert!(own_tree(0.0), "the trees do not agree, so the fold's own tree");
assert!(own_tree(3_000_000.0), "far from the origin too");
}
#[test]
fn small_panels_far_from_the_middle_of_the_blank_stack_by_the_fold_s_own_tree() {
// A 2 × 2 grid of 5 pt squares at the end of a 1,000 pt strip, the largest panel, joined to the
// grid's right squares. Every crease is at 0° but the one between the two left squares, at a
// millionth of a degree: folded about a panel on it, the strip's tree leaves that crease out
// and places the other square at most 0.0000001 pt from where the fold's own tree does.
let mut lines = vec![
cut(&[(0.0, 0.0), (1010.0, 0.0), (1010.0, 10.0), (0.0, 10.0)], 1),
crease((5.0, 0.0), (5.0, 5.0), 2),
crease((5.0, 5.0), (5.0, 10.0), 3),
crease((0.0, 5.0), (5.0, 5.0), 4),
crease((5.0, 5.0), (10.0, 5.0), 5),
crease((10.0, 0.0), (10.0, 10.0), 6),
];
for l in &mut lines {
l.angle = Some(if l.key == 4 { 0.000001 } else { 0.0 });
}
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
let h = b[0].hinges.iter().find(|h| h.keys == [4]).expect("the left squares' hinge");
let f = fold(&b[0], Some(h.a), 1.0, TOL).expect("folds");
assert!(f.hinges.iter().zip(&b[0].hinges).any(|(fh, h)| fh.tree && h.keys == [4]));
assert_eq!(f.stack.root, f.base, "the trees place a panel at different turns");
}
#[test]
fn a_negative_angle_folds_a_crease_toward_the_print() {
let mut lines = two_panels(LineKind::Crease, 0, false, false);
for l in lines.iter_mut().filter(|l| l.key == 2) {
l.angle = Some(-90.0);
}
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
let b = &b[0];
let f = fold(b, None, 1.0, TOL).expect("folds");
let child = 1 - f.base;
let placed = f.panels[child].pose.apply(flat_center(b, child));
assert!(placed[2] > 0.0, "in front of the print: {placed:?}");
}
+240 -13
View File
@@ -15,19 +15,23 @@
//! press on the second segment is dropped. Escape, an edit or Undo outside the tool, another
//! document, or a change to the first segment that leaves no undo step (a live preview, or one that
//! was canceled) forgets the first segment. The circles are looked for again whenever either
//! segment's shape differs from the one they were found on.
//! segment's shape differs from the one they were found on. With the `addPoints` option on (Alt at
//! the release turns it the other way, and a dot beside the pointer shows when it is in effect), the
//! segments the circle touches get an anchor point at each touch, which splits them without changing
//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none.
//!
//! The tool's options (its options dialog, `tool.setOption`; kept with the preferences): `radius`;
//! `center` and `radii` show or hide the circle's center cross and the lines from its center to the
//! `addPoints`; `center` and `radii` show or hide the circle's center cross and the lines from its center to the
//! two points it touches; `color` is the color of the circle, the cross, those lines and the note
//! (one of [`COLORS`]); `snapTolerance` is how near (screen pixels) the pointer picks a segment
//! with Smart Guides on, where Smart Guides' Snapping Tolerance counts instead when it is larger,
//! or with Smart Guides off while `snapWithoutGuides` is on. Without snapping a segment is picked
//! within the selection tolerance, as a click on a path picks it, and that is also the least reach
//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default the
//! cross and the lines show, the color is red, the tolerance is 3 px and `snapWithoutGuides` is on.
//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default
//! `addPoints` is off, the cross and the lines show, the color is red, the tolerance is 3 px and
//! `snapWithoutGuides` is on.
use kurbo::{CubicBez, Shape};
use kurbo::{CubicBez, ParamCurveNearest, Shape};
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_geom::{BezPath, ParamCurve, Point};
@@ -52,6 +56,12 @@ pub const NO_CIRCLE: &str = "No tangent circle here";
const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff];
const RED: [u8; 3] = [0xe0, 0x3c, 0x3c];
const GREY: [u8; 3] = [0x80, 0x80, 0x80];
/// The label of the `addPoints` option in the tool's options.
pub const ADD_POINTS: &str = "Add Points to Existing Paths";
/// How far (screen pixels) right of and below the pointer the dot shows while `addPoints` is in
/// effect, and its size.
const DOT_PX: f64 = 10.0;
const DOT_SIZE: f32 = 4.0;
/// The colors the `color` option takes, by option value, with the color the circle, its center
/// cross, its radii and the note are drawn in. Red is the first.
pub const COLORS: &[(&str, [u8; 3])] = &[
@@ -67,7 +77,7 @@ pub const SNAP_PX: f64 = 3.0;
/// The snapping tolerance the `snapTolerance` option takes (screen pixels).
pub const SNAP_RANGE: (f64, f64) = (0.0, 25.0);
/// The option keys that are true or false.
const SWITCHES: &[&str] = &["center", "radii", "snapWithoutGuides"];
const SWITCHES: &[&str] = &["addPoints", "center", "radii", "snapWithoutGuides"];
/// A segment under the pointer: where on it, and the segment itself.
#[derive(Clone, Debug, PartialEq)]
@@ -101,6 +111,11 @@ struct Press {
pub struct TangentCircleTool {
radius: f64,
/// Whether drawing a circle adds anchor points where it touches the segments.
add_points: bool,
/// The keys held at the last pointer event, and whether the pointer is over the canvas.
mods: Mods,
over: bool,
/// Whether the preview shows the center cross and the radii.
center: bool,
radii: bool,
@@ -130,6 +145,9 @@ impl Default for TangentCircleTool {
fn default() -> Self {
Self {
radius: RADIUS,
add_points: false,
mods: Mods::default(),
over: false,
center: true,
radii: true,
color: 0,
@@ -189,6 +207,11 @@ fn unchanged(cx: &ToolContext, pick: &Pick) -> bool {
/// The segments a circle may touch when `second` is picked: it and the segments on either side of
/// it, without `first`. None when `second` is the first segment again.
fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<CubicBez> {
second_segments(cx, first, second).into_iter().map(|(_, c)| c).collect()
}
/// [`second_set`] with each segment's index on the second pick's subpath.
fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize, CubicBez)> {
if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) {
return vec![];
}
@@ -205,7 +228,36 @@ fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<CubicBez> {
indices.sort_unstable();
indices.dedup();
let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k;
indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| sp.segment(k)).collect()
indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| (k, sp.segment(k))).collect()
}
/// Where on `curve` the point `p` lies: its parameter, or none when `p` is within `tol` of either
/// end, where the segment already has an anchor point.
fn split_at(curve: &CubicBez, p: Point, tol: f64) -> Option<f64> {
if p.distance(curve.p0) <= tol || p.distance(curve.p3) <= tol {
return None;
}
let t = curve.nearest(p, 1e-12).t;
(t > 0.0 && t < 1.0).then_some(t)
}
/// The `path.insertAnchor` steps that add an anchor point where circle `c` touches the first segment
/// and the segment of `second` (the segments a circle may touch, with their indices, on the subpath
/// of `pick`) nearest its second touch. On one subpath the later segment comes first, so that the
/// anchor added before it does not move it along.
fn anchor_steps(first: &Pick, pick: &Pick, second: &[(usize, CubicBez)], c: &SegmentCircle, tol: f64) -> Vec<Value> {
let mut at: Vec<(NodeId, usize, usize, f64)> = vec![];
if let Some(t) = split_at(&first.curve, c.first, tol) {
at.push((first.id, first.subpath, first.segment, t));
}
let nearest = second.iter().min_by(|(_, a), (_, b)| a.nearest(c.second, 1e-12).distance_sq.total_cmp(&b.nearest(c.second, 1e-12).distance_sq));
if let Some((k, curve)) = nearest
&& let Some(t) = split_at(curve, c.second, tol)
{
at.push((pick.id, pick.subpath, *k, t));
}
at.sort_by_key(|a| std::cmp::Reverse((a.0, a.1, a.2)));
at.into_iter().map(|(id, subpath, segment, t)| json!({ "command": "path.insertAnchor", "params": { "id": id.0, "subpath": subpath, "segment": segment, "t": t } })).collect()
}
/// Of `circles`, the one touching the second segments nearest `at`, leaving out those [`draw`] cannot
@@ -242,6 +294,14 @@ fn round_step(least: f64) -> f64 {
/// distance from the origin, or too large, in floating point), or when the circle would reach past
/// the canvas ([`crate::circle::circle_of`]), which the command refuses.
fn draw(c: &SegmentCircle, tol: f64) -> Option<Action> {
circle_params(c, tol).map(|p| Action::Exec(CIRCLE.into(), p))
}
/// The command [`draw`] runs.
const CIRCLE: &str = "shape.circleThroughPoints";
/// The params of the [`CIRCLE`] command that [`draw`] runs.
fn circle_params(c: &SegmentCircle, tol: f64) -> Option<Value> {
let (at, r) = (c.circle.center, c.circle.radius);
let points: Vec<Point> = [90.0f64, 210.0, 330.0]
.iter()
@@ -255,7 +315,7 @@ fn draw(c: &SegmentCircle, tol: f64) -> Option<Action> {
return None;
}
let points: Vec<[f64; 2]> = points.iter().map(|p| [p.x, p.y]).collect();
Some(Action::Exec("shape.circleThroughPoints".into(), json!({ "points": points })))
Some(json!({ "points": points }))
}
fn segment_path(c: &CubicBez) -> BezPath {
@@ -391,6 +451,8 @@ impl Tool for TangentCircleTool {
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
self.pointer = ev.pos;
self.mods = ev.mods;
self.over = true;
match ev.kind {
PointerKind::Move => {
self.hover = pick_at(cx, ev.pos, self.reach(cx));
@@ -424,15 +486,34 @@ impl Tool for TangentCircleTool {
// The release's own position and keys set the radius of a drag.
self.drag_to(cx, ev);
self.picking = false;
if self.press.take().is_none() {
return vec![];
}
let Some(press) = self.press.take() else { return vec![] };
// No circle, or one the three points cannot draw: the first segment stays picked,
// for another try. It also stays when the command fails: only a drawn circle tells
// the tool (`notify`) to forget it.
let Some(action) = self.found.take().and_then(|c| draw(&c, cx.tol(DRAW_PX))) else { return vec![] };
let Some(c) = self.found.take() else { return vec![] };
let Some(params) = circle_params(&c, cx.tol(DRAW_PX)) else { return vec![] };
self.looked = false;
vec![action, Action::Notify(DRAWN.into())]
// Alt at the release turns `addPoints` the other way.
let steps = match &self.first {
Some(first) if self.add_points != ev.mods.alt => {
let second = if segment_now(cx, &press.pick).is_some() { second_segments(cx, first, &press.pick) } else { vec![] };
anchor_steps(first, &press.pick, &second, &c, cx.tol(DRAW_PX))
}
_ => vec![],
};
if steps.is_empty() {
return vec![Action::Exec(CIRCLE.into(), params), Action::Notify(DRAWN.into())];
}
let mut commands = steps;
// A path that was not selected becomes the selection when it gets an anchor; the
// selection is put back before the circle, which Draw Behind places behind it.
if commands.iter().any(|s| s["params"]["id"].as_u64().is_some_and(|id| !cx.selection.contains(NodeId(id)))) {
let ids: Vec<u64> = cx.selection.objects.iter().map(|id| id.0).collect();
commands.push(json!({ "command": "select.set", "params": { "ids": ids } }));
}
commands.push(json!({ "command": CIRCLE, "params": params }));
// One undo step for the anchors and the circle, and none of them when a step fails.
vec![Action::Exec("command.batch".into(), json!({ "label": "Ellipse", "commands": commands })), Action::Notify(DRAWN.into())]
}
// The canvas sends a double-click after the second click's `Up`, which drew the circle.
PointerKind::DoubleClick | PointerKind::TripleClick => vec![],
@@ -483,6 +564,7 @@ impl Tool for TangentCircleTool {
fn hover_ended(&mut self, _cx: &ToolContext) {
self.hover = None;
self.over = false;
if self.press.is_none() {
self.found = None;
self.looked = false;
@@ -525,6 +607,11 @@ impl Tool for TangentCircleTool {
// A label, which the canvas shows in the interface language.
out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color });
}
// `addPoints` in effect, with Alt as it is now.
if (self.over || self.press.is_some()) && self.add_points != self.mods.alt {
let off = cx.tol(DOT_PX);
out.push(Overlay::CurvePoint { p: self.pointer + kurbo::Vec2::new(off, off), color: BLUE, filled: true, size: DOT_SIZE });
}
out
}
@@ -535,6 +622,7 @@ impl Tool for TangentCircleTool {
fn options(&self) -> Value {
json!({
"radius": self.radius,
"addPoints": self.add_points,
"center": self.center,
"radii": self.radii,
"color": COLORS.get(self.color).map_or("red", |(name, _)| *name),
@@ -550,6 +638,7 @@ impl Tool for TangentCircleTool {
}
match key {
"radius" => self.radius = v.as_f64().unwrap_or(self.radius),
"addPoints" => self.add_points = v.as_bool().unwrap_or(self.add_points),
"center" => self.center = v.as_bool().unwrap_or(self.center),
"radii" => self.radii = v.as_bool().unwrap_or(self.radii),
"color" => self.color = v.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)).unwrap_or(self.color),
@@ -1059,6 +1148,144 @@ mod tests {
assert!(matches!(segments[..], [n] if n < 100), "{segments:?}");
}
/// The steps of the `command.batch` an action list runs: (command, params) each.
fn batch_steps(actions: &[Action]) -> Vec<(String, Value)> {
let [Action::Exec(cmd, p), Action::Notify(what)] = actions else { panic!("{actions:?}") };
assert_eq!((cmd.as_str(), what.as_str()), ("command.batch", DRAWN));
p["commands"].as_array().unwrap().iter().map(|s| (s["command"].as_str().unwrap().to_string(), s["params"].clone())).collect()
}
/// An inserted anchor's place: (path, subpath, segment) and the point at its `t` on that segment.
fn inserted(cx: &ToolContext, params: &Value) -> (u64, u64, u64, Point) {
let (id, sub, seg) = (params["id"].as_u64().unwrap(), params["subpath"].as_u64().unwrap(), params["segment"].as_u64().unwrap());
let sp = &cx.doc.node(NodeId(id)).unwrap().path_data().unwrap().subpaths[sub as usize];
(id, sub, seg, sp.segment(seg as usize).eval(params["t"].as_f64().unwrap()))
}
fn alt(mut e: PointerEvent) -> PointerEvent {
e.mods.alt = true;
e
}
#[test]
fn add_points_adds_an_anchor_where_the_circle_touches_each_segment() {
let d = doc();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let line_at = |y: f64| pick_at(&cx, Point::new(150.0, y), cx.pick_tol()).map(|p| p.id.0).unwrap();
let (top, below) = (line_at(100.0), line_at(140.0));
let mut t = TangentCircleTool::default();
t.set_option("addPoints", &json!(true));
assert_eq!(t.options()["addPoints"], json!(true));
// The circle through (150, 100) touching the line below at (150, 140): an anchor a quarter
// along each line, then the circle, in one batch.
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0));
let steps = batch_steps(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0)));
assert_eq!(steps.len(), 4, "{steps:?}");
assert!(steps[..2].iter().all(|(c, _)| c == "path.insertAnchor"), "{steps:?}");
let mut anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect();
anchors.sort_by_key(|a| a.0);
let mut want = [(top, 0, 0, Point::new(150.0, 100.0)), (below, 0, 0, Point::new(150.0, 140.0))];
want.sort_by_key(|a| a.0);
assert!(top != below && anchors.iter().zip(want).all(|(a, b)| (a.0, a.1, a.2) == (b.0, b.1, b.2) && a.3.distance(b.3) < 1e-6), "{anchors:?}");
// The lines were not selected, so the selection (none) is put back before the circle.
assert_eq!(steps[2], ("select.set".to_string(), json!({ "ids": [] })), "{steps:?}");
let (cmd, params) = &steps[3];
let circle = drawn(&[Action::Exec(cmd.clone(), params.clone()), Action::Notify(DRAWN.into())]);
assert!(close(circle, (130.0, 100.0, 40.0, 40.0)), "{steps:?}");
assert!(t.first.is_none(), "ready for the next circle");
// With both lines selected, the anchors leave the selection as it is: no step puts it back.
let mut both = Selection::default();
both.add(NodeId(top));
both.add(NodeId(below));
let selected = self::cx(&d, &both, &p);
t.pointer(&selected, &ev(PointerKind::Down, 150.0, 101.0));
t.pointer(&selected, &ev(PointerKind::Up, 150.0, 101.0));
t.pointer(&selected, &ev(PointerKind::Down, 200.0, 139.0));
let steps = batch_steps(&up(&mut t, &selected, &ev(PointerKind::Up, 200.0, 139.0)));
assert!(steps.len() == 3 && steps[2].0 == CIRCLE, "{steps:?}");
// Alt at the release turns it off for that circle, and with the option off turns it on.
for (on, alt_up, adds) in [(true, true, false), (false, true, true), (false, false, false)] {
t.set_option("addPoints", &json!(on));
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0));
t.pointer(&cx, &alt(ev(PointerKind::Drag, 200.0, 139.0)));
let release = if alt_up { alt(ev(PointerKind::Up, 200.0, 139.0)) } else { ev(PointerKind::Up, 200.0, 139.0) };
let released = up(&mut t, &cx, &release);
if adds {
assert_eq!(batch_steps(&released).len(), 4, "on {on}, Alt {alt_up}: {released:?}");
} else {
assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "on {on}, Alt {alt_up}: {released:?}");
}
}
}
#[test]
fn add_points_on_one_path_adds_the_later_anchor_first_and_none_at_an_anchor() {
let d = doc();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = TangentCircleTool::default();
t.set_option("addPoints", &json!(true));
t.set_option("radius", &json!(10));
// The L's corner circle of radius 10 touches (290, 300) on its first segment and (300, 310)
// on its second: the second segment's anchor comes first, so the first one's index holds.
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0));
t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0));
let steps = batch_steps(&up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0)));
assert_eq!(steps.len(), 4, "{steps:?}");
let l = pick_at(&cx, Point::new(300.0, 350.0), cx.pick_tol()).map(|p| p.id.0);
let anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect();
let want = [(1, Point::new(300.0, 310.0)), (0, Point::new(290.0, 300.0))];
assert!(anchors.iter().zip(want).all(|(a, (seg, at))| Some(a.0) == l && a.1 == 0 && a.2 == seg && a.3.distance(at) < 1e-6), "{anchors:?}");
assert_eq!((steps[2].0.as_str(), steps[3].0.as_str()), ("select.set", CIRCLE));
// A circle touching both lines at their right ends: no anchor is added on top of an anchor,
// so only the circle is drawn, as without the option.
t.set_option("radius", &json!(36));
t.pointer(&cx, &ev(PointerKind::Down, 300.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Up, 300.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Down, 299.0, 139.0));
let released = up(&mut t, &cx, &ev(PointerKind::Up, 299.0, 139.0));
assert!(close(drawn(&released), (280.0, 100.0, 40.0, 40.0)), "{released:?}");
}
#[test]
fn add_points_shows_a_dot_and_is_an_option_that_refuses_other_values() {
let d = doc();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = TangentCircleTool::default();
assert_eq!(t.options()["addPoints"], json!(false), "off to start");
let dot =
|t: &TangentCircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::CurvePoint { filled: true, color, .. } if *color == BLUE));
t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0));
assert!(!dot(&t));
// Alt turns it on while held, and back off with the option on.
t.pointer(&cx, &alt(ev(PointerKind::Move, 50.0, 50.0)));
assert!(dot(&t));
t.set_option("addPoints", &json!(true));
assert!(!dot(&t));
t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0));
assert!(dot(&t));
let Some(Overlay::CurvePoint { p, .. }) = t.overlays(&cx).into_iter().find(|o| matches!(o, Overlay::CurvePoint { .. })) else {
panic!("no dot")
};
assert!(p.x > 50.0 && p.y > 50.0, "beside the pointer: {p:?}");
// The pointer off the canvas: no dot left behind.
t.hover_ended(&cx);
assert!(!dot(&t));
for bad in [json!(1), json!("true"), Value::Null] {
assert_eq!(t.check_option("addPoints", &bad), Err("`addPoints` must be true or false".into()), "{bad}");
t.set_option("addPoints", &bad);
assert_eq!(t.options()["addPoints"], json!(true), "{bad}");
}
assert_eq!(t.check_option("addPoints", &json!(false)), Ok(()));
}
#[test]
fn a_circle_that_would_reach_past_the_canvas_is_not_offered() {
// Two lines 40 pt apart ending at the canvas edge, x = 4,000,000: a click at x the first gives
+128 -23
View File
@@ -14,21 +14,35 @@
//! nothing. The pointer passes over the circles the tool drew until the selection holds none of
//! them, another tool is chosen, another document becomes active, or an edit, Undo or Redo is
//! made outside the tool.
//!
//! The tool's options (Curvature Circle Tool Options, `tool.setOption`; kept with the
//! preferences): `snapTolerance` is the 5 screen points above (VectorCraft's own range of 1 to 40);
//! `snapWithoutGuides` off makes the pointer reach no further than Selection & Anchor Display ›
//! Tolerance while Smart Guides are off (when that tolerance is as large as the reach, the reach
//! stays the same); `annotateRadius` off hides the radius label;
//! `standardAnchors` off draws the circle with an anchor where it touches the path and one every
//! 90° from there (`anchors: "touch"`) instead of at 0°, 90°, 180° and 270°; `constantRadius` off
//! gives the cubic's own curvature on the cubic of a circular arc too, with no asterisk. Every
//! switch is on by default.
use std::collections::HashSet;
use serde_json::json;
use serde_json::{Value, json};
use vectorcraft_doc::{MAX_COORD, NodeId};
use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on};
use vectorcraft_geom::{Point, Rect, Vec2, shapes};
use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on_with};
use vectorcraft_geom::{PathData, Point, Rect, Vec2, shapes};
use crate::option_check;
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
pub const ID: &str = "curvatureCircle";
/// How near (screen points) a path pulls the pointer, unless the Smart Guides' snapping tolerance
/// is larger.
const SNAP_PX: f64 = 5.0;
/// The range of `snapTolerance` (screen points).
pub const SNAP_RANGE: (f64, f64) = (1.0, 40.0);
/// `snapTolerance` by default (screen points).
pub const DEFAULT_SNAP: f64 = 5.0;
/// The option keys that are true or false.
const SWITCHES: &[&str] = &["snapWithoutGuides", "annotateRadius", "standardAnchors", "constantRadius"];
/// How far (screen points) the pointer travels from a press before the press counts as a drag.
const DRAG_PX: f64 = 2.0;
/// Half the length (screen points) of each arm of the cross at the circle's center.
@@ -52,8 +66,37 @@ enum Found {
Refused(&'static str, Point),
}
/// The tool's options (see the module comment).
#[derive(Clone, Copy, Debug, PartialEq)]
struct Options {
snap_tolerance: f64,
snap_without_guides: bool,
annotate_radius: bool,
standard_anchors: bool,
constant_radius: bool,
}
impl Default for Options {
fn default() -> Self {
Options { snap_tolerance: DEFAULT_SNAP, snap_without_guides: true, annotate_radius: true, standard_anchors: true, constant_radius: true }
}
}
impl Options {
fn switch(&mut self, key: &str) -> Option<&mut bool> {
Some(match key {
"snapWithoutGuides" => &mut self.snap_without_guides,
"annotateRadius" => &mut self.annotate_radius,
"standardAnchors" => &mut self.standard_anchors,
"constantRadius" => &mut self.constant_radius,
_ => return None,
})
}
}
#[derive(Default)]
pub struct CurvatureCircleTool {
options: Options,
/// The point under the pointer, and whether Shift was held.
hover: Option<(Hit, bool)>,
/// The press in progress, where the pointer was pressed: what a release draws.
@@ -64,6 +107,17 @@ pub struct CurvatureCircleTool {
drawn: HashSet<NodeId>,
}
/// How near (document units) a path pulls the pointer: `snapTolerance`, or Smart Guides ›
/// Snapping Tolerance when that is larger; with Smart Guides off and `snapWithoutGuides` off, no
/// further than Selection & Anchor Display › Tolerance.
fn reach(cx: &ToolContext, o: &Options) -> f64 {
let snap = cx.tol(o.snap_tolerance).max(cx.snap_tol());
if !cx.smart_guides && !o.snap_without_guides {
return snap.min(cx.pick_tol());
}
snap
}
impl CurvatureCircleTool {
/// After Deselect or a selection made outside the tool, the selection holds none of the
/// circles the tool drew, and the pointer reaches them again.
@@ -77,10 +131,9 @@ impl CurvatureCircleTool {
}
}
/// The nearest point within reach of `p` on the paths a click can pick, guides and the paths in
/// The nearest point within `tol` of `p` on the paths a click can pick, guides and the paths in
/// `skip` left out; of paths at the same distance, a selected one, then the one on top.
fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet<NodeId>) -> Option<Hit> {
let tol = cx.tol(SNAP_PX).max(cx.snap_tol());
fn hit_at(cx: &ToolContext, p: Point, tol: f64, skip: &HashSet<NodeId>) -> Option<Hit> {
let mut best: Option<(Hit, f64)> = None;
for id in crate::draw2::candidate_paths(cx) {
if skip.contains(&id) {
@@ -103,14 +156,14 @@ fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet<NodeId>) -> Option<Hit> {
/// The circle at `hit` as `shape.curvatureCircle` draws it, or why it draws none; `None` when the
/// path or segment is gone.
fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option<Found> {
fn found(cx: &ToolContext, hit: Hit, convex: bool, o: &Options) -> Option<Found> {
let sp = cx.doc.node(hit.id)?.path_data()?.subpaths.get(hit.subpath)?;
if hit.segment >= sp.segment_count() {
return None;
}
let at = vectorcraft_geom::ParamCurve::eval(&sp.segment(hit.segment), hit.t);
Some(match curvature_circle_on(sp, hit.segment, hit.t, convex) {
Ok(c) if on_canvas(&c) => Found::Circle(c),
Some(match curvature_circle_on_with(sp, hit.segment, hit.t, convex, o.constant_radius) {
Ok(c) if on_canvas(&c, o) => Found::Circle(c),
Ok(_) => Found::Refused("Circle too large", at),
Err(NoCircle::Straight) => Found::Refused("Straight segment", at),
Err(NoCircle::Cusp) => Found::Refused("Cusp", at),
@@ -118,10 +171,19 @@ fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option<Found> {
})
}
/// Does the circle stay on the canvas?
fn on_canvas(c: &CurvatureCircle) -> bool {
/// The path `shape.curvatureCircle` draws for `c`: with `standardAnchors`, the circle with anchors
/// at 0°, 90°, 180° and 270°; without, the circle with an anchor where it touches the path.
fn drawn_path(c: &CurvatureCircle, o: &Options) -> PathData {
let (p, r) = (c.center, c.radius);
[p.x - r, p.y - r, p.x + r, p.y + r].iter().all(|v| v.abs() <= MAX_COORD)
if !o.standard_anchors {
return shapes::circle_with_anchors_at(p, r, &[c.at]);
}
shapes::ellipse(Rect::new(p.x - r, p.y - r, p.x + r, p.y + r))
}
/// Does the circle stay on the canvas, as `shape.curvatureCircle` checks it?
fn on_canvas(c: &CurvatureCircle, o: &Options) -> bool {
drawn_path(c, o).bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD))
}
impl Tool for CurvatureCircleTool {
@@ -134,13 +196,14 @@ impl Tool for CurvatureCircleTool {
return vec![];
}
self.forget_unselected(cx);
let (o, tol) = (self.options, reach(cx, &self.options));
match ev.kind {
PointerKind::Move => {
self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift));
self.hover = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift));
vec![]
}
PointerKind::Down => {
self.press = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift));
self.press = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift));
self.hover = self.press;
self.from = ev.pos;
vec![]
@@ -155,12 +218,21 @@ impl Tool for CurvatureCircleTool {
}
PointerKind::Up => {
let press = self.press.take();
self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift));
self.hover = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift));
let Some((hit, convex)) = press else { return vec![] };
if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex), Some(Found::Circle(_))) {
if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex, &o), Some(Found::Circle(_))) {
return vec![];
}
let p = json!({"id": hit.id.0, "subpath": hit.subpath, "segment": hit.segment, "t": hit.t, "convex": convex});
let anchors = if o.standard_anchors { "standard" } else { "touch" };
let p = json!({
"id": hit.id.0,
"subpath": hit.subpath,
"segment": hit.segment,
"t": hit.t,
"convex": convex,
"constantRadius": o.constant_radius,
"anchors": anchors,
});
vec![Action::Exec("shape.curvatureCircle".into(), p), Action::Notify("created".into())]
}
PointerKind::DoubleClick | PointerKind::TripleClick => vec![],
@@ -236,10 +308,10 @@ impl Tool for CurvatureCircleTool {
let Some((hit, convex)) = self.hover else { return vec![] };
let color = crate::draw2::FEEDBACK;
let mut o = vec![];
match found(cx, hit, convex) {
match found(cx, hit, convex, &self.options) {
Some(Found::Circle(c)) => {
let r = c.radius;
let path = shapes::ellipse(Rect::new(c.center.x - r, c.center.y - r, c.center.x + r, c.center.y + r)).to_bezpath();
let path = drawn_path(&c, &self.options).to_bezpath();
// The outline is drawn solid when it is longer than DASHED_PX on screen.
let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX);
o.push(Overlay::Path { path, color, width: 1.0, dashed });
@@ -248,7 +320,7 @@ impl Tool for CurvatureCircleTool {
o.push(Overlay::Line { a: c.center - Vec2::new(arm, 0.0), b: c.center + Vec2::new(arm, 0.0), color, dashed: false });
o.push(Overlay::Line { a: c.center - Vec2::new(0.0, arm), b: c.center + Vec2::new(0.0, arm), color, dashed: false });
o.push(Overlay::Anchor { p: c.at, color, filled: true, size: 6.0 });
if cx.measurement_labels {
if cx.measurement_labels && self.options.annotate_radius {
let star = if c.nominal { "*" } else { "" };
o.push(Overlay::Measure { p: c.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("R: {}{star}", cx.len(r)) });
}
@@ -262,6 +334,39 @@ impl Tool for CurvatureCircleTool {
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
Cursor::Crosshair
}
fn options(&self) -> Value {
let o = self.options;
json!({
"snapTolerance": o.snap_tolerance,
"snapWithoutGuides": o.snap_without_guides,
"annotateRadius": o.annotate_radius,
"standardAnchors": o.standard_anchors,
"constantRadius": o.constant_radius,
})
}
/// `snapTolerance` takes a number in [`SNAP_RANGE`], and the switches true or false.
fn check_option(&self, key: &str, value: &Value) -> Result<(), String> {
if key == "snapTolerance" {
option_check::number(key, value, SNAP_RANGE.0, SNAP_RANGE.1)
} else if SWITCHES.contains(&key) {
option_check::boolean(key, value)
} else {
Err(option_check::unknown(key))
}
}
/// Sets one option; a value the option does not take leaves it as it was.
fn set_option(&mut self, key: &str, value: &Value) {
if key == "snapTolerance" {
if let Some(v) = value.as_f64().filter(|v| (SNAP_RANGE.0..=SNAP_RANGE.1).contains(v)) {
self.options.snap_tolerance = v;
}
} else if let (Some(switch), Some(on)) = (self.options.switch(key), value.as_bool()) {
*switch = on;
}
}
}
#[cfg(test)]
@@ -305,3 +305,98 @@ fn the_curvature_circle_tool_follows_the_circle_tool() {
let circle = ids.iter().position(|id| *id == crate::circle::ID).unwrap();
assert_eq!(ids.get(circle + 1), Some(&ID));
}
/// `snapTolerance` sets how far the pointer reaches, and with `snapWithoutGuides` off and Smart
/// Guides off the pointer reaches no further than the selection tolerance, and never further than
/// with the switch on; with Smart Guides on it reaches as far as before.
#[test]
fn the_snap_options_set_how_far_the_pointer_reaches() {
let d = doc_with(&[circle()]);
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, snapping_tolerance: 0.0, selection_tolerance: 2.0, ..cx(&d, &s, &p) };
let mut t = CurvatureCircleTool::default();
assert_eq!(click(&mut t, &cx, (308.0, 200.0), Mods::default()), vec![]);
t.set_option("snapTolerance", &json!(10));
assert_eq!(click(&mut t, &cx, (308.0, 200.0), Mods::default()).len(), 2);
t.set_option("snapTolerance", &json!(5));
t.set_option("snapWithoutGuides", &json!(false));
assert_eq!(click(&mut t, &cx, (304.0, 200.0), Mods::default()), vec![]);
assert_eq!(click(&mut t, &cx, (301.0, 200.0), Mods::default()).len(), 2);
let guides = ToolContext { smart_guides: true, ..cx };
assert_eq!(click(&mut t, &guides, (304.0, 200.0), Mods::default()).len(), 2);
let wide = ToolContext { selection_tolerance: 8.0, ..cx };
assert_eq!(click(&mut t, &wide, (304.0, 200.0), Mods::default()).len(), 2);
assert_eq!(click(&mut t, &wide, (307.0, 200.0), Mods::default()), vec![]);
}
/// `annotateRadius` off hides the radius label; `constantRadius` off shows the cubic's own radius
/// without the asterisk and sends `constantRadius: false`; `standardAnchors` off sends
/// `anchors: "touch"`.
#[test]
fn the_label_and_circle_options_change_what_is_shown_and_drawn() {
let d = doc_with(&[circle()]);
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let measure = |t: &CurvatureCircleTool| {
t.overlays(&cx).iter().find_map(|o| match o {
Overlay::Measure { text, .. } => Some(text.clone()),
_ => None,
})
};
let mut t = CurvatureCircleTool::default();
let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default()));
assert_eq!((&v["constantRadius"], &v["anchors"]), (&json!(true), &json!("standard")));
t.pointer(&cx, &ev(PointerKind::Move, (300.0, 200.0), Mods::default()));
assert!(measure(&t).is_some_and(|m| m.ends_with('*')));
t.set_option("annotateRadius", &json!(false));
assert_eq!(measure(&t), None);
t.set_option("annotateRadius", &json!(true));
let arc = preview(&t.overlays(&cx)).unwrap();
t.set_option("constantRadius", &json!(false));
assert!(measure(&t).is_some_and(|m| !m.ends_with('*')), "{:?}", measure(&t));
assert!(preview(&t.overlays(&cx)).unwrap().width() > arc.width());
t.set_option("standardAnchors", &json!(false));
let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default()));
assert_eq!((&v["constantRadius"], &v["anchors"]), (&json!(false), &json!("touch")));
}
/// The preview's outline is the path the click draws: starting at 0° whatever the Constrain Angle,
/// or with `standardAnchors` off starting where the circle touches the path.
#[test]
fn the_preview_follows_the_anchor_options() {
let d = doc_with(&[circle()]);
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let start = |t: &CurvatureCircleTool, cx: &ToolContext| {
t.overlays(cx).iter().find_map(|o| match o {
Overlay::Path { path, .. } => path.elements().first().and_then(|e| e.end_point()),
_ => None,
})
};
let mut t = CurvatureCircleTool::default();
t.pointer(&cx, &ev(PointerKind::Move, (200.0, 98.0), Mods::default()));
let upright = start(&t, &cx).unwrap();
let turned = ToolContext { constrain_angle: 30.0, ..cx };
assert_eq!(start(&t, &turned), Some(upright));
assert!(upright.distance(Point::new(200.0, 100.0)) > 1.0, "{upright:?}");
t.set_option("standardAnchors", &json!(false));
let at = start(&t, &cx).unwrap();
assert!(at.distance(Point::new(200.0, 100.0)) < 1e-6, "{at:?}");
}
/// An option the tool lacks, a tolerance out of range and a switch that is not true or false are
/// errors, and `set_option` leaves the option as it was for them.
#[test]
fn invalid_options_are_refused() {
let mut t = CurvatureCircleTool::default();
assert!(t.check_option("snapTolerance", &json!(0)).is_err());
assert!(t.check_option("snapTolerance", &json!(41)).is_err());
assert!(t.check_option("snapTolerance", &json!("5")).is_err());
assert!(t.check_option("annotateRadius", &json!(1)).is_err());
assert!(t.check_option("size", &json!(1)).is_err());
assert!(t.check_option("snapTolerance", &json!(12.5)).is_ok());
let before = t.options();
t.set_option("snapTolerance", &json!(0));
t.set_option("annotateRadius", &json!("no"));
assert_eq!(t.options(), before);
}
+5
View File
@@ -1882,6 +1882,11 @@ impl Tool for GestureTool {
fn wants_samples(&self) -> bool {
matches!(self.id, "pencil" | "paintbrush" | "blobBrush" | "eraser" | "knife" | "smooth" | "pathEraser")
}
/// The Blob Brush's and the Eraser's tip varies with the wheel when a value is on Stylus Wheel
/// with a Variation above 0.
fn reads_wheel(&self, _cx: &ToolContext) -> bool {
self.tip_modes().contains(&Variation::StylusWheel)
}
/// The outline of a long Blob Brush or Eraser drag, and a smoothing drag's band outlined again
/// after a zoom change, reach the whole drag over several frames.
fn overlays_pending(&self) -> bool {
+23
View File
@@ -4129,3 +4129,26 @@ fn pencil_alt_toggles_to_smooth_when_enabled_and_closes_when_disabled() {
assert!(matches!(&last[0], Action::Preview(_, v) if v["closed"] == true && v["style"] == "pencil"));
assert_eq!(last[1], Action::Commit);
}
#[test]
fn a_tip_reads_the_wheel_only_with_a_value_on_stylus_wheel() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
for id in ["pencil", "paintbrush", "blobBrush", "eraser"] {
assert!(!GestureTool::new(id).reads_wheel(&cx), "{id} at its defaults");
}
for value in ["angle", "roundness", "size"] {
let mut t = GestureTool::new("eraser");
t.set_option(&format!("{value}Mode"), &json!("stylusWheel"));
assert!(!t.reads_wheel(&cx), "{value} on Stylus Wheel with no Variation");
t.set_option(&format!("{value}Variation"), &json!(4));
assert!(t.reads_wheel(&cx), "{value} on Stylus Wheel");
t.set_option(&format!("{value}Mode"), &json!("pressure"));
assert!(!t.reads_wheel(&cx), "{value} on Pressure");
}
let mut t = GestureTool::new("blobBrush");
t.set_option("sizeMode", &json!("stylusWheel"));
t.set_option("sizeVariation", &json!(4));
assert!(t.reads_wheel(&cx), "the Blob Brush's size on Stylus Wheel");
}
+6
View File
@@ -319,6 +319,12 @@ pub trait Tool: Send {
fn wants_samples(&self) -> bool {
false
}
/// Does a stroke the tool draws now vary with an airbrush pen's finger wheel (a brush or tip
/// with Stylus Wheel variation)? A host that has to open a tablet interface of its own to read
/// the wheel opens it only while this is so.
fn reads_wheel(&self, _cx: &ToolContext) -> bool {
false
}
/// Is the tool waiting for work it runs on another thread (the planar map of a large selection
/// for the Shape Builder and the Live Paint Bucket, a Shape Builder merge of one)? It
/// highlights nothing under the pointer until a map is done. While this holds, the desktop app
+3 -1
View File
@@ -80,6 +80,8 @@ const ROWS: &[Row] = &[
(&["ellipse"], None, &["anchors"]),
// Circle Tool Options (`circle::CircleTool`) and the Control bar's From Center.
(&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird", "fromCenter"]),
// Curvature Circle Tool Options (`curvature_circle::CurvatureCircleTool`).
(&[crate::curvature_circle::ID], None, &["snapTolerance", "snapWithoutGuides", "annotateRadius", "standardAnchors", "constantRadius"]),
(&["freeTransform"], None, &["constrain"]),
// Shape Builder Tool Options (`builder::ShapeBuilderOptions`).
(
@@ -108,7 +110,7 @@ const ROWS: &[Row] = &[
(&[crate::addons::extend_path::ID], None, &["mode"]),
(&[crate::addons::corner_tool::ID], None, &["radius", "kind"]),
(&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]),
(&[crate::addons::tangent_circle::ID], None, &["radius", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]),
(&[crate::addons::tangent_circle::ID], None, &["radius", "addPoints", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]),
(&[crate::addons::smart_pen::ID], None, &["next"]),
// The kind first: a new kind resets the values after it.
(&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]),
+62
View File
@@ -438,6 +438,20 @@ impl Tool for BrushPaintTool {
fn wants_samples(&self) -> bool {
self.inner.wants_samples()
}
/// The brush it paints with varies with the wheel: a Calligraphic brush with a value on Stylus
/// Wheel and a variation other than 0, a Scatter brush with a value on it whose two values
/// differ, or an Art brush whose width is on it with two different widths.
fn reads_wheel(&self, cx: &ToolContext) -> bool {
use vectorcraft_brush::{BrushKind, Variation};
let wheel = |mode: Variation| mode == Variation::StylusWheel;
let Some(brush) = self.brush_name(cx).and_then(|n| vectorcraft_brush::find(cx.doc, &n)) else { return false };
match brush.kind {
BrushKind::Calligraphic(c) => c.modes().into_iter().zip(c.variation).any(|(m, v)| wheel(m) && v != 0.0),
BrushKind::Scatter(s) => s.modes().into_iter().zip(s.values()).any(|(m, (a, b))| wheel(m) && a != b),
BrushKind::Art(a) => a.width_mode.is_some_and(wheel) && a.width_range().0 != a.width_range().1,
BrushKind::Pattern(_) | BrushKind::Bristle(_) => false,
}
}
fn busy(&self) -> bool {
self.inner.busy()
}
@@ -758,4 +772,52 @@ mod tests {
let a = drag(&d, &mut BrushPaintTool::default());
assert!(matches!(&a, Action::Preview(c, v) if c == "path.freehand" && v.get("brush").is_none()), "no brush: {a:?}");
}
#[test]
fn the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush() {
use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, Scatter, Variation};
let wheel = Variation::StylusWheel;
let calligraphic =
|modes, size| BrushKind::Calligraphic(Calligraphic { variation: [0.0, 0.0, size], modes: Some(modes), ..Calligraphic::default() });
let scatter = |size| {
BrushKind::Scatter(Scatter { size, modes: Some([wheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), ..Scatter::default() })
};
let art = |width_mode, width_max| BrushKind::Art(ArtBrush { width_mode, width_max: Some(width_max), ..ArtBrush::default() });
let library = [
Brush { name: "Plain".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, Variation::Pressure], 2.0) },
Brush { name: "Nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 2.0) },
Brush { name: "Still nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 0.0) },
Brush { name: "Dots".into(), kind: scatter((50.0, 150.0)) },
Brush { name: "Even dots".into(), kind: scatter((100.0, 100.0)) },
Brush { name: "Taper".into(), kind: art(Some(wheel), 200.0) },
Brush { name: "Even taper".into(), kind: art(Some(wheel), 100.0) },
Brush { name: "Flat".into(), kind: art(None, 200.0) },
];
let (mut d, _) = doc_with_rect();
d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), serde_json::to_value(library).unwrap());
let (s, p) = (Selection::default(), paint());
let reads = |d: &vectorcraft_doc::Document, t: &BrushPaintTool| t.reads_wheel(&cx(d, &s, &p));
let mut t = BrushPaintTool::default();
assert!(!reads(&d, &t), "no brush");
let brushes = [
("Plain", false),
("Nib", true),
("Still nib", false),
("Dots", true),
("Even dots", false),
("Taper", true),
("Even taper", false),
("Flat", false),
("Deleted", false),
];
for (name, varies) in brushes {
d.unknown.insert(vectorcraft_brush::CURRENT_KEY.into(), json!(name));
assert_eq!(reads(&d, &t), varies, "the current brush {name}");
}
t.set_option("brush", &json!("Plain"));
assert!(!reads(&d, &t), "the tool's own brush comes first");
t.set_option("brush", &json!("Nib"));
d.unknown.remove(vectorcraft_brush::CURRENT_KEY);
assert!(reads(&d, &t), "and reads the wheel");
}
}
+2 -2
View File
@@ -99,8 +99,8 @@ fn pump_commit(app: &mut VectorcraftApp) {
let live = host.with(|h| h.get_mut_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), (spec.params)(d.fields()))));
if let Some((previewing, params)) = &live {
let mut preview = mem::take(&mut app.addon_dialogs.preview);
// PLAN: the undo step's label is the command id; `Spec` carries no heading (wg.A20 takes a label)
let answer = preview.run(app, *previewing, spec.command, spec.command, params);
let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label);
let answer = preview.run(app, *previewing, label, spec.command, params);
app.addon_dialogs.preview = preview;
if let (Some(found), Some(answer)) = (spec.found, answer) {
host.with(|h| {
@@ -247,6 +247,25 @@ fn add_on_dialogs_preview_cancel_and_run_their_command() {
}
}
#[test]
fn keeping_an_add_on_preview_records_the_command_name() {
let mut app = two_rects();
let undo = undo_len(&app);
open_item(&mut app, "Arrange Tools", "Arrange in Grid…");
let id = dialog_id(&app);
set(&app, id, "layout", json!("row"));
set(&app, id, "preview", json!(true));
frame(&mut app);
assert_eq!(x0(&app, 1), 30.0, "previewed");
assert_eq!(undo_len(&app), undo, "the preview is still temporary");
assert!(confirm(&app, id));
frame(&mut app);
let history = &app.session.doc().unwrap().history;
assert_eq!(history.undo.len(), undo + 1);
assert_eq!(history.undo.last().unwrap().label, "Arrange in Grid");
}
#[test]
fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview() {
let mut app = two_rects();
+111 -15
View File
@@ -1,12 +1,14 @@
//! Packaging Tools' submenu (Object › Plug-ins › Packaging Tools) and its Fold Lines panel. The
//! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects
//! have it (of the whole document while nothing is selected); clicking a role gives the selected
//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that
//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu
//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it
//! (clicking one selects its objects); each document's list is kept until that document changes. Its
//! Fold Preview button, like the Fold Preview menu item, shows the blank folded in 3D ([`preview`],
//! `ui.foldPreview`).
//! paths that role (`addon.packaging.setRole`). While the selection holds lines that fold, its Fold
//! Angle field shows the angle they fold at and sets it (`addon.packaging.setFoldAngle`, as Set Fold
//! Angle… in the submenu does), and Reset takes their own angles away. Its menu's Role Swatches…
//! picks the swatch that carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the
//! Check Fold Lines menu item, checks the fold lines (`addon.packaging.check`) and lists the issues
//! found under it (clicking one selects its objects); each document's list is kept until that
//! document changes. Its Fold Preview button, like the Fold Preview menu item, shows the blank folded
//! in 3D ([`preview`], `ui.foldPreview`).
use std::collections::HashMap;
use std::sync::{Arc, Weak};
@@ -14,11 +16,17 @@ use std::sync::{Arc, Weak};
use craft::keymap::CommandRef;
use craft::menu::Node;
use craft::ui::buttons::Button;
use craft::ui::contract::{ActivateOn, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, WordSetCx as _};
use craft::ui::contract::{
ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, WordSetCx as _, clicked,
};
use craft::ui::display::{Divider, Text};
use craft::ui::form::Field;
use craft::ui::layout_components::Row as Line;
use craft::ui::list::{Finding, Findings, FindingsList, FindingsWords, List, ListRow, Severity, ThumbSize};
use craft::ui::menu::PanelRow;
use craft::ui::runtime::commands::{CommandState, CommandStates};
use craft::ui::runtime::env::UnitKind;
use craft::ui::text::NumberField;
use egui::Ui;
use serde_json::{Value, json};
use vectorcraft_engine::doc::Document;
@@ -36,6 +44,18 @@ pub const SET_ROLE: &str = "addon.packaging.setRole";
pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch";
/// The command that checks the fold lines.
pub const CHECK: &str = "addon.packaging.check";
/// The command that sets or resets the fold angle of fold lines.
pub const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle";
/// The fold angles `addon.packaging.setFoldAngle` takes, in degrees.
pub const FOLD_ANGLES: std::ops::RangeInclusive<f64> = -180.0..=180.0;
/// The places a fold angle field shows `angle` to: all it has, so an angle such as 179.9999999° is
/// not shown as 180°, which typing 180 into the field would then leave unchanged; at least one, the
/// place the field's fine steps (a tenth of a degree) round to.
pub fn angle_places(angle: Option<f64>) -> usize {
// f64's Display is the shortest text that reads back as the same number, without an exponent.
angle.map_or(0, |a| format!("{a}").split_once('.').map_or(0, |(_, places)| places.len())).max(1)
}
/// The command that shows the Fold Preview window.
pub const PREVIEW: &str = "ui.foldPreview";
/// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them.
@@ -54,6 +74,7 @@ pub fn menu() -> Vec<Node> {
make("Make Perforation Line", "perforation"),
Sep,
c("Check Fold Lines", CHECK),
c("Set Fold Angle…", SET_FOLD_ANGLE),
Sep,
cp("Fold Preview", PREVIEW, json!({})),
]
@@ -215,14 +236,22 @@ struct Rows {
/// What they were read for: the document, its revision and its selection.
key: Option<(u64, u64, Vec<u64>)>,
rows: Vec<Row>,
/// Whether the rows count the selection (not the whole document).
selection: bool,
/// How many lines that fold (Crease, Partial Cut, Perforation) Set Fold Angle can change.
fold_lines: u64,
/// The angle they all fold at (`None`: they differ, or there are none).
angle: Option<f64>,
/// How many of them hold a stored angle, readable or not: what Reset takes away.
stored_angles: u64,
}
/// The rows for the active document as it is now, read again only when it changed.
fn rows(app: &mut VectorcraftApp) -> Vec<Row> {
let Some(st) = app.session.active() else { return vec![] };
fn read_rows(app: &mut VectorcraftApp) -> Rows {
let Some(st) = app.session.active() else { return Rows::default() };
let key = (st.uid, st.revision, st.selection.objects.iter().map(|id| id.0).collect::<Vec<_>>());
if app.addon_panels.fold.rows.key.as_ref() == Some(&key) {
return app.addon_panels.fold.rows.rows.clone();
return app.addon_panels.fold.rows.clone();
}
let answer = app.session.execute("addon.packaging.roles", &json!({})).unwrap_or(Value::Null);
let d = app.session.active().map(|st| st.doc.clone());
@@ -231,9 +260,74 @@ fn rows(app: &mut VectorcraftApp) -> Vec<Row> {
let paint = d.as_ref().and_then(|d| d.swatch(&swatch)).map(|s| s.paint.clone());
Some((r["role"].as_str()?.to_string(), swatch, paint, r["count"].as_u64()?))
};
let rows: Vec<Row> = answer["roles"].as_array().into_iter().flatten().filter_map(row).collect();
app.addon_panels.fold.rows = Rows { key: Some(key), rows: rows.clone() };
rows
let kept = Rows {
key: Some(key),
rows: answer["roles"].as_array().into_iter().flatten().filter_map(row).collect(),
selection: answer["scope"] == "selection",
fold_lines: answer["foldLines"].as_u64().unwrap_or(0),
angle: answer["foldAngle"].as_f64(),
stored_angles: answer["storedAngles"].as_u64().unwrap_or(0),
};
app.addon_panels.fold.rows = kept.clone();
kept
}
/// The role rows for the active document as it is now.
#[cfg(test)]
fn rows(app: &mut VectorcraftApp) -> Vec<Row> {
read_rows(app).rows
}
/// The fields Set Fold Angle… opens with: `addon.packaging.setFoldAngle`'s options on the angle
/// the selected lines that it can change all fold at, else 90°, and those lines as the `ids` OK
/// sends, so OK changes the lines the dialog opened on even when the selection changes while it is
/// open, with the uid of their document as `__doc`, so OK changes nothing once another document is
/// the active one. The command's reason while it can't change any.
pub(crate) fn dialog_fields(app: &VectorcraftApp) -> Result<serde_json::Map<String, Value>, String> {
let command = vectorcraft_engine::find_command(SET_FOLD_ANGLE).ok_or_else(|| format!("unknown command {SET_FOLD_ANGLE}"))?;
(command.enabled)(&app.session)?;
let angle = vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle.unwrap_or(90.0);
let ids: Vec<u64> = vectorcraft_engine::cmd::selection_fold_lines(&app.session).iter().map(|id| id.0).collect();
let doc = app.session.active().map(|st| st.uid);
match json!({ "angle": angle, "__params": { "ids": ids }, "__doc": doc }) {
Value::Object(fields) => Ok(fields),
_ => Err("no fields".into()),
}
}
/// Set Fold Angle…: opens the parameter dialog on [`dialog_fields`].
pub(crate) fn open_dialog(app: &mut VectorcraftApp) -> Result<Value, String> {
let fields = dialog_fields(app)?;
crate::dialogs::command::open(app, SET_FOLD_ANGLE, "Set Fold Angle", fields)
}
/// The Fold Angle row, while the selection holds lines that fold and can be changed: the angle
/// they all fold at (empty when they differ), which sets theirs when changed, and Reset, which
/// takes away the angles of their own.
fn show_angle(app: &mut VectorcraftApp, ui: &mut Ui, kept: &Rows) {
if !kept.selection || kept.fold_lines == 0 {
return;
}
let mut call = None;
let _ = Line::new().fill_width().show(ui, |ui, _| {
Field::new(tl!("Fold Angle")).show(ui, |ui, _| {
let field = NumberField::new(tl!("Fold Angle"), Bind::given(kept.angle))
.unit_kind(UnitKind::Degrees)
.range(FOLD_ANGLES)
.max_decimals(angle_places(kept.angle));
if let Some(a) = field.id_salt("fold-angle").show(ui).value().copied().flatten() {
call = Some(json!({ "angle": a }));
}
});
if clicked(&Button::new(tl!("Reset")).enabled(kept.stored_angles > 0).show(ui)) {
call = Some(json!({ "reset": true }));
}
});
if let Some(p) = call
&& let Err(e) = app.run(SET_FOLD_ANGLE, p)
{
app.status(e);
}
}
/// The label of role `role` (its id when it is none of [`ROLES`]).
@@ -249,8 +343,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if !selected {
Text::new(tl!("No objects are selected.").to_string()).show(ui);
}
let rows = rows(app);
let source = Positional { rows: &rows, label: |row| role_label(&row.0) };
let kept = read_rows(app);
let rows = &kept.rows;
let source = Positional { rows, label: |row| role_label(&row.0) };
let out = List::<usize>::new(tl!("Fold line roles").to_string())
.select(SelectMode::None)
.activate(ActivateOn::Click)
@@ -277,6 +372,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
{
app.status(e);
}
show_angle(app, ui, &kept);
show_check(app, ui);
}
@@ -519,6 +519,8 @@ fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() {
order: vec![],
hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)],
collisions: vec![(0, 1)],
stack: Default::default(),
origin: [0.0; 3],
};
// The summary, the fold line errors, the other blanks, the open joint, the crossing panels.
assert_eq!(status(3, Some((&Blank::default(), &f)), true).len(), 5);
+62 -2
View File
@@ -3,8 +3,9 @@ use std::sync::Arc;
use serde_json::json;
use vectorcraft_engine::Session;
use super::{CHECK, ID, SET_ROLE, follow_role, last_check, rows, run_check, select_issue};
use super::{CHECK, ID, SET_FOLD_ANGLE, SET_ROLE, follow_role, last_check, read_rows, rows, run_check, select_issue, show};
use crate::i18n::LangExt as _;
use crate::tests::panel_harness::Panel;
use crate::{VectorcraftApp, menus};
/// An app with two rectangles, nothing selected → (app, their ids).
@@ -142,8 +143,67 @@ fn every_issue_message_translates_in_every_complete_message_catalog() {
"ca", "nl", "da",
] {
let lang = crate::i18n::Lang::from_code(code).unwrap();
for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0"]) {
let no_fold_line = "select a crease, partial cut or perforation line that is neither locked nor hidden";
for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0", no_fold_line]) {
assert_ne!(crate::i18n::message(lang, m), m, "{code}: {m}");
}
}
}
#[test]
fn set_fold_angle_is_listed_after_check_fold_lines() {
let (app, _, _) = app();
let entries = menus::menu_entries(&app);
let items: Vec<&str> = entries.iter().filter(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"]).map(|e| e.label.as_str()).collect();
let at = |label: &str| items.iter().position(|l| *l == label).unwrap_or_else(|| panic!("{label}: {items:?}"));
assert_eq!(at("Set Fold Angle…"), at("Check Fold Lines") + 1);
let item = entries.iter().find(|e| e.label == "Set Fold Angle…").expect("listed");
assert_eq!(item.command.as_deref(), Some(SET_FOLD_ANGLE));
}
#[test]
fn a_fold_angle_field_shows_every_place_the_angle_has() {
use super::angle_places;
assert_eq!([None, Some(90.0), Some(-135.5), Some(179.9999999), Some(1e-12)].map(angle_places), [1, 1, 1, 7, 12]);
}
#[test]
fn the_panel_shows_the_selected_lines_fold_angle_and_what_reset_takes_away() {
let (mut app, a, b) = app();
app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap();
app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap();
app.run("select.set", json!({"ids": [b]})).unwrap();
let text = crate::tests_labels::painted_text(&mut app, show);
assert!(!text.contains("Fold Angle"), "a cut line has no fold angle: {text}");
app.run("select.set", json!({"ids": [a]})).unwrap();
let kept = read_rows(&mut app);
assert_eq!((kept.selection, kept.fold_lines, kept.angle, kept.stored_angles), (true, 1, Some(90.0), 0), "Reset is dimmed");
app.run(SET_FOLD_ANGLE, json!({"angle": 135})).unwrap();
let text = crate::tests_labels::painted_text(&mut app, show);
assert!(text.contains("Fold Angle") && text.contains("Reset"), "{text}");
let panel = Panel::new(app, show);
let values = panel.values();
let mut app = panel.app();
assert!(values.iter().any(|v| v.strip_prefix("135").is_some_and(|unit| unit.is_empty() || unit.starts_with([' ', '°']))), "{values:?}");
let kept = read_rows(&mut app);
assert_eq!((kept.angle, kept.stored_angles), (Some(135.0), 1));
// Stored text that is not an angle: the field shows the role's angle, and Reset can still remove the text.
app.session
.edit("Test", |d, _| {
if let Some(n) = d.node_mut(vectorcraft_doc::NodeId(a)) {
n.edit_attrs(|at| {
at.data.retain(|(k, _)| k != "vc-fold-angle");
at.data.push(("vc-fold-angle".into(), "wide".into()));
});
}
Ok(())
})
.unwrap();
let kept = read_rows(&mut app);
assert_eq!((kept.angle, kept.stored_angles), (Some(90.0), 1));
// Nothing selected: the rows count the document and no Fold Angle row shows.
app.run("select.none", json!({})).unwrap();
assert!(!read_rows(&mut app).selection);
let text = crate::tests_labels::painted_text(&mut app, show);
assert!(!text.contains("Fold Angle"), "{text}");
}
+1
View File
@@ -307,6 +307,7 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec<Param> {
let snap = ParamKind::number(Some(snap_lo), Some(snap_hi), tangent_circle_tool::SNAP_PX, 1.0, 2);
return vec![
Param::new("radius", tl!("Radius"), kind).length(lengths),
Param::new("addPoints", tl!(tangent_circle_tool::ADD_POINTS), ParamKind::bool(false)),
Param::new("center", tl!("Circle Center"), ParamKind::bool(true)),
Param::new("radii", tl!("Circle Radii Lines"), ParamKind::bool(true)),
Param::new("color", tl!("Color"), ParamKind::choice(colors, Some("red".into()))),
+11 -3
View File
@@ -84,11 +84,18 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() {
assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("straight"));
ok(&mut app, &[("mode", FieldValue::Text("arc".into()))]);
assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc"));
// The Tangent Circle tool's radius for Shift.
// The Tangent Circle tool's radius for Shift, and Add Points to Existing Paths (off to start).
app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap();
assert_eq!(held(&app, |d| d.expect("the held dialog").fields().number("radius")), Some(36.0));
ok(&mut app, &[("radius", FieldValue::Number(12.5))]);
let shown = held(&app, |d| {
let f = d.expect("the held dialog").fields();
(f.number("radius"), f.bool("addPoints"))
});
assert_eq!(shown, (Some(36.0), Some(false)));
let rows = super::options_params("tangentCircle", crate::canvas::rulers::general_lengths(&app));
assert!(rows.iter().any(|p| p.key == "addPoints" && p.label.as_str() == "Add Points to Existing Paths"), "the option has a row");
ok(&mut app, &[("radius", FieldValue::Number(12.5)), ("addPoints", FieldValue::Bool(true))]);
assert_eq!(app.session.tool_options_of("tangentCircle")["radius"], json!(12.5));
assert_eq!(app.session.tool_options_of("tangentCircle")["addPoints"], json!(true));
assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err());
assert_eq!(KIND, "pathToolOptions");
}
@@ -150,6 +157,7 @@ fn the_tangent_circle_options_have_their_rows_and_a_fractional_tolerance() {
rows,
[
("radius", "Radius"),
("addPoints", "Add Points to Existing Paths"),
("center", "Circle Center"),
("radii", "Circle Radii Lines"),
("color", "Color"),
+12 -2
View File
@@ -232,6 +232,7 @@ impl VectorcraftApp {
shortcuts_dialog: None,
shortcut_overrides: Default::default(),
told: Default::default(),
missing_font_edit_token: None,
held: Default::default(),
edit_scopes: Default::default(),
command_dialog: Default::default(),
@@ -445,6 +446,11 @@ impl VectorcraftApp {
let now = self.now();
self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0);
self.sync_views();
// With no document open too, so closing the last one stops the host reading the wheel. A
// held press, whose previews change the document each frame, keeps what it was told.
if self.canvas.grab.is_none() {
crate::stylus::sync_wheel_use(self);
}
// A document that moved between the main window and a floating OS window, or opened, takes
// the density of the display that shows it.
self.settle_screen_ppi_if_changed();
@@ -701,14 +707,18 @@ impl VectorcraftApp {
}
}
/// Use the same supported scale for the interface and the canvas. Invalid saved values fall back to 100%.
fn applied_ui_scaling(saved: f64) -> f32 {
if saved.is_finite() && saved > 0.0 { saved.clamp(0.75, 2.0) as f32 } else { 1.0 }
}
/// The root values the preferences give every frame: the theme, the interface scale (UI Scaling
/// over the display's `native_ppp`), Show Tool Tips, the zoom stops (100% at `print` screen points
/// to an inch, [`crate::state::print_ppi`]) and which drags scrub a value (Scrub Numeric Fields: the
/// side label only, or nothing).
pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print: Option<f64>) -> RootEnv {
let (theme, mode, accent) = theme::root_theme(prefs);
// A hand-edited preferences file must not scale the interface to nothing.
let scaling = if prefs.ui_scaling.is_finite() && prefs.ui_scaling > 0.0 { prefs.ui_scaling as f32 } else { 1.0 };
let scaling = applied_ui_scaling(prefs.ui_scaling);
let mut root = RootEnv::new().theme(theme).mode(mode).accent(accent).scale(Scale::new(scaling)).tooltips(prefs.show_tool_tips);
root.sizes = theme::app_sizes();
root.values.set(view::zoom_scheme(print, native_ppp));
+1 -1
View File
@@ -327,7 +327,7 @@ impl VectorcraftApp {
/// Preferences › User Interface › UI Scaling, as the interface applies it.
pub(crate) fn ui_scaling(&self) -> f32 {
self.session.prefs.ui_scaling.clamp(0.75, 2.0) as f32
super::applied_ui_scaling(self.session.prefs.ui_scaling)
}
/// Ask the active view's canvas to run `request` in its next pass; `bounds` are the layers' bounds
+9 -2
View File
@@ -9,6 +9,7 @@ use craft::ui::canvas::{
canvas_space, tool_pass,
};
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft::ui::primitives::PaintSlot;
use craft::ui::runtime::env::Env;
use craft::ui::runtime::focus::NudgeMods;
use craft::ui::style::StyleCx;
@@ -277,7 +278,8 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin
pressed
}
/// The body of the canvas in order: controls that take presses first, the tool host, the picture last.
/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks, the
/// picture last.
fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: Option<&ToolPass>, win: Win, kind: BodyKind) -> Body {
let live = kind == BodyKind::Live;
let presenting = app.ui.screen_mode == 3;
@@ -297,7 +299,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O
crate::dialogs::simplify_slider::show(app, ui, &space.view);
}
guides::show(app, ui, space, win, kind);
selection::show(app, ui, space, win, kind);
// The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this
// frame's pointer event, from the document as the event leaves it.
let marks = PaintSlot::reserve(ui.painter());
widgets::show(app, ui, space, win, kind);
if !presenting && !revolve_editing(app) {
crate::panels::three_d::handles::show(app, ui, space);
@@ -334,6 +338,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O
crate::type_editing::show(app, ui);
}
}
let after = PaintSlot::reserve(ui.painter());
selection::show(app, ui, space, win, kind);
marks.extend(ui.ctx(), after.take_after(ui.ctx()));
drops::show(app, ui, win, kind);
raster::picture(app, ui, space, win, kind);
out
+6
View File
@@ -362,6 +362,12 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
params["ids"] = json!([owner(app, &hit)?]);
params["focus"] = json!(false);
let cmd = crate::panels::proxy_cmd(app, false);
if let Some(gradient) = params.get_mut("gradient").and_then(Value::as_object_mut) {
if cmd == "paint.setStroke" {
gradient.remove("dither");
}
params["keepModel"] = json!(true);
}
run(app, cmd, params)
}
Payload::Panel(PanelDrag::Appearance(source)) => {
+35
View File
@@ -45,6 +45,41 @@ fn undo_len(app: &VectorcraftApp) -> usize {
app.session.active().unwrap().history.undo.len()
}
fn drop_dithered_rgb_gradient(app: &mut VectorcraftApp, fill: bool) -> NodeId {
app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap();
let result = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap();
let id = NodeId(result["id"].as_u64().unwrap());
app.session.fill_active = fill;
let mut gradient = GradientPaint::new(Default::default());
gradient.gradient.stops[0].color = Color::rgb8(255, 0, 0);
gradient.gradient.dither = true;
let start = undo_len(app);
let drag = PanelDrag::paint(Paint::Gradient(Box::new(gradient)));
drop_at(app, Payload::Panel(drag), Point::new(50.0, 50.0), DropOperation::Move).unwrap();
assert_eq!(undo_len(app), start + 1);
id
}
#[test]
fn a_gradient_drop_preserves_rgb_stops_and_fill_dither() {
let (mut app, _ctx) = app_with_canvas();
let id = drop_dithered_rgb_gradient(&mut app, true);
let doc = &app.session.active().unwrap().doc;
let Paint::Gradient(fill) = doc.node(id).unwrap().appearance.fill_paint() else { panic!("expected a gradient fill") };
assert_eq!(fill.gradient.stops[0].color, Color::rgb8(255, 0, 0));
assert!(fill.gradient.dither);
}
#[test]
fn a_dithered_gradient_drop_applies_to_a_stroke_without_dither() {
let (mut app, _ctx) = app_with_canvas();
let id = drop_dithered_rgb_gradient(&mut app, false);
let doc = &app.session.active().unwrap().doc;
let Paint::Gradient(stroke) = &doc.node(id).unwrap().appearance.stroke().unwrap().paint else { panic!("expected a gradient stroke") };
assert_eq!(stroke.gradient.stops[0].color, Color::rgb8(255, 0, 0));
assert!(!stroke.gradient.dither);
}
/// Each payload's effect, on art and off it: a style applies to the object hit (Alt adds on top), a paint fills it
/// and leaves the selection (a gradient fits it), an appearance copies unless dropped on its source, a brush strokes
/// the path hit and off art places its art if it has any, a library brush is added and applied in one step, a symbol
+91 -19
View File
@@ -8,12 +8,36 @@ pub(super) fn c32(rgb: [u8; 3]) -> Color32 {
Color32::from_rgb(rgb[0], rgb[1], rgb[2])
}
/// What the view hides among a selected object's members, which the selection marks leave out as
/// the canvas does ([`Node::hidden_by_view`]): template layers while View › Hide Template is on,
/// and paths made into guides while the guides are hidden. The default hides nothing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct ViewHides {
pub(super) templates: bool,
pub(super) guides: bool,
}
impl ViewHides {
/// What `app`'s view hides.
pub(super) fn of(app: &VectorcraftApp) -> Self {
Self { templates: !app.ui.view.templates, guides: !app.ui.view.guides_shown() }
}
/// [`Node::drawn_children`] of `n` without the members the view leaves out. Every path of a
/// compound path stays, since the compound path draws all of them, guides or not.
fn children(self, n: &Node) -> impl Iterator<Item = &std::sync::Arc<Node>> {
let hide_guides = self.guides && !matches!(n.kind, NodeKind::Compound { .. });
n.drawn_children().filter(move |c| !c.hidden_by_view(self.templates, hide_guides))
}
}
/// Outline of a node for highlighting (paths, compound children, area type frames, image bounds,
/// the box as drawn of type in perspective and of symbol instances, whose art `symbols` measures
/// ([`Node::drawn_corners`]); a clip group's clipping path only, as [`walk_drawn`] visits it).
pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath {
/// ([`Node::drawn_corners`]); a clip group's clipping path only, as [`walk_drawn`] visits it,
/// without the members `hides` leaves out).
pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes, hides: ViewHides) -> BezPath {
let mut bp = BezPath::new();
walk_drawn(n, &mut |c| match &c.kind {
walk_drawn(n, hides, &mut |c| match &c.kind {
NodeKind::Path { path, .. } => bp.extend(path.to_bezpath()),
// Area type shows its frame: the type area Direct Selection reshapes; type on a path its
// path, which the selection tools' brackets sit on; point type shows its baseline(s).
@@ -31,9 +55,10 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath {
corners(&mut bp, q);
}
}
// An image shows its frame, turned or distorted with it.
NodeKind::Image(_) => {
if let Some(b) = c.geometric_bounds_with(symbols) {
bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath());
if let Some(frame) = c.image_frame() {
bp.extend(frame);
}
}
// A symbol instance shows its art's box, turned, skewed or in perspective with it.
@@ -62,6 +87,38 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath {
bp
}
/// Whether `n` is a linked image or a placed document, which the selection marks cross.
fn is_linked(n: &Node) -> bool {
match &n.kind {
NodeKind::Image(im) => im.link.is_some(),
NodeKind::PlacedDocument(_) => true,
_ => false,
}
}
/// The lines that cross each linked image and placed document of `n` that [`walk_drawn`] visits,
/// from corner to corner of its frame or box (#9080), without the members `hides` leaves out. The
/// selection marks draw them; the hover highlight does not.
pub(super) fn linked_crosses(n: &Node, hides: ViewHides) -> BezPath {
let mut bp = BezPath::new();
walk_drawn(n, hides, &mut |c| match &c.kind {
NodeKind::Image(_) if is_linked(c) => {
if let Some(cross) = c.image_cross() {
bp.extend(cross);
}
}
NodeKind::PlacedDocument(p) => {
let [tl, tr, br, bl] = p.corners();
bp.move_to(tl);
bp.line_to(br);
bp.move_to(tr);
bp.line_to(bl);
}
_ => {}
});
bp
}
/// Adds the closed outline through the four corners `q` to `bp`.
fn corners(bp: &mut BezPath, q: [Point; 4]) {
let [a, b, c, d] = q;
@@ -77,22 +134,36 @@ fn corners(bp: &mut BezPath, q: [Point; 4]) {
/// #2460).
pub(super) const OVERLAY_MAX_ANCHORS: usize = 100_000;
/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`];
/// counting stops there).
pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator<Item = &'a Node>) -> bool {
fn over(n: &Node, left: &mut usize) -> bool {
match left.checked_sub(overlay_points(n)) {
/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`],
/// without the members `hides` leaves out; counting stops there).
pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator<Item = &'a Node>, hides: ViewHides) -> bool {
over_limit(nodes, false, hides)
}
/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline and to cross where they
/// are linked images or placed documents ([`linked_crosses`]), as the selection marks draw them
/// without the members `hides` leaves out.
pub(super) fn too_many_marks<'a>(nodes: impl IntoIterator<Item = &'a Node>, hides: ViewHides) -> bool {
over_limit(nodes, true, hides)
}
/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points ([`overlay_points`], with the
/// ends of the crossing lines when `crosses`) in what [`walk_drawn`] visits; counting stops there.
fn over_limit<'a>(nodes: impl IntoIterator<Item = &'a Node>, crosses: bool, hides: ViewHides) -> bool {
fn over(n: &Node, left: &mut usize, crosses: bool, hides: ViewHides) -> bool {
let ends = if crosses && is_linked(n) { 4 } else { 0 };
match left.checked_sub(overlay_points(n) + ends) {
Some(l) => *left = l,
None => return true,
}
// A clip group counts only its clipping path, the one child `walk_drawn` visits.
if n.clips() {
return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left));
return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses, hides));
}
!matches!(n.kind, NodeKind::Envelope { .. }) && n.editing_children().iter().any(|c| over(c, left))
!matches!(n.kind, NodeKind::Envelope { .. }) && hides.children(n).any(|c| over(c, left, crosses, hides))
}
let mut left = OVERLAY_MAX_ANCHORS;
nodes.into_iter().any(|n| over(n, &mut left))
nodes.into_iter().any(|n| over(n, &mut left, crosses, hides))
}
/// The points counted for `n` itself, without its children, toward [`OVERLAY_MAX_ANCHORS`]: a
@@ -120,21 +191,22 @@ fn overlay_points(n: &Node) -> usize {
}
/// [`Node::walk`] over what a selection highlight shows: an envelope's content is left out (the
/// envelope shows its mesh instead), and a clip group or clipping layer shows only its clipping
/// path, its first child, not the art the path clips (#2422).
pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) {
/// envelope shows its mesh instead), a clip group or clipping layer shows only its clipping path,
/// its first child, not the art the path clips (#2422), and hidden members
/// ([`Node::drawn_children`]) and the members `hides` leaves out are left out.
pub(super) fn walk_drawn<'a>(n: &'a Node, hides: ViewHides, f: &mut impl FnMut(&'a Node)) {
f(n);
if matches!(n.kind, NodeKind::Envelope { .. }) {
return;
}
if n.clips() {
if let Some(clip) = n.children().and_then(|children| children.first()) {
walk_drawn(clip, f);
walk_drawn(clip, hides, f);
}
return;
}
for c in n.editing_children().iter() {
walk_drawn(c, f);
for c in hides.children(n) {
walk_drawn(c, hides, f);
}
}
+63
View File
@@ -798,6 +798,69 @@ fn other_panes_draw_their_guides_and_selected_objects() {
assert!(!crate::canvas::selection::outlines(&app, st).is_empty(), "the selected rectangle is outlined in its pane");
}
/// Another pane crosses a selected linked image from corner to corner, as the current pane does, and outlines a
/// selected embedded image alone (#9080).
#[test]
fn other_panes_cross_a_selected_linked_image() {
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType};
let png = vectorcraft_testkit::temp_dir("panes-linked-image").join("red.png");
let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, [200u8, 40, 40, 255].repeat(40 * 40)).unwrap();
std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap();
let mut app = app_with(2);
app.run("document.activate", json!({"index": 0})).unwrap();
let mut place = |link: bool, at: [f64; 2]| {
app.session.execute("file.place", &json!({"path": png, "link": link, "at": at})).unwrap()["ids"][0].as_u64().unwrap()
};
let (linked, embedded) = (place(true, [100.0, 100.0]), place(false, [250.0, 100.0]));
app.run("window.arrange.tile", json!({})).unwrap();
let ctx = crate::testing::ui_context();
// How many paths the first document's pane outlines with `id` selected there.
let mut paths = |id: u64| {
app.run("document.activate", json!({"index": 0})).unwrap();
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
app.run("document.activate", json!({"index": 1})).unwrap();
frame(&mut app, &ctx, vec![]);
frame(&mut app, &ctx, vec![]);
let st = &app.session.documents()[0];
crate::canvas::selection::outlines(&app, st).iter().map(|o| o.paths.len()).sum::<usize>()
};
let (linked, embedded) = (paths(linked), paths(embedded));
assert_eq!((linked, embedded), (2, 1), "the outline of a linked image and its crossing lines; an embedded image's outline alone");
}
/// Another pane outlines a selected group's visible members only: hiding a member draws the same outlines as deleting
/// it.
#[test]
fn other_panes_leave_out_a_selected_groups_hidden_members() {
let mut app = app_with(2);
app.run("document.activate", json!({"index": 0})).unwrap();
let id = |made: serde_json::Value| made["id"].as_u64().unwrap();
let shown = id(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80})).unwrap());
let hidden = id(app.run("shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60})).unwrap());
app.run("select.set", json!({"ids": [shown, hidden]})).unwrap();
let group = id(app.run("object.group", json!({})).unwrap());
app.run("window.arrange.tile", json!({})).unwrap();
let ctx = crate::testing::ui_context();
// The paths the first document's pane outlines with the group selected there, after the commands `edit` there.
let outlines = |app: &mut VectorcraftApp, edit: &[(&str, serde_json::Value)]| {
app.run("document.activate", json!({"index": 0})).unwrap();
for (command, params) in edit {
app.run(command, params.clone()).unwrap();
}
app.run("select.set", json!({"ids": [group]})).unwrap();
app.run("document.activate", json!({"index": 1})).unwrap();
frame(app, &ctx, vec![]);
frame(app, &ctx, vec![]);
let st = &app.session.documents()[0];
crate::canvas::selection::outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect::<Vec<_>>()
};
let both = outlines(&mut app, &[]);
let without = outlines(&mut app, &[("select.set", json!({"ids": [hidden]})), ("edit.clear", json!({}))]);
let with_hidden = outlines(&mut app, &[("edit.undo", json!({})), ("select.set", json!({"ids": [hidden]})), ("object.hide", json!({}))]);
assert_ne!(both, without, "the outlines show both members");
assert_eq!(with_hidden, without, "a hidden member is not outlined");
}
#[test]
fn opening_a_document_while_tiled_fits_each_document_to_its_new_pane() {
let mut app = app_with(2);
+29 -22
View File
@@ -24,7 +24,7 @@ use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point};
use vectorcraft_tools::Mods;
use super::cursor::ViewKey;
use super::outline::{c32, node_outline, selection_hit_at, too_many_anchors, walk_drawn};
use super::outline::{ViewHides, c32, linked_crosses, node_outline, selection_hit_at, too_many_anchors, too_many_marks, walk_drawn};
// PLAN: `BodyKind`, `Win` and `ViewKey::from(CanvasView)` are canvas-w10's (cv.S1, S2, S5); their paths here follow the contract.
use super::{BodyKind, VectorcraftApp, Win};
// PLAN: `anchors` takes `tool_points` because the Curvature tool's own points come from `session.overlays`, which only `show` may call (`&mut app`).
@@ -147,9 +147,9 @@ fn hidden(app: &VectorcraftApp) -> bool {
crate::dialogs::halftone::previewing(app)
}
/// Whether the selection has too many points to outline: its bounds stand for it.
fn too_big(st: &DocState) -> bool {
too_many_anchors(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)))
/// Whether the selection has too many points to outline and cross in `app`'s view: its bounds stand for it.
fn too_big(app: &VectorcraftApp, st: &DocState) -> bool {
too_many_marks(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)), ViewHides::of(app))
}
/// The rectangle of `bounds` as a path.
@@ -166,17 +166,17 @@ fn group(out: &mut Vec<Outlined>, color: Color32) -> &mut Outlined {
&mut out[at]
}
/// The outlines of the selection, one [`Outlined`] per layer colour: each selected object's outline (the bounds of
/// all of them when they have too many points), the spine of each selected blend, and the key object's outline (its
/// The outlines of the selection, one [`Outlined`] per layer colour: each selected object's outline and the lines
/// across its linked images and placed documents (the bounds of all of them when they have too many points), the spine of each selected blend, and the key object's outline (its
/// bounds when it has too many points). Nothing during Halftone Preview.
pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec<Outlined> {
let mut out: Vec<Outlined> = vec![];
if hidden(app) {
return out;
}
let (sel, symbols) = (&st.selection, st.doc.symbol_boxes());
let (sel, symbols, hides) = (&st.selection, st.doc.symbol_boxes(), ViewHides::of(app));
let color_of = |id: NodeId| c32(st.doc.layer_color(id));
if too_big(st) {
if too_big(app, st) {
// The cache is warmed by `show`; a test or a miss measures again.
let bounds = match app.canvas.selection_bounds {
Some((key, bounds)) if key == (st.uid, st.revision) => bounds,
@@ -188,9 +188,11 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec<Outlined> {
} else {
for id in &sel.objects {
let Some(node) = st.doc.node(*id) else { continue };
let path = node_outline(node, &symbols);
if !path.elements().is_empty() {
group(&mut out, color_of(*id)).paths.push(path);
// Linked images and placed documents are also crossed from corner to corner.
for path in [node_outline(node, &symbols, hides), linked_crosses(node, hides)] {
if !path.elements().is_empty() {
group(&mut out, color_of(*id)).paths.push(path);
}
}
}
for (blend, spine) in blend_spines(st) {
@@ -198,7 +200,11 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec<Outlined> {
}
}
if let Some((key, node)) = sel.key.and_then(|key| Some((key, st.doc.node(key)?))) {
let path = if too_many_anchors([node]) { node.geometric_bounds_with(&symbols).map(bounds_path) } else { Some(node_outline(node, &symbols)) };
let path = if too_many_anchors([node], hides) {
node.geometric_bounds_with(&symbols).map(bounds_path)
} else {
Some(node_outline(node, &symbols, hides))
};
if let Some(path) = path {
group(&mut out, color_of(key)).key = Some(path);
}
@@ -266,10 +272,10 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin
segment_mark: SegmentMark::Line,
options: path_options(prefs),
};
if hidden(app) || too_big(st) || (curvature && tool_points) {
if hidden(app) || too_big(app, st) || (curvature && tool_points) {
return out;
}
let sel = &st.selection;
let (sel, hides) = (&st.selection, ViewHides::of(app));
// The selected anchors by path, and the selected segment with its path.
let mut chosen: Vec<(u64, Vec<KnotRef>)> = vec![];
let mut segment: Option<(u64, KnotRef)> = None;
@@ -277,7 +283,7 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin
let Some(node) = st.doc.node(*id) else { continue };
let partial = sel.partial(*id);
let color = c32(st.doc.layer_color(*id));
walk_drawn(node, &mut |c| {
walk_drawn(node, hides, &mut |c| {
let envelope = vectorcraft_doc::live::envelope_overlay(c).and_then(|(_, grid)| grid);
let grid = match &c.kind {
NodeKind::Mesh(m) => Some(m),
@@ -369,13 +375,14 @@ pub(super) fn hover(app: &VectorcraftApp, st: &DocState, tool: &str, at: Point,
if kept {
return None;
}
outline_of(st, id)
outline_of(st, id, ViewHides::of(app))
}
/// The hover outline of `id` in its layer colour, unless it has too many points.
fn outline_of(st: &DocState, id: NodeId) -> Option<Hovered> {
let node = st.doc.node(id).filter(|n| !too_many_anchors([*n]))?;
Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes()), color: c32(st.doc.layer_color(id)) })
/// The hover outline of `id` in its layer colour, without the members `hides` leaves out, unless it has too many
/// points.
fn outline_of(st: &DocState, id: NodeId, hides: ViewHides) -> Option<Hovered> {
let node = st.doc.node(id).filter(|n| !too_many_anchors([*n], hides))?;
Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes(), hides), color: c32(st.doc.layer_color(id)) })
}
/// The hover outline the canvas shows at document point `at` with the keys `held`: none while Space lends the view
@@ -405,7 +412,7 @@ pub(super) fn eyedropper_hover(app: &mut VectorcraftApp, at: Point, mods: Mods,
}
let info = app.view_info();
let id = eyedropper_hover_object(app, at, mods, info)?;
outline_of(app.session.active()?, id)
outline_of(app.session.active()?, id, ViewHides::of(app))
}
/// What the Eyedropper's hover object depends on: the point, the keys held, the document as it is, the selection and
@@ -495,7 +502,7 @@ fn eyedropper_hover_object(app: &mut VectorcraftApp, at: Point, mods: Mods, view
/// The dots of the selection: point type's origin, the centre of each object that shows it, and the key anchor.
pub(super) fn dots(app: &VectorcraftApp, st: &DocState) -> Dots {
let mut out = Dots { grow: grow(&app.session.prefs), ..Dots::default() };
if hidden(app) || too_big(st) {
if hidden(app) || too_big(app, st) {
return out;
}
let symbols = st.doc.symbol_boxes();
+293 -1
View File
@@ -243,7 +243,7 @@ fn the_key_object_has_its_own_outline() {
let ids = app.session.active().unwrap().selection.objects.clone();
app.run("select.key", json!({"id": curve.0})).unwrap();
let st = app.session.active().unwrap();
let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes());
let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes(), ViewHides::default());
let color = c32(st.doc.layer_color(curve));
let out = outlines(&app, st);
let key = out.iter().find(|o| o.color == color).and_then(|o| o.key.as_ref()).unwrap();
@@ -252,6 +252,298 @@ fn the_key_object_has_its_own_outline() {
assert_eq!(out.iter().map(|o| o.paths.len()).sum::<usize>(), ids.len(), "the selection's own outlines stay");
}
/// A file with a 40 × 40 px red PNG in a new temporary folder named `name`.
fn red_png(name: &str) -> std::path::PathBuf {
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType};
let png = vectorcraft_testkit::temp_dir(name).join("red.png");
let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, [200u8, 40, 40, 255].repeat(40 * 40)).unwrap();
std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap();
png
}
/// The two lines from corner to corner of `[tl, tr, br, bl]`.
fn cross_of([tl, tr, br, bl]: [Point; 4]) -> Vec<PathEl> {
vec![PathEl::MoveTo(tl), PathEl::LineTo(br), PathEl::MoveTo(tr), PathEl::LineTo(bl)]
}
/// The outline of `[tl, tr, br, bl]`: its corners joined by straight lines.
fn frame_of([tl, tr, br, bl]: [Point; 4]) -> Vec<PathEl> {
vec![PathEl::MoveTo(tl), PathEl::LineTo(tr), PathEl::LineTo(br), PathEl::LineTo(bl), PathEl::ClosePath]
}
/// A selected linked image and a selected placed document are crossed from corner to corner, on a turned or
/// distorted image along its frame; a selected embedded image shows its outline alone, along its frame when turned or
/// distorted. The key object's outline and the hover outline are not crossed (#9080).
#[test]
fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() {
let png = red_png("selection-linked");
let placed = png.with_file_name("art.vectorcraft");
std::fs::write(&placed, vectorcraft_format::save_file(&vectorcraft_doc::Document::new(60.0, 40.0))).unwrap();
let mut app = blank();
let place = |app: &mut VectorcraftApp, path: &std::path::Path, link: bool, at: [f64; 2]| {
NodeId(app.run("file.place", json!({"path": path, "link": link, "at": at})).unwrap()["ids"][0].as_u64().unwrap())
};
let linked = place(&mut app, &png, true, [100.0, 120.0]);
let embedded = place(&mut app, &png, false, [300.0, 120.0]);
let document = place(&mut app, &placed, true, [200.0, 230.0]);
let corners = |app: &VectorcraftApp, id: NodeId| {
let n = app.session.active().unwrap().doc.node(id).unwrap();
match &n.kind {
NodeKind::PlacedDocument(p) => p.corners(),
_ => n.image_corners().unwrap(),
}
};
// Whether the selection's outlines hold a path made of `els`.
let drawn = |app: &VectorcraftApp, els: &[PathEl]| {
outlines(app, app.session.active().unwrap()).iter().any(|o| o.paths.iter().any(|p| p.elements() == els))
};
// Whether `id` is crossed, and whether it is outlined along its frame.
let marked = |app: &VectorcraftApp, id: NodeId| (drawn(app, &cross_of(corners(app, id))), drawn(app, &frame_of(corners(app, id))));
app.run("select.all", json!({})).unwrap();
assert_eq!(marked(&app, linked), (true, true), "a linked image");
assert!(drawn(&app, &cross_of(corners(&app, document))), "a placed document");
assert_eq!(marked(&app, embedded), (false, true), "an embedded image");
assert_eq!(outlines(&app, app.session.active().unwrap()).iter().map(|o| o.paths.len()).sum::<usize>(), 5, "three outlines and two crosses");
app.run("select.set", json!({"ids": [linked.0, embedded.0]})).unwrap();
app.run("object.rotate", json!({"angle": 30})).unwrap();
assert_eq!(marked(&app, linked), (true, true), "a turned linked image, along its frame");
assert_eq!(marked(&app, embedded), (false, true), "a turned embedded image, outlined along its frame");
// Move each image's bottom right corner up its right side, so its corners no longer make a parallelogram.
app.session
.edit("Distort", |doc, _| {
for id in [linked, embedded] {
if let Some(n) = doc.node_mut(id)
&& let Some([tl, tr, br, bl]) = n.image_corners()
{
n.set_image_corners([tl, tr, br.lerp(tr, 0.4), bl]).map_err(|e| vectorcraft_engine::EngineError::Other(format!("{e:?}")))?;
}
}
Ok(())
})
.unwrap();
let doc = &app.session.active().unwrap().doc;
assert!([linked, embedded].iter().all(|id| doc.node(*id).unwrap().is_distorted_image()), "both images are distorted");
assert_eq!(marked(&app, linked), (true, true), "a distorted linked image, corner to corner");
assert_eq!(marked(&app, embedded), (false, true), "a distorted embedded image, outlined along its frame");
// The key object's outline is its frame alone, and so is the hover outline.
for id in [linked, embedded] {
app.run("select.key", json!({"id": id.0})).unwrap();
let st = app.session.active().unwrap();
let key = outlines(&app, st).into_iter().find_map(|o| o.key).unwrap();
assert_eq!(key.elements(), frame_of(corners(&app, id)).as_slice(), "the key object's outline of {id:?}");
assert_eq!(
outline_of(st, id, ViewHides::default()).unwrap().path.elements(),
frame_of(corners(&app, id)).as_slice(),
"the hover outline of {id:?}"
);
}
}
/// The selection's outlines count the ends of the lines that cross linked images toward the overlay's limit; the
/// hover outline and the key object's outline, which draw no such lines, do not (#9080).
#[test]
fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() {
use super::super::outline::{too_many_anchors, too_many_marks};
let image = |link: Option<vectorcraft_doc::LinkInfo>| {
let im = vectorcraft_doc::ImageObject {
key: "k".into(),
width: 10,
height: 10,
xf: vectorcraft_geom::Affine::IDENTITY,
link,
placement: Default::default(),
pixels: None,
};
vectorcraft_doc::Node::new(NodeId(1), NodeKind::Image(Box::new(im)))
};
// Four corners each fit; with the four ends of the crossing lines they do not.
let count = OVERLAY_MAX_ANCHORS / 6;
let linked = vec![image(Some(vectorcraft_doc::LinkInfo { path: "/a.png".into(), ..Default::default() })); count];
let embedded = vec![image(None); count];
let all = ViewHides::default();
assert!(!too_many_anchors(&linked, all) && too_many_marks(&linked, all), "linked images");
assert!(!too_many_anchors(&embedded, all) && !too_many_marks(&embedded, all), "embedded images");
}
/// A selected group outlines, marks and crosses only the members the canvas draws: a hidden member and a linked image
/// in a hidden group inside it leave no outline, anchors or crossing lines, in the selection's marks and in the hover
/// outline. Hiding them shows the same as deleting them.
#[test]
fn a_selected_group_leaves_its_hidden_members_unmarked() {
let png = red_png("selection-hidden");
let mut app = blank();
let left = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap());
let right = id_of(&app.run("shape.rectangle", json!({"x": 330, "y": 230, "width": 20, "height": 20})).unwrap());
let hidden = id_of(&app.run("shape.rectangle", json!({"x": 120, "y": 100, "width": 40, "height": 40})).unwrap());
let linked = app.run("file.place", json!({"path": png, "link": true, "at": [240.0, 150.0]})).unwrap()["ids"][0].as_u64().unwrap();
app.run("select.set", json!({"ids": [linked]})).unwrap();
let inner = id_of(&app.run("object.group", json!({})).unwrap());
app.run("select.set", json!({"ids": [left.0, right.0, hidden.0, inner.0]})).unwrap();
let group = id_of(&app.run("object.group", json!({})).unwrap());
// With the group selected after the commands `edit`: its outline paths, the paths that show anchors with their
// anchor count, and its hover outline.
let shown = |app: &mut VectorcraftApp, edit: &[(&str, serde_json::Value)]| {
for (command, params) in edit {
app.run(command, params.clone()).unwrap();
}
app.run("select.set", json!({"ids": [group.0]})).unwrap();
let st = app.session.active().unwrap();
let outlined: Vec<Vec<PathEl>> = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect();
let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::<Vec<_>>();
let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.elements().to_vec());
(outlined, anchored, hovered)
};
let both = shown(&mut app, &[]);
let without = shown(&mut app, &[("select.set", json!({"ids": [hidden.0, inner.0]})), ("edit.clear", json!({}))]);
let with_hidden = shown(&mut app, &[("edit.undo", json!({})), ("select.set", json!({"ids": [hidden.0, inner.0]})), ("object.hide", json!({}))]);
assert_ne!(both, without, "the marks show every member");
assert_eq!(without.1, vec![4, 4], "the anchors of the two visible members");
assert_eq!(with_hidden, without, "hidden members are not marked");
}
/// A selected group leaves out a member made into a guide while the guides are hidden, as the canvas does: its
/// outlines, anchors and hover outline are the same as with that member deleted. With the guides shown, the guide is
/// marked too.
#[test]
fn a_selected_group_leaves_out_its_guides_while_guides_are_hidden() {
let mut app = blank();
let path = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap());
let guide = id_of(&app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 40, "height": 40})).unwrap());
app.run("select.set", json!({"ids": [guide.0]})).unwrap();
app.run("view.guides.make", json!({})).unwrap();
app.run("select.set", json!({"ids": [path.0, guide.0]})).unwrap();
let group = id_of(&app.run("object.group", json!({})).unwrap());
assert!(
matches!(app.session.active().unwrap().doc.node(guide).map(|n| &n.kind), Some(NodeKind::Path { guide: true, .. })),
"the group holds a guide"
);
// With the group selected: the boxes of its outline paths, the paths that show anchors, and its hover outline's box.
let shown = |app: &mut VectorcraftApp| {
app.run("select.set", json!({"ids": [group.0]})).unwrap();
let st = app.session.active().unwrap();
let outlined: Vec<vectorcraft_geom::Rect> = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.bounding_box()).collect();
let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::<Vec<_>>();
let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.bounding_box());
(outlined, anchored, hovered)
};
let both = shown(&mut app);
app.run("view.guides", json!({})).unwrap();
assert!(!app.ui.view.guides_shown(), "the guides are hidden");
let guides_hidden = shown(&mut app);
app.run("view.guides", json!({})).unwrap();
app.run("select.set", json!({"ids": [guide.0]})).unwrap();
app.run("edit.clear", json!({})).unwrap();
let without = shown(&mut app);
assert_eq!(both.1.len(), 2, "with the guides shown, the guide shows its anchors too: {both:?}");
assert_ne!(both, without, "with the guides shown, the guide is marked");
assert_eq!(guides_hidden, without, "with the guides hidden, only the path is marked");
}
/// A selected layer leaves out the art of a template sublayer while View › Hide Template is on, and a group a guide
/// while the guides are hidden: their outlines and the overlay's point limit count only what the canvas draws.
#[test]
fn the_marks_leave_out_template_layers_and_guides_the_view_hides() {
use super::super::outline::{node_outline, too_many_anchors, too_many_marks};
use std::sync::Arc;
use vectorcraft_doc::{Appearance, LayerColor, Node};
use vectorcraft_geom::SubPath;
let rect = |id: u64, r: vectorcraft_geom::Rect| Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default());
let path = Arc::new(rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)));
let points: Vec<Point> = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect();
let mut many = Node::path(NodeId(3), PathData::single(SubPath::polyline(&points, false)), Appearance::default());
let mut template = Node::layer(NodeId(4), "Template", LayerColor::Preset(1));
if let NodeKind::Layer { template: on, children, .. } = &mut template.kind {
*on = true;
children.push(Arc::new(many.clone()));
}
let mut layer = Node::layer(NodeId(5), "Layer", LayerColor::Preset(0));
if let Some(children) = layer.children_mut() {
children.extend([Arc::new(template), path.clone()]);
}
if let NodeKind::Path { guide, .. } = &mut many.kind {
*guide = true;
}
let group = Node::group(NodeId(6), vec![Arc::new(many), path.clone()]);
let doc = vectorcraft_doc::Document::new(300.0, 300.0);
let symbols = doc.symbol_boxes();
let alone = node_outline(&path, &symbols, ViewHides::default()).bounding_box();
let mut wrong = vec![];
for (n, what, hides) in [
(&layer, "a layer with a template sublayer", ViewHides { templates: true, guides: false }),
(&group, "a group with a guide", ViewHides { templates: false, guides: true }),
] {
for (hides, hidden) in [(ViewHides::default(), false), (hides, true)] {
let outline = node_outline(n, &symbols, hides).bounding_box();
if (outline == alone) != hidden || too_many_anchors([n], hides) == hidden || too_many_marks([n], hides) == hidden {
wrong.push(format!("{what}, hidden by the view: {hidden}"));
}
}
}
assert!(wrong.is_empty(), "the marks count only what the view draws: {wrong:?}");
// A compound path made into a guide draws every path, so each stays outlined while the guides are hidden.
let guide_rect = |id: u64, r: vectorcraft_geom::Rect| {
let mut n = rect(id, r);
if let NodeKind::Path { guide, .. } = &mut n.kind {
*guide = true;
}
Arc::new(n)
};
let compound = Node::new(
NodeId(7),
NodeKind::Compound {
children: vec![
guide_rect(8, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0)),
guide_rect(9, vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0)),
],
rule: vectorcraft_geom::FillRule::EvenOdd,
},
);
let contours = |hides| node_outline(&compound, &symbols, hides).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count();
assert_eq!(contours(ViewHides { templates: false, guides: true }), contours(ViewHides::default()), "a compound path keeps its guide paths");
}
/// The overlay's limit counts the points of the members the highlight outlines: a hidden member of a group, a blend, a
/// repeat or an intertwine, and the art of a hidden sublayer, do not count toward it.
#[test]
fn the_overlay_limit_leaves_out_hidden_members() {
use super::super::outline::{too_many_anchors, too_many_marks};
use std::sync::Arc;
use vectorcraft_doc::{Appearance, LayerColor, Node};
use vectorcraft_geom::SubPath;
let points: Vec<Point> = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect();
let many = Arc::new(Node::path(NodeId(2), PathData::single(SubPath::polyline(&points, false)), Appearance::default()));
let few = Arc::new(Node::path(
NodeId(3),
vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)),
Appearance::default(),
));
let mut wrong = vec![];
for visible in [true, false] {
let mut member = (*many).clone();
member.visible = visible;
let members = || vec![Arc::new(member.clone()), few.clone()];
let group = Node::group(NodeId(1), members());
let blend = Node::new(NodeId(6), NodeKind::Blend { children: members(), spec: Default::default() });
let repeat = Node::new(NodeId(7), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(members(), 0.0, 0.0)));
let intertwine = Node::new(NodeId(8), NodeKind::Intertwine { children: members() });
let mut sublayer = Node::layer(NodeId(5), "Sublayer", LayerColor::Preset(1));
sublayer.visible = visible;
if let Some(children) = sublayer.children_mut() {
children.push(many.clone());
}
let mut layer = Node::layer(NodeId(4), "Layer", LayerColor::Preset(0));
if let Some(children) = layer.children_mut() {
children.extend([Arc::new(sublayer), few.clone()]);
}
for (n, what) in [(&group, "a group"), (&blend, "a blend"), (&repeat, "a repeat"), (&intertwine, "an intertwine"), (&layer, "a layer")] {
if too_many_anchors([n], ViewHides::default()) != visible || too_many_marks([n], ViewHides::default()) != visible {
wrong.push(format!("{what}, member visible: {visible}"));
}
}
}
assert!(wrong.is_empty(), "the limit is crossed only by visible points: {wrong:?}");
}
#[test]
fn the_anchors_of_a_container_selected_whole_draw_selected() {
let (mut app, _) = scene();
@@ -260,7 +260,7 @@ pub(super) struct SelectionWidgets {
impl SelectionWidgets {
fn new(layout: Layout) -> Self {
SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label("Selection widgets")
SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label(tl!("Selection widgets"))
}
}
+203 -10
View File
@@ -11,7 +11,7 @@ use super::artboards::names_an_artboard;
use super::cursor::still_wait;
use super::fill::{fill_view, polygon_area};
use super::marks::{HiddenMarks, thread_overlays};
use super::outline::{node_outline, walk_drawn};
use super::outline::{ViewHides, node_outline, walk_drawn};
use super::raster::{frame_view, pixel_region, placed_changes, placed_key_at, placed_since, poll_worker};
use super::*;
use crate::CacheKey;
@@ -31,9 +31,13 @@ fn shaper_selection_highlights_only_the_visible_result() {
let g = st.doc.node(st.selection.objects[0]).unwrap();
assert!(g.extras().shaper.is_some());
let symbols = st.doc.symbol_boxes();
let bounds = node_outline(g, &symbols).bounding_box();
let bounds = node_outline(g, &symbols, ViewHides::default()).bounding_box();
assert!((bounds.x0 - 100.0).abs() < 0.01 && (bounds.x1 - 200.0).abs() < 0.01, "{bounds:?}");
assert_eq!(node_outline(st.doc.node(line).unwrap(), &symbols).bounding_box().x0, 50.0, "an isolated original still shows its full outline");
assert_eq!(
node_outline(st.doc.node(line).unwrap(), &symbols, ViewHides::default()).bounding_box().x0,
50.0,
"an isolated original still shows its full outline"
);
}
#[test]
@@ -50,7 +54,7 @@ fn a_symbol_instance_is_outlined_around_its_art() {
inst = Some(n);
}
});
assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0));
assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes(), ViewHides::default()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0));
}
/// The points of `bp`'s move and line elements, in order.
@@ -111,7 +115,7 @@ fn a_turned_or_skewed_symbol_instance_is_outlined_along_its_frame() {
("skewed", Affine::skew(0.5, 0.0)),
] {
let (n, frame) = placed(a);
let got = outline_points(&node_outline(&n, &symbols));
let got = outline_points(&node_outline(&n, &symbols, ViewHides::default()));
assert!(same_points(&got, &frame), "{case}: {got:?} is not the frame {frame:?}");
}
// In perspective, the frame's corners go through the projection.
@@ -120,7 +124,7 @@ fn a_turned_or_skewed_symbol_instance_is_outlined_along_its_frame() {
in_perspective(&mut n, h);
let (_, flat) = placed(Affine::IDENTITY);
let drawn = flat.map(|p| h.apply(p).unwrap());
let got = outline_points(&node_outline(&n, &symbols));
let got = outline_points(&node_outline(&n, &symbols, ViewHides::default()));
assert!(same_points(&got, &drawn), "in perspective: {got:?} is not the projected frame {drawn:?}");
}
@@ -137,7 +141,7 @@ fn type_in_perspective_is_outlined_by_its_projected_box() {
let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.002, 0.0, 1.0]]);
in_perspective(&mut n, h);
let drawn = [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| h.apply(Point::new(x, y)).unwrap());
let got = outline_points(&node_outline(&n, &st.doc.symbol_boxes()));
let got = outline_points(&node_outline(&n, &st.doc.symbol_boxes(), ViewHides::default()));
assert!(same_points(&got, &drawn), "{got:?} is not the projected box {drawn:?}");
}
@@ -254,6 +258,99 @@ fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() {
assert_eq!(cmd_frame(&mut app, Point::new(200.0, 380.0)), "directSelection", "away from it, in the same frame");
}
/// One headless canvas frame with `events` → the points it paints: the centres of circles and rectangles and the
/// points of lines and paths.
fn painted_points(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<Pos2> {
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| show(app, ui));
out.textures_delta.clear();
let mut points = vec![];
for shape in flat_shapes(out.shapes) {
match shape {
Shape::Circle(c) => points.push(c.center),
Shape::Rect(r) => points.push(r.rect.center()),
Shape::LineSegment { points: ends, .. } => points.extend_from_slice(&ends),
Shape::Path(p) => points.extend_from_slice(&p.points),
_ => {}
}
}
points
}
/// A document with smart guides and the task bar off, every frame drawn on this thread.
fn drag_app() -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.ui.view.smart_guides = false;
app.ui.task_bar = false;
app.canvas.worker_started = true;
app
}
fn press(at: Pos2, pressed: bool) -> egui::Event {
egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }
}
/// A drag with the Selection tool draws the moved object's marks in the frame the pointer moves: at the corner the
/// object has after that frame's event, and none at the corner it had before it.
#[test]
fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() {
let mut app = drag_app();
let id = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap();
app.select_tool("selection");
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
let ctx = crate::testing::ui_context();
frame(&mut app, &ctx, vec![]);
let xf = app.canvas_view().unwrap();
let corner = |app: &VectorcraftApp| {
let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
xf.to_screen(Point::new(b.x0, b.y0))
};
let start = xf.to_screen(Point::new(180.0, 120.0));
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]);
frame(&mut app, &ctx, vec![press(start, true)]);
let mut moved = 0;
for i in 1..=6 {
let before = corner(&app);
let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(12.0, 7.0) * i as f32)]);
let after = corner(&app);
if after.distance(before) < 4.0 {
continue;
}
moved += 1;
let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0);
assert!(near(after), "move {i}: a mark at the corner after the move, {after:?}");
assert!(!near(before), "move {i}: no mark at the corner before it, {before:?}");
}
assert!(moved >= 4, "the drag moves the object: {moved} frames");
}
/// A Pen drag draws the handle it pulls out in the frame the pointer moves: its end at that frame's pointer, and
/// none at the pointer of the frame before.
#[test]
fn a_pen_drag_draws_its_handle_in_the_frame_the_pointer_moves() {
let mut app = drag_app();
app.session.execute("select.none", &json!({})).unwrap();
app.select_tool("pen");
let ctx = crate::testing::ui_context();
frame(&mut app, &ctx, vec![]);
let xf = app.canvas_view().unwrap();
let start = xf.to_screen(Point::new(105.0, 155.0));
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]);
frame(&mut app, &ctx, vec![press(start, true)]);
let mut before = start;
for i in 1..=6 {
let at = start + vec2(9.0, 5.0) * i as f32;
let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0);
assert!(near(at), "move {i}: the handle's end at this frame's pointer, {at:?}");
if i > 1 {
assert!(!near(before), "move {i}: no handle end at the pointer of the frame before, {before:?}");
}
before = at;
}
}
/// A click with the Selection tool inside an artboard makes it the active one, and Paste in
/// Place then pastes onto it, where the objects were on their own artboard (#693).
#[test]
@@ -3599,7 +3696,10 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() {
// Cancel: nothing is edited, and the document, its undo history and the selection stay.
let (before, undo, selected) =
(node(&app), app.session.doc().unwrap().history.undo.len(), app.session.active().unwrap().selection.objects.clone());
let cancelled_token = app.missing_font_edit_token.expect("the question's edit token");
answer(&mut app, false);
// A delayed approval for the cancelled question can no longer start an edit.
app.session.set_tool_option("missingFontEdit", &json!({"token": cancelled_token, "ok": true}));
timed(&mut app, 1.5, vec![]);
assert_eq!(app.session.tool_options()["editing"], json!(null));
assert!(!app.session.tool_wants_text());
@@ -3609,6 +3709,16 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() {
// A new double-click asks again; OK edits with the caret where the type was clicked.
double_click(&mut app, 3.0);
assert!(asking(&app), "asked again");
let replaced_token = app.missing_font_edit_token;
// A Type press sent through automation can replace the prompt before the user answers.
let view = app.view_info();
let point = Point::new(b.x0 + b.width() * 0.25, b.center().y);
for kind in [PointerKind::Down, PointerKind::Up] {
crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, point.x, point.y), view);
}
assert_ne!(app.missing_font_edit_token, replaced_token);
crate::dialogs::host::pump(&mut app, &ctx);
assert!(asking(&app), "the replacement question is open");
answer(&mut app, true);
timed(&mut app, 3.5, vec![]);
assert!(!asking(&app));
@@ -3919,6 +4029,23 @@ fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 {
app.session.active().unwrap().selection.objects[0].0
}
#[test]
fn the_canvas_type_editor_uses_the_interface_language() {
use crate::i18n::LangExt as _;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let ctx = crate::testing::ui_context();
ctx.enable_accesskit();
let former = crate::i18n::current();
start_typing(&mut app, &ctx);
crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap());
let out = typing_frame(&mut app, &ctx, vec![egui::Event::Text("Bonjour".into())]);
crate::i18n::set_current(former);
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
assert!(nodes.iter().any(|(_, node)| node.role() == egui::accesskit::Role::MultilineTextInput && node.label() == Some("Texte")));
}
/// Returns a key press and its release.
fn tap(key: egui::Key) -> [egui::Event; 2] {
[true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() })
@@ -4832,17 +4959,83 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() {
for view in TraceView::ALL {
group.extras_mut().trace = Some(Box::new(json!({"view":view.id()})));
let mut visited = vec![];
walk_drawn(&group, &mut |n| visited.push(n.id));
walk_drawn(&group, ViewHides::default(), &mut |n| visited.push(n.id));
assert_eq!(visited.contains(&NodeId(2)), view.shows_source());
let want = if view.shows_source() {
vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)
} else {
vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)
};
assert_eq!(node_outline(&group, &symbols).bounding_box(), want);
assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), want);
}
// Without a trace the image is an ordinary hidden member, which the canvas does not draw.
group.extras_mut().trace = None;
assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0));
assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0));
// A hidden path sent to the back of a trace is not its source image, in any view.
let mut path =
Node::path(NodeId(4), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default());
path.visible = false;
let art = Node::path(NodeId(3), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)), Appearance::default());
let mut group = Node::group(NodeId(1), vec![Arc::new(path), Arc::new(art)]);
for view in TraceView::ALL {
group.extras_mut().trace = Some(Box::new(json!({"view":view.id()})));
assert_eq!(
node_outline(&group, &symbols, ViewHides::default()).bounding_box(),
vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0),
"{view:?}"
);
}
}
/// A compound path draws every path it holds, hidden ones included, so its highlight outlines them
/// all; a group, a blend, a repeat, an intertwine and a layer leave out a hidden member, and a
/// layer the art of a hidden sublayer. A clip group shows its clipping path whether or not it is
/// hidden, and a hidden object on its own keeps its outline.
#[test]
fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() {
use std::sync::Arc;
use vectorcraft_doc::{Appearance, LayerColor, NodeId};
use vectorcraft_geom::{FillRule, PathEl};
let rect = |id: u64, r: vectorcraft_geom::Rect, visible: bool| {
let mut n = Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default());
n.visible = visible;
Arc::new(n)
};
let children = || {
vec![rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0), true), rect(3, vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0), false)]
};
let doc = vectorcraft_doc::Document::new(300.0, 300.0);
let symbols = doc.symbol_boxes();
let contours = |n: &Node| node_outline(n, &symbols, ViewHides::default()).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count();
assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Compound { children: children(), rule: FillRule::EvenOdd })), 2, "a compound path");
assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend");
assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group");
assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Intertwine { children: children() })), 1, "an intertwine");
assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(children(), 0.0, 0.0)))), 1, "a repeat");
// A clip group shows its clipping path, hidden or not, and none of the art it clips.
let clip = |visible: bool| {
let mut members = children();
members.insert(0, rect(6, vectorcraft_geom::Rect::new(10.0, 10.0, 90.0, 90.0), visible));
let mut n = Node::group(NodeId(1), members);
if let NodeKind::Group { clip, .. } = &mut n.kind {
*clip = true;
}
contours(&n)
};
assert_eq!((clip(true), clip(false)), (1, 1), "a clip group");
// A hidden object that is itself selected keeps its outline.
assert_eq!(contours(&rect(7, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0), false)), 1, "a hidden object");
let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0));
let mut sublayer = Node::layer(NodeId(4), "Sublayer", LayerColor::Preset(1));
sublayer.visible = false;
if let Some(c) = sublayer.children_mut() {
c.push(rect(5, vectorcraft_geom::Rect::new(150.0, 150.0, 200.0, 200.0), true));
}
if let Some(c) = layer.children_mut() {
c.extend(children());
c.push(Arc::new(sublayer));
}
assert_eq!(contours(&layer), 1, "a layer");
}
/// #2572: Show Text Threads links a thread's frames from the out port of one to the in port of
@@ -92,3 +92,20 @@ fn pixel_preview_compares_a_document_pixel_with_a_device_pixel() {
}
}
}
#[test]
fn out_of_range_saved_ui_scaling_keeps_actual_size_correct() {
let (a, b) = (Point::new(100.0, 100.0), Point::new(228.0, 100.0));
for (saved, expected) in [(0.5, 0.75), (3.0, 2.0), (0.0, 1.0), (f64::NAN, 1.0)] {
let (mut app, ctx, jobs) = shown(1.0, 1.5);
app.run("view.actualSize", json!({})).unwrap();
frame(&mut app, &ctx, (1.0, 1.5), vec![]);
let before = device_length(rendered(&jobs), a, b);
app.session.prefs.ui_scaling = saved;
let scale = crate::app::root_env(&app.session.prefs, 1.0, None).scale.0;
assert_eq!(scale, expected, "interface scale from saved value {saved}");
frame(&mut app, &ctx, (1.0, scale), vec![]);
let length = device_length(rendered(&jobs), a, b);
assert!((length - before).abs() < 1e-4, "saved scale {saved} changes 128 pt from {before} to {length} pixels");
}
}
+7 -2
View File
@@ -577,8 +577,13 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too
}
// Once a frame, before its press, which then uses the new tool; a held press (its grab) waits for the frame after
// the release, and a pointer over another window for the pointer to come in.
if ui.ctx().current_pass_index() == 0 && app.canvas.grab.is_none() && ui.input(|i| i.pointer.has_pointer()) {
crate::stylus::sync_eraser_tool(app);
if ui.ctx().current_pass_index() == 0
&& app.canvas.grab.is_none()
&& ui.input(|i| i.pointer.has_pointer())
&& crate::stylus::sync_eraser_tool(app)
{
// Before the press, which holds what the host was told about the wheel until its release.
crate::stylus::sync_wheel_use(app);
}
// A press on the canvas that a view tool takes (a middle-button pan, a held Space's Hand) counts as a press
// elsewhere for the clicks the tool's double-click or triple-click compares.
+2 -2
View File
@@ -275,7 +275,7 @@ impl ShapeWidgets {
}
fn new(marks: Vec<Mark>) -> Self {
ShapeWidgets { common: Common::new(), marks }.label("Shape widgets")
ShapeWidgets { common: Common::new(), marks }.label(tl!("Shape widgets"))
}
}
@@ -334,7 +334,7 @@ impl Component for ShapeWidgets {
}
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
access.description("Shape widgets");
access.description(tl!("Shape widgets"));
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
+8 -35
View File
@@ -120,48 +120,21 @@ pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui, controls: AnchorCon
}
}
/// The selected paths' eligible corners, as document lengths, beside the anchor controls.
/// Explicit partial selections with no corners contribute no target (unlike `picked`'s fallback).
/// The Corners link and the radius of the selected paths' picked corners
/// ([`crate::panels::picked_corners`]), beside the anchor controls. The link opens the Corners
/// pop-up for those corners; a narrow bar leaves out the link and the field together.
fn corner_radius(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some(st) = app.session.active() else { return };
let mut items = Vec::new();
let mut radius: Option<f64> = None;
let mut mixed = false;
for &id in &st.selection.objects {
let Some(lc) = st.doc.node(id).and_then(vectorcraft_doc::LiveCorners::of) else { continue };
let corners = st.selection.partial(id).map_or_else(|| lc.all(), |anchors| lc.corners_of(anchors));
if corners.is_empty() {
continue;
}
for &k in &corners {
// Keep absolute requested radii, even when their drawing is fitted smaller. Relative
// storage is a fraction, but the field and setLiveShape both consume document lengths.
let value = if lc.radii_relative() { lc.radius(k) * lc.corner(k).map_or(0.0, |c| c.max_radius()) } else { lc.radius(k) };
if let Some(first) = radius {
mixed |= (first - value).abs() >= 1e-9;
} else {
radius = Some(value);
}
}
items.push(json!({"id": id, "corners": corners}));
}
if items.is_empty() {
return;
}
let Some(picked) = crate::panels::picked_corners(app) else { return };
let label = tl!("Corner Radius:");
let shown = if mixed { None } else { radius };
// PLAN: assumed `crate::canvas::general_lengths(app) -> LengthUnits` (cv.B5b, canvas-w15).
let lengths = crate::canvas::general_lengths(app);
let mut typed = None;
group(ui, rank::GROUP, |ui| {
Field::new(label).show(ui, |ui, _| {
let number = NumberField::length(label, Bind::given(shown), lengths).show(ui);
typed = number.edit.events.committed().copied().flatten().or(typed);
});
crate::panels::corners_link(app, ui);
let number = NumberField::length(label, Bind::given(picked.radius), lengths).show(ui);
typed = number.edit.events.committed().copied().flatten().or(typed);
});
if let Some(radius) = typed {
// App::run reports any command failure in the status bar, as the other inline fields do.
app.run("object.setLiveShape", json!({"items": items, "radius": radius.max(0.0)})).ok();
crate::panels::set_picked_corners(app, &picked, json!({"radius": radius.max(0.0)}));
}
}
+3 -1
View File
@@ -32,7 +32,8 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
.map(|d| d.doc.artboards.iter().enumerate().map(|(i, a)| Entry::new(i, format!("{} {}", i + 1, a.name))).collect())
.unwrap_or_default();
let angles: Vec<Entry<usize>> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect();
let rotation = app.view().map_or(0.0, |v| v.rotation);
let view = app.view();
let rotation = view.map_or(0.0, |v| v.rotation);
let turned = ROTATE_VIEW_ANGLES.iter().position(|(_, a)| (rotation - a).abs() < 1e-9).unwrap_or(usize::MAX);
// An angle between the presets, from the Rotate View tool or `view.rotate`, shows in whole degrees; adding 0.0
// turns the -0 of a small negative angle into 0.
@@ -80,6 +81,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles)
.placeholder(angle.clone())
.look(SelectLook::Filled)
.enabled(view.is_some())
.show(ui)
.value()
.copied();
+22 -3
View File
@@ -224,11 +224,30 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) {
crumbs.push((None, false, pn.clone()));
}
// Up one level: the isolated object's parent group, or `object.exitIsolation`, which goes from an
// isolated sublayer to its parent layer and otherwise leaves isolation mode.
let up = match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) {
// isolated sublayer to its parent layer, from a group in a symbol's art to the symbol's layer, and
// otherwise leaves isolation mode. While a pattern is edited the back arrow is Done. Screen readers
// call it by what it does.
let parent_group = ancestry.iter().rev().nth(1).copied().filter(|p| st.doc.node(*p).is_some_and(|n| !n.is_layer()));
let up = match parent_group {
Some(parent) => ("object.isolate", json!({ "id": parent.0 })),
None => ("object.exitIsolation", json!({})),
};
let symbol_layer = st.doc.symbol_edit.as_ref().map(|e| e.layer);
let up_one = parent_group.is_some()
|| symbol_layer.is_some_and(|l| l != iso && ancestry.contains(&l))
|| (st.doc.mask_edit.is_none()
&& symbol_layer.is_none()
&& st.doc.node(iso).is_some_and(|n| n.is_layer())
&& st.doc.parent_of(iso).is_some_and(|p| st.doc.is_editable(p)));
let back_name = if pattern_edit.is_some() {
tl!("Done")
} else if up_one {
tl!("Back One Level")
} else if symbol_layer == Some(iso) {
tl!("Exit Symbol Editing Mode")
} else {
tl!("Exit Isolation Mode")
};
let entries: Vec<Entry<usize>> = crumbs.iter().enumerate().map(|(i, (_, _, name))| Entry::new(i, name.clone())).collect();
let mut nav: Option<(&str, serde_json::Value)> = None;
let mut pattern_cmd: Option<&str> = None;
@@ -237,7 +256,7 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) {
let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(area));
Bar::new(tl!("Isolation mode"), BarKind::Options).show(&mut bar_ui, |ui, _| {
Row::new().fill().senses_surface().show(ui, |ui, cx| {
if IconButton::new(craft::behavior::IconId::new("chevron_left")).label(tl!("Back")).show(ui).clicked() {
if IconButton::new(craft::behavior::IconId::new("chevron_left")).label(back_name).show(ui).clicked() {
if pattern_edit.is_some() {
pattern_cmd = Some("object.pattern.done");
} else {
+137 -9
View File
@@ -743,6 +743,20 @@ fn the_status_bar_rotation_box_shows_the_view_angle() {
assert_eq!(bar.tree().value_of(rotation.node), Some("-45°"));
}
#[test]
fn the_status_bar_rotation_picker_requires_a_document_view() {
let mut bar = status_readout_app();
bar.app().run("file.close", json!({})).unwrap();
assert!(bar.app().view().is_none());
bar.settle().click("Rotation").settle();
assert!(bar.find("-45°").is_none(), "the picker stays closed without a view");
bar.app().run("file.new", json!({"width": 100, "height": 100})).unwrap();
bar.settle().click("Rotation").settle();
bar.click("-45°").settle();
assert_eq!(bar.app().view().map(|v| v.rotation), Some(-45.0));
}
/// While background work runs the status bar shows it where the message was, with the count of the jobs after the
/// first, and the message of the work's result takes the same place when it ends. Screen readers find the progress.
#[test]
@@ -1277,9 +1291,28 @@ fn isolation_shown(app: crate::VectorcraftApp) -> Shown {
/// A point on the isolation bar's own surface: right of its crumbs, at the end of the path, which fills the bar up
/// to the pattern editing buttons at its right.
fn isolation_bar_surface(bar: &mut Shown) -> egui::Pos2 {
let back = bar.named("Back");
let path = bar.named("Isolation path");
egui::pos2(path.rect.right() - 8.0, back.center().y)
egui::pos2(path.rect.right() - 8.0, path.center().y)
}
/// The names of the isolation bar's controls in the latest frame that screen readers read with `role`, sorted.
fn isolation_names(bar: &Shown, role: Role) -> Vec<String> {
let tree = bar.tree();
let mut names: Vec<String> =
tree.keys().into_iter().filter(|key| tree.role_of(*key) == Some(role)).filter_map(|key| tree.name_of(key)).map(str::to_owned).collect();
names.sort();
names
}
/// The isolation bar's back arrow: the leftmost button named `name`.
fn isolation_back(bar: &mut Shown, name: &str) -> Target {
bar.frame(Vec::new());
let tree = bar.tree();
let keys: Vec<_> = tree.keys().into_iter().filter(|key| tree.role_of(*key) == Some(Role::BUTTON) && tree.name_of(*key) == Some(name)).collect();
keys.into_iter()
.filter_map(|key| bar.fixture.target(key))
.min_by(|a, b| a.rect.left().total_cmp(&b.rect.left()))
.unwrap_or_else(|| panic!("no {name:?} button in {:?}", bar.names()))
}
/// #4468: In nested isolation, clicking the back button steps up one level in the hierarchy,
@@ -1308,15 +1341,15 @@ fn isolation_bar_navigation_and_back_button_steps_up() {
let isolation = |bar: &Shown| bar.app().session.active().unwrap().isolation;
// Clicking back from `a` steps up to parent group `g1`
bar.click("Back");
bar.click("Back One Level");
assert_eq!(isolation(&bar), Some(NodeId(g1)));
// Clicking back from `g1` steps up to grandparent group `g2`
bar.click("Back");
bar.click("Back One Level");
assert_eq!(isolation(&bar), Some(NodeId(g2)));
// Clicking back from `g2` (parent is layer) exits isolation mode completely
bar.click("Back");
bar.click("Exit Isolation Mode");
assert_eq!(isolation(&bar), None);
// Deep isolate again to test clicking ancestor breadcrumb directly
@@ -1355,11 +1388,11 @@ fn isolation_bar_back_button_steps_up_through_sublayers() {
let steps = |bar: &Shown| bar.app().session.doc().unwrap().history.undo.len();
let before = steps(&bar);
bar.click("Back");
bar.click("Back One Level");
assert_eq!(isolation(&bar), Some(mid), "back from the deepest sublayer");
bar.click("Back");
bar.click("Back One Level");
assert_eq!(isolation(&bar), Some(top), "back from the middle sublayer");
bar.click("Back");
bar.click("Exit Isolation Mode");
assert_eq!(isolation(&bar), None, "back from the top-level layer");
assert_eq!(steps(&bar), before, "no undo step");
@@ -1422,7 +1455,8 @@ fn isolation_bar_background_click_leaves_pattern_edit_open() {
let st = app.session.active().unwrap();
assert!(st.doc.pattern_edit.is_some() && st.isolation.is_some(), "pattern editing stays open");
}
bar.click("Back");
let back = isolation_back(&mut bar, "Done");
bar.click_on(&back);
let app = bar.app();
let st = app.session.active().unwrap();
assert!(st.doc.pattern_edit.is_none() && st.isolation.is_none(), "the back arrow ends pattern editing");
@@ -1506,6 +1540,72 @@ fn isolation_bar_click_on_the_current_name_exits() {
assert_eq!(bar.app().session.active().unwrap().isolation, None);
}
/// Screen readers call the isolation bar's back arrow by what it does: Back One Level, Exit Isolation Mode, Exit
/// Symbol Editing Mode, or Done while a pattern is edited, in the UI's language. Each crumb of the levels above is
/// a link with the name it shows, and the current object's name is not a control.
#[test]
fn the_isolation_bars_controls_have_screen_reader_names() {
use vectorcraft_doc::NodeId;
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
let rect = |app: &mut crate::VectorcraftApp, x: f64| {
app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap()
};
let (a, b) = (rect(&mut app, 10.0), rect(&mut app, 50.0));
app.run("select.set", json!({"ids": [a, b]})).unwrap();
app.run("object.group", json!({})).unwrap();
let name = |app: &crate::VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().display_name();
let st = app.session.active().unwrap();
let (layer, group) = (st.doc.layer_of(NodeId(a)).unwrap(), st.doc.parent_of(NodeId(a)).unwrap());
let (layer_name, group_name) = (name(&app, layer), name(&app, group));
let mut bar = isolation_shown(app);
let shown = |bar: &mut Shown, role: Role| {
bar.frame(Vec::new());
isolation_names(bar, role)
};
// A path in a group: back goes to the group.
bar.app().run("object.isolate", json!({"id": a})).unwrap();
assert_eq!(shown(&mut bar, Role::BUTTON), ["Back One Level"]);
let mut crumbs = vec![layer_name.clone(), group_name.clone()];
crumbs.sort();
assert_eq!(shown(&mut bar, Role::LINK), crumbs, "the current object's name is not a link");
// The group itself: back leaves isolation mode.
bar.app().run("object.isolate", json!({"id": group.0})).unwrap();
assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Isolation Mode"]);
assert_eq!(shown(&mut bar, Role::LINK), std::slice::from_ref(&layer_name));
// An isolated sublayer: back goes to its parent layer, and from the top-level layer it leaves.
let sub = bar.app().run("layer.newSublayer", json!({"parent": layer.0, "name": "Sublayer B"})).unwrap()["id"].as_u64().unwrap();
bar.app().run("object.isolate", json!({"id": sub})).unwrap();
assert_eq!(shown(&mut bar, Role::BUTTON), ["Back One Level"]);
bar.app().run("object.isolate", json!({"id": layer.0})).unwrap();
assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Isolation Mode"]);
bar.app().run("object.isolate", json!({"id": group.0})).unwrap();
// In German.
crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered"));
let german = shown(&mut bar, Role::BUTTON);
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(german, ["Isolationsmodus beenden"]);
bar.app().run("object.exitIsolation", json!({"all": true})).unwrap();
// Pattern editing: back is Done, beside Save a Copy, Done and Cancel.
let c = rect(&mut bar.app(), 200.0);
bar.app().run("select.set", json!({"ids": [c]})).unwrap();
bar.app().run("object.pattern.make", json!({"name": "Dots", "width": 20, "height": 20})).unwrap();
assert_eq!(shown(&mut bar, Role::BUTTON), ["Cancel", "Done", "Done", "Save a Copy"]);
bar.app().run("object.pattern.cancel", json!({})).unwrap();
// Symbol editing mode: back leaves it.
let d = rect(&mut bar.app(), 300.0);
bar.app().run("select.set", json!({"ids": [d]})).unwrap();
bar.app().run("symbol.new", json!({"name": "Box"})).unwrap();
bar.app().run("symbol.edit", json!({"name": "Box"})).unwrap();
assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Symbol Editing Mode"]);
}
/// The Control bar's Isolate Selected Object isolates a path inside a group that Direct
/// Selection selected, and Exit Isolation Mode leaves with the path selected. Type, symbol
/// instances, blends, two objects and an envelope's contents get no isolate button, and pattern
@@ -2746,6 +2846,34 @@ fn the_anchor_points_group_holds_convert_and_anchors() {
assert!(has(&bar, "Anchor Point") && has(&bar, "Stroke:"), "{bar:?}");
}
/// With three corners of a path Direct-Selected, the Control bar's Corners link opens the Corners
/// pop-up; a kind picked there sets those three corners and leaves the fourth, in one undo step.
#[test]
fn the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners() {
use vectorcraft_geom::shapes::CornerKind;
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [id]})).unwrap();
app.run("object.expandShape", json!({})).unwrap();
app.select_tool("directSelection");
app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap();
let mut bar = crate::tests::panel_harness::Panel::new(app, crate::chrome::control_bar);
bar.room(egui::vec2(2400.0, 400.0)).frame();
assert!(bar.shows("Corners") && !bar.shows("Chamfer"), "the pop-up starts closed");
bar.click("Corners");
for name in ["Round", "Inverted Round", "Chamfer", "Radius", "Relative", "Absolute"] {
assert!(bar.shows(name), "the pop-up has {name}");
}
let depth = bar.app().session.doc().unwrap().history.undo.len();
bar.click("Chamfer");
assert_eq!(bar.app().session.doc().unwrap().history.undo.len(), depth + 1, "one undo step");
let n = bar.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone();
let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap();
assert_eq!((0..4).map(|k| lc.kind(k)).collect::<Vec<_>>(), [CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Round]);
}
/// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard
/// controls while it has room, and the Distribute buttons for two or more selected artboards with
/// Align to Artboard and three or more with Align to Selection. A
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff. Show more