Merge main into feat/scripts-startup-scripts

This commit is contained in:
dotCooCoo committed 2026-11-26 11:04:04 -08:00
commit bacc27e2f1
147 files changed
+9531 -483

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.
+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}");
}
}
+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}");
}
+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);
+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)
})
@@ -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"),
+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).
+34 -63
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.
@@ -1028,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 {
@@ -1098,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]
+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(());
+69 -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]
+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)]);
+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:?}");
}
+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);
}
+2
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`).
(
+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}");
}
+6 -2
View File
@@ -707,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
+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
@@ -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"))
}
}
+17
View File
@@ -4029,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() })
@@ -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");
}
}
+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();
+42
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]
@@ -2832,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
+1
View File
@@ -28,6 +28,7 @@ pub(crate) mod command;
pub mod composite_fonts;
pub mod confirm;
pub mod corners;
pub mod curvature_circle_options;
pub mod custom_dictionary;
pub mod dimension;
mod document_setup;
+50 -9
View File
@@ -8,6 +8,7 @@
//! empty, or Data Sets without a document, is an error and the dialog stays open.
use std::hash::Hash;
use std::sync::Arc;
use craft::automation::actions::Action;
use craft::host::PickRequest;
@@ -131,6 +132,8 @@ pub(crate) enum Folder {
/// The Batch dialog on the dialog host.
pub struct BatchDialog {
id: DialogId,
/// Identifies this opening even when another Batch dialog reuses `id`.
folder_owner: Arc<()>,
/// The index of the action's set.
pub set: usize,
/// The index of the action in its set.
@@ -150,13 +153,13 @@ impl BatchDialog {
&self.form.values
}
/// The Browse presses since the last call.
pub(crate) fn take_asked(&mut self) -> Vec<Folder> {
std::mem::take(&mut self.asked)
/// The Browse presses since the last call and the opening that made them.
pub(crate) fn take_asked(&mut self) -> (Arc<()>, Vec<Folder>) {
(self.folder_owner.clone(), std::mem::take(&mut self.asked))
}
/// Writes the folder the picker answered into its row.
pub(crate) fn set_folder(&mut self, which: Folder, path: String) {
fn set_folder(&mut self, which: Folder, path: String) {
match which {
Folder::Source => self.form.values.folder = path,
Folder::Destination => self.form.values.destination_folder = path,
@@ -176,6 +179,7 @@ pub fn open(app: &mut VectorcraftApp, set: usize, action: usize) -> Result<Value
refuse_steps(&included_commands(a))?;
let dialog = BatchDialog {
id: dialog_id(KEY),
folder_owner: Arc::new(()),
set,
action,
action_name: a.name.clone(),
@@ -207,9 +211,9 @@ pub(crate) fn overwrites_one_file(app: &VectorcraftApp, set: usize, action: usiz
vectorcraft_engine::cmd::fileio::batch_overwrites_one_file(&app.session, &params(fields, "", commands))
}
/// Files the request for the folder behind `which`; the answer goes into the open dialog's row.
/// Files the request for `which`; the answer goes to the row of the Batch dialog that asked.
// PLAN: PathRow shows Browse whether or not the host offers pickers; `file_asks::ask` says so when it cannot ask.
pub(crate) fn ask_folder(app: &mut VectorcraftApp, which: Folder) {
pub(crate) fn ask_folder(app: &mut VectorcraftApp, owner: Arc<()>, which: Folder) {
let title = match which {
Folder::Source => crate::i18n::t("Source Folder"),
Folder::Destination => crate::i18n::t("Destination Folder"),
@@ -218,10 +222,9 @@ pub(crate) fn ask_folder(app: &mut VectorcraftApp, which: Folder) {
if let Some(path) = picked.paths().first()
&& let Some(dialogs) = app.dialogs()
{
let path = path.to_string_lossy().into_owned();
dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<BatchDialog>() {
dialog.set_folder(which, path);
if let Some(dialog) = host.get_mut::<BatchDialog>().filter(|d| Arc::ptr_eq(&d.folder_owner, &owner)) {
dialog.set_folder(which, path.to_string_lossy().into_owned());
}
});
}
@@ -437,6 +440,44 @@ mod tests {
});
}
#[test]
fn batch_folder_answers_belong_to_the_dialog_that_asked() {
let step = ActionStep::new("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}));
let mut app = app_with(vec![step]);
let picker = crate::tests::picks::scripted(&mut app);
let ctx = app.ui_ctx.clone().unwrap();
let dialogs = app.dialogs().unwrap();
let request_folders = |app: &mut VectorcraftApp| {
dialogs.with(|host| host.get_mut::<BatchDialog>().unwrap().asked.extend([Folder::Source, Folder::Destination]));
pump(app, &ctx);
};
let folders = || {
dialogs.with(|host| {
let fields = host.get::<BatchDialog>().unwrap().fields();
(fields.folder.clone(), fields.destination_folder.clone())
})
};
let answer = |app: &mut VectorcraftApp, source: &str, destination: &str| {
picker.answer(&[destination]);
picker.answer(&[source]);
file_asks::poll(app);
};
open(&mut app, 0, 0).unwrap();
request_folders(&mut app);
assert_eq!(picker.requests().len(), 2);
dialogs.with(|host| host.cancel::<BatchDialog>(&ctx));
open(&mut app, 0, 0).unwrap();
set_fields(&app, &[("folder", json!("new-source")), ("destinationFolder", json!("new-destination"))]);
answer(&mut app, "old-source", "old-destination");
assert_eq!(folders(), ("new-source".into(), "new-destination".into()));
request_folders(&mut app);
assert_eq!(picker.requests().len(), 4);
answer(&mut app, "picked-source", "picked-destination");
assert_eq!(folders(), ("picked-source".into(), "picked-destination".into()));
}
/// Batch plays an action recorded with a key its command no longer reads, as Play does.
#[test]
fn an_action_with_a_key_no_longer_read_still_plays_in_a_batch() {
+5 -5
View File
@@ -363,13 +363,13 @@ fn push_app_data(app: &VectorcraftApp) {
}
}
/// The folder picks the open Batch dialog asked for: each goes to the app's folder request, whose
/// answer is written into the dialog.
/// Files the folder picks the Batch dialog asked for with the identity of that opening.
fn ask_batch_folders(app: &mut VectorcraftApp) {
let Some(dialogs) = app.dialogs() else { return };
let asked = dialogs.with(|host| host.get_mut::<BatchDialog>().map(BatchDialog::take_asked).unwrap_or_default());
for which in asked {
super::action_batch::ask_folder(app, which);
let asked = dialogs.with(|host| host.get_mut::<BatchDialog>().map(BatchDialog::take_asked));
let Some((owner, folders)) = asked else { return };
for which in folders {
super::action_batch::ask_folder(app, owner.clone(), which);
}
}
+162 -3
View File
@@ -44,6 +44,8 @@ struct Open {
preview: LivePreview,
/// Set Role Swatch: the role the Swatch row was last filled for.
filled_for: Option<String>,
/// The uid of the document whose objects the dialog opened on (`__doc`), for Set Fold Angle.
doc: Option<u64>,
/// Names this dialog's own open among reopenings of the same command, for its OK and Cancel.
token: Arc<()>,
}
@@ -66,7 +68,8 @@ impl Setting {
}
/// Opens the parameter dialog of `command`, headed `label`, on `params` (a menu item's own values, `__params` for the
/// fixed ones and `__rowGutterLinked` for Area Type Options' linked Row Gutter).
/// fixed ones, `__rowGutterLinked` for Area Type Options' linked Row Gutter and `__doc` for the uid of the document
/// whose objects the dialog edits).
pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut params: Map<String, Value>) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
if let Some(old) = app.command_dialog.open.take() {
@@ -77,6 +80,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par
_ => Map::new(),
};
let linked = params.remove("__rowGutterLinked").and_then(|v| v.as_f64());
let doc = params.remove("__doc").and_then(|v| v.as_u64());
params.retain(|k, _| !k.starts_with("__"));
let previews = previews(command, &params);
let setting = Setting::of(app);
@@ -104,6 +108,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par
previews,
preview: LivePreview::default(),
filled_for: None,
doc,
token,
});
Ok(Value::Null)
@@ -162,9 +167,14 @@ fn step(app: &mut VectorcraftApp, open: &mut Open) {
}
/// OK: runs the command on the dialog's values (keeping a preview as the one undo step) and closes the dialog; an
/// error keeps it open with the reason under its rows.
/// error keeps it open with the reason under its rows. A dialog opened on one document's objects (`__doc`, its uid)
/// closes as Cancel does and runs nothing once another document is the active one.
fn confirm(app: &mut VectorcraftApp, token: &Arc<()>, fields: &DialogFields) -> Result<Value, String> {
let open = app.command_dialog.open.take_if(|o| Arc::ptr_eq(&o.token, token)).ok_or("the dialog is gone")?;
if open.doc.is_some() && open.doc != app.session.active().map(|st| st.uid) {
open.preview.cancel(app);
return Ok(Value::Null);
}
let params = command_params(&open.command, &open.opening, Setting::of(app));
let value = call(&open.command, &open.fixed, open.linked, form::json_of(&params, fields));
let result = if open.previews {
@@ -222,7 +232,17 @@ fn row(command: &str, key: &str, value: &Value, setting: Setting) -> Option<Para
Value::Bool(on) => Param::new(key, label, ParamKind::bool(*on)),
Value::Number(n) => {
let whole = n.is_i64() || n.is_u64();
let mut param = Param::number(key, label, n.as_f64().unwrap_or(0.0), 1.0, if whole { 0 } else { 3 });
let range = number_range(command, key);
// A ranged number (a fold angle) is shown to every place it keeps.
let decimals = match range {
Some(_) => u32::try_from(crate::addons::packaging::angle_places(n.as_f64())).unwrap_or(u32::MAX),
None if whole => 0,
None => 3,
};
let mut param = Param::number(key, label, n.as_f64().unwrap_or(0.0), 1.0, decimals);
if let Some(range) = range {
param = param.bounds(Some(*range.start()), Some(*range.end()));
}
if lengths(command).contains(&key) {
param = param.length(setting.units);
if let Some(range) = length_range(command, key) {
@@ -358,6 +378,15 @@ pub(crate) fn length_range(command: &str, key: &str) -> Option<std::ops::RangeIn
}
}
/// The range of a number parameter (not a distance) of the commands this dialog edits, where the
/// command has one: the field keeps what is typed within it.
fn number_range(command: &str, key: &str) -> Option<std::ops::RangeInclusive<f64>> {
match (command, key) {
(crate::addons::packaging::SET_FOLD_ANGLE, "angle") => Some(crate::addons::packaging::FOLD_ANGLES),
_ => None,
}
}
/// The order the fields of the commands this dialog edits come in, where the order of their
/// names isn't it (the rest follow, by name).
fn order(command: &str) -> &'static [&'static str] {
@@ -781,4 +810,134 @@ mod tests {
}
}
}
use crate::addons::packaging::{SET_FOLD_ANGLE, SET_ROLE};
/// A window app with two rectangles, `a` a crease and `b` a cut line, nothing selected → (app, a, b).
fn fold_lines() -> (VectorcraftApp, u64, u64) {
let mut app = windowed();
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let rect = |app: &mut VectorcraftApp, x: f64| {
app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()
};
let (a, b) = (rect(&mut app, 20.0), rect(&mut app, 100.0));
app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap();
app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap();
app.run("select.none", json!({})).unwrap();
(app, a, b)
}
/// The angle the open Set Fold Angle… dialog shows.
fn shown_angle(app: &VectorcraftApp) -> Option<f64> {
let id = id_of(app);
app.dialogs().unwrap().with(|h| h.get_by_id::<HostedParamDialog>(id).and_then(|d| d.fields().number("angle")))
}
/// Set Fold Angle… from its menu item → the angle its dialog opens on, the dialog then canceled; `None` when no
/// dialog opens.
fn opened_angle(app: &mut VectorcraftApp) -> Option<f64> {
crate::menus::invoke(app, SET_FOLD_ANGLE, json!({}));
app.command_dialog.open.as_ref()?;
pump(app);
let angle = shown_angle(app);
answer_cancel(app);
angle
}
/// The angle the selection's fold lines fold at, after selecting `id`.
fn fold_angle(app: &mut VectorcraftApp, id: u64) -> Option<f64> {
app.run("select.set", json!({"ids": [id]})).unwrap();
vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle
}
#[test]
fn set_fold_angle_opens_its_dialog_on_the_selected_lines_angle() {
let (mut app, a, b) = fold_lines();
app.run("select.set", json!({"ids": [a]})).unwrap();
assert_eq!(opened_angle(&mut app), Some(90.0), "a crease folds at 90° until it has an angle of its own");
app.run(SET_FOLD_ANGLE, json!({"angle": 45})).unwrap();
assert_eq!(opened_angle(&mut app), Some(45.0));
// The cut line does not fold, so the crease's angle is still the one shown.
app.run("select.set", json!({"ids": [a, b]})).unwrap();
assert_eq!(opened_angle(&mut app), Some(45.0));
// Lines that differ open on 90°.
let c = app.run("shape.rectangle", json!({"x": 180, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
app.run(SET_ROLE, json!({"role": "partialCut", "ids": [c]})).unwrap();
app.run("select.set", json!({"ids": [a, c]})).unwrap();
assert_eq!(opened_angle(&mut app), Some(90.0));
// With only a cut line selected there is nothing to set: no dialog opens, and ui.menuDialog gives the reason.
app.run("select.set", json!({"ids": [b]})).unwrap();
assert_eq!(opened_angle(&mut app), None);
assert!(app.command_dialog.open.is_none());
let e = app.run("ui.menuDialog", json!({"command": SET_FOLD_ANGLE})).unwrap_err();
assert!(e.contains("select a crease, partial cut or perforation line"), "{e}");
app.run("select.set", json!({"ids": [a]})).unwrap();
app.run("ui.menuDialog", json!({"command": SET_FOLD_ANGLE})).unwrap();
pump(&mut app);
assert_eq!(shown_angle(&app), Some(45.0));
answer_cancel(&mut app);
// The options dialog opened with an angle keeps it.
crate::menus::invoke(&mut app, "ui.paramDialog", json!({"command": SET_FOLD_ANGLE, "label": "Set Fold Angle", "params": {"angle": 30}}));
pump(&mut app);
assert_eq!(shown_angle(&app), Some(30.0));
}
/// Set Fold Angle…'s OK changes the lines the dialog opened on, even when the selection changes while it is open
/// (a remote command can change it): the other crease keeps its angle.
#[test]
fn set_fold_angle_s_ok_changes_the_lines_the_dialog_opened_on() {
let (mut app, a, b) = fold_lines();
app.run(SET_ROLE, json!({"role": "crease", "ids": [b]})).unwrap();
app.run("select.set", json!({"ids": [a]})).unwrap();
crate::menus::invoke(&mut app, SET_FOLD_ANGLE, json!({}));
pump(&mut app);
app.run("select.set", json!({"ids": [b]})).unwrap();
set(&mut app, "angle", json!(30.0));
answer_ok(&mut app);
assert!(app.command_dialog.open.is_none(), "OK closes the dialog");
assert_eq!(fold_angle(&mut app, a), Some(30.0), "the line the dialog opened on");
assert_eq!(fold_angle(&mut app, b), Some(90.0), "the line selected later keeps its role's angle");
}
/// Set Fold Angle…'s OK changes nothing once another document is the active one, even a line there with the same
/// id as the line the dialog opened on.
#[test]
fn set_fold_angle_s_ok_changes_nothing_in_another_document() {
let (mut app, a, _) = fold_lines();
app.run("select.set", json!({"ids": [a]})).unwrap();
crate::menus::invoke(&mut app, SET_FOLD_ANGLE, json!({}));
pump(&mut app);
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let other = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
assert_eq!(other, a, "the same id in the other document");
app.run(SET_ROLE, json!({"role": "crease", "ids": [other]})).unwrap();
set(&mut app, "angle", json!(30.0));
answer_ok(&mut app);
assert!(app.command_dialog.open.is_none(), "OK closes the dialog");
assert_eq!(fold_angle(&mut app, other), Some(90.0), "the other document's line keeps its role's angle");
assert!(app.session.set_active(0));
assert_eq!(fold_angle(&mut app, a), Some(90.0), "the first document's line is left as it was");
}
/// Set Fold Angle…'s Angle row takes -180° to 180°, the range the command takes, and shows every place the angle
/// it opens on has.
#[test]
fn set_fold_angle_s_angle_row_keeps_the_commands_range() {
let (mut app, a, _) = fold_lines();
app.run(SET_FOLD_ANGLE, json!({"angle": 179.999999, "ids": [a]})).unwrap();
app.run("select.set", json!({"ids": [a]})).unwrap();
let param = row(SET_FOLD_ANGLE, "angle", &json!(179.999999), Setting::of(&app)).expect("a row");
match param.kind {
ParamKind::Number { min, max, decimals, .. } => assert_eq!((min, max, decimals), (Some(-180.0), Some(180.0), 6)),
_ => panic!("a number row"),
}
crate::menus::invoke(&mut app, SET_FOLD_ANGLE, json!({}));
pump(&mut app);
assert_eq!(shown_angle(&app), Some(179.999999));
let (ctx, id) = (app.ui_ctx.clone().unwrap(), id_of(&app));
assert!(app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, id, "angle", json!(181))).is_err(), "past the range");
set(&mut app, "angle", json!(-180));
answer_ok(&mut app);
assert_eq!(fold_angle(&mut app, a), Some(-180.0));
}
}
@@ -0,0 +1,84 @@
//! Curvature Circle Tool Options (double-click the Curvature Circle tool, or `tool.options`): Snap
//! Tolerance is how near, in screen points, a path pulls the pointer (Smart Guides' Snapping
//! Tolerance applies when it is larger); with Snap with Smart Guides Off unchecked, the pointer
//! reaches no further than the selection tolerance while Smart Guides are off; Annotate Radius
//! off hides the radius label; Anchors at Standard Positions off gives the circle an anchor where
//! it touches the path and one every 90° from there; Use the Radius of Circular Arcs off gives the
//! curve's own curvature on the curve of a circular arc too. OK sets them with
//! `tool.setOption {tool: "curvatureCircle", values}`; they last across tool switches and are saved
//! with the preferences.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::UnitKind;
use serde_json::{Value, json};
use vectorcraft_tools::curvature_circle::{DEFAULT_SNAP, ID as TOOL, SNAP_RANGE};
use super::{form, host, tool_options};
use crate::VectorcraftApp;
/// The dialog kind of Curvature Circle Tool Options.
pub const KIND: &str = "curvatureCircleOptions";
/// The switches the dialog edits, in the order it shows them, with their labels.
const SWITCHES: [(&str, &str); 4] = [
("snapWithoutGuides", "Snap with Smart Guides Off"),
("annotateRadius", "Annotate Radius"),
("standardAnchors", "Anchors at Standard Positions"),
("constantRadius", "Use the Radius of Circular Arcs"),
];
/// The rows: Snap Tolerance, then the switches.
fn params() -> Vec<Param> {
let (min, max) = SNAP_RANGE;
let snap = Param::number("snapTolerance", tl!("Snap Tolerance:"), DEFAULT_SNAP, 1.0, 1).unit(UnitKind::Pixels).bounds(Some(min), Some(max));
std::iter::once(snap).chain(SWITCHES.iter().map(|(key, label)| Param::new(*key, tl!(*label), ParamKind::bool(true)))).collect()
}
/// Open the tool's options with their current values; an error when there is no window to show them in.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let params = params();
let options = app.session.tool_options_of(TOOL);
let fields = options.as_object().map(|m| form::fields_of(&params, m)).unwrap_or_default();
let (title, shown) = (tool_options::title(TOOL), params.clone());
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| tool_options::set_options(app, TOOL, form::json_of(&params, &result.fields));
let opened = app.ui_ctx.clone().and_then(|ctx| {
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |f| ParamDialog::new(KIND, title.clone(), shown.clone()).values(Bind::bound(f)));
host::open_held(app, dialog, ok)
});
if opened.is_none() {
let message = tl!("No window to show the dialog in.").to_string();
app.status(message.clone());
return Err(message);
}
Ok(json!({ "dialog": KIND }))
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_engine::Session;
/// `tool.setOption` takes only the values the options take, and an invalid one changes none.
#[test]
fn invalid_values_are_errors_and_change_nothing() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
for values in [
json!({"annotateRadius": false, "constantRadius": "no"}),
json!({"annotateRadius": false, "snapTolerance": 0}),
json!({"annotateRadius": false, "size": 3}),
] {
assert!(app.run("tool.setOption", json!({"tool": TOOL, "values": values})).is_err(), "{values}");
assert_eq!(app.session.tool_options_of(TOOL)["annotateRadius"], json!(true));
}
}
/// Without a window the dialog cannot open, and `tool.options` says so instead of reporting it open.
#[test]
fn without_a_window_opening_the_options_is_an_error() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
assert!(app.run("tool.options", json!({"tool": TOOL})).is_err());
}
}
@@ -1123,4 +1123,76 @@ mod tests {
let preset = fields(json!({"gridColors": "blue"}));
assert_eq!(super::preview_grid(&preset, &setup), (vectorcraft_doc::GridSize::Large, [hex("#ffffff"), hex("#c4dcff")]));
}
/// The grid preview the open dialog draws in `ctx`, in frames run as the hosts run them
/// ([`crate::testing::part_frame_uploads`]): its rect, the span of its texture
/// coordinates (two cells per unit) and the four pixels of the texture it draws. `tiles` holds
/// the pixels of each 2 × 2 texture uploaded so far in `ctx`, so every frame drawn in `ctx`
/// goes through this function. The preview is the largest rect drawn with such a texture.
fn drawn_preview(
app: &mut VectorcraftApp,
ctx: &egui::Context,
tiles: &mut std::collections::HashMap<egui::TextureId, Vec<egui::Color32>>,
) -> (Rect, egui::Vec2, Vec<egui::Color32>) {
let mut preview = None;
for _ in 0..4 {
let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0))), ..Default::default() };
let mut out = crate::testing::part_frame_uploads(app, ctx, raw, |app, ui| {
if let Some(dialogs) = app.dialogs() {
dialogs.with(|h| h.run(ui));
}
});
for (id, deltas) in &out.textures_delta.set {
if let Some(d) = deltas.last() {
let egui::ImageData::Color(img) = &d.image;
if img.size == [2, 2] {
tiles.insert(*id, img.pixels.clone());
}
}
}
out.textures_delta.clear();
preview = out
.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Rect(r) => {
r.brush.as_ref().filter(|b| tiles.contains_key(&b.fill_texture_id)).map(|b| (r.rect, b.uv, b.fill_texture_id))
}
_ => None,
})
.max_by(|a, b| a.0.area().total_cmp(&b.0.area()));
}
let (rect, uv, texture) = preview.unwrap_or_else(|| panic!("no grid preview"));
let pixels = tiles.get(&texture).cloned().unwrap_or_else(|| panic!("no tile for {texture:?}"));
(rect, uv.size(), pixels)
}
/// The tile's pixels for the grid colors `a` and `b`: `a` in the top-left and bottom-right cells.
fn tile(a: &str, b: &str) -> Vec<egui::Color32> {
let c = |h| crate::panels::c32(&hex(h));
vec![c(a), c(b), c(b), c(a)]
}
/// In an open dialog, the preview follows each edit of Grid Colors and Grid Size: after a
/// color edit it draws a tile in the new colors, and after a size edit it draws the new cells.
#[test]
fn the_grid_preview_follows_edits_in_the_open_dialog() {
let (mut app, ctx) = setup_open();
let mut tiles = std::collections::HashMap::new();
set(&app, &ctx, "tab", json!("Transparency"));
let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles);
assert_eq!((uv, pixels), (rect.size() / 16.0, tile(LIGHT[0], LIGHT[1])), "Medium, Light");
set(&app, &ctx, "gridColors", json!(["#ff0000", "#0000ff"]));
let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles);
assert_eq!((uv, pixels), (rect.size() / 16.0, tile("#ff0000", "#0000ff")), "color edit");
set(&app, &ctx, "gridSize", json!("large"));
let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles);
assert_eq!((uv, pixels), (rect.size() / 32.0, tile("#ff0000", "#0000ff")), "size edit");
set(&app, &ctx, "gridColors", json!("Dark"));
let (_, _, pixels) = drawn_preview(&mut app, &ctx, &mut tiles);
assert_eq!(pixels, tile("#666666", "#4d4d4d"), "preset edit");
let st = app.session.active().unwrap();
assert_eq!((st.doc.setup.grid_size, st.doc.setup.grid_colors), (vectorcraft_doc::GridSize::Medium, LIGHT.map(hex)));
assert_eq!(undo_steps(&app), 0);
}
}
+98 -2
View File
@@ -10,6 +10,7 @@
//! effect's defaults for the rest.
use std::path::PathBuf;
use std::sync::Arc;
use craft::host::{PickRequest, Picked};
use craft::ui::contract::Bind;
@@ -48,6 +49,8 @@ pub(crate) struct EffectDialogs {
pub(crate) struct Open {
/// The dialog's id; while [`asking`](Open::asking), the question's.
pub id: DialogId,
/// Identity of this opening, since effect dialogs reuse the same dialog ID.
opening: Arc<()>,
/// The item the effect goes to, resolved.
target: Value,
/// The parameters that find the applied effect (`item`, `aligned`).
@@ -107,6 +110,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let target = edit_target.get("item").cloned().unwrap_or(target);
let mut open = Open {
id: DialogId::NULL,
opening: Arc::new(()),
target: target.clone(),
edit_target,
index: None,
@@ -144,6 +148,7 @@ pub(crate) fn open_last(app: &mut VectorcraftApp, effect: &str, params: Value) -
vectorcraft_effects::effect_info(effect).ok_or_else(|| format!("unknown effect `{effect}`"))?;
let open = Open {
id: DialogId::NULL,
opening: Arc::new(()),
target: Value::Null,
edit_target: json!({}),
index: None,
@@ -465,7 +470,18 @@ fn drive(app: &mut VectorcraftApp, mut open: Open) {
let _ = open.preview.run(app, previewing, &english, cmd, &params);
if let Some(request) = path {
let (id, key) = (open.id, request.key);
pick_texture(app, Owner::Document, move |app, path, fields| {
let opening = Arc::clone(&open.opening);
let is_current = move |app: &VectorcraftApp| {
app.effect_dialogs.effect.as_ref().is_some_and(|current| current.id == id && Arc::ptr_eq(&opening, &current.opening))
};
let same_opening = is_current.clone();
let is_live = move |app: &VectorcraftApp| {
same_opening(app) && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::<HostedParamDialog>(id).is_some()))
};
pick_texture_while(app, Owner::Document, is_live, move |app, path, fields| {
if !is_current(app) {
return;
}
let Some(dialogs) = app.dialogs() else { return };
dialogs.with(|h| {
if let Some(d) = h.get_mut_by_id::<HostedParamDialog>(id) {
@@ -486,11 +502,20 @@ pub(super) fn pick_texture(
app: &mut VectorcraftApp,
owner: Owner,
then: impl FnOnce(&mut VectorcraftApp, PathBuf, [(&'static str, FieldValue); 2]) + 'static,
) {
pick_texture_while(app, owner, |_| true, then);
}
fn pick_texture_while(
app: &mut VectorcraftApp,
owner: Owner,
current: impl FnOnce(&VectorcraftApp) -> bool + 'static,
then: impl FnOnce(&mut VectorcraftApp, PathBuf, [(&'static str, FieldValue); 2]) + 'static,
) {
use vectorcraft_engine::cmd::fileio;
let rasters = fileio::FORMATS.iter().filter(|f| f.read && f.raster);
let request = rasters.fold(PickRequest::open("texture"), |r, f| r.filter(f.label, fileio::read_extensions(f)));
file_asks::ask(app, request, owner, move |app: &mut VectorcraftApp, picked: Picked| {
file_asks::ask_while(app, request, owner, current, move |app: &mut VectorcraftApp, picked: Picked| {
let Some(path) = picked.first_path() else { return Ok(Value::Null) };
let bytes = match picked {
Picked::Contents(mut files) if !files.is_empty() => files.swap_remove(0).1,
@@ -668,6 +693,77 @@ mod tests {
}
}
#[test]
fn a_delayed_texture_reply_only_reaches_the_effect_opening_that_requested_it() {
use std::cell::RefCell;
use std::rc::Rc;
use craft::ui::testing::{Fixture, Room};
use vectorcraft_effects::pixel::TEXTURE_IMAGE;
let mut png = Vec::new();
let img: image::DynamicImage = image::RgbaImage::from_pixel(6, 4, image::Rgba([40, 60, 90, 255])).into();
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
for (reopen, switch_document) in [(true, false), (false, true), (false, false)] {
let mut app = app();
rect(&mut app, 10);
app.run("select.all", json!({})).unwrap();
let app = Rc::new(RefCell::new(app));
let shown = Rc::clone(&app);
let mut fixture = Fixture::new(move |ui| crate::tests::picks::dialogs(&mut shown.borrow_mut(), ui));
fixture.in_room(Room::Window);
let ctx = fixture.ctx().clone();
app.borrow_mut().ui_ctx = Some(ctx.clone());
let picker = crate::tests::picks::scripted(&mut app.borrow_mut());
let open = || app.borrow_mut().run("effect.dialog", json!({"effect": ROUGH_PASTELS})).unwrap();
open();
fixture.settle();
let browse = fixture.by_label("Browse…").expect("the Load Texture Browse button");
fixture.click(&browse).settle();
assert_eq!(picker.requests().len(), 1, "Browse requested a file");
if reopen || switch_document {
let dialog = id(&app.borrow());
assert!(app.borrow().dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, dialog)));
}
if switch_document {
let mut app = app.borrow_mut();
let original = app.session.active().unwrap().uid;
// The reply arrives before the host pump has cleared the closed effect's app record.
app.session.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let active = app.session.active().unwrap().uid;
assert_ne!(active, original, "a different document is active");
let status = app.ui.status.clone();
picker.answer_contents(&[("invalid.png", b"not an image")]);
crate::file_asks::poll(&mut app);
assert_eq!(app.session.active().unwrap().uid, active, "a stale reply cannot switch documents");
assert_eq!(app.ui.status, status, "a stale reply cannot report a texture error");
continue;
}
if reopen {
fixture.settle();
open();
fixture.settle();
}
let current = || {
let app = app.borrow();
fields(&app, id(&app))
};
let before = current();
picker.answer_contents(&[("texture.png", &png)]);
crate::file_asks::poll(&mut app.borrow_mut());
fixture.settle();
let after = current();
if reopen {
assert_eq!(after.text("texture"), before.text("texture"), "a reopened effect keeps its own texture choice");
assert_eq!(after.text(TEXTURE_IMAGE), before.text(TEXTURE_IMAGE), "the previous effect's image is absent");
} else {
assert_eq!(after.text("texture"), Some("loaded"), "the originating effect loads the picked texture");
assert!(after.text(TEXTURE_IMAGE).and_then(vectorcraft_effects::pixel::texture).is_some());
}
}
}
/// A Pathfinder effect opens with its own Pathfinder Options (or, saved without them, the
/// values it evaluates with); OK with nothing changed records no step, a change one step.
#[test]
+30 -12
View File
@@ -10,6 +10,7 @@
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use craft::imaging::ui::filter_gallery::{
EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGallerySession, FilterIndex, FilterTree,
@@ -117,7 +118,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) {
let shown = dialogs.with(|host| {
host.get_mut_by_id::<EffectGalleryDialog>(id).map(|dialog| {
let visible = dialog.entries(true);
(dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), dialog.asked.take())
let asked = dialog.asked.take().map(|layer| (Arc::clone(&dialog.opening), layer));
(dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), asked)
})
});
let Some((on, batch, asked)) = shown else {
@@ -127,18 +129,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) {
// `run` reports a failed preview itself.
let _ = open.preview.run(app, on, LABEL, COMMAND, &batch);
app.effect_dialogs.gallery = Some(open);
if let Some(layer) = asked {
ask_texture(app, id, layer);
if let Some((opening, layer)) = asked {
ask_texture(app, id, opening, layer);
}
}
/// Asks for the image Load Texture reads into the layer `layer`. The answer finds the layer by its own id, wherever
/// it moved, and is dropped for a layer deleted since or a gallery that closed (a layer id is never used twice).
fn ask_texture(app: &mut VectorcraftApp, id: DialogId, layer: LayerId) {
/// Load Texture follows `layer` within its gallery opening and drops the reply when either is gone.
fn ask_texture(app: &mut VectorcraftApp, id: DialogId, opening: Arc<()>, layer: LayerId) {
effect::pick_texture(app, Owner::Free, move |app, _, fields| {
let Some(dialogs) = app.dialogs() else { return };
dialogs.with(|host| {
if let Some(dialog) = host.get_mut_by_id::<EffectGalleryDialog>(id) {
if let Some(dialog) = host.get_mut_by_id::<EffectGalleryDialog>(id).filter(|dialog| Arc::ptr_eq(&opening, &dialog.opening)) {
dialog.answer_texture(layer, fields);
}
});
@@ -234,6 +235,8 @@ fn entries_of(layers: &[EffectLayer], index: &FilterIndex, visible_only: bool) -
/// [`FilterGallerySession`], with a preview of the visible layers and OK held for [`commit`].
pub(crate) struct EffectGalleryDialog {
id: DialogId,
/// Dialog IDs and layer IDs can both be reused when the gallery opens again.
opening: Arc<()>,
open: bool,
catalog: Catalog,
index: FilterIndex,
@@ -255,6 +258,7 @@ impl EffectGalleryDialog {
let session = FilterGallerySession::new(&first, &catalog);
EffectGalleryDialog {
id: dialog_id(KEY),
opening: Arc::new(()),
open: true,
catalog,
index,
@@ -652,8 +656,7 @@ mod tests {
assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1);
}
/// Load Texture… in the Settings, answered after the stack changed: the image goes into the layer that asked
/// wherever it moved, and an answer for a deleted layer is dropped.
/// A delayed Load Texture… reply follows its layer when it moves and is dropped when the layer or its gallery closes.
#[test]
fn settings_load_texture_answers_into_the_gallery() {
use vectorcraft_effects::pixel::{TEXTURE_IMAGE, texture};
@@ -677,10 +680,13 @@ mod tests {
})
.collect()
};
// Selects `row`, presses Browse of its Texture row, and lets `meanwhile` change the stack before the answer.
let ask = |app: &mut VectorcraftApp, row: usize, meanwhile: &dyn Fn(&VectorcraftApp)| {
let rough_pastels = || {
let layer = json!({ "filter": "artistic.roughPastels", "visible": true, "params": {} });
set(app, &ctx, "effects", json!([layer, layer]));
json!([layer, layer])
};
// Selects `row`, presses Browse of its Texture row, and lets `meanwhile` change the gallery before the answer.
let ask = |app: &mut VectorcraftApp, row: usize, meanwhile: &dyn Fn(&mut VectorcraftApp)| {
set(app, &ctx, "effects", rough_pastels());
set(app, &ctx, "select", json!(row));
// The Texture row's Browse press, as the dialog's pass records it.
app.dialogs().unwrap().with(|host| {
@@ -696,6 +702,18 @@ mod tests {
assert_eq!(ask(&mut app, 1, &|_| {}), [false, true], "the selected layer asked");
assert_eq!(ask(&mut app, 0, &|app| set(app, &ctx, "move", json!({"from": 0, "to": 1}))), [false, true], "the layer that asked moved");
assert_eq!(ask(&mut app, 1, &|app| set(app, &ctx, "delete", json!(true))), [false], "the layer that asked was deleted");
let reopen = |app: &mut VectorcraftApp| {
assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id())));
frame(app, &ctx);
super::open(app, &json!({})).unwrap();
};
// Both openings start with identical stacks, which gives their corresponding layers the same session-local IDs.
reopen(&mut app);
let answers = ask(&mut app, 0, &|app| {
reopen(app);
set(app, &ctx, "effects", rough_pastels());
});
assert_eq!(answers, [false, false], "a reopened gallery keeps its own textures");
let _ = std::fs::remove_dir_all(&dir);
}
}
@@ -77,6 +77,7 @@ fn ok_sets_each_tools_options() {
let layers = app.session.doc().unwrap().doc.layers.clone();
let circle = vectorcraft_tools::circle::ID;
let arc = vectorcraft_tools::three_point_arc::ID;
let curvature = vectorcraft_tools::curvature_circle::ID;
// The tool opened, the fields set, the tool whose options are read, and the options expected there.
let rows: Vec<(&str, Value, &str, Value)> = vec![
(
@@ -107,6 +108,12 @@ fn ok_sets_each_tools_options() {
circle,
json!({"radii": false, "standardAnchors": false, "dragThird": false, "color": "magenta"}),
),
(
curvature,
json!({"snapTolerance": 8, "annotateRadius": false, "standardAnchors": false}),
curvature,
json!({"snapTolerance": 8.0, "snapWithoutGuides": true, "annotateRadius": false, "standardAnchors": false, "constantRadius": true}),
),
(arc, json!({"direction": true}), arc, json!({"direction": true})),
("objectsOnPath", json!({"pivot": 7, "rotate": 30}), "objectsOnPath", json!({"pivot": 7, "rotate": 30.0})),
(
+47 -8
View File
@@ -18,6 +18,7 @@
//! empties it).
use std::collections::BTreeMap;
use std::sync::Arc;
use craft::behavior::{EditEvent, NumberCodec};
use craft::host::{PickRequest, Picked};
@@ -395,8 +396,12 @@ fn can_import(app: &VectorcraftApp) -> bool {
file_asks::can(app, craft::host::PickKind::Open) && app.services.read.is_some()
}
/// Import Data's answer: a tab-separated text file's rows into the sheet.
fn import(app: &mut VectorcraftApp, picked: Picked) -> Result<Value, String> {
/// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it.
fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result<Value, String> {
let Some(dialogs) = app.dialogs() else { return Ok(Value::Null) };
if !dialogs.with(|host| host.get::<GraphDataDialog>().is_some_and(|d| Arc::ptr_eq(&d.import_owner, owner))) {
return Ok(Value::Null);
}
let bytes = match picked {
Picked::Paths(paths) => {
let Some(path) = paths.first().map(|p| p.to_string_lossy().into_owned()) else { return Ok(Value::Null) };
@@ -420,15 +425,14 @@ fn import(app: &mut VectorcraftApp, picked: Picked) -> Result<Value, String> {
return Err("the file is larger than 1 MB".into());
}
let grid = grid_from_text(&decode(&bytes));
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.get_mut::<GraphDataDialog>().map(|d| d.replace(grid)));
}
dialogs.with(|host| host.get_mut::<GraphDataDialog>().filter(|d| Arc::ptr_eq(&d.import_owner, owner)).map(|d| d.replace(grid)));
Ok(Value::Null)
}
/// What the window asked of the app since the last [`pump`].
struct Asks {
graph: Option<u64>,
import_owner: Arc<()>,
apply: Option<Sheet>,
actions: Vec<Action>,
}
@@ -444,7 +448,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
d.take_asks()
})
});
let Some(Asks { graph, apply: filed, actions }) = asked else { return };
let Some(Asks { graph, import_owner, apply: filed, actions }) = asked else { return };
if let Some(sheet) = filed {
if let Err(e) = apply(app, &sheet, graph) {
app.status(e);
@@ -455,7 +459,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
match action {
Action::Import => {
let request = PickRequest::open("document").filter("Text", &["txt", "tsv", "csv"]);
file_asks::ask(app, request, Owner::Document, import);
let owner = import_owner.clone();
file_asks::ask(app, request, Owner::Document, move |app, picked| import(app, &owner, picked));
}
Action::Revert => match graph_grid(app, graph) {
Ok(grid) => {
@@ -636,6 +641,8 @@ fn body(ui: &mut egui::Ui, values: &mut Sheet, pane: &mut Pane<'_>) -> bool {
/// sheet for [`pump`], which sends it to the graph and keeps the window open.
pub(crate) struct GraphDataDialog {
id: DialogId,
/// Identifies this opening even when another Graph Data dialog reuses `id`.
import_owner: Arc<()>,
sheet: Sheet,
state: GridState,
entry: Entry,
@@ -658,6 +665,7 @@ impl GraphDataDialog {
load(&sheet, &state, &mut entry);
GraphDataDialog {
id: dialog_id(KIND),
import_owner: Arc::new(()),
sheet,
state,
entry,
@@ -672,7 +680,7 @@ impl GraphDataDialog {
/// Everything the window asked since the last call, once.
fn take_asks(&mut self) -> Asks {
Asks { graph: self.graph, apply: self.held.take(), actions: std::mem::take(&mut self.actions) }
Asks { graph: self.graph, import_owner: self.import_owner.clone(), apply: self.held.take(), actions: std::mem::take(&mut self.actions) }
}
/// The pump sent Apply's sheet to the graph; the window stays open and Apply is ready again.
@@ -959,6 +967,37 @@ mod tests {
assert_eq!(at(&h, 0, 1), "c");
}
#[test]
fn graph_data_import_keeps_late_answers_out_of_a_reopened_sheet() {
let (mut app, _) = app_with(",first\nQ1,1", "column");
let files = Arc::new(ScriptedFiles::held());
app.services.read = Some(Box::new(|_| Err("this picker answers with bytes".into())));
app.host.with_files(files.clone()).install(app.ui_ctx.as_ref().unwrap());
app.host = Arc::new(app.host.with_files(files.clone()));
open(&mut app).unwrap();
let mut h = harness(app);
h.run_steps(4);
h.get_by_label("Import Data…").click();
h.run_steps(3);
assert_eq!(files.open(), 1);
let app = h.state_mut();
let ctx = app.ui_ctx.as_ref().unwrap().clone();
app.dialogs().unwrap().with(|host| host.cancel::<GraphDataDialog>(&ctx));
app.run("graph.create", json!({"type": "column", "x": 20, "y": 20, "width": 100, "height": 100, "csv": ",second\nQ2,2"})).unwrap();
open(app).unwrap();
let series = |h: &Harness| read(h.state(), |d| cell_of(&d.sheet.grid, 0, 1));
assert!(files.answer(Picked::Contents(vec![("first.txt".into(), b"\tstale\nQ1\t7".to_vec())])).is_some());
h.run_steps(4);
assert_eq!(series(&h), "second");
h.get_by_label("Import Data…").click();
h.run_steps(3);
assert!(files.answer(Picked::Contents(vec![("second.txt".into(), b"\timported\nQ2\t8".to_vec())])).is_some());
h.run_steps(4);
assert_eq!(series(&h), "imported");
}
#[test]
fn transpose_and_switch_xy() {
assert_eq!(transpose(&g(&[&["", "a", "b"], &["Q1", "1", "2"]])), g(&[&["", "Q1"], &["a", "1"], &["b", "2"]]));
+48 -4
View File
@@ -519,13 +519,14 @@ impl GraphDesignDialog {
}
true
});
if let Some(options) = shown.accepted {
self.column = options;
if shown.closed.is_some() {
return Some(DialogResult::Cancel);
}
if shown.picked == Some(0) && !waiting {
let answer = self.answer();
self.held.file(answer);
return None;
}
shown.closed.map(|_| DialogResult::Cancel)
None
}
}
@@ -836,6 +837,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
#[cfg(test)]
mod tests {
use egui_kittest::kittest::Queryable;
use serde_json::{Value, json};
use super::GraphDesignDialog;
@@ -879,6 +881,48 @@ mod tests {
assert!(!dialogs.with(|host| host.is_open::<GraphDesignDialog>()));
}
#[test]
fn graph_design_footer_ok_applies_column_and_marker_designs_unless_dismissed() {
for (graph_type, command, dismiss) in [("column", "graph.column", false), ("line", "graph.marker", false), ("column", "graph.column", true)] {
let (mut app, ctx) = app_with_design();
select_graph(&mut app, graph_type);
crate::menus::invoke(&mut app, command, json!({}));
set(&app, &ctx, "selected", json!("New Design")).unwrap();
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
if !std::mem::replace(&mut fonts, true) {
crate::testing::install(ui.ctx());
return;
}
app.dialogs().unwrap().with(|host| host.run(ui));
super::pump(app, ui.ctx());
},
app,
);
h.run_steps(4);
if dismiss {
h.get_by_label("OK").click_accesskit();
h.input_mut().events.push(egui::Event::Key {
key: egui::Key::Escape,
physical_key: None,
pressed: true,
repeat: false,
modifiers: Default::default(),
});
} else {
h.get_by_label("OK").click();
}
h.run_steps(4);
let app = h.state_mut();
assert!(!app.dialogs().unwrap().with(|host| host.is_open::<GraphDesignDialog>()));
let expected = if dismiss { Value::Null } else { json!("New Design") };
assert_eq!(app.session.execute(command, &json!({})).unwrap()["design"], expected);
}
}
#[test]
fn marker_lists_the_designs_and_applies_the_one_picked() {
let (mut app, ctx) = app_with_design();
+6 -7
View File
@@ -372,14 +372,13 @@ impl ImportPdfDialog {
if self.held.refusal().is_some_and(|(_, refused)| *refused != self.s) {
self.held.clear_refusal();
}
match (out.accepted, out.closed) {
(Some(_), _) => {
self.ok();
None
}
(None, Some(_)) => Some(DialogResult::Cancel),
(None, None) => None,
if out.closed.is_some() {
return Some(DialogResult::Cancel);
}
if out.picked == Some(0) && !waiting {
self.ok();
}
None
}
}
+10 -5
View File
@@ -1505,6 +1505,7 @@ impl Feed {
/// What the pump works on with the app, out of the host: the values, their steps and what `show`
/// asked for.
struct Work {
opening: Arc<()>,
fields: Fields,
steps: Steps,
filed: Filed,
@@ -1544,7 +1545,7 @@ impl Work {
randomize(app, &mut self.fields, sb);
}
if filed.library {
pick_library(app);
pick_library(app, Arc::clone(&self.opening));
}
let d = &mut self.fields;
if let Some(before) = filed.edited {
@@ -1591,16 +1592,16 @@ fn randomize(app: &mut VectorcraftApp, d: &mut Fields, sb: bool) {
/// Other Library…: import a library (.ase, .acb, .gpl, .vcswatches or a document's swatches) and
/// limit to it.
fn pick_library(app: &mut VectorcraftApp) {
fn pick_library(app: &mut VectorcraftApp, opening: Arc<()>) {
let request = builtin_open_filters().fold(PickRequest::open("library"), |request, (name, exts)| request.filter(name, exts));
// PLAN: assumed `file_asks::Owner::Free` (fl.A3's owner of a continuation no document holds), as appearance-w19 codes it.
crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, |app, picked| {
// A loaded library belongs to the session. The Limit to Library choice belongs to the opening that asked.
crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, move |app, picked| {
let Some(path) = picked.first_path() else { return Ok(Value::Null) };
let r = app.run("swatch.library.load", json!({ "path": path }))?;
let library = r["library"].clone();
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| {
if let Some(d) = host.get_mut::<RecolorDialog>() {
if let Some(d) = host.get_mut_by_id::<RecolorDialog>(dialog_id(KIND)).filter(|d| Arc::ptr_eq(&opening, &d.opening)) {
d.fields.fields.insert("limitTo".into(), library);
}
});
@@ -1765,6 +1766,8 @@ fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> {
/// commits the recolour.
pub(crate) struct RecolorDialog {
id: DialogId,
/// The identity of this opening, since Recolor Artwork reuses its dialog ID.
opening: Arc<()>,
fields: Fields,
steps: Steps,
held: HeldAnswer<Fields>,
@@ -1787,6 +1790,7 @@ impl RecolorDialog {
fn new(app: &VectorcraftApp, fields: Fields) -> Self {
RecolorDialog {
id: dialog_id(KIND),
opening: Arc::new(()),
feed: Feed::of(app, &fields),
steps: Steps::opened(snapshot(&fields)),
fields,
@@ -1803,6 +1807,7 @@ impl RecolorDialog {
/// The values, steps and requests, for the pump to work on with the app.
fn take_work(&mut self) -> Work {
Work {
opening: Arc::clone(&self.opening),
fields: std::mem::take(&mut self.fields),
steps: std::mem::replace(&mut self.steps, Steps::opened(Snapshot::new())),
filed: std::mem::take(&mut self.filed),
@@ -1,6 +1,7 @@
//! The Import PDF dialog: opening and placing multi-page and password-protected PDFs.
use craft::ui::dialog::{HeldOk, StackDialog};
use egui_kittest::kittest::Queryable;
use serde_json::json;
use vectorcraft_doc::NodeKind;
use vectorcraft_engine::Session;
@@ -72,6 +73,50 @@ fn artboard_widths(app: &VectorcraftApp) -> Vec<f64> {
app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect.width()).collect()
}
fn click_page_footer_ok(app: VectorcraftApp, dismiss: bool) -> egui_kittest::Harness<'static, VectorcraftApp> {
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
if !std::mem::replace(&mut fonts, true) {
crate::testing::install(ui.ctx());
return;
}
app.dialogs().unwrap().with(|host| host.run(ui));
super::import_pdf::pump(app, ui.ctx());
},
app,
);
h.run_steps(4);
if dismiss {
h.get_by_label("OK").focus();
h.run_steps(2);
h.get_by_label("OK").click_accesskit();
h.input_mut().events.push(egui::Event::Key {
key: egui::Key::Escape,
physical_key: None,
pressed: true,
repeat: false,
modifiers: Default::default(),
});
} else {
h.get_by_label("OK").click();
}
h.run_steps(4);
assert!(!is_open(h.state()));
h
}
#[test]
fn pdf_page_footer_ok_opens_the_chosen_range() {
let mut app = app();
io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap();
set(&mut app, "allPages", json!(false));
set(&mut app, "range", json!("2-3"));
let h = click_page_footer_ok(app, false);
assert_eq!(artboard_widths(h.state()), [200.0, 300.0]);
}
#[test]
fn opening_a_multi_page_pdf_asks_for_the_pages() {
let mut app = app();
@@ -228,6 +273,24 @@ fn place(app: &mut VectorcraftApp, bytes: &[u8], extra: serde_json::Value) -> Re
crate::place::run(app, &p)
}
#[test]
fn pdf_page_footer_ok_places_the_chosen_page_unless_dismissed() {
for dismiss in [false, true] {
let mut app = app();
place(&mut app, &three_pages(), json!({"at": [100, 120], "link": false})).unwrap();
set(&mut app, "page", json!(2));
set(&mut app, "cropTo", json!("art"));
let h = click_page_footer_ok(app, dismiss);
if dismiss {
assert!(h.state().session.active().unwrap().selection.objects.is_empty());
} else {
let (_, bounds) = placed(h.state());
assert_eq!((bounds.width(), bounds.height()), (50.0, 60.0));
}
}
}
#[test]
fn placing_a_pdf_page_asks_for_the_page_and_crop_box() {
let mut app = app();
+3
View File
@@ -55,6 +55,8 @@ pub(crate) struct Data {
pub bevels_file: bool,
/// The active document, for the symbol pictures.
pub doc: Option<Arc<Document>>,
/// The document that owns the object IDs accepted by the Graphics drop target.
pub document_uid: Option<u64>,
/// The active document's version.
pub revision: u64,
/// Whether the active document has a selection.
@@ -77,6 +79,7 @@ pub(crate) fn data(app: &VectorcraftApp, effect: Option<&str>, params: &Map<Stri
bevels: effect.map(|e| revolve::bevel_options(app, params, e).0).unwrap_or_default(),
bevels_file: app.session.bevels.path().is_some(),
doc: st.map(|s| s.doc.clone()),
document_uid: st.map(|s| s.uid),
revision: st.map_or(0, |s| s.revision),
selected: st.is_some_and(|s| !s.selection.objects.is_empty()),
surfaces: None,
@@ -174,11 +174,12 @@ fn body(ui: &mut Ui, fields: &mut DialogFields, cx: &mut CustomContext, data: &D
fn library(ui: &mut Ui, data: &Data, apply: bool) -> Option<Action> {
Text::new(tl!("Graphics")).show(ui);
let mut action = None;
let (Some(doc), true) = (data.doc.clone(), true) else { return action };
let (Some(doc), Some(uid)) = (data.doc.clone(), data.document_uid) else { return action };
let names: Vec<String> = doc.symbols.iter().map(|s| s.name.clone()).collect();
let keys = crate::panels::symbols::document_symbols(&doc, data.revision);
let source = keyed(&names[..], |name: &String| name.clone()).with_text(|name| Cow::Borrowed(name.as_str()));
let mut dropped = DropAction::<PanelDrag>::new(|drag| matches!(drag, PanelDrag::Art { .. })).show(ui, |ui, _| {
let drop_art = DropAction::<PanelDrag>::new(move |drag| matches!(drag, PanelDrag::Art { document, .. } if *document == uid));
let mut dropped = drop_art.show(ui, |ui, _| {
TileGrid::new(tl!("Graphics")).activate(ActivateOn::Click).show_items(ui, &source, &mut |name, _| {
let tip = if apply { name.clone() } else { format!("{name}: {}", tl!("Select a 3D object to map the graphic onto it.")) };
let (doc, keys, name) = (doc.clone(), keys.clone(), name.clone());
+21 -3
View File
@@ -21,6 +21,8 @@ use crate::VectorcraftApp;
use crate::dialogs::confirm::{ReplaceFiles, ReplaceFilesPrompt};
type Then = Box<dyn FnOnce(&mut VectorcraftApp, Picked) -> Result<Value, String>>;
/// Whether the part of the app that requested a pick is still waiting for it.
type PickGuard = Box<dyn FnOnce(&VectorcraftApp) -> bool>;
/// What proceeding past a replace question runs.
type Proceed = Box<dyn FnOnce(&mut VectorcraftApp) -> Result<Value, String>>;
@@ -45,6 +47,7 @@ struct Waiting {
scope: ScopeHandle,
/// Automation asked ([`VectorcraftApp::automation_asked`]): the continuation runs as its.
automated: bool,
current: Option<PickGuard>,
then: Then,
}
@@ -120,7 +123,18 @@ pub(crate) fn ask(
owner: Owner,
then: impl FnOnce(&mut VectorcraftApp, Picked) -> Result<Value, String> + 'static,
) -> Value {
start(app, owner, |files| files.pick(request), then)
start(app, owner, |files| files.pick(request), None, then)
}
/// Like [`ask`], but drops a reply if its requester is gone, before choosing a document or reporting a picker error.
pub(crate) fn ask_while(
app: &mut VectorcraftApp,
request: PickRequest,
owner: Owner,
current: impl FnOnce(&VectorcraftApp) -> bool + 'static,
then: impl FnOnce(&mut VectorcraftApp, Picked) -> Result<Value, String> + 'static,
) -> Value {
start(app, owner, |files| files.pick(request), Some(Box::new(current)), then)
}
/// Save `bytes` as the file service saves them (`Files::save`: the desktop asks where with `request` and
@@ -133,7 +147,7 @@ pub(crate) fn save(
owner: Owner,
then: impl FnOnce(&mut VectorcraftApp, Picked) -> Result<Value, String> + 'static,
) -> Value {
start(app, owner, |files| files.save(request, bytes), then)
start(app, owner, |files| files.save(request, bytes), None, then)
}
/// Asks the file service with `ask` and files `then` for its answer.
@@ -141,6 +155,7 @@ fn start(
app: &mut VectorcraftApp,
owner: Owner,
ask: impl FnOnce(&dyn Files) -> PickId,
current: Option<PickGuard>,
then: impl FnOnce(&mut VectorcraftApp, Picked) -> Result<Value, String> + 'static,
) -> Value {
let Some(host) = app.ui_ctx.as_ref().and_then(Host::try_of_ctx) else { return Value::Null };
@@ -150,7 +165,7 @@ fn start(
Owner::Free => None,
};
let (scope, automated) = (ScopeHandle::capture(), app.automation_asked());
app.file_asks.waiting.push(Waiting { ticket, owner, doc, scope, automated, then: Box::new(then) });
app.file_asks.waiting.push(Waiting { ticket, owner, doc, scope, automated, current, then: Box::new(then) });
json!({ "pending": "fileDialog" })
}
@@ -289,6 +304,9 @@ pub(crate) fn poll(app: &mut VectorcraftApp) {
}
}
for (w, picked) in answered {
if w.current.is_some_and(|current| !current(app)) {
continue;
}
match &picked {
Picked::Cancelled => continue,
Picked::Unavailable(why) => {
+7
View File
@@ -6624,6 +6624,8 @@ arrowhead Feather Перо
VectorCraft Default По подразбиране за VectorCraft
VectorCraft Defaults Стандартни настройки на VectorCraft
VectorCraft Generic CMYK (SWOP-like) Общ CMYK за VectorCraft (подобен на SWOP)
VectorCraft Coated CMYK (FOGRA51) Мелиран CMYK за VectorCraft (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) Немелиран CMYK за VectorCraft (FOGRA52)
VectorCraft Swatches (.vcswatches) Образци на VectorCraft (.vcswatches)
Vertical Align Вертикално подравняване
Vertical Area Type Вертикално въвеждане в област
@@ -8601,6 +8603,11 @@ breakText Glyphs Глифи
No objects are selected. Няма избрани обекти.
Open a document to mark its fold lines. Отворете документ, за да отбележите линиите му на сгъване.
Remove Fold Line Role Премахни вида на линията
Fold Angle Ъгъл на сгъване
Set Fold Angle… Задай ъгъл на сгъване…
Set Fold Angle Задай ъгъл на сгъване
Reset Fold Angle Нулирай ъгъла на сгъване
@msg select a crease, partial cut or perforation line that is neither locked nor hidden изберете линия за биговане, частично рязане или перфорация, която не е заключена или скрита
Check Провери
Check Fold Lines Провери линиите на сгъване
@msg No cut lines are in the selection. В селекцията няма линии за рязане.
Can't render this file because it is too large.
+7
View File
@@ -657,6 +657,8 @@
RGB RGB
sRGB IEC61966-2.1 sRGB IEC61966-2.1
VectorCraft Generic CMYK (SWOP-like) VectorCraft generički CMYK (sličan SWOP-u)
VectorCraft Coated CMYK (FOGRA51) VectorCraft premazani CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraft nepremazani CMYK (FOGRA52)
Legacy Macintosh RGB (Gamma 1.8) Naslijeđeni Macintosh RGB (gama 1.8)
Internet Standard RGB (sRGB) Internet standardni RGB (sRGB)
Monitor RGB RGB monitora
@@ -7985,6 +7987,11 @@ shape Open Otvoren
No objects are selected. Nijedan objekat nije odabran.
Open a document to mark its fold lines. Otvorite dokument da označite njegove linije savijanja.
Remove Fold Line Role Ukloni vrstu linije
Fold Angle Ugao savijanja
Set Fold Angle… Postavi ugao savijanja…
Set Fold Angle Postavi ugao savijanja
Reset Fold Angle Poništi ugao savijanja
@msg select a crease, partial cut or perforation line that is neither locked nor hidden odaberite liniju bigovanja, djelimičnog rezanja ili perforacije koja nije zaključana ni skrivena
Check Provjeri
Check Fold Lines Provjeri linije savijanja
@msg No cut lines are in the selection. U odabiru nema linija rezanja.
Can't render this file because it contains an unexpected character in line 2 and column 73.
+7
View File
@@ -5970,6 +5970,8 @@ digits Malayalam Malaiàlam
VectorCraft didn't quit normally last time. These documents had unsaved changes: VectorCraft no es va tancar correctament l’última vegada. Aquests documents tenien canvis no desats:
VectorCraft documents: one locked object, updated when the file changes. Documents de VectorCraft: un objecte bloquejat, actualitzat quan canvia el fitxer.
VectorCraft Generic CMYK (SWOP-like) CMYK genèric de VectorCraft (similar a SWOP)
VectorCraft Coated CMYK (FOGRA51) CMYK estucat de VectorCraft (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) CMYK no estucat de VectorCraft (FOGRA52)
VectorCraft Help… Ajuda de VectorCraft…
VectorCraft on getartcraft.com VectorCraft a getartcraft.com
VectorCraft on GitHub VectorCraft al GitHub
@@ -9049,6 +9051,11 @@ breakText Glyphs Glifs
No objects are selected. No hi ha cap objecte seleccionat.
Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat.
Remove Fold Line Role Elimina el tipus de línia
Fold Angle Angle de plegat
Set Fold Angle… Defineix l’angle de plegat…
Set Fold Angle Defineix l’angle de plegat
Reset Fold Angle Restableix l’angle de plegat
@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleccioneu una línia d’hendit, de tall parcial o de perforació que no estigui bloquejada ni amagada
Check Comprova
Check Fold Lines Comprova les línies de plegat
@msg No cut lines are in the selection. No hi ha cap línia de tall a la selecció.
Can't render this file because it is too large.
+7
View File
@@ -669,6 +669,8 @@
RGB RGB
sRGB IEC61966-2.1 sRGB IEC61966-2.1
VectorCraft Generic CMYK (SWOP-like) VectorCraft obecný CMYK (podobný SWOP)
VectorCraft Coated CMYK (FOGRA51) VectorCraft natíraný CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraft nenatíraný CMYK (FOGRA52)
Legacy Macintosh RGB (Gamma 1.8) Starší Macintosh RGB (gama 1,8)
Internet Standard RGB (sRGB) Standardní internetové RGB (sRGB)
Monitor RGB RGB monitoru
@@ -10832,6 +10834,11 @@ breakText Glyphs Glyfy
No objects are selected. Nejsou vybrány žádné objekty.
Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu.
Remove Fold Line Role Odstranit typ linie
Fold Angle Úhel skladu
Set Fold Angle… Nastavit úhel skladu…
Set Fold Angle Nastavit úhel skladu
Reset Fold Angle Obnovit úhel skladu
@msg select a crease, partial cut or perforation line that is neither locked nor hidden vyberte linii bigu, částečného řezu nebo perforace, která není zamčená ani skrytá
# Tool cards (General › Show Tool Cards): one sentence on what each tool does.
Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Místo popisku zobrazí kartu s tím, co dělá nástroj z panelu a co dělají jeho klávesy; vyžaduje Zobrazovat popisky nástrojů.
Selects whole objects and groups to move, resize or rotate them. Vybírá celé objekty a skupiny, abyste je mohli přesunout, změnit jejich velikost nebo je otočit.
Can't render this file because it is too large.
+7
View File
@@ -3441,6 +3441,8 @@ liquify-list-end {0}, {1} {0} og {1}
RGB RGB
sRGB IEC61966-2.1 sRGB IEC61966-2.1
VectorCraft Generic CMYK (SWOP-like) VectorCraft-generisk CMYK (SWOP-lignende)
VectorCraft Coated CMYK (FOGRA51) VectorCraft bestrøget CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraft ubestrøget CMYK (FOGRA52)
Legacy Macintosh RGB (Gamma 1.8) Ældre Macintosh RGB (gamma 1,8)
Internet Standard RGB (sRGB) Internetstandard-RGB (sRGB)
Monitor RGB Skærm-RGB
@@ -10920,6 +10922,11 @@ breakText Glyphs Glyffer
No objects are selected. Ingen objekter er markeret.
Open a document to mark its fold lines. Åbn et dokument for at markere dets foldelinjer.
Remove Fold Line Role Fjern linjetype
Fold Angle Foldevinkel
Set Fold Angle… Angiv foldevinkel…
Set Fold Angle Angiv foldevinkel
Reset Fold Angle Nulstil foldevinkel
@msg select a crease, partial cut or perforation line that is neither locked nor hidden markér en rillelinje, delvis skærelinje eller perforeringslinje, der hverken er låst eller skjult
Check Kontrollér
Check Fold Lines Kontrollér foldelinjer
@msg No cut lines are in the selection. Der er ingen skærelinjer i markeringen.
Can't render this file because it is too large.
+5
View File
@@ -10474,6 +10474,11 @@ breakText Glyphs Glyphen
No objects are selected. Es sind keine Objekte ausgewählt.
Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen.
Remove Fold Line Role Linienart entfernen
Fold Angle Faltwinkel
Set Fold Angle… Faltwinkel festlegen…
Set Fold Angle Faltwinkel festlegen
Reset Fold Angle Faltwinkel zurücksetzen
@msg select a crease, partial cut or perforation line that is neither locked nor hidden Wählen Sie eine Rill-, Teilschnitt- oder Perforationslinie aus, die weder gesperrt noch ausgeblendet ist
# Tool cards (General › Show Tool Cards): one sentence on what each tool does.
Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Zeigt statt des Tooltips eine Karte, was ein Werkzeug der Werkzeugleiste und seine Tasten tun; erfordert Tooltips anzeigen.
Selects whole objects and groups to move, resize or rotate them. Wählt ganze Objekte und Gruppen aus, um sie zu verschieben, zu skalieren oder zu drehen.
Can't render this file because it is too large.
+7
View File
@@ -6625,6 +6625,8 @@ arrowhead Feather Φτερό
VectorCraft Default Προεπιλογή VectorCraft
VectorCraft Defaults Προεπιλογές VectorCraft
VectorCraft Generic CMYK (SWOP-like) Γενικό CMYK του VectorCraft (τύπου SWOP)
VectorCraft Coated CMYK (FOGRA51) CMYK επιχρισμένου χαρτιού του VectorCraft (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) CMYK μη επιχρισμένου χαρτιού του VectorCraft (FOGRA52)
VectorCraft Swatches (.vcswatches) Δείγματα χρωμάτων VectorCraft (.vcswatches)
Vertical Align Κατακόρυφη στοίχιση
Vertical Area Type Κατακόρυφο κείμενο περιοχής
@@ -9022,6 +9024,11 @@ breakText Glyphs Γλύφοι
No objects are selected. Δεν έχουν επιλεγεί αντικείμενα.
Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του.
Remove Fold Line Role Αφαίρεση τύπου γραμμής
Fold Angle Γωνία δίπλωσης
Set Fold Angle… Ορισμός γωνίας δίπλωσης…
Set Fold Angle Ορισμός γωνίας δίπλωσης
Reset Fold Angle Επαναφορά γωνίας δίπλωσης
@msg select a crease, partial cut or perforation line that is neither locked nor hidden επιλέξτε μια γραμμή πτύχωσης, μερικής κοπής ή διάτρησης που δεν είναι κλειδωμένη ούτε κρυφή
Check Έλεγχος
Check Fold Lines Έλεγχος γραμμών δίπλωσης
@msg No cut lines are in the selection. Η επιλογή δεν περιέχει γραμμές κοπής.
Can't render this file because it is too large.
+7
View File
@@ -6795,6 +6795,8 @@ mark-style Japanese Japonesas
Variation Variación
VectorCraft Default Predeterminado de VectorCraft
VectorCraft Generic CMYK (SWOP-like) CMYK genérico de VectorCraft (similar a SWOP)
VectorCraft Coated CMYK (FOGRA51) CMYK estucado de VectorCraft (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) CMYK no estucado de VectorCraft (FOGRA52)
VectorCraft Swatches (.vcswatches) Muestras de VectorCraft (.vcswatches)
Vertical Area Type Texto de área vertical
Vertical Type Texto vertical
@@ -10766,6 +10768,11 @@ breakText Glyphs Glifos
No objects are selected. No hay objetos seleccionados.
Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado.
Remove Fold Line Role Quitar tipo de línea
Fold Angle Ángulo de plegado
Set Fold Angle… Definir ángulo de plegado…
Set Fold Angle Definir ángulo de plegado
Reset Fold Angle Restablecer ángulo de plegado
@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleccione una línea de hendido, de corte parcial o de perforación que no esté bloqueada ni oculta
Check Comprobar
Check Fold Lines Comprobar líneas de plegado
@msg No cut lines are in the selection. No hay líneas de corte en la selección.
Can't render this file because it is too large.
+7
View File
@@ -663,6 +663,8 @@
RGB RGB
sRGB IEC61966-2.1 sRGB IEC61966-2.1
VectorCraft Generic CMYK (SWOP-like) VectorCraftin yleinen CMYK (SWOP-tyyppinen)
VectorCraft Coated CMYK (FOGRA51) VectorCraftin päällystetty CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraftin päällystämätön CMYK (FOGRA52)
Legacy Macintosh RGB (Gamma 1.8) Vanha Macintosh RGB (gamma 1.8)
Internet Standard RGB (sRGB) Internetin standardi-RGB (sRGB)
Monitor RGB Näytön RGB
@@ -9105,6 +9107,11 @@ breakText Glyphs Merkit
No objects are selected. Objekteja ei ole valittu.
Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat.
Remove Fold Line Role Poista viivatyyppi
Fold Angle Taittokulma
Set Fold Angle… Aseta taittokulma…
Set Fold Angle Aseta taittokulma
Reset Fold Angle Palauta taittokulma
@msg select a crease, partial cut or perforation line that is neither locked nor hidden valitse nuuttausviiva, osittainen leikkausviiva tai rei’itysviiva, joka ei ole lukittu eikä piilotettu
Check Tarkista
Check Fold Lines Tarkista taittoviivat
@msg No cut lines are in the selection. Valinnassa ei ole leikkausviivoja.
Can't render this file because it is too large.
+7
View File
@@ -6906,6 +6906,8 @@ arrowhead Feather Empennage
VectorCraft Default VectorCraft par défaut
VectorCraft Defaults Valeurs par défaut de VectorCraft
VectorCraft Generic CMYK (SWOP-like) CMJN générique VectorCraft (de type SWOP)
VectorCraft Coated CMYK (FOGRA51) CMJN couché VectorCraft (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) CMJN non couché VectorCraft (FOGRA52)
VectorCraft Swatches (.vcswatches) Nuances VectorCraft (.vcswatches)
Vertical Align Alignement vertical
Vertical Area Type Texte captif vertical
@@ -10827,6 +10829,11 @@ breakText Glyphs Glyphes
No objects are selected. Aucun objet n’est sélectionné.
Open a document to mark its fold lines. Ouvrez un document pour marquer ses lignes de pliage.
Remove Fold Line Role Supprimer le type de ligne
Fold Angle Angle de pliage
Set Fold Angle… Définir l’angle de pliage…
Set Fold Angle Définir l’angle de pliage
Reset Fold Angle Réinitialiser l’angle de pliage
@msg select a crease, partial cut or perforation line that is neither locked nor hidden sélectionnez une ligne de rainage, de découpe partielle ou de perforation qui n’est ni verrouillée ni masquée
Tap Appui bref
Clear Hold Effacer le maintien
Hold Shortcuts Raccourcis de maintien
Can't render this file because it is too large.
+5
View File
@@ -5666,6 +5666,11 @@ swatch [Registration] [રજિસ્ટ્રેશન]
No objects are selected. કોઈ ઑબ્જેક્ટ પસંદ કરેલ નથી.
Open a document to mark its fold lines. તેની ફોલ્ડ લાઇન્સ ચિહ્નિત કરવા દસ્તાવેજ ખોલો.
Remove Fold Line Role લાઇન પ્રકાર દૂર કરો
Fold Angle ફોલ્ડ ખૂણો
Set Fold Angle… ફોલ્ડ ખૂણો સેટ કરો…
Set Fold Angle ફોલ્ડ ખૂણો સેટ કરો
Reset Fold Angle ફોલ્ડ ખૂણો રીસેટ કરો
@msg select a crease, partial cut or perforation line that is neither locked nor hidden એવી ક્રીઝ, આંશિક કટ અથવા પર્ફોરેશન લાઇન પસંદ કરો જે લૉક કે છુપાયેલી ન હોય
Check ચેક કરો
Check Fold Lines ફોલ્ડ લાઇન્સ ચેક કરો
@msg No cut lines are in the selection. પસંદગીમાં કોઈ કટ લાઇન નથી.
Can't render this file because it contains an unexpected character in line 72 and column 5.
+7
View File
@@ -6399,6 +6399,8 @@ arrowhead Feather पंख
VectorCraft didn't quit normally last time. These documents had unsaved changes: पिछली बार VectorCraft सामान्य तरीके से बंद नहीं हुआ था। इन डॉक्यूमेंट्स में बिना सेव किए बदलाव थे:
VectorCraft documents: one locked object, updated when the file changes. VectorCraft डॉक्यूमेंट्स: एक लॉक्ड ऑब्जेक्ट, जो फ़ाइल बदलने पर अपडेट होता है।
VectorCraft Generic CMYK (SWOP-like) वेक्टर क्रेफ्ट जेनेरिक CMYK (SWOP-like)
VectorCraft Coated CMYK (FOGRA51) वेक्टर क्रेफ्ट कोटेड CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) वेक्टर क्रेफ्ट अनकोटेड CMYK (FOGRA52)
VectorCraft Help… VectorCraft मदद…
VectorCraft on getartcraft.com getartcraft.com पर VectorCraft
VectorCraft on GitHub GitHub पर VectorCraft
@@ -10450,6 +10452,11 @@ theme Appearance अपीयरेंस
No objects are selected. कोई ऑब्जेक्ट सिलेक्ट नहीं है।
Open a document to mark its fold lines. फ़ोल्ड लाइनें मार्क करने के लिए कोई डॉक्यूमेंट ओपन करें।
Remove Fold Line Role लाइन प्रकार हटाएँ
Fold Angle फ़ोल्ड कोण
Set Fold Angle… फ़ोल्ड कोण सेट करें…
Set Fold Angle फ़ोल्ड कोण सेट करें
Reset Fold Angle फ़ोल्ड कोण रीसेट करें
@msg select a crease, partial cut or perforation line that is neither locked nor hidden ऐसी क्रीज़, आंशिक कट या परफ़ोरेशन लाइन चुनें जो न लॉक हो न छिपी हो
# Tool cards (General › Show Tool Cards): one sentence on what each tool does.
Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. टूलबार का टूल और उसकी कुंजियाँ क्या करती हैं, यह टिप की जगह एक कार्ड में दिखाता है; इसके लिए टूल युक्तियाँ दिखाएँ चालू होना चाहिए।
Selects whole objects and groups to move, resize or rotate them. पूरे ऑब्जेक्ट और समूह चुनता है, ताकि उन्हें खिसकाया, आकार बदला या घुमाया जा सके।
Can't render this file because it is too large.
+7
View File
@@ -5344,6 +5344,8 @@ mark-style Japanese Japán
VectorCraft didn't quit normally last time. These documents had unsaved changes: A VectorCraft legutóbb nem szabályosan lépett ki. Ezekben a dokumentumokban mentetlen módosítások voltak:
VectorCraft documents: one locked object, updated when the file changes. VectorCraft-dokumentumok: egyetlen zárolt objektum, amely a fájl változásakor frissül.
VectorCraft Generic CMYK (SWOP-like) VectorCraft általános CMYK (SWOP-szerű)
VectorCraft Coated CMYK (FOGRA51) VectorCraft mázolt CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraft mázolatlan CMYK (FOGRA52)
VectorCraft Help… VectorCraft súgó…
VectorCraft on getartcraft.com A VectorCraft a getartcraft.com oldalon
VectorCraft on GitHub A VectorCraft a GitHubon
@@ -10820,6 +10822,11 @@ breakText Glyphs Glifák
No objects are selected. Nincs kijelölt objektum.
Open a document to mark its fold lines. Nyiss meg egy dokumentumot a hajtásvonalai megjelöléséhez.
Remove Fold Line Role Vonaltípus eltávolítása
Fold Angle Hajtásszög
Set Fold Angle… Hajtásszög beállítása…
Set Fold Angle Hajtásszög beállítása
Reset Fold Angle Hajtásszög visszaállítása
@msg select a crease, partial cut or perforation line that is neither locked nor hidden jelöljön ki egy bigvonalat, részleges vágóvonalat vagy perforációs vonalat, amely nincs zárolva és nincs elrejtve
# Tool cards (General › Show Tool Cards): one sentence on what each tool does.
Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Az elemleírás helyett kártyán mutatja, mit csinál az eszköztár egy eszköze és a billentyűi; ehhez az Elemleírások megjelenítése szükséges.
Selects whole objects and groups to move, resize or rotate them. Teljes objektumokat és csoportokat jelöl ki áthelyezéshez, átméretezéshez vagy forgatáshoz.
Can't render this file because it is too large.
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more