Merge main into feat/image-color-mask

This commit is contained in:
dotCooCoo committed 2026-11-12 17:40:13 -08:00
commit df155042d4
307 files changed
+20556 -1377

No files matched your search

Generated
+11 -11
View File
@@ -217,7 +217,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
"wl-clipboard-rs",
"x11rb",
]
@@ -986,12 +986,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1060,7 +1060,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1620,7 +1620,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -3869,7 +3869,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4391,7 +4391,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4769,7 +4769,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4828,7 +4828,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -5687,7 +5687,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.6",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -7517,7 +7517,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
+1 -1
View File
@@ -14,7 +14,7 @@ repository = "https://github.com/storytold/vectorcraft"
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb8320f5fa5d20fa78a026d0de06fe4e2f08a099", features = ["serde"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
+4 -1
View File
@@ -238,14 +238,17 @@ fn main() -> ExitCode {
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
/// (`script.listInstalled`). `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there.
/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_scripts_dir(&mut h.session);
prefs_dir::attach_new_doc_profiles(&mut h.session);
prefs_dir::attach_profile_store(&mut h.session);
prefs_dir::attach_color_settings(&mut h.session);
prefs_dir::attach_plugin_store(&mut h.session);
prefs_dir::attach_pdf_preset_store(&mut h.session);
prefs_dir::attach_custom_dictionary(&mut h.session);
prefs_dir::attach_arrowheads(&mut h.session);
h
}
+3
View File
@@ -478,6 +478,7 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_plugin_store(&mut session);
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
prefs_dir::attach_scripts_dir(&mut session);
prefs_dir::attach_new_doc_profiles(&mut session);
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
app.set_startup_update_check(true);
load_prefs(&mut app, saved);
@@ -487,6 +488,8 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_pdf_preset_store(&mut app.session);
// The custom dictionary's words, kept in their own file next to the preferences.
prefs_dir::attach_custom_dictionary(&mut app.session);
// The custom arrowheads, kept in their own file next to the preferences.
prefs_dir::attach_arrowheads(&mut app.session);
// Fit the window to its monitor, or put it back where it was (still hidden).
let winit_window = cc.winit_window().cloned();
if let Some(w) = &winit_window {
+16
View File
@@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
}
}
/// Have File › New start each category's documents from its profile in the `New Document
/// Profiles` folder, which `file.newProfiles.edit` makes.
pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("New Document Profiles") {
session.attach_new_doc_profiles(dir);
}
}
/// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from
/// now on there. After the preferences were restored: the folder is the one place the presets live.
pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
@@ -81,6 +89,14 @@ pub fn attach_custom_dictionary(session: &mut vectorcraft_engine::Session) {
}
}
/// Keep the custom arrowheads (Stroke panel menu › Edit Arrowheads…) in the `Arrowheads.vectorcraft`
/// file next to the settings, and list the heads it holds.
pub fn attach_arrowheads(session: &mut vectorcraft_engine::Session) {
if let Some(path) = store_dir(vectorcraft_engine::cmd::arrowheads::FILE_NAME) {
session.attach_arrowheads_file(path.to_string_lossy().to_string());
}
}
#[cfg(test)]
mod tests {
use super::*;
+11 -7
View File
@@ -187,6 +187,9 @@ pub struct HpglOutput {
pub pens: Vec<[u8; 3]>,
/// What was approximated or left out.
pub warnings: Vec<String>,
/// Notes on the options: sorting the paths or drawing the inner paths first was applied only
/// in part.
pub setting_notes: Vec<String>,
}
/// Write the visible art of `doc` over `opts.region` as an HP-GL plot. Live geometry effects are
@@ -280,10 +283,11 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R
if !by_pen.iter().all(Vec::is_empty) {
pen_warnings.iter().for_each(|w| warn(&mut warnings, w));
}
let mut setting_notes = vec![];
if opts.sort || opts.inside_first {
let (mut at, mut work) = ((0, 0), MAX_SORT_WORK);
for paths in &mut by_pen {
at = reorder(paths, at, &mut work, opts.sort, opts.inside_first, &mut warnings);
at = reorder(paths, at, &mut work, opts.sort, opts.inside_first, &mut setting_notes);
}
}
if opts.version == Version::Hpgl && by_pen.iter().flatten().flatten().any(|(x, y)| !CLASSIC_RANGE.contains(x) || !CLASSIC_RANGE.contains(y)) {
@@ -293,7 +297,7 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R
Version::Hpgl => plain(&by_pen),
Version::Hpgl2 => encoded(&by_pen, &pens),
};
out.push(HpglOutput { bytes, pens: pens.clone(), warnings });
out.push(HpglOutput { bytes, pens: pens.clone(), warnings, setting_notes });
}
Ok(out)
}
@@ -366,20 +370,20 @@ fn box_dist2(p: (i64, i64), b: [i64; 4]) -> i128 {
/// for a closed path any of its points (where it then starts); without, the first in paint order.
/// With `inside_first`, a path is drawn only once every path lying inside it ([`nest::outer`]) is.
/// Once `work` is spent, the paths left keep paint order, each after the paths inside it with
/// `inside_first`, with a warning. Returns where the pen stops.
/// `inside_first`, with a note in `notes`. Returns where the pen stops.
fn reorder(
paths: &mut Vec<Vec<(i64, i64)>>,
mut at: (i64, i64),
work: &mut u64,
nearest: bool,
inside_first: bool,
warnings: &mut Vec<String>,
notes: &mut Vec<String>,
) -> (i64, i64) {
let boxes: Vec<[i64; 4]> = paths.iter().map(|p| nest::bounds(p)).collect();
// The paths each path lies inside, and how many paths inside each are still to draw.
let outer = inside_first.then(|| nest::outer(paths, &boxes, work)).flatten();
if inside_first && outer.is_none() {
warn(warnings, UNNESTED);
warn(notes, UNNESTED);
}
let mut waiting = vec![0usize; paths.len()];
for o in outer.iter().flatten().flatten() {
@@ -430,11 +434,11 @@ fn reorder(
if *work == 0 || best.0 >= left.len() {
match &outer {
Some(outer) => {
warn(warnings, UNSORTED_INSIDE);
warn(notes, UNSORTED_INSIDE);
inner_first(left.into_iter().map(|(j, p, _)| (j, p)).collect(), outer, &mut waiting, paths);
}
None => {
warn(warnings, UNSORTED);
warn(notes, UNSORTED);
paths.extend(left.into_iter().map(|(_, p, _)| p));
}
}
+7 -6
View File
@@ -852,7 +852,8 @@ fn sorting_measures_a_closed_path_by_its_nearest_point() {
fn sorting_stops_at_its_budget_and_keeps_every_path() {
let d = doc_with(|d| (0..600).map(|i| stroked(d, line((1.0 + (i % 100) as f64, 10.0), (1.0 + (i % 100) as f64, 20.0)), Color::BLACK)).collect());
let out = plot(&d, &HpglOptions { sort: true, ..opts(&d) });
assert!(out.warnings.iter().any(|w| w == UNSORTED), "{:?}", out.warnings);
assert_eq!(out.setting_notes, [UNSORTED]);
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
assert_eq!(text(&out).matches("PD").count(), 600);
}
@@ -944,18 +945,18 @@ fn inside_first_orders_each_pens_paths() {
}
/// Finding which of 100 nested rings lie inside which is past the budget: they are drawn in
/// paint order, with a warning.
/// paint order, with a note on the option.
#[test]
fn inside_first_past_its_budget_draws_in_paint_order() {
let d = doc_with(|d| (0..100).map(|i| stroked(d, rect(1.0 + 0.4 * f64::from(i), 10.0, 199.0, 90.0), Color::BLACK)).collect());
let out = plot(&d, &HpglOptions { inside_first: true, ..opts(&d) });
assert_eq!(out.warnings, [UNNESTED]);
assert_eq!(out.setting_notes, [UNNESTED]);
let l = lefts(&out);
assert_eq!(l.len(), 100);
assert!(l.windows(2).all(|w| w[0] <= w[1]), "{l:?}");
// With `sort` too, the budget is spent before sorting starts: paint order, with both warnings.
// With `sort` too, the budget is spent before sorting starts: paint order, with both notes.
let out = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) });
assert_eq!(out.warnings, [UNNESTED, UNSORTED]);
assert_eq!(out.setting_notes, [UNNESTED, UNSORTED]);
assert_eq!(lefts(&out), l);
}
@@ -969,7 +970,7 @@ fn inside_first_past_its_sorting_budget_keeps_the_rings_last() {
v
});
let out = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) });
assert_eq!(out.warnings, [UNSORTED_INSIDE]);
assert_eq!(out.setting_notes, [UNSORTED_INSIDE]);
let l = lefts(&out);
assert_eq!(l.len(), 602);
assert_eq!(l.get(600..), Some(&[plu(0.7), plu(0.5)][..]));
+3
View File
@@ -410,6 +410,9 @@ pub struct DxfOutput {
pub images: Vec<DxfImage>,
/// What was approximated or left out.
pub warnings: Vec<String>,
/// What was left out because an option turns it off (Include Placed Images or Include Fill
/// Hatches off).
pub setting_notes: Vec<String>,
}
/// The smallest and largest `scale` (drawing units per unit).
+15 -3
View File
@@ -520,6 +520,8 @@ pub(crate) struct Scene<'a> {
/// Image keys → index into `images` (`None`: left out).
by_key: HashMap<String, Option<usize>>,
warnings: Vec<String>,
/// What was left out because an option asked for it ([`DxfOutput::setting_notes`]).
setting_notes: Vec<String>,
brushes: Option<Vec<vectorcraft_brush::Brush>>,
extents: Option<[f64; 4]>,
/// The opacity of the containers around the current object.
@@ -554,6 +556,7 @@ impl<'a> Scene<'a> {
files: vec![],
by_key: HashMap::new(),
warnings: vec![],
setting_notes: vec![],
brushes: None,
extents: None,
opacity: 1.0,
@@ -588,15 +591,24 @@ impl<'a> Scene<'a> {
metric: matches!(self.o.unit, Unit::Millimeters | Unit::Centimeters | Unit::Meters),
next: self.next,
};
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings }
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings, setting_notes: self.setting_notes }
}
/// Note `w`, once, about something of the document that the drawing leaves out or that reaches
/// it changed. A note about an option goes to [`Self::note_setting`].
fn warn(&mut self, w: &str) {
if !self.warnings.iter().any(|x| x == w) {
self.warnings.push(w.to_string());
}
}
/// Note `w`, once, about something left out because an option turns it off.
fn note_setting(&mut self, w: &str) {
if !self.setting_notes.iter().any(|x| x == w) {
self.setting_notes.push(w.to_string());
}
}
fn handle(&mut self) -> Handle {
let h = Handle(self.next);
self.next = self.next.saturating_add(1);
@@ -930,7 +942,7 @@ impl<'a> Scene<'a> {
// The outlines close as the fill does, so an open path's fill keeps its closing edge.
self.lines(&closed_fill(outline), style, 0.0);
if !self.o.include_hatches {
self.warn(HATCHES_OFF);
self.note_setting(HATCHES_OFF);
return;
}
let h = self.handle();
@@ -1321,7 +1333,7 @@ impl<'a> Scene<'a> {
return;
}
if !self.o.include_images {
self.warn(IMAGES_OFF);
self.note_setting(IMAGES_OFF);
return;
}
let Some(i) = self.image_def(im) else { return };
+13 -8
View File
@@ -881,12 +881,13 @@ fn fills_without_hatches_keep_their_outlines() {
let d = shapes_doc();
let out = export(&d, &DxfOptions { include_hatches: false, ..opts(&d) }).unwrap();
assert_eq!(kinds(&out), ["LWPOLYLINE", "LWPOLYLINE", "CIRCLE"], "the fill's outline, the stroke, the circle");
assert_eq!(out.warnings, [HATCHES_OFF]);
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
assert_eq!(out.setting_notes, [HATCHES_OFF]);
let e = entities(&out);
assert_eq!((get(&e[0], 70), get(&e[0], 370)), (Some("1"), None), "the closed outline, without a lineweight");
// Hatches stay by default, with no note.
let on = export(&d, &opts(&d)).unwrap();
assert!(kinds(&on).iter().any(|k| k == "HATCH") && !on.warnings.iter().any(|w| w == HATCHES_OFF));
assert!(kinds(&on).iter().any(|k| k == "HATCH") && on.setting_notes.is_empty());
// The outlines are the ones written beside hatches, also for overlapping subpaths, which are
// merged first; a fill with no area (a flat rectangle, a diagonal line) writes nothing either way.
let compound = doc_with(|d| {
@@ -916,13 +917,14 @@ fn fills_without_hatches_keep_their_outlines() {
assert!(!kinds(&altered).iter().any(|k| k == "HATCH") && !kinds(&altered).is_empty(), "{:?}", kinds(&altered));
// Nothing filled: no note.
let lines = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
assert!(export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap().warnings.is_empty());
let none = export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap();
assert!(none.warnings.is_empty() && none.setting_notes.is_empty());
// R12 has no hatches anyway: the same outlines, and its own note alone.
let r12 = |include_hatches| export(&d, &DxfOptions { version: DxfVersion::R12, include_hatches, ..opts(&d) }).unwrap();
let (off, on) = (r12(false), r12(true));
assert_eq!(off.bytes, on.bytes);
assert_eq!(off.warnings, on.warnings);
assert!(!off.warnings.iter().any(|w| w == HATCHES_OFF));
assert!(off.setting_notes.is_empty());
}
#[test]
@@ -957,15 +959,18 @@ fn images_can_be_left_out_with_their_files() {
let p = pairs(&out.bytes);
assert!(!section(&p, "OBJECTS").iter().any(|o| matches!(kind(o), "IMAGEDEF" | "IMAGEDEF_REACTOR" | "RASTERVARIABLES")));
assert!(!section(&p, "CLASSES").iter().any(|o| get(o, 1) == Some("IMAGE")));
assert_eq!(out.warnings, [IMAGES_OFF]);
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
assert_eq!(out.setting_notes, [IMAGES_OFF]);
// An image that can't be decoded is not read when images are left out.
let mut broken = d.clone();
broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None });
assert_eq!(export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap().warnings, [IMAGES_OFF]);
let left_out = export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap();
assert!(left_out.warnings.is_empty(), "{:?}", left_out.warnings);
assert_eq!(left_out.setting_notes, [IMAGES_OFF]);
assert!(export(&broken, &opts(&broken)).unwrap().warnings.iter().any(|w| w.contains("couldn't be decoded")));
// R12 has no images anyway: its own note alone.
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, include_images: false, ..opts(&d) }).unwrap();
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && !r12.warnings.iter().any(|w| w == IMAGES_OFF));
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && r12.setting_notes.is_empty());
}
#[test]
@@ -983,7 +988,7 @@ fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_b
let cnc = run(DxfPreset::Cnc.options());
assert_eq!(kinds(&cnc), ["LWPOLYLINE"]);
assert!(cnc.images.is_empty());
assert!(cnc.warnings.iter().any(|w| w == IMAGES_OFF) && cnc.warnings.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.warnings);
assert!(cnc.setting_notes.iter().any(|w| w == IMAGES_OFF) && cnc.setting_notes.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.setting_notes);
let custom = DxfPreset::Custom.options();
assert!(custom.include_images && custom.include_hatches, "Custom keeps both");
}
+78 -13
View File
@@ -6,8 +6,9 @@
//! * **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);
//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
//! * The **active settings** (Edit → Color Settings) are process-wide; [`crate::Color::to_rgb`]
//! uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`].
//! * 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;
//! [`crate::Color::to_rgb`] uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`].
pub mod generic;
pub mod icc;
@@ -320,6 +321,9 @@ pub struct Cms {
settings: ColorSettings,
rgb: RgbSpace,
cmyk: CmykSpace,
/// The working settings, when a document's assigned profiles take the place of their spaces
/// ([`use_document_profiles`]): a [`ProofTarget::WorkingCmyk`] proof simulates their CMYK space.
working: Option<Arc<Cms>>,
}
impl std::fmt::Debug for Cms {
@@ -330,7 +334,7 @@ impl std::fmt::Debug for Cms {
impl Default for Cms {
fn default() -> Self {
Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()) }
Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()), working: None }
}
}
@@ -338,7 +342,7 @@ impl Cms {
/// Profiles named by a legacy name are stored under their current name.
pub fn new(settings: &ColorSettings) -> Result<Self, CmsError> {
let settings = ColorSettings { rgb: canonical_name(&settings.rgb).into(), cmyk: canonical_name(&settings.cmyk).into(), ..settings.clone() };
Ok(Self { rgb: rgb_space(&settings.rgb)?, cmyk: cmyk_space(&settings.cmyk)?, settings })
Ok(Self { rgb: rgb_space(&settings.rgb)?, cmyk: cmyk_space(&settings.cmyk)?, settings, working: None })
}
pub fn settings(&self) -> &ColorSettings {
&self.settings
@@ -542,8 +546,9 @@ impl Cms {
ProofTarget::Deuteranopia => simulate_cvd(srgb, &DEUTERANOPIA),
ProofTarget::Tritanopia => TRITANOPIA.simulate(srgb),
ProofTarget::WorkingCmyk => {
let cmyk = self.srgb_to_cmyk(srgb, proof.intent);
self.cmyk_to_srgb(cmyk, proof.simulate_paper)
let working = self.working_cms();
let cmyk = working.srgb_to_cmyk(srgb, proof.intent);
working.cmyk_to_srgb(cmyk, proof.simulate_paper)
}
ProofTarget::Cmyk(name) => match cmyk_space(name) {
Ok(sp) => {
@@ -555,20 +560,29 @@ impl Cms {
}
}
/// Display sRGB of CMYK inks in the proof's CMYK space (the working space for RGB targets).
/// Display sRGB of CMYK inks in the proof's CMYK space (this context's CMYK space for RGB
/// targets).
pub fn proof_cmyk_to_srgb(&self, cmyk: [f32; 4], proof: &ProofSetup) -> [f32; 3] {
match &proof.target {
ProofTarget::Cmyk(name) => match cmyk_space(name) {
Ok(sp) => Self::cmyk_to_srgb_in(&sp, cmyk, proof.simulate_paper, self.settings.bpc),
Err(_) => self.cmyk_to_srgb(cmyk, proof.simulate_paper),
},
ProofTarget::WorkingCmyk => self.working_cms().cmyk_to_srgb(cmyk, proof.simulate_paper),
_ => self.cmyk_to_srgb(cmyk, proof.simulate_paper),
}
}
/// The context of the working settings: the one [`use_document_profiles`] put a document's
/// profiles in place of, else this one.
fn working_cms(&self) -> &Cms {
self.working.as_deref().unwrap_or(self)
}
/// A cached 3-D lookup table implementing [`Cms::proof_srgb`] for 8-bit pixels.
pub fn proof_lut(&self, proof: &ProofSetup) -> Arc<ProofLut> {
let key = format!("{:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper);
let working = self.working.as_ref().map(|w| &w.settings);
let key = format!("{:?}|{working:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper);
let mut cache = PROOF_CACHE.lock().unwrap_or_else(|e| e.into_inner());
if let Some((_, l)) = cache.iter().find(|(k, _)| *k == key) {
return l.clone();
@@ -890,10 +904,12 @@ impl CmykLut {
// ---------- the active (process-wide) settings ----------
static ACTIVE: RwLock<Option<Arc<Cms>>> = RwLock::new(None);
static WORKING: RwLock<Option<Arc<Cms>>> = RwLock::new(None);
static RGB_IS_SRGB: AtomicBool = AtomicBool::new(true);
static CMYK_IS_DEVICE: AtomicBool = AtomicBool::new(false);
/// The active colour-management context (Edit → Color Settings).
/// The active color-management context: the working settings, with the profiles
/// [`use_document_profiles`] last put in place of the working spaces.
pub fn active() -> Arc<Cms> {
if let Some(c) = ACTIVE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
return c.clone();
@@ -906,13 +922,62 @@ pub fn active_settings() -> ColorSettings {
active().settings.clone()
}
/// Replace the active settings (fails, leaving them unchanged, if a profile is unknown).
/// The color-management context of Edit → Color Settings (the working spaces, intent and black
/// point compensation), as [`set_active`] last set them, whatever profiles a document is assigned.
pub fn working() -> Arc<Cms> {
if let Some(c) = WORKING.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
return c.clone();
}
let mut w = WORKING.write().unwrap_or_else(|e| e.into_inner());
w.get_or_insert_with(|| Arc::new(Cms::default())).clone()
}
/// The settings of [`working`].
pub fn working_settings() -> ColorSettings {
working().settings.clone()
}
/// Replace the working settings (Edit → Color Settings) and make them the active settings (fails,
/// leaving both unchanged, if a profile is unknown).
pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
let cms = Cms::new(settings)?;
let cms = Arc::new(Cms::new(settings)?);
*WORKING.write().unwrap_or_else(|e| e.into_inner()) = Some(cms.clone());
install(cms);
Ok(())
}
/// Make the working settings the active settings, with the profiles a document is assigned
/// (`None`: none) in place of the working spaces. An assigned profile that is not available, or
/// is not of its model, leaves the working space. The working settings stay as they are. True when
/// the active settings changed.
pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool {
let working = working();
let mut st = working.settings.clone();
if let Some(p) = rgb.and_then(profile).filter(|p| p.kind == ProfileKind::Rgb) {
st.rgb = p.name;
}
if let Some(p) = cmyk.and_then(profile).filter(|p| p.kind == ProfileKind::Cmyk) {
st.cmyk = p.name;
}
if st == active().settings {
return false;
}
if st == working.settings {
install(working);
return true;
}
// The working settings were checked when they were set; a working profile removed since then
// leaves the active settings as they are.
let Ok(mut cms) = Cms::new(&st) else { return false };
cms.working = Some(working);
install(Arc::new(cms));
true
}
fn install(cms: Arc<Cms>) {
RGB_IS_SRGB.store(cms.rgb_is_srgb(), Ordering::Relaxed);
CMYK_IS_DEVICE.store(matches!(cms.cmyk, CmykSpace::Device), Ordering::Relaxed);
*ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(cms));
Ok(())
*ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = Some(cms);
}
/// Fast path for [`Color::to_rgb`]: RGB colours need no conversion while the working space is sRGB.
+116 -10
View File
@@ -4,7 +4,8 @@
use kurbo::{Point, Rect, Vec2};
use super::{Gradient, GradientGeom, GradientKind, GradientSpread, GradientStop};
use super::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientSpread, GradientStop};
use crate::Color;
/// Most runs of the stops [`Gradient::padded_over`] writes.
pub const MAX_SPREAD_RUNS: usize = 256;
@@ -33,8 +34,8 @@ pub struct Padded {
pub first: f64,
/// How many runs are written, evenly spaced from [`Self::first`] to 1.
pub runs: usize,
/// The area needed more runs than [`MAX_SPREAD_RUNS`] (or than [`MAX_SPREAD_STOPS`] allows),
/// or runs past [`MAX_SPREAD_LEVEL`]: the gradient pads past the runs written.
/// The area needed more runs than [`MAX_SPREAD_RUNS`] (or more than half the stops allowed,
/// two to a run), or runs past [`MAX_SPREAD_LEVEL`]: the gradient pads past the runs written.
pub capped: bool,
}
@@ -50,7 +51,9 @@ impl Gradient {
self.padded_within(geom, area, MAX_SPREAD_STOPS)
}
/// [`Self::padded_over`] with at most `max_stops` stops (and at least one run).
/// [`Self::padded_over`] with at most `max_stops` stops (and at least one run). When the runs
/// written need more stops than that, each run leaves out the stops that change its colors
/// least ([`fit_run`]), so every run is still written.
pub fn padded_within(&self, geom: &GradientGeom, area: Rect, max_stops: usize) -> Option<Padded> {
let kind = self.kind;
if !self.is_spread() || matches!(kind, GradientKind::Conic | GradientKind::Freeform) || self.stops.is_empty() {
@@ -68,8 +71,8 @@ impl Gradient {
// smallest 0 when the area holds the rings' center, else on its edge.
let lo = if centered { inner_level(&period, kind, area).floor() } else { ts.iter().copied().fold(f64::INFINITY, f64::min).floor() };
let hi = ts.iter().copied().fold(f64::NEG_INFINITY, f64::max).ceil().max(lo + 1.0);
let one = whole_run(&self.stops);
let most = MAX_SPREAD_RUNS.min(max_stops.min(MAX_SPREAD_STOPS) / one.len().max(1)).max(1);
let budget = max_stops.min(MAX_SPREAD_STOPS);
let most = MAX_SPREAD_RUNS.min(budget / 2).max(1);
let capped = hi - lo > most as f64;
// Capped, the runs kept are the area's innermost ones (radial and diamond), or (linear)
// those around the vector's start where the area reaches it, else the area's runs nearest
@@ -79,6 +82,7 @@ impl Gradient {
_ => lo,
};
let n = (hi - lo).min(most as f64).max(1.0);
let one = fit_run(whole_run(&self.stops), budget / n as usize, self.method);
// A radial or diamond writes its runs among the levels from 0, which its stops' offsets
// (single-precision fractions of the outermost level) tell apart only so far out, the
// nearer the closer its stops lie: past that, the runs end there and the gradient pads.
@@ -112,8 +116,9 @@ impl Gradient {
self.unrolled_within(MAX_SPREAD_STOPS)
}
/// [`Self::unrolled`] with at most `max_stops` stops (and at least one run): past the runs
/// that fit, the last one pads.
/// [`Self::unrolled`] with at most `max_stops` stops: every run, each run without the stops
/// that change its colors least ([`fit_run`]) when the runs need more stops than that. Only with
/// fewer than two stops for each run do the runs past those that fit pad with the last one.
pub fn unrolled_within(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> {
use std::borrow::Cow;
if !self.is_spread() {
@@ -123,13 +128,29 @@ impl Gradient {
if self.stops.is_empty() {
return Cow::Owned(Gradient { spread: GradientSpread::Pad, repeats: 1, ..self.clone() });
}
let one = whole_run(&self.stops);
let n = self.repeat_count() as usize;
let kept = n.min(max_stops.min(MAX_SPREAD_STOPS) / one.len().max(1)).max(1);
let budget = max_stops.min(MAX_SPREAD_STOPS);
let kept = n.min(budget / 2).max(1);
let one = fit_run(whole_run(&self.stops), budget / kept, self.method);
let stops = self.runs(&one, false, 0.0, kept, n as f64);
Cow::Owned(Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() })
}
/// The gradient as [`Self::unrolled`] gives it with at most `max_stops` stops (at least two):
/// a gradient that repeats or reflects as [`Self::unrolled_within`] gives it, and one that
/// pads with more stops than that without the stops that change its colors least
/// ([`fit_run`]). Others as they are.
pub fn fitted(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> {
use std::borrow::Cow;
if self.is_spread() {
return self.unrolled_within(max_stops);
}
if self.stops.len() <= max_stops.max(2) {
return Cow::Borrowed(self);
}
Cow::Owned(Gradient { stops: fit_run(whole_run(&self.stops), max_stops, self.method), ..self.clone() })
}
/// One cycle of a gradient that repeats or reflects, which repeated end to end paints it, as
/// a gradient that pads: one run of the stops (Repeat), or a run and its mirror (Reflect),
/// between 0 and 1, and how many runs that is (1 or 2). `None` for a gradient that pads and
@@ -257,6 +278,91 @@ fn whole_run(stops: &[GradientStop]) -> Vec<GradientStop> {
out
}
/// `one` (a run of a gradient's stops, [`whole_run`]) with at most `budget` stops (at least two):
/// as it is when it fits, else without the stops that change its colors least, left out one at a
/// time. Leaving out a stop costs how far its color lies from the one that mixing the stops still
/// on either side of it by `method` gives there, and how far its CMYK inks, opacity, tint or
/// process plates lie from the line between theirs (a whole unit when its swatch link or color
/// model differs from either of theirs, and a whole unit more when its midpoint or the one before
/// it is off center), so the ends, sharp steps, ink changes and shaped spans stay. A stop whose
/// next stop was left out gets its midpoint centered. The work is the stops times their logarithm.
fn fit_run(one: Vec<GradientStop>, budget: usize, method: GradientMethod) -> Vec<GradientStop> {
use std::cmp::Reverse;
use std::collections::BinaryHeap;
let budget = budget.max(2);
let n = one.len();
if n <= budget {
return one;
}
let mix = |x: &Color, y: &Color, v: f32| match method {
GradientMethod::Classic => x.lerp_keep_model(y, v),
m => m.mix(x, y, v),
};
let cost = |a: &GradientStop, s: &GradientStop, b: &GradientStop| -> u32 {
let span = b.offset - a.offset;
let u = if span > 0.0 { ((s.offset - a.offset) / span).clamp(0.0, 1.0) } else { 0.0 };
// Left out, the span from `a` to `b` has a centered midpoint, so it mixes them by `u`.
let (want, cs) = (mix(&a.color, &b.color, u).to_rgb(), s.color.to_rgb());
let color = (0..3).map(|k| (want[k] - cs[k]).abs()).fold(0.0, f32::max);
let opacity = (a.opacity + (b.opacity - a.opacity) * u - s.opacity).abs();
// Process inks, which colors that look alike can print differently: off their line, or a
// change of color model.
let process = match (&a.color, &s.color, &b.color) {
(Color::Cmyk { c: c0, m: m0, y: y0, k: k0 }, Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c1, m: m1, y: y1, k: k1 }) => {
[(c0, c, c1), (m0, m, m1), (y0, y, y1), (k0, k, k1)].iter().map(|(p, q, r)| (*p + (*r - *p) * u - *q).abs()).fold(0.0, f32::max)
}
_ if a.color.model() == s.color.model() && s.color.model() == b.color.model() => 0.0,
_ => 1.0,
};
let color = color.max(process);
// Separations: a change of swatch link, or of tint or process plates off their line.
let ink = if s.swatch != a.swatch || s.swatch != b.swatch {
1.0
} else {
let tint = (a.tint + (b.tint - a.tint) * u - s.tint).abs();
let plates = match (a.plates, s.plates, b.plates) {
(None, None, None) => 0.0,
(Some(pa), Some(ps), Some(pb)) => (0..4).map(|k| (pa[k] + (pb[k] - pa[k]) * u - ps[k]).abs()).fold(0.0, f32::max),
_ => 1.0,
};
tint.max(plates)
};
// Leaving it out merges two spans, and an off-center midpoint shapes one of them.
let shaped = if [a.midpoint, s.midpoint].iter().any(|m| (m - 0.5).abs() > 1e-3) { 1.0 } else { 0.0 };
// Non-negative, so the bits order as the numbers do (NaN counts as 0).
(color.max(opacity).max(ink) + shaped).max(0.0).to_bits()
};
// The stops still kept on either side of each stop, and each stop's latest cost entry.
let mut prev: Vec<usize> = (0..n).map(|i| i.saturating_sub(1)).collect();
let mut next: Vec<usize> = (1..=n).collect();
let mut gone = vec![false; n];
let mut version = vec![0u32; n];
let mut heap: BinaryHeap<Reverse<(u32, usize, u32)>> = (1..n - 1).map(|i| Reverse((cost(&one[i - 1], &one[i], &one[i + 1]), i, 0))).collect();
let mut left = n;
while left > budget {
let Some(Reverse((_, i, v))) = heap.pop() else { break };
if gone[i] || v != version[i] {
continue;
}
gone[i] = true;
left -= 1;
let (a, b) = (prev[i], next[i]);
next[a] = b;
prev[b] = a;
for j in [a, b] {
if j != 0 && j != n - 1 {
version[j] += 1;
heap.push(Reverse((cost(&one[prev[j]], &one[j], &one[next[j]]), j, version[j])));
}
}
}
one.into_iter()
.enumerate()
.filter(|(i, _)| !gone[*i])
.map(|(i, s)| if next[i] == i + 1 { s } else { GradientStop { midpoint: 0.5, ..s } })
.collect()
}
/// A run mirrored: the stops in reverse, each midpoint measured from the other side.
fn mirror(run: &[GradientStop]) -> Vec<GradientStop> {
let mut g = Gradient::new(GradientKind::Linear, run.to_vec());
+117 -5
View File
@@ -148,11 +148,12 @@ fn radial_and_diamond_gradients_pad_in_rings_from_their_first_level() {
}
}
/// A run of the stops far too short for the area, or a gradient of many stops, is written with at
/// most so many runs and stops, and pads past them; a conic, a padding gradient and one without
/// stops have nothing to pad.
/// A run of the stops far too short for the area is written with at most so many runs, and pads
/// past them; a gradient of many stops is written with every run the area needs, each run
/// without the stops that change its colors least, within so many stops; a conic, a padding
/// gradient and one without stops have nothing to pad.
#[test]
fn far_repeats_and_many_stops_are_capped() {
fn far_repeats_are_capped_and_many_stops_are_sampled() {
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.01, 0.0), aspect: 1.0, focal: None };
let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) };
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
@@ -162,7 +163,13 @@ fn far_repeats_and_many_stops_are_capped() {
let g = Gradient { spread: GradientSpread::Reflect, repeats: 50, ..Gradient::new(GradientKind::Linear, many) };
let wide = GradientGeom { end: Point::new(100.0, 0.0), ..geom };
let p = g.padded_over(&wide, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
assert!(p.capped && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{}", p.gradient.stops.len());
assert!(!p.capped && p.runs == 50 && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{} {}", p.runs, p.gradient.stops.len());
for x in [0.7, 33.3, 66.1, 99.5] {
let q = Point::new(x, 0.5);
let want = g.sample(g.spread_param(wide.param_at(GradientKind::Linear, q)) as f32).0.to_rgb();
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0.to_rgb();
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{x}: {want:?} vs {got:?}");
}
assert!(g.unrolled().stops.len() <= MAX_SPREAD_STOPS);
assert!(p.gradient.padded_over(&p.geom, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none(), "it pads");
assert!(spread(GradientKind::Conic, GradientSpread::Repeat, 3).padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none());
@@ -325,6 +332,111 @@ fn unrolled_and_cycle_stops() {
assert!(matches!(Gradient::default().unrolled(), std::borrow::Cow::Borrowed(_)));
}
/// A gradient of more stops than [`MAX_SPREAD_STOPS`] allows for all its runs keeps every run
/// when unrolled, each run without the stops that change its colors least: its last run ends on
/// its last color instead of the rest padding with it.
#[test]
fn unrolled_many_stops_keep_every_run() {
let stops: Vec<GradientStop> = (0..200).map(|i| GradientStop::new(i as f32 / 199.0, Color::gray(i as f32 / 199.0))).collect();
let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, stops) };
let u = g.unrolled();
assert!(u.stops.len() <= MAX_SPREAD_STOPS, "{}", u.stops.len());
for t in [0.005, 0.5051, 0.9149, 0.9951] {
let want = g.sample(g.spread_param(t) as f32).0.to_rgb();
let got = u.sample(t as f32).0.to_rgb();
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{t}: {want:?} vs {got:?}");
}
// A padding gradient fitted to fewer stops keeps its ends.
let pad = Gradient::new(GradientKind::Linear, g.stops.clone());
let fitted = pad.fitted(16);
assert_eq!(fitted.stops.len(), 16);
for (stop, want) in [(&fitted.stops[0], Color::gray(0.0)), (&fitted.stops[15], Color::gray(1.0))] {
assert!(stop.color.to_rgb().iter().zip(want.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-5), "{:?}", stop.color);
}
assert!(matches!(pad.fitted(500), std::borrow::Cow::Borrowed(_)));
}
/// One run of more stops than the limit (255 inside it, and a copy of each end color at 0 and 1)
/// is written within the limit, every run the area needs included.
#[test]
fn a_run_over_the_stop_limit_is_written_within_it() {
let stops: Vec<GradientStop> = (1..=255).map(|i| GradientStop::new(i as f32 / 256.0, Color::gray(i as f32 / 256.0))).collect();
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, stops) };
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(20.0, 0.0), aspect: 1.0, focal: None };
let p = g.padded_within(&geom, Rect::new(0.0, 0.0, 20.0, 1.0), 256).unwrap();
assert!(!p.capped && p.runs == 2 && p.gradient.stops.len() <= 256, "{} {} {}", p.capped, p.runs, p.gradient.stops.len());
assert!(g.unrolled_within(256).stops.len() <= 256);
}
/// Fitting a run to fewer stops keeps a narrow band between two sharp steps, a stop linked to a
/// swatch, and each kept stop's link and tint, where sampling at evenly spaced places would lose
/// them.
#[test]
fn fitting_keeps_sharp_steps_and_swatch_links() {
let mut stops: Vec<GradientStop> = (0..300).map(|i| GradientStop::new(i as f32 / 299.0, Color::gray(i as f32 / 299.0))).collect();
let red = Color::rgb(1.0, 0.0, 0.0);
// A band of red from 0.5003 to 0.5013, with a sharp step at each side.
for (offset, color) in [(0.5003, None), (0.5003, Some(red)), (0.5013, Some(red)), (0.5013, None)] {
let gray = Color::gray(offset);
stops.push(GradientStop::new(offset, color.unwrap_or(gray)));
}
let spot = GradientStop { swatch: Some("Ink".into()), tint: 0.4, ..GradientStop::new(0.25, Color::gray(0.25)) };
stops.push(spot.clone());
// Three stops of one ink that look alike but print at different tints.
for (offset, tint) in [(0.8, 0.2), (0.81, 0.9), (0.82, 0.2)] {
stops.push(GradientStop { swatch: Some("Ink2".into()), tint, ..GradientStop::new(offset, Color::gray(offset)) });
}
// A span shaped by an off-center midpoint.
if let Some(s) = stops.iter_mut().find(|s| (s.offset - 0.6).abs() < 2e-3) {
s.midpoint = 0.13;
}
stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
let g = Gradient::new(GradientKind::Linear, stops);
let fitted = g.fitted(32);
assert!(fitted.stops.len() <= 32, "{}", fitted.stops.len());
let red_at = |t: f32| fitted.sample(t).0.to_rgb();
assert_eq!(red_at(0.5008), [1.0, 0.0, 0.0], "the band stays");
assert!(red_at(0.499)[1] > 0.4 && red_at(0.503)[1] > 0.4, "the band stays narrow");
assert!(fitted.stops.iter().any(|s| s.swatch.as_deref() == Some("Ink") && s.tint == 0.4 && s.offset == 0.25), "{:?}", fitted.stops);
assert!(fitted.stops.iter().any(|s| s.swatch.as_deref() == Some("Ink2") && s.tint == 0.9), "the tint change stays");
assert!(fitted.stops.iter().any(|s| s.midpoint == 0.13), "the shaped span stays");
// Of a stop that changes only its ink's tint and one that the colors' line nearly gives, the
// first stays. (The stop before an ink starts stays as well: leaving it out would blend the
// ink in sooner.)
let ink = |offset: f32, tint: f32| GradientStop { swatch: Some("Ink2".into()), tint, ..GradientStop::new(offset, Color::gray(0.5)) };
let few = vec![
GradientStop::new(0.0, Color::gray(0.0)),
GradientStop::new(0.2, Color::gray(0.17)),
GradientStop::new(0.3, Color::gray(0.3)),
ink(0.4, 0.2),
ink(0.5, 0.9),
ink(0.6, 0.2),
GradientStop::new(1.0, Color::gray(1.0)),
];
let fitted = Gradient::new(GradientKind::Linear, few).fitted(6).into_owned();
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.3, 0.4, 0.5, 0.6, 1.0]);
// A Perceptual gradient leaves out the stop its own mixing gives, not the one the RGB line
// gives.
let (blue, yellow, gray) = (Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0), Color::rgb(0.5, 0.5, 0.5));
let on_curve = GradientMethod::Perceptual.mix(&gray, &yellow, 0.5);
let stops = vec![GradientStop::new(0.0, blue), GradientStop::new(0.5, gray), GradientStop::new(0.75, on_curve), GradientStop::new(1.0, yellow)];
let perceptual = Gradient { method: GradientMethod::Perceptual, ..Gradient::new(GradientKind::Linear, stops) };
let fitted = perceptual.fitted(3).into_owned();
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.5, 1.0]);
// A black of other inks between blacks that look the same prints differently: it stays.
let k = |offset: f32| GradientStop::new(offset, Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0 });
let rich = GradientStop::new(0.5, Color::Cmyk { c: 0.6, m: 0.4, y: 0.4, k: 1.0 });
let blacks = vec![k(0.0), k(0.4), rich, k(0.6), k(1.0)];
let fitted = Gradient::new(GradientKind::Linear, blacks).fitted(3).into_owned();
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.5, 1.0]);
let spread = Gradient { spread: GradientSpread::Repeat, repeats: 4, ..g.clone() };
let u = spread.unrolled_within(128);
assert_eq!(u.stops.iter().filter(|s| s.swatch.as_deref() == Some("Ink")).count(), 4, "one linked stop a run");
}
/// Pixels (what the canvas draws a diamond, dithered or Perceptual gradient as, and what SVG and
/// PDF write as images) repeat with the stops, for each kind.
#[test]
+115
View File
@@ -485,6 +485,88 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec<Vec<usize>> {
rows
}
/// The distinct colors [`theme_palette`] clusters, at most.
const THEME_CANDIDATES: usize = 4096;
/// The color palette of the weighted colors `samples` (color, weight), for Recolor Artwork's Color
/// Theme Picker: at most `n` colors. The same color given twice counts once with both weights,
/// and past [`THEME_CANDIDATES`] distinct colors, colors close in Lab merge into the heaviest of
/// them first.
/// The colors are grouped as [`cluster`] groups them, each group shows its heaviest color (a color
/// of `samples`, in its own model; on a tie the one given first), and the heaviest group comes
/// first (on a tie the group whose first color was given first). Samples without a positive,
/// finite weight are left out, so no samples give no colors.
pub fn theme_palette(samples: &[(Color, f32)], n: usize) -> Vec<Color> {
let mut index: std::collections::HashMap<ColorKey, usize> = std::collections::HashMap::new();
let mut colors: Vec<Color> = vec![];
let mut weights: Vec<f32> = vec![];
for (c, w) in samples {
if !(w.is_finite() && *w > 0.0) {
continue;
}
let i = *index.entry(ColorKey::of(c)).or_insert_with(|| {
colors.push(*c);
weights.push(0.0);
colors.len() - 1
});
weights[i] += w;
}
if colors.is_empty() || n == 0 {
return vec![];
}
// At most THEME_CANDIDATES colors are clustered: past that, colors in the same cube of Lab
// space merge into the heaviest of them, the cubes doubling in size until few enough remain.
if colors.len() > THEME_CANDIDATES {
let labs: Vec<[f32; 3]> = colors
.iter()
.map(|c| {
let l = c.to_lab();
[l.l, l.a, l.b]
})
.collect();
let mut side = 2.0f32;
loop {
let mut cube: std::collections::HashMap<[i32; 3], usize> = std::collections::HashMap::new();
let (mut top, mut sum): (Vec<usize>, Vec<f32>) = (vec![], vec![]);
for (i, lab) in labs.iter().enumerate() {
let k = lab.map(|v| (v / side).floor() as i32);
match cube.get(&k) {
Some(&j) => {
sum[j] += weights[i];
if weights[i] > weights[top[j]] {
top[j] = i;
}
}
None => {
cube.insert(k, top.len());
top.push(i);
sum.push(weights[i]);
}
}
}
if top.len() <= THEME_CANDIDATES {
colors = top.iter().map(|&i| colors[i]).collect();
weights = sum;
break;
}
side *= 2.0;
}
}
let mut groups: Vec<(f32, usize, Color)> = cluster(&colors, &weights, n)
.into_iter()
.filter_map(|g| {
let total: f32 = g.iter().map(|&i| weights[i]).sum();
let top = g.iter().copied().fold(None::<usize>, |best, i| match best {
Some(b) if weights[b] >= weights[i] => Some(b),
_ => Some(i),
})?;
Some((total, *g.first()?, colors[top]))
})
.collect();
groups.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
groups.into_iter().map(|g| g.2).collect()
}
/// A set of colours to snap to (Limit to Library), with their Lab values cached.
#[derive(Clone, Debug, Default)]
pub struct Palette(Vec<(Color, Lab)>);
@@ -691,6 +773,39 @@ mod tests {
assert!(cluster(&[], &[], 3).is_empty());
}
/// The Color Theme Picker's palette: similar colors merge, each group shows its heaviest
/// color in its own model, and the heaviest group comes first.
#[test]
fn theme_palette_takes_the_heaviest_color_of_each_group_heaviest_first() {
let red = Color::rgb(1.0, 0.0, 0.0);
let pink = Color::rgb(1.0, 0.2, 0.2);
let blue = Color::cmyk(1.0, 0.8, 0.0, 0.0);
let navy = Color::cmyk(1.0, 0.9, 0.0, 0.3);
let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 2.5), (red, 0.5)];
// Blue and navy weigh 4.5, and so do red (3 + 0.5, its two samples add up) and pink.
assert_eq!(theme_palette(&samples, 2), vec![red, navy], "a tie: the group given first");
let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 1.0)];
assert_eq!(theme_palette(&samples, 2), vec![red, blue], "heaviest group first, its heaviest color");
assert_eq!(theme_palette(&samples, 9).len(), 4, "never more colors than given");
assert_eq!(theme_palette(&samples, 1), vec![red]);
assert!(theme_palette(&samples, 0).is_empty());
assert!(theme_palette(&[(red, 0.0), (blue, f32::NAN), (pink, -1.0)], 3).is_empty(), "no weight, no colors");
assert!(theme_palette(&[], 3).is_empty());
}
/// Past 4,096 distinct colors, close colors merge before clustering: the palette still keeps
/// a heavy color apart from thousands of light ones.
#[test]
fn theme_palette_merges_close_colors_past_its_candidate_limit() {
let mut samples: Vec<(Color, f32)> = (0..20_000).map(|i| (Color::rgb(0.0, 0.0, 0.3 + 0.7 * i as f32 / 20_000.0), 0.001)).collect();
samples.extend((0..20_000).map(|i| (Color::rgb(1.0, 0.8 * i as f32 / 20_000.0, 0.0), 0.0001)));
samples.push((Color::rgb(0.0, 1.0, 0.0), 50.0));
let p = theme_palette(&samples, 3);
assert_eq!(p.len(), 3);
assert_eq!(p[0], Color::rgb(0.0, 1.0, 0.0), "the heavy green first, exactly as given");
assert!(p[1].to_hsb()[0] > 180.0 && p[2].to_hsb()[0] < 90.0, "then the blues, then the reds and oranges: {p:?}");
}
#[test]
fn hue_shift_with_own_model_puts_every_colour_of_the_row_in_the_new_model() {
let to = Color::cmyk(0.0, 1.0, 1.0, 0.0);
+1 -1
View File
@@ -10,7 +10,7 @@ mod stroke_style;
pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds};
pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
pub use stroke_style::{ArrowAlign, Arrowhead, CustomArrowhead, Dash, LineCap, LineJoin, StrokeAlign};
/// One entry of the appearance stack.
// A stroke takes 328 bytes and a fill 104; an appearance holds a few of each.
+4 -2
View File
@@ -193,8 +193,10 @@ impl StrokeLayer {
/// How far the start (`end == false`) or end arrowhead can reach from its end point (0
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
pub fn head_reach(&self, end: bool) -> f64 {
let head = if end { self.end_arrow } else { self.start_arrow };
head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0)
let head = if end { &self.end_arrow } else { &self.start_arrow };
// A custom head can paint in front of its tip, which Extend puts past the end point.
let reach = |k: &Arrowhead| if self.arrow_align == ArrowAlign::Extend { k.reach().max(k.length()) } else { k.reach() };
head.as_ref().map_or(0.0, |k| reach(k) * self.arrow_weight(end) + self.width / 2.0)
}
/// How far the arrowheads can reach from the path's end points (0 without heads).
pub fn arrow_reach(&self) -> f64 {
+98 -5
View File
@@ -1,3 +1,7 @@
use std::sync::Arc;
use vectorcraft_geom::{PathData, Rect};
use super::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -53,8 +57,74 @@ impl Dash {
/// (the open arrow's arms are cut square a little behind the box).
const HEAD_REACH: f64 = 4.6;
/// An arrowhead the user drew (Stroke panel menu › Edit Arrowheads…), carried with its art so a
/// document that uses it draws it wherever it opens.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(from = "CustomArrowheadData")]
pub struct CustomArrowhead {
/// The name the arrowhead menus show (the symbol's name in the arrowheads file).
pub name: String,
/// The filled outline (non-zero rule) in head units: x from the tip (0) back along the line, y
/// across it, positive to the right of the direction the head points. A head is 4 units wide,
/// as the built-in heads are, and a unit is the head's weight.
pub path: PathData,
}
#[derive(Deserialize)]
struct CustomArrowheadData {
name: String,
#[serde(default)]
path: PathData,
}
impl From<CustomArrowheadData> for CustomArrowhead {
fn from(d: CustomArrowheadData) -> Self {
CustomArrowhead::new(d.name, d.path)
}
}
impl CustomArrowhead {
/// The most anchors a custom head's outline may have, and the most subpaths.
pub const MAX_ANCHORS: usize = 4096;
/// How far from the tip a custom head's outline may reach, in head units.
pub const MAX_UNITS: f64 = 64.0;
/// Head `name` with outline `path` (in head units). An outline with more than
/// [`Self::MAX_ANCHORS`] anchors or subpaths, a point that is not finite, or a point farther
/// than [`Self::MAX_UNITS`] from the tip is dropped: the head then draws nothing.
pub fn new(name: String, path: PathData) -> Self {
let path = if Self::fits(&path) { path } else { PathData::default() };
CustomArrowhead { name, path }
}
/// Whether outline `path` has at most [`Self::MAX_ANCHORS`] anchors and as many subpaths, with
/// finite points within [`Self::MAX_UNITS`] only.
pub fn fits(path: &PathData) -> bool {
let anchors = path.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>();
let near = |p: vectorcraft_geom::Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= Self::MAX_UNITS && p.y.abs() <= Self::MAX_UNITS;
anchors <= Self::MAX_ANCHORS
&& path.subpaths.len() <= Self::MAX_ANCHORS
&& path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| near(a.p) && near(a.h_in) && near(a.h_out))
}
fn bounds(&self) -> Option<Rect> {
self.path.control_bounds()
}
/// How far any part of the head can be from its tip, in head units.
pub fn reach(&self) -> f64 {
self.bounds().map_or(0.0, |b| b.x0.hypot(b.y0).max(b.x1.hypot(b.y0)).max(b.x0.hypot(b.y1)).max(b.x1.hypot(b.y1)))
}
/// How far the head spreads either side of its line, in head units.
pub fn half_width(&self) -> f64 {
self.bounds().map_or(0.0, |b| b.y0.abs().max(b.y1.abs()))
}
/// Where the stroke ends under the head, in head units back from the tip: halfway along the
/// head's length.
pub fn stop(&self) -> f64 {
self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0)
}
}
/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Arrowhead {
Triangle,
TriangleOpen,
@@ -102,6 +172,8 @@ pub enum Arrowhead {
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
/// the other heads.
LineArrow,
/// A head the user drew, with its art.
Custom(Arc<CustomArrowhead>),
}
impl Arrowhead {
@@ -151,23 +223,43 @@ impl Arrowhead {
];
/// How far any part of the head can be from its tip, in units of its weight.
pub fn reach(self) -> f64 {
pub fn reach(&self) -> f64 {
match self {
// Its farthest corners are 4 + ½√2 back and 4 − ½√2 out.
Arrowhead::LineArrow => 5.75,
Arrowhead::Custom(c) => c.reach(),
_ => HEAD_REACH,
}
}
/// How far the head spreads either side of its line, in units of its weight.
pub fn half_width(self) -> f64 {
pub fn half_width(&self) -> f64 {
match self {
Arrowhead::LineArrow => 4.0,
Arrowhead::Custom(c) => c.half_width(),
_ => 2.0,
}
}
/// How far past its end point a head placed with [`ArrowAlign::Extend`] can paint, in units of
/// its weight: the built-in heads' length, or a custom head's reach past its tip, which sits
/// [`CustomArrowhead::stop`] past the end point.
pub fn length(&self) -> f64 {
match self {
Arrowhead::Custom(c) => c.stop() + c.reach(),
_ => 4.0,
}
}
/// The name the arrowhead menus show.
pub fn label(self) -> &'static str {
/// The name the arrowhead menus show: [`Self::label`], or a custom head's own name.
pub fn name(&self) -> &str {
match self {
Arrowhead::Custom(c) => &c.name,
_ => self.label(),
}
}
/// The name the arrowhead menus show for a built-in head ("Custom" for a custom one, whose
/// own name is [`Self::name`]).
pub fn label(&self) -> &'static str {
match self {
Arrowhead::Triangle => "Triangle",
Arrowhead::TriangleOpen => "Triangle (open)",
@@ -210,6 +302,7 @@ impl Arrowhead {
Arrowhead::TriangleBar => "Triangle to Bar",
Arrowhead::Oval => "Oval",
Arrowhead::LineArrow => "Line Arrow",
Arrowhead::Custom(_) => "Custom",
}
}
}
+53 -1
View File
@@ -337,13 +337,65 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
];
for name in SAVED {
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
assert_eq!(serde_json::to_value(a).unwrap(), name);
assert_eq!(serde_json::to_value(&a).unwrap(), name);
assert_eq!(Arrowhead::ALL.iter().filter(|x| **x == a).count(), 1, "{name} in the menu once");
}
let labels: std::collections::HashSet<&str> = Arrowhead::ALL.iter().map(|a| a.label()).collect();
assert_eq!(labels.len(), Arrowhead::ALL.len(), "labels are distinct");
}
/// A custom head: a triangle from its tip back 3 units, 2 units right and 1 left of its line.
fn custom_head() -> Arrowhead {
use vectorcraft_geom::{PathData, Point, SubPath};
let path = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true));
Arrowhead::Custom(std::sync::Arc::new(CustomArrowhead::new("Wedge".into(), path)))
}
#[test]
fn custom_arrowheads_carry_their_art_and_measure_it() {
let head = custom_head();
assert_eq!((head.name(), head.label()), ("Wedge", "Custom"));
assert_eq!(head.reach(), 3.0f64.hypot(2.0));
assert_eq!(head.half_width(), 2.0);
let Arrowhead::Custom(c) = &head else { panic!("custom") };
assert_eq!(c.stop(), 1.5, "the line stops halfway along the head");
// Saved with the stroke, art and all, beside the built-in heads' names.
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
(st.start_arrow, st.end_arrow) = (Some(Arrowhead::Triangle), Some(head.clone()));
let json = serde_json::to_value(&st).unwrap();
assert_eq!(json["start_arrow"], "Triangle");
assert_eq!(json["end_arrow"]["Custom"]["name"], "Wedge");
let back: StrokeLayer = serde_json::from_value(json).unwrap();
assert_eq!(back, st);
// Extended, the tip sits the stop past the end point; on it, only the reach counts.
assert_eq!(head.length(), 1.5 + head.reach());
assert_eq!(st.head_reach(true), head.length() * 2.0 + 1.0);
st.arrow_align = ArrowAlign::Tip;
assert_eq!(st.head_reach(true), head.reach() * 2.0 + 1.0);
}
#[test]
fn custom_arrowheads_out_of_bounds_draw_nothing() {
let Arrowhead::Custom(c) = custom_head() else { panic!("custom") };
let mut path = c.path.clone();
path.subpaths[0].anchors[1] = vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1e9, 0.0));
// A file can hold what `new` drops: reading it drops it too.
let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path }).unwrap();
let far: CustomArrowhead = serde_json::from_value(json).unwrap();
assert_eq!((far.name.as_str(), far.path.subpaths.len()), ("Wedge", 0));
assert_eq!((far.reach(), far.half_width(), far.stop()), (0.0, 0.0, 0.0));
let anchors = vec![vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1.0, 0.0)); CustomArrowhead::MAX_ANCHORS + 1];
let many = CustomArrowhead::new("Many".into(), vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::new(anchors, true)));
assert!(many.path.subpaths.is_empty(), "too many anchors");
// Empty subpaths add no anchors, and still count.
let mut hollow = c.path.clone();
hollow.subpaths.extend(std::iter::repeat_n(vectorcraft_geom::SubPath::new(vec![], false), CustomArrowhead::MAX_ANCHORS));
assert!(!CustomArrowhead::fits(&hollow), "too many subpaths");
let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow }).unwrap();
let hollow: CustomArrowhead = serde_json::from_value(json).unwrap();
assert!(hollow.path.subpaths.is_empty(), "too many subpaths, read back");
}
#[test]
fn arrow_align_defaults_to_extend_and_round_trips() {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
+3 -3
View File
@@ -569,7 +569,7 @@ fn clip_contains(clip: &Node, p: Point) -> bool {
/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in
/// [`clip_contains`].
fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
let frame = |n: &Node| {
let b = n.geometric_bounds()?;
Some(Node::path(n.id, vectorcraft_geom::shapes::rectangle(b), Default::default()))
@@ -640,7 +640,7 @@ fn source_of(n: &Node, scope: Option<NodeId>) -> bool {
/// Do clicks and marquees skip the child `i` of `parent` with `scope` isolated? For a Shaper
/// Group that is its original shapes (its first child), or, in Construction mode, when they are
/// isolated, the art the group shows.
fn shaper_hides(parent: &Node, i: usize, scope: Option<NodeId>) -> bool {
pub fn shaper_hides(parent: &Node, i: usize, scope: Option<NodeId>) -> bool {
parent.extras().shaper.is_some() && (i == 0) != source_of(parent, scope)
}
@@ -1356,7 +1356,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
/// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None
/// when the marquee misses it); otherwise it is all of `r`.
fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
pub fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
match parent.children().and_then(|c| c.first()) {
Some(clip) if parent.clips() => marquee_in_clip(clip, r),
_ => Some(r),
+3 -3
View File
@@ -52,7 +52,7 @@ pub mod overprint;
pub mod pattern;
pub mod perspective;
mod pixels;
pub use pixels::{GraySource, MAX_RASTER_ALLOC};
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick};
pub mod placed_document;
pub mod plugin_data;
pub mod profiles;
@@ -83,8 +83,8 @@ pub(crate) mod skip;
pub use appearance::StrokeGradientMode;
pub use appearance::{
AngleProfile, Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, PressureProfile, ProfilePreset,
SavedProfile, StrokeAlign, StrokeLayer, WidthProfile,
AngleProfile, Appearance, AppearanceItem, ArrowAlign, Arrowhead, CustomArrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, PressureProfile,
ProfilePreset, SavedProfile, StrokeAlign, StrokeLayer, WidthProfile,
};
pub use assets::ExportAsset;
pub use compound_shape::ShapeMode;
+72
View File
@@ -11,6 +11,10 @@ use crate::ImageBlob;
/// address and aborts when an allocation fails, so it keeps the decoder's own 512 MB.
pub const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 };
/// A box of an image to sample, in 0 to 1 units of its width and height (`None`: all of it), and
/// the pixel centres to take from it ([`ImageBlob::sample_pixels`]).
pub type PixelPick<'a> = (Option<[f64; 4]>, &'a dyn Fn(f64, f64) -> bool);
/// The pixels of encoded image `bytes` as RGBA; `None` when they can't be decoded, would take
/// more than `max` bytes as RGBA, or need more than `max` bytes to decode. The size is read from
/// the header first: the decoder's limit is on the file's samples, and a gray image is a quarter
@@ -61,6 +65,49 @@ impl ImageBlob {
Some(Self::png(png))
}
/// For each of `picks`, at most `budget` of the image's pixels (at least one), spread evenly
/// in rows and columns over the pick's box (`[u0, v0, u1, v1]`, where 0 to 1 spans the
/// image's width and height from the top left; clipped to the image; `None`: the whole image),
/// as straight RGBA. Only pixels whose centres the pick's function takes (in the same 0 to 1
/// units) are given. The image is decoded once for all the picks. `None` when it can't be
/// decoded within [`MAX_RASTER_ALLOC`].
pub fn sample_pixels(&self, picks: &[PixelPick<'_>], budget: usize) -> Option<Vec<Vec<[u8; 4]>>> {
let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?;
let (w, h) = img.dimensions();
let (fw, fh) = (f64::from(w), f64::from(h));
let span = |a: f64, b: f64, n: f64| {
let (a, b) = (a.min(b), a.max(b));
((a * n).floor().clamp(0.0, n) as u32, (b * n).ceil().clamp(0.0, n) as u32)
};
let sample = |area: Option<[f64; 4]>, keep: &dyn Fn(f64, f64) -> bool| {
let [u0, v0, u1, v1] = area.unwrap_or([0.0, 0.0, 1.0, 1.0]);
let (x0, x1) = span(u0, u1, fw);
let (y0, y1) = span(v0, v1, fh);
if x0 >= x1 || y0 >= y1 {
return vec![];
}
// Rows and columns in proportion to the box, at most `budget` cells in all.
let (bw, bh, budget) = (f64::from(x1 - x0), f64::from(y1 - y0), budget.max(1) as f64);
let (sx, sy) = if bw * bh <= budget {
(1, 1)
} else {
let rows = (budget * bh / bw).sqrt().floor().clamp(1.0, bh.min(budget));
let cols = (budget / rows).floor().clamp(1.0, bw);
((bw / cols).ceil() as usize, (bh / rows).ceil() as usize)
};
let mut out = vec![];
for y in (y0..y1).step_by(sy) {
for x in (x0..x1).step_by(sx) {
if keep((f64::from(x) + 0.5) / fw, (f64::from(y) + 0.5) / fh) {
out.push(img.get_pixel(x, y).0);
}
}
}
out
};
Some(picks.iter().map(|(area, keep)| sample(*area, *keep)).collect())
}
/// The image as a grayscale PNG: `f` gives each pixel's gray level from its (straight) RGB, and
/// the PNG has an alpha channel only when some pixel isn't opaque. `f` runs once per distinct
/// color. `None` when the image can't be decoded, or when its file stores grayscale already
@@ -276,6 +323,31 @@ mod tests {
image::load_from_memory(&b.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
}
/// Sampling reads the pixels of a box of the image, spread to about the budget, and only those
/// whose centres `keep` takes.
#[test]
fn sampled_pixels_stay_in_their_box_and_budget() {
// 4 × 2: a red left half and a blue right half.
let (r, b) = ([255, 0, 0, 255], [0, 0, 255, 255]);
let img = blob(&[r, r, b, b, r, r, b, b], 4, 2);
let any = |_: f64, _: f64| true;
let one = |b: &ImageBlob, area: Option<[f64; 4]>, budget: usize| b.sample_pixels(&[(area, &any)], budget).unwrap().remove(0);
assert_eq!(one(&img, None, 100).len(), 8, "the budget covers every pixel");
assert_eq!(one(&img, Some([0.5, 0.0, 1.0, 1.0]), 100), vec![b; 4], "the right half");
assert_eq!(one(&img, Some([1.0, 1.0, 0.5, 0.0]), 100), vec![b; 4], "a box given backwards");
assert!(one(&img, Some([2.0, 0.0, 3.0, 1.0]), 100).is_empty(), "outside the image");
assert_eq!(one(&img, None, 2).len(), 2, "every second pixel of every second row");
assert_eq!(one(&img, None, 0), vec![r], "a budget of 0 counts as 1");
let left = |u: f64, _: f64| u < 0.5;
let both = img.sample_pixels(&[(None, &left), (Some([0.5, 0.0, 1.0, 1.0]), &any)], 100).unwrap();
assert_eq!(both, vec![vec![r; 4], vec![b; 4]], "several picks, each with the centres its function takes");
// A narrow image keeps to the budget too.
let tall = blob(&vec![r; 5000], 1, 5000);
let n = one(&tall, None, 100).len();
assert!((50..=100).contains(&n), "{n} pixels");
assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, &any)], 100).is_none());
}
/// A GIF whose `w` × `h` screen holds one opaque red pixel at the top left. The file holds no
/// other pixels, and the decoder makes them transparent.
fn gif_with_one_red_pixel(w: u16, h: u16) -> Vec<u8> {
+237 -69
View File
@@ -1,6 +1,7 @@
//! Where a path's strokes paint, from the path's geometry without building their outlines: the
//! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes
//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points.
//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points,
//! and a bevel ends at the corners of the two segments it joins.
use vectorcraft_geom::bez::{CORNER_COS, has_length, kink, segments, subpaths, tangent, unit};
use vectorcraft_geom::hit::fill_contains;
@@ -39,10 +40,20 @@ fn joints(segs: &[PathSeg], closed: bool) -> impl Iterator<Item = (Point, Vec2,
/// path: its tip and the corner's outer offset points, or `None` when the path doesn't turn there
/// or the miter limit bevels it.
fn miter(at: Point, t_in: Vec2, t_out: Vec2, side: f64, limit: f64) -> Option<[Point; 3]> {
let cos = t_in.dot(t_out);
// cos(half the turn) is sin(half the angle between the segments): the miter is side / it.
let half = ((1.0 + cos) / 2.0).max(0.0).sqrt();
if cos >= CORNER_COS || half * limit < 1.0 {
let half = ((1.0 + t_in.dot(t_out)) / 2.0).max(0.0).sqrt();
if half * limit < 1.0 {
return None;
}
let ([a, b], out) = bevel(at, t_in, t_out, side)?;
Some([a, at + out * (side / half), b])
}
/// The bevel at a corner with tangents `t_in`, `t_out` of a stroke reaching `side` from its path:
/// the outer corners of the two segments' strokes and the unit direction out of the turn, or
/// `None` when the path doesn't turn there.
fn bevel(at: Point, t_in: Vec2, t_out: Vec2, side: f64) -> Option<([Point; 2], Vec2)> {
if t_in.dot(t_out) >= CORNER_COS {
return None;
}
let out = unit(t_in - t_out);
@@ -51,7 +62,7 @@ fn miter(at: Point, t_in: Vec2, t_out: Vec2, side: f64, limit: f64) -> Option<[P
let n = Vec2::new(-t.y, t.x);
if n.dot(out) >= 0.0 { n } else { -n }
};
Some([at + outer(t_in) * side, at + out * (side / half), at + outer(t_out) * side])
Some(([at + outer(t_in) * side, at + outer(t_out) * side], out))
}
/// The heads' ends of `bp`: the start of its first subpath and the end of its last, when open (as
@@ -187,26 +198,44 @@ fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool {
}
impl StrokeLayer {
/// Does bounding this stroke need its path's shape: miter spikes, projecting caps, arrowheads,
/// an alignment that depends on whether the path is closed, or butt caps, which stop at the
/// ends of an open path? Else it reaches evenly round it.
/// Does bounding this stroke need its path's shape: miter spikes, bevels, projecting caps,
/// arrowheads, an alignment that depends on whether the path is closed, or butt caps, which
/// stop at the ends of an open path? Else it reaches evenly round it.
fn needs_shape(&self) -> bool {
self.join == LineJoin::Miter
self.join != LineJoin::Round
|| self.cap != LineCap::Round
|| self.start_arrow.is_some()
|| self.end_arrow.is_some()
|| self.align != StrokeAlign::Center
}
/// The box this stroke paints along `segs`, the segments with length of an open subpath, when
/// its caps are butt caps: each segment's [`swept_box`] and, with round joins, the arc each
/// joint between segments paints ([`round_join_box`]), a shallow one included.
/// `None` when `segs` is empty. Butt dashes stop inside the same box. The heads and miter tips
/// are measured apart. A segment in the middle is measured only when its own box grown by
/// `side`, which holds everything it paints, is not inside the box so far.
fn butt_body(&self, segs: &[PathSeg], side: f64) -> Option<Rect> {
/// Does this stroke stop at the corners of its segments along a subpath that is `closed` or
/// open, where its caps are butt caps on an open subpath or its joins are bevels or miters?
/// Dashes with round or projecting caps can end at a corner, so with them only butt caps stop.
fn stops_at_corners(&self, closed: bool) -> bool {
let capped_dashes = self.cap != LineCap::Butt && self.dash.as_ref().is_some_and(Dash::is_dashed);
(self.cap == LineCap::Butt && !closed) || (self.join != LineJoin::Round && !capped_dashes)
}
/// Does this stroke reach past a subpath that is `closed` or open by a margin that follows the
/// direction of its segments at their corners: where it stops at them
/// ([`Self::stops_at_corners`]) or paints miter spikes, which dashes with round or projecting
/// caps also paint?
fn reaches_by_corners(&self, closed: bool) -> bool {
self.stops_at_corners(closed) || self.join == LineJoin::Miter
}
/// The box this stroke's body paints along `segs`, the segments with length of a subpath, short
/// of its caps, joined with `within`: each segment's [`swept_box`] and, with round joins on an
/// open subpath, the arc each joint between segments paints ([`round_join_box`]), a shallow one
/// included. A bevel stays inside the boxes of the segments it joins. `None` when `segs` is
/// empty. Butt dashes stop inside the same box. The caps other than butt ones, the heads and
/// miter tips are measured apart. A segment in the middle is measured only when its own box
/// grown by `side`, which holds everything it paints, is not inside the box so far, which
/// starts as `within` and the first and last segments' boxes.
fn body_along(&self, segs: &[PathSeg], side: f64, within: Rect) -> Option<Rect> {
let (first, last) = (segs.first()?, segs.last()?);
let ends = swept_box(first, side, 3).union(swept_box(last, side, 3));
let ends = swept_box(first, side, 3).union(swept_box(last, side, 3)).union(within);
let body = segs.iter().skip(1).take(segs.len().saturating_sub(2)).fold(ends, |b, s| {
if b.contains_rect(ParamCurveExtrema::bounding_box(s).inflate(side, side)) { b } else { b.union(swept_box(s, side, 3)) }
});
@@ -217,24 +246,28 @@ impl StrokeLayer {
}
/// The box this stroke paints along `bp` (geometric bounds `bounds`): an open subpath with butt
/// caps by [`Self::butt_body`], every other subpath by the box of its segments grown by its
/// reach, with `tips` and, when `measure_tips`, the miter spikes the limit keeps, the corners of
/// projecting caps and the reach of the arrowheads round their end points.
/// caps, and every subpath when the joins are bevels or miters, by [`Self::body_along`] with its
/// caps, every other subpath by the box of its segments grown by its reach, with `tips` and,
/// when `measure_tips`, the miter spikes the limit keeps, the corners of projecting caps and the
/// reach of the arrowheads round their end points.
fn reach_along(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>, measure_tips: bool) -> Rect {
let els = bp.elements();
let subs = subpaths(bp);
let mut out = tips.map_or(bounds, |t| bounds.union(t));
let mut side_max: f64 = 0.0;
// Every subpath reaches evenly unless one is open and butt-capped; only then is each
// subpath's own box needed.
let even_only = self.cap != LineCap::Butt || subs.iter().all(|s| s.1);
let mut even = even_only.then_some(bounds);
// Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere.
let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed);
// A butt cap stops at an open subpath's end, and a bevel, or a miter the limit bevels, at
// the two segments' corners, so such a subpath is measured along its segments. Every
// subpath reaches evenly unless one is measured that way; only then is each subpath's own
// box needed.
let even_only = !subs.iter().any(|s| self.stops_at_corners(s.1));
let mut even = even_only.then_some(bounds);
for (r, closed) in subs {
let side = self.side_reach(closed);
let butt = self.cap == LineCap::Butt && !closed;
if !butt {
let along = self.stops_at_corners(closed);
if !along {
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
}
if side <= 0.0 {
@@ -242,10 +275,10 @@ impl StrokeLayer {
}
let square = self.cap == LineCap::Square && !closed;
let miters = measure_tips && self.join == LineJoin::Miter;
if !(butt || square || miters || !even_only) {
if !(along || square || miters || !even_only) {
continue;
}
let segs = drawn(&els[r]);
let segs = drawn(&els[r.clone()]);
if miters {
for (at, t_in, t_out) in joints(&segs, closed) {
if let Some([_, tip, _]) = miter(at, t_in, t_out, side, self.miter_limit) {
@@ -253,13 +286,24 @@ impl StrokeLayer {
}
}
}
if butt {
if let Some(body) = self.butt_body(&segs, side) {
out = out.union(body);
if along {
// The path's bounds are in the box already, so only the segments that can reach
// past them are measured.
match self.body_along(&segs, side, out) {
Some(body) => out = out.union(body),
// A subpath with no length paints at most its caps' dot.
None if !butt => {
let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b));
out = dot.map_or(out, |d| out.union(d.inflate(side, side)));
}
None => {}
}
continue;
}
if !even_only {
if self.cap == LineCap::Round && !closed {
for (at, _) in ends(&segs).into_iter().flatten() {
out = out.union(Rect::from_center_size(at, (2.0 * side, 2.0 * side)));
}
}
} else if !even_only {
even = vectorcraft_geom::union_opt(even, segs.iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)));
}
if square {
@@ -279,7 +323,8 @@ impl StrokeLayer {
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
/// projecting caps and the reach of the arrowheads round their end points. An open subpath
/// with butt caps does not reach past its ends ([`Self::butt_body`]).
/// with butt caps does not reach past its ends, and a bevel does not reach round its corner
/// ([`Self::body_along`]).
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
self.reach_along(bp, bounds, None, true)
}
@@ -329,6 +374,9 @@ impl StrokeLayer {
let segs = drawn(&els[r]);
let (half, region) = self.body(closed);
let full = half * self.profile_max() * dash_caps.unwrap_or(1.0);
// Past a butt cap or a bevel the stroke stops at the segments' corners. A width profile
// keeps the round reach at the ends.
let squared = self.profile.is_none() && self.stops_at_corners(closed);
// Every segment near enough to reach `p`: with a width profile the wider side of a
// farther segment can paint past the nearest one, so the nearest alone is not enough.
let near = segs.iter().enumerate().filter_map(|(i, s)| {
@@ -365,7 +413,8 @@ impl StrokeLayer {
}
})
};
if d <= half * factor.max(0.0) + tol && on_side(region, d) {
if d <= half * factor.max(0.0) + tol && on_side(region, d) && (!squared || self.paints_at_end(&segs, closed, (i, nr.t), p, half, tol))
{
return true;
}
}
@@ -393,6 +442,35 @@ impl StrokeLayer {
false
}
/// Does this stroke, where it stops at the corners of its segments ([`Self::stops_at_corners`]),
/// paint `p`, which is within `side` (and `tol`) of segment `i` of the subpath `segs`
/// (`closed`: a closed one) and nearest to it at `t`? It does when `p` is not past the end of
/// the segment that `t` is at, by more than `tol`, and past it when a round cap or a round join
/// paints there, when the path does not turn at that end, or when `p` is within `tol` of the
/// bevel's triangle. Projecting caps and
/// miter spikes are checked apart. A curve that bends more tightly than `side` ([`gentle`])
/// counts as painting round its ends.
fn paints_at_end(&self, segs: &[PathSeg], closed: bool, (i, t): (usize, f64), p: Point, side: f64, tol: f64) -> bool {
let (n, at_start) = (segs.len(), t <= 1e-9);
let Some(seg) = segs.get(i) else { return true };
if (!at_start && t < 1.0 - 1e-9) || !(matches!(seg, PathSeg::Line(_)) || gentle(seg, side)) {
return true;
}
let (at, out) = if at_start { (seg.start(), -tangent(seg, 0.0)) } else { (seg.end(), tangent(seg, 1.0)) };
if (p - at).dot(out) <= tol {
return true;
}
// The segment on the other side of this end, `None` at the end of an open subpath.
let other = if at_start { (i > 0 || closed).then(|| (i + n - 1) % n) } else { (i + 1 < n || closed).then(|| (i + 1) % n) };
let Some(other) = other.and_then(|o| segs.get(o)) else { return self.cap == LineCap::Round };
if self.join == LineJoin::Round {
return true;
}
let (t_in, t_out) = if at_start { (tangent(other, 1.0), tangent(seg, 0.0)) } else { (tangent(seg, 1.0), tangent(other, 0.0)) };
// A joint where the path does not turn has no bevel: the stroke runs on through it.
bevel(at, t_in, t_out, side).is_none_or(|([a, b], _)| in_convex(&[at, a, b], p, tol))
}
/// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path
/// leaving along `out`) can paint? A head reaches [`crate::Arrowhead::reach`] weights from its tip and
/// [`crate::Arrowhead::half_width`] either side of its line (4.6 and 2 for most). With
@@ -400,13 +478,15 @@ impl StrokeLayer {
/// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the
/// chord the path bends through under it, so anywhere within its length of the end.
fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool {
let Some(kind) = (if end { self.end_arrow } else { self.start_arrow }) else { return false };
let Some(kind) = (if end { &self.end_arrow } else { &self.start_arrow }) else { return false };
let (hw, v) = (self.arrow_weight(end), p - at);
match self.arrow_align {
ArrowAlign::Tip => v.hypot() <= kind.reach() * hw + tol,
ArrowAlign::Extend => {
let along = v.dot(out);
v.cross(out).abs() <= kind.half_width() * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -kind.reach() * hw - tol
v.cross(out).abs() <= kind.half_width() * hw + tol
&& along <= kind.length() * hw + self.width / 2.0 + tol
&& along >= -kind.reach() * hw - tol
}
}
}
@@ -426,7 +506,7 @@ impl Appearance {
}
/// [`Self::stroked_bounds`] with the box of each visible stroke that needs the path's shape
/// (miter spikes, projecting or butt caps, arrowheads or an alignment) given by `shaped`.
/// (miter spikes, bevels, projecting or butt caps, arrowheads or an alignment) given by `shaped`.
pub fn stroked_bounds_by(&self, bounds: Rect, mut shaped: impl FnMut(&StrokeLayer) -> Rect) -> Rect {
self.painted_strokes().fold(bounds, |acc, s| {
if !s.needs_shape() {
@@ -437,17 +517,21 @@ impl Appearance {
})
}
/// Does this appearance have a visible butt-capped stroke?
pub fn has_butt_stroke(&self) -> bool {
self.painted_strokes().any(|s| s.cap == LineCap::Butt)
/// Does this appearance have a visible stroke that stops at the corners of its segments on an
/// open subpath or a closed one, or paints miter spikes: butt caps, or bevel and miter joins
/// ([`StrokeLayer::reaches_by_corners`])?
pub fn has_cornered_stroke(&self) -> bool {
self.painted_strokes().any(|s| s.reaches_by_corners(false))
}
/// Does a visible butt-capped stroke of this appearance run along an open subpath of `bp` with
/// a segment that starts or ends at a slant, not square to the axes, once placed by `a`? The
/// visual box's margin at the stroke's corners there depends on their direction, which a scale
/// out of proportion changes.
pub fn has_slanted_butt_stroke(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool {
if !self.has_butt_stroke() {
/// Does a visible stroke of this appearance that stops at the corners of its segments (butt
/// caps on an open subpath, bevel and miter joins) or paints miter spikes, dashed ones with
/// round or projecting caps included, run along a subpath of `bp` where it does so, with a
/// segment that starts or ends at a slant, not square to the axes, once placed by `a`? The
/// visual box's margin at those corners, and at miter tips, depends on their direction, which a
/// scale out of proportion changes.
pub fn has_slanted_stroke_corners(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool {
if !self.has_cornered_stroke() {
return false;
}
let slanted = |v: Vec2| {
@@ -455,9 +539,10 @@ impl Appearance {
(d.x * d.y).abs() > 1e-9
};
let els = bp.elements();
subpaths(bp)
.into_iter()
.filter(|(_, closed)| !closed)
let subs = subpaths(bp);
let cornered = |closed: bool| self.painted_strokes().any(|s| s.reaches_by_corners(closed));
subs.into_iter()
.filter(|(_, closed)| cornered(*closed))
.any(|(r, _)| drawn(&els[r]).iter().any(|s| slanted(tangent(s, 0.0)) || slanted(tangent(s, 1.0))))
}
@@ -468,28 +553,28 @@ impl Appearance {
}
}
/// How many symbol instances [`crate::Node::has_slanted_butt_stroke`] looks into for one object
/// How many symbol instances [`crate::Node::has_slanted_stroke_corners`] looks into for one object
/// before it answers yes without looking further.
pub const SLANT_INSTANCES: usize = 4096;
impl crate::Node {
/// Does a visible butt-capped stroke of this object, of an object in it or of an object in a
/// symbol instance's art from `symbols`, placed by `a`, run along an open path with a segment
/// at a slant ([`Appearance::has_slanted_butt_stroke`])? Past [`SLANT_INSTANCES`] instances it
/// answers yes.
pub fn has_slanted_butt_stroke(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
self.slanted_butt(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
/// Does a visible stroke of this object, of an object in it or of an object in a symbol
/// instance's art from `symbols`, placed by `a`, stop at the corners of a segment at a slant
/// ([`Appearance::has_slanted_stroke_corners`])? Past [`SLANT_INSTANCES`] instances it answers
/// yes.
pub fn has_slanted_stroke_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
self.slanted_corners(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
}
/// [`Self::has_slanted_butt_stroke`] with `left` instances still to look into.
fn slanted_butt(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool {
/// [`Self::has_slanted_stroke_corners`] with `left` instances still to look into.
fn slanted_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool {
if let crate::NodeKind::SymbolInstance { symbol, xf } = &self.kind {
let Some(l) = left.get().checked_sub(1) else { return true };
left.set(l);
return symbols.measure_art(symbol, |art| art.slanted_butt(symbols, a * *xf, left)).unwrap_or(false);
return symbols.measure_art(symbol, |art| art.slanted_corners(symbols, a * *xf, left)).unwrap_or(false);
}
(self.appearance.has_butt_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_butt_stroke(&bp, a)))
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_butt(symbols, a, left)))
(self.appearance.has_cornered_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_stroke_corners(&bp, a)))
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_corners(symbols, a, left)))
}
}
@@ -566,6 +651,79 @@ mod tests {
assert_eq!(stroke(4.0, |s| s.align = StrokeAlign::Outside).bounds_on(&sq, b), b.inflate(4.0, 4.0));
}
#[test]
fn a_bevel_stops_at_the_corners_of_the_segments_it_joins() {
// A 40 × 100 pt triangle stroked 20 pt: a miter limit of 2 or a bevel join bevels its
// 22.6° tip at (20, 0), so the stroke reaches 10 · 20 / √10400 pt above it, not 10 pt.
let mut tri = BezPath::new();
tri.move_to((0.0, 100.0));
tri.line_to((20.0, 0.0));
tri.line_to((40.0, 100.0));
tri.close_path();
let tb = tri.bounding_box();
let (top, side) = (-200.0 / 10400.0_f64.sqrt(), 1000.0 / 10400.0_f64.sqrt());
let limited = stroke(20.0, |s| s.miter_limit = 2.0);
let bevel = stroke(20.0, |s| {
s.join = LineJoin::Bevel;
s.cap = LineCap::Round;
});
let b = limited.bounds_on(&tri, tb);
assert!((b.y0 - top).abs() < 1e-9, "{b:?}");
// The limit keeps the base corners' miters, whose tips reach about 12.2 pt left and right.
assert!(b.x0 < -12.0 && b.x1 > 52.0, "{b:?}");
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 20.0);
*ap.stroke_mut().unwrap() = bevel.clone();
let b = ap.stroked_bounds(tb, || tri.clone());
for (got, want) in [(b.x0, -side), (b.y0, top), (b.x1, 40.0 + side), (b.y1, 110.0)] {
assert!((got - want).abs() < 1e-9, "{b:?}");
}
// Open, the same corner is beveled and the round caps reach the half weight round the ends.
let chevron = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]);
let b = bevel.bounds_on(&chevron, chevron.bounding_box());
for (got, want) in [(b.x0, -10.0), (b.y0, top), (b.x1, 50.0), (b.y1, 110.0)] {
assert!((got - want).abs() < 1e-9, "{b:?}");
}
// A round join, and the round caps of dashes, which can end at the tip, reach round it.
let round = stroke(20.0, |s| s.join = LineJoin::Round);
assert!((round.bounds_on(&tri, tb).y0 + 10.0).abs() < 1e-9);
let mut dashed = bevel.clone();
dashed.dash = Some(Dash { pattern: vec![7.0, 4.0], offset: 0.0, align_corners: false });
assert!((dashed.bounds_on(&chevron, chevron.bounding_box()).y0 + 10.0).abs() < 1e-9);
}
#[test]
fn a_click_past_a_bevel_or_a_butt_end_misses() {
// 5 pt above the triangle's tip is within the half weight of it, but past the bevel, which
// reaches about 1.96 pt above it. A round join paints there.
let mut tri = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]);
tri.close_path();
let (above, on) = (Point::new(20.0, -5.0), Point::new(20.0, -1.5));
for join in [LineJoin::Bevel, LineJoin::Miter] {
let st = stroke(20.0, |s| (s.join, s.miter_limit) = (join, 2.0));
assert!(!st.hits(&tri, FillRule::NonZero, above, 0.5), "{join:?}");
assert!(st.hits(&tri, FillRule::NonZero, on, 0.0), "{join:?}");
}
assert!(stroke(20.0, |s| s.join = LineJoin::Round).hits(&tri, FillRule::NonZero, above, 0.5));
// 1.5 pt past a butt end of a 4 pt line misses, and a quarter point within it hits; a round
// cap paints past it.
let line = polyline(&[(0.0, 0.0), (0.0, 50.0)]);
let butt = stroke(4.0, |s| s.cap = LineCap::Butt);
assert!(!butt.hits(&line, FillRule::NonZero, Point::new(1.0, -1.5), 0.25));
assert!(butt.hits(&line, FillRule::NonZero, Point::new(1.0, -0.2), 0.25));
assert!(stroke(4.0, |s| s.cap = LineCap::Round).hits(&line, FillRule::NonZero, Point::new(1.0, -1.5), 0.25));
}
#[test]
fn a_joint_too_shallow_to_bevel_paints_past_both_segments_ends() {
// The path turns by about 0.57° at (100, -0.5), too little to bevel, so the stroke runs on
// through the joint: 3.5 pt above it is past the end of both segments and still painted.
let kink = polyline(&[(0.0, 0.0), (100.0, -0.5), (200.0, 0.0)]);
let above = Point::new(100.0, -4.0);
for join in [LineJoin::Bevel, LineJoin::Miter, LineJoin::Round] {
assert!(stroke(10.0, |s| s.join = join).hits(&kink, FillRule::NonZero, above, 0.0), "{join:?}");
}
}
/// An open path through `points`.
fn polyline(points: &[(f64, f64)]) -> BezPath {
let mut bp = BezPath::new();
@@ -691,15 +849,25 @@ mod tests {
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
ap.stroke_mut().unwrap().cap = LineCap::Butt;
let id = vectorcraft_geom::Affine::IDENTITY;
assert!(!ap.has_slanted_butt_stroke(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id));
assert!(!ap.has_slanted_stroke_corners(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id));
// Square ends, slanted segments in the middle.
let apex = polyline(&[(0.0, 50.0), (0.0, 40.0), (10.0, 0.0), (20.0, 40.0), (20.0, 50.0)]);
assert!(ap.has_slanted_butt_stroke(&apex, id));
// A rotation slants a vertical line; a round cap is never slanted.
assert!(ap.has_slanted_stroke_corners(&apex, id));
// A rotation slants a vertical line.
let v = polyline(&[(0.0, 0.0), (0.0, 50.0)]);
assert!(ap.has_slanted_butt_stroke(&v, vectorcraft_geom::Affine::rotate(0.3)));
assert!(ap.has_slanted_stroke_corners(&v, vectorcraft_geom::Affine::rotate(0.3)));
// With round caps, the miter join still stops at the corners of the slanted segments, on a
// closed path too; round caps and round joins never do.
ap.stroke_mut().unwrap().cap = LineCap::Round;
assert!(!ap.has_slanted_butt_stroke(&apex, id));
assert!(ap.has_slanted_stroke_corners(&apex, id));
let mut tri = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]);
tri.close_path();
ap.stroke_mut().unwrap().join = LineJoin::Bevel;
assert!(ap.has_slanted_stroke_corners(&tri, id));
assert!(!ap.has_slanted_stroke_corners(&square(), id));
ap.stroke_mut().unwrap().join = LineJoin::Round;
assert!(!ap.has_slanted_stroke_corners(&apex, id));
assert!(!ap.has_slanted_stroke_corners(&tri, id));
}
#[test]
@@ -723,11 +891,11 @@ mod tests {
}
let top = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S12".into(), xf: vectorcraft_geom::Affine::IDENTITY });
let symbols = d.symbol_boxes();
assert!(top.has_slanted_butt_stroke(&symbols, vectorcraft_geom::Affine::IDENTITY));
assert!(top.has_slanted_stroke_corners(&symbols, vectorcraft_geom::Affine::IDENTITY));
assert!(symbols.art_measured() <= SLANT_INSTANCES, "{}", symbols.art_measured());
// One instance of S1 holds three instances, all looked into.
let one = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S1".into(), xf: vectorcraft_geom::Affine::IDENTITY });
assert!(!one.has_slanted_butt_stroke(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY));
assert!(!one.has_slanted_stroke_corners(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY));
}
#[test]
+1 -1
View File
@@ -17,7 +17,7 @@ mod wrap;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
use char_style::yes;
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, ScriptMetrics};
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, ScriptMetrics};
pub use composite::{
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
CompositeParts,
+20 -1
View File
@@ -34,6 +34,16 @@ pub struct CharStyle {
/// before it whose [`Self::kerning`] could space it. Elsewhere it has no effect.
#[serde(default, rename = "kerningBefore", skip_serializing_if = "crate::skip::is_default")]
pub kerning_before: f64,
/// Insert Aki Left (Character panel, East Asian options): space added before the character in
/// reading order, in 1/1000 em as [`Self::tracking`], 0 to 1000. Before is on the left in
/// left-to-right type, on the right in right-to-left type and above in vertical type. A
/// cluster takes the value of its first character, and full justification leaves it as it is.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, rename = "akiLeft", skip_serializing_if = "crate::skip::is_default")]
pub aki_left: f64,
/// Insert Aki Right: space added after the character in reading order, as [`Self::aki_left`].
#[serde(default, rename = "akiRight", skip_serializing_if = "crate::skip::is_default")]
pub aki_right: f64,
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
#[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")]
pub optical_kerning: bool,
@@ -404,6 +414,9 @@ fn hundred() -> f64 {
100.0
}
/// The largest Insert Aki Left or Right ([`CharStyle::aki_left`]), in 1/1000 em: one em.
pub const MAX_AKI: f64 = 1000.0;
pub(super) fn yes() -> bool {
true
}
@@ -420,6 +433,8 @@ impl Default for CharStyle {
tracking: 0.0,
kerning: None,
kerning_before: 0.0,
aki_left: 0.0,
aki_right: 0.0,
optical_kerning: false,
baseline_shift: 0.0,
h_scale: 100.0,
@@ -468,7 +483,8 @@ impl CharStyle {
/// becomes Auto, and a value past [`crate::MAX_COORD`] (a baseline shift past it either way)
/// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a
/// baseline shift that is not a number becomes 0. The Tate-chu-yoko Up/Down and Left/Right
/// offsets are kept as the baseline shift is.
/// offsets are kept as the baseline shift is. Insert Aki Left and Right are kept from 0 to
/// [`MAX_AKI`], and one that is not a number becomes 0.
pub fn keep_dimensions_in_range(&mut self) {
let default = Self::default();
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
@@ -480,6 +496,9 @@ impl CharStyle {
self.baseline_shift = shift(self.baseline_shift);
self.tcy_up_down = shift(self.tcy_up_down);
self.tcy_left_right = shift(self.tcy_left_right);
let aki = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) };
self.aki_left = aki(self.aki_left);
self.aki_right = aki(self.aki_right);
}
/// Do the characters draw a stroke (a paint and a positive weight)?
pub fn has_stroke(&self) -> bool {
+4
View File
@@ -490,6 +490,8 @@ impl crate::Document {
st.baseline_shift = num("baseline_shift").unwrap_or(st.baseline_shift);
st.tcy_up_down = num("tcyUpDown").unwrap_or(st.tcy_up_down);
st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right);
st.aki_left = num("akiLeft").unwrap_or(st.aki_left);
st.aki_right = num("akiRight").unwrap_or(st.aki_right);
st.keep_dimensions_in_range();
let kept = [
("size", Some(st.size)),
@@ -498,6 +500,8 @@ impl crate::Document {
("baseline_shift", Some(st.baseline_shift)),
("tcyUpDown", Some(st.tcy_up_down)),
("tcyLeftRight", Some(st.tcy_left_right)),
("akiLeft", Some(st.aki_left)),
("akiRight", Some(st.aki_right)),
("leading", st.leading),
];
for (k, v) in kept {
+3 -1
View File
@@ -357,7 +357,7 @@ impl ParaList {
/// The style the marker is set in: `first` (the style of the paragraph's first character)
/// without its baseline shift, rotation, superscript or subscript, tracking, manual kerning,
/// tate-chu-yoko, underline and strikethrough.
/// Insert Aki, tate-chu-yoko, underline and strikethrough.
pub fn marker_style(first: &CharStyle) -> CharStyle {
CharStyle {
baseline_shift: 0.0,
@@ -366,6 +366,8 @@ impl ParaList {
tracking: 0.0,
kerning: None,
kerning_before: 0.0,
aki_left: 0.0,
aki_right: 0.0,
optical_kerning: first.optical_kerning,
tate_chu_yoko: false,
underline: false,
+37
View File
@@ -92,6 +92,43 @@ fn font_height_reference_is_saved_only_when_not_the_em_box() {
assert_eq!(serde_json::from_value::<CharStyle>(old).unwrap().font_height_reference, FontHeightReference::EmBox);
}
/// Insert Aki Left and Right are 0 by default and saved only when not 0, each side on its own;
/// styles written before them read as 0, and a value out of range from a file is kept from 0 to one
/// em.
#[test]
fn insert_aki_is_saved_only_when_set() {
let st = CharStyle::default();
assert_eq!((st.aki_left, st.aki_right), (0.0, 0.0));
let saved = serde_json::to_value(&st).unwrap();
assert!(saved.get("akiLeft").is_none() && saved.get("akiRight").is_none());
for set in [
CharStyle { aki_left: 250.0, ..CharStyle::default() },
CharStyle { aki_right: 500.0, ..CharStyle::default() },
CharStyle { aki_left: 125.5, aki_right: 1000.0, ..CharStyle::default() },
] {
let saved = serde_json::to_value(&set).unwrap();
assert_eq!(saved.get("akiLeft").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_left);
assert_eq!(saved.get("akiRight").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_right);
assert_eq!(saved.get("akiLeft").is_some(), set.aki_left != 0.0);
assert_eq!(serde_json::from_value::<CharStyle>(saved).unwrap(), set);
}
let old = serde_json::to_value(&st).unwrap();
let read = serde_json::from_value::<CharStyle>(old).unwrap();
assert_eq!((read.aki_left, read.aki_right), (0.0, 0.0));
let mut damaged = CharStyle { aki_left: -20.0, aki_right: 4000.0, ..CharStyle::default() };
damaged.keep_dimensions_in_range();
assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI));
let mut damaged = CharStyle { aki_left: f64::NAN, aki_right: f64::INFINITY, ..CharStyle::default() };
damaged.keep_dimensions_in_range();
assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI));
// A character style from a file is kept in range the same way.
let mut d = crate::Document::new(100.0, 100.0);
let attrs = serde_json::json!({"akiLeft": 5000, "akiRight": -1});
d.char_styles.push(TextStyleDef { name: "Spaced".into(), attrs: attrs.as_object().cloned().unwrap_or_default() });
d.keep_type_values_in_range();
assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0)));
}
/// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its
/// script's block; every system saves under its id, which reads back, and other names are refused.
#[test]
+2
View File
@@ -26,3 +26,5 @@ serde_json = { workspace = true }
[dev-dependencies]
vectorcraft-color = { workspace = true }
# A face built in code from the bundled Source Sans 3 (no font file is committed).
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
+2
View File
@@ -440,6 +440,8 @@ fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> {
if carry.moves(&m.appearance) {
carry.apply(&mut m.appearance);
}
// The raster effects of its fills and strokes follow its Transform effects, as on the canvas.
crate::raster::follow_items(&mut m);
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
Some((g, rule, ctx, m))
}
+5 -5
View File
@@ -189,8 +189,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
EXTRUDE,
"Extrude & Bevel…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}),
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}),
),
g(
INFLATE,
@@ -203,8 +203,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
ROTATE,
"Rotate…",
&["Effect", "3D and Materials"],
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}),
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}),
),
g(
CLASSIC_EXTRUDE,
@@ -267,7 +267,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"distort.transform",
"Transform…",
DT,
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are; so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}),
),
g(
+4 -1
View File
@@ -257,6 +257,9 @@ fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node {
if carry.moves(&m.appearance) {
carry.apply(&mut m.appearance);
}
// So do the raster effects of its fills and strokes, by `n`'s Transform effects
// ([`crate::follow_items`]).
crate::raster::follow_items_of(&mut m, &n.appearance.effects);
}
without_geometry_effects(&mut m);
m
@@ -686,7 +689,7 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
}
/// A path node of `id` on `path` (filled under `rule`) painted by `ap`.
fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node {
pub(crate) fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node {
let mut n = Node::path(id, path, ap);
if let NodeKind::Path { rule: r, .. } = &mut n.kind {
*r = rule;
+17
View File
@@ -1281,6 +1281,23 @@ fn compound_shape(mode: ShapeMode) -> Node {
g
}
/// A compound shape's Transform effect turns its fill's drop shadow with the area it turns.
#[test]
fn a_compound_shapes_transform_turns_its_fills_shadow() {
let mut shape = compound_shape(ShapeMode::Add);
if let Some(item) = shape.appearance.items.first_mut() {
*item.effects_mut() =
vec![Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({"x": 10, "y": 0, "blur": 0}), visible: true }];
}
shape.appearance.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({"rotate": 90}), visible: true });
let art = shape_art(None, &shape, None).unwrap();
let item = art.appearance.items.first().unwrap();
match crate::raster_effects(item.effects()).first() {
Some(crate::RasterFx::DropShadow { dx, dy, .. }) => assert!(dx.abs() < 1e-9 && (dy + 10.0).abs() < 1e-9, "{dx} {dy}"),
other => panic!("expected a drop shadow, got {other:?}"),
}
}
/// A compound shape draws the area its members' modes make, one unpainted path that its own
/// appearance paints; evaluated, it is plain art painted with that appearance.
#[test]
+11 -5
View File
@@ -78,7 +78,7 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects, without_geometry};
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art,
has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
@@ -87,15 +87,21 @@ pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
};
pub use solids::{
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES,
classic_extrude_options, classic_shading, extrude_options, has_solid, inflate_options, is_classic_three_d, is_three_d, solid_art, solid_art_in,
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in,
validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, ROTATE, ROTATE_SURFACES,
ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds,
graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, solid_art, solid_art_in, takes_graphics, three_d_meshes,
three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in,
validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after, rename_appearance_graphic_symbol,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
pub use trap::TRAP;
pub use vectorcraft_three_d::Mesh;
pub use vectorcraft_three_d::PlanarFace;
pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version};
mod catalog;
+100 -2
View File
@@ -5,7 +5,7 @@ use std::borrow::Cow;
use serde_json::{Map, Value, json};
use vectorcraft_doc::color::{BlendMode, Color};
use vectorcraft_doc::rastersettings::MAX_ADD_AROUND;
use vectorcraft_doc::{Effect, RasterColorModel, RasterEffectsSettings};
use vectorcraft_doc::{AppearanceItem, Effect, Node, RasterColorModel, RasterEffectsSettings};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
@@ -478,6 +478,104 @@ pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool {
changed
}
/// The linear part of the visible Transform effects of `owner`, an object's or a container's own
/// effects, in order: what they do to the raster effects of everything the object paints (its
/// fills and strokes, and a container's members and theirs), which those effects transform with
/// the rest of the art. `None` when they leave them as they are: no Transform effect moves the
/// art, or one of them makes copies or moves at random ([`followed`]).
pub(crate) fn contents_step(owner: &[Effect]) -> Option<Affine> {
let a = owner.iter().filter(|e| e.visible && e.id == "distort.transform").try_fold(Affine::IDENTITY, |a, e| transform_step(e).map(|s| s * a))?;
(a != Affine::IDENTITY).then_some(a)
}
/// Make the raster effects of `effects`, the own effects of something inside an object (a fill's
/// or stroke's, or a member's), follow `a`, the linear part of the object's Transform effects
/// ([`contents_step`]), which apply after all of them. `outer` is what the Transform effects
/// between them and `a` do to them (those of the fill's or stroke's object and of the groups that
/// hold it inside the object). A raster effect that the Transform effects after it in `effects`
/// move ([`followed`]) is set so that it draws as those effects, then `outer` and then `a`
/// transform it, whichever of them is applied first. One that a Transform effect after it in
/// `effects` holds back keeps its value through those effects, so it is set to draw as `outer` and
/// then `a` transform it. `false` when nothing changed.
pub(crate) fn follow_contents(effects: &mut [Effect], a: Affine, outer: Affine) -> bool {
if a == Affine::IDENTITY || !effects.iter().any(|e| follows(&e.id)) {
return false;
}
let mut changed = false;
// The linear part of the Transform effects after the effect at hand, as `followed` reads it;
// `None` once one of them holds the effect back, which they then leave as it is.
let mut after = Some(Affine::IDENTITY);
for e in effects.iter_mut().rev() {
if e.id == "distort.transform" {
after = after.and_then(|b| transform_step(e).map(|s| b * s));
continue;
}
if !follows(&e.id) {
continue;
}
let b = outer * after.unwrap_or(Affine::IDENTITY);
// The effect is still to be mapped by `b` when it is drawn, so it takes b⁻¹·a·b now:
// drawn, it is a·b of what it was. A `b` that flattens the art takes `a` alone.
let det = b.determinant();
let c = if b == Affine::IDENTITY || !(det.is_finite() && det.abs() > 1e-12) { a } else { b.inverse() * a * b };
if c.is_finite() {
follow_transform(e, c);
changed = true;
}
}
changed
}
/// Make the raster effects of the fills and strokes of `n` follow the Transform effects of its own
/// effect list ([`contents_step`]), as they do while the object is drawn with them: for art that
/// applies those effects and keeps the fills and strokes. `false` when nothing changed.
pub fn follow_items(n: &mut Node) -> bool {
let Some(a) = contents_step(&n.appearance.effects) else { return false };
follow_items_by(n, a)
}
/// [`follow_items`] for `n` holding the fills and strokes of an object whose own effects are
/// `owner` (the area of a compound shape, which carries none of the shape's effects).
pub(crate) fn follow_items_of(n: &mut Node, owner: &[Effect]) -> bool {
let Some(a) = contents_step(owner) else { return false };
follow_items_by(n, a)
}
/// Make the raster effects of the fills and strokes of `n` follow `a` ([`follow_contents`]).
fn follow_items_by(n: &mut Node, a: Affine) -> bool {
if !n.appearance.items.iter().any(|i| i.effects().iter().any(|e| follows(&e.id))) {
return false;
}
let mut changed = false;
for item in &mut n.appearance.items {
changed |= follow_contents(item.effects_mut(), a, Affine::IDENTITY);
}
changed
}
/// Make the raster effects of `items`, the fills and strokes of an object whose own effects are
/// `owner`, follow the Transform effects of `owner` ([`follow_contents`]): for art that applies
/// those effects to the object's path and draws each fill and stroke on it as a node of its own.
pub(crate) fn follow_paints(items: &mut [AppearanceItem], owner: &[Effect]) {
let Some(a) = contents_step(owner) else { return };
for item in items {
follow_contents(item.effects_mut(), a, Affine::IDENTITY);
}
}
/// `effects`, those of a fill or stroke of an object whose own effects are `owner`, with each
/// raster effect following the Transform effects of `owner` as well ([`follow_contents`]): the
/// list to draw that fill's or stroke's raster effects from ([`raster_effects`]). Borrowed when
/// nothing changes.
pub fn item_effects_in<'a>(owner: &[Effect], effects: &'a [Effect]) -> Cow<'a, [Effect]> {
let Some(a) = contents_step(owner) else { return Cow::Borrowed(effects) };
if !effects.iter().any(|e| follows(&e.id)) {
return Cow::Borrowed(effects);
}
let mut out = effects.to_vec();
if follow_contents(&mut out, a, Affine::IDENTITY) { Cow::Owned(out) } else { Cow::Borrowed(effects) }
}
/// How many of the effects of `effects` that [`without_geometry`] keeps no longer follow the
/// Transform effects listed after `effects` ([`followed`]): those before the last visible Transform
/// effect among them that makes copies or moves at random.
@@ -511,7 +609,7 @@ fn transform_step(e: &Effect) -> Option<Affine> {
/// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG
/// filter does not, and neither does Rasterize, whose image keeps its own pixel grid and room
/// around the art.
fn follows(id: &str) -> bool {
pub(crate) fn follows(id: &str) -> bool {
crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE
}
+113 -11
View File
@@ -741,12 +741,16 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
wholes.entry(id).or_insert_with(|| copies_whole(m));
});
let mut warped = WarpedImages::new();
// The raster effects of what the art holds follow each Transform effect that moves it once,
// whatever its options, unless one of the effects makes copies or moves at random
// ([`crate::raster::contents_step`], [`follow_art`]).
let held = listed.iter().any(|e| crate::raster::holds_back(e));
for e in fx {
let Some(bounds) = warped.bounds(art) else { break };
let params = merged_params(&e.id, &e.params);
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
let step = Step { e, params: &params, bounds, seed, effect, apart, doc, wholes: &wholes };
let step = Step { e, params: &params, bounds, seed, effect, apart, doc, wholes: &wholes, held };
// Art with linked masks keeps its shape under an effect that a mask in it could not take
// as the art it masks did, so no mask is left apart from its art.
let before = masked.then(|| (art.clone(), used));
@@ -769,8 +773,10 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
/// One geometry effect of an object run over its art ([`reshape_leaves_apart`]): the effect, its
/// merged params, the reference box and seed of the object's art, where a deferred live-effect
/// plug-in is listed, whether each Transform copy becomes an object, the document that the
/// swatches and patterns of painted pieces are looked up in, and [`copies_whole`] of the art of
/// each linked mask before the first effect, by the id of the object it masks.
/// swatches and patterns of painted pieces are looked up in, [`copies_whole`] of the art of
/// each linked mask before the first effect, by the id of the object it masks, and whether one of
/// the object's effects holds the raster effects in its art back from its Transform effects
/// ([`follow_art`]).
struct Step<'a> {
e: &'a Effect,
params: &'a serde_json::Value,
@@ -780,6 +786,7 @@ struct Step<'a> {
apart: bool,
doc: Option<&'a Document>,
wholes: &'a HashMap<NodeId, bool>,
held: bool,
}
/// What [`Step::run`] did to a piece of art.
@@ -886,6 +893,8 @@ impl Step<'_> {
let options = crate::distort::TransformOptions::of(params);
(m, copies, options, crate::distort::transform_affine(bounds, params, seed))
});
// What the effect does to the raster effects in the art, when they follow it.
let raster_map = if self.held { None } else { crate::raster::contents_step(std::slice::from_ref(e)) };
// In a mask's art, images and symbol instances take only a Transform effect
// ([`transform_placed`]): a mask's art that holds one can't take another effect as the art
// it masks does.
@@ -945,7 +954,7 @@ impl Step<'_> {
// The copies of a path replace it by a group of them, the path included.
let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len);
if options.reach_appearance() {
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, None);
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None);
*used = used.minus(before).plus(made);
if moved {
// With Transform Objects off the path stays, and its mask takes the
@@ -1015,12 +1024,22 @@ impl Step<'_> {
*art = Node::group(id, vec![Arc::new(one)]);
}
let placed = if watch { masked_placed(art, own) } else { 0 };
transform_placed(art, m, copies, copy_scaling(options));
// Scale Strokes & Effects leaves the raster effects that follow the effect to
// [`follow_art`].
let mut scaling = copy_scaling(options);
if raster_map.is_some() {
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
}
transform_placed(art, m, copies, scaling);
short |= watch && masked_placed(art, own) < placed.saturating_mul(copies.saturating_add(1));
if root && let Some([one]) = art.children().map(Vec::as_slice) {
*art = (**one).clone();
}
}
// A mask's art takes them as a group inside the art: its own raster effects follow too.
if let Some(a) = raster_map {
follow_art(art, a, &kept_ids, Some(&moved_ids), own.then_some(Affine::IDENTITY), depth);
}
if outlines.iter().any(Option::is_some) {
rebase_type_outlines(art, &mut outlines.into_iter());
}
@@ -1240,15 +1259,94 @@ fn copy_scaling(options: crate::distort::TransformOptions) -> vectorcraft_doc::S
}
}
/// [`crate::scale_effect`] for the effects that do not follow a Transform effect as raster effects
/// do ([`crate::raster::follows`]): Scale Strokes & Effects scales them, and [`follow_art`] moves
/// the others.
fn scale_unfollowed(e: &mut Effect, s: f64) {
if !crate::raster::follows(&e.id) {
crate::scale_effect(e, s);
}
}
/// Make the raster effects under `art` follow `a`, the linear part of a Transform effect that moved
/// it ([`crate::raster::follow_contents`]): those of every object in it (its own and its fills' and
/// strokes'), the art's own effects excepted (`up` is `None` for the art itself). A path that kept
/// its shape (in `kept`), and a group with such a path under it, keep their own and their fills'
/// and strokes'. `up` is what the Transform effects of the groups between an object and the art do
/// to the object's effects. A Transform effect of an object's own that makes copies or moves at
/// random leaves the effects it holds back as they are, so those follow `a` and the groups' maps
/// alone. The linked opacity mask of an object that took the effect as an object (in `moved`, and
/// every image and symbol instance) moved with it, so the raster effects in the mask's art follow
/// `a` as those of a mask that takes the effect as art do ([`Step::reshape_masks`]); `moved` is
/// `None` inside such a mask's art, where every linked mask moved. The walk reaches the groups and
/// layers that [`for_each_leaf`] made the art's own, so it copies nothing. Returns whether a path in
/// `kept` is under `n`.
fn follow_art(n: &mut Node, a: Affine, kept: &HashSet<NodeId>, moved: Option<&HashSet<NodeId>>, up: Option<Affine>, depth: usize) -> bool {
if n.is_guide() {
return false;
}
if moved.is_none_or(|moved| moved.contains(&n.id)) || is_placed(n) {
follow_moved_mask(n, a, depth);
}
// What the object's own Transform effects then do to its fills' and strokes' effects and its
// members' (nothing when one of them holds those back); the art's own effects are the ones
// being applied.
let below = up.map_or(Affine::IDENTITY, |up| crate::raster::contents_step(&n.appearance.effects).map_or(up, |s| up * s));
let keeps = match &mut n.kind {
NodeKind::Path { .. } | NodeKind::Compound { .. } => kept.contains(&n.id),
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
let mut keeps = false;
for c in children.iter_mut() {
keeps |= follow_art(Arc::make_mut(c), a, kept, moved, Some(below), depth);
}
keeps
}
_ => false,
};
if !keeps {
if let Some(up) = up
&& contents_raster(&n.appearance.effects)
{
crate::raster::follow_contents(&mut n.appearance.effects, a, up);
}
if n.appearance.items.iter().any(|i| contents_raster(i.effects())) {
for item in &mut n.appearance.items {
crate::raster::follow_contents(item.effects_mut(), a, below);
}
}
}
keeps
}
/// Make the raster effects in the art of the linked opacity mask of `n`, which moved with `n`,
/// follow `a` ([`follow_art`]), with those of the linked masks inside that art, which moved too. A
/// mask past [`vectorcraft_doc::depth::MAX_DEPTH`] masks inside masks stays as it is.
fn follow_moved_mask(n: &mut Node, a: Affine, depth: usize) {
if depth >= vectorcraft_doc::depth::MAX_DEPTH {
return;
}
let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) else { return };
follow_art(Arc::make_mut(&mut m.art), a, &HashSet::new(), None, Some(Affine::IDENTITY), depth + 1);
}
/// Does any of `effects` follow a Transform effect as a raster effect ([`crate::raster::follows`])?
fn contents_raster(effects: &[Effect]) -> bool {
effects.iter().any(|e| crate::raster::follows(&e.id))
}
/// A Transform effect whose Transform Patterns or Scale Strokes & Effects is on (`options`), with
/// map `m` and `copies`, applied to `leaf` (a path or compound path with geometry `path`) as Object
/// › Transform with those options transforms an object (#885): the strokes' weights and dashes
/// and the distances of the effects on its fills and strokes scale by `m`'s mean scale, and its
/// pattern paints transform by `m`. With copies, the original keeps them and copy `k` takes them
/// `k` times, each copy an object of its own ([`copy_leaf`], within `budget`). With Transform
/// Objects off the geometry stays and the options apply once. The effects `kept` names keep their
/// values on the leaf and on each copy ([`keep_listed`]). Returns what the leaf costs after, and
/// `false` when the path kept its shape because the moved path would pass `budget`.
/// Objects off the geometry stays and the options apply once. With `follows`, Scale Strokes &
/// Effects leaves the raster effects that follow the Transform effect ([`follow_art`]) to the
/// caller. The effects `kept` names keep their values on the leaf and on each copy
/// ([`keep_listed`]), whether Scale Strokes & Effects scaled them or left them to the caller.
/// Returns what the leaf costs after, and `false` when the path kept its shape because the moved
/// path would pass `budget`.
#[allow(clippy::too_many_arguments)]
fn transform_leaf(
leaf: &mut Node,
path: &PathData,
@@ -1256,9 +1354,13 @@ fn transform_leaf(
copies: usize,
options: crate::distort::TransformOptions,
budget: Budget,
follows: bool,
kept: Kept,
) -> (Budget, bool) {
let scaling = copy_scaling(options);
let mut scaling = copy_scaling(options);
if follows && copies == 0 {
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
}
if !options.objects {
if options.strokes
&& let Some(k) = vectorcraft_doc::Scaling::factor(m).filter(|k| k.is_finite() && *k > 0.0)
@@ -1717,7 +1819,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
set_geometry(&mut p, g.clone(), rule);
let after = kept_before.len();
let keep = |k: usize| k >= after || !options.objects;
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, Some((&rest, &keep)));
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, false, Some((&rest, &keep)));
*used = used.plus(made);
let from = crate::raster::held_back(before);
if moved && !held_later {
@@ -1796,7 +1898,7 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), h
let options = crate::distort::TransformOptions::of(&params);
let map = crate::distort::transform_affine(bounds, &params, seed);
let keep = |k: usize| k > j || (k < j && !options.objects);
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, Some((item.effects(), &keep)));
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep)));
*used = used.minus(before).plus(made);
if moved {
follow_piece(leaf, was, from, &e);
+111 -4
View File
@@ -509,6 +509,60 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
Ok(out)
}
/// The outline of every face [`revolve_art`] draws for `n`'s Revolve or Revolve (Classic) (its symbol
/// instances, blends and clipping groups already resolved), in document coordinates: with the
/// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of
/// them, reshaped by the geometry effects after each one's Revolve; on a group or layer, one for
/// each member, about one shared axis. The swatches and patterns named by a live-effect plug-in
/// after a fill's or stroke's Revolve are looked up in `doc`.
pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> {
let faces = |path: &PathData, b: Rect, options: Revolve| -> Result<Vec<PathData>, String> {
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(vectorcraft_three_d::Face::path).collect())
};
if is_container(n) {
let index = n
.appearance
.effects
.iter()
.position(|e| e.visible && is_revolve(&e.id))
.ok_or("a 3D effect on a group's fill or stroke draws nothing")?;
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
let mut shapes = members(n, "Revolve")?;
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
let options = shared_options(&shapes, fx_options(fx))?;
let mut out = vec![];
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
out.extend(faces(&s.path, b, options)?);
}
return Ok(out);
}
let (path, _) = object_profile(n, "Revolve")?;
let ctx = GeomContext::of(n);
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
if surface_item(&solid_paints(n)).is_none() {
return Err("the revolved object has no fill or stroke".into());
}
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
return faces(&path, b, fx_options(fx));
}
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
for item in n.appearance.items.iter().filter(|i| crate::paints(i)) {
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id))
&& let Some(fx) = item.effects().get(index)
{
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
let b = p.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let surface = faces(&p, b, fx_options(fx))?;
out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
}
Ok(out)
}
/// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis.
fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> {
let index = n
@@ -540,7 +594,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
if is_container(n) {
return group_art(n, expand);
}
let (path, _) = profile(n)?;
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
let mut children = vec![];
let mut copies = 0;
@@ -565,12 +619,18 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
} else {
let path = geometry(&path, &n.appearance.effects, &ctx);
remaining = crate::without_geometry(&remaining);
// The object's Transform effects, applied to the path above, transform the items' raster
// effects too. Each copy keeps its item beside it, which plug-in effects are told they sit
// on.
let originals: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| crate::paints(i)).collect();
let mut items: Vec<AppearanceItem> = originals.iter().map(|i| (*i).clone()).collect();
crate::raster::follow_paints(&mut items, &n.appearance.effects);
// Every item's shadow goes behind every item's art.
let mut shadows = vec![];
for item in n.appearance.items.iter().filter(|i| crate::paints(i)) {
for (original, item) in originals.into_iter().zip(&items) {
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) {
let fx = item.effects().get(index)?;
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?;
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
@@ -582,7 +642,8 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
}
children.push(Arc::new(art));
} else {
children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() })));
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat)));
}
}
children.splice(0..0, shadows);
@@ -964,6 +1025,52 @@ mod tests {
assert!(surface.children().unwrap().iter().all(|c| c.opacity == 1.0 && !has_revolve(c)));
}
#[test]
fn a_fill_without_the_revolve_keeps_the_even_odd_hole() {
use vectorcraft_geom::FillRule;
use vectorcraft_geom::hit::fill_contains;
// Two nested squares drawn in the same direction: only the even-odd rule leaves a hole.
let [outer, inner] = [(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| {
let mut b = BezPath::new();
b.move_to((lo, lo));
b.line_to((hi, lo));
b.line_to((hi, hi));
b.line_to((lo, hi));
b.close_path();
PathData::from_bezpath(&b)
});
let flat = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.1, 0.3, 0.9))));
for id in [REVOLVE, CLASSIC_REVOLVE] {
let mut top = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.8, 0.2, 0.1))));
top.effects_mut().push(crate::new_effect(id, &json!({})).unwrap());
let appearance = Appearance { items: vec![flat.clone(), top], ..Default::default() };
let members = vec![
Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())),
Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())),
];
let mut compound = Node::new(NodeId(1), NodeKind::Compound { children: members, rule: FillRule::EvenOdd });
compound.appearance = appearance.clone().into();
let both = PathData::new(outer.subpaths.iter().chain(&inner.subpaths).cloned().collect());
let path = crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance);
for (n, shape) in [(compound, "compound path"), (path, "path")] {
for (art, how) in [(revolve_art(&n), "live"), (expand_revolve_art(&n), "expanded")] {
let what = format!("{id} on the top fill of a {shape}, {how}");
let art = art.unwrap_or_else(|| panic!("{what}"));
let children = art.children().unwrap();
let plain: Vec<usize> = (0..children.len())
.filter(|&i| children[i].appearance.items == [flat.clone()] && children[i].path_data().is_some())
.collect();
let [index] = plain[..] else { panic!("{what}: one flat child, got {plain:?}") };
let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") };
assert_eq!(*rule, FillRule::EvenOdd, "{what}");
let bez = path.to_bezpath();
assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled");
assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open");
assert!(index + 1 < children.len(), "{what}: the revolved art is drawn above");
}
}
}
}
#[test]
fn export_bakes_faces_with_unique_ids_and_no_revolve_effects() {
let mut d = Document::new(300.0, 300.0);
let mut n = profile_node();
+298 -25
View File
@@ -6,7 +6,7 @@ use serde_json::Value;
use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask, StrokeLayer};
use vectorcraft_geom::{FillRule, PathData, Rect};
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View};
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, PlanarFace, View};
#[cfg(test)]
use vectorcraft_doc::color::Color;
@@ -20,8 +20,20 @@ pub use classic::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, ROTATE_SURFACES, SHADING_COLO
mod source;
pub(crate) use source::{resolve, resolve_for};
mod graphics;
pub use graphics::{
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol,
rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
};
pub use graphics::{
MAX_OFFSET as GRAPHIC_MAX_OFFSET, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, rename_appearance_graphic_symbol,
};
pub(crate) mod shadow;
pub(crate) mod wireframe;
pub use wireframe::three_d_wireframe_in;
pub const EXTRUDE: &str = "threeD.extrude";
pub const INFLATE: &str = "threeD.inflate";
pub const ROTATE: &str = "threeD.rotate";
@@ -67,6 +79,12 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
}
}
}
// A plane has only a front, so graphics on the back cap are dropped.
if to == ROTATE
&& let Some(Value::Array(list)) = out.get_mut(GRAPHICS)
{
list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id()));
}
Value::Object(out)
}
@@ -209,6 +227,7 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
}
crate::lighting::validate(p)?;
shadow::validate(p)?;
graphics::validate(id, p)?;
if let Some(v) = p.get("bevel")
&& !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some())
{
@@ -238,6 +257,9 @@ pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
/// `item`, whose shadow is cast by that item's solid alone.
fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, item: Option<usize>) -> Result<(), String> {
validate_solid_params(id, p)?;
if let Some(doc) = doc {
graphics::validate_symbols(doc, p)?;
}
let label = label_of(id);
let n = &*source::resolve_for(doc, n, label, is_plane(id))?;
if is_container(n) {
@@ -431,6 +453,7 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> {
/// [`validate_three_d`] with the symbols of `doc` ([`validate_solid_in`]).
pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> {
graphics::validate(id, p)?;
if crate::revolve::is_revolve(id) { crate::revolve::validate_in(doc, n, id, p) } else { validate_solid_in(doc, n, id, p) }
}
@@ -446,6 +469,7 @@ pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usi
/// [`validate_three_d_at`] with the symbols of `doc` ([`validate_solid_in`]). A symbol instance, a
/// blend and a clipping group take a 3D effect as groups do: on the object itself.
pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> {
graphics::validate(id, p)?;
match at {
Some(_) if is_container(n) || source::resolves(n) => {
Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into())
@@ -460,6 +484,7 @@ pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Va
/// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does
/// not need to fit.
pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
graphics::validate(id, p)?;
if crate::revolve::is_revolve(id) { crate::revolve::validate_params_of(id, p) } else { validate_solid_params(id, p) }
}
@@ -709,8 +734,8 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
/// blending mode, and those of a group it is in, apply to the surfaces of the members it holds
/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it
/// off), to be drawn behind every surface of the object, and the surfaces.
fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
let art = surfaces_for(n, fx, shapes)?;
fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
let art = surfaces_for(doc, n, fx, shapes)?;
// A shadow past the limits draws the source path, as a solid past them does; commands report
// the error ([`validate_solid_in`]).
let shadow = match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes).ok()? {
@@ -786,8 +811,139 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
/// its member's scopes and ink ([`cast_shadow`]).
type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec<shadow::Cast<'a>>);
/// [`art_for`] without the shadow: the solids' surfaces.
fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
/// The graphics of a 3D effect with parameters `p`, drawn on its faces ([`graphics::face_art`]):
/// for each planar face with a graphic, the art and the face. `caps` are the faces the viewer sees
/// of the ends of the object's solids, each with its end; `bounds` are the bounds the solids were
/// built with; `opacity` is the opacity of the fill or stroke those solids are painted with, which
/// the graphics take too. `elements` is the effect's count of drawn path elements, shared by every
/// call for one effect ([`graphics::face_art`]).
fn graphic_art(
doc: Option<&Document>,
id: NodeId,
(effect, p): (&str, &Value),
bounds: Rect,
caps: &[&Facet],
opacity: f32,
elements: &mut usize,
) -> Vec<(PlanarFace, Arc<Node>)> {
let list = graphics::mapped_graphics(p);
if list.is_empty() || !takes_graphics(effect) {
return vec![];
}
let view = view_options(p);
PlanarFace::ALL
.into_iter()
.filter_map(|face| {
let on: Vec<&Facet> = caps.iter().copied().filter(|f| f.end == Some(face)).collect();
let map = if effect == ROTATE {
vectorcraft_three_d::plane_face_map(bounds, view)
} else {
vectorcraft_three_d::extrude_face_map(bounds, extrude_options(p), view, face)
}?;
graphics::face_art(doc, id, &list, (face, &map), bounds.center(), &on, elements).map(|mut art| {
art.opacity *= opacity;
(face, Arc::new(art))
})
})
.collect()
}
/// A solid (a fill's or a stroke's) with ends the viewer sees: the index of its surface, its
/// member, the ends, the opacity and blending mode of its fill or stroke, and whether its surface
/// carries an opacity mask (a gradient's transparency under a colored light, [`surface`]).
struct Filled {
at: usize,
member: usize,
caps: Vec<Facet>,
opacity: f32,
blend: BlendMode,
masked: bool,
}
/// Does a surface in `paint` carry an opacity mask ([`surface`])?
fn masks_surface(paint: &Paint, colored: bool) -> bool {
colored && crate::lighting::opaque_paint(paint).1.is_some()
}
/// The graphics of the solids `filled` ([`graphic_art`]), each with the index of the surface it is
/// drawn right after (the last of those solids holding its face) and its face. With `per_member`
/// (a member's opacity mask or blending mode applies to its surfaces) each member's solids get
/// graphics of their own, clipped to that member's caps, so they stay in that member's scopes.
/// All the groups share one limit on the path elements drawn: once it is reached, later groups
/// draw no graphics.
fn placed_graphics(
doc: Option<&Document>,
id: NodeId,
effect: (&str, &Value),
bounds: Rect,
filled: &[Filled],
per_member: bool,
) -> Vec<(usize, PlanarFace, Arc<Node>)> {
let mut groups: Vec<Vec<&Filled>> = vec![];
for f in filled {
// Solids whose fills or strokes differ in opacity or blending mode get graphics of their
// own, each drawn as its fill or stroke is. A solid whose surface carries an opacity mask
// gets its own too, which takes that mask ([`with_graphics`]).
let joins = |first: &Filled| {
(!per_member || first.member == f.member) && first.opacity == f.opacity && first.blend == f.blend && !first.masked && !f.masked
};
match groups.iter_mut().find(|g| g.first().is_some_and(|first| joins(first))) {
Some(g) => g.push(f),
None => groups.push(vec![f]),
}
}
let mut out = vec![];
let mut elements = 0usize;
for group in groups {
let caps: Vec<&Facet> = group.iter().flat_map(|f| &f.caps).collect();
let opacity = group.first().map_or(1.0, |f| f.opacity);
let blend = group.first().map_or(BlendMode::Normal, |f| f.blend);
for (face, mut art) in graphic_art(doc, id, effect, bounds, &caps, opacity, &mut elements) {
if let Some(f) = group.iter().rev().find(|f| f.caps.iter().any(|c| c.end == Some(face))) {
Arc::make_mut(&mut art).blend = blend;
out.push((f.at, face, art));
}
}
}
out
}
/// One solid's surface as [`surfaces_for`] builds it: its faces' depths, its art, its member's
/// scopes, and for each face the end of a solid it is, when the viewer sees it.
type BuiltSurface<'s> = (Vec<Placed>, Node, &'s [Scope], Vec<Option<PlanarFace>>);
/// [`with_graphics`] of built surfaces, each drawn whole.
fn whole_surfaces<'s>(surfaces: Vec<BuiltSurface<'s>>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), arts)
}
/// `surfaces` drawn whole, each with its scopes, and the graphics `arts` ([`placed_graphics`]) each
/// right after its surface, with that surface's scopes and its opacity mask (a gradient's
/// transparency), so a graphic is hidden where its cap is.
fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc<Node>)>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
let mut out = Vec::with_capacity(surfaces.len() + arts.len());
for (k, (scopes, s)) in surfaces.into_iter().enumerate() {
let mask = s.extras().mask.clone();
out.push((scopes, s));
out.extend(arts.iter().filter(|(at, ..)| *at == k).map(|(.., art)| {
let mut art = art.clone();
if let Some(mask) = &mask {
Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone());
}
(scopes, art)
}));
}
out
}
/// The ends of `f` the viewer sees, for a fill's solid or a stroke's: where its graphics go.
fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> {
f.iter().filter(|f| f.end.is_some() && !f.away)
}
/// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar
/// faces drawn right after the last of the solids' surfaces that holds that face.
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
let b = union_bounds(shapes)?;
let p = crate::merged_params(&fx.id, &fx.params);
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
@@ -795,11 +951,14 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
let masks = has_masks(shapes);
// The paint copies of every solid together: past the allowance the source path is drawn.
let mut paint_bytes = 0usize;
// The caps are copied only when the effect has graphics to draw on them.
let graphics_on = !classic && takes_graphics(&fx.id) && !mapped_graphics(&p).is_empty();
if is_plane(&fx.id) {
// Every part turns about the centre of the object's own bounds (a group's members about
// the centre of theirs), so they stay together.
let mut out = vec![];
for s in shapes {
let mut filled = vec![];
for (member, s) in shapes.iter().enumerate() {
for item in &s.items {
let (paint, opacity, blend) = paint_of(item, s.opacity);
let (area, rule) = region(&s.path, s.rule, item);
@@ -807,10 +966,18 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) {
return None;
}
if graphics_on {
let caps: Vec<Facet> = seen_ends(&f).cloned().collect();
if !caps.is_empty() {
filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) });
}
}
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
out.push((s.scopes.as_slice(), Arc::new(art)));
}
}
let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks);
let out = with_graphics(out, &arts);
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
}
let (parts, bounds) = solid_parts(shapes, b);
@@ -842,36 +1009,56 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
let (_, opacity, blend) = paint_of(item, *member);
opacity >= 1.0 && blend == BlendMode::Normal
});
let surfaces: Vec<(Vec<Placed>, Node, &[Scope])> = solids
let arts = if !graphics_on {
vec![]
} else {
let filled: Vec<Filled> = solids
.iter()
.enumerate()
.filter_map(|(at, (item, member, _, f, shape))| {
let caps: Vec<Facet> = seen_ends(f).cloned().collect();
let (paint, opacity, blend) = paint_of(item, *member);
let masked = masks_surface(&paint, colored);
(!caps.is_empty()).then_some(Filled { at, member: *shape, caps, opacity, blend, masked })
})
.collect();
placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks)
};
let surfaces: Vec<BuiltSurface> = solids
.into_iter()
.map(|(item, member, scopes, f, shape)| {
let closed = shapes.get(shape).is_some_and(|s| s.path.subpaths.iter().all(|p| p.closed));
let paints = Paints::of(item, closed);
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
let (paint, opacity, blend) = paint_of(item, member);
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
(depths, art, scopes)
(depths, art, scopes, ends)
})
.collect();
if masks {
return Some(masked(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect()));
return Some(masked(n.id, whole_surfaces(surfaces, &arts)));
}
// One order takes a plain group of faces from each solid, one face for each facet. With
// colored lights a surface can instead be one clipped composite of all its facets. A composite
// has no faces to order, so when any surface is one, every surface of the solid, masked ones
// included, draws whole in member order.
let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
if !opaque || !plain {
return Some(surfaces.into_iter().map(|(_, s, _)| Arc::new(s)).collect());
}
let plain =
surfaces.iter().all(|(depths, s, _, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
// A surface in a gradient with transparent stops carries an opacity mask: its faces go in runs
// ([`in_runs`]), and each run carries the mask.
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _)| s.extras().mask.clone()).collect();
let (mut placed, mut faces) = (vec![], vec![]);
for (surface, (depths, s, _)) in surfaces.into_iter().enumerate() {
// ([`in_runs`]), and each run carries the mask. With graphics as well, the surfaces draw whole,
// each graphic right after its surface.
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect();
let masked_faces = masks.iter().any(Option::is_some);
if !opaque || !plain || (masked_faces && !arts.is_empty()) {
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
}
let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]);
for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() {
if let NodeKind::Group { children, .. } = s.kind {
placed.extend(depths);
faces.extend(children.into_iter().map(|face| Some((surface, face))));
ends.extend(e);
}
}
let sealed = match fx.id.as_str() {
@@ -880,8 +1067,18 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
_ => extrude_options(&p).cap,
};
let order = draw_order(&placed, sealed);
let faces: Vec<(usize, Arc<Node>)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect();
let children = if masks.iter().all(Option::is_none) { faces.into_iter().map(|(_, face)| face).collect() } else { in_runs(n.id, faces, &masks) };
if masked_faces {
let faces: Vec<(usize, Arc<Node>)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect();
return Some(vec![Arc::new(Node::group(n.id, in_runs(n.id, faces, &masks)))]);
}
// Each face's graphics go right after the last of the faces they are drawn on.
let last: Vec<Option<usize>> =
arts.iter().map(|(_, face, _)| order.iter().rposition(|k| ends.get(*k).copied().flatten() == Some(*face))).collect();
let mut children = Vec::with_capacity(order.len() + arts.len());
for (at, k) in order.into_iter().enumerate() {
children.extend(faces.get_mut(k).and_then(Option::take).map(|(_, face)| face));
children.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (.., art))| art.clone()));
}
Some(vec![Arc::new(Node::group(n.id, children))])
}
@@ -966,7 +1163,7 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
}
let n = &*resolve(doc, n, "").ok()?;
if is_container(n) {
return group_solid_art(n);
return group_solid_art(doc, n);
}
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
@@ -975,19 +1172,23 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
let remaining: Vec<Effect>;
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
let (shadow, surfaces) = art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?;
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?;
children.extend(shadow.into_iter().chain(surfaces));
// Later geometry effects act on the projected art as a whole.
remaining = past_effect(&n.appearance.effects, index);
} else {
let path = geometry(&path, &n.appearance.effects, &ctx);
remaining = crate::without_geometry(&n.appearance.effects);
// The object's Transform effects, applied to the path above, transform the items' raster
// effects too.
let mut paints = paints;
crate::raster::follow_paints(&mut paints, &n.appearance.effects);
// Every item's shadow goes behind every item's art.
let mut shadows = vec![];
for item in &paints {
if let Some((index, fx)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
let (shadow, surfaces) = art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
let later: Vec<Effect> = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect();
let with_later = |mut art: Arc<Node>| {
Arc::make_mut(&mut art).appearance.effects = later.clone();
@@ -996,7 +1197,8 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
shadows.extend(shadow.into_iter().map(with_later));
children.extend(surfaces.into_iter().map(with_later));
} else {
children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() })));
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat)));
}
}
children.splice(0..0, shadows);
@@ -1011,11 +1213,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// geometry effects before it reshape the members, those after it bend the result as a whole; the
/// group's own fills and strokes are not drawn. `None` when the effect is only on one of the
/// group's own fills or strokes, or when its members can't become solids.
fn group_solid_art(n: &Node) -> Option<Node> {
fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option<Node> {
let (index, fx) = solid(&n.appearance.effects)?;
let mut shapes = members(n, "").ok()?;
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
let (shadow, surfaces) = art_for(n, fx, &shapes)?;
let (shadow, surfaces) = art_for(doc, n, fx, &shapes)?;
let children = shadow.into_iter().chain(surfaces).collect();
let remaining = past_effect(&n.appearance.effects, index);
let mut art = n.clone();
@@ -1024,6 +1226,77 @@ fn group_solid_art(n: &Node) -> Option<Node> {
Some(art)
}
/// Where the graphics of the 3D effect of `n` (on the object itself with `item` `None`, else on its
/// fill or stroke `item`) are drawn: the bounds its solids are built with and the maps of their
/// planar faces ([`graphics::GraphicFrame`]). `None` when `n` has no visible Extrude & Bevel or
/// Rotate there, or its art can't be built.
pub fn graphic_frame(doc: Option<&Document>, n: &Node, item: Option<usize>) -> Option<graphics::GraphicFrame> {
frame_of(doc, n, item, &solid)
}
/// [`graphic_frame`] of the 3D effect at `index` in that list, which must be a visible Extrude &
/// Bevel or Rotate.
pub fn graphic_frame_at(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<graphics::GraphicFrame> {
frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && SOLIDS.contains(&e.id.as_str())).map(|e| (index, e)))
}
/// Does a visible geometry effect come after the 3D effect at `index` in the effects of `n` (on the
/// object itself with `item` `None`, else on its fill or stroke `item`)? Such an effect moves or
/// bends the drawn art, graphics included, while [`graphic_frame_at`] places the graphics on the
/// art before it.
pub fn graphics_reshaped_after(n: &Node, item: Option<usize>, index: usize) -> bool {
n.appearance.effects_at(item).and_then(|fx| fx.get(index + 1..)).is_some_and(crate::has_geometry)
}
/// Finds a 3D effect in a list of effects, with its index there.
type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p;
/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`.
fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<graphics::GraphicFrame> {
let n = &*resolve(doc, n, "").ok()?;
let (fx, shapes) = if is_container(n) {
let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?;
let mut shapes = members(n, "").ok()?;
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
(fx, shapes)
} else {
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
match item {
None => {
let (index, fx) = pick(&n.appearance.effects)?;
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
(fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }])
}
Some(k) => {
let it = n.appearance.items.get(k)?;
let (index, fx) = pick(it.effects())?;
let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it));
(fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }])
}
}
};
if !takes_graphics(&fx.id) {
return None;
}
let p = crate::merged_params(&fx.id, &fx.params);
let b = union_bounds(&shapes)?;
let view = view_options(&p);
if fx.id == ROTATE {
let plane = vectorcraft_three_d::plane_face_map(b, view);
return Some(graphics::GraphicFrame::new(b, plane, None));
}
let (_, bounds) = solid_parts(&shapes, b);
let options = extrude_options(&p);
let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face);
Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back)))
}
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
pub fn graphic_bounds(doc: &Document, name: &str) -> Option<Rect> {
graphics::art_bounds(doc, name)
}
/// `effects` without the 3D effect at `index` and the geometry effects before it, which shape the
/// art it projects. Each raster effect before it follows the Transform effects among those
/// ([`crate::without_geometry`]), unless a Transform effect after it makes copies or moves at
+631
View File
@@ -0,0 +1,631 @@
//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials ›
//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a
//! plane, turned, foreshortened and shaded with that face and clipped to it.
//!
//! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale,
//! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of
//! the object's bounds in the face's own plane (points, x to the right and y down as the face is
//! seen from the front of that face), its size as a share of the symbol's own, and its turn
//! (degrees, counterclockwise). On the back cap, x runs to the right as the back is seen from
//! behind, so the graphic reads the right way round there.
use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol};
use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath};
use vectorcraft_three_d::{FaceMap, Facet, PlanarFace};
/// The effect parameter that holds the graphics.
pub const GRAPHICS: &str = "graphics";
/// The most graphics one 3D effect maps.
pub const MAX_GRAPHICS: usize = 64;
/// The most fills and stroke outlines the art of one symbol draws as a graphic.
const MAX_PIECES: usize = 4096;
/// The most path elements the graphics of one 3D effect draw together, after a perspective cuts
/// their curves.
const MAX_ELEMENTS: usize = 400_000;
/// The pieces each curve of a graphic is cut into under a perspective map, which bends it.
const PERSPECTIVE_PIECES: usize = 8;
/// How deep symbol instances in a graphic's art may nest.
const MAX_NESTING: usize = 8;
/// How deep the objects of a graphic's art may be, counting groups and the art of the symbols it
/// places: as deep as an object may be drawn.
const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH;
/// The size range of a graphic, as a percentage of its symbol's own size.
pub const SCALE_RANGE: (f64, f64) = (1.0, 10_000.0);
/// How far a graphic's center may be from the center of its object, in points.
pub const MAX_OFFSET: f64 = 1e6;
/// One graphic mapped onto a face of a 3D object.
#[derive(Clone, Debug, PartialEq)]
pub struct MappedGraphic {
pub symbol: String,
pub face: PlanarFace,
pub x: f64,
pub y: f64,
/// Percent of the symbol's own size.
pub scale: f64,
/// Degrees, counterclockwise.
pub rotation: f64,
}
impl MappedGraphic {
pub fn to_value(&self) -> Value {
json!({"symbol": self.symbol, "face": self.face.id(), "x": self.x, "y": self.y, "scale": self.scale, "rotation": self.rotation})
}
/// The graphic `v` describes. Only `symbol` is required: `face` defaults to front, the offsets
/// and the rotation to 0 and the scale to 100.
pub fn from_value(v: &Value) -> Result<Self, String> {
let Value::Object(m) = v else { return Err(format!("each of `{GRAPHICS}` must be an object")) };
if let Some(k) = m.keys().find(|k| !matches!(k.as_str(), "symbol" | "face" | "x" | "y" | "scale" | "rotation")) {
return Err(format!("`{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}`"));
}
let symbol = match m.get("symbol") {
Some(Value::String(s)) if !s.trim().is_empty() => s.clone(),
_ => return Err(format!("each of `{GRAPHICS}` needs `symbol`, the name of a symbol")),
};
let face = match m.get("face") {
None => PlanarFace::Front,
Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?,
};
let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result<f64, String> {
match m.get(key) {
None => Ok(default),
Some(v) => v
.as_f64()
.filter(|n| n.is_finite() && (lo..=hi).contains(n))
.ok_or_else(|| format!("`{GRAPHICS}` {key} must be a number from {lo} to {hi}")),
}
};
Ok(Self {
symbol,
face,
x: number("x", 0.0, (-MAX_OFFSET, MAX_OFFSET))?,
y: number("y", 0.0, (-MAX_OFFSET, MAX_OFFSET))?,
scale: number("scale", 100.0, SCALE_RANGE)?,
rotation: number("rotation", 0.0, (-360.0, 360.0))?,
})
}
/// Where the graphic's art goes in the face's plane, for symbol art whose bounds are `art` on an
/// object whose bounds have center `center`.
fn placement(&self, art: Rect, center: Point) -> Affine {
let place = Affine::translate((center.x + self.x, center.y + self.y))
* Affine::rotate(-self.rotation.to_radians())
* Affine::scale(self.scale / 100.0)
* Affine::translate(-art.center().to_vec2());
match self.face {
PlanarFace::Front => place,
// Seen from behind, the back's right is the front's left.
PlanarFace::Back => {
Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place
}
}
}
}
/// The 3D effects that take graphics: Extrude & Bevel (its caps) and Rotate (the plane), the two
/// object types of the 3D and Materials panel with planar faces.
pub fn takes_graphics(id: &str) -> bool {
id == super::EXTRUDE || id == super::ROTATE
}
/// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold
/// anything; commands check every entry with [`validate`]).
pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
match p.get(GRAPHICS) {
Some(Value::Array(list)) => list.iter().take(MAX_GRAPHICS).filter_map(|v| MappedGraphic::from_value(v).ok()).collect(),
_ => vec![],
}
}
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel and Rotate take
/// graphics, and a plane has only a front.
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
let list = match p.get(GRAPHICS) {
None => return Ok(()),
Some(Value::Array(list)) => list,
Some(_) => return Err(format!("`{GRAPHICS}` must be an array")),
};
if list.is_empty() {
return Ok(());
}
if !takes_graphics(id) {
return Err("Graphics map onto planar faces: use the Extrude or Plane object type".into());
}
if list.len() > MAX_GRAPHICS {
return Err(format!("`{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics"));
}
for v in list {
let g = MappedGraphic::from_value(v)?;
if id == super::ROTATE && g.face == PlanarFace::Back {
return Err("A plane has one face: map its graphics onto the front".into());
}
}
Ok(())
}
/// The first symbol the graphics in `p` name that `doc` does not have, leaving out the symbols the
/// graphics in `old` (the effect's parameters before an edit) already name: a graphic whose symbol
/// was deleted may stay.
pub fn missing_symbol(doc: &Document, p: &Value, old: Option<&Value>) -> Option<String> {
let kept = old.map(mapped_graphics).unwrap_or_default();
mapped_graphics(p)
.into_iter()
.map(|g| g.symbol)
.find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.iter().any(|g| g.symbol == *name))
}
/// Does the art of the symbols the graphics in `p` name fit the limits? A graphic whose symbol
/// `doc` does not have draws nothing and is not counted. With a perspective, each curve counts as
/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once.
pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> {
let curve = if super::view_options(p).perspective > 0.0 { PERSPECTIVE_PIECES } else { 1 };
let mut elements = 0usize;
for g in mapped_graphics(p) {
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
let pieces = pieces_of(doc, symbol)?;
elements = elements.saturating_add(pieces.iter().map(|p| drawn_elements(&p.path, curve)).sum());
if elements > MAX_ELEMENTS {
return Err("The graphics are too complex: simplify the symbols' art".into());
}
}
Ok(())
}
/// The path elements `path` draws when each curve draws `curve` elements, before curves near the
/// eye are split further: one for each straight line, move and close.
fn drawn_elements(path: &PathData, curve: usize) -> usize {
let segments = |s: &SubPath| (0..s.segment_count()).map(|i| if s.segment_is_line(i) { 1 } else { curve }).sum::<usize>();
path.subpaths.iter().map(|s| 1 + usize::from(s.closed) + segments(s)).sum()
}
/// One area of a graphic's art, drawn with one paint: a fill, or a stroke's outline.
struct Piece {
path: PathData,
rule: FillRule,
paint: Paint,
opacity: f32,
blend: BlendMode,
}
/// The areas the art of `symbol` paints, back to front, at the symbol's natural size: the fills of
/// its paths, compound paths and type (as outlines), and its strokes' outlines, through the symbol
/// instances it holds (with their changes to dynamic symbols, and through 9-slice guides). Hidden objects, guides, clipping paths and images are left out, and clipping
/// groups draw their art unclipped.
fn pieces_of(doc: &Document, symbol: &Symbol) -> Result<Vec<Piece>, String> {
fn walk(doc: &Document, n: &Node, outer: f32, xf: Affine, (depth, level): (usize, usize), out: &mut Vec<Piece>) -> Result<(), String> {
if !n.visible || n.is_guide() {
return Ok(());
}
if level > MAX_LEVELS {
return Err(format!("A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art"));
}
let opacity = outer * n.opacity;
let shape = match &n.kind {
NodeKind::Path { path, rule, clipping: false, .. } => Some((path.clone(), *rule)),
NodeKind::Compound { children, rule } => {
Some((PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()), *rule))
}
NodeKind::Text(_) => {
if let Some(mut outlined) = crate::outline_text(n) {
// The outlines take the type's place, with its opacity.
outlined.visible = true;
outlined.opacity = n.opacity;
walk(doc, &outlined, outer, xf, (depth, level + 1), out)?;
}
None
}
NodeKind::SymbolInstance { symbol, xf: at } => {
if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) {
if depth >= MAX_NESTING {
return Err(format!("A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art"));
}
// The instance shows its own changes to a dynamic symbol's art, and a symbol
// with 9-slice guides is placed through them, as the canvas draws it. The
// pieces are not clipped, so paths that cross a guide are cut at it.
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n);
if doc.symbol_slice_map(symbol, *at).is_some() {
let Some(placed) = doc.place_symbol_art_unclipped(symbol, &art, *at) else {
return Err("A graphic's art holds too many objects: simplify the symbol's art".into());
};
walk(doc, &placed, opacity, xf, (depth + 1, level + 1), out)?;
} else {
walk(doc, &art, opacity, xf * *at, (depth + 1, level + 1), out)?;
}
}
None
}
_ => {
for c in n.children().into_iter().flatten() {
walk(doc, c, opacity, xf, (depth, level + 1), out)?;
}
None
}
};
let Some((path, rule)) = shape else { return Ok(()) };
// Symbol art keeps its strokes' widths as drawn while its geometry is scaled to the
// symbol's square, so a stroke is outlined after the art takes its size.
let path = path.transformed(xf);
for item in n.appearance.items.iter().filter(|i| i.visible()) {
let (area, rule, paint, item_opacity, blend) = match item {
AppearanceItem::Fill(f) => (path.clone(), rule, f.paint.clone(), f.opacity, f.blend),
AppearanceItem::Stroke(s) if s.width > 0.0 && s.width.is_finite() => {
(crate::stroke::outline_region(&path, rule, s), FillRule::EvenOdd, s.paint.clone(), s.opacity, s.blend)
}
AppearanceItem::Stroke(_) => continue,
};
if matches!(paint, Paint::None) || area.bounds().is_none() {
continue;
}
if out.len() >= MAX_PIECES {
return Err(format!("A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art"));
}
// A placed gradient or pattern takes the same size and place as its path.
let mut paint = paint;
match &mut paint {
Paint::Gradient(g) => g.transform(xf),
Paint::Pattern { xf: placed, .. } => *placed = xf * *placed,
Paint::None | Paint::Solid { .. } => {}
}
out.push(Piece { path: area, rule, paint, opacity: opacity * item_opacity, blend });
}
Ok(())
}
let mut out = vec![];
walk(doc, &symbol.art, 1.0, doc.symbol_natural_xf(&symbol.name), (0, 1), &mut out)?;
Ok(out)
}
/// `path` through `map`: exactly for an affine map, otherwise with each curve cut into
/// [`PERSPECTIVE_PIECES`] pieces whose control points go through it (straight lines stay straight
/// under a perspective). Fails when part of it has no page point, or when it takes more than `room`
/// elements.
fn map_path(path: &PathData, map: &FaceMap, affine: Option<Affine>, room: usize) -> Result<BezPath, NotMapped> {
let bp = path.to_bezpath();
if let Some(a) = affine {
return if bp.elements().len() <= room { Ok(a * bp) } else { Err(NotMapped::Full) };
}
let to = |p: Point| map.to_page(p).ok_or(NotMapped::Behind);
let mut out = BezPath::new();
let mut at = Point::ZERO;
for el in bp.elements() {
if out.elements().len() > room {
return Err(NotMapped::Full);
}
match *el {
PathEl::MoveTo(p) => {
out.move_to(to(p)?);
at = p;
}
PathEl::LineTo(p) => {
out.line_to(to(p)?);
at = p;
}
PathEl::QuadTo(c, p) => {
cubic_to(&mut out, vectorcraft_geom::kurbo::QuadBez::new(at, c, p).raise(), map).ok_or(NotMapped::Behind)?;
at = p;
}
PathEl::CurveTo(c1, c2, p) => {
cubic_to(&mut out, CubicBez::new(at, c1, c2, p), map).ok_or(NotMapped::Behind)?;
at = p;
}
PathEl::ClosePath => out.close_path(),
}
}
if out.elements().len() <= room { Ok(out) } else { Err(NotMapped::Full) }
}
/// Why [`map_path`] drew nothing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NotMapped {
/// Part of the path has no page point: it is at or behind the eye.
Behind,
/// The path takes more elements than it has room for.
Full,
}
/// Curve `c` through `map`, cut into [`PERSPECTIVE_PIECES`] pieces. A piece that lies in front of
/// the eye while a control point does not is split further ([`piece_to`]). `None` when part of a
/// piece has no page point.
fn cubic_to(out: &mut BezPath, c: CubicBez, map: &FaceMap) -> Option<()> {
for k in 0..PERSPECTIVE_PIECES {
let (t0, t1) = (k as f64 / PERSPECTIVE_PIECES as f64, (k + 1) as f64 / PERSPECTIVE_PIECES as f64);
let s = c.subsegment(t0..t1);
if !map.maps_curve([s.p0, s.p1, s.p2, s.p3]) {
return None;
}
piece_to(out, s, map, MAX_SPLITS)?;
}
Some(())
}
/// How many times [`piece_to`] halves a piece whose control points are behind the eye.
const MAX_SPLITS: usize = 4;
/// Piece `s`, which lies in front of the eye, through `map`: halved until the control points of
/// each half have page points, at most `splits` times, and drawn straight past that.
fn piece_to(out: &mut BezPath, s: CubicBez, map: &FaceMap, splits: usize) -> Option<()> {
let end = map.to_page(s.p3)?;
match (map.to_page(s.p1), map.to_page(s.p2)) {
(Some(c1), Some(c2)) => out.curve_to(c1, c2, end),
_ if splits == 0 => out.line_to(end),
_ => {
let (a, b) = s.subdivide();
piece_to(out, a, map, splits - 1)?;
piece_to(out, b, map, splits - 1)?;
}
}
Some(())
}
/// The graphics `graphics` lists for `face`, drawn on caps `caps` (the faces of that end of the
/// object's solids that the viewer sees) through `map`, for an object whose bounds have
/// center `center`: one clipping group of every such graphic, shaded with the first cap's light.
/// Pattern tiles keep their colors: the document's pattern draws them. A graphic whose symbol
/// `doc` does not have draws nothing. `elements` counts the path elements
/// the effect's graphics have drawn so far, after a perspective cuts their curves, and is shared by
/// every call for one effect. `None` when there is nothing to draw or that count passes
/// [`MAX_ELEMENTS`].
pub(super) fn face_art(
doc: Option<&Document>,
id: NodeId,
graphics: &[MappedGraphic],
(face, map): (PlanarFace, &FaceMap),
center: Point,
caps: &[&Facet],
elements: &mut usize,
) -> Option<Node> {
let doc = doc?;
let light = caps.first()?.illumination;
let affine = map.local_affine(center).filter(|_| map.is_affine());
let mut children = vec![];
for g in graphics.iter().filter(|g| g.face == face) {
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
// A symbol past the limits is left out; the other graphics still draw.
let Ok(pieces) = pieces_of(doc, symbol) else { continue };
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
let place = g.placement(bounds, center);
// Gradients follow the face's map as it is near the graphic's center.
let middle = place * bounds.center();
// When the center is at or behind the eye, they follow it near the middle of the part that
// is in front; a graphic with no part in front is left out.
let local = map.local_affine(middle).or_else(|| {
let part = map.mapped_part(place.transform_rect_bbox(bounds))?;
let sum = part.iter().fold(Point::ZERO, |s, p| s + p.to_vec2());
map.local_affine(Point::new(sum.x / part.len() as f64, sum.y / part.len() as f64))
});
let Some(local) = local else { continue };
let gradient_map = local * place;
for piece in pieces {
let placed = piece.path.transformed(place);
// Each anchor draws at least one element. A perspective cuts curves into more, and
// straight lines stay one each: the path may take what is left of the limit, and is
// counted as it is drawn. Past the limit, the face draws nothing.
let least: usize = placed.subpaths.iter().map(|s| s.anchors.len()).sum();
let before = *elements;
if before.saturating_add(least) > MAX_ELEMENTS {
return None;
}
let room = MAX_ELEMENTS - before;
let mut rule = piece.rule;
let mapped = match map_path(&placed, map, affine, room) {
Err(NotMapped::Behind) => {
// Part of it is at or behind the eye: the part in front is drawn.
let Some(part) = placed.bounds().and_then(|b| map.mapped_part(b)) else { continue };
let Some(&first) = part.first() else { continue };
let mut front = BezPath::new();
front.move_to(first);
part.iter().skip(1).for_each(|p| front.line_to(*p));
front.close_path();
let cut = vectorcraft_pathops::boolean(
&placed,
piece.rule,
&PathData::from_bezpath(&front),
FillRule::NonZero,
vectorcraft_pathops::BoolOp::Intersect,
);
rule = FillRule::NonZero;
map_path(&cut, map, affine, room)
}
done => done,
};
let mapped = match mapped {
Ok(mapped) => mapped,
Err(NotMapped::Full) => return None,
Err(NotMapped::Behind) => continue,
};
*elements = before.saturating_add(mapped.elements().len());
let mut paint = piece.paint;
vectorcraft_doc::recolor::map_paint(&mut paint, &|c| crate::lighting::shade(c, light));
// A pattern's tiles follow the graphic onto the face, as its gradients do below.
if let Paint::Pattern { xf, .. } = &mut paint {
*xf = gradient_map * *xf;
}
let mut fill = FillLayer::new(paint);
fill.opacity = piece.opacity;
fill.blend = piece.blend;
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
appearance.transform_gradients(gradient_map);
let mut node = Node::path(id, PathData::from_bezpath(&mapped), appearance);
if let NodeKind::Path { rule: r, .. } = &mut node.kind {
*r = rule;
}
children.push(Arc::new(node));
}
}
if children.is_empty() {
return None;
}
let mut clip = BezPath::new();
for cap in caps {
// A cap's holes are contours of the same path wound against its outline, so turning the
// whole path keeps them holes under the nonzero rule.
let mut outline = cap.path().to_bezpath();
if outline.area() < 0.0 {
outline = outline.reverse_subpaths();
}
clip.extend(outline.iter());
}
let clip = Node::path(id, PathData::from_bezpath(&clip), Appearance::default());
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))
}
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
pub(super) fn art_bounds(doc: &Document, name: &str) -> Option<Rect> {
let symbol = doc.symbols.iter().find(|s| s.name == name)?;
pieces_of(doc, symbol).ok()?.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b))
}
/// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics'
/// offsets are from their center) and the maps of its front and back faces, when it has them.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GraphicFrame {
pub bounds: Rect,
front: Option<FaceMap>,
back: Option<FaceMap>,
}
impl GraphicFrame {
pub(super) fn new(bounds: Rect, front: Option<FaceMap>, back: Option<FaceMap>) -> Self {
Self { bounds, front, back }
}
pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> {
match face {
PlanarFace::Front => self.front.as_ref(),
PlanarFace::Back => self.back.as_ref(),
}
}
/// The point of `face`'s plane that offset `(x, y)` names, as [`MappedGraphic`] places a
/// graphic's center.
fn art_point(&self, face: PlanarFace, (x, y): (f64, f64)) -> Point {
let c = self.bounds.center();
match face {
PlanarFace::Front => Point::new(c.x + x, c.y + y),
PlanarFace::Back => Point::new(c.x - x, c.y + y),
}
}
/// Where graphic `g`'s center lands on the page, and whether its face is turned toward the
/// viewer. `None` when the object has no such face or the point has no page point.
pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> {
let map = self.map(g.face)?;
Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible))
}
/// The offset of a graphic on `face` whose center lands on page point `page`.
pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> {
let art = self.map(face)?.to_art(page)?;
let c = self.bounds.center();
let (x, y) = match face {
PlanarFace::Front => (art.x - c.x, art.y - c.y),
PlanarFace::Back => (c.x - art.x, art.y - c.y),
};
(x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y))
}
/// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most
/// 100: where a newly mapped graphic starts.
pub fn fitting_scale(&self, art: Rect) -> f64 {
let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9));
(fit * 100.0).clamp(SCALE_RANGE.0, 100.0)
}
}
/// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes').
pub fn graphic_symbols(n: &Node) -> Vec<String> {
appearance_graphic_symbols(&n.appearance)
}
/// The symbols the graphics of the 3D effects in `appearance` name, as [`graphic_symbols`]: for a
/// graphic style's appearance.
pub fn appearance_graphic_symbols(appearance: &Appearance) -> Vec<String> {
std::iter::once(&appearance.effects)
.chain(appearance.items.iter().map(AppearanceItem::effects))
.flatten()
.filter(|e| takes_graphics(&e.id))
.flat_map(|e| mapped_graphics(&e.params))
.map(|g| g.symbol)
.collect()
}
/// Makes the graphics of `n`'s 3D effects that name symbol `from` name `to` instead. Returns
/// whether any changed.
pub fn rename_graphic_symbol(n: &mut Node, from: &str, to: &str) -> bool {
// Checked first, so an appearance that names another symbol is not copied.
graphic_symbols(n).iter().any(|s| s == from) && rename_appearance_graphic_symbol(&mut n.appearance, from, to)
}
/// [`rename_graphic_symbol`] for the 3D effects in `appearance`: for a graphic style's appearance.
pub fn rename_appearance_graphic_symbol(appearance: &mut Appearance, from: &str, to: &str) -> bool {
if !appearance_graphic_symbols(appearance).iter().any(|s| s == from) {
return false;
}
let mut lists: Vec<&mut Vec<vectorcraft_doc::Effect>> = vec![];
let (effects, items) = (&mut appearance.effects, &mut appearance.items);
lists.push(effects);
lists.extend(items.iter_mut().map(AppearanceItem::effects_mut));
for e in lists.into_iter().flatten().filter(|e| takes_graphics(&e.id)) {
if let Some(Value::Array(list)) = e.params.get_mut(GRAPHICS) {
for g in list.iter_mut() {
if g.get("symbol").and_then(Value::as_str) == Some(from) {
g["symbol"] = json!(to);
}
}
}
}
true
}
/// Does `n` or any object in it, opacity masks included, have a graphic that names symbol `from`?
pub fn names_graphic_symbol(n: &Node, from: &str) -> bool {
let mut found = false;
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| found |= graphic_symbols(c).iter().any(|s| s == from));
found
}
/// [`rename_graphic_symbol`] for `n` and every object in it, at any depth, opacity masks included.
/// Only the parts that name `from` are copied. Returns whether any changed.
pub fn rename_graphic_symbol_in(n: &mut Node, from: &str, to: &str) -> bool {
let names = names_graphic_symbol;
let mut changed = rename_graphic_symbol(n, from, to);
if let Some(mask) = n.extras_if_any().and_then(|x| x.mask.as_deref_mut()).filter(|m| names(&m.art, from)) {
changed |= rename_graphic_symbol_in(Arc::make_mut(&mut mask.art), from, to);
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut().filter(|c| names(c, from)) {
changed |= rename_graphic_symbol_in(Arc::make_mut(c), from, to);
}
}
changed
}
/// `p` with graphic `g` added at the end of its list.
pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value {
let mut out = p.as_object().cloned().unwrap_or_else(Map::new);
let mut list = match out.get(GRAPHICS) {
Some(Value::Array(list)) => list.clone(),
_ => vec![],
};
list.push(g.to_value());
out.insert(GRAPHICS.into(), Value::Array(list));
Value::Object(out)
}
#[cfg(test)]
#[path = "tests_graphics.rs"]
mod tests;
+62
View File
@@ -457,6 +457,68 @@ fn transparency_stays_on_the_whole_surface_and_items_take_their_own_effect() {
assert!(matches!(surfaces[1].kind, NodeKind::Path { .. }));
}
/// Two nested squares drawn in the same direction, so only the even-odd rule leaves a hole.
fn nested_squares() -> [PathData; 2] {
[(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| {
let mut b = BezPath::new();
b.move_to((lo, lo));
b.line_to((hi, lo));
b.line_to((hi, hi));
b.line_to((lo, hi));
b.close_path();
PathData::from_bezpath(&b)
})
}
/// The nested squares as an even-odd compound path and as one even-odd path, painted by `items`.
fn even_odd_shapes(items: Vec<AppearanceItem>) -> [Node; 2] {
let [outer, inner] = nested_squares();
let appearance = Appearance { items, ..Default::default() };
let children = vec![
Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())),
Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())),
];
let mut compound = Node::new(NodeId(1), NodeKind::Compound { children, rule: FillRule::EvenOdd });
compound.appearance = appearance.clone().into();
let both = PathData::new(outer.subpaths.into_iter().chain(inner.subpaths).collect());
[compound, crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance)]
}
/// Check that `art` draws `item` as one flat child: an even-odd path with a hole in the middle,
/// below the 3D art after it.
fn assert_flat_item_keeps_the_hole(art: &Node, item: &AppearanceItem, what: &str) {
use vectorcraft_geom::hit::fill_contains;
let children = art.children().unwrap();
let flat: Vec<usize> =
(0..children.len()).filter(|&i| children[i].appearance.items == [item.clone()] && children[i].path_data().is_some()).collect();
let [index] = flat[..] else { panic!("{what}: one flat child, got {flat:?}") };
let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") };
assert_eq!(*rule, FillRule::EvenOdd, "{what}");
let bez = path.to_bezpath();
assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled");
assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open");
assert!(index + 1 < children.len(), "{what}: the 3D art is drawn above");
}
#[test]
fn a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole() {
let red = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(RED)));
let blue = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(BLUE)));
let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 4.0));
for id in SOLIDS {
// The top fill and then the top stroke take the effect; the fill below stays flat.
for (top, on) in [(&red, "fill"), (&stroke, "stroke")] {
let mut lifted = top.clone();
lifted.effects_mut().push(fx(id, json!({})));
for (n, shape) in even_odd_shapes(vec![blue.clone(), lifted]).into_iter().zip(["compound path", "path"]) {
let what = format!("{id} on the top {on} of a {shape}");
let art = solid_art(&n).unwrap_or_else(|| panic!("{what}"));
assert_flat_item_keeps_the_hole(&art, &blue, &what);
}
}
}
}
#[test]
fn export_and_expand_bake_faces_with_their_own_ids() {
for id in SOLIDS {
+659
View File
@@ -0,0 +1,659 @@
use serde_json::json;
use vectorcraft_doc::color::Color;
use vectorcraft_doc::{StrokeLayer, Symbol};
use vectorcraft_geom::shapes;
use super::super::{EXTRUDE, INFLATE, ROTATE, graphic_frame, solid_art_in, three_d_params_as, validate_three_d_in, validate_three_d_params};
use super::*;
fn red() -> Color {
Color::rgb(1.0, 0.0, 0.0)
}
fn square(id: u64, r: Rect, paint: Paint) -> Node {
Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0))
}
/// A document with symbol "Mark": a red 10 × 10 square.
fn document() -> Document {
let mut d = Document::new(1000.0, 1000.0);
d.symbols.push(Symbol {
dynamic: false,
name: "Mark".into(),
art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), Paint::solid(red()))),
});
d
}
/// A gray 100 × 100 square at (0, 0) with effect `id`, its parameters `params` over a view
/// straight on.
fn object(id: &str, params: Value) -> Node {
let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false});
if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) {
p.extend(extra.clone());
}
let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
n.appearance.effects.push(crate::new_effect(id, &p).unwrap());
n
}
/// The graphics clip groups in `art`, in drawing order: each one's mapped paths.
fn graphics_in(art: &Node) -> Vec<Vec<(PathData, Paint)>> {
let mut out = vec![];
art.walk(&mut |n| {
if let NodeKind::Group { children, clip: true } = &n.kind
&& let [_, inner] = children.as_slice()
&& let NodeKind::Group { children: paths, clip: false } = &inner.kind
{
let paths: Vec<(PathData, Paint)> = paths
.iter()
.filter_map(|p| {
let fill = p.appearance.items.iter().find_map(|i| match i {
AppearanceItem::Fill(f) => Some(f.paint.clone()),
AppearanceItem::Stroke(_) => None,
})?;
Some((p.path_data()?.clone(), fill))
})
.collect();
if paths.iter().any(|(_, p)| p.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3)) {
out.push(paths);
}
}
});
out
}
fn bounds_of(paths: &[(PathData, Paint)]) -> Rect {
paths.iter().filter_map(|(p, _)| p.bounds()).reduce(|a, b| a.union(b)).unwrap()
}
fn close(a: Rect, b: Rect) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6)
}
#[test]
fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() {
let d = document();
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}]}));
let art = solid_art_in(Some(&d), &n).unwrap();
let found = graphics_in(&art);
assert_eq!(found.len(), 1);
// Straight on, the front cap is the art: a 20 × 20 square centered 20 right of and 10 above (50, 50).
assert!(close(bounds_of(&found[0]), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds_of(&found[0]));
// Turned 45°, the square's corners reach out to its half diagonal.
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "rotation": 45.0}]}));
let b = bounds_of(&graphics_in(&solid_art_in(Some(&d), &n).unwrap())[0]);
assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6);
}
#[test]
fn without_the_document_or_its_symbol_nothing_is_drawn() {
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]}));
let art = solid_art_in(None, &n).unwrap();
assert!(graphics_in(&art).is_empty());
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Gone"}]}));
assert!(graphics_in(&solid_art_in(Some(&document()), &n).unwrap()).is_empty());
// Without graphics, the art is the same as before they existed.
let plain = object(EXTRUDE, json!({}));
assert_eq!(solid_art_in(Some(&document()), &plain), solid_art_in(None, &plain));
}
#[test]
fn the_graphic_is_shaded_with_its_face() {
let d = document();
let n = object(EXTRUDE, json!({"shade": true, "lightIntensity": 0.0, "ambient": 50.0, "graphics": [{"symbol": "Mark"}]}));
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
let c = found[0][0].1.color().unwrap().to_rgb();
assert!((c[0] - 0.5).abs() < 1e-3 && c[1].abs() < 1e-6 && c[2].abs() < 1e-6, "{c:?}");
}
#[test]
fn the_graphic_goes_right_after_its_cap_and_is_clipped_to_it() {
let d = document();
let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 25.0, "graphics": [{"symbol": "Mark", "scale": 2000.0}]}));
let art = solid_art_in(Some(&d), &n).unwrap();
let NodeKind::Group { children, .. } = &art.kind else { panic!("a group") };
let NodeKind::Group { children: faces, .. } = &children.last().unwrap().kind else { panic!("the ordered faces") };
let last = faces.last().unwrap();
assert!(matches!(&last.kind, NodeKind::Group { clip: true, .. }), "the graphic is drawn last, over the front cap");
let NodeKind::Group { children: parts, .. } = &last.kind else { panic!() };
let clip = parts[0].path_data().unwrap().bounds().unwrap();
let cap = faces[faces.len() - 2].path_data().unwrap().bounds().unwrap();
assert!(close(clip, cap), "clipped to the cap: {clip:?} against {cap:?}");
}
#[test]
fn the_back_cap_reads_the_right_way_round_from_behind() {
let d = document();
let behind = json!({"rotationY": 180.0, "graphics": [{"symbol": "Mark", "face": "back", "x": 20.0}]});
let n = object(EXTRUDE, behind);
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
assert_eq!(found.len(), 1);
let b = bounds_of(&found[0]);
// Seen from behind, x runs to the right on the page too.
assert!((b.center().x - 70.0).abs() < 1e-6, "{b:?}");
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": 20.0})).unwrap();
let (at, visible) = frame.handle(&g).unwrap();
assert!(visible && (at.x - 70.0).abs() < 1e-6);
let (x, y) = frame.offset_at(PlanarFace::Back, Point::new(40.0, 55.0)).unwrap();
assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6);
// From the front the back cap is hidden, and so is its graphic.
let front = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "face": "back"}]}));
assert!(graphics_in(&solid_art_in(Some(&d), &front).unwrap()).is_empty());
}
#[test]
fn a_perspective_foreshortens_the_graphic_with_its_face() {
let d = document();
let params = json!({"rotationX": -30.0, "rotationY": 35.0, "perspectiveAngle": 100.0, "graphics": [{"symbol": "Mark", "scale": 400.0}]});
let n = object(EXTRUDE, params);
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let map = frame.map(PlanarFace::Front).unwrap();
// The corners of the 40 × 40 square centered on the object land where the face's map takes them.
let path = &found[0][0].0;
let corners: Vec<Point> = [(30.0, 30.0), (70.0, 30.0), (70.0, 70.0), (30.0, 70.0)].map(|(x, y)| map.to_page(Point::new(x, y)).unwrap()).into();
for c in corners {
let near = path.subpaths.iter().flat_map(|s| &s.anchors).map(|a| a.p.distance(c)).fold(f64::INFINITY, f64::min);
assert!(near < 1e-6, "{c:?} is {near} from the drawn graphic");
}
}
#[test]
fn a_graphic_behind_the_eye_leaves_the_others_drawn() {
let d = document();
let view = json!({"rotationX": -60.0, "rotationY": 0.0, "perspectiveAngle": 160.0});
let n = object(EXTRUDE, view.clone());
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let map = frame.map(PlanarFace::Front).unwrap();
let c = frame.bounds.center();
// An offset whose point of the front's plane is at or behind the eye.
let y = [1.0, -1.0]
.into_iter()
.flat_map(|s| (1..60).map(move |k| s * 10f64.powf(f64::from(k) / 10.0)))
.find(|y| map.local_affine(Point::new(c.x, c.y + y)).is_none())
.expect("an offset behind the eye");
let mut params = view;
params["graphics"] = json!([{"symbol": "Mark"}, {"symbol": "Mark", "y": y}]);
let found = graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, params)).unwrap());
assert_eq!(found.len(), 1, "the graphic that projects is still drawn");
// A graphic centered there but large enough to reach over the cap draws the part in front.
let mut params = json!({"rotationX": -60.0, "rotationY": 0.0, "perspectiveAngle": 160.0});
params["graphics"] = json!([{"symbol": "Mark", "y": y, "scale": (20.0 * (y.abs() + 50.0)).clamp(1.0, 10_000.0)}]);
let found = graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, params)).unwrap());
assert_eq!(found.len(), 1, "the part in front is drawn (offset {y})");
assert!(!found[0].is_empty());
}
#[test]
fn the_graphic_takes_the_opacity_of_its_fill() {
let d = document();
for id in [EXTRUDE, ROTATE] {
let mut n = object(id, json!({"graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.opacity = 0.25;
}
let art = solid_art_in(Some(&d), &n).unwrap();
let mut opacities = vec![];
art.walk(&mut |c| {
if matches!(c.kind, NodeKind::Group { clip: true, .. }) {
opacities.push(c.opacity);
}
});
assert_eq!(opacities, vec![0.25], "{id}");
}
}
#[test]
fn the_graphic_takes_the_blending_mode_of_its_fill() {
let d = document();
for id in [EXTRUDE, ROTATE] {
let mut n = object(id, json!({"graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.blend = BlendMode::Multiply;
}
let art = solid_art_in(Some(&d), &n).unwrap();
let mut blends = vec![];
art.walk(&mut |c| {
if matches!(c.kind, NodeKind::Group { clip: true, .. }) {
blends.push(c.blend);
}
});
assert_eq!(blends, vec![BlendMode::Multiply], "{id}");
}
}
#[test]
fn each_fill_of_a_plane_gives_its_graphic_its_own_opacity() {
let d = document();
let mut n = object(ROTATE, json!({"graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.opacity = 0.25;
}
let mut second = FillLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2)));
second.opacity = 0.75;
n.appearance.items.push(AppearanceItem::Fill(second));
let art = solid_art_in(Some(&d), &n).unwrap();
let mut opacities = vec![];
art.walk(&mut |c| {
if matches!(c.kind, NodeKind::Group { clip: true, .. }) {
opacities.push(c.opacity);
}
});
opacities.sort_by(f32::total_cmp);
assert_eq!(opacities, vec![0.25, 0.75]);
}
#[test]
fn a_symbols_gradient_takes_the_size_of_its_art() {
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
let mut d = document();
// Symbol art kept in its 20 × 20 square, drawn 40 × 20.
let mut g = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)]));
g.geom = Some(GradientGeom { start: Point::new(-10.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None });
let art = square(0, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::Gradient(Box::new(g)));
d.symbols.push(Symbol { dynamic: false, name: "Ramp".into(), art: Arc::new(art) });
d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({"Ramp": [40.0, 20.0]}));
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Ramp"}]}));
let out = solid_art_in(Some(&d), &n).unwrap();
let mut found = None;
out.walk(&mut |c| {
if let (Some(p), Some(AppearanceItem::Fill(f))) = (c.path_data(), c.appearance.items.first())
&& let Paint::Gradient(g) = &f.paint
{
found = Some((p.bounds().unwrap(), g.geom.unwrap()));
}
});
let (bounds, geom) = found.unwrap();
assert!(close(bounds, Rect::new(30.0, 40.0, 70.0, 60.0)), "{bounds:?}");
assert!(geom.start.distance(Point::new(30.0, 50.0)) < 1e-6 && geom.end.distance(Point::new(70.0, 50.0)) < 1e-6, "{geom:?}");
}
#[test]
fn a_symbols_pattern_follows_the_graphic() {
let mut d = document();
let tiles = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY };
d.symbols.push(Symbol { dynamic: false, name: "Tiles".into(), art: Arc::new(square(0, Rect::new(-10.0, -10.0, 10.0, 10.0), tiles)) });
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Tiles", "scale": 200.0}]}));
let out = solid_art_in(Some(&d), &n).unwrap();
let mut found = None;
out.walk(&mut |c| {
if let Some(AppearanceItem::Fill(f)) = c.appearance.items.first()
&& let Paint::Pattern { xf, .. } = &f.paint
{
found = Some((c.path_data().unwrap().bounds().unwrap(), *xf));
}
});
let (bounds, xf) = found.unwrap();
// The 20 × 20 art drawn 40 × 40 on the middle of the front: its tiles go with it.
assert!(close(bounds, Rect::new(30.0, 30.0, 70.0, 70.0)), "{bounds:?}");
assert!((xf * Point::new(-10.0, -10.0)).distance(Point::new(30.0, 30.0)) < 1e-6, "{xf:?}");
assert!((xf * Point::new(10.0, 10.0)).distance(Point::new(70.0, 70.0)) < 1e-6, "{xf:?}");
}
#[test]
fn a_curve_in_front_of_the_eye_maps_though_its_control_points_do_not() {
let bounds = Rect::new(10.0, 20.0, 70.0, 60.0);
let view = vectorcraft_three_d::View { rotation_x: -89.0, rotation_y: 40.0, rotation_z: 10.0, perspective: 160.0, ..Default::default() };
let map = vectorcraft_three_d::plane_face_map(bounds, view).unwrap();
// Where the page map stops along the line x = `x`, between the center and a point it does not map.
let edge = |x: f64| {
let inside = Point::new(x, bounds.center().y);
let far = [Point::new(x, -1e6), Point::new(x, 1e6)].into_iter().find(|p| map.to_page(*p).is_none()).unwrap();
let (mut a, mut b) = (inside, far);
for _ in 0..200 {
let m = a.midpoint(b);
if map.to_page(m).is_some() { a = m } else { b = m }
}
a
};
let (b1, b2) = (edge(40.0), edge(60.0));
let u = (b2 - b1).normalize();
let mut n = vectorcraft_geom::Vec2::new(-u.y, u.x);
if map.to_page(b1 + n * 10.0).is_none() {
n = -n;
}
// Ends 219.17 in front of that line and control points 100 and 42 past it: the curve stays
// about 1 in front, while a control point of one of the pieces it is cut into falls behind.
let at = |s: f64, t: f64| b1 + n * s + u * t;
let mut curve = BezPath::new();
curve.move_to(at(219.17, 0.0));
curve.curve_to(at(-100.0, 5.0), at(-42.0, 15.0), at(219.17, 20.0));
let c = CubicBez::new(at(219.17, 0.0), at(-100.0, 5.0), at(-42.0, 15.0), at(219.17, 20.0));
assert!((0..=1000).all(|k| map.to_page(c.eval(k as f64 / 1000.0)).is_some()), "the curve itself is in front");
let pieces = (0..PERSPECTIVE_PIECES).map(|k| c.subsegment(k as f64 / 8.0..(k + 1) as f64 / 8.0));
assert!(pieces.flat_map(|s| [s.p1, s.p2]).any(|p| map.to_page(p).is_none()), "a piece's control point is behind");
let mapped = map_path(&PathData::from_bezpath(&curve), &map, None, usize::MAX).expect("the curve maps");
// The split pieces count toward the room the path is given: without room, the path is full,
// not behind the eye, so it is not clipped.
assert!(mapped.elements().len() > 1 + PERSPECTIVE_PIECES);
assert_eq!(map_path(&PathData::from_bezpath(&curve), &map, None, PERSPECTIVE_PIECES + 1).err(), Some(NotMapped::Full));
assert!(mapped.elements().iter().all(|e| e.end_point().is_none_or(|p| p.x.is_finite() && p.y.is_finite())));
// That piece is split until its halves' control points map, so it stays a curve.
assert!(mapped.elements().iter().all(|e| !matches!(e, PathEl::LineTo(_))), "{mapped:?}");
// With its ends at 214.25 instead, the curve dips about 0.24 behind the line between the ends
// of two pieces, which still map: it has no page point there, and is left to the clipping.
let c = CubicBez::new(at(214.25, 0.0), at(-100.0, 5.0), at(-42.0, 15.0), at(214.25, 20.0));
assert!((0..=PERSPECTIVE_PIECES).all(|k| map.to_page(c.eval(k as f64 / 8.0)).is_some()));
assert!((0..=1000).any(|k| map.to_page(c.eval(k as f64 / 1000.0)).is_none()));
let mut dips = BezPath::new();
dips.move_to(c.p0);
dips.curve_to(c.p1, c.p2, c.p3);
assert_eq!(map_path(&PathData::from_bezpath(&dips), &map, None, usize::MAX).err(), Some(NotMapped::Behind));
}
#[test]
fn members_with_their_own_blending_get_graphics_of_their_own() {
let d = document();
let a = square(1, Rect::new(0.0, 0.0, 50.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
let mut b = square(2, Rect::new(50.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
b.blend = BlendMode::Multiply;
let mut group = Node::group(NodeId(3), vec![Arc::new(a), Arc::new(b)]);
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 1000.0}]});
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
let art = solid_art_in(Some(&d), &group).unwrap();
let found = graphics_in(&art);
// One graphic clipped to each member's cap: the second stays inside the member's Multiply group.
assert_eq!(found.len(), 2);
let mut blended = 0;
art.walk(&mut |c| {
if c.blend == BlendMode::Multiply {
blended += graphics_in(c).len();
}
});
assert_eq!(blended, 1);
}
/// [`document`] with symbol "Dense" too: a red polygon of 30,000 sides, straight or `curved`.
fn dense_document(curved: bool) -> Document {
let mut d = document();
let mut poly = BezPath::new();
let mut last = Point::ZERO;
for k in 0..30_000 {
let a = k as f64 / 30_000.0 * std::f64::consts::TAU;
let p = Point::new(5.0 + 5.0 * a.cos(), 5.0 + 5.0 * a.sin());
if k == 0 {
poly.move_to(p);
} else if curved {
poly.curve_to(last.lerp(p, 1.0 / 3.0), last.lerp(p, 2.0 / 3.0), p);
} else {
poly.line_to(p);
}
last = p;
}
poly.close_path();
let art = Node::path(NodeId(0), PathData::from_bezpath(&poly), Appearance::basic(Paint::solid(red()), Paint::None, 0.0));
d.symbols.push(Symbol { dynamic: false, name: "Dense".into(), art: Arc::new(art) });
d
}
/// The graphics drawn on a group of two members, each with its own graphic of symbol "Dense"
/// ([`dense_document`]), seen under a perspective.
fn dense_graphics_drawn(curved: bool) -> usize {
let d = dense_document(curved);
let a = square(1, Rect::new(0.0, 0.0, 50.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
let mut b = square(2, Rect::new(50.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
b.blend = BlendMode::Multiply;
let mut group = Node::group(NodeId(3), vec![Arc::new(a), Arc::new(b)]);
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "perspectiveAngle": 60.0, "shade": false, "graphics": [{"symbol": "Dense", "scale": 1000.0}]});
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
graphics_in(&solid_art_in(Some(&d), &group).unwrap()).len()
}
#[test]
fn members_with_graphics_of_their_own_share_one_element_limit() {
// A perspective cuts each of the 30,000 curves into 8: one copy fits the limit, two do not.
// The first member's graphic is drawn; the second would pass the limit, so it draws none.
assert_eq!(dense_graphics_drawn(true), 1);
}
#[test]
fn straight_sides_count_once_under_a_perspective() {
// A perspective keeps each of the 30,000 straight sides one element: both copies fit the limit.
assert_eq!(dense_graphics_drawn(false), 2);
}
#[test]
fn the_symbol_check_counts_what_the_view_draws() {
// Two graphics of the 30,000-sided polygon under a perspective: straight, they fit the limit;
// curved, they do not.
let two = json!({"perspectiveAngle": 60.0, "graphics": [{"symbol": "Dense"}, {"symbol": "Dense", "face": "back"}]});
let n = object(EXTRUDE, two.clone());
assert!(validate_three_d_in(Some(&dense_document(false)), &n, EXTRUDE, &two).is_ok());
let e = validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &two).unwrap_err();
assert!(e.contains("too complex"), "{e}");
// Without a perspective each curve draws once: curved, they fit too.
let flat = json!({"perspectiveAngle": 0.0, "graphics": two["graphics"].clone()});
assert!(validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &flat).is_ok());
}
#[test]
fn a_plane_and_a_hollow_solid() {
let d = document();
let plane = object(ROTATE, json!({"rotationY": 30.0, "graphics": [{"symbol": "Mark"}]}));
assert_eq!(graphics_in(&solid_art_in(Some(&d), &plane).unwrap()).len(), 1);
let hollow = object(EXTRUDE, json!({"cap": false, "graphics": [{"symbol": "Mark"}]}));
assert!(graphics_in(&solid_art_in(Some(&d), &hollow).unwrap()).is_empty());
}
#[test]
fn a_stroked_graphic_draws_its_stroke_as_an_outline() {
let mut d = document();
let mut ring = square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::None);
ring.appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(red()), 2.0))], ..Default::default() }.into();
d.symbols.push(Symbol { dynamic: false, name: "Ring".into(), art: Arc::new(ring) });
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Ring"}]}));
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
// The 10 × 10 square's 2 pt stroke reaches 1 pt outside it.
assert!(close(bounds_of(&found[0]), Rect::new(44.0, 44.0, 56.0, 56.0)), "{:?}", bounds_of(&found[0]));
}
#[test]
fn graphics_are_checked() {
let n = object(EXTRUDE, json!({}));
let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics}));
assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok());
assert!(check(EXTRUDE, json!([])).is_ok());
for bad in [
json!("Mark"),
json!([{"face": "front"}]),
json!([{"symbol": ""}]),
json!([{"symbol": "Mark", "face": "side"}]),
json!([{"symbol": "Mark", "scale": 0.0}]),
json!([{"symbol": "Mark", "rotation": 400.0}]),
json!([{"symbol": "Mark", "x": "1"}]),
json!([{"symbol": "Mark", "repeat": true}]),
json!(vec![json!({"symbol": "Mark"}); MAX_GRAPHICS + 1]),
] {
assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}");
}
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err());
assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err());
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err());
// A loaded file's invalid entries are left out when drawn.
assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1);
}
#[test]
fn the_frame_at_an_index_is_that_effects() {
let d = document();
let mut n = object(EXTRUDE, json!({}));
n.appearance.effects.push(crate::new_effect(ROTATE, &json!({})).unwrap());
// The first 3D effect is the Extrude & Bevel, with a back cap; the second is a plane, without.
assert!(graphic_frame(Some(&d), &n, None).unwrap().map(PlanarFace::Back).is_some());
assert!(super::super::graphic_frame_at(Some(&d), &n, None, 0).unwrap().map(PlanarFace::Back).is_some());
assert!(super::super::graphic_frame_at(Some(&d), &n, None, 1).unwrap().map(PlanarFace::Back).is_none());
assert!(super::super::graphic_frame_at(Some(&d), &n, None, 2).is_none());
}
#[test]
fn a_change_to_a_plane_drops_the_back_caps_graphics() {
let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]});
let plane = three_d_params_as(EXTRUDE, &p, ROTATE);
assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}]));
assert!(validate_three_d_params(ROTATE, &plane).is_ok());
// Back to Extrude & Bevel, the front's graphic stays.
assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]);
}
#[test]
fn a_stroked_solid_carries_its_graphic_too() {
let d = document();
let mut n = Node::path(
NodeId(7),
shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)),
Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 20.0),
);
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 2000.0}]});
n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
assert_eq!(graphics_in(&solid_art_in(Some(&d), &n).unwrap()).len(), 1);
}
#[test]
fn art_nested_too_deep_is_refused_and_not_drawn() {
let mut d = document();
let mut art = square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()));
for k in 0..=MAX_LEVELS {
art = Node::group(NodeId(k as u64 + 1), vec![Arc::new(art)]);
}
d.symbols.push(Symbol { dynamic: false, name: "Deep".into(), art: Arc::new(art) });
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]}));
let e = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Deep"}]})).unwrap_err();
assert!(e.contains("nested"), "{e}");
assert!(graphics_in(&solid_art_in(Some(&d), &n).unwrap()).is_empty());
// A loaded file draws its other graphics.
let both = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}, {"symbol": "Mark"}]}));
assert_eq!(graphics_in(&solid_art_in(Some(&d), &both).unwrap()).len(), 1);
}
#[test]
fn symbols_nested_too_deep_are_refused_and_not_drawn() {
let mut d = document();
// Symbol `N{k}` holds an instance of `N{k-1}`, and `N0` is a square.
d.symbols.push(Symbol { dynamic: false, name: "N0".into(), art: Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()))) });
for k in 1..=MAX_NESTING + 1 {
let instance = Node::new(NodeId(k as u64), NodeKind::SymbolInstance { symbol: format!("N{}", k - 1), xf: Affine::IDENTITY });
d.symbols.push(Symbol { dynamic: false, name: format!("N{k}"), art: Arc::new(instance) });
}
let deepest = format!("N{MAX_NESTING}");
let p = json!({"graphics": [{"symbol": deepest}]});
assert!(validate_three_d_in(Some(&d), &object(EXTRUDE, p.clone()), EXTRUDE, &p).is_ok());
assert_eq!(graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, p)).unwrap()).len(), 1);
let past = format!("N{}", MAX_NESTING + 1);
let p = json!({"graphics": [{"symbol": past}]});
let e = validate_three_d_in(Some(&d), &object(EXTRUDE, p.clone()), EXTRUDE, &p).unwrap_err();
assert!(e.contains("nest"), "{e}");
assert!(graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, p)).unwrap()).is_empty());
}
#[test]
fn a_solid_in_a_transparent_gradient_keeps_its_graphic() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let d = document();
let mut stop = GradientStop::new(1.0, red());
stop.opacity = 0.25;
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
// Under a colored light the faces are drawn opaque and masked by the gradient's transparency.
let mut n = object(EXTRUDE, json!({"shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Gradient(Box::new(gradient));
}
let art = solid_art_in(Some(&d), &n).unwrap();
let mut masked = false;
art.walk(&mut |c| masked |= c.extras().mask.is_some());
assert!(masked);
assert_eq!(graphics_in(&art).len(), 1);
// Each graphic clip group in `art`, in drawing order: whether it carries an opacity mask.
let masks = |art: &Node| {
let mut out = vec![];
art.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind
&& let [_, inner] = children.as_slice()
&& matches!(inner.kind, NodeKind::Group { clip: false, .. })
{
out.push(c.extras().mask.is_some());
}
});
out
};
// The graphic carries the cap's mask, so it is hidden where the gradient is transparent.
assert_eq!(masks(&art), vec![true]);
// With an opaque stroke drawn after the fill, the fill's cap keeps a masked graphic of its own
// and the stroke's outline gets an unmasked one.
n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0)));
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]);
}
#[test]
fn a_cap_with_a_hole_keeps_the_hole_out_of_the_graphic() {
let d = document();
let outer = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath();
let hole = shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)).to_bezpath().reverse_subpaths();
let mut ring = outer;
ring.extend(hole.iter());
for flip in [false, true] {
let ring = if flip { ring.reverse_subpaths() } else { ring.clone() };
let mut n =
Node::path(NodeId(7), PathData::from_bezpath(&ring), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0));
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 2000.0}]});
n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
let art = solid_art_in(Some(&d), &n).unwrap();
let mut clips = vec![];
art.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind {
clips.push(children[0].path_data().unwrap().to_bezpath());
}
});
assert_eq!(clips.len(), 1, "flip {flip}");
assert_ne!(clips[0].winding(Point::new(10.0, 10.0)), 0, "flip {flip}: the ring is inside the clip");
assert_eq!(clips[0].winding(Point::new(50.0, 50.0)), 0, "flip {flip}: the hole is outside it");
}
}
#[test]
fn a_graphic_starts_inside_its_object() {
let d = document();
let frame = graphic_frame(Some(&d), &object(EXTRUDE, json!({})), None).unwrap();
assert_eq!(frame.fitting_scale(Rect::new(0.0, 0.0, 10.0, 10.0)), 100.0);
assert!((frame.fitting_scale(Rect::new(0.0, 0.0, 400.0, 200.0)) - 25.0).abs() < 1e-9);
assert_eq!(super::super::graphic_bounds(&d, "Mark"), Some(Rect::new(500.0, 500.0, 510.0, 510.0)));
}
#[test]
fn a_symbol_instance_in_a_graphic_draws_as_the_canvas_shows_it() {
let mut d = document();
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
// A dynamic symbol whose instance in "Changed" fills its square blue instead of red.
d.symbols.push(Symbol { dynamic: true, name: "Dynamic".into(), art: Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()))) });
let mut changed = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "Dynamic".into(), xf: Affine::IDENTITY });
changed.extras_mut().symbol_overrides =
vec![vectorcraft_doc::symbol_overrides::SymbolOverride { fill: Some(blue.clone()), ..Default::default() }];
d.symbols.push(Symbol { dynamic: false, name: "Changed".into(), art: Arc::new(changed) });
let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "Changed").unwrap()).unwrap();
assert_eq!(pieces.iter().map(|p| p.paint.clone()).collect::<Vec<_>>(), [blue]);
// A symbol with 9-slice guides, a 100 × 100 square with a 10 × 10 one in its corner, placed
// three times as wide: the corner keeps its width while the rest stretches.
let corner = square(2, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()));
let whole = square(3, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(red()));
d.symbols.push(Symbol { dynamic: false, name: "Sliced".into(), art: Arc::new(Node::group(NodeId(4), vec![Arc::new(whole), Arc::new(corner)])) });
d.set_symbol_nine_slice("Sliced", Some(vectorcraft_doc::SymbolNineSlice::default()));
let wide = Node::new(NodeId(5), NodeKind::SymbolInstance { symbol: "Sliced".into(), xf: Affine::scale_non_uniform(3.0, 1.0) });
d.symbols.push(Symbol { dynamic: false, name: "Wide".into(), art: Arc::new(wide) });
let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "Wide").unwrap()).unwrap();
let widths: Vec<f64> = pieces.iter().map(|p| p.path.bounds().unwrap().width()).collect();
assert_eq!(widths.len(), 2);
assert!((widths[1] / widths[0] - 1.0 / 30.0).abs() < 1e-6, "{widths:?}");
// With a gradient, the square crossing the guides is cut at them: its pieces cover the
// placed 300 × 100 once, not one whole copy for each cell.
use vectorcraft_doc::color::{Gradient, GradientPaint};
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
let shaded = square(6, Rect::new(0.0, 0.0, 100.0, 100.0), gradient);
d.symbols.push(Symbol { dynamic: false, name: "Shaded".into(), art: Arc::new(Node::group(NodeId(7), vec![Arc::new(shaded)])) });
d.set_symbol_nine_slice("Shaded", Some(vectorcraft_doc::SymbolNineSlice::default()));
let wide = Node::new(NodeId(8), NodeKind::SymbolInstance { symbol: "Shaded".into(), xf: Affine::scale_non_uniform(3.0, 1.0) });
d.symbols.push(Symbol { dynamic: false, name: "WideShaded".into(), art: Arc::new(wide) });
let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "WideShaded").unwrap()).unwrap();
let area: f64 = pieces.iter().map(|p| p.path.to_bezpath().area().abs()).sum();
assert!((area - 30_000.0).abs() < 1e-3, "{area}");
}
+276
View File
@@ -0,0 +1,276 @@
//! Expand as Wireframes: the edges of the faces a 3D effect draws, as open and closed paths that
//! can be edited on their own.
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId};
use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath};
use vectorcraft_three_d::Facet;
use super::{
INFLATE, Profile, ROTATE, facets, geometry, has_solid, inflate_options, is_container, is_plane, is_three_d, label_of, members, object_profile,
region, reshape_members, resolve, resolve_for, solid, solid_paints, solid_parts, union_bounds, view_options,
};
use crate::{GeomContext, is_geometry};
/// The most distinct edges one object's wireframe may have.
pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000;
/// The grid points are rounded to before edges are compared, in points: two faces that share an
/// edge give it once.
const GRID: f64 = 1.0 / 1024.0;
const NO_EFFECT: &str = "the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)";
/// The wireframe of `n`'s 3D effect (Extrude & Bevel, Revolve, Inflate, Rotate or one of their 3D
/// (Classic) forms), in document coordinates: the edges of every face the effect draws for the object as
/// it is turned and projected, each edge once. Edges that meet end to end are joined into one path;
/// a run that comes back to where it started is closed. A curved edge stays a curve. The geometry
/// effects after the object's 3D effect reshape the wireframe as they reshape the drawn art. On a
/// group or layer, the edges of the solids of all its members. An error when `n` has no visible 3D
/// effect, when its solids can't be built, when the canvas draws the source art in their place, when
/// they draw no face, or past [`MAX_WIRE_EDGES`] edges.
pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> {
if !crate::has_revolve(n) && !has_solid(n) {
return Err(NO_EFFECT.into());
}
let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id));
// The faces come from the effect whose art the canvas draws (Revolve first, as the canvas tries
// it first). When neither draws, past their limits, the canvas shows the source art and there
// is no surface to expand.
let revolve = crate::has_revolve(n) && crate::revolve_art_in(doc, n).is_some();
if !revolve && !(has_solid(n) && super::solid_art_in(doc, n).is_some()) {
// The builders' own error says why, when there is one. Revolve's art is cut for Revolve,
// as the canvas cuts it.
if crate::has_revolve(n) {
crate::revolve::revolve_face_paths(doc, &*resolve_for(doc, n, label, false)?)?;
} else {
solid_face_paths(doc, &*resolve(doc, n, label)?)?;
}
return Err(format!("{label} draws the source art for this object instead of its 3D surface"));
}
// Revolve's art is cut for Revolve whatever other 3D effect the object carries, as the canvas
// cuts it ([`crate::revolve_art_in`]).
let n = &*if revolve { resolve_for(doc, n, label, false)? } else { resolve(doc, n, label)? };
let faces = if revolve { crate::revolve::revolve_face_paths(doc, n)? } else { solid_face_paths(doc, n)? };
let faces = after_geometry(doc, n, faces, revolve);
let wire = edges(&faces)?;
if wire.is_empty() {
return Err(format!("{label} draws no faces for this object"));
}
Ok(wire)
}
/// `faces` reshaped by the visible geometry effects after the 3D effect of `n`'s own that drew them
/// ([`reshaped`]): its first visible Revolve when `revolve` is set, else its first visible Extrude &
/// Bevel, Inflate or Rotate.
fn after_geometry(doc: Option<&Document>, n: &Node, faces: Vec<PathData>, revolve: bool) -> Vec<PathData> {
let fx = &n.appearance.effects;
let drawn = if revolve { fx.iter().position(|e| e.visible && crate::revolve::is_revolve(&e.id)) } else { solid(fx).map(|(i, _)| i) };
let Some(index) = drawn else { return faces };
reshaped(faces, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) })
}
/// `faces` reshaped by the visible geometry effects in `later` (the effects after a 3D effect), as
/// they reshape the faces of the drawn surface ([`crate::reshape::reshape_leaves`]): each effect
/// reshapes each face on its own, about the bounds all the faces have before it, and the faces keep
/// to one budget of anchors together. `ctx` gives the object's id, the seed of a random Transform,
/// and the document.
pub(crate) fn reshaped(faces: Vec<PathData>, later: &[Effect], ctx: &GeomContext) -> Vec<PathData> {
let after: Vec<&Effect> = later.iter().filter(|e| e.visible && is_geometry(&e.id)).collect();
if after.is_empty() {
return faces;
}
let id = NodeId(ctx.seed);
let fill = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
let mut art = Node::group(id, faces.into_iter().map(|f| Arc::new(Node::path(id, f, fill.clone()))).collect());
crate::reshape::reshape_leaves(&mut art, &after, later, ctx.doc);
let mut out = vec![];
art.walk(&mut |c| out.extend(c.path_data().cloned()));
out
}
/// The outline of every face [`super::solid_art`] draws for `n` (already resolved): with the effect
/// on the object, its solids; with it on fills and strokes, the solid of each; on a group or layer,
/// the solids of its members, about one shared axis. The swatches and patterns named by a live-effect
/// plug-in after a fill's or stroke's 3D effect are looked up in `doc`.
fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> {
if is_container(n) {
let (index, fx) = solid(&n.appearance.effects).ok_or("a 3D effect on a group's fill or stroke draws nothing")?;
let mut shapes = members(n, label_of(&fx.id))?;
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
return facet_paths(fx, &shapes);
}
let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id));
let (path, rule) = object_profile(n, label)?;
let ctx = GeomContext::of(n);
let paints = solid_paints(n);
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
return facet_paths(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }]);
}
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
for item in &paints {
if let Some((index, fx)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
let faces = facet_paths(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
out.extend(reshaped(faces, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
}
Ok(out)
}
/// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: Rotate and
/// Rotate (Classic) turn every fill and stroke; Extrude & Bevel and Inflate build a solid from each shape's
/// top fill and from the outline of each stroke. A stroke whose solid is past the limits is left out,
/// as it is left out of the drawn art.
fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<PathData>, String> {
let label = label_of(&fx.id);
let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
let p = crate::merged_params(&fx.id, &fx.params);
let mut out = vec![];
if is_plane(&fx.id) {
for s in shapes {
for item in &s.items {
let (area, rule) = region(&s.path, s.rule, item);
out.extend(facets(ROTATE, &area, rule, b, &p)?.iter().map(Facet::path));
}
}
return Ok(out);
}
let (parts, bounds) = solid_parts(shapes, b);
let built: Vec<Result<Vec<Facet>, String>> = if fx.id == INFLATE {
let shapes: Vec<(&PathData, vectorcraft_geom::FillRule)> = parts.iter().map(|(_, _, area, rule, ..)| (area, *rule)).collect();
vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p))
} else {
parts.iter().map(|(_, _, area, rule, ..)| facets(&fx.id, area, *rule, bounds, &p)).collect()
};
for ((item, ..), f) in parts.iter().zip(built) {
match f {
Ok(f) => out.extend(f.iter().map(Facet::path)),
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
Err(e) => return Err(e),
}
}
Ok(out)
}
/// A point on the [`GRID`].
type Snap = (i64, i64);
fn snap(p: Point) -> Snap {
((p.x / GRID).round() as i64, (p.y / GRID).round() as i64)
}
fn reversed(c: CubicBez) -> CubicBez {
CubicBez::new(c.p3, c.p2, c.p1, c.p0)
}
/// The edges of `faces`, each once, joined end to end into paths ([`three_d_wireframe_in`]).
pub(crate) fn edges(faces: &[PathData]) -> Result<Vec<PathData>, String> {
let mut seen: HashSet<[Snap; 4]> = HashSet::new();
let mut segments: Vec<CubicBez> = vec![];
for sp in faces.iter().flat_map(|f| &f.subpaths) {
for i in 0..sp.segment_count() {
let mut c = sp.segment(i);
if sp.segment_is_line(i) {
c = CubicBez::new(c.p0, c.p0, c.p3, c.p3);
}
if [c.p0, c.p1, c.p2, c.p3].iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
continue;
}
let key = [c.p0, c.p1, c.p2, c.p3].map(snap);
// A segment that starts and ends on one grid point with its handles there too draws nothing.
if key.iter().all(|k| *k == key[0]) {
continue;
}
let back = [key[3], key[2], key[1], key[0]];
if seen.contains(&back) || !seen.insert(key) {
continue;
}
if segments.len() >= MAX_WIRE_EDGES {
return Err(format!("the wireframe has more than {MAX_WIRE_EDGES} edges"));
}
segments.push(c);
}
}
Ok(chain(&segments))
}
/// `segments` joined end to end: each path starts at the first segment not yet used and takes in
/// the unused segments that meet its ends until none is left at either end, or it closes.
fn chain(segments: &[CubicBez]) -> Vec<PathData> {
let mut at: HashMap<Snap, Vec<usize>> = HashMap::new();
for (i, c) in segments.iter().enumerate() {
at.entry(snap(c.p0)).or_default().push(i);
if snap(c.p3) != snap(c.p0) {
at.entry(snap(c.p3)).or_default().push(i);
}
}
let mut used = vec![false; segments.len()];
// The next unused segment at `point`, turned to leave it (`leave`) or to arrive at it.
let mut take = |used: &mut Vec<bool>, point: Snap, leave: bool| -> Option<CubicBez> {
let list = at.get_mut(&point)?;
while let Some(&i) = list.last() {
if used.get(i).copied().unwrap_or(true) {
list.pop();
continue;
}
if let Some(u) = used.get_mut(i) {
*u = true;
}
let c = *segments.get(i)?;
let starts = snap(c.p0) == point;
return Some(if starts == leave { c } else { reversed(c) });
}
None
};
let mut out = vec![];
for (i, first) in segments.iter().enumerate() {
if used.get(i).copied().unwrap_or(true) {
continue;
}
if let Some(u) = used.get_mut(i) {
*u = true;
}
let mut run: VecDeque<CubicBez> = VecDeque::from([*first]);
// A path of one anchor has no segment (`SubPath::segment_count`), so a run of one segment
// that comes back to its start stays open, with its two ends on one point.
let closes = |run: &VecDeque<CubicBez>| run.len() > 1 && run.front().zip(run.back()).is_some_and(|(f, b)| snap(f.p0) == snap(b.p3));
while !closes(&run) {
let Some(end) = run.back().map(|c| snap(c.p3)) else { break };
let Some(c) = take(&mut used, end, true) else { break };
run.push_back(c);
}
while !closes(&run) {
let Some(start) = run.front().map(|c| snap(c.p0)) else { break };
let Some(c) = take(&mut used, start, false) else { break };
run.push_front(c);
}
out.push(PathData::single(subpath(&run, closes(&run))));
}
out
}
/// `run`, segments that meet end to end, as one subpath; a closed one ends at its first anchor.
fn subpath(run: &VecDeque<CubicBez>, closed: bool) -> SubPath {
let mut anchors: Vec<Anchor> = vec![];
if let Some(first) = run.front() {
let h_in = if closed { run.back().map_or(first.p0, |b| b.p2) } else { first.p0 };
anchors.push(Anchor::with_handles(first.p0, h_in, first.p1));
}
for (k, c) in run.iter().enumerate() {
let h_out = run.get(k + 1).map_or(c.p3, |next| next.p1);
anchors.push(Anchor::with_handles(c.p3, c.p2, h_out));
}
// A closed run's last anchor is its first, whose in handle already comes from the last segment.
if closed {
anchors.pop();
}
SubPath::new(anchors, closed)
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,235 @@
use serde_json::{Value, json};
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, Node, NodeId};
use vectorcraft_geom::{BezPath, Rect};
use super::*;
fn square(x: f64, y: f64, size: f64) -> PathData {
let mut b = BezPath::new();
b.move_to((x, y));
b.line_to((x + size, y));
b.line_to((x + size, y + size));
b.line_to((x, y + size));
b.close_path();
PathData::from_bezpath(&b)
}
/// A filled 100 pt square without a stroke, with effect `id` and `params`.
fn solid_square(id: &str, params: Value) -> Node {
let mut n = Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
n.appearance.effects.push(crate::new_effect(id, &params).unwrap());
n
}
/// Every segment of `wire`, each as its two ends on the grid.
fn segments(wire: &[PathData]) -> Vec<(Snap, Snap)> {
wire.iter()
.flat_map(|p| &p.subpaths)
.flat_map(|sp| (0..sp.segment_count()).map(move |i| sp.segment(i)))
.map(|c| (snap(c.p0), snap(c.p3)))
.collect()
}
fn bounds(paths: &[PathData]) -> Rect {
paths.iter().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap()
}
/// The paths of the faces `art` draws (every leaf of the art).
fn face_paths(art: &Node) -> Vec<PathData> {
let mut out = vec![];
art.walk(&mut |c| out.extend(c.path_data().cloned()));
out
}
#[test]
fn two_faces_that_share_an_edge_give_it_once() {
let wire = edges(&[square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)]).unwrap();
let segs = segments(&wire);
assert_eq!(segs.len(), 7, "{segs:?}");
for (i, a) in segs.iter().enumerate() {
for b in segs.iter().skip(i + 1) {
assert!(a != b && (a.1, a.0) != *b, "{a:?} twice");
}
}
}
#[test]
fn a_loop_of_edges_is_one_closed_path_and_a_curve_stays_a_curve() {
let wire = edges(&[square(0.0, 0.0, 10.0)]).unwrap();
assert_eq!(wire.len(), 1);
assert!(wire[0].subpaths[0].closed);
assert_eq!(wire[0].subpaths[0].anchors.len(), 4);
let mut b = BezPath::new();
b.move_to((0.0, 0.0));
b.curve_to((0.0, 10.0), (10.0, 10.0), (10.0, 0.0));
b.close_path();
let wire = edges(&[PathData::from_bezpath(&b)]).unwrap();
let curved = wire.iter().flat_map(|p| &p.subpaths).any(|sp| (0..sp.segment_count()).any(|i| !sp.segment_is_line(i)));
assert!(curved, "{wire:?}");
}
/// A single curve that comes back to its start keeps its segment: it stays open, with two anchors on
/// one point, since a path of one anchor has no segment.
#[test]
fn a_single_curve_that_comes_back_to_its_start_keeps_its_segment() {
let p = Point::new(0.0, 0.0);
let anchors = vec![Anchor::with_handles(p, p, Point::new(0.0, 10.0)), Anchor::with_handles(p, Point::new(10.0, 10.0), p)];
let face = PathData::single(SubPath::new(anchors, false));
assert_eq!(face.subpaths[0].segment_count(), 1);
let wire = edges(&[face]).unwrap();
assert_eq!(wire.len(), 1);
let sp = &wire[0].subpaths[0];
assert_eq!(sp.segment_count(), 1, "{sp:?}");
assert!(!sp.segment_is_line(0));
}
#[test]
fn edges_without_length_or_with_non_finite_points_are_left_out() {
let point = PathData::single(SubPath::polyline(&[Point::new(5.0, 5.0), Point::new(5.0, 5.0)], false));
let bad = PathData::single(SubPath::polyline(&[Point::new(f64::NAN, 0.0), Point::new(1.0, 1.0)], false));
assert!(edges(&[point, bad]).unwrap().is_empty());
assert!(edges(&[]).unwrap().is_empty());
}
#[test]
fn a_box_turned_off_axis_shows_the_nine_edges_of_its_three_faces() {
let n = solid_square(super::super::EXTRUDE, json!({}));
let wire = three_d_wireframe_in(None, &n).unwrap();
assert_eq!(segments(&wire).len(), 9, "{wire:?}");
// The wireframe covers what the effect draws, in the same place.
let art = super::super::solid_art(&n).unwrap();
let (w, a) = (bounds(&wire), bounds(&face_paths(&art)));
for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] {
assert!((x - y).abs() < 1e-6, "{w:?} {a:?}");
}
}
#[test]
fn the_classic_wireframe_surface_expands_to_all_twelve_edges() {
let n = solid_square(super::super::CLASSIC_EXTRUDE, json!({"surface": "wireframe"}));
assert_eq!(segments(&three_d_wireframe_in(None, &n).unwrap()).len(), 12);
}
#[test]
fn revolve_inflate_and_rotate_expand_too() {
for id in [crate::REVOLVE, super::super::INFLATE, ROTATE] {
let wire = three_d_wireframe_in(None, &solid_square(id, json!({}))).unwrap_or_else(|e| panic!("{id}: {e}"));
assert!(!wire.is_empty(), "{id}");
assert!(wire.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.anchors).all(|a| a.p.x.is_finite() && a.p.y.is_finite()), "{id}");
}
// Rotate is one flat face: its outline.
let plane = three_d_wireframe_in(None, &solid_square(ROTATE, json!({}))).unwrap();
assert_eq!(segments(&plane).len(), 4);
}
/// Revolve (Classic) and Rotate (Classic) expand to the edges of the faces they draw, in the same
/// place.
#[test]
fn revolve_classic_and_rotate_classic_expand_too() {
let n = solid_square(crate::CLASSIC_REVOLVE, json!({}));
let wire = three_d_wireframe_in(None, &n).unwrap();
assert!(!wire.is_empty());
let art = crate::revolve_art(&n).unwrap();
let (w, a) = (bounds(&wire), bounds(&face_paths(&art)));
for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] {
assert!((x - y).abs() < 1e-6, "{w:?} {a:?}");
}
// On a fill, with a geometry effect after it.
let mut n = solid_square(crate::CLASSIC_REVOLVE, json!({}));
let fx = n.appearance.effects.remove(0);
for item in &mut n.appearance.items {
if matches!(item, AppearanceItem::Fill(_)) {
item.effects_mut().push(fx.clone());
}
}
let plain = bounds(&three_d_wireframe_in(None, &n).unwrap());
for item in &mut n.appearance.items {
if matches!(item, AppearanceItem::Fill(_)) {
item.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap());
}
}
let moved = bounds(&three_d_wireframe_in(None, &n).unwrap());
assert!((moved.x0 - plain.x0 - 50.0).abs() < 1e-6 && (moved.y0 - plain.y0).abs() < 1e-6, "{plain:?} {moved:?}");
// Rotate (Classic) is one flat face: its outline.
let plane = three_d_wireframe_in(None, &solid_square(super::super::CLASSIC_ROTATE, json!({}))).unwrap();
assert_eq!(segments(&plane).len(), 4);
}
/// The geometry effects after a 3D effect reshape each face on its own, as they reshape each face
/// of the drawn surface: two faces that touch stay two outlines.
#[test]
fn later_geometry_effects_reshape_each_face_on_its_own() {
let n = solid_square(super::super::EXTRUDE, json!({}));
let fx = [crate::new_effect("path.offsetPath", &json!({"offset": 1.0})).unwrap()];
let out = reshaped(vec![square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)], &fx, &GeomContext::of(&n));
assert_eq!(out.len(), 2, "{out:?}");
let (a, b) = (out[0].bounds().unwrap(), out[1].bounds().unwrap());
assert!((a.x0 + 1.0).abs() < 1e-3 && (a.x1 - 11.0).abs() < 1e-3, "{a:?}");
assert!((b.x0 - 9.0).abs() < 1e-3 && (b.x1 - 21.0).abs() < 1e-3, "{b:?}");
}
/// A geometry effect after a fill's 3D effect moves that fill's edges, as it moves its drawn surface.
#[test]
fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() {
for id in [super::super::EXTRUDE, crate::REVOLVE] {
let mut n = solid_square(id, json!({}));
let fx = n.appearance.effects.remove(0);
for item in &mut n.appearance.items {
if matches!(item, AppearanceItem::Fill(_)) {
item.effects_mut().push(fx.clone());
}
}
let plain = bounds(&three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}")));
for item in &mut n.appearance.items {
if matches!(item, AppearanceItem::Fill(_)) {
item.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap());
}
}
let moved = bounds(&three_d_wireframe_in(None, &n).unwrap());
assert!((moved.x0 - plain.x0 - 50.0).abs() < 1e-6 && (moved.y0 - plain.y0).abs() < 1e-6, "{id}: {plain:?} {moved:?}");
}
}
/// With two 3D effects, a geometry effect between them reshapes the faces of the one drawn only
/// once: Revolve is drawn, so a Transform before it moves its profile and not its faces again.
#[test]
fn a_geometry_effect_before_the_drawn_3d_effect_is_not_applied_again() {
let mut n = solid_square(crate::REVOLVE, json!({}));
n.appearance.effects.insert(0, crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap());
let alone = bounds(&three_d_wireframe_in(None, &n).unwrap());
n.appearance.effects.insert(0, crate::new_effect(super::super::EXTRUDE, &json!({})).unwrap());
let both = bounds(&three_d_wireframe_in(None, &n).unwrap());
assert!((both.x0 - alone.x0).abs() < 1e-6 && (both.x1 - alone.x1).abs() < 1e-6, "{alone:?} {both:?}");
}
/// A clipping group with Revolve and Rotate draws Revolve, which cuts the art's fills as one piece
/// in the top fill's place. Its wireframe is cut the same way, so art with more fills than a 3D
/// effect takes members still expands, to the edges of Revolve alone.
#[test]
fn a_clipping_group_with_revolve_and_rotate_expands_the_art_revolve_cuts() {
let mut art = Node::path(NodeId(3), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
let fill = art.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).cloned().unwrap();
art.appearance.items = vec![fill; super::super::MAX_MEMBERS + 4];
let mut clip = Node::path(NodeId(2), square(100.0, 100.0, 50.0), Appearance::default());
if let vectorcraft_doc::NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
let mut n = Node::new(NodeId(1), vectorcraft_doc::NodeKind::Group { children: vec![Arc::new(clip), Arc::new(art)], clip: true });
n.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({})).unwrap());
let alone = segments(&three_d_wireframe_in(None, &n).unwrap());
n.appearance.effects.push(crate::new_effect(ROTATE, &json!({})).unwrap());
assert!(crate::revolve_art_in(None, &n).is_some(), "the canvas draws Revolve");
let both = segments(&three_d_wireframe_in(None, &n).unwrap());
assert_eq!(both, alone);
}
#[test]
fn an_object_without_a_visible_3d_effect_is_an_error() {
let mut n = solid_square(super::super::EXTRUDE, json!({}));
n.appearance.effects[0].visible = false;
assert!(three_d_wireframe_in(None, &n).unwrap_err().contains("no 3D effect"));
n.appearance.effects.clear();
assert!(three_d_wireframe_in(None, &n).is_err());
}
+21 -11
View File
@@ -4,7 +4,8 @@
//! in the back wall of hollow ones (with the cap kept out of the hole) and at the chevron's inner
//! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by
//! the inset; with [`ArrowAlign::Extend`] the path keeps its length and the tip sits the inset
//! past the end point. Heads added after the first ten are drawn in local units ([`local`]).
//! past the end point. Heads added after the first ten are drawn in local units ([`local`]), as are
//! custom heads, whose stroke ends halfway along their length.
use std::borrow::Cow;
@@ -37,8 +38,14 @@ pub(super) fn pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a>
let last = subs.last().filter(|s| !s.1).map(|s| s.0.clone());
let cap = cap_extent(st.cap, st.width);
let (hw0, hw1) = (st.arrow_weight(false), st.arrow_weight(true));
let start = st.start_arrow.zip(first).map(|(k, r)| (k, r, inset(k, hw0, cap)));
let end = st.end_arrow.zip(last).map(|(k, r)| (k, r, inset(k, hw1, cap)));
let start = st.start_arrow.clone().zip(first).map(|(k, r)| {
let i = inset(&k, hw0, cap);
(k, r, i)
});
let end = st.end_arrow.clone().zip(last).map(|(k, r)| {
let i = inset(&k, hw1, cap);
(k, r, i)
});
if start.is_none() && end.is_none() {
return StrokePieces { line: Cow::Borrowed(bp), heads: vec![] };
}
@@ -56,7 +63,8 @@ pub(super) fn pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a>
} else {
(end_pt + outward * inset, outward)
};
heads.push(Arrow { kind, outline: shape(kind, tip, dir, hw), tip, dir, inset });
let outline = shape(&kind, tip, dir, hw);
heads.push(Arrow { kind, outline, tip, dir, inset });
};
if let Some((k, r, i)) = start {
place(k, r, true, i, hw0);
@@ -181,12 +189,12 @@ pub(super) fn trims(st: &StrokeLayer) -> (f64, f64) {
return (0.0, 0.0);
}
let cap = cap_extent(st.cap, st.width);
let inset_of = |kind: Option<Arrowhead>, end: bool| kind.map_or(0.0, |k| inset(k, st.arrow_weight(end), cap));
(inset_of(st.start_arrow, false), inset_of(st.end_arrow, true))
let inset_of = |kind: &Option<Arrowhead>, end: bool| kind.as_ref().map_or(0.0, |k| inset(k, st.arrow_weight(end), cap));
(inset_of(&st.start_arrow, false), inset_of(&st.end_arrow, true))
}
/// Distance from the tip where the stroke ends, for a stroke whose cap reaches `cap` past its end.
fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
fn inset(kind: &Arrowhead, hw: f64, cap: f64) -> f64 {
let l = len(hw);
// Solid heads: halfway in, far enough that the cap stays behind the tip.
let solid = |back: f64| (back / 2.0).max(cap);
@@ -199,6 +207,7 @@ fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
Arrowhead::TriangleOpen | Arrowhead::CircleOpen | Arrowhead::SquareOpen => hollow(l),
// The inner corner of the chevron: arm / sin(half angle).
Arrowhead::ArrowOpen => (arm(hw) * (l * l + l * l / 4.0).sqrt() / (l / 2.0)).max(cap),
Arrowhead::Custom(c) => (c.stop() * hw).max(cap),
_ => match local_stop(kind) {
Stop::At(u) => (u * hw).max(cap),
Stop::Wall(back) => hollow(back * hw),
@@ -207,7 +216,7 @@ fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
}
/// Outline of a `kind` head of weight `hw` with its tip at `tip`, pointing along `dir`.
fn shape(kind: Arrowhead, tip: Point, dir: Vec2, hw: f64) -> BezPath {
fn shape(kind: &Arrowhead, tip: Point, dir: Vec2, hw: f64) -> BezPath {
let n = Vec2::new(-dir.y, dir.x);
let l = len(hw);
let half = l / 2.0;
@@ -265,7 +274,7 @@ const HEX: f64 = 2.0 * 1.732_050_807_568_877_2;
const LOCAL_TOL: f64 = 1e-3;
/// Where the stroke ends under a head drawn in local units ([`local`]), in those units.
fn local_stop(kind: Arrowhead) -> Stop {
fn local_stop(kind: &Arrowhead) -> Stop {
match kind {
Arrowhead::Target | Arrowhead::TagOpen | Arrowhead::DiamondOpen => Stop::Wall(4.0),
Arrowhead::HexagonOpen => Stop::Wall(HEX),
@@ -288,8 +297,8 @@ fn local_stop(kind: Arrowhead) -> Stop {
/// The outline of a head added after the first ten, in local units: x from the tip (0) back
/// along the line (to at most 4; the line arrow's square-cut arms 4.71), y across it (−2 to 2,
/// the line arrow −4 to 4; positive to the right of the direction the head points). Every shape
/// is generated here.
fn local(kind: Arrowhead) -> BezPath {
/// is generated here, and a custom head's outline is its own.
fn local(kind: &Arrowhead) -> BezPath {
let mut p = BezPath::new();
let poly = |p: &mut BezPath, pts: &[(f64, f64)]| polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>());
let ring_poly = |p: &mut BezPath, pts: &[(f64, f64)]| ring_polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>(), ring(1.0));
@@ -385,6 +394,7 @@ fn local(kind: Arrowhead) -> BezPath {
let t = FRAC_1_SQRT_2;
poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]);
}
Arrowhead::Custom(c) => p = c.path.to_bezpath(),
// The first ten are drawn by `shape`.
Arrowhead::Triangle
| Arrowhead::TriangleOpen
+27 -6
View File
@@ -32,6 +32,12 @@ const SHARP: f64 = 1.25;
const HAIRPIN: f64 = 4.0;
/// Rows of a mesh across the stroke (more where the gradient has stops).
const MESH_ROWS: usize = 16;
/// The most stops of the gradient [`gradient_meshes`] puts rows or columns at
/// ([`Gradient::fitted`]: past it, the stops that change the colors least are left out).
pub(crate) const MAX_MESH_STOPS: usize = 1024;
/// The most points of one mesh [`gradient_meshes`] makes, unless a single pair of ribs needs more:
/// a subpath with more ribs than leave room for a row at each stop becomes several meshes.
pub(crate) const MAX_MESH_POINTS: usize = 1 << 20;
/// The most of a subpath one column of a mesh along the stroke spans.
const MESH_STEP: f64 = 1.0 / 32.0;
/// The most of a subpath one slice spans while a width profile shapes the across gradient.
@@ -513,26 +519,33 @@ fn mesh_marks(g: &Gradient) -> Vec<f64> {
/// Outline Stroke of stroke `st` of `bp` (filled with `rule`) whose gradient `g` runs along or
/// across it: a gradient mesh per subpath over all the stroke can paint there (clip it to the
/// stroke's outline), coloured as [`gradient_slices`] paint it.
/// stroke's outline), coloured as [`gradient_slices`] paint it. The gradient's stops are fitted to
/// [`MAX_MESH_STOPS`], and a subpath whose mesh would hold more than [`MAX_MESH_POINTS`] points is
/// split into meshes of fewer ribs ([`rib_pieces`]).
pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradient) -> Vec<GradientMesh> {
let g = &*g.unrolled();
let fitted = g.fitted(MAX_MESH_STOPS);
let across = st.gradient_mode == StrokeGradientMode::Across;
let color = |t: f64| g.sample_keep_model(t.clamp(0.0, 1.0) as f32);
let at_stops = mesh_marks(g);
// Along: a column at each stop (colours are linear between columns), close enough to look smooth.
let marks: Vec<f64> = if across { vec![] } else { at_stops.clone() };
let marks: Vec<f64> = if across { vec![] } else { mesh_marks(&fitted) };
let max_dt = match (across, st.profile.is_some()) {
(false, _) => MESH_STEP,
(true, true) => PROFILE_STEP,
(true, false) => 1.0,
};
// Rows across: the strip's edges, then (across) the band's left edge to its right edge with a row at each stop.
let mut us: Vec<f64> = if across { (0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(at_stops).collect() } else { vec![0.5] };
let mut us: Vec<f64> = if across { (0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(mesh_marks(&fitted)).collect() } else { vec![0.5] };
us.sort_by(f64::total_cmp);
us.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
let us = &us;
let g = &*fitted;
let color = |t: f64| g.sample_keep_model(t.clamp(0.0, 1.0) as f32);
// A mesh is a point for each row (and its two edges) on each rib: a strip with more ribs than
// that leaves room for is split into meshes of fewer ribs.
let per_mesh = MAX_MESH_POINTS / (us.len() + 2);
strips(bp, rule, st, SLICE_TOL, SLICE_MARGIN, &marks, max_dt)
.into_iter()
.filter(|ribs| ribs.len() > 1)
.flat_map(|ribs| rib_pieces(ribs.len(), per_mesh).into_iter().map(move |r| ribs.get(r).unwrap_or_default().to_vec()))
.map(|ribs| {
let (rows, cols) = (us.len() + 1, ribs.len() - 1);
// Each level across: a point on each rib and the gradient position there.
@@ -569,3 +582,11 @@ pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradi
})
.collect()
}
/// The ribs (index ranges of `n`, at least two) of each mesh [`gradient_meshes`] makes of a strip:
/// at most `per_mesh` ribs each (at least two), each starting on the last rib of the one before,
/// so the meshes meet without a gap.
pub(crate) fn rib_pieces(n: usize, per_mesh: usize) -> Vec<std::ops::Range<usize>> {
let per_mesh = per_mesh.max(2);
(0..n.saturating_sub(1)).step_by(per_mesh - 1).map(|start| start..(start + per_mesh).min(n)).collect()
}
+5 -5
View File
@@ -280,7 +280,7 @@ fn no_heads_borrows_the_path_and_closed_paths_get_none() {
#[test]
fn tip_mode_shortens_the_stroke_by_the_head_and_puts_the_tip_on_the_end_point() {
for kind in Arrowhead::ALL {
let st = arrows(kind, ArrowAlign::Tip, LineCap::Butt);
let st = arrows(kind.clone(), ArrowAlign::Tip, LineCap::Butt);
let l = line(0.0, 100.0);
let p = stroke_pieces(&l, &st);
let [h] = &p.heads[..] else { panic!("one head") };
@@ -335,7 +335,7 @@ fn extend_mode_keeps_the_path_and_overhangs_by_the_inset() {
#[test]
fn hollow_heads_are_rings_and_the_stroke_stays_out_of_the_hole() {
for (kind, cap) in [(Arrowhead::CircleOpen, LineCap::Round), (Arrowhead::SquareOpen, LineCap::Square), (Arrowhead::TriangleOpen, LineCap::Butt)] {
let st = arrows(kind, ArrowAlign::Tip, cap);
let st = arrows(kind.clone(), ArrowAlign::Tip, cap);
let l = line(0.0, 100.0);
let p = stroke_pieces(&l, &st);
let h = &p.heads[0];
@@ -361,7 +361,7 @@ fn hollow_heads_are_rings_and_the_stroke_stays_out_of_the_hole() {
fn round_caps_never_poke_past_the_tip() {
for kind in Arrowhead::ALL {
for scale in [10.0, 100.0, 300.0] {
let mut st = arrows(kind, ArrowAlign::Tip, LineCap::Round);
let mut st = arrows(kind.clone(), ArrowAlign::Tip, LineCap::Round);
st.arrow_scale = (scale, scale);
let l = line(0.0, 100.0);
let p = stroke_pieces(&l, &st);
@@ -403,8 +403,8 @@ fn degenerate_paths_and_patterns_neither_panic_nor_hang() {
for pat in patterns {
for off in [0.0, -7.0, 1e12, f64::INFINITY] {
let st = stroke(2.0, |s| {
s.start_arrow = Some(kind);
s.end_arrow = Some(kind);
s.start_arrow = Some(kind.clone());
s.end_arrow = Some(kind.clone());
s.arrow_align = align;
s.cap = cap;
s.dash = Some(dashed(pat, off));
+29 -2
View File
@@ -50,7 +50,7 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() {
let (o, d) = (Point::ORIGIN, Point::new(2.0, 2.0));
assert!(cross((o, d), (Point::new(0.0, 2.0), Point::new(2.0, 0.0))) && !cross((o, d), (d, Point::new(4.0, 0.0))), "the check itself");
for kind in Arrowhead::ALL {
let h = head(kind);
let h = head(kind.clone());
assert!(h.outline.area().abs() > 4.0, "{kind:?} is drawn");
let b = h.outline.bounding_box();
let (reach, side) = (2.0 * kind.reach(), 2.0 * kind.half_width());
@@ -73,7 +73,7 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() {
#[test]
fn the_stroke_ends_inside_every_head() {
for kind in Arrowhead::ALL {
let h = head(kind);
let h = head(kind.clone());
// Just in front of where the line stops, on its centre line.
let end = h.tip - h.dir * (h.inset - 0.1);
assert_ne!(h.outline.winding(end), 0, "{kind:?}: the line ends outside the head (inset {})", h.inset);
@@ -112,3 +112,30 @@ fn half_arrows_barb_on_their_own_side() {
assert!(head(Arrowhead::HalfArrowLeft).outline.bounding_box().y1 < 1.5);
assert!(head(Arrowhead::HalfArrowRight).outline.bounding_box().y1 > 3.0);
}
#[test]
fn custom_heads_draw_their_own_art_at_the_tip() {
use vectorcraft_doc::CustomArrowhead;
use vectorcraft_geom::{PathData, SubPath};
// From the tip back 3 units, 2 to the right of the line and 1 to the left.
let wedge = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true));
let kind = Arrowhead::Custom(std::sync::Arc::new(CustomArrowhead::new("Wedge".into(), wedge)));
let h = head(kind.clone());
// Weight 2: drawn back to x 94, right of +x is +y on a y-down page.
let b = h.outline.bounding_box();
assert!((b.x0 - 94.0).abs() < 1e-9 && (b.x1 - 100.0).abs() < 1e-9 && (b.y0 + 2.0).abs() < 1e-9 && (b.y1 - 4.0).abs() < 1e-9, "{b:?}");
assert_eq!(h.outline.winding(Point::new(95.0, 1.0)), h.outline.winding(Point::new(95.0, 0.5)));
assert_ne!(h.outline.winding(Point::new(95.0, 1.0)), 0);
// The line stops halfway along the head.
assert!((h.inset - 3.0).abs() < 1e-9, "inset {}", h.inset);
// Extended, the tip sits the inset past the end point, and scaling scales the art.
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
(st.start_arrow, st.arrow_scale) = (Some(kind), (200.0, 100.0));
let mut l = BezPath::new();
l.move_to((0.0, 0.0));
l.line_to((100.0, 0.0));
let p = stroke_pieces(&l, &st);
let [s] = &p.heads[..] else { panic!("one head") };
assert!((s.tip.x + 6.0).abs() < 1e-9 && s.dir.x < 0.0, "tip {:?}", s.tip);
assert!((s.outline.bounding_box().width() - 12.0).abs() < 1e-9);
}
@@ -345,6 +345,35 @@ fn a_narrow_peak_where_a_reflecting_gradient_turns_back_stays_in_the_mesh() {
}
}
/// Outline Stroke's mesh across a stroke of many ribs, with a gradient of many stops repeated 100
/// times: each mesh holds at most so many points, and every run still starts on its first color.
#[test]
fn a_mesh_across_many_ribs_and_stops_stays_bounded() {
use vectorcraft_color::GradientSpread;
let pts: Vec<(f64, f64)> = (0..1200).map(|i| (i as f64 * 10.0, if i % 2 == 0 { 0.0 } else { 10.0 })).collect();
let bp = poly(&pts, false);
let stops: Vec<GradientStop> = (0..200).map(|i| GradientStop::new(i as f32 / 199.0, Color::gray(1.0 - i as f32 / 199.0))).collect();
let g = Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(vectorcraft_color::GradientKind::Linear, stops) };
let mut st = stroke(4.0, StrokeGradientMode::Across);
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
let meshes = gradient_meshes(&bp, FillRule::NonZero, &st, &g);
assert!(!meshes.is_empty());
for m in &meshes {
assert!(m.points.len() <= super::gradient::MAX_MESH_POINTS, "{} points", m.points.len());
// A row at the start of each of the 100 runs, on every rib, is white.
let light = m.points.iter().filter(|p| p.color.to_rgb()[0] > 0.97).count();
assert!(light >= 100 * (m.cols as usize + 1), "{light} light points of {}", m.points.len());
}
// A strip of more ribs than one mesh has room for is split into meshes that share their end
// ribs, every rib in one of them.
use super::gradient::rib_pieces;
assert_eq!(rib_pieces(5, 3), [0..3, 2..5]);
assert_eq!(rib_pieces(4, 3), [0..3, 2..4]);
let one = rib_pieces(2, 1000);
assert_eq!((one.len(), one.first()), (1, Some(&(0..2))));
assert_eq!(rib_pieces(3, 0), [0..2, 1..3]);
}
/// #5960: with dashes, the ribs reach as far as the stroke gets wide within a cap's length along
/// the path, however many points lie that far: not as far as it is wide anywhere when more than
/// 256 do.
+44 -2
View File
@@ -78,6 +78,35 @@ fn a_butt_capped_open_path_is_measured_where_it_paints() {
}
}
#[test]
fn beveled_corners_are_measured_where_they_paint() {
let mut tip = BezPath::new();
tip.move_to((0.0, 100.0));
tip.line_to((20.0, 0.0));
tip.line_to((40.0, 100.0));
tip.close_path();
let mut chevron = BezPath::new();
chevron.move_to((0.0, 100.0));
chevron.line_to((20.0, 0.0));
chevron.line_to((40.0, 100.0));
// A rectangle with no width turns back at its top and bottom.
let flat = vectorcraft_geom::shapes::rectangle(Rect::new(3.0, 100.0, 3.0, 150.0)).to_bezpath();
let ps = paths();
for (name, bp) in [("tip", &tip), ("chevron", &chevron), ("zigzag", &ps[1]), ("triangle", &ps[2]), ("flat", &flat)] {
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
for (join, limit) in [(LineJoin::Bevel, 10.0), (LineJoin::Miter, 1.0), (LineJoin::Miter, 2.0), (LineJoin::Miter, 10.0)] {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 20.0);
(st.cap, st.join, st.miter_limit) = (cap, join, limit);
let painted = outline_region(&PathData::from_bezpath(bp), FillRule::NonZero, &st).to_bezpath().bounding_box();
let bounds = st.bounds_on(bp, bp.bounding_box());
for (got, want) in [(bounds.x0, painted.x0), (bounds.y0, painted.y0), (bounds.x1, painted.x1), (bounds.y1, painted.y1)] {
assert!((got - want).abs() < 0.05, "{name} {cap:?} {join:?} {limit}: measured {bounds:?}, paints {painted:?}");
}
}
}
}
}
#[test]
fn bounds_and_clicks_cover_what_every_stroke_paints() {
let profiles = [None, Some(WidthProfile::lens()), Some(WidthProfile { points: vec![(0.0, 2.0, 0.5), (0.6, 0.8, 1.6), (1.0, 1.2, 0.3)] })];
@@ -99,14 +128,27 @@ fn bounds_and_clicks_cover_what_every_stroke_paints() {
}
}
/// Custom heads: one wholly behind its tip, and a long one reaching as far in front of its tip as
/// behind it (its tip sits halfway along it past the end point with Extend).
fn custom_heads() -> Vec<Arrowhead> {
use vectorcraft_geom::{Point as P, SubPath};
let head = |name: &str, pts: &[(f64, f64)]| {
let pts: Vec<P> = pts.iter().map(|&(x, y)| P::new(x, y)).collect();
let path = PathData::single(SubPath::polyline(&pts, true));
Arrowhead::Custom(std::sync::Arc::new(vectorcraft_doc::CustomArrowhead::new(name.into(), path)))
};
vec![head("Wedge", &[(0.0, 0.0), (3.0, 2.0), (3.0, -1.0)]), head("Spindle", &[(-10.0, 0.0), (0.0, 2.0), (10.0, 0.0), (0.0, -2.0)])]
}
#[test]
fn bounds_and_clicks_cover_every_arrowhead() {
let bp = &paths()[0];
for kind in Arrowhead::ALL {
for kind in Arrowhead::ALL.into_iter().chain(custom_heads()) {
for align in [ArrowAlign::Extend, ArrowAlign::Tip] {
for (scale, cap) in [(50.0, LineCap::Round), (100.0, LineCap::Butt), (300.0, LineCap::Square)] {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 3.0);
(st.start_arrow, st.end_arrow, st.arrow_align, st.arrow_scale, st.cap) = (Some(kind), Some(kind), align, (scale, scale), cap);
(st.start_arrow, st.end_arrow, st.arrow_align, st.arrow_scale, st.cap) =
(Some(kind.clone()), Some(kind.clone()), align, (scale, scale), cap);
check(bp, &st, &format!("{kind:?} {align:?} {scale}%"));
}
}
+231
View File
@@ -325,6 +325,23 @@ fn a_shadow_before_a_transform_follows_it_into_3d_art() {
}
}
/// An object's Transform effect transforms the raster effects of its fills when only a fill has a
/// 3D effect: the shadow after that fill's 3D effect and another fill's shadow, as it does without
/// the 3D effect.
#[test]
fn an_objects_transform_moves_its_fills_shadows_beside_a_fills_3d_effect() {
for three_d in [crate::EXTRUDE, crate::REVOLVE] {
let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) };
let mut n = fill_square(18, vec![fx(three_d, json!({})), shadow(10.0, 10.0, 0.0)]);
let mut other = n.appearance.items[0].clone();
*other.effects_mut() = vec![shadow(10.0, 10.0, 0.0)];
n.appearance.items.push(other);
n.appearance.effects = vec![transform(json!({"scaleH": 200, "scaleV": 100}))];
let drawn = shadows_in(&art(&n).unwrap());
assert!(drawn.len() > 1 && near(&drawn, &vec![(20.0, 10.0); drawn.len()]), "{three_d}: {drawn:?}");
}
}
#[test]
fn glows_blurs_and_feathers_scale_with_the_transform_after_them() {
let effects = [
@@ -419,3 +436,217 @@ fn expanded_and_exported_objects_keep_the_shadow_the_canvas_draws() {
assert!(close(drawn_shadow(&b.appearance.effects), (20.0, 20.0, 8.0)), "{id}: {:?}", b.appearance.effects);
}
}
/// A group of `members` with `effects` of its own.
fn group(id: u64, members: Vec<Node>, effects: Vec<Effect>) -> Node {
let mut g = Node::group(NodeId(id), members.into_iter().map(std::sync::Arc::new).collect());
g.appearance.effects = effects;
g
}
/// The node with `id` under `n`.
fn node_in(n: &Node, id: u64) -> Node {
let mut found = None;
n.walk(&mut |m| {
if m.id == NodeId(id) && found.is_none() {
found = Some(m.clone());
}
});
found.unwrap_or_else(|| panic!("no node {id}"))
}
/// The offset of the Drop Shadow that the first fill of `n` draws, its own effects and `n`'s
/// Transform effects applied ([`crate::item_effects_in`]).
fn fill_shadow(n: &Node) -> (f64, f64) {
let item = n.appearance.items.first().unwrap();
match raster_effects(&crate::item_effects_in(&n.appearance.effects, item.effects())).first() {
Some(RasterFx::DropShadow { dx, dy, .. }) => (*dx, *dy),
other => panic!("expected a drop shadow, got {other:?}"),
}
}
/// A group's Transform effect transforms the raster effects of what the group holds with the art,
/// whatever its options: a member's own shadow, a member's fill's shadow and a nested group's own
/// shadow, drawn (the group's art) and baked.
#[test]
fn a_groups_transform_moves_its_members_shadows() {
let cases = [
(json!({"scaleH": 200, "scaleV": 200}), (20.0, 20.0)),
(json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)),
(json!({"rotate": 90, "patterns": true}), (10.0, -10.0)),
(json!({"rotate": 90, "strokes": true}), (10.0, -10.0)),
];
for (params, want) in cases {
let members = vec![
square(21, vec![shadow(10.0, 10.0, 0.0)]),
fill_square(22, vec![shadow(10.0, 10.0, 0.0)]),
group(23, vec![square(24, vec![])], vec![shadow(10.0, 10.0, 0.0)]),
];
let g = group(20, members, vec![transform(params.clone())]);
let art = crate::evaluate_container(None, &g).unwrap();
assert!(near(&shadows_in(&art), &[want; 3]), "{params}: drawn {:?}", shadows_in(&art));
let mut d = Document::new(800.0, 800.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, g).unwrap();
let baked = bake_document(&d).unwrap();
for id in [21, 22, 23] {
let b = baked.node(NodeId(id)).unwrap();
assert!(near(&shadows_in(b), &[want]), "{params}: {id} baked {:?}", shadows_in(b));
}
}
}
/// A group's Transform effect that makes copies or moves at random leaves its members' shadows as
/// they are, as it leaves the shadows listed before it in its own effects.
#[test]
fn a_groups_copying_transform_leaves_its_members_shadows() {
for params in [json!({"scaleH": 200, "scaleV": 200, "copies": 1}), json!({"scaleH": 200, "scaleV": 200, "random": true})] {
let g = group(25, vec![square(26, vec![shadow(10.0, 10.0, 0.0)]), square(27, vec![])], vec![transform(params.clone())]);
let art = crate::evaluate_container(None, &g).unwrap();
let drawn = shadows_in(&art);
assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 10.0); drawn.len()]), "{params}: {drawn:?}");
}
}
/// The Transform effects inside a group apply before the group's: a member's own turn of 90°
/// applies to its shadow before the group's uneven scale does, for the member's own shadow, its
/// fill's shadow, and the shadow of a member of a nested group that has the turn.
#[test]
fn a_groups_transform_applies_after_its_members_own() {
let turn = || transform(json!({"rotate": 90}));
let uneven = || transform(json!({"scaleH": 200, "scaleV": 100}));
// Turned first, (10, 0) goes to (0, -10), which the scale leaves; scaled first, it would be (0, -20).
let want = (0.0, -10.0);
let own = group(30, vec![square(31, vec![shadow(10.0, 0.0, 0.0), turn()])], vec![uneven()]);
let art = crate::evaluate_container(None, &own).unwrap();
assert!(near(&shadows_in(&art), &[want]), "own: {:?}", shadows_in(&art));
let mut on_fill = fill_square(33, vec![shadow(10.0, 0.0, 0.0)]);
on_fill.appearance.effects = vec![turn()];
let art = crate::evaluate_container(None, &group(32, vec![on_fill], vec![uneven()])).unwrap();
assert!(near(&[fill_shadow(&node_in(&art, 33))], &[want]), "fill: {:?}", fill_shadow(&node_in(&art, 33)));
let nested = group(34, vec![group(35, vec![square(36, vec![shadow(10.0, 0.0, 0.0)])], vec![turn()])], vec![uneven()]);
let art = crate::evaluate_container(None, &nested).unwrap();
let inner = crate::evaluate_container(None, &node_in(&art, 35)).unwrap();
assert!(near(&shadows_in(&inner), &[want]), "nested: {:?}", shadows_in(&inner));
}
/// An object's Transform effect transforms the raster effects of its fills and strokes with the
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. One that
/// makes copies leaves them.
#[test]
fn an_objects_transform_moves_its_fills_shadows() {
let cases = [
(json!({"scaleH": 200, "scaleV": 100}), (20.0, 10.0)),
(json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)),
(json!({"rotate": 90, "patterns": true}), (10.0, -10.0)),
(json!({"rotate": 90, "strokes": true}), (10.0, -10.0)),
(json!({"scaleH": 200, "scaleV": 200, "copies": 1}), (10.0, 10.0)),
];
for (params, want) in cases {
let mut n = fill_square(40, vec![shadow(10.0, 10.0, 0.0)]);
n.appearance.effects = vec![transform(params.clone())];
if crate::has_transform_art(&n) {
let art = crate::reshape(None, &n, None).unwrap();
let drawn = shadows_in(&art);
assert!(!drawn.is_empty() && near(&drawn, &vec![want; drawn.len()]), "{params}: drawn {drawn:?}");
} else {
assert!(near(&[fill_shadow(&n)], &[want]), "{params}: drawn {:?}", fill_shadow(&n));
}
let mut d = Document::new(800.0, 800.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, n).unwrap();
let baked = bake_document(&d).unwrap();
let drawn = shadows_in(baked.node(NodeId(40)).unwrap());
assert!(!drawn.is_empty() && near(&drawn, &vec![want; drawn.len()]), "{params}: baked {drawn:?}");
}
}
/// A 10 pt image at the origin with `effects`.
fn image(id: u64, effects: Vec<Effect>) -> Node {
let mut n = Node::new(
NodeId(id),
vectorcraft_doc::NodeKind::Image(Box::new(vectorcraft_doc::ImageObject {
key: "k".into(),
width: 10,
height: 10,
xf: vectorcraft_geom::Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
})),
);
n.appearance.effects = effects;
n
}
/// A group's Transform effect transforms, with Scale Strokes & Effects off or on, the raster
/// effects that a member's own Transform effect with copies holds back: they keep their value
/// through the member's effect and transform with the group's. That holds for a shadow listed
/// before the member's copying effect, one listed after it, a fill's shadow under it, the shadow
/// of a member of a nested group with such an effect, and an image's shadow.
#[test]
fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() {
let copies = || transform(json!({"moveH": 60, "copies": 1}));
// Halved and turned 90° counterclockwise on screen, (10, 10) goes to (5, -5).
let want = (5.0, -5.0);
for strokes in [false, true] {
let mut on_fill = fill_square(73, vec![shadow(10.0, 10.0, 0.0)]);
on_fill.appearance.effects = vec![copies()];
let members = vec![
square(71, vec![shadow(10.0, 10.0, 0.0), copies()]),
square(72, vec![copies(), shadow(10.0, 10.0, 0.0)]),
on_fill,
group(74, vec![square(75, vec![shadow(10.0, 10.0, 0.0)])], vec![copies()]),
image(76, vec![shadow(10.0, 10.0, 0.0)]),
];
let g = group(70, members, vec![transform(json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes}))]);
let art = crate::evaluate_container(None, &g).unwrap();
for id in [71, 72, 73, 75, 76] {
let drawn = shadows_in(&node_in(&art, id));
assert!(near(&drawn, &[want]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}");
}
}
}
/// A group's Transform effect transforms the raster effects in the art of a member's linked opacity
/// mask with the member, a path's or an image's, with Scale Strokes & Effects off or on.
#[test]
fn a_groups_transform_moves_the_shadow_in_a_members_mask() {
let masked = |mut n: Node, id: u64| {
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(square(id, vec![shadow(10.0, 10.0, 0.0)]), true)));
n
};
for strokes in [false, true] {
let params = json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes});
let g = group(80, vec![masked(square(81, vec![]), 82), masked(image(83, vec![]), 84)], vec![transform(params)]);
let art = crate::evaluate_container(None, &g).unwrap();
for id in [81, 83] {
let member = node_in(&art, id);
let mask = member.extras().mask.as_deref().unwrap();
assert!(near(&shadows_in(&mask.art), &[(5.0, -5.0)]), "Scale Strokes & Effects {strokes}: {id} {:?}", shadows_in(&mask.art));
}
}
}
/// A group's Transform effect transforms the shadows of its members' fills that carry a Transform
/// effect of their own with Scale Strokes & Effects on, with the group's Scale Strokes & Effects off
/// or on: a shadow listed after the fill's Transform effect keeps its value through that effect and
/// transforms with the group's, and one listed before it follows the fill's Transform effect and
/// then the group's. Drawn through each member's art.
#[test]
fn a_groups_transform_moves_its_members_fills_shadows_beside_their_own_transform() {
let scaled = || transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true}));
// Halved and turned 90° counterclockwise on screen, (10, 10) goes to (5, -5); doubled first by
// the fill's own Transform effect, it goes to (10, -10).
let cases = [(91, vec![scaled(), shadow(10.0, 10.0, 0.0)], (5.0, -5.0)), (92, vec![shadow(10.0, 10.0, 0.0), scaled()], (10.0, -10.0))];
for strokes in [false, true] {
let members = cases.iter().map(|(id, effects, _)| fill_square(*id, effects.clone())).collect();
let g = group(90, members, vec![transform(json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes}))]);
let art = crate::evaluate_container(None, &g).unwrap();
for (id, _, want) in &cases {
let member = node_in(&art, *id);
let drawn = shadows_in(&crate::reshape(None, &member, None).unwrap());
assert!(!drawn.is_empty() && near(&drawn, &vec![*want; drawn.len()]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}");
}
}
}
+21 -3
View File
@@ -6,20 +6,38 @@
use std::sync::Arc;
use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_geom::{Point, Rect, Shape};
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
/// The largest distance between the edges of `a` and `b`.
fn off(a: Rect, b: Rect) -> f64 {
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()))
}
/// "Type" at 48 pt in a face the test adds, so its glyphs draw on a machine without craft-fonts or
/// system fonts.
fn type_in_test_face() -> TextObject {
assert!(vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()) > 0, "the test face loads");
TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { font_family: HEIGHT_FAMILY.into(), size: 48.0, ..Default::default() })
}
/// The box of the outlines `t`'s glyphs draw, in document space, measured glyph by glyph.
fn outline_box(t: &TextObject) -> Rect {
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let outlines: Vec<Rect> = laid.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| (t.xf * &g.outline).bounding_box()).collect();
assert_eq!(outlines.len(), 4, "every glyph of \"Type\" draws an outline");
outlines.into_iter().reduce(|a, b| a.union(b)).unwrap()
}
#[test]
fn live_evaluation_measures_type_in_envelopes_by_its_glyphs() {
let t = TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { size: 48.0, ..Default::default() });
let t = type_in_test_face();
let n = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
let laid = n.geometric_bounds().unwrap();
let ink = t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap());
let ink = outline_box(&t);
assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}");
let measured = vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap();
assert!(off(measured, ink) < 1e-6, "the envelope measure gives the glyphs' box: {measured:?} vs {ink:?}");
let before = vectorcraft_doc::live::envelope_content_bounds(std::slice::from_ref(&n)).unwrap();
assert!(off(before, laid) < 1e-6, "with nothing registered, type keeps its laid-out box: {before:?} vs {laid:?}");
+12 -1
View File
@@ -4,6 +4,8 @@ pub mod actionset;
mod addons;
mod apiref;
pub(crate) mod appearance;
pub mod arrowheads;
mod artboardalign;
mod assets;
mod attributes;
pub mod brushlib;
@@ -105,6 +107,7 @@ mod variablecmds;
pub(crate) mod views;
pub mod wand;
pub mod webexport;
mod wireframe;
mod xform;
use serde::Serialize;
@@ -297,6 +300,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
// Split out of `paint` (M3.8); kept next to it so lists in registry order (the command
// palette, `engine.commands`) show them where they always were.
v.extend(stroke::specs());
v.extend(arrowheads::specs());
v.extend(appearance::specs());
v.extend(style::specs());
v.extend(swatch::specs());
@@ -308,6 +312,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(draw2::specs());
v.extend(xform::specs());
v.extend(effectcmd::specs());
v.extend(wireframe::specs());
v.extend(pathops::specs());
v.extend(compoundshape::specs());
v.extend(typecmd::specs());
@@ -334,6 +339,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(variablecmds::specs());
v.extend(docinfo::specs());
v.extend(panelcmds::specs());
v.extend(artboardalign::specs());
v.extend(buildcmds::specs());
v.extend(shaper::specs());
v.extend(brushsym::specs());
@@ -420,8 +426,13 @@ pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
pub(crate) fn f64_or(p: &Value, key: &str, default: f64) -> f64 {
p.get(key).and_then(Value::as_f64).unwrap_or(default)
}
/// The number `p` gives for `key`. A missing key or null is "missing number `{key}`"; any other
/// value, such as `"40"`, is "`{key}` must be a number, not {v}", as [`number_or`] words it.
pub(crate) fn f64_req(p: &Value, key: &str, cmd: &str) -> Result<f64> {
p.get(key).and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("missing number `{key}`")))
match p.get(key) {
None | Some(Value::Null) => Err(bad(cmd, format!("missing number `{key}`"))),
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
}
}
/// The number `p` gives for `key`, or `default` when `p` leaves it out or gives null. Any other
/// value, such as `"40"`, is an error: "`{key}` must be a number, not {v}".
+6 -5
View File
@@ -12,7 +12,7 @@ use vectorcraft_doc::{CharStyle, Document, Justify, Node, NodeId, NodeKind, Para
use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit};
use crate::cmd::fonts::{edit_symbol_texts, symbol_texts};
use crate::cmd::fonts::{art_texts_of, edit_art_texts_of};
use crate::cmd::textedit::{editing_range, editing_story};
use crate::cmd::typecmd::refresh_bounds;
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Missing Fonts…",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in the art of its symbols included) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in its opacity masks and in the art of its symbols and patterns included, hidden or locked type and disabled masks too) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
has_doc,
replace_fonts
),
@@ -982,8 +982,9 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
}
});
}
// The type in the symbols' art too, which exports name when its font is missing.
if ids.is_empty() && !symbol_texts(d, None).into_iter().any(|(t, _)| lacks(t)) {
// The type in opacity masks and in the art of symbols and patterns too, hidden or locked type
// included, which exports name when its font is missing.
if ids.is_empty() && !art_texts_of(d).into_iter().any(|(_, t, _)| lacks(t)) {
return Err(EngineError::Other("No fonts are missing".into()));
}
let runs = s.edit("Replace Missing Fonts", |d, _| {
@@ -1008,7 +1009,7 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
replace(t);
}
}
edit_symbol_texts(d, None, &|t, _| lacks(t), &mut replace);
edit_art_texts_of(d, &lacks, &mut replace);
Ok(runs)
})?;
Ok(json!({ "runs": runs, "font": family }))
@@ -415,3 +415,53 @@ fn replace_missing_fonts_reaches_the_type_in_symbols() {
s.execute("symbol.exitEditing", &json!({})).unwrap();
assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None);
}
/// Replace Missing Fonts reaches the type in opacity masks (of a hidden object, disabled, in a
/// symbol's art) and in a pattern swatch nothing paints with, and the export warning, the missing
/// fonts list and Find Font name that type's font until it is replaced.
#[test]
fn replace_missing_fonts_reaches_the_type_in_masks_and_patterns() {
let mut s = session();
let mask = |s: &mut Session, owner: NodeId, art: NodeId| {
s.edit("Mask", |d, _| {
let art = d.remove(art)?;
d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
Ok(())
})
.unwrap();
};
let lost = |s: &mut Session| text(s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family"}));
let rect =
|s: &mut Session| NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap());
let (hidden, disabled, in_symbol) = (rect(&mut s), rect(&mut s), rect(&mut s));
for owner in [hidden, disabled, in_symbol] {
let t = lost(&mut s);
mask(&mut s, owner, t);
}
s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap();
s.execute("object.hide", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [disabled.0]})).unwrap();
s.execute("transparency.disableOpacityMask", &json!({})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap();
let t = lost(&mut s);
s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap();
select(&mut s, &[t]);
s.execute("edit.clear", &json!({})).unwrap();
let mut on_layers = 0;
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
assert_eq!(on_layers, 0, "the type is only in masks, a symbol and a pattern");
let missing = |s: &Session| crate::cmd::fontfiles::missing_fonts(&s.doc().unwrap().doc).into_iter().map(|f| f.family).collect::<Vec<_>>();
assert_eq!(missing(&s), ["No Such Font Family"]);
assert!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc).is_some_and(|w| w.contains("No Such Font Family")));
let listed = s.execute("text.fonts", &json!({})).unwrap();
assert_eq!((listed[0]["family"].as_str(), listed[0]["objects"].as_u64()), (Some("No Such Font Family"), Some(4)), "{listed}");
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap();
assert_eq!(r["runs"].as_u64(), Some(4), "{r}");
assert_eq!(steps(&s), before + 1);
assert!(missing(&s).is_empty());
assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None);
assert_eq!(other(s.execute("addon.cleanup.replaceFonts", &json!({}))), "No fonts are missing");
assert_eq!(steps(&s), before + 1);
}
+1 -1
View File
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Weed Box and Lines…",
["Object", "Plug-ins", "Cutting Tools"],
None,
"{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt (instead of count: as few lines as keep them at most this far apart), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}",
"{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt more than 0 and at most 100000 (instead of count, never with it: as few lines as keep them at most this far apart, up to 1000 each way), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}",
has_selection,
weed
)]
@@ -723,12 +723,13 @@ pub(super) fn lines(region: &Region, outline: &[Segment], frame: Rect, n: Counts
continue;
}
// The lines (0-based) each outline segment comes within `gap` of: lines k (1-based) lie at
// v0 + k·step.
// v0 + k·step. The range is widened by a small tolerance so that a line whose position
// rounds just past a segment's end is still measured; `near` drops lines the segment misses.
let reach = |&(a, b): &Segment| {
let (va, vb) = (uv(a, vertical).1, uv(b, vertical).1);
let (lo, hi) = (va.min(vb) - gap, va.max(vb) + gap);
let first = ((lo - v0) / step).ceil().max(1.0);
let last = ((hi - v0) / step).floor().min(count as f64);
let first = ((lo - v0) / step - 1e-9).ceil().max(1.0);
let last = ((hi - v0) / step + 1e-9).floor().min(count as f64);
if step > 0.0 && first <= last { (first as usize - 1)..(last as usize) } else { 0..0 }
};
// The outlines near each line, found once for all of them, by index into `outline`.
@@ -541,6 +541,24 @@ fn indexed_crossings_find_the_same_stretches() {
}
}
/// An outline that lies on a weeding line stops it even when the line's position rounds just past
/// the outline's: the one line across 0.1 to 0.5 lies at 0.1 + 0.2, which is 0.30000000000000004,
/// and (0.30000000000000004 - 0.1) / 0.2 is 1.0000000000000002.
#[test]
fn an_outline_on_a_rounded_line_position_stops_the_line() {
let doc = vectorcraft_doc::Document::new(800.0, 600.0);
let c = 0.1 + 0.2;
let mut p = BezPath::new();
p.move_to((20.0, c));
p.line_to((80.0, c));
let n = Node::path(NodeId(1), PathData::from_bezpath(&p), Appearance::default());
let region = super::geometry::Reader::new(&doc).read(&[&n]).unwrap().unwrap();
let outline = region.outline().unwrap();
let counts = super::geometry::Counts { horizontal: 1, vertical: 0 };
let pieces = super::geometry::lines(&region, &outline, Rect::new(0.0, 0.1, 100.0, 0.5), counts, 0.0, 100).unwrap();
assert_eq!(pieces, [(Point::new(0.0, c), Point::new(20.0, c)), (Point::new(80.0, c), Point::new(100.0, c))]);
}
#[test]
fn art_nested_too_deep_is_refused() {
// A rectangle inside `levels` groups, each holding the next. A document keeps none this deep,
+453
View File
@@ -0,0 +1,453 @@
//! Custom arrowheads (Stroke panel menu › Edit Arrowheads…). The arrowheads file is a native
//! document kept next to the preferences ([`Session::attach_arrowheads_file`]). Each of its symbols
//! is one arrowhead, listed by the symbol's name after the built-in heads in the Stroke panel's
//! arrowhead menus. A head points right (+x): the symbol's registration point is its tip, and the
//! art's height (its extent across the line) is drawn as wide as the built-in heads, four times
//! the head's weight. A head covers what its art paints: the visible fills, and the visible
//! strokes outlined, of the paths, compound paths and groups in it, and its gradient meshes, with
//! their geometry effects applied and clip groups clipped. A head is one solid shape in the stroke's paint: art at 0 %
//! opacity is left out, and other opacities, blend modes and opacity masks do not change the
//! shape. Saving the file reloads the heads. A stroke that uses a custom head carries a copy of its art
//! ([`vectorcraft_doc::CustomArrowhead`]), so its document draws it anywhere.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, CustomArrowhead, Document, Node, NodeId, NodeKind, Symbol, SymbolRegistration};
use vectorcraft_geom::{Affine, FillRule, PathData, Point, SubPath};
use vectorcraft_pathops::BoolOp;
use super::{CommandSpec, Result, Session, always, bad, cmd};
/// The arrowheads file's name, in the folder of the preferences.
pub const FILE_NAME: &str = "Arrowheads.vectorcraft";
/// The largest arrowheads file read, and the most its document or its images may unpack to when
/// compressed.
pub const MAX_FILE_BYTES: u64 = 64 << 20;
/// The most heads read from the file; symbols past it are skipped.
pub const MAX_HEADS: usize = 256;
/// The most anchors a symbol's art, and the shapes it paints, may have; a symbol past it is skipped.
pub const MAX_ART_ANCHORS: usize = 16 * CustomArrowhead::MAX_ANCHORS;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "stroke.arrowheads.list",
"Arrowheads",
[],
None,
"{} → {arrowheads: [{name (stroke.set `startArrow`/`endArrow` as {custom: name}), reach, halfWidth (in head weights)}], file: the arrowheads file's path or null (no file here, as on the web), skipped: [{name, reason}] symbols of the file that are not heads, error: why the file could not be read, or null} the custom arrowheads, listed after the built-in ones in the Stroke panel's arrowhead menus",
always,
list
),
cmd!(
"stroke.arrowheads.edit",
"Edit Arrowheads",
[],
None,
"{} open the arrowheads file (a native document next to the preferences; created first with one example head when it is missing). Each symbol in it is one custom arrowhead named after the symbol: it points right, its registration point is the tip, and its height is drawn as wide as the built-in heads; its visible fills and outlined strokes make the head. Saving the file reloads the heads → {path, created: whether the file was made now}",
has_file,
edit
),
cmd!(
"stroke.arrowheads.reload",
"Reload Arrowheads",
[],
None,
"{} read the arrowheads file again (a save of it from VectorCraft does this already) → {count, skipped: [{name, reason}]}",
has_file,
reload
),
]
}
/// The custom arrowheads read from the arrowheads file.
#[derive(Default)]
pub struct Arrowheads {
path: Option<String>,
heads: Vec<Arc<CustomArrowhead>>,
skipped: Vec<(String, String)>,
error: Option<String>,
}
impl Arrowheads {
/// The arrowheads file's path; `None` without one (the web, runs without preferences).
pub fn path(&self) -> Option<&str> {
self.path.as_deref()
}
/// The heads, in the order of the file's symbols.
pub fn heads(&self) -> &[Arc<CustomArrowhead>] {
&self.heads
}
/// Head `name`.
pub fn get(&self, name: &str) -> Option<Arc<CustomArrowhead>> {
self.heads.iter().find(|h| h.name == name).cloned()
}
fn set(&mut self, read: Read) {
(self.heads, self.skipped) = (read.heads.into_iter().map(Arc::new).collect(), read.skipped);
self.error = None;
}
}
/// The heads a document holds, and the symbols that are not heads with the reason.
#[derive(Debug, Default)]
pub struct Read {
pub heads: Vec<CustomArrowhead>,
pub skipped: Vec<(String, String)>,
}
/// The heads of document `doc`: one per symbol, up to [`MAX_HEADS`] (see the module docs).
pub fn heads_of(doc: &Document) -> Read {
let mut d = doc.clone();
let brushes = vectorcraft_brush::library(&d);
let mut out = Read::default();
for (i, sym) in doc.symbols.iter().enumerate() {
if i >= MAX_HEADS {
out.skipped.push((sym.name.clone(), format!("only the first {MAX_HEADS} symbols are read")));
continue;
}
if out.heads.iter().any(|h| h.name == sym.name) {
out.skipped.push((sym.name.clone(), "another symbol has this name".into()));
continue;
}
match head(&mut d, &brushes, sym) {
Ok(h) => out.heads.push(h),
Err(why) => out.skipped.push((sym.name.clone(), why.into())),
}
}
out
}
/// Symbol `sym` of `d` as a head.
fn head(d: &mut Document, brushes: &[vectorcraft_brush::Brush], sym: &Symbol) -> std::result::Result<CustomArrowhead, &'static str> {
const TOO_DETAILED: &str = "its art is too long or too detailed for a head";
const UNITED: &str = "its shapes could not be combined into one";
if art_anchors(&sym.art) > MAX_ART_ANCHORS {
return Err(TOO_DETAILED);
}
let art = baked_art(d, sym);
let mut shapes = Shapes::default();
painted(d, brushes, &art, &mut shapes);
if shapes.too_detailed {
return Err(TOO_DETAILED);
}
if shapes.failed {
return Err(UNITED);
}
let area = shapes.united().ok_or(UNITED)?;
let b = area.bounds().filter(|b| b.height() > 1e-9 && b.is_finite()).ok_or("its art paints nothing")?;
let tip = b.center() + d.symbol_registration(&sym.name).offset_from_center(b.width(), b.height());
// Head units: x back from the tip, y across to the right of +x, 4 units to the art's height.
let k = 4.0 / b.height();
let local = Affine::new([-k, 0.0, 0.0, k, k * tip.x, -k * tip.y]);
let h = CustomArrowhead::new(sym.name.clone(), area.transformed(local));
if h.path.subpaths.is_empty() {
return Err(TOO_DETAILED);
}
Ok(h)
}
/// The anchors of the paths in `n` and of the pieces of its gradient meshes ([`mesh_anchors`]), its
/// members' included.
fn art_anchors(n: &Node) -> usize {
let own = match &n.kind {
NodeKind::Mesh(m) => mesh_anchors(m),
_ => n.path_data().map_or(0, PathData::anchor_count),
};
n.children().map_or(own, |c| c.iter().fold(own, |sum, c| sum.saturating_add(art_anchors(c))))
}
/// The art of symbol `sym` of `d` with every geometry effect in it applied (its objects', fills',
/// strokes' and groups'), as the canvas draws it: the art baked as for export, on a copy of `d`.
fn baked_art(d: &Document, sym: &Symbol) -> Node {
// A plain new layer, so the file's own layers' effects stay out of the art.
let mut tmp = d.clone();
tmp.layers = Document::new(1.0, 1.0).layers;
let Some(children) = tmp.layers.first_mut().and_then(|l| Arc::make_mut(l).children_mut()) else { return (*sym.art).clone() };
*children = vec![sym.art.clone()];
let baked = vectorcraft_render::effects::bake_document(&tmp);
baked.as_ref().and_then(|b| b.layers.first()?.children()?.first().map(|c| (**c).clone())).unwrap_or_else(|| (*sym.art).clone())
}
/// The shapes a symbol's art paints, up to [`MAX_ART_ANCHORS`] anchors in all.
#[derive(Default)]
struct Shapes {
list: Vec<(PathData, FillRule)>,
anchors: usize,
/// More anchors were asked for than fit; the shapes past the limit were not made.
too_detailed: bool,
/// A clip group's art could not be combined or clipped, so a shape it paints is missing.
failed: bool,
}
impl Shapes {
/// Whether `anchors` more fit; when they do not, the shapes are too detailed.
fn room(&mut self, anchors: usize) -> bool {
self.too_detailed |= self.anchors.saturating_add(anchors) > MAX_ART_ANCHORS;
!self.too_detailed
}
fn push(&mut self, shape: (PathData, FillRule)) {
if self.room(shape.0.anchor_count()) {
self.anchors += shape.0.anchor_count();
self.list.push(shape);
}
}
/// The shapes united, or `None` when one of them could not be (the union would miss it).
fn united(&self) -> Option<PathData> {
let refs: Vec<(&PathData, FillRule)> = self.list.iter().map(|(p, r)| (p, *r)).collect();
vectorcraft_pathops::try_unite_all(&refs).ok()
}
/// The shapes of `inside` clipped to `outline` (filled under `rule`), added as one.
fn push_clipped(&mut self, inside: Shapes, outline: &PathData, rule: FillRule) {
if inside.too_detailed || !self.room(inside.anchors) {
self.too_detailed = true;
return;
}
self.failed |= inside.failed;
let clip = |art: PathData| {
vectorcraft_pathops::try_boolean(&art, FillRule::NonZero, outline, rule, BoolOp::Intersect, vectorcraft_pathops::DEFAULT_PRECISION).ok()
};
let Some(clipped) = inside.united().and_then(clip) else {
self.failed = true;
return;
};
if !clipped.subpaths.is_empty() {
self.push((clipped, FillRule::NonZero));
}
}
}
/// The shapes the shown paths and compound paths in `n` (baked art) paint: their filled areas and
/// their strokes' outlines, its groups' members included (baking has already made a group's own
/// fills and strokes art among its members), and the areas its gradient meshes cover. A clip
/// group's clipped art is clipped to
/// its clipping path, whose own fill and stroke paint unclipped, as on the canvas; a group used as
/// the clipping path paints nothing ([`clip_paint`]). Hidden or fully
/// transparent art is left out.
fn painted(d: &mut Document, brushes: &[vectorcraft_brush::Brush], n: &Node, out: &mut Shapes) {
if !n.visible || n.opacity <= 0.0 || out.too_detailed {
return;
}
match &n.kind {
NodeKind::Path { guide: true, .. } => {}
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
fills(n, out);
// The outline holds a copy of the path for each fill too, which adds nothing new.
if let Some(o) = super::pathops::outline_strokes(d, brushes, n) {
fills_in(&o, out);
}
}
NodeKind::Group { children, clip: true } => {
let Some((clip, rest)) = children.split_first() else { return };
clip_paint(clip).iter().for_each(|part| painted(d, brushes, part, out));
// Nothing to clip by hides the clipped art, as on the canvas.
let Some((outline, rule)) = vectorcraft_render::effects::clip_outline(clip) else { return };
let mut inside = Shapes { anchors: out.anchors, ..Default::default() };
rest.iter().for_each(|c| painted(d, brushes, c, &mut inside));
inside.anchors -= out.anchors;
out.push_clipped(inside, &PathData::from_bezpath(&outline), rule);
}
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| painted(d, brushes, c, out)),
NodeKind::Mesh(_) => mesh_area(n, out),
_ => {}
}
}
/// What clipping path `clip` paints ([`Node::clip_paint`]): its fills and its strokes, each as a
/// copy of it keeping only those. A group or another object that does not paint as a clipping
/// path gives neither.
fn clip_paint(clip: &Node) -> Vec<Node> {
let paint = clip.clip_paint();
[paint.fill, paint.stroke].into_iter().flatten().collect()
}
/// The areas the shown paths and gradient meshes in `n` (an outlined stroke) fill, clipped by its
/// clip groups, whose clipping paths' own fills paint unclipped. A stroke with a gradient along or
/// across it is outlined as gradient meshes clipped to the stroke's outline.
fn fills_in(n: &Node, out: &mut Shapes) {
if !n.visible || n.opacity <= 0.0 || out.too_detailed {
return;
}
match &n.kind {
NodeKind::Mesh(_) => mesh_area(n, out),
NodeKind::Group { children, clip: true } => {
let Some((clip, rest)) = children.split_first() else { return };
clip_paint(clip).iter().for_each(|part| fills_in(part, out));
let Some((outline, rule)) = vectorcraft_render::effects::clip_outline(clip) else { return };
let mut inside = Shapes { anchors: out.anchors, ..Default::default() };
rest.iter().for_each(|c| fills_in(c, &mut inside));
inside.anchors -= out.anchors;
out.push_clipped(inside, &PathData::from_bezpath(&outline), rule);
}
_ => match n.children() {
Some(children) => children.iter().for_each(|c| fills_in(c, out)),
None => fills(n, out),
},
}
}
/// The anchors [`mesh_area`] makes at most of mesh `m`: its outline's, one a patch along each side,
/// when no point of it is fully transparent, else four by four quads of four anchors a patch.
fn mesh_anchors(m: &vectorcraft_doc::GradientMesh) -> usize {
let (rows, cols) = (m.rows as usize, m.cols as usize);
if opaque(m) { rows.saturating_add(cols).saturating_mul(2) } else { rows.saturating_mul(cols).saturating_mul(64) }
}
fn opaque(m: &vectorcraft_doc::GradientMesh) -> bool {
m.points.iter().all(|p| p.opacity > 0.0)
}
/// The area gradient mesh `n` paints: its outline when no point of it is fully transparent, else
/// the pieces of it that are not fully transparent (four by four quads a patch). A mesh whose
/// pieces do not fit in `out` makes the shapes too detailed.
fn mesh_area(n: &Node, out: &mut Shapes) {
let NodeKind::Mesh(m) = &n.kind else { return };
if !out.room(mesh_anchors(m)) {
return;
}
if opaque(m) {
let outline = m.outline();
if !outline.subpaths.is_empty() {
out.push((outline, FillRule::NonZero));
}
return;
}
for q in m.quads(4) {
if q.opacity > 0.0 || q.corners.iter().any(|(_, o)| *o > 0.0) {
out.push((PathData::single(SubPath::polyline(&q.pts, true)), FillRule::NonZero));
}
}
}
/// The area path `n` fills, when a shown fill paints it.
fn fills(n: &Node, out: &mut Shapes) {
let paints = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(f) if f.visible && f.opacity > 0.0 && !f.paint.is_none());
if n.appearance.items.iter().any(paints)
&& let Some(shape) = super::pathops::node_path(n)
{
out.push(shape);
}
}
/// The document a missing arrowheads file starts as: one example head, a solid triangle.
pub fn starter() -> Document {
let mut doc = Document::new(612.0, 792.0);
doc.title = "Arrowheads".into();
let name = "Example Arrowhead";
let tri = SubPath::polyline(&[Point::new(-10.0, -8.0), Point::new(10.0, 0.0), Point::new(-10.0, 8.0)], true);
let art = Node::path(NodeId(0), PathData::single(tri), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0));
let art = doc.reid(&art);
doc.symbols.push(Symbol { name: name.into(), art: Arc::new(art), dynamic: false });
// The tip is the right edge's middle.
doc.set_symbol_registration(name, SymbolRegistration(5));
let id = doc.alloc_id();
let instance = Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::translate((306.0, 396.0)) });
let layer = doc.layers.first().map(|l| l.id);
let _ = doc.insert(layer, 0, instance);
doc
}
impl Session {
/// Keep the custom arrowheads in the file at `path` and read the heads it holds (none while it
/// is missing; an unreadable file is reported by `stroke.arrowheads.list`).
pub fn attach_arrowheads_file(&mut self, path: String) {
self.arrowheads.path = Some(path);
self.reload_arrowheads();
}
/// Read the arrowheads file again.
fn reload_arrowheads(&mut self) {
let Some(path) = self.arrowheads.path.clone() else { return };
match read(&path) {
Ok(Some(doc)) => self.arrowheads.set(heads_of(&doc)),
Ok(None) => self.arrowheads.set(Read::default()),
Err(e) => {
self.arrowheads.set(Read::default());
self.arrowheads.error = Some(e);
}
}
}
/// A document was saved to `path`: when that is the arrowheads file, its heads are read back
/// from what was written.
pub(crate) fn arrowheads_saved(&mut self, path: &str) {
if self.arrowheads.path.as_deref().is_some_and(|a| same_file(a, path)) {
self.reload_arrowheads();
}
}
}
fn same_file(a: &str, b: &str) -> bool {
let canon = |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| std::path::PathBuf::from(p));
std::path::Path::new(a) == std::path::Path::new(b) || canon(a) == canon(b)
}
/// The document in the arrowheads file at `path`; `None` when there is no file.
fn read(path: &str) -> std::result::Result<Option<Document>, String> {
let size = match std::fs::metadata(path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(format!("{path}: {e}")),
Ok(m) if !m.is_file() => return Err(format!("{path}: not a file")),
Ok(m) => m.len(),
};
if size > MAX_FILE_BYTES {
return Err(format!("{path}: larger than {} MB", MAX_FILE_BYTES >> 20));
}
let bytes = crate::file_access::unconfined(|| super::fileio::read_file(path)).map_err(|e| e.to_string())?;
// A compressed file's document, and its images, may unpack to no more than an uncompressed
// file may hold.
let parse = || vectorcraft_format::load_file_capped(&bytes, MAX_FILE_BYTES).map(|f| f.doc).map_err(|e| format!("{path}: {e}"));
crate::guard::catch_panic(parse).map_err(|_| format!("{path}: could not be read"))?.map(Some)
}
fn has_file(s: &Session) -> std::result::Result<(), String> {
if s.arrowheads.path.is_some() { Ok(()) } else { Err("no arrowheads file here".into()) }
}
fn skipped(s: &Session) -> Vec<Value> {
s.arrowheads.skipped.iter().map(|(name, reason)| json!({"name": name, "reason": reason})).collect()
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let heads: Vec<Value> = s.arrowheads.heads.iter().map(|h| json!({"name": h.name, "reach": h.reach(), "halfWidth": h.half_width()})).collect();
Ok(json!({"arrowheads": heads, "file": s.arrowheads.path, "skipped": skipped(s), "error": s.arrowheads.error}))
}
fn reload(s: &mut Session, _: &Value) -> Result<Value> {
const C: &str = "stroke.arrowheads.reload";
s.reload_arrowheads();
if let Some(e) = &s.arrowheads.error {
return Err(bad(C, e.clone()));
}
Ok(json!({"count": s.arrowheads.heads.len(), "skipped": skipped(s)}))
}
fn edit(s: &mut Session, _: &Value) -> Result<Value> {
const C: &str = "stroke.arrowheads.edit";
let path = s.arrowheads.path.clone().ok_or_else(|| bad(C, "no arrowheads file here"))?;
if let Some(dir) = std::path::Path::new(&path).parent() {
std::fs::create_dir_all(dir).map_err(|e| bad(C, format!("{}: {e}", dir.display())))?;
}
// Made only when no file is there, also when another run makes one at the same moment.
let bytes = vectorcraft_format::save_file(&starter());
let created = match crate::file_access::unconfined(|| super::fileio::write_new_file(&path, &bytes)) {
Ok(()) => true,
Err(_) if std::path::Path::new(&path).exists() => false,
Err(e) => return Err(bad(C, e.to_string())),
};
if created {
s.reload_arrowheads();
}
// Already open: that document comes to the front.
let open = s.documents().iter().position(|st| st.path.as_deref().is_some_and(|p| same_file(p, &path)));
match open {
Some(i) => {
s.set_active(i);
}
None => {
crate::file_access::unconfined(|| s.execute("document.open", &json!({ "path": path })))?;
}
}
Ok(json!({"path": path, "created": created}))
}
+271
View File
@@ -0,0 +1,271 @@
//! Align and Distribute for artboards: what the Align panel's buttons run while the Artboard tool
//! is chosen.
use serde_json::{Value, json};
use vectorcraft_doc::Scaling;
use vectorcraft_geom::{Rect, Vec2};
use super::object::choice;
use super::panelcmds::{artboard_index, artboards_art, locked_and_hidden, named_or_selected, note_artboards};
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, switch_or};
use crate::EngineError;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"artboard.align",
"Align",
[],
None,
"{index? | indices?: [n…], selectedArtboards?: [n…] (as artboard.duplicate; default: the artboards the Artboard tool has selected, else its active one), horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\" (one of the two is needed), to?: \"selection\"|\"artboard\" (default \"selection\": the bounds of the artboards together; \"artboard\": artboard `artboard`, which stays where it is), artboard?: n (0-based; the artboard to align to with to: \"artboard\"; default: the Artboard tool's active one; it need not be one of the artboards aligned), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it), moveArt?: bool (the art fully inside each artboard moves with it, art inside two of them with the first by index, which may stay; default: the Artboard tool's Move Artwork with Artboard option), patterns?: bool, lockedAndHidden?: bool (as artboard.move)} (Align panel › Align Objects with the Artboard tool chosen) each artboard moves until its edge or center is on that edge or center of what it aligns to, with its guides, in one undo step; a locked artboard stays where it is and still counts in the bounds, and the call fails with `the artboard is locked` when every artboard it names is locked; when no artboard moves, no undo step is recorded → {moved: [index…]}",
has_doc,
align
),
cmd!(
"artboard.distribute",
"Distribute",
[],
None,
"{index? | indices?, selectedArtboards? (as artboard.align), horizontal?: \"left\"|\"center\"|\"right\" | vertical?: \"top\"|\"center\"|\"bottom\" (one is needed; horizontal goes first), to?: \"selection\"|\"artboard\", artboard?: n, activeArtboard?: n (as artboard.align; with `spacing` the artboard must be one of those distributed), spacing?: pt (used with to: \"artboard\"), moveArt?, patterns?, lockedAndHidden? (as artboard.align)} (Align panel › Distribute Objects with the Artboard tool chosen) the named edges or centers of the artboards are spaced evenly between the first and the last along the axis, which stay where they are (three or more artboards); with to: \"artboard\", the artboards are spaced the same way and then moved together so that artboard `artboard`, when it is one of them, stays where it is; with to: \"artboard\" and `spacing`, that artboard stays and the edges or centers are placed `spacing` apart, outward from it in their order (two or more); a locked artboard stays where it is and keeps its place in the order, and the call fails with `the artboard is locked` when every artboard it names is locked; a spacing that would move an artboard past the canvas is an error; with fewer artboards, or when none moves, no undo step is recorded → {moved: [index…]}",
has_doc,
distribute
),
cmd!(
"artboard.distributeSpacing",
"Distribute Spacing",
[],
None,
"{index? | indices?, selectedArtboards? (as artboard.align), axis?: \"horizontal\"|\"vertical\" (default horizontal), to?: \"selection\"|\"artboard\", artboard?: n, activeArtboard?: n (as artboard.distribute), spacing?: pt (used with to: \"artboard\"), moveArt?, patterns?, lockedAndHidden? (as artboard.align)} (Align panel › Distribute Spacing with the Artboard tool chosen) the gaps between the artboards along the axis become equal, the first and the last staying where they are (three or more artboards); with to: \"artboard\", the gaps become equal the same way and the artboards then move together so that artboard `artboard`, when it is one of them, stays where it is; with to: \"artboard\" and `spacing`, that artboard stays and the others are placed with a gap of `spacing` between neighbors (two or more; a negative spacing overlaps them); a locked artboard stays where it is and keeps its place in the order, and the call fails with `the artboard is locked` when every artboard it names is locked; a spacing that would move an artboard past the canvas is an error; with fewer artboards, or when none moves, no undo step is recorded → {moved: [index…]}",
has_doc,
distribute_spacing
),
]
}
/// What an artboard Align or Distribute command acts on, read from its params.
struct Boards {
/// The artboards named, in artboard order, each with its rectangle.
items: Vec<(usize, Rect)>,
/// With `to: "artboard"`, the artboard to align to and its rectangle.
reference: Option<(usize, Rect)>,
/// Whether the art inside each artboard moves with it.
move_art: bool,
/// Whether locked and hidden art moves too.
locked_art: bool,
}
/// Reads the params that `artboard.align`, `artboard.distribute` and `artboard.distributeSpacing`
/// (command `cmd`) share, and adds the artboards and the art choice to the journal entry. The
/// artboard to align to is `artboard`, else `activeArtboard` (a replay of the journal), else the
/// Artboard tool's active one, which the journal entry then records as `activeArtboard`. It fails
/// when every artboard named is locked.
fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result<Boards> {
check_switches(p, &["patterns"], cmd)?;
let to_artboard = choice(p, cmd, "to", &["selection", "artboard"])? == Some("artboard");
let indices = named_or_selected(s, p, cmd)?;
let given = |key: &str| -> Result<Option<usize>> {
match p.get(key).filter(|v| !v.is_null()) {
Some(v) => artboard_index(&s.doc()?.doc, &json!({ "index": v }), cmd).map(Some),
None => Ok(None),
}
};
let (named, recorded) = (given("artboard")?, given("activeArtboard")?);
let move_art = switch_or(p, "moveArt", s.tool_options_of("artboard")["moveArt"].as_bool().unwrap_or(true), cmd)?;
let locked_art = locked_and_hidden(s, p, move_art, cmd)?;
note_artboards(s, p, &indices);
s.note_journal("moveArt", json!(move_art));
let reference = match (to_artboard, named.or(recorded)) {
(false, _) => None,
(true, Some(i)) => Some(i),
(true, None) => {
let active = s.tool_options_of("artboard")["active"].clone();
Some(artboard_index(&s.doc()?.doc, &json!({ "index": active }), cmd)?)
}
};
if let Some(i) = reference.filter(|_| named.is_none()) {
s.note_journal("activeArtboard", json!(i));
}
let d = &s.doc()?.doc;
let rect = |i: usize| d.artboards.get(i).map(|a| (i, a.rect)).ok_or_else(|| EngineError::Other("no such artboard".into()));
let items = indices.iter().map(|i| rect(*i)).collect::<Result<Vec<_>>>()?;
if indices.iter().all(|i| d.artboards.get(*i).is_some_and(|a| a.locked)) {
return Err(EngineError::Other("the artboard is locked".into()));
}
Ok(Boards { items, reference: reference.map(rect).transpose()?, move_art, locked_art })
}
/// `spacing` of the Distribute commands: a finite number, or `None` when it is missing or null.
fn spacing(p: &Value, cmd: &str) -> Result<Option<f64>> {
p.get("spacing")
.filter(|v| !v.is_null())
.map(|v| v.as_f64().filter(|g| g.is_finite()).ok_or_else(|| bad(cmd, "`spacing` must be a number")))
.transpose()
}
/// The place in `items` of the artboard `b` aligns to, which the Distribute commands keep where it
/// is. `None` without one, or when it is not one of `items`; with a `gap` that is an error
/// (`no such artboard`), since the gap is measured from it.
fn kept(b: &Boards, items: &[(usize, Rect)], gap: Option<f64>) -> Result<Option<usize>> {
let Some((reference, _)) = b.reference else { return Ok(None) };
match items.iter().position(|(i, _)| *i == reference) {
None if gap.is_some() => Err(EngineError::Other("no such artboard".into())),
at => Ok(at),
}
}
/// Moves each artboard of `moves` by its offset as undo step `label`, with its guides and, when
/// `b` says so, the art inside it; art inside two of the artboards `b` names goes with the one
/// first in artboard order, and stays when that one stays. Locked artboards stay where they are.
/// When no artboard moves
/// more than 1e-9 pt on either axis, the document and its undo history stay as they are. The edit
/// fails with nothing changed when an artboard would end up past the canvas, as every edit does.
fn apply(s: &mut Session, label: &str, p: &Value, b: &Boards, moves: &[(usize, Vec2)]) -> Result<Value> {
let d = &s.doc()?.doc;
let mut moves: Vec<(usize, Vec2)> =
moves.iter().copied().filter(|(i, dv)| (dv.x.abs() > 1e-9 || dv.y.abs() > 1e-9) && d.artboards.get(*i).is_some_and(|a| !a.locked)).collect();
// In artboard order, as the other artboard edits take them, whatever order the Distribute
// commands spaced them in.
moves.sort_by_key(|(i, _)| *i);
let moved: Vec<usize> = moves.iter().map(|(i, _)| *i).collect();
if moves.is_empty() {
return Ok(json!({ "moved": moved }));
}
// The art of every artboard named, those that stay included, so that art on overlapping
// artboards goes with the first by index; then that of the artboards that move.
let named: Vec<usize> = b.items.iter().map(|(i, _)| *i).collect();
let arts: Vec<(usize, Vec<NodeId>)> =
artboards_art(s, &named, b.move_art, b.locked_art, true)?.into_iter().filter(|(i, _)| moved.contains(i)).collect();
let ids: Vec<NodeId> = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect();
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() };
s.edit(label, |d, _| {
for ((i, dv), (_, art)) in moves.iter().zip(&arts) {
let a = d.artboards.get_mut(*i).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
a.rect = a.rect + *dv;
let id = a.id;
d.move_artboard_guides(id, *dv);
for id in art {
if let Some(n) = d.node_mut(*id) {
n.transform(Affine::translate(*dv), sc);
super::object::keep_pixel_aligned(n, sc);
}
}
}
Ok(())
})?;
Ok(json!({ "moved": moved }))
}
fn align(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "artboard.align";
let h = choice(p, C, "horizontal", &["left", "center", "right"])?;
let v = choice(p, C, "vertical", &["top", "center", "bottom"])?;
if h.is_none() && v.is_none() {
return Err(bad(C, "give horizontal or vertical"));
}
let b = boards(s, p, C)?;
let Some(r) = b.reference.map(|(_, r)| r).or_else(|| b.items.iter().map(|(_, r)| *r).reduce(|a, b| a.union(b))) else {
return Ok(json!({ "moved": [] }));
};
let moves: Vec<(usize, Vec2)> = b
.items
.iter()
.map(|(i, a)| {
let dx = match h {
Some("left") => r.x0 - a.x0,
Some("center") => r.center().x - a.center().x,
Some("right") => r.x1 - a.x1,
_ => 0.0,
};
let dy = match v {
Some("top") => r.y0 - a.y0,
Some("center") => r.center().y - a.center().y,
Some("bottom") => r.y1 - a.y1,
_ => 0.0,
};
(*i, Vec2::new(dx, dy))
})
.collect();
apply(s, "Align", p, &b, &moves)
}
fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "artboard.distribute";
let h = choice(p, C, "horizontal", &["left", "center", "right"])?;
let v = choice(p, C, "vertical", &["top", "center", "bottom"])?;
let (horiz, line): (bool, fn(&Rect) -> f64) = match (h, v) {
(Some("left"), _) => (true, |r| r.x0),
(Some("right"), _) => (true, |r| r.x1),
(Some(_), _) => (true, |r| r.center().x),
(None, Some("top")) => (false, |r| r.y0),
(None, Some("bottom")) => (false, |r| r.y1),
(None, Some(_)) => (false, |r| r.center().y),
(None, None) => return Err(bad(C, "give horizontal or vertical")),
};
let gap = spacing(p, C)?;
let b = boards(s, p, C)?;
let mut items = b.items.clone();
items.sort_by(|x, y| line(&x.1).total_cmp(&line(&y.1)));
let kept = kept(&b, &items, gap)?;
// With a spacing: the place in the order and the line of the artboard it is measured from.
let from = kept.zip(gap).and_then(|(at, gap)| items.get(at).map(|(_, r)| (at, gap, line(r))));
let n = items.len();
// Two artboards are the ends already; with a spacing the second is placed from the first.
if n < if from.is_some() { 2 } else { 3 } {
return Ok(json!({ "moved": [] }));
}
let (Some((_, first)), Some((_, last))) = (items.first(), items.last()) else { return Ok(json!({ "moved": [] })) };
let (first, last) = (line(first), line(last));
let deltas: Vec<f64> = items
.iter()
.enumerate()
.map(|(k, (_, r))| {
let target = match from {
Some((at, gap, origin)) => origin + gap * (k as f64 - at as f64),
None => first + (last - first) * k as f64 / (n - 1) as f64,
};
target - line(r)
})
.collect();
// The artboard aligned to stays where it is, and the others keep their places from it.
let hold = kept.and_then(|at| deltas.get(at)).copied().unwrap_or(0.0);
let moves: Vec<(usize, Vec2)> = items.iter().zip(&deltas).map(|((i, _), d)| (*i, along(horiz, d - hold))).collect();
apply(s, "Distribute", p, &b, &moves)
}
fn distribute_spacing(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "artboard.distributeSpacing";
let horiz = choice(p, C, "axis", &["horizontal", "vertical"])? != Some("vertical");
let gap = spacing(p, C)?;
let b = boards(s, p, C)?;
let start = |r: &Rect| if horiz { r.x0 } else { r.y0 };
let size = |r: &Rect| if horiz { r.width() } else { r.height() };
let mut items = b.items.clone();
items.sort_by(|x, y| start(&x.1).total_cmp(&start(&y.1)));
let kept = kept(&b, &items, gap)?;
let gap = gap.filter(|_| kept.is_some());
let n = items.len();
if n < if gap.is_some() { 2 } else { 3 } {
return Ok(json!({ "moved": [] }));
}
let (Some((_, first)), Some((_, last))) = (items.first(), items.last()) else { return Ok(json!({ "moved": [] })) };
let (lo, hi) = (start(first), start(last) + size(last));
let gap = gap.unwrap_or_else(|| (hi - lo - items.iter().map(|(_, r)| size(r)).sum::<f64>()) / (n - 1) as f64);
let mut pos = lo;
let mut deltas = Vec::with_capacity(n);
for (i, r) in &items {
deltas.push((*i, pos - start(r)));
pos += size(r) + gap;
}
// The artboard aligned to stays where it is, and the others keep their places from it.
let hold = kept.and_then(|at| deltas.get(at)).map_or(0.0, |d| d.1);
let moves: Vec<(usize, Vec2)> = deltas.into_iter().map(|(i, d)| (i, along(horiz, d - hold))).collect();
apply(s, "Distribute Spacing", p, &b, &moves)
}
/// An offset of `d` along the axis: x when `horiz`, else y.
fn along(horiz: bool, d: f64) -> Vec2 {
if horiz { Vec2::new(d, 0.0) } else { Vec2::new(0.0, d) }
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,310 @@
//! Align and Distribute for artboards.
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use crate::Session;
use crate::tooling::ViewInfo;
/// A document with three artboards, each with a 10 pt square 5 pt inside its top-left corner:
/// 0 at (0, 0) 100 × 100, 1 at (150, 40) 60 × 80 and 2 at (400, 10) 100 × 50 → the squares' ids.
fn three_boards() -> (Session, [u64; 3]) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap();
s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap();
let mut sq = |x: u64, y: u64| s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
let ids = [sq(5, 5), sq(155, 45), sq(405, 15)];
s.execute("select.none", &json!({})).unwrap();
(s, ids)
}
/// The top-left corner of each artboard.
fn corners(s: &Session) -> Vec<(f64, f64)> {
s.doc().unwrap().doc.artboards.iter().map(|a| (a.rect.x0, a.rect.y0)).collect()
}
/// The top-left corner of object `id`.
fn corner(s: &Session, id: u64) -> (f64, f64) {
let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
(b.x0, b.y0)
}
fn undo_steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
const ALL: [u64; 3] = [0, 1, 2];
/// Align Objects lines the artboards up on the bounds of all of them, each with the art inside
/// it, in one undo step.
#[test]
fn align_moves_the_artboards_to_their_common_edge_with_their_art() {
let (mut s, [a, b, c]) = three_boards();
let before = corners(&s);
let steps = undo_steps(&s);
let out = s.execute("artboard.align", &json!({"indices": ALL, "vertical": "top"})).unwrap();
assert_eq!(out, json!({"moved": [1, 2]}));
assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 0.0), (400.0, 0.0)]);
assert_eq!([corner(&s, a), corner(&s, b), corner(&s, c)], [(5.0, 5.0), (155.0, 5.0), (405.0, 5.0)], "each square stays on its artboard");
assert_eq!(undo_steps(&s), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((corners(&s), corner(&s, b)), (before, (155.0, 45.0)), "one undo step");
s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "right", "vertical": "bottom"})).unwrap();
assert_eq!(corners(&s), [(400.0, 20.0), (440.0, 40.0), (400.0, 70.0)], "the right edges at 500 and the bottom edges at 120");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "center", "moveArt": false})).unwrap();
assert_eq!(corners(&s), [(200.0, 0.0), (220.0, 40.0), (200.0, 10.0)], "the centers at 250");
assert_eq!(corner(&s, a), (5.0, 5.0), "moveArt false leaves the art");
}
/// Align to an artboard: that artboard stays where it is and the others line up on it. It need not
/// be one of the artboards aligned.
#[test]
fn align_to_an_artboard_keeps_that_artboard_in_place() {
let (mut s, _) = three_boards();
let out = s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 2})).unwrap();
assert_eq!(out, json!({"moved": [0, 1]}));
assert_eq!(corners(&s), [(400.0, 0.0), (400.0, 40.0), (400.0, 10.0)]);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.align", &json!({"index": 0, "vertical": "center", "to": "artboard", "artboard": 1})).unwrap();
assert_eq!(corners(&s), [(0.0, 30.0), (150.0, 40.0), (400.0, 10.0)], "artboard 1's center is at y 80");
}
/// With no artboard named, the commands act on the artboards the Artboard tool has selected and
/// align to its active one; the journal records both for a replay, and an action leaves them out.
#[test]
fn the_artboard_tools_selection_is_the_default_and_is_recorded() {
let (mut s, [_, _, c]) = three_boards();
s.select_tool("artboard", ViewInfo::default()).unwrap();
s.set_tool_option("selected", &json!([1, 2]));
let start = s.journal.len();
assert_eq!(s.execute("artboard.align", &json!({"horizontal": "left"})).unwrap(), json!({"moved": [2]}));
assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 40.0), (150.0, 10.0)]);
assert_eq!(corner(&s, c), (155.0, 15.0), "the tool's Move Artwork with Artboard option is on");
let recorded = json!({"horizontal": "left", "selectedArtboards": [1, 2], "moveArt": true, "lockedAndHidden": false});
assert_eq!(s.journal.last().unwrap(), &("artboard.align".to_string(), recorded));
assert_eq!(
s.journal_for_action(start),
[("artboard.align".to_string(), json!({"horizontal": "left", "moveArt": true, "lockedAndHidden": false}))]
);
s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard"})).unwrap();
assert_eq!(corners(&s)[2], (150.0, 40.0), "artboard 2 lines up on the active artboard, 1");
assert_eq!(s.journal.last().unwrap().1["activeArtboard"], json!(1));
assert_eq!(s.journal_for_action(start)[1].1.get("activeArtboard"), None, "an action aligns to the artboard active when it plays");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard", "activeArtboard": 0})).unwrap();
assert_eq!(corners(&s)[1..], [(150.0, 0.0), (150.0, 0.0)], "a replay aligns to the artboard it recorded, 0");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.align", &json!({"vertical": "bottom", "to": "artboard", "artboard": 0, "activeArtboard": 2})).unwrap();
assert_eq!(corners(&s)[1..], [(150.0, 20.0), (150.0, 50.0)], "`artboard` goes ahead of the recorded one");
let action = s.journal_for_action(start);
let entry = &action.last().unwrap().1;
assert_eq!((entry.get("artboard"), entry.get("activeArtboard")), (Some(&json!(0)), None), "an action keeps the artboard a call named");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard"})).unwrap();
s.set_tool_option("moveArt", &json!(false));
s.execute("artboard.align", &json!({"horizontal": "right"})).unwrap();
assert_eq!((corners(&s)[1], corner(&s, c)), ((190.0, 40.0), (155.0, 45.0)), "with the option off the art stays");
}
/// A command that moves no artboard leaves the document and its undo history as they are.
#[test]
fn nothing_to_move_records_no_undo_step() {
let (mut s, _) = three_boards();
s.execute("artboard.align", &json!({"indices": ALL, "vertical": "top"})).unwrap();
let (steps, before) = (undo_steps(&s), corners(&s));
for (id, p) in [
("artboard.align", json!({"indices": ALL, "vertical": "top"})),
("artboard.align", json!({"index": 1, "horizontal": "left", "vertical": "bottom"})),
("artboard.align", json!({"index": 1, "horizontal": "center", "to": "artboard", "artboard": 1})),
("artboard.distribute", json!({"indices": [0, 2], "horizontal": "center"})),
("artboard.distribute", json!({"index": 2, "vertical": "top", "to": "artboard", "artboard": 2, "spacing": 30})),
("artboard.distributeSpacing", json!({"indices": [0, 1], "axis": "horizontal"})),
("artboard.distributeSpacing", json!({"indices": [1], "axis": "vertical"})),
] {
assert_eq!(s.execute(id, &p).unwrap(), json!({"moved": []}), "{id} {p}");
assert_eq!((undo_steps(&s), corners(&s)), (steps, before.clone()), "{id} {p}");
}
}
/// A locked artboard stays where it is and still counts in the bounds and in the order. When every
/// artboard named is locked, the command fails.
#[test]
fn a_locked_artboard_stays_where_it_is() {
let (mut s, _) = three_boards();
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
assert_eq!(s.execute("artboard.align", &json!({"indices": ALL, "vertical": "bottom"})).unwrap(), json!({"moved": [0, 2]}));
assert_eq!(corners(&s), [(0.0, 20.0), (150.0, 40.0), (400.0, 70.0)], "the bottom edges at 120, the locked artboard's");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.execute("artboard.distributeSpacing", &json!({"indices": ALL})).unwrap(), json!({"moved": []}), "the middle artboard is locked");
let out =
s.execute("artboard.distribute", &json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 0, "spacing": 100})).unwrap();
assert_eq!((out, corners(&s)), (json!({"moved": [2]}), vec![(0.0, 0.0), (150.0, 40.0), (200.0, 10.0)]), "the third left edge goes to 200");
s.execute("edit.undo", &json!({})).unwrap();
let (steps, before) = (undo_steps(&s), corners(&s));
for (id, p) in [
("artboard.align", json!({"index": 1, "horizontal": "left", "to": "artboard", "artboard": 0})),
("artboard.distribute", json!({"index": 1, "horizontal": "left"})),
("artboard.distributeSpacing", json!({"indices": [1]})),
] {
assert_eq!(s.execute(id, &p).unwrap_err().to_string(), "the artboard is locked", "{id}");
assert_eq!((undo_steps(&s), corners(&s)), (steps, before.clone()), "{id}");
}
}
/// Distribute Objects spaces the named edges or centers evenly between the outermost artboards;
/// with a spacing and an artboard to align to, it places them that far apart from that artboard.
#[test]
fn distribute_spaces_the_edges_or_centers() {
let (mut s, [_, b, _]) = three_boards();
assert_eq!(s.execute("artboard.distribute", &json!({"indices": ALL, "horizontal": "center"})).unwrap(), json!({"moved": [1]}));
assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "the centers at 50, 250 and 450");
assert_eq!(corner(&s, b), (225.0, 45.0));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.distribute", &json!({"indices": ALL, "vertical": "bottom"})).unwrap();
assert_eq!(corners(&s), [(0.0, -10.0), (150.0, 40.0), (400.0, 10.0)], "the bottom edges at 60, 90 and 120");
s.execute("edit.undo", &json!({})).unwrap();
let p = json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 1, "spacing": 100});
assert_eq!(s.execute("artboard.distribute", &p).unwrap(), json!({"moved": [0, 2]}));
assert_eq!(corners(&s), [(50.0, 0.0), (150.0, 40.0), (250.0, 10.0)], "the left edges 100 apart, artboard 1 in place");
s.execute("edit.undo", &json!({})).unwrap();
let two = json!({"indices": [0, 2], "horizontal": "right", "to": "artboard", "artboard": 2, "spacing": 150});
assert_eq!(s.execute("artboard.distribute", &two).unwrap(), json!({"moved": [0]}));
assert_eq!(corners(&s)[0], (250.0, 0.0), "two artboards are enough with a spacing: the right edges at 350 and 500");
s.execute("edit.undo", &json!({})).unwrap();
let held = json!({"indices": ALL, "horizontal": "center", "to": "artboard", "artboard": 1});
assert_eq!(s.execute("artboard.distribute", &held).unwrap(), json!({"moved": [0, 2]}));
assert_eq!(corners(&s), [(-70.0, 0.0), (150.0, 40.0), (330.0, 10.0)], "the centers 200 apart, artboard 1 in place");
}
/// Distribute Spacing makes the gaps between the artboards equal; with a spacing and an artboard
/// to align to, the gaps are that wide and that artboard stays.
#[test]
fn distribute_spacing_makes_the_gaps_equal() {
let (mut s, _) = three_boards();
assert_eq!(s.execute("artboard.distributeSpacing", &json!({"indices": ALL})).unwrap(), json!({"moved": [1]}));
assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "gaps of 120 between 0 and 500");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.distributeSpacing", &json!({"indices": ALL, "axis": "vertical"})).unwrap();
assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 40.0), (400.0, 45.0)], "top to bottom: artboards 0, 2 and 1, overlapping by 55");
s.execute("edit.undo", &json!({})).unwrap();
let p = json!({"indices": ALL, "axis": "horizontal", "to": "artboard", "artboard": 1, "spacing": 20});
assert_eq!(s.execute("artboard.distributeSpacing", &p).unwrap(), json!({"moved": [0, 2]}));
assert_eq!(corners(&s), [(30.0, 0.0), (150.0, 40.0), (230.0, 10.0)], "gaps of 20 on both sides of artboard 1");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.distributeSpacing", &json!({"indices": [0, 2], "to": "artboard", "artboard": 0, "spacing": -25})).unwrap();
assert_eq!(corners(&s)[2], (75.0, 10.0), "a negative spacing overlaps them");
s.execute("edit.undo", &json!({})).unwrap();
let held = json!({"indices": ALL, "to": "artboard", "artboard": 1});
assert_eq!(s.execute("artboard.distributeSpacing", &held).unwrap(), json!({"moved": [0, 2]}));
assert_eq!(corners(&s), [(-70.0, 0.0), (150.0, 40.0), (330.0, 10.0)], "gaps of 120, artboard 1 in place");
}
/// A value outside what a param takes is an error, and nothing changes.
#[test]
fn bad_params_are_errors() {
let (mut s, _) = three_boards();
let (steps, before) = (undo_steps(&s), corners(&s));
let with = |extra: Value| {
let mut p = json!({"indices": ALL, "horizontal": "left"});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
p
};
let shared = [
json!({"horizontal": "middle"}),
json!({"horizontal": 1}),
json!({"to": "key"}),
json!({"to": "artboard", "artboard": 9}),
json!({"artboard": "1"}),
json!({"artboard": -1}),
json!({"moveArt": "yes"}),
json!({"patterns": 1}),
json!({"lockedAndHidden": "no"}),
json!({"indices": [9]}),
json!({"indices": []}),
json!({"indices": "0"}),
];
for id in ["artboard.align", "artboard.distribute", "artboard.distributeSpacing"] {
let axis = if id == "artboard.distributeSpacing" { json!({"horizontal": null, "axis": "horizontal"}) } else { json!({}) };
for extra in &shared {
let mut p = with(axis.clone());
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
if id == "artboard.distributeSpacing" && extra.get("horizontal").is_some() {
p = json!({"indices": ALL, "axis": extra["horizontal"]});
}
assert!(s.execute(id, &p).is_err(), "{id} {p}");
}
}
for (id, p) in [
("artboard.align", json!({"indices": ALL})),
("artboard.align", json!({"indices": ALL, "vertical": "middle"})),
("artboard.distribute", json!({"indices": ALL})),
("artboard.distribute", with(json!({"spacing": "10"}))),
("artboard.distribute", with(json!({"spacing": true}))),
("artboard.distribute", json!({"indices": [0, 1], "horizontal": "left", "to": "artboard", "artboard": 2, "spacing": 10})),
("artboard.distributeSpacing", json!({"indices": ALL, "spacing": [10]})),
("artboard.distributeSpacing", json!({"indices": [0, 1], "to": "artboard", "artboard": 2, "spacing": 10})),
] {
assert!(s.execute(id, &p).is_err(), "{id} {p}");
}
// Spacings that would put an artboard past the canvas, or overflow to infinity.
for (id, p) in [
("artboard.distribute", with(json!({"to": "artboard", "artboard": 0, "spacing": 1e9}))),
("artboard.distribute", with(json!({"to": "artboard", "artboard": 1, "spacing": 1e308}))),
("artboard.distributeSpacing", json!({"indices": ALL, "to": "artboard", "artboard": 0, "spacing": 1e9})),
("artboard.distributeSpacing", json!({"indices": ALL, "to": "artboard", "artboard": 1, "spacing": 1e308})),
] {
let e = s.execute(id, &p).unwrap_err().to_string();
assert!(e.contains("exceed the canvas"), "{id} {p}: {e}");
}
assert_eq!((undo_steps(&s), corners(&s)), (steps, before));
}
/// Art inside two overlapping artboards moves with the one first in artboard order, as with the
/// other artboard edits, even when Distribute spaces the other one first: artboard 2 at x 140 is
/// left of artboard 1 at x 200, and the square inside both goes with artboard 1.
#[test]
fn art_on_overlapping_artboards_moves_with_the_first_by_index() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 140, "y": 0, "width": 100, "height": 100})).unwrap();
let sq = s.execute("shape.rectangle", &json!({"x": 210, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.none", &json!({})).unwrap();
let p = json!({"indices": ALL, "to": "artboard", "artboard": 0, "spacing": 10});
assert_eq!(s.execute("artboard.distributeSpacing", &p).unwrap(), json!({"moved": [1, 2]}));
assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 0.0), (110.0, 0.0)]);
assert_eq!(corner(&s, sq), (230.0, 10.0), "with artboard 1, 20 pt to the right");
}
/// Art inside an artboard that stays and a later one that moves stays with the first: artboard 2
/// overlaps artboard 0, and aligning it to artboard 0 leaves the square inside both in place.
#[test]
fn art_shared_with_an_artboard_that_stays_stays() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 60, "y": 0, "width": 100, "height": 100})).unwrap();
let sq = s.execute("shape.rectangle", &json!({"x": 70, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.none", &json!({})).unwrap();
let p = json!({"indices": [0, 2], "horizontal": "left", "to": "artboard", "artboard": 0});
assert_eq!(s.execute("artboard.align", &p).unwrap(), json!({"moved": [2]}));
assert_eq!(corners(&s)[2], (0.0, 0.0));
assert_eq!(corner(&s, sq), (70.0, 10.0), "with artboard 0, which stays");
}
/// An artboard's own guides move with it.
#[test]
fn an_artboards_guides_move_with_it() {
let (mut s, _) = three_boards();
s.execute("guide.add", &json!({"vertical": true, "pos": 160, "artboard": 1})).unwrap();
s.execute("artboard.align", &json!({"indices": [0, 1], "horizontal": "left"})).unwrap();
let d = &s.doc().unwrap().doc;
let positions: Vec<f64> = d.ruler_guides().iter().map(|g| g.pos).collect();
assert_eq!(positions, [10.0], "the guide stays 10 pt inside artboard 1");
}
+2 -2
View File
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbol Options…",
[],
None,
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
has_doc,
symbol_options
),
@@ -326,7 +326,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select All Unused",
[],
None,
"{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used",
"{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics mapped onto 3D objects (threeD.mapGraphic), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used",
has_doc,
symbol_unused
),
+31
View File
@@ -115,6 +115,8 @@ fn art_symbols(n: &Node, out: &mut Vec<String>) {
if let NodeKind::SymbolInstance { symbol, .. } = &m.kind {
out.push(symbol.clone());
}
// A graphic on a 3D object draws its symbol's art too.
out.extend(vectorcraft_render::effects::graphic_symbols(m));
});
}
@@ -129,6 +131,8 @@ pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result<Value> {
let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()));
let trees = d.layers.iter().map(|l| &**l).chain(d.graph_designs.iter().map(|g| &*g.art));
trees.chain(patterns.flat_map(|p| p.art.iter().map(|n| &**n))).chain(lib.iter().flat_map(|b| b.art())).for_each(|n| art_symbols(n, &mut todo));
// A graphic in a graphic style draws its symbol's art wherever the style is applied.
todo.extend(d.graphic_styles.iter().flat_map(|g| vectorcraft_render::effects::appearance_graphic_symbols(&g.appearance)));
let mut used = std::collections::BTreeSet::new();
while let Some(name) = todo.pop() {
if !used.contains(&name) {
@@ -290,6 +294,33 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
*symbol = n.clone();
}
}
// The graphics mapped onto 3D objects follow the new name: in the layers, the art of
// symbols, patterns, graph designs and brushes, their opacity masks, and graphic styles.
let patterns = d.patterns.iter_mut().chain(d.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()));
let trees = d
.layers
.iter_mut()
.chain(d.symbols.iter_mut().map(|sym| &mut sym.art))
.chain(d.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(patterns.flat_map(|p| p.art.iter_mut()));
for art in trees.filter(|art| vectorcraft_render::effects::names_graphic_symbol(art, &name)) {
vectorcraft_render::effects::rename_graphic_symbol_in(Arc::make_mut(art), &name, n);
}
let styled = |g: &vectorcraft_doc::GraphicStyle| vectorcraft_render::effects::appearance_graphic_symbols(&g.appearance).contains(&name);
if d.graphic_styles.iter().any(styled) {
for style in d.graphic_styles.iter_mut() {
vectorcraft_render::effects::rename_appearance_graphic_symbol(&mut style.appearance, &name, n);
}
}
// The brush library is stored again only when a brush's art changed.
let mut lib = brush::library(d);
let mut brushes = false;
for art in lib.iter_mut().flat_map(|b| b.art_mut()) {
brushes |= vectorcraft_render::effects::rename_graphic_symbol_in(art, &name, n);
}
if brushes {
brush::store(d, &lib);
}
rename_natural_size(d, &name, n);
d.rename_symbol_registration(&name, n);
d.rename_symbol_export_type(&name, n);
+43 -70
View File
@@ -86,6 +86,10 @@ fn paint_refs(p: &Paint, f: Visit) {
}
fn appearance_refs(a: &Appearance, f: Visit) {
// The graphics mapped onto the faces of its 3D effects name symbols.
for s in vectorcraft_render::effects::appearance_graphic_symbols(a) {
f(Ref::Name(Res::Symbol, &s));
}
for it in &a.items {
paint_refs(it.paint(), f);
if let AppearanceItem::Stroke(l) = it
@@ -624,6 +628,17 @@ impl Relink {
}
}
}
// A 3D effect's mapped graphics follow their symbols' names in the document. Each name is
// looked up once, so renames that chain (A to B, B to C) do not apply twice.
let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
for e in a.effects.iter_mut().chain(items).filter(|e| vectorcraft_render::effects::takes_graphics(&e.id)) {
let list = e.params.get_mut(vectorcraft_render::effects::GRAPHICS).and_then(Value::as_array_mut);
for g in list.into_iter().flatten() {
if let Some(Value::String(s)) = g.get_mut("symbol") {
self.name(Res::Symbol, s);
}
}
}
for it in &mut a.items {
self.paint(it.paint_mut());
if let AppearanceItem::Stroke(l) = it
@@ -705,15 +720,6 @@ fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool {
relinked(&Relink::default(), ours) == relinked(r, theirs)
}
/// Does brush `b`'s art show symbols or patterns?
fn shows_definitions(b: &Brush) -> bool {
let mut found = false;
for a in b.art() {
node_refs(a, &mut |r| found |= matches!(r, Ref::Name(Res::Symbol | Res::Pattern, _)));
}
found
}
/// A symbol's Symbol Options, which its document keeps by symbol name: copied with the symbol and
/// given to it under the name pasting adds it as.
#[derive(Clone, Debug, PartialEq)]
@@ -747,7 +753,7 @@ impl SymbolOptions {
}
/// A character or paragraph style, symbol (with the Symbol Options copied with it), pattern or
/// brush (placed with the others only when they are placed in use order) to place
/// brush to place
/// ([`Clipboard::import_used`]).
#[derive(Clone, Copy)]
enum Def<'c> {
@@ -1063,49 +1069,40 @@ impl Clipboard {
}
/// Add the resources the objects use to `d` (inside the paste's undo step) and work out how
/// pasted copies relink to them. An error, with `d` unchanged, when a pasted SVG filter finds no
/// free name ([`Self::filter_links`]).
/// pasted copies relink to them. Each style, symbol, pattern and brush is placed after those it
/// uses, as [`import_text_styles`] places them, so that a style that paints with a pattern added
/// under a free name ("Dots 2") is compared and added with that name. An error, with `d`
/// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]).
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
self.import_used(d, &self.used(), choices, same_doc, false)
self.import_used(d, &self.used(), choices, same_doc)
}
/// [`Self::import_into`] for the resources `used` names. The character and paragraph styles
/// come before the symbols and patterns, whose art may set type in them; with `in_use_order`,
/// each style, symbol, pattern and brush comes after the styles, symbols, patterns and brushes it uses
/// ([`use_order`]), so that it is compared and relinked with their names here, and each loop
/// of definitions that use each other is matched on its own ([`loop_groups`]).
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Result<Imported> {
/// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush
/// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is
/// compared and relinked with their names here, and each loop of definitions that use each
/// other is matched on its own ([`loop_groups`]). Pasted back into its own document
/// (`same_doc`), each definition of a loop is the document's of its name.
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
let mut out = Imported::default();
out.relink.filters = self.filter_links(d, same_doc)?;
self.import_images(d, used, same_doc, &mut out);
self.import_swatches(d, used, choices, same_doc, &mut out);
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
// they may brush; the others once those are in. With `in_use_order`, the brushes are
// placed in use order with the others.
let mut added_brushes: HashSet<String> =
if in_use_order { HashSet::new() } else { self.import_brushes(d, used, same_doc, false, &mut out).into_iter().collect() };
let mut defs: Vec<Def<'_>> = vec![];
for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] {
defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s)));
}
defs.extend(self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).map(|s| Def::Symbol(s, self.symbol_options.get(&s.name))));
defs.extend(self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).map(Def::Pattern));
if in_use_order {
defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush));
}
defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush));
// Groups to place in order; true for a loop of definitions that use each other.
let groups: Vec<(Vec<Def<'_>>, bool)> = if in_use_order {
let (order, rest) = use_order(defs);
let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped));
std::iter::once((order, false)).chain(loops).collect()
} else {
vec![(defs, false)]
};
// Styles (their colors relinked first), symbols and patterns (compared once relinked,
// symbols with their options too). The symbols and patterns added are relinked at the end,
// when every new name and graphic style id is known; with `in_use_order`, so are the
// styles added, which a loop of uses may place before a pattern they paint with.
let (mut added_symbols, mut added_patterns, mut added_styles) = (HashSet::new(), HashSet::new(), vec![]);
let (order, rest) = use_order(defs);
let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped));
let groups: Vec<(Vec<Def<'_>>, bool)> = std::iter::once((order, false)).chain(loops).collect();
// Styles (their colors relinked first), symbols, patterns and brushes (compared once
// relinked, symbols with their options too). The styles, symbols, patterns and brushes
// added are relinked at the end, when every new name and graphic style id is known: a loop
// of uses may place one before a definition it uses.
let (mut added_symbols, mut added_patterns, mut added_brushes, mut added_styles) = (HashSet::new(), HashSet::new(), HashSet::new(), vec![]);
// Each definition, whether it is in a loop, and the loop it starts.
let steps = groups
.iter()
@@ -1115,8 +1112,8 @@ impl Clipboard {
let mut fresh = false;
// The names in the document of the loop being placed, when it has them all at once.
let mut matched: BTreeMap<(Res, String), String> = BTreeMap::new();
// The document's brush library, read the first time a brush is placed in use order and
// stored again after each brush added; nothing else in the loop changes it.
// The document's brush library, read the first time a brush is placed and stored again
// after each brush added; nothing else in the loop changes it.
let mut library: Option<Vec<Brush>> = None;
for (def, looped, starts) in steps {
fresh &= looped;
@@ -1124,8 +1121,9 @@ impl Clipboard {
matched.clear();
}
// A loop of uses that the document has all at once is known under those names before
// its definitions are compared.
if let Some(group) = starts {
// its definitions are compared. In its own document, each definition is the
// document's of its name, as outside a loop.
if let Some(group) = starts.filter(|_| !same_doc) {
matched.clear();
match names_of_loop(d, group, &out.relink) {
Some(names) => {
@@ -1154,7 +1152,7 @@ impl Clipboard {
out.relink.attrs(&mut s.attrs);
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
let p = place(theirs, &s, same_doc, |a, b| !fresh && a == b);
if in_use_order && let Some(name) = p.new_name(&def.name) {
if let Some(name) = p.new_name(&def.name) {
added_styles.push((r, name, def));
}
out.placed(r, &def.name, &p);
@@ -1208,9 +1206,6 @@ impl Clipboard {
}
}
}
if !in_use_order {
added_brushes.extend(self.import_brushes(d, used, same_doc, true, &mut out));
}
self.import_graphic_styles(d, used, same_doc, &mut out);
for (r, name, def) in added_styles {
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
@@ -1331,28 +1326,6 @@ impl Clipboard {
}
}
/// The brushes whose art shows symbols or patterns (`late`), or the others: each one the
/// document has (its art compared once relinked) is used, the others are added. → the names of
/// those added, whose art is relinked at the end.
fn import_brushes(&self, d: &mut Document, used: &Used, same_doc: bool, late: bool, out: &mut Imported) -> Vec<String> {
let brushes: Vec<&Brush> = self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name) && shows_definitions(b) == late).collect();
if brushes.is_empty() {
return vec![];
}
let mut lib = vectorcraft_brush::library(d);
let mut added = vec![];
for b in brushes {
let r = &out.relink;
let p = place(&mut lib, b, same_doc, |ours, theirs| same_brush(r, ours, theirs));
added.extend(p.new_name(&b.name));
out.placed(Res::Brush, &b.name, &p);
}
if !added.is_empty() {
vectorcraft_brush::store(d, &lib);
}
added
}
/// Global and spot colours (a name conflict merges or adds as `choices` say), then the tint
/// swatches of the tints used and the gradient swatches.
fn import_swatches(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, out: &mut Imported) {
@@ -1437,7 +1410,7 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
let used = Used::of_text_styles(&Defs::of(src, &library), chars, paras);
let clip = Clipboard::with_used(src, &used, &library, vec![]);
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true)?;
let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?;
let mut placed: Vec<LoadedStyle> = vec![];
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
for s in list {
+38 -23
View File
@@ -5,7 +5,9 @@
//! Colour settings and the proof view are process-wide (`vectorcraft_color::cms::active`,
//! `vectorcraft_render::proof::view`). A document's assigned profiles are stored in
//! `Document::color_profiles` (files before format v3: `Document.unknown["colorProfiles"]`) and
//! become active when assigned.
//! take the place of the working spaces in the active settings when assigned, and when the working
//! settings change while the document is in front ([`use_front_profiles`]); the working spaces stay
//! as Edit → Color Settings set them.
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -59,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Assign Profile…",
["Edit"],
None,
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (colour numbers are kept) → {rgb, cmyk}",
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: the working space). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}",
has_doc,
assign_profile
),
@@ -176,9 +178,19 @@ fn touch_all(s: &mut Session) {
}
}
/// Make the active settings the working settings with the profiles the front document is assigned
/// in place of the working spaces (none, or no document open: the working spaces). The open
/// documents redraw when the active settings change.
fn use_front_profiles(s: &mut Session) {
let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default();
if cms::use_document_profiles(rgb.as_deref(), cmyk.as_deref()) {
touch_all(s);
}
}
fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.colorSettings";
let mut st = cms::active_settings();
let mut st = cms::working_settings();
let before = st.clone();
if let Some(v) = text_param(p, "rgb", C)? {
st.rgb = cms::canonical_name(v).to_string();
@@ -194,6 +206,7 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
// Saved for the next start when the app attached a settings file (#6335).
s.store_color_settings(&st);
use_front_profiles(s);
touch_all(s);
}
Ok(settings_json(&st))
@@ -208,14 +221,18 @@ fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
let info = cms::register_icc(&bytes, None).map_err(|e| bad(C, e.to_string()))?;
// The bytes are kept, not the path: the file may move or go away.
let remembered = s.store_profile(&info.name, &bytes);
// A new file of a working space: the active settings still hold the old one.
let working = cms::active_settings();
let is_working = working.rgb == info.name || working.cmyk == info.name;
if is_working {
// A new file of a working space or of an assigned profile in use: the active settings still
// hold the old one. A profile the front document is assigned, loaded after it was removed, is
// in use again.
let (working, active) = (cms::working_settings(), cms::active_settings());
let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default();
let front = [rgb, cmyk].iter().any(|n| n.as_deref() == Some(info.name.as_str()));
if front || [&working.rgb, &working.cmyk, &active.rgb, &active.cmyk].contains(&&info.name) {
cms::set_active(&working).map_err(|e| bad(C, e.to_string()))?;
}
// A new file of a working space, or of the CMYK profile View → Proof Setup targets: redraw.
if is_working || proof_targets(&info.name) {
use_front_profiles(s);
touch_all(s);
} else if proof_targets(&info.name) {
// A new file of the CMYK profile View → Proof Setup targets: redraw.
touch_all(s);
}
Ok(json!({"name": info.name, "kind": info.kind, "remembered": remembered}))
@@ -229,14 +246,21 @@ fn remove_profile(s: &mut Session, p: &Value) -> Result<Value> {
if info.builtin {
return Err(bad(C, format!("`{name}` is a built-in profile and stays")));
}
let working = cms::active_settings();
let working = cms::working_settings();
if working.rgb == name || working.cmyk == name {
return Err(bad(C, format!("`{name}` is a working space: choose another with edit.colorSettings first")));
}
let active = cms::active_settings();
if !cms::unregister_icc(&info.name) {
return Err(bad(C, format!("no profile named `{name}`")));
}
s.unstore_profile(&info.name);
// An assigned profile in use: the working space takes its place, as for any document assigned
// a profile that is not available.
if active.rgb == name || active.cmyk == name {
use_front_profiles(s);
}
// The CMYK profile View → Proof Setup targets: redraw.
if proof_targets(&info.name) {
touch_all(s);
}
@@ -284,18 +308,9 @@ fn assign_profile(s: &mut Session, p: &Value) -> Result<Value> {
d.color_profiles = profiles;
Ok(())
})?;
let mut st = cms::active_settings();
let before = st.clone();
if let Some(r) = &rgb {
st.rgb = r.clone();
}
if let Some(c) = &cmyk {
st.cmyk = c.clone();
}
if st != before {
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
touch_all(s);
}
// The document draws through its profiles now, and a Document Color Mode later in the same
// batch converts through them. The working spaces stay as they are.
use_front_profiles(s);
}
Ok(json!({"rgb": rgb, "cmyk": cmyk}))
}
+9 -7
View File
@@ -7,7 +7,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_svg::{CssOptions, CssSheet, css_rules};
use super::fileio::{default_name, encode_with_warnings, isolated, write_file};
use super::fileio::{Note, default_name, encode_with_notes, isolated, note_texts, write_file};
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, named_ids, targets};
pub fn specs() -> Vec<CommandSpec> {
@@ -118,20 +118,22 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
}
let css = format!("{}\n", sheet.text());
let doc = &s.doc()?.doc;
// Encode the pictures of rasterized art, and add each of their warnings once.
// Encode the pictures of rasterized art, and add each of their warnings once. What CSS can't
// describe is a loss.
let mut images = Vec::new();
let mut warnings = sheet.warnings.clone();
let mut notes: Vec<Note> = sheet.warnings.iter().cloned().map(Note::loss).collect();
for r in &sheet.rules {
let Some(name) = &r.image else { continue };
let (d, _) = isolated(doc, &[r.id], name).ok_or_else(|| bad(C, format!("{} paints nothing to rasterize", r.selector)))?;
let (png, notes) = encode_with_warnings(&d, "png", &json!({}))?;
let (png, given) = encode_with_notes(&d, "png", &json!({}))?;
images.push((name, png));
for w in notes {
if !warnings.contains(&w) {
warnings.push(w);
for n in given {
if !notes.iter().any(|x| x.text == n.text) {
notes.push(n);
}
}
}
let warnings = note_texts(&notes);
let n = sheet.rules.len();
match path {
Some(path) => {
+1 -1
View File
@@ -568,7 +568,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) ->
ArrowStyle::Tick => Some(Arrowhead::Slash),
ArrowStyle::None => None,
};
st.start_arrow = head;
st.start_arrow = head.clone();
st.end_arrow = head;
st.arrow_scale = (o.arrow_scale, o.arrow_scale);
st.arrow_align = vectorcraft_doc::appearance::ArrowAlign::Tip;
+261 -34
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Info",
["Window", "Document Info"],
None,
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
has_doc,
info
),
@@ -131,14 +131,16 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
}
/// The Document Info categories of `d` (only `category` when given) from `info` (what
/// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the
/// rows of its objects filled or stroked with a spot color, with a pattern and with a gradient.
/// `document.info` reports), its fonts, its image objects, the rows of the brushes its art uses, the
/// rows of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a
/// pattern and with a gradient.
#[allow(clippy::too_many_arguments)]
fn sections(
d: &Document,
info: &Value,
fonts: &BTreeSet<super::fonts::UsedFont>,
images: &[ImageRow],
brushes: &[(String, String)],
repeats: &[(String, String)],
spot_objects: &[(String, String)],
pattern_objects: &[(String, String)],
@@ -184,7 +186,7 @@ fn sections(
rows
}
"graphicStyles" => names("graphicStyleNames"),
"brushes" => names("brushNames"),
"brushes" => brushes.to_vec(),
"spotColors" => spot_objects.to_vec(),
"patterns" => pattern_objects.to_vec(),
"gradients" => gradient_objects.to_vec(),
@@ -326,12 +328,18 @@ fn painted_runs<'a>(d: &Document, spots: &HashSet<&str>, n: &'a Node) -> Option<
if !own && !t.runs.iter().any(|r| is_listed(&r.style.fill) || is_listed(&r.style.stroke)) {
return None;
}
Some((t, drawn_runs(d, t)))
}
/// The runs of type `t` that its layout draws: those with a glyph outline (list markers and ruby
/// included) or an underline or strikethrough bar, laid out as the renderer lays it out.
fn drawn_runs(d: &Document, t: &vectorcraft_doc::TextObject) -> BTreeSet<usize> {
let db = vectorcraft_text::FontDb::global();
let resolved = d.inline_resolved(t);
let lay = vectorcraft_text::layout(db, &resolved);
let mut painted: BTreeSet<usize> = lay.glyphs.iter().chain(&lay.ruby).filter(|g| !g.outline.elements().is_empty()).map(|g| g.run).collect();
painted.extend(vectorcraft_text::decorations(&lay, db, &resolved).into_iter().map(|(run, _)| run));
Some((t, painted))
painted
}
/// The names a paint is listed by in a Document Info category: its spot colors, its pattern or its
@@ -340,7 +348,8 @@ type PaintNames<'a> = dyn Fn(&Paint) -> Vec<String> + 'a;
/// The spot colors, patterns or gradients (`label`: [`spot_labels`], [`pattern_label`] or
/// [`gradient_label`], each paint's names) that `n`'s own fills and strokes paint, each once. A
/// hidden fill or stroke and a stroke with no width paint nothing, and neither does any fill or
/// hidden fill or stroke, a fill or stroke at an opacity of 0 and a stroke with no width paint
/// nothing, and neither does any fill or
/// stroke of a guide (drawn in the guide color), of a compound path's member (`members`: the
/// compound path's own fills and strokes paint it) or of type whose layout draws nothing
/// (`painted_runs`). An image's fills and strokes paint only where an effect gives them a shape.
@@ -364,7 +373,7 @@ fn own_paints(
.then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().flat_map(|(_, _, item)| label(item.paint())).collect());
let mut out: Vec<String> = vec![];
for item in &n.appearance.items {
if !item.visible() || matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) {
if !item.visible() || item.opacity() <= 0.0 || matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) {
continue;
}
for name in label(item.paint()) {
@@ -381,6 +390,41 @@ fn one_label(label: fn(&Paint) -> Option<String>) -> impl Fn(&Paint) -> Vec<Stri
move |p| label(p).into_iter().collect()
}
/// The brushes `n`'s own strokes draw with, in the order of its appearance. A hidden stroke, a
/// stroke at an opacity of 0, a stroke with no paint and a stroke with no width draw nothing, and neither does any stroke of a
/// guide (drawn in the guide color) or of a compound path's member (`members`: the compound path's
/// own strokes draw it). An image's strokes draw only where an effect gives them a shape, and only
/// paths, compound paths, type and images draw strokes of their own.
fn applied_brushes(d: &Document, n: &Node, members: &HashSet<*const Node>) -> Vec<String> {
if matches!(n.kind, NodeKind::Path { guide: true, .. }) || members.contains(&std::ptr::from_ref(n)) {
return vec![];
}
let brush = |item: &vectorcraft_doc::AppearanceItem| match item {
vectorcraft_doc::AppearanceItem::Stroke(st) if item.visible() && st.opacity > 0.0 && !st.paint.is_none() && st.width > 0.0 => {
st.brush.clone().filter(|b| !b.is_empty())
}
_ => None,
};
if matches!(n.kind, NodeKind::Image(_)) {
return vectorcraft_render::effects::image_paint(Some(d), n).iter().filter_map(|(_, _, item)| brush(item)).collect();
}
let used: Vec<String> = n.appearance.items.iter().filter_map(brush).collect();
if used.is_empty() {
return used;
}
// A path or compound path with no segment gives its strokes nothing to follow, and neither does
// type whose layout draws nothing (spaces and line breaks without an underline or strikethrough).
let segments = |pd: &vectorcraft_geom::PathData| pd.subpaths.iter().any(|sp| sp.segment_count() > 0);
let follows = match &n.kind {
NodeKind::Path { .. } => n.path_data().is_some_and(segments),
NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).any(segments),
NodeKind::Text(t) => !drawn_runs(d, t).is_empty(),
// A brush on any other kind of object (a layer, a group, a ruler guide) is not listed.
_ => false,
};
if follows { used } else { vec![] }
}
fn info(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "document.info";
let category = str_param(p, "category");
@@ -425,8 +469,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
let mut spot = BTreeSet::new();
let (spot_label, pattern, gradient) = (|p: &Paint| spot_labels(&spot_swatches, p), one_label(pattern_label), one_label(gradient_label));
let mut styles: Vec<&str> = if selection_only { vec![] } else { d.graphic_styles.iter().map(|g| g.name.as_str()).collect() };
// `brushes` holds the Brushes panel's brushes, or with selectionOnly it holds the brushes that the selected objects' strokes use.
let mut brushes: Vec<String> = if selection_only { vec![] } else { vectorcraft_brush::library(d).into_iter().map(|b| b.name).collect() };
// `library` holds the Brushes panel's brushes, and `brushes` the brushes the visited objects' strokes draw with, each once,
// in walk order.
let library = vectorcraft_brush::library(d);
let mut brushes: Vec<String> = vec![];
// `repeats` and `repeat_rows` hold the `repeatObjects` entries and the rows of the Repeat objects that the walk visits, in walk order.
let mut repeats: Vec<Value> = vec![];
let mut repeat_rows: Vec<(String, String)> = vec![];
@@ -569,14 +615,9 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
{
styles.push(&g.name);
}
if selection_only {
for item in &n.appearance.items {
if let vectorcraft_doc::AppearanceItem::Stroke(st) = item
&& let Some(b) = &st.brush
&& !brushes.contains(b)
{
brushes.push(b.clone());
}
for b in applied_brushes(d, n, &members) {
if !brushes.contains(&b) {
brushes.push(b);
}
}
if let NodeKind::Repeat(spec) = &n.kind {
@@ -586,7 +627,24 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
}
});
}
// The document's fonts include those of the type in opacity masks and in the art of its
// symbols and patterns, as Find Font lists them.
if !selection_only {
fonts.extend(super::fonts::art_texts_of(d).into_iter().flat_map(|(_, t, _)| t.runs.iter().map(|r| super::fonts::font_of(&r.style))));
}
let font_names: Vec<String> = fonts.iter().map(super::fonts::font_label).collect();
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the last of two
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type
// as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them.
let kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = library.iter().map(|b| (b.name.as_str(), &b.kind)).collect();
let brush_entries: Vec<Value> =
brushes.iter().map(|name| json!({ "name": name, "type": kinds.get(name.as_str()).map(|k| k.type_id()) })).collect();
let brush_rows: Vec<(String, String)> = brushes
.iter()
.map(|name| {
(name.clone(), kinds.get(name.as_str()).map_or_else(|| "missing from the Brushes panel".to_string(), |k| format!("{} Brush", k.label())))
})
.collect();
let mut out = json!({
"document": document_summary(d),
"objects": counts,
@@ -601,6 +659,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
"graphicStyles": d.graphic_styles.len(),
"graphicStyleNames": styles,
"brushNames": brushes,
"brushes": brush_entries,
"panelBrushNames": library.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(),
"repeatObjects": repeats,
"characterStyles": d.char_styles.len(),
"paragraphStyles": d.para_styles.len(),
@@ -612,7 +672,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
});
// The document's name: its file's, else its title.
out["document"]["name"] = json!(st.title());
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
let sections = sections(d, &out, &fonts, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
if text {
return Ok(json!({ "text": report_text(&st.title(), selection_only, &sections) }));
}
@@ -701,6 +761,40 @@ mod tests {
assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1);
}
/// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a
/// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's.
#[test]
fn info_fonts_include_masks_symbols_and_patterns() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let id = |v: Value| NodeId(v["id"].as_u64().unwrap());
let text = |s: &mut Session, font: &str| id(s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": font})).unwrap());
let rect = |s: &mut Session| id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap());
let (masked, in_symbol) = (rect(&mut s), rect(&mut s));
for (owner, font) in [(masked, "Mask Family"), (in_symbol, "Symbol Mask Family")] {
let t = text(&mut s, font);
s.edit("Mask", |d, _| {
let art = d.remove(t)?;
d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
Ok(())
})
.unwrap();
}
s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap();
let t = text(&mut s, "Pattern Family");
s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let plain = text(&mut s, "Source Sans 3");
let fonts = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["fonts"].clone();
assert_eq!(
fonts(&mut s, json!({})),
json!(["Mask Family Regular", "Pattern Family Regular", "Source Sans 3 Regular", "Symbol Mask Family Regular"])
);
s.execute("select.set", &json!({"ids": [plain.0]})).unwrap();
assert_eq!(fonts(&mut s, json!({"selectionOnly": true})), json!(["Source Sans 3 Regular"]));
}
/// Document Info › Objects gives the paths' total length in the document's units (#1958): an
/// open line, a closed rectangle's perimeter and a compound path's pieces count, a guide doesn't.
#[test]
@@ -725,38 +819,129 @@ mod tests {
assert_eq!(length(&mut s, json!({"selectionOnly": true})), 0.0);
}
/// Document Info › Brushes lists the Brushes panel's brushes, and with Selection Only it lists
/// the brushes the selected objects' strokes use, each once.
/// Document Info › Brushes lists the brushes the art's strokes use, each once with its type, and
/// leaves out the Brushes panel's brushes no art uses (`panelBrushNames` lists those). With
/// Selection Only it lists the brushes the selected objects' strokes use.
#[test]
fn info_lists_the_brushes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let panel: Vec<Value> =
s.execute("brush.list", &json!({})).unwrap()["brushes"].as_array().unwrap().iter().map(|b| b["name"].clone()).collect();
let i = s.execute("document.info", &json!({"category": "brushes"})).unwrap();
assert_eq!(i["brushNames"], json!(panel));
let brushes = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap();
// No art uses a brush: the category is empty.
let i = brushes(&mut s, json!({"category": "brushes"}));
assert_eq!((i["brushNames"].clone(), i["brushes"].clone(), i["panelBrushNames"].clone()), (json!([]), json!([]), json!(panel)));
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("brushes"), Some("Brushes")));
let rows: Vec<Value> = panel.iter().map(|n| json!([n, ""])).collect();
assert_eq!(i["sections"][0]["rows"], json!(rows));
assert_eq!(i["sections"][0]["rows"], json!([]));
let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let c = s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("brush.apply", &json!({"ids": [a], "name": "Charcoal"})).unwrap();
s.execute("brush.apply", &json!({"ids": [b], "name": "Arrow"})).unwrap();
s.execute("brush.apply", &json!({"ids": [b], "name": "Dots"})).unwrap();
s.execute("brush.apply", &json!({"ids": [c], "name": "Charcoal"})).unwrap();
let names =
|s: &mut Session| s.execute("document.info", &json!({"selectionOnly": true, "category": "brushes"})).unwrap()["brushNames"].clone();
// The whole document: the two brushes the art uses, each once, with their types; "3 pt. Round" (a Calligraphic
// brush in the panel) is left out.
let i = brushes(&mut s, json!({"category": "brushes"}));
assert_eq!(i["brushNames"], json!(["Charcoal", "Dots"]));
assert_eq!(i["brushes"], json!([{"name": "Charcoal", "type": "art"}, {"name": "Dots", "type": "scatter"}]));
assert_eq!(i["sections"][0]["rows"], json!([["Charcoal", "Art Brush"], ["Dots", "Scatter Brush"]]));
assert!(panel.contains(&json!("3 pt. Round")) && i["panelBrushNames"] == json!(panel));
let text = brushes(&mut s, json!({"category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string();
assert!(text.contains("\nBRUSHES\nCharcoal: Art Brush\nDots: Scatter Brush\n") && !text.contains("3 pt. Round"), "{text}");
assert!(!text.contains("OBJECTS"), "{text}");
// Selection Only: the brushes the selected objects' strokes use.
let selected = |s: &mut Session| brushes(s, json!({"selectionOnly": true, "category": "brushes"}));
s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap();
assert_eq!(names(&mut s), json!(["Charcoal", "Arrow"]));
assert_eq!(selected(&mut s)["brushNames"], json!(["Charcoal", "Dots"]));
s.execute("select.set", &json!({"ids": [b]})).unwrap();
assert_eq!(names(&mut s), json!(["Arrow"]));
let i = selected(&mut s);
assert_eq!(
(i["brushes"].clone(), i["sections"][0]["rows"].clone()),
(json!([{"name": "Dots", "type": "scatter"}]), json!([["Dots", "Scatter Brush"]]))
);
let text = brushes(&mut s, json!({"selectionOnly": true, "category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string();
assert!(text.contains("\nBRUSHES\nDots: Scatter Brush\n") && !text.contains("Charcoal"), "{text}");
// A stroke without a brush lists none.
let plain = s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [plain]})).unwrap();
assert_eq!(names(&mut s), json!([]));
let text = s.execute("document.info", &json!({"category": "brushes", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
assert!(text.contains(&format!("\nBRUSHES\n{}\n", panel[0].as_str().unwrap())), "{text}");
assert!(text.contains("\nCharcoal\n") && text.contains("\nArrow\n") && !text.contains("OBJECTS"), "{text}");
assert_eq!(selected(&mut s)["brushNames"], json!([]));
}
/// Document Info › Brushes leaves out brushes on strokes that draw nothing (hidden, at an
/// opacity of 0, with no width or paint, a guide's, a compound path member's, a path's with no segment, type's that
/// draws no characters, a group's own), lists a brush the Brushes panel does
/// not hold with no type, and gives a name two panel brushes share the type the renderer uses.
#[test]
fn info_brushes_skip_undrawn_strokes_and_name_missing_brushes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let square = |s: &mut Session, x: f64| {
s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()
};
let (hidden, thin, guide, missing) = (square(&mut s, 0.0), square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0));
let (empty, faint) = (square(&mut s, 80.0), square(&mut s, 200.0));
s.execute("brush.apply", &json!({"ids": [hidden, thin, guide, missing, empty, faint], "name": "Charcoal"})).unwrap();
let (p, q) = (square(&mut s, 100.0), square(&mut s, 120.0));
s.execute("select.set", &json!({"ids": [p, q]})).unwrap();
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
// A compound path's member: the compound path's own stroke draws it.
let NodeKind::Compound { children, .. } = &mut d.node_mut(NodeId(compound)).unwrap().kind else { panic!("not a compound path") };
let member = &mut std::sync::Arc::make_mut(&mut children[0]).appearance;
member.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
member.stroke_mut().unwrap().brush = Some("Dots".into());
d.node_mut(NodeId(hidden)).unwrap().appearance.stroke_mut().unwrap().visible = false;
d.node_mut(NodeId(thin)).unwrap().appearance.stroke_mut().unwrap().width = 0.0;
// A stroke at an opacity of 0 draws nothing.
d.node_mut(NodeId(faint)).unwrap().appearance.stroke_mut().unwrap().opacity = 0.0;
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(guide)).unwrap().kind {
*g = true;
}
// A path with no segment: its stroke follows nothing.
if let NodeKind::Path { path, .. } = &mut d.node_mut(NodeId(empty)).unwrap().kind {
*path = vectorcraft_geom::PathData::default();
}
d.node_mut(NodeId(missing)).unwrap().appearance.stroke_mut().unwrap().brush = Some("Gone".into());
let i = s.execute("document.info", &json!({"category": "brushes"})).unwrap();
assert_eq!(i["brushes"], json!([{"name": "Gone", "type": null}]));
assert_eq!(i["sections"][0]["rows"], json!([["Gone", "missing from the Brushes panel"]]));
// A stroke with no paint draws nothing.
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
d.node_mut(NodeId(missing)).unwrap().appearance.stroke_mut().unwrap().paint = Paint::None;
assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([]));
// Two panel brushes with one name: the type is the one the renderer draws with, the last one's.
let twin = square(&mut s, 140.0);
s.execute("brush.apply", &json!({"ids": [twin], "name": "Charcoal"})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let mut lib = vectorcraft_brush::library(d);
let kinds: Vec<vectorcraft_brush::BrushKind> =
["Charcoal", "Dots"].iter().map(|n| lib.iter().find(|b| b.name == *n).unwrap().kind.clone()).collect();
lib.extend(kinds.into_iter().map(|kind| vectorcraft_brush::Brush { name: "Twin".into(), kind }));
vectorcraft_brush::store(d, &lib);
d.node_mut(NodeId(twin)).unwrap().appearance.stroke_mut().unwrap().brush = Some("Twin".into());
assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([{"name": "Twin", "type": "scatter"}]));
// Type: a brushed stroke on drawn characters is listed, one on spaces alone is not.
let blank = s.execute("text.create", &json!({"x": 10, "y": 60, "text": " "})).unwrap()["id"].as_u64().unwrap();
let word = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "Hi"})).unwrap()["id"].as_u64().unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
for (id, name) in [(blank, "Dots"), (word, "Arrow")] {
let ap = &mut d.node_mut(NodeId(id)).unwrap().appearance;
ap.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
ap.stroke_mut().unwrap().brush = Some(name.into());
}
let names = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushNames"].clone();
assert_eq!(names, json!(["Twin", "Arrow"]));
// A group's own stroke: the group draws its members.
let (m1, m2) = (square(&mut s, 160.0), square(&mut s, 180.0));
s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let ap = &mut d.node_mut(NodeId(group)).unwrap().appearance;
ap.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
ap.stroke_mut().unwrap().brush = Some("Leaves".into());
let names = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushNames"].clone();
assert_eq!(names, json!(["Twin", "Arrow"]));
}
/// Document Info › Repeat Objects lists each Repeat object by name with its kind and the number
@@ -867,6 +1052,11 @@ mod tests {
s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [e], "swatch": "Dots"})).unwrap();
s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap();
// Nor does a pattern fill at an opacity of 0.
let clear = square(&mut s, 220.0);
s.execute("paint.setStroke", &json!({"ids": [clear], "none": true})).unwrap();
s.execute("paint.setFill", &json!({"ids": [clear], "swatch": "Dots"})).unwrap();
s.execute("appearance.setItem", &json!({"ids": [clear], "index": 0, "opacity": 0})).unwrap();
// A type object with no characters paints nothing either.
let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Dots"})).unwrap();
@@ -927,7 +1117,7 @@ mod tests {
assert_eq!(i["patternNames"], json!(["Dots"]));
// Objects counts the objects that Pattern Objects lists.
assert_eq!(i["objects"]["patterns"].as_u64(), Some(5), "{}", i["objects"]);
s.execute("select.set", &json!({"ids": [d, e, empty, blank, guide, compound, image.0]})).unwrap();
s.execute("select.set", &json!({"ids": [d, e, clear, empty, blank, guide, compound, image.0]})).unwrap();
let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
assert!(i["objects"]["patterns"].is_null() && i["patternObjects"] == json!([]), "{}", i["objects"]);
let i = s.execute("document.info", &json!({"category": "patterns"})).unwrap();
@@ -1228,6 +1418,43 @@ mod tests {
assert_eq!(i["objects"]["spots"].as_u64(), Some(1), "{}", i["objects"]);
}
/// Spot Color Objects leaves out a fill or stroke at an opacity of 0, which prints no ink, and
/// keeps the object while another of its fills or strokes prints the spot color. Gradient
/// Objects leaves out a clear gradient fill as well.
#[test]
fn spot_color_objects_skip_clear_fills_and_strokes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [rect], "swatch": "Ink"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [rect], "swatch": "Ink"})).unwrap();
let ramp = s.execute("shape.rectangle", &json!({"x": 50, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let stops = json!([{"offset": 0, "color": "#000", "swatch": "Ink"}, {"offset": 1, "color": "#fff", "swatch": "Ink"}]);
s.execute("paint.setFill", &json!({"ids": [ramp], "gradient": {"kind": "linear", "stops": stops}})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [ramp], "none": true})).unwrap();
let items = |s: &Session, id: &Value| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().appearance.items.clone();
let spots = |s: &mut Session| {
let i = s.execute("document.info", &json!({})).unwrap();
let mut ids: Vec<u64> = i["spotObjects"].as_array().unwrap().iter().map(|o| o["id"].as_u64().unwrap()).collect();
ids.sort_unstable();
(ids, i["objects"]["spots"].as_u64(), i["objects"]["gradients"].as_u64())
};
// The rectangle's fill at an opacity of 0: its stroke still prints the spot color.
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
let fill = items(&s, &rect).iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
s.execute("appearance.setItem", &json!({"index": fill, "opacity": 0})).unwrap();
assert_eq!(spots(&mut s), (vec![rect.as_u64().unwrap(), ramp.as_u64().unwrap()], Some(2), Some(1)));
// Every fill and stroke of both objects at an opacity of 0.
for id in [&rect, &ramp] {
s.execute("select.set", &json!({"ids": [id]})).unwrap();
for index in 0..items(&s, id).len() {
s.execute("appearance.setItem", &json!({"index": index, "opacity": 0})).unwrap();
}
}
assert_eq!(spots(&mut s), (vec![], None, None));
}
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
/// it counts that object once.
+2 -2
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New…",
["File"],
None,
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode}; the size is remembered in file.newPresets' Recent",
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
always,
super::newdoc::file_new
),
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
doc_compare
),
cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model (with automation read roots, a linked or placed file outside them is named by its file name alone, without its relative path, size or date, in brush art too, and so is a data set's image value outside them; a relative path that leads outside them is left out; a stored brush entry that does not read as a brush is left out; a folder outside them is left out of export_settings)", has_doc, |s, _| {
cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model (with automation read roots, a linked or placed file outside them is named by its file name alone, without its relative path, size or date, in brush art too, and so are a data set's image value and a linked JavaScript file in svg_scripts outside them (a URL is kept); a relative path that leads outside them is left out; a stored brush entry that does not read as a brush is left out; a folder outside them is left out of export_settings)", has_doc, |s, _| {
let st = s.doc()?;
let d = super::links::with_hidden_paths_named(&st.doc, super::links::LinkBase::of(st));
Ok(serde_json::to_value(&*d).unwrap_or(Value::Null))
+16 -1
View File
@@ -34,8 +34,15 @@ fn svg_filter_name(s: &Session, xml: &str, cmd: &str) -> Result<String> {
Ok(name)
}
/// The effect commands of the Effect menu and the Appearance panel.
/// The effect commands of the Effect menu and the Appearance panel, and the 3D and Materials
/// panel's Graphics.
pub fn specs() -> Vec<CommandSpec> {
let mut specs = effect_specs();
specs.extend(graphics::specs());
specs
}
fn effect_specs() -> Vec<CommandSpec> {
vec![
cmd!(
"effect.apply",
@@ -454,6 +461,9 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten();
let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len())));
effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?;
if let Some(name) = effects::missing_symbol(d, &effect.params, None) {
return Err(bad(C, format!("no symbol named `{name}`")));
}
if id == effects::REVOLVE && effects::has_revolve(n) {
return Err(bad(C, "A profile supports one Revolve effect. Edit the existing effect's options instead."));
}
@@ -758,6 +768,9 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(to, &params)) {
cur.extend(new);
}
if let Some(name) = effects::missing_symbol(d, &prospective, Some(&e.params)) {
return Err(bad(C, format!("no symbol named `{name}`")));
}
if visible != Some(false) {
effects::validate_three_d_at_in(Some(d), n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?;
} else {
@@ -1201,6 +1214,8 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
mod graphics;
#[cfg(test)]
mod lighting_presets_tests;
+153
View File
@@ -0,0 +1,153 @@
//! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single
//! Graphic) and mapped onto the planar faces of 3D objects (Extrude & Bevel's caps, a plane). The
//! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams`
//! also edits.
use serde_json::{Map, Value, json};
use vectorcraft_doc::{Effect, Node};
use vectorcraft_render::effects;
use super::super::appearance::{appearance_targets, index_param, item_target};
use super::super::brushsym::{normalize, selection_art, store_symbol};
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_doc, has_selection, str_param};
use super::{effect_targets, ids_json};
pub(super) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"threeD.addGraphic",
"Add as Single Graphic",
[],
None,
"{name?: string (default Graphic; made unique), ids?|id?} keep the selection's art as a new document symbol, listed among the 3D and Materials panel's Graphics; the selection stays as it is → {name}",
has_selection,
add_graphic
),
cmd!(
"threeD.mapGraphic",
"Map Graphic",
[],
None,
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane), scale?: % (1..10000; default 100, or less so the graphic fits inside the object), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it; every object's 3D effect must be Extrude & Bevel (on a solid cap) or Rotate (the Plane type); one undo step → {ids, graphic}",
has_doc,
map_graphic
),
]
}
/// `threeD.addGraphic`: stores the selection's art as a symbol without replacing it with an
/// instance.
fn add_graphic(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "threeD.addGraphic";
if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !["name", "ids", "id"].contains(&k.as_str()))) {
return Err(bad(C, format!("unknown parameter `{key}`")));
}
if p.get("name").is_some_and(|v| v.as_str().is_none_or(|n| n.trim().is_empty())) {
return Err(bad(C, "`name` must be a name that is not empty"));
}
let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?;
crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art);
let (art, size, _) = normalize(art)?;
let name = s.doc()?.doc.unique_symbol_name(str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Graphic"));
s.edit("Add as Single Graphic", |d, _| {
store_symbol(d, &art, &name, size);
Ok(())
})?;
Ok(json!({ "name": name }))
}
/// The 3D effect of `n` that a graphic goes on when none is named: its own first, then its fills'
/// and strokes', as the 3D and Materials panel finds it.
fn first_three_d(n: &Node) -> Option<(Option<usize>, usize)> {
let at = |fx: &[Effect]| fx.iter().position(|e| effects::is_three_d(&e.id));
at(&n.appearance.effects)
.map(|i| (None, i))
.or_else(|| n.appearance.items.iter().enumerate().find_map(|(k, item)| at(item.effects()).map(|i| (Some(k), i))))
}
/// `threeD.mapGraphic`: appends a graphic to the 3D effect of each target, after checking that every
/// target takes it.
fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "threeD.mapGraphic";
const KEYS: [&str; 10] = ["symbol", "face", "x", "y", "scale", "rotation", "index", "item", "ids", "id"];
if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !KEYS.contains(&k.as_str()))) {
return Err(bad(C, format!("unknown parameter `{key}`")));
}
// An item names where the effect is in that item's list, so it takes an index too.
if p.get("item").is_some() && p.get("index").is_none() {
return Err(bad(C, "`item` needs `index`"));
}
// The graphic's own settings, checked as the effect checks them.
let mut given = Map::new();
for key in ["symbol", "face", "x", "y", "scale", "rotation"] {
if let Some(v) = p.get(key) {
given.insert(key.into(), v.clone());
}
}
let base = effects::MappedGraphic::from_value(&Value::Object(given)).map_err(|e| bad(C, e))?;
let d = &s.doc()?.doc;
if !d.symbols.iter().any(|sym| sym.name == base.symbol) {
return Err(bad(C, format!("no symbol named `{}`", base.symbol)));
}
let targets: Vec<(NodeId, Option<usize>, usize)> = if p.get("index").is_some() {
let index = index_param(p, "index", C)?;
let item = item_target(s, p, C)?;
effect_targets(s, p, item, index, C)?
} else {
let mut out = vec![];
for id in appearance_targets(s, p)? {
let (item, index) = d.node(id).and_then(first_three_d).ok_or_else(|| bad(C, format!("object {} needs a 3D effect", id.0)))?;
out.push((id, item, index));
}
out
};
if targets.is_empty() {
return Err(bad(C, "select an object with a 3D effect"));
}
let mut edits = Vec::with_capacity(targets.len());
for &(id, item, index) in &targets {
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
let Some(effect) = n.appearance.effects_at(item).and_then(|fx| fx.get(index)).filter(|e| effects::is_three_d(&e.id)) else {
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
};
if !effects::takes_graphics(&effect.id) {
return Err(bad(C, format!("object {}: Graphics map onto planar faces: use the Extrude or Plane object type", id.0)));
}
// A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again,
// but has no cap to show a new one on.
let merged = effects::merged_params(&effect.id, &effect.params);
let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged));
if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0)));
}
// With a depth of 0 the art is a plane, which has only a front.
if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) {
return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0)));
}
let mut graphic = base.clone();
if p.get("scale").is_none()
&& let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol))
{
graphic.scale = frame.fitting_scale(art);
}
let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic);
effects::validate_three_d_at_in(Some(d), n, &effect.id, &params, item.map(|i| (i, index))).map_err(|e| bad(C, e))?;
edits.push((id, item, index, graphic));
}
let first = edits.first().map(|(.., g)| g.to_value());
let ids = s.edit("Map Graphic", |d, _| {
let mut done = vec![];
for (id, item, index, graphic) in &edits {
let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects_mut(*item)).and_then(|fx| fx.get_mut(*index)) else { continue };
let current = effects::upgrade_params(&e.id, &e.params);
e.params = effects::with_graphic(&current, graphic);
done.push(*id);
}
Ok(done)
})?;
Ok(json!({ "ids": ids_json(&ids), "graphic": first }))
}
#[cfg(test)]
#[path = "graphics_tests.rs"]
mod tests;
@@ -0,0 +1,289 @@
#![allow(clippy::unwrap_used, clippy::panic)]
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use crate::Session;
/// A 100 × 100 square with `effect`, and a 10 × 20 red rectangle beside it kept as graphic "Mark".
fn setup(effect: &str) -> (Session, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
let mark = s.execute("path.create", &json!({"d":"M300 300L310 300L310 320L300 320Z"})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap();
let made = s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [mark]})).unwrap();
assert_eq!(made["name"], "Mark");
let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap();
s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":{"rotationX":0.0,"rotationY":0.0,"rotationZ":0.0}})).unwrap();
(s, id)
}
fn graphics(s: &Session, id: NodeId) -> Value {
s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params["graphics"].clone()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
#[test]
fn add_as_single_graphic_keeps_the_art_and_makes_a_symbol() {
let (s, _) = setup("threeD.extrude");
let d = &s.doc().unwrap().doc;
assert!(d.symbols.iter().any(|sym| sym.name == "Mark"));
// The art stays a plain path: no instance replaced it.
let mut instances = 0;
for l in &d.layers {
l.walk(&mut |n| instances += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. })));
}
assert_eq!(instances, 0);
// The 10 × 20 rectangle and its 1 pt stroke.
assert_eq!(vectorcraft_render::effects::graphic_bounds(d, "Mark").map(|r| (r.width(), r.height())), Some((11.0, 21.0)));
}
#[test]
fn map_graphic_adds_to_the_selected_object_in_one_undo_step_and_undoes() {
let (mut s, id) = setup("threeD.extrude");
let before = s.doc().unwrap().doc.clone();
let history = undo_len(&s);
let r = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "x": 5.0, "rotation": 30.0})).unwrap();
assert_eq!(r["ids"], json!([id.0]));
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 5.0, "y": 0.0, "scale": 100.0, "rotation": 30.0}]));
assert_eq!(undo_len(&s), history + 1);
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back"})).unwrap();
assert_eq!(graphics(&s, id).as_array().unwrap().len(), 2);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
}
#[test]
fn a_large_graphic_starts_inside_its_object() {
let (mut s, id) = setup("threeD.rotate");
let big = s.execute("path.create", &json!({"d":"M0 0L400 0L400 200L0 200Z"})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Big", "ids": [big]})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Big", "ids": [id.0]})).unwrap();
// 401 pt wide with its stroke, in a 100 pt square.
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
assert!((scale - 100.0 * 100.0 / 401.0).abs() < 1e-9, "{scale}");
}
#[test]
fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
let (mut s, id) = setup("threeD.inflate");
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("Extrude or Plane"), "{e}");
let (mut s, id) = setup("threeD.rotate");
for (p, says) in [
(json!({"symbol": "Gone"}), "no symbol named"),
(json!({"face": "front"}), "needs `symbol`"),
(json!({"symbol": "Mark", "face": "back"}), "one face"),
(json!({"symbol": "Mark", "scale": 0.0}), "scale"),
(json!({"symbol": "Mark", "tile": true}), "`tile`"),
(json!({"symbol": "Mark", "item": 0}), "`item` needs `index`"),
(json!({"symbol": "Mark", "item": null}), "`item` needs `index`"),
] {
let mut p = p;
p["ids"] = json!([id.0]);
let e = s.execute("threeD.mapGraphic", &p).unwrap_err().to_string();
assert!(e.contains(says), "{p}: {e}");
}
assert_eq!(undo_len(&s), history);
// An object without a 3D effect.
let plain = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].clone();
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [plain]})).unwrap_err().to_string();
assert!(e.contains("3D effect"), "{e}");
// A hollow Extrude & Bevel has no cap to show a new graphic on.
let (mut s, id) = setup("threeD.extrude");
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap();
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("turn on Cap"), "{e}");
assert_eq!(undo_len(&s), history);
// With a depth of 0 there is no back.
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": true, "depth": 0.0}})).unwrap();
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("one face"), "{e}");
assert_eq!(undo_len(&s), history);
assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok());
}
#[test]
fn set_params_edits_graphics_and_checks_them() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let moved = json!([{"symbol": "Mark", "face": "front", "x": -12.0, "y": 8.0, "scale": 150.0, "rotation": 0.0}]);
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": moved}})).unwrap();
assert_eq!(graphics(&s, id), moved);
let bad = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": [{"symbol": "Mark", "face": "top"}]}});
assert!(s.execute("effect.setParams", &bad).is_err());
let null = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": null}});
assert!(s.execute("effect.setParams", &null).is_err());
assert_eq!(graphics(&s, id), moved);
// Extrude to Plane keeps the graphics; to Inflate drops them.
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "plane"})).unwrap();
assert_eq!(graphics(&s, id), moved);
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "inflate"})).unwrap();
assert_eq!(graphics(&s, id), Value::Null);
}
#[test]
fn effect_commands_refuse_an_unknown_symbol_but_keep_a_deleted_ones_graphic() {
let (mut s, id) = setup("threeD.extrude");
let unknown = json!([{"symbol": "Nowhere"}]);
let history = undo_len(&s);
assert!(s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": unknown}})).is_err());
s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap();
let created = undo_len(&s);
assert!(s.execute("effect.apply", &json!({"effect": "threeD.extrude", "item": null, "params": {"graphics": unknown}})).is_err());
assert_eq!((history + 1, undo_len(&s)), (created, created));
// A graphic whose symbol was deleted stays while the effect's other settings change.
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap();
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).symbols.retain(|sym| sym.name != "Mark");
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"depth": 30.0}})).unwrap();
assert_eq!(graphics(&s, id)[0]["symbol"], "Mark");
}
#[test]
fn a_symbol_a_graphic_uses_is_used_and_follows_a_rename() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let unused = s.execute("symbol.unused", &json!({})).unwrap();
assert!(!unused["names"].as_array().unwrap().iter().any(|n| n == "Mark"), "{unused}");
// A 3D object with the graphic kept in another symbol's art follows the rename too.
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
s.execute("symbol.new", &json!({"name": "Holder"})).unwrap();
s.execute("symbol.options", &json!({"name": "Mark", "newName": "Label"})).unwrap();
assert_eq!(graphics(&s, id)[0]["symbol"], "Label");
let d = &s.doc().unwrap().doc;
let holder = d.symbols.iter().find(|sym| sym.name == "Holder").unwrap();
let mut held = vec![];
holder.art.walk(&mut |n| held.extend(vectorcraft_render::effects::graphic_symbols(n)));
assert_eq!(held, vec!["Label".to_string()]);
}
#[test]
fn a_rename_reaches_graphics_in_graph_designs_and_opacity_masks() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let held = d.node(id).unwrap().clone();
d.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Bars".into(), art: std::sync::Arc::new(held.clone()) });
d.graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Boxed", (*held.appearance).clone()));
let mut lib = vectorcraft_brush::library(d);
let scatter = lib.iter_mut().find(|b| !b.art().is_empty()).unwrap();
*scatter.art_mut()[0] = held.clone();
vectorcraft_brush::store(d, &lib);
d.node_mut(id).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(held, true)));
s.execute("symbol.options", &json!({"name": "Mark", "newName": "Label"})).unwrap();
let d = &s.doc().unwrap().doc;
let style = d.graphic_styles.iter().find(|g| g.name == "Boxed").unwrap();
assert_eq!(vectorcraft_render::effects::appearance_graphic_symbols(&style.appearance), vec!["Label".to_string()]);
let brush: Vec<String> =
vectorcraft_brush::library(d).iter().flat_map(|b| b.art()).flat_map(vectorcraft_render::effects::graphic_symbols).collect();
assert_eq!(brush, vec!["Label".to_string()]);
let names = |n: &vectorcraft_doc::Node| {
let mut out = vec![];
n.walk(&mut |c| out.extend(vectorcraft_render::effects::graphic_symbols(c)));
out
};
assert_eq!(names(&d.graph_designs[0].art), vec!["Label".to_string()]);
let mask = d.node(id).unwrap().extras().mask.as_deref().map(|m| names(&m.art));
assert_eq!(mask, Some(vec!["Label".to_string()]));
}
#[test]
fn pasted_into_another_document_a_graphic_brings_its_symbol() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// The symbol the pasted object's graphic names, and the size of that symbol's art.
let pasted = |s: &mut Session| {
s.execute("edit.paste", &json!({})).unwrap();
let st = s.doc().unwrap();
let n = st.doc.node(st.selection.objects[0]).unwrap();
let name = n.appearance.effects[0].params["graphics"][0]["symbol"].as_str().unwrap().to_string();
let size = vectorcraft_render::effects::graphic_bounds(&st.doc, &name).map(|r| (r.width(), r.height()));
(name, size)
};
// A document without the symbol gets it.
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
assert_eq!(pasted(&mut s), ("Mark".to_string(), Some((11.0, 21.0))));
// A document whose symbol "Mark" is other art gets the copied symbol under a free name.
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
let other = s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [other]})).unwrap();
let (name, size) = pasted(&mut s);
assert_ne!(name, "Mark");
assert_eq!(size, Some((11.0, 21.0)));
}
#[test]
fn a_symbol_only_a_graphic_style_uses_is_used() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let appearance = (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone();
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"graphics": []}})).unwrap();
let unused = |s: &mut Session| s.execute("symbol.unused", &json!({})).unwrap()["names"].clone();
assert!(unused(&mut s).as_array().unwrap().iter().any(|n| n == "Mark"));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Boxed", appearance));
assert!(!unused(&mut s).as_array().unwrap().iter().any(|n| n == "Mark"));
}
#[test]
fn add_graphic_refuses_bad_parameters_and_changes_nothing() {
let (mut s, _) = setup("threeD.extrude");
let art = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].clone();
let (symbols, history) = (s.doc().unwrap().doc.symbols.len(), undo_len(&s));
for p in [
json!({"name": 5, "ids": [art]}),
json!({"name": null, "ids": [art]}),
json!({"name": "", "ids": [art]}),
json!({"name": " ", "ids": [art]}),
json!({"tile": true, "ids": [art]}),
] {
assert!(s.execute("threeD.addGraphic", &p).is_err(), "{p}");
}
assert_eq!((s.doc().unwrap().doc.symbols.len(), undo_len(&s)), (symbols, history));
}
#[test]
fn map_graphic_refuses_a_selection_with_an_object_without_a_3d_effect() {
let (mut s, id) = setup("threeD.extrude");
let plain = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].as_u64().unwrap();
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0, plain]})).unwrap_err().to_string();
assert!(e.contains(&format!("object {plain} needs a 3D effect")), "{e}");
assert_eq!(undo_len(&s), history);
assert_eq!(graphics(&s, id).as_array().map_or(0, Vec::len), 0);
}
#[test]
fn the_graphic_is_drawn_on_the_object() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let d = &s.doc().unwrap().doc;
let art = vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap()).unwrap();
let mut red = None;
art.walk(&mut |n| {
if let (Some(p), Some(vectorcraft_doc::AppearanceItem::Fill(f))) = (n.path_data(), n.appearance.items.first())
&& f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1)
{
red = p.bounds();
}
});
// Seen straight on, the 10 × 20 graphic sits at the center of the square.
let r = red.unwrap();
assert!(
(r.center().x - 150.0).abs() < 1e-6
&& (r.center().y - 150.0).abs() < 1e-6
&& (r.width() - 10.0).abs() < 1e-6
&& (r.height() - 20.0).abs() < 1e-6,
"{r:?}"
);
}
+63 -13
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand…",
["Object"],
None,
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge; one that needs more than 256 runs across the box stays a gradient)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
has_selection,
expand
),
@@ -194,10 +194,12 @@ impl Expandable {
NodeKind::Text(t) => t.runs.iter().any(|r| r.style.has_stroke()),
_ => shape && !c.appearance.stroke_paint().is_none(),
};
e.gradient |= match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
_ => shape && c.appearance.items.iter().any(|i| gradient_fill(i).is_some()),
};
// Once one is found, the next path is not measured.
e.gradient = e.gradient
|| match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
_ => shape && gradient_expands(d, c),
};
e.fill |= e.gradient;
e.fill |= match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some())),
@@ -222,6 +224,43 @@ fn gradient_fill(i: &AppearanceItem) -> Option<(&FillLayer, &GradientPaint)> {
}
}
/// Whether path `l` has a gradient fill that Fill expands ([`expand_fills`]): one that repeats or
/// reflects stays a gradient when its box needs more runs than are written ([`padded_on`]). For a
/// path that live-effect plug-ins paint, whether a piece of the art they paint has one
/// ([`expand_pieces`]).
fn gradient_expands(d: &Document, l: &Node) -> bool {
if !l.appearance.items.iter().any(|i| gradient_fill(i).is_some()) {
return false;
}
if !vectorcraft_render::effects::has_painted_effects(l) {
return piece_gradient_expands(d, l);
}
let Some(art) = vectorcraft_render::effects::reshape(Some(d), l, None) else { return false };
let mut any = false;
art.walk(&mut |c| {
any = any
|| (matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
&& !c.is_ruler_guide()
&& c.appearance.items.iter().any(|i| gradient_fill(i).is_some())
&& piece_gradient_expands(d, c));
});
any
}
/// [`gradient_expands`] for a path that no live-effect plug-in paints ([`expand_piece_fills`]).
fn piece_gradient_expands(d: &Document, l: &Node) -> bool {
if !l.appearance.items.iter().filter_map(gradient_fill).any(|(_, g)| g.gradient.is_spread()) {
return l.appearance.items.iter().any(|i| gradient_fill(i).is_some());
}
let reshaped = reshaped(d, l);
let l = reshaped.as_ref().unwrap_or(l);
let Some((path, _)) = node_path(l) else { return false };
let Some(bounds) = path.bounds() else { return false };
l.appearance.items.iter().filter(|i| gradient_fill(i).is_some()).any(|item| {
fill_shape(d, l, item, &path, bounds).is_some_and(|(_, _, b, moved)| gradient_fill(&moved).is_some_and(|(_, g)| padded_on(g, b).is_some()))
})
}
/// The definition and placement of a visible pattern fill whose pattern `d` defines.
fn pattern_fill<'a, 'd>(d: &'d Document, i: &'a AppearanceItem) -> Option<(&'a FillLayer, &'d PatternDef, Affine)> {
match i {
@@ -476,8 +515,9 @@ fn gradient_art(d: &mut Document, l: &Node, path: &PathData, bounds: Rect, f: &F
let m = GradientMesh::for_path_with(path, FREEFORM_MESH, FREEFORM_MESH, &*gradient_sampler(g, bounds, d.color_mode.model()))?;
vec![Node::new(d.alloc_id(), NodeKind::Mesh(m))]
} else {
// A gradient that repeats or reflects expands as its stops repeated over the box.
let (g, runs) = padded_on(g, bounds);
// A gradient that repeats or reflects expands as its stops repeated over the box (and
// stays a gradient when the box needs more runs than are written).
let (g, runs) = padded_on(g, bounds)?;
let g = &*g;
let frame = Frame::new(g, bounds);
match to {
@@ -548,7 +588,9 @@ fn expand_piece_leaves(
/// Path `l` as the canvas paints its fills and strokes: its visible geometry effects applied to its
/// path (a plain path then), and every geometry effect of its own removed, with each raster effect
/// following the Transform effects after it
/// ([`without_geometry`](vectorcraft_render::effects::without_geometry)). `None` when it has no
/// ([`without_geometry`](vectorcraft_render::effects::without_geometry)) and those of its fills and
/// strokes following its Transform effects
/// ([`follow_items`](vectorcraft_render::effects::follow_items)). `None` when it has no
/// visible geometry effect. The swatches and patterns that live-effect plug-ins painting their
/// pieces name are looked up in `doc`. This merges the pieces of such a plug-in into one path, so a
/// path that one paints goes through [`expand_pieces`] instead.
@@ -564,6 +606,8 @@ pub(crate) fn reshaped(doc: &Document, l: &Node) -> Option<Node> {
if carry.moves(&m.appearance) {
carry.apply(&mut m.appearance);
}
// So do the raster effects of its fills and strokes.
vectorcraft_render::effects::follow_items(&mut m);
m.appearance.effects = without_geometry(&m.appearance.effects);
Some(m)
}
@@ -1246,26 +1290,32 @@ pub(crate) fn gradient_sampler(g: &GradientPaint, bounds: Rect, doc_model: Model
Box::new(move |p| g.gradient.sample_keep_model(spread(geom.param_at(g.gradient.kind, p)) as f32))
}
/// For stops repeated by [`padded_on`]: where along the vector (0 to 1) their first run starts and
/// how many runs lie evenly from there to 1.
type Runs = Option<(f64, usize)>;
/// `g` placed on box `bounds` as a gradient that pads past its ends: a linear, radial or diamond
/// gradient that repeats or reflects with its stops repeated as many times as the box needs
/// ([`vectorcraft_color::Gradient::padded_over`]), a conic one with its stops repeated around the
/// turn ([`vectorcraft_color::Gradient::unrolled`]); others as they are. With it, for the repeated
/// stops, where along the vector (0 to 1) their first run starts and how many runs lie evenly from
/// there to 1.
fn padded_on(g: &GradientPaint, bounds: Rect) -> (std::borrow::Cow<'_, GradientPaint>, Option<(f64, usize)>) {
/// there to 1. `None` when the box needs more runs than are written
/// ([`vectorcraft_color::Padded::capped`]): the gradient stays.
fn padded_on(g: &GradientPaint, bounds: Rect) -> Option<(std::borrow::Cow<'_, GradientPaint>, Runs)> {
use std::borrow::Cow;
if !g.gradient.is_spread() {
return (Cow::Borrowed(g), None);
return Some((Cow::Borrowed(g), None));
}
let geom = g.resolve(bounds);
match g.gradient.padded_over(&geom, bounds) {
Some(p) if p.capped => None,
Some(p) => {
let runs = Some((p.first, p.runs));
(Cow::Owned(GradientPaint { gradient: p.gradient, geom: Some(p.geom), angle: p.geom.angle_deg(), ..g.clone() }), runs)
Some((Cow::Owned(GradientPaint { gradient: p.gradient, geom: Some(p.geom), angle: p.geom.angle_deg(), ..g.clone() }), runs))
}
None => {
let runs = Some((0.0, g.gradient.repeat_count() as usize));
(Cow::Owned(GradientPaint { gradient: g.gradient.unrolled().into_owned(), geom: Some(geom), ..g.clone() }), runs)
Some((Cow::Owned(GradientPaint { gradient: g.gradient.unrolled().into_owned(), geom: Some(geom), ..g.clone() }), runs))
}
}
}
+1 -1
View File
@@ -66,7 +66,7 @@ use serde_json::{Value, json};
pub use action_batch::batch_overwrites_one_file;
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings};
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, note_texts};
pub(crate) use encode::{anti_alias, background, with_single_artboard};
pub(crate) use export::with_artboard_fills;
pub(crate) use export::{export_crop, isolated};
+1
View File
@@ -241,6 +241,7 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
enc.warnings.push(w);
}
}
enc.add_setting_notes(out.setting_notes);
for img in out.images {
if !enc.linked.iter().any(|l| l.name == img.name) {
enc.linked.push(vectorcraft_svg::LinkedImage { name: img.name, bytes: Arc::new(img.bytes) });
+133 -20
View File
@@ -74,18 +74,104 @@ pub struct Encoded {
pub linked: Vec<vectorcraft_svg::LinkedImage>,
/// Image maps, each written beside its image under the image's name (raster `imageMap`).
pub maps: Vec<imagemap::Map>,
/// The encoder's warnings (features approximated or left out, options not applied yet).
/// The encoder's warnings: what the file leaves out of the document or writes differently
/// ([`NoteKind::Loss`]).
pub warnings: Vec<String>,
/// The encoder's notes on the options: options not applied yet or applied another way, and
/// what an option turns off ([`NoteKind::Setting`]). A reply gives them after the warnings
/// ([`Self::notes`]).
pub setting_notes: Vec<String>,
/// What joins the file's stem and the artboard name when there is a file per artboard
/// (default `-`; EPS uses `_`, as the reference app names them).
pub joiner: Option<&'static str>,
}
/// What a note an export gives with its file is about.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NoteKind {
/// Something of the document (its art, type, layers or artboards) that the file leaves out or
/// that reaches it changed: the format, its version or a limit can't hold it, or the export
/// couldn't write it.
Loss,
/// An option the export didn't apply or applied another way while the art reaches the file as
/// it looks, or something left out because an option turns it off.
Setting,
}
/// A note an export gives with its file.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Note {
/// What the note is about.
pub kind: NoteKind,
/// The note, in English.
pub text: String,
}
impl Note {
/// A note about what the file loses ([`NoteKind::Loss`]).
pub fn loss(text: impl Into<String>) -> Self {
Self { kind: NoteKind::Loss, text: text.into() }
}
/// A note on the options ([`NoteKind::Setting`]).
pub fn setting(text: impl Into<String>) -> Self {
Self { kind: NoteKind::Setting, text: text.into() }
}
}
/// The texts of `notes` in the order a reply gives them: the losses first, then the notes on the
/// options, each kind in the order given (the status bar names the first).
pub fn note_texts(notes: &[Note]) -> Vec<String> {
let of = |kind| notes.iter().filter(move |n| n.kind == kind).map(|n| n.text.clone());
of(NoteKind::Loss).chain(of(NoteKind::Setting)).collect()
}
/// Add `note` to `notes` unless a note with its text is there already.
pub(super) fn add_note(notes: &mut Vec<Note>, note: Note) {
if !notes.iter().any(|n| n.text == note.text) {
notes.push(note);
}
}
impl Encoded {
pub(super) fn one(bytes: Vec<u8>) -> Self {
Self { files: vec![(None, bytes)], ..Self::default() }
}
/// The file `bytes` with `notes`, each in the list of its kind, in the order given.
pub(super) fn one_with_notes(bytes: Vec<u8>, notes: Vec<Note>) -> Self {
let mut enc = Self::one(bytes);
for n in notes {
match n.kind {
NoteKind::Loss => enc.warnings.push(n.text),
NoteKind::Setting => enc.setting_notes.push(n.text),
}
}
enc
}
/// Add each of `texts` to [`Self::setting_notes`] unless a note with its text is there already.
pub(super) fn add_setting_notes(&mut self, texts: impl IntoIterator<Item = String>) {
for t in texts {
if !self.warnings.contains(&t) && !self.setting_notes.contains(&t) {
self.setting_notes.push(t);
}
}
}
/// Every note with its kind: the warnings, then the notes on the options that aren't also
/// warnings.
pub fn kinded_notes(&self) -> Vec<Note> {
let settings = self.setting_notes.iter().filter(|t| !self.warnings.contains(t)).map(Note::setting);
self.warnings.iter().map(Note::loss).chain(settings).collect()
}
/// The notes' texts in the order a reply gives them ([`note_texts`]): the warnings, then the
/// notes on the options, each once.
pub fn notes(&self) -> Vec<String> {
note_texts(&self.kinded_notes())
}
/// Every file to write for the destination `path` (a path or a file name): the file itself
/// when there is one, else `{stem}-{artboard name}.{ext}` beside it (see `joiner`; a file of no artboard
/// among several, as Save's master file, is the file itself), then the linked images beside it
@@ -128,13 +214,14 @@ impl Encoded {
out
}
/// The one file and the warnings, when the export wrote nothing else.
fn single(self, f: &Format) -> Result<(Vec<u8>, Vec<String>)> {
/// The one file and the notes, when the export wrote nothing else.
fn single(self, f: &Format) -> Result<(Vec<u8>, Vec<Note>)> {
if !self.linked.is_empty() || !self.maps.is_empty() {
return Err(bad(C, format!("{} with linked images or an image map writes several files: use document.export", f.label)));
}
let notes = self.kinded_notes();
match <[_; 1]>::try_from(self.files) {
Ok([(_, bytes)]) => Ok((bytes, self.warnings)),
Ok([(_, bytes)]) => Ok((bytes, notes)),
Err(_) => Err(bad(C, format!("{} writes one file per artboard here: use document.export, or name one artboard", f.label))),
}
}
@@ -321,15 +408,31 @@ pub(crate) fn anti_alias(id: &str) -> std::result::Result<AntiAlias, String> {
/// The `useArtboards` param of a PDF, AI, DXF or raster export (SVG has its own): `true` writes every
/// chosen artboard (default all), `false` the bounds of the visible art instead, absent one
/// artboard (raster, DXF) or the chosen pages (PDF, AI).
fn use_artboards(p: &Value) -> Result<Option<bool>> {
/// artboard (raster, DXF) or the chosen pages (PDF, AI). Errors name the command `cmd`.
pub(super) fn use_artboards(cmd: &str, p: &Value) -> Result<Option<bool>> {
match p.get("useArtboards") {
None | Some(Value::Null) => Ok(None),
Some(Value::Bool(b)) => Ok(Some(*b)),
Some(v) => Err(bad(C, format!("useArtboards must be true or false, not {v}"))),
Some(v) => Err(bad(cmd, format!("useArtboards must be true or false, not {v}"))),
}
}
/// With `useArtboards: false` in `p`: `doc` without its opacity-mask or symbol editing layer and
/// with one artboard, the bounds of its visible art, and `p` without the artboard choice. `None`
/// when `useArtboards` is absent, null or true. A document with no visible art is refused.
pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(Document, Value)>> {
if use_artboards(cmd, p)? != Some(false) {
return Ok(None);
}
let doc = &*doc.without_edit_modes();
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?;
let mut q = super::export::without_artboards(p);
if let Some(o) = q.as_object_mut() {
o.remove("useArtboards");
}
Ok(Some((single_artboard(doc, bounds, "Art"), q)))
}
/// The `rect` param of a raster export: `[x, y, width, height]` in points, y down. `None` when
/// absent; an error when it is not four finite numbers with a positive size, when the format isn't
/// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would
@@ -419,8 +522,14 @@ pub fn encode(doc: &Document, format: &str, p: &Value) -> Result<Vec<u8>> {
/// Like [`encode`], also returning the encoder's warnings (PDF and SVG: options not applied yet,
/// features approximated or left out; every format that draws type: fonts written in the fallback
/// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame).
/// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame), what
/// the file loses first ([`note_texts`]).
pub fn encode_with_warnings(doc: &Document, format: &str, p: &Value) -> Result<(Vec<u8>, Vec<String>)> {
encode_with_notes(doc, format, p).map(|(bytes, notes)| (bytes, note_texts(&notes)))
}
/// Like [`encode_with_warnings`], with each note's kind ([`Encoded::kinded_notes`]).
pub fn encode_with_notes(doc: &Document, format: &str, p: &Value) -> Result<(Vec<u8>, Vec<Note>)> {
let f = super::writable(C, Some(format), None)?;
let enc = encode_all(doc, f.id, p)?;
// The error for a version 7 .ai of several artboards names the legacy .ai.
@@ -476,7 +585,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
/// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON
/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else
/// one named after the document) with that path's extension when the plug-in lists it, else its
/// first. Its warnings come back with the file.
/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result<Encoded> {
use vectorcraft_plugins::{Error, export};
let doc = &*doc.without_edit_modes();
@@ -503,7 +612,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
let doc = &*doc.without_edit_modes();
let n = doc.artboards.len();
// SVG reads its own `useArtboards` (an SVG option).
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(p)? } else { None };
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(C, p)? } else { None };
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
if let Some(rect) = page_rect(f, p)? {
let mut q = super::export::without_artboards(p);
@@ -513,13 +622,17 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
}
return encode_files(&single_artboard(doc, rect, "Rect"), f, &q);
}
if use_artboards == Some(false) {
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(C, "nothing to export: the document has no visible art"))?;
let mut q = super::export::without_artboards(p);
if let Some(o) = q.as_object_mut() {
o.remove("useArtboards");
}
return encode_files(&single_artboard(doc, bounds, "Art"), f, &q);
// A PDF of the art's bounds carries no editing data (it would replace the artboards).
if use_artboards == Some(false)
&& f.id == "pdf"
&& let Some((bytes, notes)) = super::pdf::encode_art_page(C, doc, p)?
{
return Ok(Encoded::one_with_notes(bytes, notes));
}
if use_artboards == Some(false)
&& let Some((art, q)) = art_page(C, doc, p)?
{
return encode_files(&art, f, &q);
}
let bytes = match f.id {
"vectorcraft" => super::native::encode(C, f, doc, p)?,
@@ -539,8 +652,8 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
"hpgl" => return super::hpgl::encode(doc, p, use_artboards),
"ai" => return super::save::encode_ai(C, f, doc, p),
"pdf" => {
let (bytes, warnings) = super::pdf::encode(C, doc, p)?;
return Ok(Encoded { warnings, ..Encoded::one(bytes) });
let (bytes, notes) = super::pdf::encode(C, doc, p)?;
return Ok(Encoded::one_with_notes(bytes, notes));
}
"png" | "jpg" | "webp" | "gif" | "png8" | "tiff" | "bmp" | "tga" | "psd" => {
let o: RasterOptions = options(f, p)?;
@@ -607,7 +720,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
let regions: Vec<Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect();
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(&regions)));
if format == RasterFormat::WebP && o.lossless == Some(false) {
enc.warnings.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into());
enc.setting_notes.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into());
}
return Ok(enc);
}
+1
View File
@@ -382,6 +382,7 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
enc.warnings.push(w);
}
}
enc.add_setting_notes(out.setting_notes);
}
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(&regions)));
Ok(enc)
+2 -2
View File
@@ -42,7 +42,7 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
}
_ => json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }),
};
let mut out = merge(data(main.first().map_or(&[][..], |m| &m.1)), json!({ "warnings": enc.warnings }));
let mut out = merge(data(main.first().map_or(&[][..], |m| &m.1)), json!({ "warnings": enc.notes() }));
if main.len() > 1 {
out["files"] = main.iter().map(|(name, bytes)| merge(json!({ "name": name }), data(bytes))).collect();
}
@@ -69,7 +69,7 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("_displayDocTitle".into(), json!(display_doc_title));
}
let enc = encode_all(doc, f.id, &q)?;
write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.warnings }))
write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.notes() }))
}
/// The document an export of `st` in format `f` writes ([`export_source`]): a `.ai` or `.ait`
+11 -8
View File
@@ -782,9 +782,9 @@ pub fn open_extensions() -> &'static [&'static str] {
/// File › Open's filters: "All readable files" first, then one per readable format, then one per
/// importer plug-in (under its name, with the extensions [`open_extensions`] takes from it), then
/// swatch libraries (which open in the library panel), Libraries panel libraries, flattener, PDF,
/// print and export presets (imported), scripts (checked without running them) and plug-ins
/// (installed).
/// swatch and graphic style libraries (which open in their library panels), Libraries panel
/// libraries, flattener, PDF, print, perspective grid and export presets and composite fonts
/// (imported), shortcut sets, scripts (checked without running them) and plug-ins (installed).
pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
let (all, importers) = importer_open_part();
std::iter::once(("All readable files", all)).chain(format_filters()).chain(importers).chain(other_open_filters())
@@ -797,14 +797,17 @@ pub fn builtin_open_filters() -> impl Iterator<Item = (&'static str, &'static [&
std::iter::once(("All readable files", OPEN_EXTS)).chain(format_filters()).chain(other_open_filters())
}
/// The open-dialog filters after the document formats: swatch libraries, Libraries panel
/// libraries, presets, composite fonts, shortcut sets, scripts and plug-ins.
/// The open-dialog filters after the document formats: swatch and graphic style libraries,
/// Libraries panel libraries, presets (perspective grid presets among them), composite fonts,
/// shortcut sets, scripts and plug-ins.
fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once(("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS))
.chain(std::iter::once(("Graphic Style Libraries", std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT))))
.chain(std::iter::once(("Libraries", crate::cmd::library::LIBRARY_EXTS)))
.chain(std::iter::once(("Flattener presets", crate::cmd::flatten::PRESET_EXTS)))
.chain(std::iter::once(("PDF presets", crate::cmd::pdfcmds::PRESET_EXTS)))
.chain(std::iter::once(("Print presets", crate::cmd::printpresets::PRESET_EXTS)))
.chain(std::iter::once(("Perspective grid presets", crate::cmd::perspgrid::PRESET_EXTS)))
.chain(std::iter::once(("Export presets", screens::PRESET_FILE_EXTS)))
.chain(std::iter::once(("Composite fonts", crate::cmd::compositefonts::EXTS)))
.chain(std::iter::once(("Shortcut sets", crate::cmd::shortcutset::EXTS)))
@@ -815,13 +818,13 @@ fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'stati
/// Open-dialog filters for Swatch Libraries and Graphic Style Libraries Other Library… and Locate
/// Library…. The library formats come first so Linux file portals (which grey out files that don't
/// match the default filter) still list `.ase` and the other library extensions; then the same
/// filters as [`builtin_open_filters`] so a document can be picked for its swatches or graphic
/// styles.
/// filters as [`builtin_open_filters`], without a second copy of the library filter, so a document
/// can be picked for its swatches or graphic styles.
pub fn library_open_filters(
library_label: &'static str,
library_exts: &'static [&'static str],
) -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once((library_label, library_exts)).chain(builtin_open_filters())
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts)))
}
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
+1
View File
@@ -116,6 +116,7 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
enc.warnings.push(w);
}
}
enc.add_setting_notes(out.setting_notes);
}
if enc.files.is_empty() {
return Err(bad(C, "the document has no artboard"));
+4 -1
View File
@@ -136,10 +136,12 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
}
let images = see_through_images(&d, mode);
if !images.is_empty() {
note(&mut enc.warnings, if mode == SeeThrough::Flatten { FLATTENED } else { OMITTED });
if mode == SeeThrough::Flatten {
note(&mut enc.warnings, FLATTENED);
flatten_images(&mut d, &images)?;
} else {
// A note on the options: `transparentImages: omit` leaves them out.
enc.add_setting_notes([OMITTED.to_string()]);
for (_, id) in images {
let _ = d.remove(id); // Inside an image left out before: gone already.
}
@@ -150,6 +152,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
for w in placed.iter().chain(&out.warnings) {
note(&mut enc.warnings, w);
}
enc.add_setting_notes(out.setting_notes);
enc.files.push((Some(b), out.bytes));
}
// Expanding raster effects and flattening images draw the art, and an image the renderer
+63 -25
View File
@@ -12,7 +12,7 @@ use vectorcraft_pdf::{Overprint, PdfError, PdfOptions, PdfPreset, PdfSettings, S
use super::super::flatten::{FlattenOptions, flatten_document, see_through_images};
use super::super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
use super::{ArtboardPick, FormatOption, write_or_return};
use super::{ArtboardPick, FormatOption, Note, note_texts, write_or_return};
use crate::EngineError;
const C: &str = "document.exportPdf";
@@ -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), 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; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; 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; 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?: false (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), 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). 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 another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), out 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, 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; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; 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; 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?: false (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), 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). 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 another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdf Line truncated
has_doc,
export_pdf
),
@@ -137,7 +137,7 @@ pub fn specs() -> Vec<CommandSpec> {
"PDF Settings",
[],
None,
"{preset?, includeDocument?: false, …options of document.exportPdf} → {settings (the preset with the options applied), presets: [name…], changed: [{option: \"compression.compressText\", value}] (what differs from the preset), warnings}; includeDocument also exports the active document in memory and adds its warnings (knockout groups approximated, effects left out…). A key PDF doesn't take, and an unknown key inside one of the option objects, are refused",
"{preset?, includeDocument?: false, …options of document.exportPdf} → {settings (the preset with the options applied), presets: [name…], changed: [{option: \"compression.compressText\", value}] (what differs from the preset), warnings}; includeDocument also exports the active document in memory (one page of the art's bounds with useArtboards: false) and adds its warnings (knockout groups approximated, effects left out…). A key PDF doesn't take, and an unknown key inside one of the option objects, are refused",
always,
pdf_settings
),
@@ -280,25 +280,47 @@ fn options_at(cmd: &str, doc: &Document, p: &Value, now: Option<i64>) -> Result<
pub const EDITING_NEEDS_EVERY_ARTBOARD: &str =
"Preserve editing was left out: it needs a PDF of every artboard, in order (reopened, this one would show the others too)";
/// Why a PDF of the art's bounds (`useArtboards: false`) carries no editing data.
pub const EDITING_NEEDS_THE_ARTBOARDS: &str =
"Preserve editing was left out: it needs a PDF of the artboards (reopened, this one would replace them with one artboard around the art)";
/// With `useArtboards: false` in `p`: the PDF of one page, the bounds of `doc`'s visible art
/// ([`super::encode::art_page`]) → (bytes, notes). It carries no editing data: with Preserve
/// Editing on, the notes end with [`EDITING_NEEDS_THE_ARTBOARDS`]. `None` when `p` asks for the
/// artboards.
pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(Vec<u8>, Vec<Note>)>> {
let Some((art, mut q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) };
let left_out = settings(cmd, &q)?.preserve_editing;
if left_out && let Some(o) = q.as_object_mut() {
o.insert("preserveEditing".into(), json!(false));
}
let (bytes, mut notes) = encode(cmd, &art, &q)?;
if left_out {
notes.push(Note::setting(EDITING_NEEDS_THE_ARTBOARDS));
}
Ok(Some((bytes, notes)))
}
/// The warning for a PDF/X file that leaves out the document's bleed
/// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]).
pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings";
/// Encode `doc` as PDF with the options in `p` → (bytes, warnings). Raster effects are rendered
/// Encode `doc` as PDF with the options in `p` → (bytes, notes). Raster effects are rendered
/// to images at the document's raster effects resolution. Preserve Editing embeds `doc` itself
/// when the PDF has every artboard (a PDF of some reopens as just those).
pub fn encode(cmd: &str, doc: &Document, p: &Value) -> Result<(Vec<u8>, Vec<String>)> {
pub fn encode(cmd: &str, doc: &Document, p: &Value) -> Result<(Vec<u8>, Vec<Note>)> {
encode_at(cmd, doc, p, None)
}
/// [`encode`] modified at `modified` (Unix seconds) when given, instead of the time of writing.
pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i64>) -> Result<(Vec<u8>, Vec<String>)> {
pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i64>) -> Result<(Vec<u8>, Vec<Note>)> {
// Keep the editable object tree independent of preview fallbacks used by the drawn pages.
let (full, mut warnings) = crate::cmd::place::document::full_documents(doc);
let (bytes, drawn_warnings) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?;
warnings.extend(drawn_warnings);
warnings.extend(overflow_warning(cmd, &full, p)?);
Ok((bytes, warnings))
let (full, placed) = crate::cmd::place::document::full_documents(doc);
let mut notes: Vec<Note> = placed.into_iter().map(Note::loss).collect();
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?;
notes.extend(drawn);
notes.extend(overflow_warning(cmd, &full, p)?.map(Note::loss));
Ok((bytes, notes))
}
/// The warning about the type that the pages of a PDF of `doc` with the options in `p` draw and
@@ -321,7 +343,7 @@ pub(super) fn encode_carrying(
p: &Value,
native: impl FnOnce() -> Result<Vec<u8>>,
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
) -> Result<(Vec<u8>, Vec<String>)> {
) -> Result<(Vec<u8>, Vec<Note>)> {
encode_carrying_at(cmd, doc, p, None, native, private)
}
@@ -334,7 +356,7 @@ fn encode_carrying_at(
modified: Option<i64>,
native: impl FnOnce() -> Result<Vec<u8>>,
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
) -> Result<(Vec<u8>, Vec<String>)> {
) -> Result<(Vec<u8>, Vec<Note>)> {
let mut opts = options_at(cmd, doc, p, modified.or_else(vectorcraft_doc::metadata::output_time))?;
// The pages' background colors, behind the art (the editing data keeps them as colors).
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
@@ -345,21 +367,22 @@ fn encode_carrying_at(
if opts.settings.thumbnails {
opts.thumbnails = thumbnails(doc, &opts).map_err(|e| pdf_error(cmd, e))?;
}
let mut warnings = vec![];
// The status bar shows the first warning, so this one goes ahead of the flattening note.
let mut notes = vec![];
// A loss, ahead of the flattening note: the PDF/X pages leave out the bleed that Document
// Setup gives.
if opts.settings.leaves_out_bleed(doc) {
warnings.push(BLEED_LEFT_OUT.to_string());
notes.push(Note::loss(BLEED_LEFT_OUT));
}
if opts.settings.preserve_editing {
if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) {
opts.native = Some(native()?);
if let Some((data, lost)) = private()? {
opts.private_data = Some(data);
warnings.extend(lost);
notes.extend(lost.into_iter().map(Note::loss));
}
} else {
opts.settings.preserve_editing = false;
warnings.push(EDITING_NEEDS_EVERY_ARTBOARD.to_string());
notes.push(Note::setting(EDITING_NEEDS_EVERY_ARTBOARD));
}
}
let set = &opts.settings;
@@ -370,12 +393,13 @@ fn encode_carrying_at(
vectorcraft_doc::cancel::check()?;
if flattened {
let kind = if set.standard.flattens() { set.standard.label() } else { set.compatibility.label() };
warnings.push(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset"));
notes.push(Note::loss(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset")));
}
let r = super::super::rasterfx::export_pdf_with_report(flat.as_ref().unwrap_or(doc), &opts).map_err(|e| pdf_error(cmd, e))?;
warnings.extend(r.warnings);
warnings.extend(crate::cmd::fonts::substitution_warning(doc));
Ok((r.bytes, warnings))
notes.extend(r.warnings.into_iter().map(Note::loss));
notes.extend(r.setting_notes.into_iter().map(Note::setting));
notes.extend(crate::cmd::fonts::substitution_warning(doc).map(Note::loss));
Ok((r.bytes, notes))
}
/// The flattener preset of PDF 1.3 files whose `flattenerPreset` is empty.
@@ -479,8 +503,13 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
} else {
q = json!({ "_displayDocTitle": display_doc_title });
}
let (bytes, warnings) = encode(C, titled.as_ref().unwrap_or(&st.doc), &q)?;
write_or_return(str_param(p, "path"), &bytes, json!({ "warnings": warnings }))
// The opacity-mask or symbol editing layer is left out.
let doc = titled.as_ref().unwrap_or(&st.doc).without_edit_modes();
let (bytes, notes) = match encode_art_page(C, &doc, &q)? {
Some(encoded) => encoded,
None => encode(C, &doc, &q)?,
};
write_or_return(str_param(p, "path"), &bytes, json!({ "warnings": note_texts(&notes) }))
}
/// `(path, value)` for every leaf of `v` that differs from `default` (`compression.color.ppi`).
@@ -510,9 +539,18 @@ fn pdf_settings(s: &mut Session, p: &Value) -> Result<Value> {
const Q: &str = "document.pdfSettings";
let saved = &s.prefs.pdf_presets;
let set = settings_with(Q, p, saved)?;
super::encode::use_artboards(Q, p)?;
let diff = changes(&set, &preset_settings(Q, p, saved)?);
let warnings = match s.active() {
Some(st) if bool_or(p, "includeDocument", false) => encode(Q, &st.doc, &*expand_preset(s, Q, p)?)?.1,
Some(st) if bool_or(p, "includeDocument", false) => {
let q = expand_preset(s, Q, p)?;
let doc = st.doc.without_edit_modes();
let (_, notes) = match encode_art_page(Q, &doc, &q)? {
Some(encoded) => encoded,
None => encode(Q, &doc, &q)?,
};
note_texts(&notes)
}
_ => set.warnings(),
};
let v = serde_json::to_value(&set).map_err(|e| EngineError::Other(e.to_string()))?;
+16 -10
View File
@@ -752,12 +752,14 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
carries_editing.set(true);
Ok(Some((data, resolved_warnings)))
};
let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, &params, native, private)?;
warnings.extend(placed_warnings);
let (bytes, notes) = super::pdf::encode_carrying(cmd, &pages, &params, native, private)?;
let mut enc = Encoded::one_with_notes(bytes, notes);
enc.warnings.extend(placed_warnings);
// A note on the options: `pdfCompatible: false` writes blank pages.
if !pdf_compatible {
warnings.push(if carries_editing.get() { NOT_PDF_COMPATIBLE_EDITING } else { NOT_PDF_COMPATIBLE }.to_string());
enc.setting_notes.push(if carries_editing.get() { NOT_PDF_COMPATIBLE_EDITING } else { NOT_PDF_COMPATIBLE }.to_string());
}
Ok(Encoded { warnings, ..Encoded::one(bytes) })
Ok(enc)
}
/// Snapshot the active document for `plan` (stamping File Info's dates on the snapshot when the
@@ -845,8 +847,8 @@ impl SaveJob {
}
/// Encode the file → it (and, with `separateArtboards`, a file per artboard after it), with
/// the warnings (what the format loses first, then the encoder's own notes: PDF options not
/// applied yet…, then the plan's notes on its params).
/// the notes (what the format loses first, then the encoder's own notes: PDF options not
/// applied yet…, then the plan's notes on its params, which are notes on the options).
pub fn encode(&self) -> Result<Encoded> {
let mut enc = self.encode_one(&self.doc)?;
for &b in &self.boards {
@@ -854,7 +856,7 @@ impl SaveJob {
enc.files.extend(one.files.into_iter().map(|(_, bytes)| (Some(b), bytes)));
}
enc.warnings.splice(0..0, self.format_losses());
enc.warnings.extend(self.plan.notes.iter().cloned());
enc.setting_notes.extend(self.plan.notes.iter().cloned());
Ok(enc)
}
@@ -905,9 +907,8 @@ impl SaveJob {
/// order: when `stop` returns a value, nothing is written and that value is returned.
pub fn write_unless(&self, stop: impl FnOnce(&[&str]) -> Option<Value>, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
let (plan, doc) = (&self.plan, &*self.doc);
let mut enc = self.encode()?;
let warnings = std::mem::take(&mut enc.warnings);
let extra = json!({ "format": plan.format.id, "warnings": warnings });
let enc = self.encode()?;
let extra = json!({ "format": plan.format.id, "warnings": enc.notes() });
let Some(path) = &plan.path else {
let mut out = write_encoded(None, &plan.name, doc, &enc, extra)?;
out["name"] = json!(plan.name);
@@ -1031,6 +1032,8 @@ impl SaveJob {
}
// The other open documents that place this one show the new version.
let written = self.plan.path.clone().filter(|_| matches!(self.plan.format.id, "vectorcraft" | "template"));
// A save of the arrowheads file lists its heads in the arrowhead menus.
let native = self.plan.format.id == "vectorcraft";
if let Some(st) = s.document_mut(uid) {
self.finish(st);
}
@@ -1038,6 +1041,9 @@ impl SaveJob {
crate::cmd::recovery::forget(s, uid);
}
if let Some(path) = written {
if native {
s.arrowheads_saved(&path);
}
crate::cmd::links::refresh_placed(s, uid, &path);
}
}
+12 -11
View File
@@ -17,12 +17,12 @@ use vectorcraft_doc::Document;
use vectorcraft_geom::Rect;
use super::super::{EngineError, NodeId, Result, Session, bad, bool_or, str_param};
use super::encode::single_artboard;
use super::encode::{add_note, single_artboard};
use super::export::{export_crop, isolated, selected_artwork, without_artboards};
use super::naming::{self, NameParts};
use super::{
ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names_keeping_dots, create_dir, distinct_names_by, encode_with_warnings, merge,
unique_file_names_keeping_dots, with_black_output, writable, write_file,
ARTBOARD_PARAMS, ArtboardPick, Format, Note, artboard_file_names_keeping_dots, create_dir, distinct_names_by, encode_with_notes, merge,
note_texts, unique_file_names_keeping_dots, with_black_output, writable, write_file,
};
const C: &str = "document.exportForScreens";
@@ -1021,7 +1021,8 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map<Stri
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
/// so do different files that would share a name, with or without the `name` pattern. The reply's
/// `warnings` lists every warning the encoders give for the files, each once.
/// `warnings` lists every warning the encoders give for the files, each once, what the files lose
/// first ([`super::note_texts`]).
pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
check_passwords(p)?;
let o = ScreenParams::of(p)?;
@@ -1140,18 +1141,16 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
create_dir(dir)?;
}
let mut out = Output::default();
// The encoders' warnings for every file, each once.
let mut warnings: Vec<String> = Vec::new();
// The encoders' notes for every file, each once.
let mut notes: Vec<Note> = Vec::new();
// Include Bleed: a grown artboard already holds the bleed. Assets, layers and a selection are
// written on a page of their own bounds, which it doesn't grow.
let bleed_on_page = o.include_bleed && o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
let (bytes, notes) = vectorcraft_doc::cancel::quiet(|| encode_with_warnings(doc, format, options))?;
for w in notes {
if !(bleed_on_page && w == super::pdf::BLEED_LEFT_OUT) && !warnings.contains(&w) {
warnings.push(w);
}
let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?;
for n in given.into_iter().filter(|n| !(bleed_on_page && n.text == super::pdf::BLEED_LEFT_OUT)) {
add_note(&mut notes, n);
}
Ok(bytes)
};
@@ -1226,6 +1225,8 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
if o.zip || folder.is_none() {
vectorcraft_doc::cancel::check()?;
}
// What the files lose first, across every file.
let warnings = note_texts(&notes);
let names: Vec<&str> = out.kept.iter().map(|(n, _)| n.as_str()).collect();
if o.zip {
let zip = super::zip::deflate(&out.kept, super::zip::FIXED_TIME, vectorcraft_doc::cancel::is_cancelled);
+1
View File
@@ -204,6 +204,7 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco
enc.warnings.push(w);
}
}
enc.add_setting_notes(out.setting_notes);
enc.files.push((artboard, if compressed { vectorcraft_svg::compress_bytes(&bytes) } else { bytes }));
}
// Live type names its fonts; outlines and embedded fonts are the fallback font's.
+18 -2
View File
@@ -390,9 +390,20 @@ fn open_exts_cover_every_readable_format() {
assert_eq!(filters[0], ("All readable files", OPEN_EXTS));
assert_eq!(
filters.len(),
11 + FORMATS.iter().filter(|f| f.read).count(),
"and swatch libraries, libraries, flattener, PDF, print and export presets, composite fonts, shortcut sets, scripts, plug-ins"
13 + FORMATS.iter().filter(|f| f.read).count(),
"and swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export presets, composite \
fonts, shortcut sets, scripts, plug-ins"
);
let at = |label: &str| filters.iter().position(|f| f.0 == label).unwrap_or_else(|| panic!("File › Open has no {label} filter"));
let styles: &[&str] = &[vectorcraft_doc::style_libs::STYLES_EXT];
assert_eq!(filters[at("Graphic Style Libraries")].1, styles, "File › Open opens graphic style libraries");
assert_eq!(at("Graphic Style Libraries"), at("Swatch libraries") + 1, "next to the swatch libraries");
assert_eq!(filters[at("Perspective grid presets")].1, crate::cmd::perspgrid::PRESET_EXTS, "File › Open imports perspective grid presets");
assert_eq!(at("Perspective grid presets"), at("Print presets") + 1, "among the presets");
assert_eq!(at("Export presets"), at("Perspective grid presets") + 1, "among the presets");
for e in [vectorcraft_doc::style_libs::STYLES_EXT].iter().chain(crate::cmd::perspgrid::PRESET_EXTS) {
assert!(!filters[0].1.contains(e), "All readable files lists documents only, not .{e}");
}
assert!(filters.contains(&("Export presets", SCREEN_EXPORT_PRESET_EXTS)), "File › Open imports export presets");
assert!(filters.contains(&("Scripts", crate::cmd::scripts::EXTS)), "File › Open checks scripts");
assert_eq!(filters.last(), Some(&("Plug-ins", crate::cmd::plugin::EXTS)), "File › Open installs plug-ins");
@@ -404,6 +415,11 @@ fn library_open_filters_list_library_formats_first() {
assert_eq!(filters[0], ("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS));
assert!(filters[0].1.contains(&"ase"));
assert_eq!(filters[1], ("All readable files", OPEN_EXTS));
let styles: &'static [&'static str] = std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT);
for (label, exts) in [("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS), ("Graphic Style Libraries", styles)] {
let filters: Vec<_> = library_open_filters(label, exts).collect();
assert_eq!(filters.iter().filter(|f| f.0 == label).count(), 1, "{label} is listed once");
}
}
/// The extensions usage texts list for export: one per writable format, each picking that format
+15
View File
@@ -194,6 +194,21 @@ fn placed_images_and_fill_hatches_can_be_left_out() {
let _ = std::fs::remove_dir_all(dir);
}
/// The reply gives what the drawings lose before a note on the options, across the files: the
/// first artboard's drawing notes the fill hatches that `includeHatches: false` leaves out, and
/// the second's also has a see-through rectangle that DXF 2000 writes opaque.
#[test]
fn what_the_drawings_lose_comes_before_what_an_option_left_out() {
let mut s = two_boards();
s.execute("object.setProps", &json!({"opacity": 50})).unwrap();
let r = s.execute("document.export", &json!({"format": "dxf", "version": "2000", "includeHatches": false, "useArtboards": true})).unwrap();
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
let Some((option, losses)) = warnings.split_last() else { panic!("no notes") };
assert!(option.starts_with("fill hatches are left out"), "{warnings:?}");
assert!(losses.iter().any(|w| w.starts_with("transparency needs DXF 2004")), "{warnings:?}");
assert!(!losses.iter().any(|w| w.starts_with("fill hatches")), "each note once: {warnings:?}");
}
/// Two placed images whose pixel data can't be decoded are left out of the drawing and get no
/// linked file, and `warnings` holds the note raster exports give, once, without naming either
/// image's key.
@@ -117,3 +117,35 @@ fn formats_list_use_artboards() {
}
assert!(opts("vectorcraft").get("useArtboards").is_none());
}
/// An export's reply gives what the file loses before its notes on the options, whatever order
/// the encoder gave them: the WebP encoder notes that lossy WebP isn't applied before the export
/// notes the type it drew in the fallback font. With only notes on the options, they keep their
/// order.
#[test]
fn what_the_file_loses_comes_before_a_note_on_the_options() {
let lossy = "lossy WebP isn't available yet: the file is lossless (exact, but larger)";
let warnings = |s: &mut Session, p: Value| -> Vec<String> {
let r = s.execute("document.export", &p).unwrap();
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect()
};
let mut s = session(60.0, 40.0, 1);
assert_eq!(warnings(&mut s, json!({"format": "webp", "lossless": false})), [lossy]);
s.execute("text.create", &json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap();
let w = warnings(&mut s, json!({"format": "webp", "lossless": false}));
assert_eq!(w.len(), 2, "{w:?}");
assert!(w[0].contains("fallback font") && w[0].contains("Nonexistent Sans Probe"), "{w:?}");
assert_eq!(w[1], lossy);
// document.serialize gives them in the same order.
let r = s.execute("document.serialize", &json!({"format": "webp", "lossless": false})).unwrap();
assert_eq!(r["warnings"], json!(w));
}
#[test]
fn note_texts_give_the_losses_first_each_kind_in_order() {
use super::encode::{Note, note_texts};
let notes = [Note::setting("s1"), Note::loss("l1"), Note::setting("s2"), Note::loss("l2")];
assert_eq!(note_texts(&notes), ["l1", "l2", "s1", "s2"]);
assert_eq!(note_texts(&[Note::setting("s1"), Note::setting("s2")]), ["s1", "s2"]);
assert!(note_texts(&[]).is_empty());
}
+120
View File
@@ -56,6 +56,126 @@ fn export_pdf_writes_the_compatibility_header_and_the_range() {
assert!(b64(&v).starts_with(b"%PDF-1.6"));
}
/// `useArtboards: false` writes one page, the bounds of the visible art, as `document.export`
/// does, whatever artboards are chosen. Art longer than 200 in keeps its size with
/// `longPagesInPoints`. A document with no visible art and a value that isn't a boolean are
/// refused.
#[test]
fn use_artboards_false_writes_one_page_of_the_arts_bounds() {
let mut s = session(3);
let page = |bytes: &[u8]| {
let d = vectorcraft_pdf::import(bytes).unwrap();
(d.artboards.len(), d.artboards[0].rect.size())
};
let through_export = page(&b64(&s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap()));
assert!(through_export.0 == 1 && through_export.1.width < 50.0 && through_export.1.height < 40.0, "{through_export:?}");
for p in [
json!({"useArtboards": false}),
json!({"useArtboards": false, "range": "2"}),
json!({"useArtboards": false, "artboards": [0, 1]}),
json!({"useArtboards": false, "artboard": 2}),
] {
assert_eq!(page(&b64(&export(&mut s, p.clone()))), through_export, "{p}");
}
assert_eq!(pages(&b64(&export(&mut s, json!({"useArtboards": true})))), 3);
assert_eq!(pages(&b64(&export(&mut s, json!({"useArtboards": null})))), 3);
// A 10 m drawing on a small artboard: its page is 10 m long, in points.
s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 28_346.46, "height": 100})).unwrap();
let v = export(&mut s, json!({"useArtboards": false, "longPagesInPoints": true}));
let pdf = b64(&v);
let (n, size) = page(&pdf);
assert!(n == 1 && size.width > 28_346.0 && size.width < 28_350.0, "{size:?}");
assert!(!String::from_utf8_lossy(&pdf).contains("/UserUnit"));
assert!(warnings(&v).iter().any(|w| w.contains("written without a UserUnit, in points")), "{v}");
// The Summary's export in memory writes the same page.
let mut long = |p: Value| warnings(&s.execute("document.pdfSettings", &p).unwrap()).iter().any(|w| w.contains("longer than PDF's page limit"));
assert!(long(json!({"includeDocument": true, "useArtboards": false})));
assert!(!long(json!({"includeDocument": true})), "the artboards are small");
let e = s.execute("document.pdfSettings", &json!({"useArtboards": "no"})).unwrap_err();
assert!(matches!(e, crate::EngineError::BadParams { .. }), "without includeDocument too: {e}");
s.execute("select.all", &json!({})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
for p in [json!({"useArtboards": false}), json!({"useArtboards": "no"})] {
let e = s.execute("document.exportPdf", &p).unwrap_err();
assert!(matches!(e, crate::EngineError::BadParams { .. }), "{p}: {e}");
}
}
/// A PDF of the art's bounds carries no Preserve Editing data, through `document.exportPdf`,
/// `document.export` and the Summary's export in memory, and says so in a warning: reopened, its
/// editing data would replace the document's artboards with the one around the art. A PDF of the
/// artboards keeps the data, and it reopens with every artboard. With Preserve Editing off, there
/// is no warning.
#[test]
fn a_pdf_of_the_arts_bounds_carries_no_editing_data() {
let mut s = session(3);
let left_out = |v: &Value| warnings(v).iter().any(|w| w == super::pdf::EDITING_NEEDS_THE_ARTBOARDS);
let art = json!({"useArtboards": false});
for v in [export(&mut s, art.clone()), s.execute("document.export", &as_export(&art)).unwrap()] {
let pdf = b64(&v);
assert!(vectorcraft_pdf::editing(&pdf).is_none(), "{:?}", warnings(&v));
assert!(left_out(&v), "{:?}", warnings(&v));
assert_eq!(pages(&pdf), 1);
}
let summary = s.execute("document.pdfSettings", &json!({"includeDocument": true, "useArtboards": false})).unwrap();
assert!(left_out(&summary), "{summary}");
let quiet = export(&mut s, json!({"useArtboards": false, "preserveEditing": false}));
assert!(!left_out(&quiet), "{:?}", warnings(&quiet));
for v in [export(&mut s, json!({})), export(&mut s, json!({"useArtboards": true}))] {
let editing = vectorcraft_pdf::editing(&b64(&v)).expect("editing data");
let reopened = vectorcraft_format::load(&editing.data).unwrap();
assert_eq!(reopened.artboards.len(), 3);
assert!(!left_out(&v), "{:?}", warnings(&v));
}
}
/// While an opacity mask is edited, a PDF of the art's bounds measures the art without the
/// editing layer, as `document.export` does: a mask shape drawn past the masked object doesn't
/// widen the page.
#[test]
fn a_pdf_of_the_art_leaves_out_the_mask_editing_layer() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let obj = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()["id"].clone();
let mask = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"color": "#ffffff", "ids": [mask]})).unwrap();
s.execute("select.set", &json!({"ids": [obj, mask]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("transparency.editOpacityMask", &json!({})).unwrap();
s.execute("shape.ellipse", &json!({"x": 250, "y": 250, "width": 40, "height": 40})).unwrap();
assert!(s.doc().unwrap().doc.mask_edit.is_some());
let width = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().artboards[0].rect.width();
let through_export = width(&b64(&s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap()));
assert!(through_export < 250.0, "{through_export}");
assert_eq!(width(&b64(&export(&mut s, json!({"useArtboards": false})))), through_export);
}
/// While an opacity mask is edited, a PDF of the artboards leaves out the editing layer too, as
/// `document.export` does: from the drawn page and from the Preserve Editing data.
#[test]
fn a_pdf_of_the_artboards_leaves_out_the_mask_editing_layer() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let obj = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()["id"].clone();
let mask = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"color": "#ffffff", "ids": [mask]})).unwrap();
s.execute("select.set", &json!({"ids": [obj, mask]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("transparency.editOpacityMask", &json!({})).unwrap();
s.execute("shape.ellipse", &json!({"x": 250, "y": 250, "width": 40, "height": 40})).unwrap();
assert!(s.doc().unwrap().doc.mask_edit.is_some());
let nodes = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().node_count();
let plain = json!({"preserveEditing": false});
let through_export = nodes(&b64(&s.execute("document.export", &as_export(&plain)).unwrap()));
assert_eq!(nodes(&b64(&export(&mut s, plain))), through_export, "the drawn page");
let layers = |v: &Value| vectorcraft_format::load(&vectorcraft_pdf::editing(&b64(v)).unwrap().data).unwrap().layers;
let through_export = layers(&s.execute("document.export", &as_export(&json!({}))).unwrap());
assert_eq!(layers(&export(&mut s, json!({}))), through_export, "the Preserve Editing data");
}
#[test]
fn bad_options_are_refused() {
let mut s = session(2);
@@ -56,3 +56,21 @@ fn permissions_without_a_password_warn_and_a_password_applies_them() {
let bytes = vectorcraft_format::base64_decode(locked["dataBase64"].as_str().unwrap()).unwrap();
assert!(String::from_utf8_lossy(&bytes).contains("/Encrypt"));
}
/// The writer notes the permissions it didn't apply before the export notes the type it drew in
/// the fallback font: the reply gives what the file loses first, through both commands.
#[test]
fn the_fallback_font_note_comes_before_the_permissions_note() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
s.execute("text.create", &json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap();
for r in [
s.execute("document.exportPdf", &json!({"security": {"printing": "none"}})).unwrap(),
s.execute("document.export", &json!({"format": "pdf", "security": {"printing": "none"}})).unwrap(),
] {
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
let at = |s: &str| warnings.iter().position(|w| w.contains(s));
let (font, permissions) = (at("Nonexistent Sans Probe"), at("permissions need a password"));
assert!(font.is_some() && permissions.is_some() && font < permissions, "{warnings:?}");
}
}
@@ -507,6 +507,22 @@ fn type_in_a_missing_family_is_named_once_for_every_format() {
assert!(fallback[0].contains("Nonexistent Sans Probe"), "{fallback:?}");
}
/// What a later file loses comes before a note on the options that an earlier file gave: the
/// first artboard's WebP gives only the lossy WebP note, the second's also says its type doesn't
/// fit.
#[test]
fn what_any_file_loses_comes_before_the_notes_on_the_options() {
let mut s = session(2);
let second = s.doc().unwrap().doc.artboards[1].rect;
let area = json!({"width": 30, "height": 8});
s.execute("text.create", &json!({"x": second.x0 + 2.0, "y": second.y0 + 2.0, "size": 12, "area": area, "text": "Ab\nCd\nEf\nGh"})).unwrap();
let r = export(&mut s, json!({"formats": [{"format": "webp", "lossless": false}]}));
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(warnings[0].contains("doesn't fit its frame"), "{warnings:?}");
assert!(warnings[1].starts_with("lossy WebP"), "{warnings:?}");
}
#[test]
fn full_document_gives_one_file_per_format() {
let mut s = session(3);
+2 -2
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Missing Fonts",
[],
None,
"{} → {fonts: [{family, style, status: missing|substitute, resolved: {family, style}}] (sorted by name; at most 1000), count, fontsNextToDocument?} the fonts the active document's type uses, in its layers and its symbols (for type in a composite font, the fonts of the parts its characters are drawn in), that aren't available as named: missing (the family is unknown and the fallback family stands in) or substitute (the family is there but not the style; resolved names the stand-in), as text.fonts says. CSS generic families such as sans-serif and names longer than 256 bytes are left out. fontsNextToDocument: the Fonts folder next to the saved document (File › Package writes it), when there is one and a search may start there (not in another app's folders, such as a mail app's attachments)",
"{} → {fonts: [{family, style, status: missing|substitute, resolved: {family, style}}] (sorted by name; at most 1000), count, fontsNextToDocument?} the fonts the active document's type uses, in its layers, its symbols and its patterns, opacity masks included (for type in a composite font, the fonts of the parts its characters are drawn in), that aren't available as named: missing (the family is unknown and the fallback family stands in) or substitute (the family is there but not the style; resolved names the stand-in), as text.fonts says. CSS generic families such as sans-serif and names longer than 256 bytes are left out. fontsNextToDocument: the Fonts folder next to the saved document (File › Package writes it), when there is one and a search may start there (not in another app's folders, such as a mail app's attachments)",
has_doc,
missing
),
@@ -103,7 +103,7 @@ pub struct MissingFont {
pub resolved: Option<(String, String)>,
}
/// The fonts the type of `d` uses, in its layers and its symbols (a composite font's parts, those
/// The fonts the type of `d` uses, in its layers, symbols and patterns, opacity masks included (a composite font's parts, those
/// its characters are drawn in, in place of its name), that aren't available as named (sorted by family and style, each once whatever version its type names; at most 1000). CSS generic families such as `sans-serif`
/// ([`GENERIC_FAMILIES`]) and names longer than 256 bytes are left out.
pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
+617 -177
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fonts in Document",
[],
None,
"{selectionOnly?} (the type in the art of the symbols in scope included: all of the document's, or those the selected instances show) → [{family, style, runs, objects, missing, status: exact|substitute|missing, resolved: {family, style}, missingGlyphs, version?: the installed version the type names (when it names one)}] sorted by name. A font is found by any of its names (ヒラギノ角ゴシック = Hiragino Sans) among the loaded and installed fonts; substitute: the family is there but not the style (resolved names the stand-in); missing: the family is unknown (the fallback family stands in); missingGlyphs: characters of its text the resolved font lacks (drawn by a fallback font). For a composite font, status is the worst among the parts its characters are drawn in, and missingGlyphs counts the characters their part's font lacks",
"{selectionOnly?} (the type in the opacity masks of the objects in scope and in the art of the symbols and patterns in scope included: all of the document's, a pattern swatch that nothing paints included, or those the selected objects show through their instances and paints; disabled masks too) → [{family, style, runs, objects, missing, status: exact|substitute|missing, resolved: {family, style}, missingGlyphs, version?: the installed version the type names (when it names one)}] sorted by name. A font is found by any of its names (ヒラギノ角ゴシック = Hiragino Sans) among the loaded and installed fonts; substitute: the family is there but not the style (resolved names the stand-in); missing: the family is unknown (the fallback family stands in); missingGlyphs: characters of its text the resolved font lacks (drawn by a fallback font). For a composite font, status is the worst among the parts its characters are drawn in, and missingGlyphs counts the characters their part's font lacks",
has_doc,
fonts
),
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Font",
[],
None,
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name, a composite font's as its own name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the art of the symbols in scope changes too (all of the document's, or those the selected instances show, so every instance of them follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's art), or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name, a composite font's as its own name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the opacity masks of the objects in scope (disabled masks too) and in the art of the symbols and patterns in scope changes too (all of the document's, or those the selected objects show through their instances and paints, so every instance of a symbol and every object a pattern paints follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's, pattern's or mask's art), in the mask of a hidden or locked object, or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
has_doc,
replace
),
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Text by Font",
[],
None,
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, and the instances of the symbols whose art uses it, that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the objects painted with a pattern whose art uses it and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
has_doc,
select_font
),
@@ -64,15 +64,23 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// Text objects in scope: the selection's (and their descendants') or the whole document's.
fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> {
/// Text objects in scope: the selection's (and their descendants') or the whole document's, and
/// the objects among them that have an opacity mask (not the object whose mask is being edited:
/// its art is on the editing layer).
fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<(Vec<NodeId>, Vec<NodeId>)> {
let st = s.doc()?;
let mut v = vec![];
let editing = st.doc.mask_edit.map(|m| m.object);
let (mut texts, mut masked) = (vec![], vec![]);
let mut seen = HashSet::new();
let mut add = |n: &vectorcraft_doc::Node| {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::Text(_)) && seen.insert(c.id) {
v.push(c.id);
if seen.insert(c.id) {
if matches!(c.kind, NodeKind::Text(_)) {
texts.push(c.id);
}
if c.extras().mask.is_some() && Some(c.id) != editing {
masked.push(c.id);
}
}
})
};
@@ -87,7 +95,7 @@ fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Resu
add(l);
}
}
Ok(v)
Ok((texts, masked))
}
/// Whether `name` is the symbol being edited, whose art is on the editing layer.
@@ -95,106 +103,269 @@ fn being_edited(d: &Document, name: &str) -> bool {
d.symbol_edit.as_ref().is_some_and(|e| e.symbol == name)
}
/// The symbols that the selected objects of `s` show: those of the instances among them and their
/// descendants, and of the instances in those symbols' art that are not hidden or locked, nor in a
/// hidden or locked group of the art. Returned as (all of them, those shown by instances the
/// Selection tool can reach: not hidden or locked, as `Document::editable` says).
fn selected_symbols(s: &Session, selected: Option<&[NodeId]>) -> Result<(BTreeSet<String>, BTreeSet<String>)> {
fn open_instances(n: &Node, out: &mut BTreeSet<String>) {
/// Whether `name` is the pattern being edited, whose tile art is on the editing layer.
fn pattern_being_edited(d: &Document, name: &str) -> bool {
d.pattern_edit.as_ref().is_some_and(|e| e.pattern == name)
}
/// The patterns that the fills and strokes `n` draws name (of a text object, also those of its
/// characters): visible ones, and strokes wider than 0.
fn paint_patterns(n: &Node) -> impl Iterator<Item = &str> {
let runs = match &n.kind {
NodeKind::Text(t) => t.runs.as_slice(),
_ => &[],
};
n.appearance
.items
.iter()
.filter(|i| i.visible() && !matches!(i, AppearanceItem::Stroke(s) if s.width <= 0.0))
.map(AppearanceItem::paint)
.chain(runs.iter().flat_map(|r| [Some(&r.style.fill), (r.style.stroke_width > 0.0).then_some(&r.style.stroke)]).flatten())
.filter_map(|p| match p {
Paint::Pattern { pattern, .. } => Some(pattern.as_str()),
_ => None,
})
}
/// Symbols and patterns, by name: those whose art is in scope.
#[derive(Clone, Debug, Default)]
struct Resources {
symbols: BTreeSet<String>,
patterns: BTreeSet<String>,
}
impl Resources {
/// Adds what `n` itself shows: the symbol of an instance, the patterns its paints name, and
/// what the art of its opacity mask shows (not hidden or locked objects of that art).
fn add_own(&mut self, n: &Node) {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
self.symbols.insert(symbol.clone());
}
self.patterns.extend(paint_patterns(n).map(str::to_string));
if let Some(m) = n.extras().mask.as_deref() {
self.add(&m.art);
}
}
/// Adds what `n` and its descendants show, leaving out hidden or locked objects and what they
/// hold.
fn add(&mut self, n: &Node) {
if !n.visible || n.locked {
return;
}
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
out.insert(symbol.clone());
}
self.add_own(n);
for c in n.children().map(Vec::as_slice).unwrap_or_default() {
open_instances(c, out);
self.add(c);
}
}
let expand = |names: &mut BTreeSet<String>, d: &Document| loop {
let mut more = BTreeSet::new();
for sym in d.symbols.iter().filter(|sym| names.contains(&sym.name)) {
open_instances(&sym.art, &mut more);
/// Adds what the art of the symbols and patterns named shows, until nothing more is added; each
/// symbol and pattern is read once, so art that shows itself ends.
fn expand(&mut self, d: &Document) {
let mut symbols: Vec<String> = self.symbols.iter().cloned().collect();
let mut patterns: Vec<String> = self.patterns.iter().cloned().collect();
while !symbols.is_empty() || !patterns.is_empty() {
let mut more = Resources::default();
for name in symbols.drain(..) {
if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) {
more.add(&sym.art);
}
}
for name in patterns.drain(..) {
for art in d.pattern(&name).map(|p| p.art.as_slice()).unwrap_or_default() {
more.add(art);
}
}
symbols.extend(more.symbols.into_iter().filter(|name| self.symbols.insert(name.clone())));
patterns.extend(more.patterns.into_iter().filter(|name| self.patterns.insert(name.clone())));
}
let before = names.len();
names.extend(more);
if names.len() == before {
break;
}
/// The symbols and patterns of `self` that are not in `other`.
fn difference(&self, other: &Self) -> Self {
Self {
symbols: self.symbols.difference(&other.symbols).cloned().collect(),
patterns: self.patterns.difference(&other.patterns).cloned().collect(),
}
};
}
}
/// The symbols and patterns that the selected objects of `s` show: those of the instances among
/// them and their descendants and the patterns their paints name (also in the art of their
/// opacity masks), and those that the art of these symbols and patterns shows through objects that
/// are not hidden or locked, nor in a hidden or locked group of the art. Returned as (all of them,
/// those shown by objects the Selection tool can reach: not hidden or locked, as
/// `Document::editable` says).
fn selected_art(s: &Session, selected: Option<&[NodeId]>) -> Result<(Resources, Resources)> {
let st = s.doc()?;
let (mut all, mut open) = (BTreeSet::new(), BTreeSet::new());
let (mut all, mut open) = (Resources::default(), Resources::default());
let editable = st.doc.editable();
for id in selected.unwrap_or(&st.selection.objects) {
if let Some(n) = st.doc.node(*id) {
n.walk(&mut |c| {
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
all.insert(symbol.clone());
if editable(c.id) {
open.insert(symbol.clone());
}
all.add_own(c);
if editable(c.id) {
open.add_own(c);
}
});
}
}
drop(editable);
expand(&mut all, &st.doc);
expand(&mut open, &st.doc);
all.expand(&st.doc);
open.expand(&st.doc);
Ok((all, open))
}
/// The text objects in the art of `d`'s symbols (with `only`, of those it names), each with
/// whether it is open: neither it nor a group around it in the art is hidden or locked. The symbol
/// being edited is left out: its art is on the editing layer.
pub(super) fn symbol_texts<'a>(d: &'a Document, only: Option<&BTreeSet<String>>) -> Vec<(&'a TextObject, bool)> {
fn visit<'a>(n: &'a Node, open: bool, out: &mut Vec<(&'a TextObject, bool)>) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &n.kind {
out.push((&**t, open));
}
for c in n.children().map(Vec::as_slice).unwrap_or_default() {
visit(c, open, out);
}
/// A text object found in art: its id, the text and whether it is open (neither it nor a group
/// around it, nor an object whose opacity mask holds it, is hidden or locked).
pub(super) type ArtText<'a> = (NodeId, &'a TextObject, bool);
/// Adds the text objects of `n` and its descendants, the art of their opacity masks included, to
/// `out`; each is open when `open` holds and [`ArtText`] says so.
fn art_texts<'a>(n: &'a Node, open: bool, out: &mut Vec<ArtText<'a>>) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &n.kind {
out.push((n.id, &**t, open));
}
if let Some(m) = n.extras().mask.as_deref() {
art_texts(&m.art, open, out);
}
for c in n.children().map(Vec::as_slice).unwrap_or_default() {
art_texts(c, open, out);
}
}
/// The text objects in the art of the opacity masks of the objects `masked` (each with whether
/// the object is open: when it isn't, none of its mask's text is).
fn mask_texts<'a>(d: &'a Document, masked: &[(NodeId, bool)]) -> Vec<ArtText<'a>> {
let mut out = vec![];
for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.contains(&s.name))) {
visit(&s.art, true, &mut out);
for (id, open) in masked {
if let Some(m) = d.node(*id).and_then(|n| n.extras().mask.as_deref()) {
art_texts(&m.art, *open, &mut out);
}
}
out
}
/// Calls `f` on each text object in the art of `d`'s symbols (with `only`, of those it names) for
/// which `wants(text, open)` holds (open as in [`symbol_texts`]), the symbol being edited left out.
/// Art without such text is left as it is.
pub(super) fn edit_symbol_texts(
d: &mut Document,
only: Option<&BTreeSet<String>>,
wants: &impl Fn(&TextObject, bool) -> bool,
f: &mut impl FnMut(&mut TextObject),
) {
fn wanted(n: &Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool) -> bool {
let open = open && n.visible && !n.locked;
matches!(&n.kind, NodeKind::Text(t) if wants(t, open)) || n.children().is_some_and(|ch| ch.iter().any(|c| wanted(c, open, wants)))
/// The text objects in the art of `d`'s symbols and patterns (with `only`, of those it names, a
/// pattern's art read once however many objects it paints), opacity masks in that art included.
/// The symbol and the pattern being edited are left out: their art is on the editing layer.
fn resource_texts<'a>(d: &'a Document, only: Option<&Resources>) -> Vec<ArtText<'a>> {
let mut out = vec![];
for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.symbols.contains(&s.name))) {
art_texts(&s.art, true, &mut out);
}
fn visit(n: &mut Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &mut n.kind
&& wants(t, open)
{
f(t);
for p in d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name) && only.is_none_or(|o| o.patterns.contains(&p.name))) {
for art in &p.art {
art_texts(art, true, &mut out);
}
for c in n.children_mut().into_iter().flatten() {
if wanted(c, open, wants) {
visit(Arc::make_mut(c), open, wants, f);
}
out
}
/// The text objects in the art of `d`'s symbols (with `only`, of those it names), as
/// [`resource_texts`] finds them, each with whether it is open.
#[cfg(test)]
pub(super) fn symbol_texts<'a>(d: &'a Document, only: Option<&BTreeSet<String>>) -> Vec<(&'a TextObject, bool)> {
let mut out = vec![];
for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.contains(&s.name))) {
art_texts(&s.art, true, &mut out);
}
out.into_iter().map(|(_, t, open)| (t, open)).collect()
}
/// Whether `n` or a descendant (the art of their opacity masks included) holds a text object for
/// which `wants(text, open)` holds, open as [`ArtText`] says.
fn wanted(n: &Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool) -> bool {
let open = open && n.visible && !n.locked;
matches!(&n.kind, NodeKind::Text(t) if wants(t, open))
|| n.extras().mask.as_deref().is_some_and(|m| wanted(&m.art, open, wants))
|| n.children().is_some_and(|ch| ch.iter().any(|c| wanted(c, open, wants)))
}
/// Calls `f` on each text object of `n` and its descendants (the art of their opacity masks
/// included) for which `wants(text, open)` holds; only the nodes on the way to such text are
/// copied.
fn edit_art(n: &mut Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &mut n.kind
&& wants(t, open)
{
f(t);
}
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& wanted(&m.art, open, wants)
{
edit_art(Arc::make_mut(&mut m.art), open, wants, f);
}
for c in n.children_mut().into_iter().flatten() {
if wanted(c, open, wants) {
edit_art(Arc::make_mut(c), open, wants, f);
}
}
}
/// Calls `f` on each text object in the opacity masks of the objects `masked` (as [`mask_texts`]
/// finds them) for which `wants(text, open)` holds. Masks without such text are left as they are.
fn edit_mask_texts(d: &mut Document, masked: &[(NodeId, bool)], wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
for (id, open) in masked {
if d.node(*id).and_then(|n| n.extras().mask.as_deref()).is_some_and(|m| wanted(&m.art, *open, wants))
&& let Some(m) = d.node_mut(*id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut())
{
edit_art(Arc::make_mut(&mut m.art), *open, wants, f);
}
}
}
/// Calls `f` on each text object in the art of `d`'s symbols and patterns (as [`resource_texts`]
/// finds them) for which `wants(text, open)` holds. Art without such text is left as it is.
fn edit_resource_texts(d: &mut Document, only: Option<&Resources>, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
let symbol = d.symbol_edit.as_ref().map(|e| e.symbol.clone());
let pattern = d.pattern_edit.as_ref().map(|e| e.pattern.clone());
for s in &mut d.symbols {
if symbol.as_ref() != Some(&s.name) && only.is_none_or(|o| o.symbols.contains(&s.name)) && wanted(&s.art, true, wants) {
edit_art(Arc::make_mut(&mut s.art), true, wants, f);
}
}
for p in &mut d.patterns {
if pattern.as_ref() != Some(&p.name) && only.is_none_or(|o| o.patterns.contains(&p.name)) {
for art in &mut p.art {
if wanted(art, true, wants) {
edit_art(Arc::make_mut(art), true, wants, f);
}
}
}
}
let edited = d.symbol_edit.as_ref().map(|e| e.symbol.clone());
for s in &mut d.symbols {
if edited.as_ref() != Some(&s.name) && only.is_none_or(|o| o.contains(&s.name)) && wanted(&s.art, true, wants) {
visit(Arc::make_mut(&mut s.art), true, wants, f);
}
/// Every text object of `d` outside the objects of its layers: in the opacity masks of the
/// objects on its layers, and in the art of its symbols and patterns (as [`mask_texts`] and
/// [`resource_texts`] find them, each mask's text open).
pub(super) fn art_texts_of(d: &Document) -> Vec<ArtText<'_>> {
let masked = masked_objects(d);
let mut out = mask_texts(d, &masked);
out.extend(resource_texts(d, None));
out
}
/// Calls `f` on each text object of [`art_texts_of`] for which `wants(text)` holds.
pub(super) fn edit_art_texts_of(d: &mut Document, wants: &impl Fn(&TextObject) -> bool, f: &mut impl FnMut(&mut TextObject)) {
let masked = masked_objects(d);
edit_mask_texts(d, &masked, &|t, _| wants(t), f);
edit_resource_texts(d, None, &|t, _| wants(t), f);
}
/// The objects on the layers of `d` that have an opacity mask (not the object whose mask is being
/// edited), each as open.
fn masked_objects(d: &Document) -> Vec<(NodeId, bool)> {
let editing = d.mask_edit.map(|m| m.object);
let mut out = vec![];
d.walk(|n| {
if n.extras().mask.is_some() && Some(n.id) != editing {
out.push((n.id, true));
}
}
});
out
}
/// A font as type names it: family, style and, when it names one, the installed version.
@@ -218,14 +389,16 @@ pub(super) fn run_fonts(r: &TextRun) -> Vec<UsedFont> {
}
}
/// The fonts (family, style, version) the type in the layers and symbols of `d` is drawn in, a
/// composite font's parts in place of its name ([`run_fonts`]).
/// The fonts (family, style, version) the type in the layers, symbols and patterns of `d` is drawn
/// in, the type in opacity masks included, a composite font's parts in place of its name
/// ([`run_fonts`]).
pub(super) fn used_fonts(d: &Document) -> BTreeSet<UsedFont> {
art_fonts(d, &[])
}
/// The fonts (family, style, version) of the type in the layers and symbols of `d` and in `art`
/// (art read from a file, its resources in `d`).
/// The fonts (family, style, version) of the type in the layers, symbols and patterns of `d` and
/// in `art` (art read from a file, its resources in `d`), the type in opacity masks included. The
/// pattern being edited is read from the editing layer only.
pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
let mut fonts = BTreeSet::new();
let mut add = |n: &Node| {
@@ -233,12 +406,9 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
fonts.extend(t.runs.iter().flat_map(run_fonts));
}
};
d.walk(&mut add);
for s in &d.symbols {
s.art.walk(&mut add);
}
for n in art {
n.walk(&mut add);
let patterns = d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name)).flat_map(|p| p.art.iter().map(|a| &**a));
for n in d.layers.iter().map(|l| &**l).chain(d.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(art) {
vectorcraft_doc::swatches::walk_with_masks(n, &mut add);
}
fonts
}
@@ -513,50 +683,78 @@ impl Session {
pub fn skipped_font_ids(&self, params: &Value, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> {
let (family, style) = font_param(params, "from", "text.replaceFont")?;
let selection_only = bool_or(params, "selectionOnly", false);
let selected_symbols = selection_only.then(|| selected_symbols(self, selected)).transpose()?;
let d = &self.doc()?.doc;
let other: Vec<NodeId> = {
let editable = d.editable();
scope(self, selection_only, selected)?.into_iter().filter(|id| !editable(*id)).collect()
};
let in_scope = ReplaceScope::read(self, selection_only, selected)?;
let uses = |t: &TextObject| {
t.runs.iter().any(|r| {
r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|name| r.style.font_style.eq_ignore_ascii_case(name))
})
};
let mut ids = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).collect::<Vec<_>>();
fn visit(n: &Node, open: bool, closed: bool, uses: &impl Fn(&TextObject) -> bool, ids: &mut Vec<NodeId>) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &n.kind
&& (!open || closed)
&& uses(t)
{
ids.push(n.id);
}
for child in n.children().map(Vec::as_slice).unwrap_or_default() {
visit(child, open, closed, uses, ids);
}
Ok(in_scope.skipped(&self.doc()?.doc, &uses))
}
}
/// What Replace Font looks at: the text objects in scope that the Selection tool can reach and
/// those it can't, the objects with an opacity mask (each with whether it can reach them), and the
/// symbols and patterns whose art is in scope (`None`: all of the document's) with those shown
/// only by hidden or locked objects of the selection.
struct ReplaceScope {
ids: Vec<NodeId>,
other: Vec<NodeId>,
masked: Vec<(NodeId, bool)>,
resources: Option<Resources>,
closed: Resources,
}
impl ReplaceScope {
fn read(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<Self> {
// With selectionOnly: the symbols and patterns the selection shows; those shown only by
// hidden or locked objects keep their type, counted in `skipped`.
let (resources, closed) = if selection_only {
let (all, open) = selected_art(s, selected)?;
let closed = all.difference(&open);
(Some(open), closed)
} else {
(None, Resources::default())
};
let d = &s.doc()?.doc;
let editable = d.editable();
let (texts, masked) = scope(s, selection_only, selected)?;
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = texts.into_iter().partition(|id| editable(*id));
let masked = masked.into_iter().map(|id| (id, editable(id))).collect();
Ok(Self { ids, other, masked, resources, closed })
}
/// The text objects in the art of opacity masks, symbols and patterns in scope.
fn art<'a>(&self, d: &'a Document) -> Vec<ArtText<'a>> {
let mut texts = mask_texts(d, &self.masked);
texts.extend(resource_texts(d, self.resources.as_ref()));
texts
}
/// The text objects in scope set in a font `uses` matches that Replace Font leaves as they are:
/// those the Selection tool can't reach, hidden or locked text in art, and the text of the
/// symbols and patterns shown only by hidden or locked objects of the selection.
fn skipped(&self, d: &Document, uses: &impl Fn(&TextObject) -> bool) -> Vec<NodeId> {
let mut ids: Vec<NodeId> = self.other.iter().copied().filter(|id| text(d, *id).is_some_and(uses)).collect();
ids.extend(self.art(d).into_iter().filter(|(_, t, open)| !open && uses(t)).map(|(id, ..)| id));
if !self.closed.symbols.is_empty() || !self.closed.patterns.is_empty() {
ids.extend(resource_texts(d, Some(&self.closed)).into_iter().filter(|(_, t, _)| uses(t)).map(|(id, ..)| id));
}
for symbol in d
.symbols
.iter()
.filter(|symbol| !being_edited(d, &symbol.name) && selected_symbols.as_ref().is_none_or(|(all, _)| all.contains(&symbol.name)))
{
let closed = selected_symbols.as_ref().is_some_and(|(_, open)| !open.contains(&symbol.name));
visit(&symbol.art, true, closed, &uses, &mut ids);
}
Ok(ids)
ids
}
}
fn font_inventory(s: &Session, selected: Option<&[NodeId]>) -> Result<Value> {
let ids = scope(s, selected.is_some(), selected)?;
let (ids, masked) = scope(s, selected.is_some(), selected)?;
let d = &s.doc()?.doc;
let db = vectorcraft_text::FontDb::global();
// The type in the art of the symbols in scope too: all of them, or those the selection shows.
let symbols = if selected.is_some() { Some(selected_symbols(s, selected)?.0) } else { None };
// The type in the art of the opacity masks of the objects in scope, and of the symbols and
// patterns in scope: all of them, or those the selection shows.
let resources = if selected.is_some() { Some(selected_art(s, selected)?.0) } else { None };
let mut texts: Vec<&TextObject> = ids.iter().filter_map(|id| text(d, *id)).collect();
texts.extend(symbol_texts(d, symbols.as_ref()).into_iter().map(|(t, _)| t));
let masked: Vec<(NodeId, bool)> = masked.into_iter().map(|id| (id, true)).collect();
texts.extend(mask_texts(d, &masked).into_iter().map(|(_, t, _)| t));
texts.extend(resource_texts(d, resources.as_ref()).into_iter().map(|(_, t, _)| t));
// Each font's runs, objects and the text of its runs.
let mut found: BTreeMap<UsedFont, (usize, usize, Vec<&str>)> = BTreeMap::new();
for t in texts {
@@ -617,21 +815,6 @@ fn font_param(p: &Value, k: &str, c: &str) -> Result<(String, Option<String>)> {
Ok((family.to_string(), v.get("style").and_then(Value::as_str).map(str::to_string)))
}
fn skipped_font_texts(
d: &Document,
other: &[NodeId],
symbols: &[(&TextObject, bool)],
closed: &BTreeSet<String>,
uses: &impl Fn(&TextObject) -> bool,
) -> usize {
let mut skipped = other.iter().filter(|id| text(d, **id).is_some_and(uses)).count();
skipped += symbols.iter().filter(|(t, open)| !open && uses(t)).count();
if !closed.is_empty() {
skipped += symbol_texts(d, Some(closed)).into_iter().filter(|(t, _)| uses(t)).count();
}
skipped
}
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.replaceFont";
let (ff, fs) = font_param(p, "from", C)?;
@@ -660,35 +843,25 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
};
// Only text the Selection tool can reach changes: not hidden or locked, in a hidden or locked
// group or layer, or on a locked artboard. The text left in the font is counted. The type in
// the art of the symbols in scope (all of them, or those the selection shows) changes too,
// unless it or a group around it in the art is hidden or locked.
// the opacity masks of the objects in scope, and in the art of the symbols and patterns in
// scope (all of them, or those the selection shows), changes too, unless it, a group around it
// in the art or the object whose mask holds it is hidden or locked.
let selection_only = bool_or(p, "selectionOnly", false);
// With selectionOnly: the symbols the selection shows; those shown only by hidden or locked
// instances keep their type, counted in `skipped`.
let (symbols, closed) = if selection_only {
let (all, open) = selected_symbols(s, None)?;
let closed: BTreeSet<String> = all.difference(&open).cloned().collect();
(Some(open), closed)
} else {
(None, BTreeSet::new())
};
let uses = |t: &TextObject| t.runs.iter().any(|r| matches(&r.style));
// Whether a run of `t` changes.
let changes = |t: &TextObject| t.runs.iter().any(|r| new_style(&r.style).is_some());
let (ids, skipped, in_symbols) = {
let in_scope = ReplaceScope::read(s, selection_only, None)?;
let (ids, skipped, in_art) = {
let d = &s.doc()?.doc;
let editable = d.editable();
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only, None)?.into_iter().partition(|id| editable(*id));
let texts = symbol_texts(d, symbols.as_ref());
let skipped = skipped_font_texts(d, &other, &texts, &closed, &uses);
let skipped = in_scope.skipped(d, &uses).len();
// The text that changes: when none does, the document and its undo history stay as they are.
let ids: Vec<NodeId> = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect();
let in_symbols = texts.iter().any(|(t, open)| *open && changes(t));
(ids, skipped, in_symbols)
let ids: Vec<NodeId> = in_scope.ids.iter().copied().filter(|id| text(d, *id).is_some_and(changes)).collect();
let in_art = in_scope.art(d).iter().any(|(_, t, open)| *open && changes(t));
(ids, skipped, in_art)
};
// The fonts the replaced runs are set in, for the warning.
let mut set = BTreeSet::new();
let n = if ids.is_empty() && !in_symbols {
let n = if ids.is_empty() && !in_art {
0
} else {
s.edit("Replace Font", |d, _| {
@@ -717,7 +890,9 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
replace_in(t);
}
}
edit_symbol_texts(d, symbols.as_ref(), &|t, open| open && changes(t), &mut replace_in);
let wants = |t: &TextObject, open: bool| open && changes(t);
edit_mask_texts(d, &in_scope.masked, &wants, &mut replace_in);
edit_resource_texts(d, in_scope.resources.as_ref(), &wants, &mut replace_in);
Ok(n)
})?
};
@@ -734,13 +909,26 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// Whether `n` or a descendant that is not hidden or locked, nor in a hidden or locked group,
/// shows type in a font `uses` matches: text set in it, an instance of a symbol in `found`, a paint
/// naming a pattern in `found`, or such type in the art of its opacity mask.
fn reaches(n: &Node, uses: &impl Fn(&TextObject) -> bool, found: &Resources) -> bool {
n.visible
&& !n.locked
&& (matches!(&n.kind, NodeKind::Text(t) if uses(t))
|| matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol))
|| paint_patterns(n).any(|p| found.patterns.contains(p))
|| n.extras().mask.as_deref().is_some_and(|m| reaches(&m.art, uses, found))
|| n.children().is_some_and(|ch| ch.iter().any(|c| reaches(c, uses, found))))
}
/// What Replace Font says when it left text in the font that it can't reach.
const REPLACE_SKIPPED: &str = "some text is hidden or locked, so its font wasn't replaced";
fn select_font(s: &mut Session, p: &Value) -> Result<Value> {
let family = str_param(p, "family").ok_or_else(|| bad("select.font", "missing `family`"))?.to_string();
let style = str_param(p, "style").map(str::to_string);
let ids = scope(s, false, None)?;
let (ids, masked) = scope(s, false, None)?;
let d = &s.doc()?.doc;
let within = FontScope::read(d, p)?;
// Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group
@@ -752,37 +940,40 @@ fn select_font(s: &mut Session, p: &Value) -> Result<Value> {
.any(|r| r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|x| r.style.font_style.eq_ignore_ascii_case(x)))
};
let mut hits: Vec<NodeId> = ids.into_iter().filter(|id| editable(*id) && text(d, *id).is_some_and(uses)).collect();
// The symbols whose art uses the font in type that is not hidden or locked, nor in a hidden or
// locked group of the art, also through the instances of other symbols it holds.
fn reaches(n: &Node, uses: &impl Fn(&TextObject) -> bool, symbols: &BTreeSet<&str>) -> bool {
n.visible
&& !n.locked
&& match &n.kind {
NodeKind::Text(t) => uses(t),
NodeKind::SymbolInstance { symbol, .. } => symbols.contains(symbol.as_str()),
_ => n.children().is_some_and(|ch| ch.iter().any(|c| reaches(c, uses, symbols))),
}
}
let mut symbols: BTreeSet<&str> = BTreeSet::new();
// The symbols and patterns whose art uses the font in type that is not hidden or locked, nor in
// a hidden or locked group of the art, also through the instances, patterns and opacity masks
// it holds. The pattern being edited is left out: its art is on the editing layer.
let mut found = Resources::default();
loop {
let found: Vec<&str> = d
let symbols: Vec<String> = d
.symbols
.iter()
.filter(|sym| !symbols.contains(sym.name.as_str()) && reaches(&sym.art, &uses, &symbols))
.map(|sym| sym.name.as_str())
.filter(|sym| !found.symbols.contains(&sym.name) && reaches(&sym.art, &uses, &found))
.map(|sym| sym.name.clone())
.collect();
if found.is_empty() {
let patterns: Vec<String> = d
.patterns
.iter()
.filter(|p| !pattern_being_edited(d, &p.name) && !found.patterns.contains(&p.name) && p.art.iter().any(|a| reaches(a, &uses, &found)))
.map(|p| p.name.clone())
.collect();
if symbols.is_empty() && patterns.is_empty() {
break;
}
symbols.extend(found);
found.symbols.extend(symbols);
found.patterns.extend(patterns);
}
// Their instances the Selection tool can reach.
if !symbols.is_empty() {
// The objects the Selection tool can reach that show such type: the instances of those
// symbols, the objects that those patterns paint, and the objects whose opacity mask holds it
// (not layers, which the Selection tool doesn't select).
let masked: HashSet<NodeId> = masked.into_iter().collect();
if !found.symbols.is_empty() || !found.patterns.is_empty() || !masked.is_empty() {
let texts: HashSet<NodeId> = hits.iter().copied().collect();
d.walk(&mut |n: &Node| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& symbols.contains(symbol.as_str())
&& editable(n.id)
{
let shows = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol))
|| paint_patterns(n).any(|p| found.patterns.contains(p))
|| (masked.contains(&n.id) && n.extras().mask.as_deref().is_some_and(|m| reaches(&m.art, &uses, &found)));
if shows && !n.is_layer() && !texts.contains(&n.id) && editable(n.id) {
hits.push(n.id);
}
});
@@ -1311,6 +1502,255 @@ mod tests {
assert_eq!(s.execute("text.replaceFont", &serif_to_sans).unwrap(), json!({"runs": 0}));
}
/// Moves object `art` of the layers into the opacity mask of `owner` (a layer or an object).
fn mask_with(s: &mut Session, owner: u64, art: u64) {
s.edit("Mask", |d, _| {
let art = d.remove(NodeId(art))?;
d.node_mut(NodeId(owner)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
Ok(())
})
.unwrap();
}
/// The font families of the first runs of the text in the opacity mask of `owner`.
fn mask_families(s: &Session, owner: u64) -> Vec<String> {
let d = &s.doc().unwrap().doc;
mask_texts(d, &[(NodeId(owner), true)]).iter().map(|(_, t, _)| t.runs[0].style.font_family.clone()).collect()
}
/// The font families of the first runs of the text in the art of pattern `name`.
fn pattern_families(s: &Session, name: &str) -> Vec<String> {
let d = &s.doc().unwrap().doc;
let mut out = vec![];
for art in &d.pattern(name).unwrap().art {
art_texts(art, true, &mut out);
}
out.iter().map(|(_, t, _)| t.runs[0].style.font_family.clone()).collect()
}
/// The rows of `text.fonts` with `p`: family, runs and objects.
fn font_rows(s: &mut Session, p: Value) -> Vec<(String, u64, u64)> {
let fonts = s.execute("text.fonts", &p).unwrap();
fonts
.as_array()
.unwrap()
.iter()
.map(|f| (f["family"].as_str().unwrap().to_string(), f["runs"].as_u64().unwrap(), f["objects"].as_u64().unwrap()))
.collect()
}
/// Find Font lists, selects and changes the type in opacity masks: on objects, on a layer,
/// disabled and inside the art of another mask. The type in the mask of a locked object is
/// listed and left in its font; Find selects the objects whose mask holds the type.
#[test]
fn find_font_reaches_the_type_in_opacity_masks() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let text = |s: &mut Session, y: i32| {
s.execute("text.create", &json!({"x": 10, "y": y, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap()
};
let rect = |s: &mut Session, y: i32| {
s.execute("shape.rectangle", &json!({"x": 0, "y": y, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap()
};
let mut owners = vec![];
for y in [20, 50, 80] {
let owner = rect(&mut s, y);
let t = text(&mut s, y);
mask_with(&mut s, owner, t);
owners.push(owner);
}
let (open, locked, disabled) = (owners[0], owners[1], owners[2]);
s.execute("select.set", &json!({"ids": [locked]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [disabled]})).unwrap();
s.execute("transparency.disableOpacityMask", &json!({})).unwrap();
// A mask whose art is an object with a mask of its own, and a layer's mask.
let nested = rect(&mut s, 110);
let inner = rect(&mut s, 110);
let t = text(&mut s, 110);
mask_with(&mut s, inner, t);
mask_with(&mut s, nested, inner);
let layer = s.doc().unwrap().doc.layers[0].id.0;
let t = text(&mut s, 140);
mask_with(&mut s, layer, t);
let mut on_layers = 0;
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
assert_eq!(on_layers, 0, "the type is only in masks");
assert_eq!(font_rows(&mut s, json!({})), [("Source Serif 4".to_string(), 5, 5)]);
s.execute("select.set", &json!({"ids": [open]})).unwrap();
assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), [("Source Serif 4".to_string(), 1, 1)]);
// Find selects the objects whose mask holds the type, not the locked one or the layer.
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 3);
let mut selected = s.doc().unwrap().selection.objects.clone();
selected.sort();
assert_eq!(selected, [NodeId(open), NodeId(disabled), NodeId(nested)]);
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4", "scope": {"artboards": [0]}})).unwrap()["count"], 3);
// Change All: one undo step, the locked object's mask left in its font and counted.
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
let serif_to_sans = json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}});
let r = s.execute("text.replaceFont", &serif_to_sans).unwrap();
assert_eq!((r["runs"].as_u64(), r["skipped"].as_u64()), (Some(4), Some(1)), "{r}");
assert_eq!(steps(&s), before + 1);
for owner in [open, disabled, nested, layer] {
assert_eq!(mask_families(&s, owner), ["Source Sans 3"], "the mask of {owner}");
}
assert_eq!(mask_families(&s, locked), ["Source Serif 4"]);
let r = s.execute("text.replaceFont", &serif_to_sans).unwrap();
assert_eq!(r, json!({"runs": 0, "skipped": 1, "warning": REPLACE_SKIPPED}));
assert_eq!(steps(&s), before + 1);
s.execute("edit.undo", &json!({})).unwrap();
for owner in [open, disabled, nested, layer] {
assert_eq!(mask_families(&s, owner), ["Source Serif 4"], "the mask of {owner} after Undo");
}
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(mask_families(&s, nested), ["Source Sans 3"]);
// While a mask is edited, its type on the editing layer is counted and changed once.
s.execute("transparency.editOpacityMask", &json!({"id": open})).unwrap();
assert_eq!(font_rows(&mut s, json!({})), [("Source Sans 3".to_string(), 4, 4), ("Source Serif 4".to_string(), 1, 1)]);
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap();
assert_eq!(r["runs"].as_u64(), Some(4), "{r}");
let families: Vec<String> = used_fonts(&s.doc().unwrap().doc).into_iter().map(|(family, ..)| family).collect();
assert_eq!(families, ["Inter", "Source Serif 4"], "the edited mask is written back after each edit");
s.execute("transparency.stopEditingOpacityMask", &json!({})).unwrap();
assert_eq!(mask_families(&s, open), ["Inter"]);
}
/// Find Font lists the type in pattern swatches once, also when nothing paints with them;
/// Find selects the objects the pattern paints, and Change changes the pattern's art once for
/// every object it paints. While a pattern is edited, its type is taken from the editing layer.
#[test]
fn find_font_reaches_the_type_in_patterns() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let pattern = |s: &mut Session, name: &str, font: &str| {
let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": font})).unwrap()["id"].as_u64().unwrap();
s.execute("object.pattern.make", &json!({"ids": [t], "name": name, "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [t]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
};
pattern(&mut s, "Dots", "Source Serif 4");
pattern(&mut s, "Unused", "Inter");
let mut on_layers = 0;
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
assert_eq!(on_layers, 0, "the type is only in patterns");
let all = [("Inter".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)];
assert_eq!(font_rows(&mut s, json!({})), all);
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0);
let mut painted = vec![];
for y in [20, 60] {
painted.push(s.execute("shape.rectangle", &json!({"x": 0, "y": y, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap());
}
s.execute("paint.setFill", &json!({"swatch": "Dots", "ids": painted})).unwrap();
assert_eq!(font_rows(&mut s, json!({})), all, "a pattern's type counts once");
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 2);
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(painted[0]), NodeId(painted[1])]);
assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 0);
// Only the selection: the patterns the selected objects paint with.
s.execute("select.set", &json!({"ids": [painted[0]]})).unwrap();
assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), [("Source Serif 4".to_string(), 1, 1)]);
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
let r = s
.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true}))
.unwrap();
assert_eq!(r, json!({"runs": 1}));
assert_eq!(steps(&s), before + 1);
assert_eq!(pattern_families(&s, "Dots"), ["Source Sans 3"]);
assert_eq!(pattern_families(&s, "Unused"), ["Inter"]);
// No run changes: no undo step.
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Source Sans 3"}})).unwrap();
assert_eq!(r, json!({"runs": 0}));
assert_eq!(steps(&s), before + 1);
// Change All reaches the swatch nothing paints with.
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Serif 4"}})).unwrap();
assert_eq!(r, json!({"runs": 1}));
assert_eq!(pattern_families(&s, "Unused"), ["Source Serif 4"]);
// A pattern in a hidden fill doesn't show: Find doesn't select the object for its type.
let hidden = s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Unused", "ids": [hidden]})).unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1);
s.edit("Hide the fill", |d, _| {
for it in d.node_mut(NodeId(hidden)).unwrap().appearance.items.iter_mut() {
if let AppearanceItem::Fill(f) = it {
f.visible = false;
}
}
Ok(())
})
.unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0);
// Nor does a pattern on a stroke of no width.
s.execute("paint.setStroke", &json!({"swatch": "Unused", "ids": [hidden]})).unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1);
s.edit("Thin the stroke", |d, _| {
for it in d.node_mut(NodeId(hidden)).unwrap().appearance.items.iter_mut() {
if let AppearanceItem::Stroke(st) = it {
st.width = 0.0;
}
}
Ok(())
})
.unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0);
// A locked painted object: its pattern's type is listed and left in its font.
s.execute("select.set", &json!({"ids": [painted[1]]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [painted[1]]})).unwrap();
let r =
s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}, "selectionOnly": true})).unwrap();
assert_eq!((r["runs"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}");
assert_eq!(s.execute("select.font", &json!({"family": "Source Sans 3"})).unwrap()["count"], 1);
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(painted[0])]);
// While the pattern is edited, its type on the editing layer is counted and changed once.
s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap();
let rows = font_rows(&mut s, json!({}));
assert_eq!(rows, [("Source Sans 3".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)]);
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap();
assert_eq!(r, json!({"runs": 1}));
let families: Vec<String> = used_fonts(&s.doc().unwrap().doc).into_iter().map(|(family, ..)| family).collect();
assert_eq!(families, ["Inter", "Source Serif 4"], "the pattern's stored art is left out while it is edited");
s.execute("object.pattern.done", &json!({})).unwrap();
assert_eq!(pattern_families(&s, "Dots"), ["Inter"]);
}
/// A pattern whose art holds a symbol instance, painting objects inside and outside a symbol:
/// Find Font lists each pattern's and symbol's type once and reaches the symbol's type through
/// the pattern.
#[test]
fn find_font_reaches_symbols_through_patterns() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let inter = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "In", "font": "Inter"})).unwrap()["id"].clone();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [inter]})).unwrap();
let instance = s.doc().unwrap().selection.objects[0].0;
let serif = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Se", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap();
let tile = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 80})).unwrap()["id"].as_u64().unwrap();
s.execute("object.pattern.make", &json!({"ids": [tile, serif, instance], "name": "Loop", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [tile, serif, instance]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
// Another object paints with the pattern too: its type is still read once.
let other = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [other]})).unwrap();
s.execute("symbol.new", &json!({"name": "Outer", "ids": [other]})).unwrap();
let outer = s.doc().unwrap().selection.objects[0];
let painted = s.execute("shape.rectangle", &json!({"x": 0, "y": 100, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [painted]})).unwrap();
let both = [("Inter".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)];
assert_eq!(font_rows(&mut s, json!({})), both);
s.execute("select.set", &json!({"ids": [painted]})).unwrap();
assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), both);
// Find reaches the symbol's type through the pattern, and through a symbol whose art paints
// with the pattern.
assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 2);
assert_eq!(s.doc().unwrap().selection.objects, [outer, NodeId(painted)]);
s.execute("select.set", &json!({"ids": [painted]})).unwrap();
let r =
s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})).unwrap();
assert_eq!(r, json!({"runs": 1}));
assert_eq!(symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family, "Source Sans 3");
}
/// The font family of text object `id`'s first run.
fn text_family(s: &Session, id: u64) -> String {
text(&s.doc().unwrap().doc, NodeId(id)).unwrap().runs[0].style.font_family.clone()
+6 -1
View File
@@ -1202,7 +1202,8 @@ pub(crate) fn with_found_paths(d: &mut Document, base: LinkBase) {
/// `d`, a document saved at `doc_path`, as a reply to the caller asking now may show it: without
/// read roots in force, `d` itself; with them, a copy in which each link [`path_shown`] does not
/// allow names its file alone, without its relative path or the size and date kept of its file,
/// and each data set's image value it does not allow names its file alone too. The folder Export
/// and each data set's image value and linked JavaScript file (`svg_scripts`) it does not allow
/// names its file alone too, while a JavaScript file given as a URL stays as it is. The folder Export
/// for Screens last wrote to is left out of the export settings when it is outside the read roots.
/// A link whose path is allowed but whose relative path leads outside the read roots loses its
/// relative path. Links in the layers, symbols, graph designs, patterns, the pattern being edited
@@ -1268,6 +1269,10 @@ pub(crate) fn with_hidden_paths_named<'a>(d: &'a Document, base: LinkBase) -> Co
}
}
}
let script_hidden = |f: &str| !path_shown(f, doc_path) && !matches!(fileio::document_path(f, doc_path), Err(craft_docpath::Refused::Url));
for f in d.svg_scripts.iter_mut().filter(|f| script_hidden(f)) {
*f = LinkInfo::new(f.as_str()).name().to_string();
}
Cow::Owned(d)
}
+300 -3
View File
@@ -1,10 +1,21 @@
//! File → New: the settings `file.new` takes, the New Document presets (generated in code, by
//! category), the user's saved presets and the recently used sizes (both kept in the
//! preferences), and the artboard grid layout shared with Rearrange All Artboards.
//!
//! New Document profiles: each built-in category has a profile, a native document in the
//! `New Document Profiles` folder next to the preferences ([`Session::attach_new_doc_profiles`]).
//! `file.new` starts a document of that category with the profile's swatches, graphic styles,
//! brushes, symbols, character and paragraph styles, rulers, document setup and print settings
//! ([`DocSettings::document_from_profile`]). The grid stays that of Preferences › Guides & Grid,
//! which applies to every open document. A category without a profile file starts with the
//! defaults, and a profile that can't be read leaves them in place and is reported in `file.new`'s
//! result.
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_doc::{Artboard, Background, ColorMode, Document, Unit};
use vectorcraft_doc::{Artboard, Background, ColorMode, Document, LayerColor, Node, Unit};
use vectorcraft_geom::{Point, Rect};
use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param, switch_or};
@@ -38,6 +49,33 @@ pub fn specs() -> Vec<CommandSpec> {
|s| if s.prefs.new_doc_presets.is_empty() { Err("no saved presets".into()) } else { Ok(()) },
delete
),
cmd!(
query "file.newProfiles",
"New Document Profiles",
[],
None,
"{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), path?; both left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}",
always,
list_profiles
),
cmd!(
"file.newProfiles.edit",
"Edit Profile",
[],
None,
"{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first → document.open's result",
always,
edit_profile
),
cmd!(
"file.newProfiles.reset",
"Reset Profile",
[],
None,
"{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open → {name, reset: whether a file was deleted}",
always,
reset_profile
),
]
}
@@ -148,6 +186,11 @@ pub struct DocSettings {
/// on in the Mobile and Web presets, off in the others and in a saved or Recent preset from
/// before it.
pub align_new_objects_to_pixel_grid: bool,
/// The New Document profile the document starts from (a built-in category's name): the
/// category of a built-in preset, kept by the saved and Recent presets made from it; `None`:
/// the defaults.
#[serde(skip_serializing_if = "Option::is_none")]
pub profile: Option<String>,
}
impl Default for DocSettings {
@@ -168,6 +211,7 @@ impl Default for DocSettings {
raster_effects_ppi: 72.0,
preview_mode: PreviewMode::Default,
align_new_objects_to_pixel_grid: false,
profile: None,
}
}
}
@@ -217,6 +261,7 @@ impl DocSettings {
"rasterEffectsPpi": self.raster_effects_ppi,
"previewMode": self.preview_mode.id(),
"alignNewObjectsToPixelGrid": self.align_new_objects_to_pixel_grid,
"profile": self.profile,
})
}
@@ -280,6 +325,11 @@ impl DocSettings {
self.preview_mode = m.as_str().and_then(PreviewMode::parse).ok_or_else(|| bad(cmd, "previewMode must be default, pixel or overprint"))?;
}
self.align_new_objects_to_pixel_grid = switch_or(p, "alignNewObjectsToPixelGrid", self.align_new_objects_to_pixel_grid, cmd)?;
match p.get("profile") {
None => {}
Some(Value::Null) => self.profile = None,
Some(v) => self.profile = Some(profile_name(v, cmd)?.to_string()),
}
let extent = self.boards().iter().fold(Rect::ZERO, |a, r| a.union(*r));
if extent.width().max(extent.height()) + self.bleed.iter().fold(0.0f64, |a, b| a.max(*b)) * 2.0 > crate::MAX_COORD {
return Err(bad(cmd, "the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size"));
@@ -357,6 +407,101 @@ impl DocSettings {
.collect();
d
}
/// The new document started from New Document profile `profile`: [`Self::document`] with the
/// profile's swatches, swatch groups, graphic styles, brushes, symbols, patterns and the images
/// they use, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler
/// origin and mode, transparency grid, document setup (bleed, background and Align New Objects
/// to Pixel Grid stay these settings'), assigned color profiles, raster effects settings (the
/// resolution stays these settings') and print settings, in these settings' color mode (the
/// profile's colors converted as Document Color Mode converts them). The profile's art,
/// layers and artboards are left out: the document has one empty layer.
pub fn document_from_profile(&self, mut profile: Document) -> Document {
if profile.color_mode != self.color_mode {
super::colormgmt::set_color_mode(&mut profile, self.color_mode, true, None, super::colormgmt::Grays::Profile);
}
let profile_next_id = profile.peek_next_id();
let mut d = self.document();
d.swatches = profile.swatches;
d.swatch_groups = profile.swatch_groups;
d.graphic_styles = profile.graphic_styles;
d.char_styles = profile.char_styles;
d.para_styles = profile.para_styles;
d.composite_fonts = profile.composite_fonts;
d.symbols = profile.symbols;
d.graph_designs = profile.graph_designs;
d.patterns = profile.patterns;
d.images = profile.images;
d.svg_filters = profile.svg_filters;
d.spot_use_lab = profile.spot_use_lab;
d.ruler_origin = profile.ruler_origin;
d.rulers = profile.rulers;
d.artboard_ruler_origins = profile.artboard_ruler_origins.into_iter().filter(|(id, _)| d.artboards.iter().any(|a| a.id == *id)).collect();
d.transparency_grid = profile.transparency_grid;
d.print_setup = profile.print_setup;
d.color_profiles = profile.color_profiles;
// The resolution stays the preset's (raster_effects_ppi); the other raster effects settings
// are the profile's.
d.raster_effects = profile.raster_effects;
let setup = std::mem::replace(&mut d.setup, profile.setup);
d.setup.bleed = setup.bleed;
d.setup.background = setup.background;
d.setup.align_new_objects_to_pixel_grid = setup.align_new_objects_to_pixel_grid;
if let Some(brushes) = profile.unknown.get("brushes") {
d.unknown.insert("brushes".into(), brushes.clone());
}
// Symbol, pattern and graph design art keeps the profile's ids, which a damaged file can
// have above its counter: the counter goes past all of them, as it does for a loaded
// document's layers, before the new layer takes an id.
d.raise_next_id(profile_next_id);
d.layers = d
.symbols
.iter()
.map(|s| s.art.clone())
.chain(d.graph_designs.iter().map(|g| g.art.clone()))
.chain(d.patterns.iter().flat_map(|p| p.art.iter().cloned()))
.collect();
d.fix_next_id();
let layer = d.alloc_id();
d.layers = vec![Arc::new(Node::layer(layer, "Layer 1", LayerColor::Preset(0)))];
// Images only the profile's art used stay behind: an image is kept when an object of the new
// document names it in its `key`, as a native save keeps only the images its objects name.
let images = std::mem::take(&mut d.images);
if !images.is_empty() {
d.images = match serde_json::to_value(&d) {
Ok(v) => {
let used = image_keys(&v);
images.into_iter().filter(|(k, _)| used.contains(k.as_str())).collect()
}
Err(_) => images,
};
}
d
}
}
/// The string values of every `key` member at any depth of `v`, which name the images a document's
/// objects use, collected in one pass.
fn image_keys(v: &Value) -> std::collections::HashSet<&str> {
let mut keys = std::collections::HashSet::new();
let mut stack = vec![v];
while let Some(v) = stack.pop() {
match v {
Value::Object(m) => {
for (k, v) in m {
match v.as_str() {
Some(s) if k == "key" => {
keys.insert(s);
}
_ => stack.push(v),
}
}
}
Value::Array(a) => stack.extend(a),
_ => {}
}
}
keys
}
/// Largest artboard side `file.new` and `artboard.new` accept, points: the span of the canvas
@@ -594,6 +739,7 @@ fn builtin(c: &Category, general: Unit) -> impl Iterator<Item = DocSettings> + '
color_mode,
raster_effects_ppi: ppi,
align_new_objects_to_pixel_grid: align,
profile: Some(category.into()),
..DocSettings::default()
})
}
@@ -644,7 +790,18 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
if size != Some(sorted(&settings)) {
settings.name = "Custom".into();
}
let mut d = settings.document();
let (profile, profile_error) = match settings.profile.as_deref() {
Some(name) => match s.read_profile(name) {
Ok(p) => (p, None),
Err(e) => (None, Some(e)),
},
None => (None, None),
};
let applied = profile.is_some();
let mut d = match profile {
Some(p) => settings.document_from_profile(p),
None => settings.document(),
};
d.grid = s.prefs.grid();
d.title = match str_param(p, "name").or(str_param(p, "title")).map(str::trim).filter(|t| !t.is_empty()) {
// New Document offers the next untitled name: taking it uses it up.
@@ -660,7 +817,14 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
s.execute("view.overprintPreview", &json!({ "on": true }))?;
}
remember(s, &settings);
Ok(json!({ "index": i, "previewMode": settings.preview_mode.id() }))
let mut out = json!({ "index": i, "previewMode": settings.preview_mode.id() });
if applied {
out["profile"] = json!(settings.profile);
}
if let Some(e) = profile_error {
out["profileError"] = json!({ "profile": settings.profile, "reason": e });
}
Ok(out)
}
/// Put `settings` first in Recent (one entry per size and units).
@@ -714,3 +878,136 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
let i = saved.iter().position(|q| q.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(C, format!("no saved preset called `{name}`")))?;
Ok(json!({ "deleted": saved.remove(i).name }))
}
/// The largest New Document profile file `file.new` reads, bytes (VectorCraft's own limit); a
/// larger one is reported and the document starts with the defaults.
pub const MAX_PROFILE_BYTES: u64 = 64 << 20;
/// The New Document profiles' names: the built-in categories, in tab order.
pub fn profile_names() -> impl Iterator<Item = &'static str> {
CATEGORIES.iter().map(|c| c.0)
}
/// The profile `v` names (a built-in category, any case).
fn profile_name(v: &Value, cmd: &str) -> Result<&'static str> {
let name = v.as_str().map(str::trim).unwrap_or_default();
profile_names().find(|c| c.eq_ignore_ascii_case(name)).ok_or_else(|| {
let shown = v.as_str().map_or_else(|| v.to_string(), str::to_string);
bad(cmd, format!("no New Document profile called `{shown}` ({})", profile_names().collect::<Vec<_>>().join(", ")))
})
}
impl Session {
/// Keep the New Document profiles in the folder `dir` (`New Document Profiles` next to the
/// preferences). The folder is made when a profile is first edited.
pub fn attach_new_doc_profiles(&mut self, dir: std::path::PathBuf) {
self.new_doc_profile_dir = Some(dir);
}
/// The New Document profiles' folder ([`Session::attach_new_doc_profiles`]); none on the web.
pub fn new_doc_profile_dir(&self) -> Option<&std::path::Path> {
self.new_doc_profile_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
}
/// The file of profile `name`, whether or not it exists.
fn profile_path(&self, name: &str) -> Option<std::path::PathBuf> {
Some(self.new_doc_profile_dir()?.join(format!("{name}.{}", vectorcraft_format::EXTENSION)))
}
/// Whether profile `name` has a file, which `file.newProfiles.reset` deletes.
pub fn new_doc_profile_customized(&self, name: &str) -> bool {
self.profile_path(name).is_some_and(|p| p.is_file())
}
/// Profile `name`'s document: `None` when it has no file (the shipped profile, the defaults),
/// the reason when the request being served may not read it, or its file can't be read, is
/// larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft reads.
fn read_profile(&self, name: &str) -> std::result::Result<Option<Document>, String> {
let Some(path) = self.profile_path(name) else { return Ok(None) };
// Checked before the file is looked for, so a request that may not read the folder learns
// nothing of its files.
crate::file_access::check_read(&path.to_string_lossy())?;
if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) {
return Ok(None);
}
crate::file_access::check_read(&path.to_string_lossy())?;
let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?;
let mut doc = vectorcraft_format::load(&bytes).map_err(|e| e.to_string())?;
// Linked images in its symbols, patterns and brushes are read from their files, as placing
// a document reads them.
super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&path.to_string_lossy())), false, false);
Ok(Some(doc))
}
}
/// The shipped profile of category `name`: the defaults, as a document of the category's first
/// preset.
fn shipped_profile(s: &Session, name: &str) -> Document {
let first = CATEGORIES.iter().find(|c| c.0 == name).and_then(|c| builtin(c, s.default_units()).next());
let mut d = first.unwrap_or_default().document();
d.title = name.to_string();
d
}
/// `path` when the request being served may read it.
fn shown(path: &std::path::Path) -> Option<String> {
let path = path.to_string_lossy().to_string();
crate::file_access::check_read(&path).is_ok().then_some(path)
}
fn list_profiles(s: &mut Session, _: &Value) -> Result<Value> {
let profiles: Vec<Value> = profile_names()
.map(|name| {
let mut v = json!({ "name": name });
match s.profile_path(name) {
// A request that may not read the folder learns nothing of its files.
Some(path) => {
if let Some(p) = shown(&path) {
v["customized"] = json!(path.is_file());
v["path"] = json!(p);
}
}
None => v["customized"] = json!(false),
}
v
})
.collect();
Ok(json!({ "profiles": profiles, "folder": s.new_doc_profile_dir().and_then(shown) }))
}
/// The file of profile `name` for `cmd` to change, checked against the request's write access.
fn writable_profile(s: &Session, name: &str, cmd: &str) -> Result<std::path::PathBuf> {
let path = s.profile_path(name).ok_or_else(|| bad(cmd, "New Document profiles need the preferences folder, which this run doesn't have"))?;
crate::file_access::check_write(&path.to_string_lossy()).map_err(super::EngineError::Other)?;
Ok(path)
}
fn edit_profile(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "file.newProfiles.edit";
let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?;
let file = writable_profile(s, name, C)?;
let path = file.to_string_lossy().to_string();
// document.open reads it next: a profile it can't open is not written either.
crate::file_access::check_read(&path).map_err(super::EngineError::Other)?;
if !file.exists() {
let bytes = vectorcraft_format::save(&shipped_profile(s, name), false);
file.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::write(&file, bytes))
.map_err(|e| super::EngineError::Other(format!("{path}: {e}")))?;
}
s.execute("document.open", &json!({ "path": path }))
}
fn reset_profile(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "file.newProfiles.reset";
let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?;
let file = writable_profile(s, name, C)?;
let path = file.to_string_lossy().to_string();
let reset = match std::fs::remove_file(&file) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
Err(e) => return Err(super::EngineError::Other(format!("{path}: {e}"))),
};
Ok(json!({ "name": name, "reset": reset }))
}
+4 -4
View File
@@ -133,16 +133,16 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
// the objects differ, the members of groups and the objects in symbols' art included, and with
// strokes that scale, when the sizes are out of proportion. The objects are then measured one
// by one ([`Spans::measure`]), and the scales solved for. Objects with geometry effects,
// objects with a butt-capped stroke along a segment at a slant, whose margins change with the
// segment's direction, and type measured by its glyphs, are measured as drawn after each scale
// tried instead ([`refit_drawn`]).
// objects with a stroke that stops at the corners of a segment at a slant (butt caps, bevel and
// miter joins), whose margins change with the segment's direction, and type measured by its
// glyphs, are measured as drawn after each scale tried instead ([`refit_drawn`]).
let to_local = frame.to_doc().inverse();
let drawn = || {
by_glyphs
|| ids
.iter()
.filter_map(|id| d.node(*id))
.any(|n| effects::preview::draws_geometry(&symbols, n) || n.has_slanted_butt_stroke(&symbols, to_local))
.any(|n| effects::preview::draws_geometry(&symbols, n) || n.has_slanted_stroke_corners(&symbols, to_local))
};
// Without Use Preview Bounds the box has no margins (`v`, `vs` and `g` are one box, glyph ink
// included), so the scales above are exact and nothing is refitted.
+189 -19
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character / Paragraph",
[],
None,
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave Line truncated
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave Line truncated
has_doc,
set_format
),
@@ -122,7 +122,7 @@ pub(crate) fn boards_and_art_noted(s: &mut Session, p: &Value, cmd: &str) -> Res
/// Add `selectedArtboards` to the running command's journal entry when `p` names no artboard, so a
/// replay acts on the artboards the Artboard tool had selected. An action leaves it out
/// (`REPLAY_ONLY`) and keeps an `index` or `indices` the call gave.
fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) {
pub(crate) fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) {
if p.get("index").is_none() && p.get("indices").is_none() {
s.note_journal("selectedArtboards", json!(indices));
}
@@ -130,7 +130,7 @@ fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) {
/// The artboards `cmd` acts on: `index` or `indices`, else `selectedArtboards` (a replay of the
/// journal), else those the Artboard tool has selected, else its active one.
fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result<Vec<usize>> {
pub(crate) fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result<Vec<usize>> {
let t = s.tool_options_of("artboard");
let d = &s.doc()?.doc;
if p.get("index").is_some() || p.get("indices").is_some() {
@@ -467,6 +467,9 @@ fn list_level_param(p: &Value, cmd: &str) -> Result<Option<u8>> {
fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.setFormat";
if p.get("paragraphIndents").is_some() {
return set_paragraph_indents(s, p);
}
let ids = super::typecmd::text_targets(s, p, C)?;
check_switches(
p,
@@ -487,6 +490,27 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
],
C,
)?;
// Each value that `num` reads below must be a number or null.
super::check_numbers(
p,
&[
"baselineShift",
"hScale",
"vScale",
"rotation",
"leftIndent",
"rightIndent",
"firstLineIndent",
"spaceBefore",
"spaceAfter",
"wordsLongerThan",
"afterFirst",
"beforeLast",
"hyphenLimit",
"hyphenationZone",
],
C,
)?;
let num = |k: &str| p.get(k).and_then(Value::as_f64);
let flag = |k: &str| p.get(k).and_then(Value::as_bool);
let kerning = match p.get("kerning") {
@@ -547,6 +571,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"tateChuYoko",
"tcyUpDown",
"tcyLeftRight",
"akiLeft",
"akiRight",
"standardVerticalRoman",
"noBreak",
"digits",
@@ -559,7 +585,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"kashida",
"composer",
];
if !keys.iter().any(|k| p.get(*k).is_some()) {
// A null value leaves its attribute as it is, as an omitted one does.
if !keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return Err(bad(C, "nothing to change"));
}
// The anti-aliasing method belongs to the whole type object; each frame keeps its own method.
@@ -588,8 +615,10 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
let font_height_reference = super::textedit::font_height_reference_param(p, C)?;
let tcy_up_down = super::textedit::tcy_offset_param(p, "tcyUpDown", C)?;
let tcy_left_right = super::textedit::tcy_offset_param(p, "tcyLeftRight", C)?;
let aki_left = super::textedit::aki_param(p, "akiLeft", C)?;
let aki_right = super::textedit::aki_param(p, "akiRight", C)?;
let mojikumi = match p.get("mojikumi") {
None => None,
None | Some(Value::Null) => None,
Some(v) => Some(match v.as_str() {
Some("none") => vectorcraft_doc::Mojikumi::None,
Some("lineEndHalf") => vectorcraft_doc::Mojikumi::LineEndHalf,
@@ -597,7 +626,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
}),
};
let kinsoku = match p.get("kinsoku") {
None => None,
None | Some(Value::Null) => None,
Some(v) => Some(match v.as_str() {
Some("none") => vectorcraft_doc::Kinsoku::None,
Some("hard") => vectorcraft_doc::Kinsoku::Hard,
@@ -606,7 +635,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
}),
};
let kinsoku_type = match p.get("kinsokuType") {
None => None,
None | Some(Value::Null) => None,
Some(v) => Some(match v.as_str() {
Some("pushInFirst") => vectorcraft_doc::KinsokuShoriType::PushInFirst,
Some("pushOutFirst") => vectorcraft_doc::KinsokuShoriType::PushOutFirst,
@@ -615,7 +644,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
}),
};
let direction = match p.get("direction") {
None => None,
None | Some(Value::Null) => None,
Some(v) => Some(match v.as_str() {
Some("auto") => None,
Some("leftToRight") => Some(vectorcraft_doc::ParaDirection::LeftToRight),
@@ -624,7 +653,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
}),
};
let leading_model = match p.get("leadingModel") {
None => None,
None | Some(Value::Null) => None,
Some(v) => Some(match v.as_str() {
Some("romanBaseline") => vectorcraft_doc::LeadingModel::RomanBaseline,
Some("emBoxTop") => vectorcraft_doc::LeadingModel::EmBoxTop,
@@ -632,7 +661,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
}),
};
let burasagari = match p.get("burasagari") {
None => None,
None | Some(Value::Null) => None,
Some(v) => Some(match v.as_str() {
Some("none") => vectorcraft_doc::Burasagari::None,
Some("standard") => vectorcraft_doc::Burasagari::Standard,
@@ -641,7 +670,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
}),
};
let kashida = match p.get("kashida") {
None => None,
None | Some(Value::Null) => None,
Some(v) => Some(match v.as_str() {
Some("none") => vectorcraft_doc::text::Kashida::None,
Some("short") => vectorcraft_doc::text::Kashida::Short,
@@ -672,7 +701,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
let spacing = |k: &str| spacing_param(p, k, C);
let (word_spacing, letter_spacing, glyph_scaling) = (spacing("wordSpacing")?, spacing("letterSpacing")?, spacing("glyphScaling")?);
let single_word = match p.get("singleWordJustification") {
None => None,
None | Some(Value::Null) => None,
Some(v) => Some(match v.as_str() {
Some("fullJustify") => SingleWordJustify::FullJustify,
Some("alignLeft") => SingleWordJustify::AlignLeft,
@@ -682,7 +711,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
}),
};
let auto_leading = match p.get("autoLeading") {
None => None,
None | Some(Value::Null) => None,
Some(v) => Some(v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(C, "`autoLeading` must be a number"))?),
};
// A paragraph whose Minimum, Desired and Maximum would no longer be in order.
@@ -748,6 +777,12 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = tcy.1 {
st.tcy_left_right = v;
}
if let Some(v) = aki_left {
st.aki_left = v;
}
if let Some(v) = aki_right {
st.aki_right = v;
}
if let Some(v) = flag("standardVerticalRoman") {
st.standard_vertical_roman = v;
}
@@ -789,12 +824,20 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
l.level = list_level.unwrap_or(l.level);
}
};
s.edit("Character", |d, _| {
// The change is made on a copy first: a call whose values are the ones the text already has
// records no edit, undo step or revision. Only the type objects and graph label styles the call
// changes are compared, not the whole document.
super::variablecmds::settle_typing(s)?;
let mut doc = (*s.doc()?.doc).clone();
let mut changed = false;
{
let d = &mut doc;
// The paragraph change, for the graph labels to keep.
let mut para_change = None;
let out_of_order_error = |name: &str| bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"));
for id in &ids {
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
let before = t.clone();
let baseline_shift = num("baselineShift").map(|v| super::typecmd::local_type_value(t, v, (-1296.0, 1296.0), false, C)).transpose()?;
let h_scale = num("hScale").map(|v| super::typecmd::local_type_value(t, v, (1.0, 10000.0), true, C)).transpose()?;
let local = |v: Option<f64>| v.map(|v| super::typecmd::local_type_value(t, v, (-1296.0, 1296.0), false, C)).transpose();
@@ -901,16 +944,17 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
return Err(out_of_order_error(name));
}
super::typecmd::refresh_bounds(t);
changed |= *t != before;
para_change = Some(paras);
}
// Graph labels keep a change made to all of their text through the graph being drawn again.
if range.is_none() {
let shift = num("baselineShift").map(|v| v.clamp(-1296.0, 1296.0));
let scale = num("hScale").map(|v| v.clamp(1.0, 10000.0));
super::graph::capture_label_styles(d, &ids, &|st| chars(st, shift, scale, (tcy_up_down, tcy_left_right)));
changed |= super::graph::capture_label_styles(d, &ids, &|st| chars(st, shift, scale, (tcy_up_down, tcy_left_right)));
if let Some(paras) = para_change {
// The kept attributes are checked too: they may differ from the labels'.
super::graph::capture_label_paragraphs(d, &ids, &|para| {
changed |= super::graph::capture_label_paragraphs(d, &ids, &|para| {
let mut out_of_order = None;
paras(para, &mut out_of_order);
out_of_order.map_or(Ok(()), |name| Err(out_of_order_error(name)))
@@ -920,14 +964,20 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = anti_alias {
for id in &ids {
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
changed |= t.anti_alias != v;
t.anti_alias = v;
}
}
// Graph labels keep the method through the graph being drawn again.
super::graph::capture_label_anti_alias(d, &ids, v);
changed |= super::graph::capture_label_anti_alias(d, &ids, v);
}
Ok(())
})?;
}
if changed {
s.edit("Character", |d, _| {
*d = doc;
Ok(())
})?;
}
let mut result = json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() });
if let Some(kerning) = p.get("kerning") {
result["kerning"] = kerning.clone();
@@ -935,6 +985,126 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
Ok(result)
}
/// The most entries `paragraphIndents` takes in one `text.setFormat` call.
pub(crate) const MAX_PARAGRAPH_INDENTS: usize = 100_000;
/// The indents one `paragraphIndents` entry gives its paragraph.
#[derive(Clone, Copy, Debug, PartialEq)]
struct ParagraphIndent {
left: Option<f64>,
first_line: Option<f64>,
}
/// A type object that `paragraphIndents` names: the bytes where its paragraphs start and the
/// indents its entries give them, by paragraph index.
struct IndentedFrame {
id: NodeId,
starts: Vec<usize>,
changes: Vec<(usize, ParagraphIndent)>,
}
/// `text.setFormat` with `paragraphIndents`: each entry names one paragraph of a type object, by
/// the object and the byte where the paragraph starts, and sets its left and first-line indents.
/// Every entry is checked against the document before anything changes. Each type object's
/// paragraph styles are rebuilt once and the whole change is one edit, so a threaded story flows
/// again once however many of its paragraphs change. When no entry changes its paragraph, nothing
/// is edited.
fn set_paragraph_indents(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.setFormat";
const KEY: &str = "paragraphIndents";
if let Some(other) = p.as_object().and_then(|o| o.keys().find(|k| *k != KEY)) {
return Err(bad(C, format!("`{KEY}` takes no `{other}` beside it")));
}
let entries = p.get(KEY).and_then(Value::as_array).ok_or_else(|| bad(C, format!("`{KEY}` must be a list")))?;
if entries.is_empty() {
return Err(bad(C, format!("`{KEY}` is empty")));
}
if entries.len() > MAX_PARAGRAPH_INDENTS {
return Err(bad(C, format!("`{KEY}` takes at most {MAX_PARAGRAPH_INDENTS} entries (got {})", entries.len())));
}
let d = &s.doc()?.doc;
// The type objects in the order they first appear.
let mut frames: Vec<IndentedFrame> = vec![];
let mut frame_at: std::collections::HashMap<NodeId, usize> = std::collections::HashMap::new();
let mut given: std::collections::HashMap<(NodeId, usize), ParagraphIndent> = std::collections::HashMap::new();
for (n, e) in entries.iter().enumerate() {
let e = e.as_object().ok_or_else(|| bad(C, format!("`{KEY}` entry {n} must be an object")))?;
if let Some(k) = e.keys().find(|k| !["id", "start", "leftIndent", "firstLineIndent"].contains(&k.as_str())) {
return Err(bad(C, format!("`{KEY}` entry {n}: unknown key `{k}`")));
}
let indent = |k: &str| -> Result<Option<f64>> {
match e.get(k) {
None => Ok(None),
Some(v) => match v.as_f64() {
Some(x) if x.is_finite() && x.abs() <= MAX_PARA => Ok(Some(x)),
_ => Err(bad(C, format!("`{KEY}` entry {n}: `{k}` must be a number from -{MAX_PARA} to {MAX_PARA} pt"))),
},
}
};
let change = ParagraphIndent { left: indent("leftIndent")?, first_line: indent("firstLineIndent")? };
if change.left.is_none() && change.first_line.is_none() {
return Err(bad(C, format!("`{KEY}` entry {n} sets neither `leftIndent` nor `firstLineIndent`")));
}
let id = NodeId(e.get("id").and_then(Value::as_u64).ok_or_else(|| bad(C, format!("`{KEY}` entry {n}: `id` must be an object id")))?);
let start = index(e.get("start").and_then(Value::as_u64).ok_or_else(|| bad(C, format!("`{KEY}` entry {n}: `start` must be a byte offset")))?);
let k = match frame_at.get(&id) {
Some(k) => *k,
None => {
let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else {
return Err(bad(C, format!("`{KEY}` entry {n}: {} is not a type object", id.0)));
};
let plain = t.plain_text();
let mut starts = vec![0];
starts.extend(plain.bytes().enumerate().filter_map(|(i, c)| (c == b'\n').then_some(i + 1)));
frames.push(IndentedFrame { id, starts, changes: vec![] });
frame_at.insert(id, frames.len() - 1);
frames.len() - 1
}
};
let Some(IndentedFrame { starts, changes, .. }) = frames.get_mut(k) else { continue };
let para = starts.binary_search(&start).map_err(|_| bad(C, format!("`{KEY}` entry {n}: no paragraph of {} starts at byte {start}", id.0)))?;
match given.insert((id, para), change) {
None => changes.push((para, change)),
Some(was) if was == change => {}
Some(_) => {
return Err(bad(
C,
format!("`{KEY}` entry {n} gives the paragraph at byte {start} of {} other indents than an entry before it", id.0),
));
}
}
}
let ids = json!({ "ids": frames.iter().map(|f| f.id.0).collect::<Vec<_>>() });
// Only the type objects with a paragraph whose indents change are edited.
let differs = |t: &vectorcraft_doc::TextObject, i: usize, c: &ParagraphIndent| {
let para = t.para_at(i);
c.left.is_some_and(|v| v != para.left_indent) || c.first_line.is_some_and(|v| v != para.first_line_indent)
};
frames.retain(|f| match d.node(f.id).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => f.changes.iter().any(|(i, c)| differs(t, *i, c)),
_ => false,
});
if frames.is_empty() {
return Ok(ids);
}
s.edit("Character", |d, _| {
for f in &frames {
let Some(NodeKind::Text(t)) = d.node_mut(f.id).map(|n| &mut n.kind) else { continue };
let mut styles = t.paragraph_styles();
for (i, c) in &f.changes {
if let Some(para) = styles.get_mut(*i) {
para.left_indent = c.left.unwrap_or(para.left_indent);
para.first_line_indent = c.first_line.unwrap_or(para.first_line_indent);
}
}
t.set_paragraph_styles(styles);
super::typecmd::refresh_bounds(t);
}
Ok(())
})?;
Ok(ids)
}
/// The part of a story paragraph in one frame, as [`convert_list_to_text`] reads it: the frame,
/// the frame's paragraph, its bytes there, its list, the marker the frame's layout draws for it
/// and the numbered paragraphs the frame counts before it at each list level.
+33 -7
View File
@@ -169,6 +169,10 @@ pub(crate) const NOT_FILES: &[(&str, &str)] = &[
("document.exportForScreens", "folders"),
];
/// Commands and the keys from the top of their params down to a key in [`FILE_KEYS`] that, there,
/// names part of the document, not a file: a custom arrowhead's outline in `stroke.set`.
const NESTED_NOT_FILES: &[(&str, &[&str])] = &[("stroke.set", &["startArrow", "Custom", "path"]), ("stroke.set", &["endArrow", "Custom", "path"])];
/// Is command id `id` one a plug-in may never call, from its id alone ([`DENIED_PREFIXES`],
/// [`FILE_WORDS`])?
fn denied_id(id: &str) -> bool {
@@ -232,20 +236,32 @@ pub(crate) fn names_key(text: &str, key: &str) -> bool {
/// Does `args`, the arguments of a call of command `id`, carry a key in [`FILE_KEYS`] at any depth
/// (in objects and in arrays), such as an effect's `textureImage.path`? Only a key [`NOT_FILES`]
/// names for `id`, at the top level, isn't counted. The walk keeps its own stack, so deep
/// arguments can't overflow the thread's.
/// names for `id`, at the top level, and one at the end of a [`NESTED_NOT_FILES`] key list for
/// `id`, aren't counted. The walk keeps its own stack, so deep arguments can't overflow the
/// thread's.
fn names_file(id: &str, args: &Value) -> bool {
let mut stack = vec![(args, true)];
while let Some((v, top)) = stack.pop() {
// Each value, whether it is the params themselves, and the keys of a NESTED_NOT_FILES list
// still to follow below it.
let mut stack: Vec<(&Value, bool, Option<&[&str]>)> = vec![(args, true, None)];
while let Some((v, top, trail)) = stack.pop() {
match v {
Value::Array(a) => stack.extend(a.iter().map(|x| (x, false))),
Value::Array(a) => stack.extend(a.iter().map(|x| (x, false, None))),
Value::Object(o) => {
for (k, x) in o {
let k = k.as_str();
if FILE_KEYS.contains(&k) && !(top && NOT_FILES.contains(&(id, k))) {
let rest = if top {
NESTED_NOT_FILES
.iter()
.find(|(c, keys)| *c == id && keys.first() == Some(&k))
.map(|(_, keys)| keys.get(1..).unwrap_or_default())
} else {
trail.filter(|keys| keys.first() == Some(&k)).map(|keys| keys.get(1..).unwrap_or_default())
};
let document = (top && NOT_FILES.contains(&(id, k))) || rest.is_some_and(<[&str]>::is_empty);
if FILE_KEYS.contains(&k) && !document {
return true;
}
stack.push((x, false));
stack.push((x, false, rest.filter(|keys| !keys.is_empty())));
}
}
_ => {}
@@ -585,6 +601,16 @@ mod tests {
assert!(!names_file("object.setLiveShape", &json!({"path": [[0, 0], [1, 1]]})));
assert!(names_file("object.setLiveShape", &json!({"options": {"path": "/tmp/x"}})));
assert!(names_file("object.move", &json!({"path": [[0, 0]]})));
// A custom arrowhead's outline in stroke.set, only where stroke.set takes one.
let outline = json!({"subpaths": []});
assert!(!names_file("stroke.set", &json!({"endArrow": {"Custom": {"name": "A", "path": outline}}})));
assert!(!names_file("stroke.set", &json!({"startArrow": {"Custom": {"name": "A", "path": outline}}, "endArrow": "Triangle"})));
assert!(names_file("stroke.set", &json!({"endArrow": {"Custom": {"name": "A", "path": outline, "file": "/tmp/x"}}})));
assert!(names_file("stroke.set", &json!({"endArrow": {"Custom": {"path": {"path": "/tmp/x"}}}})));
assert!(names_file("stroke.set", &json!({"endArrow": {"path": "/tmp/x"}})));
assert!(names_file("stroke.set", &json!({"options": {"endArrow": {"Custom": {"path": "/tmp/x"}}}})));
assert!(names_file("stroke.set", &json!({"endArrow": [{"Custom": {"path": "/tmp/x"}}]})));
assert!(names_file("object.move", &json!({"endArrow": {"Custom": {"path": "/tmp/x"}}})));
// Deep nesting is walked without recursion.
let mut deep = json!({"file": "/tmp/x"});
for _ in 0..10_000 {
@@ -89,9 +89,12 @@ pub(super) const ALLOWED: &[&str] = &[
"appearance.showAllHidden",
"appearance.targetContents",
"appearance.transfer",
"artboard.align",
"artboard.convertToArtboards",
"artboard.delete",
"artboard.deleteEmpty",
"artboard.distribute",
"artboard.distributeSpacing",
"artboard.duplicate",
"artboard.fitToArt",
"artboard.fitToSelection",
@@ -472,6 +475,7 @@ pub(super) const ALLOWED: &[&str] = &[
"perspective.transform",
"recolor.apply",
"recolor.colors",
"recolor.pickTheme",
"recolor.randomize",
"recolor.reduce",
"select.add",
@@ -627,6 +631,8 @@ pub(super) const ALLOWED: &[&str] = &[
"text.thread.releaseSelection",
"text.thread.remove",
"text.touchType",
"threeD.addGraphic",
"threeD.mapGraphic",
"transparency.disableOpacityMask",
"transparency.editOpacityMask",
"transparency.enableOpacityMask",
@@ -692,5 +698,6 @@ pub(super) const DENIED: &[&str] = &[
"object.blend.options",
"object.liquify",
"object.pathfinder.options",
"stroke.arrowheads.edit",
"type.compositeFonts.set",
];
+2 -2
View File
@@ -645,8 +645,8 @@ pub fn export_pdf(doc: &Document, opts: &vectorcraft_pdf::PdfOptions) -> std::re
export_pdf_with_report(doc, opts).map(|r| r.bytes)
}
/// Like [`export_pdf`], also returning the writer's warnings (options not applied yet, features
/// approximated or left out).
/// Like [`export_pdf`], also returning the writer's warnings (features approximated or left out)
/// and its notes on the options (options not applied yet).
pub fn export_pdf_with_report(
doc: &Document,
opts: &vectorcraft_pdf::PdfOptions,
+819
View File
@@ -11,6 +11,7 @@ use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng,
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{Point, Rect};
use super::colorcmds::{NotChanged, Recolor, Scope, left_out};
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param};
@@ -53,9 +54,827 @@ pub fn specs() -> Vec<CommandSpec> {
always,
randomize
),
cmd!(
query "recolor.pickTheme",
"Color Theme Picker",
[],
None,
"{picks: [{at: [x, y]} (a click: the object a Selection tool click there takes, with everything inside it) | {rect: [x0, y0, x1, y1]} (a marquee: every painted object it touches, and the part of each image inside it)] (1 to 256, in document points), colors?: 5 (1 to 64)} → {colors: [colour keys, the most used first], objects: the number of objects read} the colour palette of the art picked, for Recolor Artwork's Color Theme Picker: visible fills and strokes, gradient stops, text, mesh points, pattern tiles (with the patterns they use), the art of symbol instances (placed through their 9-slice guides), the colorize colour of an image it applies to and other images' pixels (at most 65,536 pixels of each pick of an image, spread evenly, and 1,048,576 pixels of at most 64 images in all; pixels less than half opaque and images that can't be decoded are left out). In a clip group, or under an opacity mask that clips, only what shows inside the clipping path or the mask art is read; a blend, envelope or repeat a marquee touches is read whole. Hidden or fully transparent objects and fill or stroke items are left out; locked objects are read. Each object read weighs the same, shared among its colours (an image's among its pixels; the vector art a symbol instance places counts as one object, each image it places on its own); similar colours merge (k-means in Lab) into at most `colors`, each shown by its most used colour in its own model. Picks that touch no art give no colours. Changes nothing",
has_doc,
pick_theme
),
]
}
/// The pixels one read of an image by the Color Theme Picker takes, at most, the pixels all its
/// reads share, and the images one pick reads, at most.
const THEME_PIXELS: usize = 65_536;
const THEME_TOTAL_PIXELS: usize = 1 << 20;
const MAX_THEME_IMAGES: usize = 64;
/// The image reads one pick queues, at most.
const MAX_THEME_READS: usize = 4096;
/// The stroke segments the opacity masks one pick reads are outlined along, at most.
const MASK_OUTLINE_SEGMENTS: usize = 20_000;
/// The point-in-region tests one pick makes to find whether outlines show through clip groups,
/// and the clipping-path elements the pixels of one image are tested against, at most.
const THEME_WORK: usize = 4_000_000;
/// The picks one `recolor.pickTheme` takes, and the colours it gives, at most.
const MAX_PICKS: usize = 256;
const MAX_THEME_COLORS: u64 = 64;
/// The objects the Color Theme Picker reads through, one inside another, at most.
const MAX_THEME_DEPTH: usize = 256;
/// A pick of the Color Theme Picker: a click at a point or a marquee.
enum Pick {
At(Point),
Area(Rect),
}
impl Pick {
/// `{at: [x, y]}` or `{rect: [x0, y0, x1, y1]}`, finite numbers.
fn param(v: &Value, cmd: &str) -> Result<Self> {
let numbers = |a: &Value, n: usize| -> Option<Vec<f64>> {
let a = a.as_array().filter(|a| a.len() == n)?;
a.iter().map(|x| x.as_f64().filter(|x| x.is_finite())).collect()
};
match (v.get("at"), v.get("rect")) {
(Some(at), None) => {
numbers(at, 2).map(|p| Pick::At(Point::new(p[0], p[1]))).ok_or_else(|| bad(cmd, format!("`at` must be [x, y] (got {at})")))
}
(None, Some(r)) => numbers(r, 4)
.map(|r| Pick::Area(Rect::new(r[0], r[1], r[2], r[3]).abs()))
.ok_or_else(|| bad(cmd, format!("`rect` must be [x0, y0, x1, y1] (got {r})"))),
_ => Err(bad(cmd, format!("each pick is {{at: [x, y]}} or {{rect: [x0, y0, x1, y1]}} (got {v})"))),
}
}
}
/// A filled region: its outline and fill rule.
type Region = (vectorcraft_geom::BezPath, vectorcraft_geom::FillRule);
/// An image the Color Theme Picker reads: its pixels, where it lies, the marquee it is read in
/// (`None`: all of it) and the region the clip groups around it show (`None`: unclipped). An
/// image its colorize paint applies to ([`vectorcraft_doc::ImageBlob::takes_colorize`]) gives that
/// paint's colours where a pixel read shows ink (opaque and darker than white).
#[derive(Clone)]
struct ImageRead<'a> {
blob: &'a vectorcraft_doc::ImageBlob,
xf: vectorcraft_geom::Affine,
size: (f64, f64),
area: Option<Rect>,
clip: Option<Vec<Region>>,
colorize: Option<Vec<Color>>,
}
/// The colours the Color Theme Picker has read: each object weighs 1, shared among its colours.
struct Theme<'a> {
d: &'a Document,
boxes: vectorcraft_doc::SymbolBoxes<'a>,
samples: Vec<(Color, f32)>,
/// The images to read, each image decoded once for all its reads ([`Self::read_images`]),
/// and the images they read.
images: Vec<ImageRead<'a>>,
blobs: std::collections::HashSet<*const vectorcraft_doc::ImageBlob>,
/// What the clip groups being read show, in document space: the union of these regions
/// (none: nothing shows); `None` outside clip groups.
clip: Option<Vec<Region>>,
/// The colours of the patterns read so far, and the patterns whose tiles are being read.
pattern_colors: HashMap<String, (Vec<Color>, Vec<ImageRead<'a>>)>,
pattern_stack: Vec<String>,
/// The region tests [`Self::shows`] has made.
work: std::cell::Cell<usize>,
/// The object isolated in isolation mode.
scope: Option<NodeId>,
/// The stroke segments opacity masks may still be outlined along ([`mask_regions`]).
mask_budget: usize,
objects: usize,
}
/// The region both `a` and `b` (each a union of regions) cover, filled non-zero.
fn intersect_regions(a: &[Region], b: &[Region]) -> Vec<Region> {
let paths: Vec<vectorcraft_geom::PathData> = a.iter().chain(b).map(|(bp, _)| vectorcraft_geom::PathData::from_bezpath(bp)).collect();
let inputs: Vec<(&vectorcraft_geom::PathData, vectorcraft_geom::FillRule)> =
paths.iter().zip(a.iter().chain(b)).map(|(p, (_, rule))| (p, *rule)).collect();
let split = a.len();
let both = vectorcraft_pathops::boolean_n(&inputs, |inside| inside.iter().any(|i| *i < split) && inside.iter().any(|i| *i >= split));
if both.subpaths.is_empty() { vec![] } else { vec![(both.to_bezpath(), vectorcraft_geom::FillRule::NonZero)] }
}
impl<'a> Theme<'a> {
fn new(d: &'a Document) -> Self {
Self {
d,
boxes: d.symbol_boxes(),
samples: vec![],
images: vec![],
blobs: std::collections::HashSet::new(),
clip: None,
pattern_colors: HashMap::new(),
pattern_stack: vec![],
work: std::cell::Cell::new(0),
scope: None,
mask_budget: MASK_OUTLINE_SEGMENTS,
objects: 0,
}
}
fn add(&mut self, colors: Vec<Color>) {
if colors.is_empty() {
return;
}
let w = 1.0 / colors.len() as f32;
self.samples.extend(colors.into_iter().map(|c| (c, w)));
self.objects += 1;
}
/// Read the images queued, each image's pixels decoded once, as colours: the pixels a read
/// gives that fall in one cell of 16 levels a channel merge into their average, weighted by how
/// many there are, and the cells of all the reads add up, so the images give at most 16³
/// colours. Images that can't be decoded give none. The first [`MAX_THEME_IMAGES`] images
/// are read, and all the reads share [`THEME_TOTAL_PIXELS`] pixels (each read at least one, at
/// most [`THEME_PIXELS`]).
fn read_images(&mut self) {
let reads = std::mem::take(&mut self.images);
// The reads of each image, in the order its first read came.
let mut by_image: Vec<(*const vectorcraft_doc::ImageBlob, Vec<&ImageRead>)> = vec![];
for r in &reads {
let key: *const vectorcraft_doc::ImageBlob = r.blob;
match by_image.iter().position(|(k, _)| *k == key) {
Some(i) => by_image[i].1.push(r),
None if by_image.len() < MAX_THEME_IMAGES => by_image.push((key, vec![r])),
None => {}
}
}
let count: usize = by_image.iter().map(|(_, g)| g.len()).sum();
let budget = (THEME_TOTAL_PIXELS / count.max(1)).clamp(1, THEME_PIXELS);
let mut pixels: HashMap<[u8; 3], ([f64; 3], f64)> = HashMap::new();
for (_, group) in by_image {
let keeps: Vec<Box<dyn Fn(f64, f64) -> bool + '_>> = group
.iter()
.map(|r| {
let (xf, (w, h), area, clip) = (r.xf, r.size, r.area, &r.clip);
Box::new(move |u: f64, v: f64| {
let p = xf * Point::new(u * w, v * h);
area.is_none_or(|a| a.contains(p))
&& clip.as_ref().is_none_or(|rs| rs.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p)))
}) as Box<dyn Fn(f64, f64) -> bool + '_>
})
.collect();
let picks: Vec<vectorcraft_doc::PixelPick> = group
.iter()
.zip(&keeps)
.map(|(r, keep)| {
use vectorcraft_geom::kurbo::Shape;
let (w, h) = r.size;
let inv = r.xf.inverse();
// The box sampled: the marquee, cut to the clipping paths' bounds, so a small
// region a clip shows of a large image is still sampled densely.
let clip_box = r.clip.as_ref().map(|rs| rs.iter().map(|(bp, _)| bp.bounding_box()).reduce(|a, b| a.union(b)).unwrap_or_default());
let region = match (r.area, clip_box) {
(Some(a), Some(c)) => Some(a.intersect(c)),
(a, c) => a.or(c),
};
let box_uv = region.map(|a| {
let uv: Vec<Point> =
[(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)].into_iter().map(|(x, y)| inv * Point::new(x, y)).collect();
let low = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::INFINITY, f64::min);
let high = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::NEG_INFINITY, f64::max);
[low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h]
});
(box_uv, keep.as_ref())
})
.collect();
// Each sampled pixel inside a clip group is tested against the clipping regions: the
// pixels one image gives keep that work within THEME_WORK path elements.
let elements =
group.iter().map(|r| r.clip.as_ref().map_or(0, |rs| rs.iter().map(|(bp, _)| bp.elements().len()).sum::<usize>())).max().unwrap_or(0);
let budget = THEME_WORK.checked_div(elements).map_or(budget, |w| budget.min(w.max(1)));
let Some(each) = group[0].blob.sample_pixels(&picks, budget) else { continue };
for (px, read) in each.into_iter().zip(&group) {
if let Some(colors) = &read.colorize {
// Ink: an opaque pixel darker than white takes the colorize paint.
if !colors.is_empty() && px.iter().any(|p| p[3] >= 128 && p[..3].iter().any(|v| *v < 255)) {
let w = 1.0 / colors.len().max(1) as f32;
self.samples.extend(colors.iter().map(|c| (*c, w)));
self.objects += 1;
}
continue;
}
let mut cells: HashMap<[u8; 3], ([u64; 3], u64)> = HashMap::new();
for [r, g, b, _] in px.into_iter().filter(|p| p[3] >= 128) {
let cell = cells.entry([r >> 4, g >> 4, b >> 4]).or_default();
for (sum, v) in cell.0.iter_mut().zip([r, g, b]) {
*sum += u64::from(v);
}
cell.1 += 1;
}
let total: u64 = cells.values().map(|c| c.1).sum();
if total == 0 {
continue;
}
for (key, (sum, n)) in cells {
let cell = pixels.entry(key).or_default();
for (acc, s) in cell.0.iter_mut().zip(sum) {
*acc += s as f64 / total as f64;
}
cell.1 += n as f64 / total as f64;
}
self.objects += 1;
}
}
let mut cells: Vec<_> = pixels.into_iter().collect();
// The same order on every run.
cells.sort_unstable_by_key(|c| c.0);
for (_, (sum, w)) in cells {
let [r, g, b] = sum.map(|s| (s / w).round().clamp(0.0, 255.0) as u8);
self.samples.push((Color::rgb8(r, g, b), w as f32));
}
}
/// Read `n` and everything visible inside it: each image (its part inside `area` when given,
/// and inside the clipping paths around it) and each other object with colours of its own
/// (that touches `area` when given, and shows inside the clipping paths around it). The art a
/// symbol instance shows (with a dynamic instance's own paints), placed where the instance
/// draws it, and the objects a blend, an envelope or a repeat draws elsewhere than they lie,
/// are read whole when the instance or the live object touches `area`. `depth` counts the
/// objects passed through: deeper art is left out. An enabled opacity mask that clips (and is
/// not inverted) shows the object only where its mask art is lighter than black
/// ([`mask_regions`]), as a clip group would.
fn read(&mut self, n: &Node, area: Option<Rect>, depth: usize) {
let Some(mask) = n.extras().mask.as_deref().filter(|m| !m.disabled && m.clip && !m.invert) else {
return self.read_unmasked(n, area, depth);
};
let regions = mask_regions(&mask.art, &mut self.mask_budget);
let outer = self.clip.clone();
self.clip = Some(match &outer {
None => regions,
Some(o) => intersect_regions(o, &regions),
});
self.read_unmasked(n, area, depth);
self.clip = outer;
}
/// [`Self::read`] without `n`'s opacity mask.
fn read_unmasked(&mut self, n: &Node, area: Option<Rect>, depth: usize) {
// Hidden and fully transparent objects show nothing.
if depth > MAX_THEME_DEPTH || !n.visible || n.opacity <= 0.0 || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
return;
}
let touches = area.is_none_or(|r| self.touches(n, r));
match &n.kind {
NodeKind::Image(im) => {
if !touches {
return;
}
// A document keeps its images' pixels in its image store.
let Some(blob) = self.d.images.get(&im.key) else { return };
// An image with a colorize paint shows that paint's color, not its own pixels;
// other paints its appearance has (with effects that draw them) count as well.
let colorized = n.extras().colorize.is_some() && blob.takes_colorize();
let own = if colorized || n.extras().colorize.is_none() {
self.own(n, true)
} else {
// A colorize paint the image does not take (a linked image's preview)
// shows nothing.
let mut plain = n.clone();
plain.extras_mut().colorize = None;
self.own(&plain, true)
};
let colorize = if colorized {
Some(own)
} else {
if self.shows(n, area) {
self.add(own);
}
None
};
let size = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
self.queue_image(ImageRead { blob, xf: im.xf, size, area, clip: self.clip.clone(), colorize });
return;
}
NodeKind::SymbolInstance { symbol, xf } => {
if touches
&& self.shows(n, area)
&& let Some(s) = self.d.symbols.iter().find(|s| s.name == *symbol)
{
// The instance's own paints; its overrides show in its art.
let own = self.own(n, false);
self.add(own);
// The art as the instance places it: through the symbol's 9-slice guides when
// it has them, else by the instance's transform. Art that would place too many
// objects is left out, as the renderer leaves it out.
let dynamic = (!n.extras().symbol_overrides.is_empty()).then(|| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n));
if let Some(placed) = self.d.place_symbol_art(symbol, dynamic.as_ref().unwrap_or(&s.art), *xf) {
// The vector art counts as one object, each of its colours once, so an
// object the 9-slice guides cut into several copies does not count more.
// Each image placed is read on its own, as images are elsewhere.
let (samples, objects) = (self.samples.len(), self.objects);
self.read(&placed, None, depth + 1);
let added = self.samples.split_off(samples);
self.objects = objects;
let mut seen = std::collections::HashSet::new();
let colors: Vec<Color> = added.into_iter().map(|(c, _)| c).filter(|c| seen.insert(ColorKey::of(c))).collect();
self.add(colors);
}
}
return;
}
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) => {
if touches && self.shows(n, area) {
let own = self.own(n, true);
self.add(own);
// The copies are drawn elsewhere than the objects lie: the clipping paths
// around the live object, tested above, do not apply to the objects.
let clip = self.clip.take();
for c in n.children().into_iter().flatten() {
self.read(c, None, depth + 1);
}
self.clip = clip;
}
return;
}
_ => {}
}
if touches && self.shows(n, area) {
let own = self.own(n, true);
self.add(own);
}
// A compound path's members are its geometry: the compound paints them.
if matches!(n.kind, NodeKind::Compound { .. }) {
return;
}
// A clip group's clipping path paints whole, over the art it clips: it is read in the
// marquee as given and under the clip groups around it alone.
let clip_child = n.children().and_then(|c| c.first()).filter(|_| n.clips());
if let Some(first) = clip_child {
self.read(first, area, depth + 1);
}
let inner = match area {
Some(r) => match vectorcraft_doc::hit::marquee_in(n, r) {
Some(inner) => Some(inner),
None => return,
},
None => None,
};
// A clip group shows its art where its clipping path's regions and the clip groups around
// it all show.
let outer = self.clip.clone();
if n.clips()
&& let Some(first) = n.children().and_then(|c| c.first())
{
let regions: Vec<Region> = vectorcraft_doc::hit::clip_regions(first);
self.clip = Some(match &outer {
None => regions,
Some(o) => intersect_regions(o, &regions),
});
}
// A Shaper Group's original shapes, which the group keeps but does not show, are left out.
for (i, c) in n.children().into_iter().flatten().enumerate().skip(usize::from(clip_child.is_some())) {
if !vectorcraft_doc::hit::shaper_hides(n, i, self.scope) {
self.read(c, inner, depth + 1);
}
}
self.clip = outer;
}
/// Does `n` show inside the region the clip groups around it show, in `area` when given? Its
/// box (cut to `area`) meets a region of it: the region's outline crosses the box, or a point
/// on a 9 × 9 grid over the part of the box inside the region's bounds lies in the region.
fn shows(&self, n: &Node, area: Option<Rect>) -> bool {
use vectorcraft_geom::kurbo::Shape;
let Some(regions) = &self.clip else { return true };
let Some(b) = n.visual_bounds_with(&self.boxes) else { return false };
let b = area.map_or(b, |r| b.intersect(r));
let valid = |r: &Rect| r.width() >= 0.0 && r.height() >= 0.0;
if !valid(&b) {
return false;
}
// A path or compound path paints along its outline, and inside it where it has a visible
// fill: a point along the outline, or (filled) a point of a 9 × 9 grid over the part of the
// box inside a region's bounds that lies in both its fill and the region, must show.
let filled = has_fill(n);
let outline: Option<(Vec<&vectorcraft_geom::PathData>, vectorcraft_geom::FillRule)> = match &n.kind {
NodeKind::Path { path, rule, .. } => Some((vec![path], *rule)),
NodeKind::Compound { children, rule } => Some((children.iter().filter(|c| c.visible).filter_map(|c| c.path_data()).collect(), *rule)),
_ => None,
};
if let Some((paths, own_rule)) = outline {
use vectorcraft_geom::ParamCurve;
use vectorcraft_geom::kurbo::ParamCurveArclen;
// The work all these tests do is bounded: past it, objects count as shown.
if self.work.get() > THEME_WORK {
return true;
}
let half = stroke_reach(n);
let cost: usize = regions.iter().map(|(bp, _)| bp.elements().len().max(1)).sum();
let in_region = |p: Point| {
// Past the work allowed, the outline counts as shown.
if self.work.get() > THEME_WORK {
return true;
}
self.work.set(self.work.get() + cost);
regions.iter().any(|(bp, rule)| {
vectorcraft_geom::hit::fill_contains(bp, *rule, p) || half > 0.0 && vectorcraft_geom::hit::stroke_contains(bp, 0.0, half, p)
})
};
let mut fill = vectorcraft_geom::BezPath::new();
for p in &paths {
fill.extend(p.to_bezpath().elements().iter().copied());
}
// At most 4,096 points along the outline, shared among its segments by length, no
// farther apart than half the smallest region's width or height where that allows.
let step = regions
.iter()
.map(|(bp, _)| bp.bounding_box())
.chain(area)
.map(|rb| rb.width().min(rb.height()))
.fold(f64::INFINITY, f64::min)
.max(0.01)
/ 2.0;
// With a marquee, only the outline inside it (within the stroke's reach) counts.
let picked = area.map(|r| r.inflate(half, half));
let segs: Vec<(vectorcraft_geom::PathSeg, f64)> = fill
.segments()
.take(4096)
.map(|s| {
let len = s.arclen(0.5);
(s, if len.is_finite() { len } else { 0.0 })
})
.collect();
let total: f64 = segs.iter().map(|(_, l)| l).sum();
let points = (total / step).ceil().clamp(64.0, 4096.0);
let along = segs.iter().any(|(seg, len)| {
let n = if total > 0.0 { (points * len / total).round().clamp(1.0, 4096.0) as u32 } else { 1 };
(0..=n).any(|i| {
let p = seg.eval(f64::from(i) / f64::from(n));
picked.is_none_or(|r| r.contains(p)) && in_region(p)
})
});
return along
|| filled
&& regions.iter().any(|(bp, _)| {
let g = b.intersect(bp.bounding_box());
valid(&g)
&& (0..81).any(|i| {
let p = Point::new(g.x0 + g.width() * f64::from(i % 9) / 8.0, g.y0 + g.height() * f64::from(i / 9) / 8.0);
in_region(p) && vectorcraft_geom::hit::fill_contains(&fill, own_rule, p)
})
});
}
regions.iter().any(|(bp, rule)| {
let g = b.intersect(bp.bounding_box());
valid(&g)
&& (vectorcraft_geom::hit::intersects_rect(&vectorcraft_geom::PathData::from_bezpath(bp), b)
|| (0..81).any(|i| {
let p = Point::new(g.x0 + g.width() * f64::from(i % 9) / 8.0, g.y0 + g.height() * f64::from(i / 9) / 8.0);
vectorcraft_geom::hit::fill_contains(bp, *rule, p)
}))
})
}
/// Does the marquee `r` touch what `n` paints? A path or a compound path is touched where its
/// outline comes within half its widest visible stroke of `r` or, when it has a visible fill,
/// where `r`'s centre lies in that fill; any other object is touched by its box.
fn touches(&self, n: &Node, r: Rect) -> bool {
let boxed = n.visual_bounds_with(&self.boxes).is_some_and(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1);
let filled = || has_fill(n);
let half = stroke_reach(n);
let near = r.inflate(half, half);
let crosses = |paths: &[&vectorcraft_geom::PathData], rule: vectorcraft_geom::FillRule| {
paths.iter().any(|p| vectorcraft_geom::hit::intersects_rect(p, near))
|| filled() && {
let mut bp = vectorcraft_geom::BezPath::new();
for p in paths {
bp.extend(p.to_bezpath().elements().iter().copied());
}
// A point on a 5 × 5 grid over the part of the marquee in the path's box lies
// in its fill.
use vectorcraft_geom::kurbo::Shape;
let g = r.intersect(bp.bounding_box());
g.width() >= 0.0
&& g.height() >= 0.0
&& (0..25).any(|i| {
let p = Point::new(g.x0 + g.width() * f64::from(i % 5) / 4.0, g.y0 + g.height() * f64::from(i / 5) / 4.0);
vectorcraft_geom::hit::fill_contains(&bp, rule, p)
})
}
};
match &n.kind {
NodeKind::Path { path, rule, .. } => boxed && crosses(&[path], *rule),
NodeKind::Compound { children, rule } => {
let paths: Vec<&vectorcraft_geom::PathData> = children.iter().filter(|c| c.visible).filter_map(|c| c.path_data()).collect();
boxed && crosses(&paths, *rule)
}
_ => boxed,
}
}
}
/// The regions where opacity mask art `art` lets the masked object show: the regions
/// ([`vectorcraft_doc::hit::clip_regions`]) of its visible paths and compound paths filled lighter
/// than black (a solid color, a gradient with a stop lighter than black, or a pattern), the
/// outlines of the strokes lighter than black they have (dashes read as solid), the frames of its
/// images, the boxes of its type painted lighter than black, the boxes of art with effects (with
/// what the effects reach), and the regions of its clip groups and live objects whole. Black,
/// unfilled and unstroked paths without effects hide; how light the art is beyond that is not
/// read. Strokes are outlined along at most `budget` segments in all (it counts down); past that
/// a stroke counts by its box grown by half its width.
fn mask_regions(art: &Node, budget: &mut usize) -> Vec<Region> {
// Any color but black lets the masked art show.
fn light(p: &Paint) -> bool {
let lit = |c: &Color| c.to_rgba8(1.0)[..3].iter().any(|v| *v > 0);
match p {
Paint::None => false,
Paint::Solid { color, .. } => lit(color),
Paint::Gradient(g) => g.gradient.stops.iter().any(|s| lit(&s.color)),
_ => true,
}
}
fn walk(n: &Node, depth: usize, out: &mut Vec<Region>, budget: &mut usize) {
use vectorcraft_geom::kurbo::Shape;
// The mask art's root masks even when it is hidden.
// Guides draw nothing.
if depth > MAX_THEME_DEPTH || depth > 0 && (!n.visible || n.opacity <= 0.0) || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
return;
}
// Art with effects can show light anywhere near it (a glow on black art): it counts
// whole, as a clipping path would.
let effects = !n.appearance.effects.is_empty()
|| n.appearance.items.iter().any(|it| match it {
vectorcraft_doc::AppearanceItem::Fill(l) => l.visible && !l.effects.is_empty(),
vectorcraft_doc::AppearanceItem::Stroke(l) => l.visible && !l.effects.is_empty(),
});
if effects {
if let Some(b) = n.visual_bounds() {
out.push((b.to_path(0.1), vectorcraft_geom::FillRule::NonZero));
}
return;
}
let lit = n
.appearance
.items
.iter()
.any(|it| matches!(it, vectorcraft_doc::AppearanceItem::Fill(l) if l.visible && l.opacity > 0.0 && light(&l.paint)));
let stroke = n
.appearance
.items
.iter()
.filter_map(|it| match it {
vectorcraft_doc::AppearanceItem::Stroke(l) if l.visible && l.opacity > 0.0 && l.width > 0.0 && light(&l.paint) => Some(l.width / 2.0),
_ => None,
})
.fold(None, |a: Option<f64>, w| Some(a.map_or(w, |a| a.max(w))));
let boxed = |out: &mut Vec<Region>| {
if let Some(b) = n.geometric_bounds() {
out.push((b.to_path(0.1), vectorcraft_geom::FillRule::NonZero));
}
};
match &n.kind {
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
if lit {
out.extend(vectorcraft_doc::hit::clip_regions(n));
}
// A stroke shows the art along it: its outline with round ends and corners, a
// dashed stroke read as solid (the most it can show).
if let Some(half) = stroke {
let paths: Vec<&vectorcraft_geom::PathData> = match &n.kind {
NodeKind::Path { path, .. } => vec![path],
NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).collect(),
_ => vec![],
};
for p in paths {
// Past MASK_OUTLINE_SEGMENTS outlined segments, a stroke counts by its
// box grown by half its width.
let segments = p.to_bezpath().elements().len();
if *budget < segments {
if let Some(b) = p.bounds().filter(|_| half.is_finite()) {
out.push((b.inflate(half, half).to_path(0.1), vectorcraft_geom::FillRule::NonZero));
}
continue;
}
*budget -= segments;
let region = vectorcraft_pathops::outline_stroke(
p,
half * 2.0,
vectorcraft_pathops::Cap::Round,
vectorcraft_pathops::Join::Round,
10.0,
);
if !region.subpaths.is_empty() {
out.push((region.to_bezpath(), vectorcraft_geom::FillRule::NonZero));
}
}
}
}
NodeKind::Image(_) => out.extend(vectorcraft_doc::hit::clip_regions(n)),
NodeKind::Text(t) => {
if lit || stroke.is_some() || t.runs.iter().any(|r| light(&r.style.fill) || r.style.stroke_width > 0.0 && light(&r.style.stroke)) {
boxed(out);
}
}
NodeKind::Group { clip: false, .. } | NodeKind::Layer { clip: false, .. } => {
// A Shaper Group's original shapes are kept but not drawn.
for (i, c) in n.children().into_iter().flatten().enumerate() {
if !vectorcraft_doc::hit::shaper_hides(n, i, None) {
walk(c, depth + 1, out, budget);
}
}
}
// Clip groups, live objects and placed documents count by the regions they clip to.
_ => out.extend(vectorcraft_doc::hit::clip_regions(n)),
}
}
let mut out = vec![];
walk(art, 0, &mut out, budget);
out
}
/// Does `n` have a fill item that paints: visible, not fully transparent and not None?
fn has_fill(n: &Node) -> bool {
n.appearance
.items
.iter()
.any(|it| matches!(it, vectorcraft_doc::AppearanceItem::Fill(l) if l.visible && l.opacity > 0.0 && !matches!(l.paint, Paint::None)))
}
/// How far `n`'s widest painting stroke reaches from its path: half its width (0 without one).
fn stroke_reach(n: &Node) -> f64 {
let paints = |l: &vectorcraft_doc::StrokeLayer| l.visible && l.opacity > 0.0 && !matches!(l.paint, Paint::None) && l.width.is_finite();
n.appearance
.items
.iter()
.filter_map(|it| match it {
vectorcraft_doc::AppearanceItem::Stroke(l) if paints(l) => Some(l.width.max(0.0) / 2.0),
_ => None,
})
.fold(0.0, f64::max)
}
/// The paints `m` shows: its visible fill items and its visible strokes wider than 0, its text's
/// fills and strokes wider than 0, and its colorize paint.
fn shown_paints(m: &Node) -> impl Iterator<Item = &Paint> {
let runs = match &m.kind {
NodeKind::Text(t) => t.runs.as_slice(),
_ => &[],
};
let items = m.appearance.items.iter().filter_map(|it| match it {
vectorcraft_doc::AppearanceItem::Fill(l) if l.visible && l.opacity > 0.0 => Some(&l.paint),
vectorcraft_doc::AppearanceItem::Stroke(l) if l.visible && l.opacity > 0.0 && l.width > 0.0 => Some(&l.paint),
_ => None,
});
let text = runs.iter().flat_map(|r| std::iter::once(&r.style.fill).chain((r.style.stroke_width > 0.0).then_some(&r.style.stroke)));
items.chain(text).chain(m.extras().colorize.as_deref())
}
/// Add the colours `m` shows itself to `out` (solid colours, gradient stops, its text's colours
/// and its mesh points; the paints a dynamic symbol instance keeps for objects of its art only
/// when `overrides` is set), and the names of the patterns it paints with to `patterns`, leaving
/// out names already there.
fn paint_colors_of(m: &Node, overrides: bool, out: &mut Vec<Color>, patterns: &mut Vec<String>) {
let kept = override_paints(m).filter(|_| overrides);
for p in shown_paints(m).chain(kept) {
match p {
Paint::Solid { color, .. } => out.push(*color),
Paint::Gradient(g) => out.extend(g.gradient.stops.iter().map(|s| s.color)),
Paint::Pattern { pattern, .. } if !patterns.contains(pattern) => patterns.push(pattern.clone()),
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
out.extend(mesh.points.iter().map(|p| p.color));
}
}
impl<'a> Theme<'a> {
/// Queue image read `r`, within the limits of a pick: at most [`MAX_THEME_READS`] reads of
/// [`MAX_THEME_IMAGES`] images; nothing inside clip groups that show nothing.
fn queue_image(&mut self, r: ImageRead<'a>) {
if self.images.len() >= MAX_THEME_READS || r.clip.as_ref().is_some_and(Vec::is_empty) {
return;
}
let key: *const vectorcraft_doc::ImageBlob = r.blob;
if !self.blobs.contains(&key) {
if self.blobs.len() >= MAX_THEME_IMAGES {
return;
}
self.blobs.insert(key);
}
self.images.push(r);
}
/// The colours `m` paints itself ([`paint_colors_of`]; a dynamic symbol instance's paints for
/// objects of its art only with `overrides`), and the colours its pattern tiles show, read as
/// document art is read (clip groups and symbols included; the tiles' images join this pick's
/// image reads). Each pattern's colours
/// are read once; a pattern whose tile uses itself, directly or through other patterns, adds
/// nothing more the second time.
fn own(&mut self, m: &Node, overrides: bool) -> Vec<Color> {
let mut out = vec![];
let mut patterns: Vec<String> = vec![];
paint_colors_of(m, overrides, &mut out, &mut patterns);
for name in patterns {
if let Some((colors, reads)) = self.pattern_colors.get(&name) {
out.extend(colors);
// The tiles' images count again for each use, within the pick's limits.
let reads = reads.clone();
for r in reads {
self.queue_image(r);
}
continue;
}
if self.pattern_stack.contains(&name) || self.pattern_stack.len() >= MAX_THEME_DEPTH {
continue;
}
let Some(def) = self.d.pattern(&name) else { continue };
let mut sub = Theme::new(self.d);
sub.pattern_stack = std::mem::take(&mut self.pattern_stack);
sub.pattern_stack.push(name.clone());
sub.pattern_colors = std::mem::take(&mut self.pattern_colors);
// The tiles' images join this pick's image reads, within its limits.
sub.images = std::mem::take(&mut self.images);
sub.blobs = std::mem::take(&mut self.blobs);
// The tiles share this pick's limits on work too.
sub.work.set(self.work.get());
sub.mask_budget = self.mask_budget;
let before = sub.images.len();
for a in &def.art {
sub.read(a, None, 0);
}
sub.pattern_stack.pop();
self.pattern_stack = std::mem::take(&mut sub.pattern_stack);
self.pattern_colors = std::mem::take(&mut sub.pattern_colors);
let reads: Vec<ImageRead<'a>> = sub.images.get(before..).unwrap_or_default().to_vec();
self.images = std::mem::take(&mut sub.images);
self.blobs = std::mem::take(&mut sub.blobs);
self.work.set(sub.work.get());
self.mask_budget = sub.mask_budget;
let colors: Vec<Color> = sub.samples.iter().map(|(c, _)| *c).collect();
out.extend(&colors);
self.pattern_colors.insert(name, (colors, reads));
}
out
}
}
fn pick_theme(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "recolor.pickTheme";
let picks = match p.get("picks") {
Some(Value::Array(a)) if !a.is_empty() && a.len() <= MAX_PICKS => a.iter().map(|v| Pick::param(v, C)).collect::<Result<Vec<_>>>()?,
Some(Value::Array(a)) => return Err(bad(C, format!("`picks` must hold 1 to {MAX_PICKS} picks (got {})", a.len()))),
Some(v) => return Err(bad(C, format!("`picks` must be an array (got {v})"))),
None => return Err(bad(C, "missing `picks`")),
};
let n = super::menucmds::whole_or(p, "colors", 5, C)?;
if !(1..=MAX_THEME_COLORS).contains(&n) {
return Err(bad(C, format!("`colors` must be between 1 and {MAX_THEME_COLORS} (got {n})")));
}
let st = s.doc()?;
let d = &st.doc;
let mut theme = Theme::new(d);
theme.scope = st.isolation;
// In isolation mode: the isolated object, everything inside it and the containers around it.
let scope: Option<std::collections::HashSet<NodeId>> = st.isolation.and_then(|iso| d.node(iso)).map(|iso| {
let mut allowed = std::collections::HashSet::new();
iso.walk(&mut |m| {
allowed.insert(m.id);
});
let mut up = d.parent_of(iso.id);
while let Some(p) = up {
allowed.insert(p);
up = d.parent_of(p);
}
allowed
});
for pick in picks {
match pick {
Pick::At(pt) => {
// In isolation mode only the isolated art (and the groups around it) can be hit;
// isolated Shaper Group originals are hittable then.
let opt = vectorcraft_doc::hit::HitOptions { scope: st.isolation, ..Default::default() };
let hit = match &scope {
Some(allowed) => vectorcraft_doc::hit::hit_test_visible_skipping(d, pt, opt, &|id| !allowed.contains(&id)),
None => vectorcraft_doc::hit::hit_test_visible(d, pt, opt),
};
if let Some(n) = hit.and_then(|h| d.node(h.top_object(st.isolation))) {
theme.read(n, None, 0);
}
}
Pick::Area(r) => match st.isolation.and_then(|iso| d.node(iso)) {
// In isolation mode a marquee reads the isolated art alone.
Some(iso) => theme.read(iso, Some(r), 0),
None => {
for l in &d.layers {
theme.read(l, Some(r), 0);
}
}
},
}
}
theme.read_images();
let colors = vectorcraft_color::recolor::theme_palette(&theme.samples, index(n));
Ok(json!({"colors": colors.iter().map(key_str).collect::<Vec<_>>(), "objects": theme.objects}))
}
/// A colour the art uses: how often, and the global swatch it is linked to.
struct Used {
color: Color,
+40 -4
View File
@@ -2,7 +2,9 @@
//! art retained underneath. Recipes select topology regions; source edits re-evaluate them in
//! the same undo transaction. Rendering and exporters only see ordinary groups and paths.
use super::pathops::Beside;
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, object_param, point_param};
use super::{
CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, number_or, object_param, point_param,
};
use serde_json::{Value, json};
use std::{
collections::{BTreeMap, HashMap},
@@ -34,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Shaper Face",
[],
None,
"{point: [x,y], source?: bool} click selects a group, then a face; source enters construction isolation and selects an original (while an opacity mask or a pattern is edited, it selects the original and the editing layer stays isolated); while a group's originals are isolated, it selects one of that group's originals → {id}",
"{point: [x,y], source?: bool, tolerance?: pt (3)} click selects a group, then a face; with the group or one of its faces selected, a click within tolerance of an original shape's outline enters construction isolation and selects that original; source enters construction isolation and selects an original (while an opacity mask or a pattern is edited, it selects the original and the editing layer stays isolated); while a group's originals are isolated, it selects one of that group's originals → {id}",
has_doc,
select
),
@@ -734,16 +736,50 @@ fn group_at(d: &Document, point: Point, construction: bool, within: Option<NodeI
});
groups.last().copied()
}
/// The topmost editable Shaper Group that is selected, or has a face selected, with a visible,
/// unlocked original shape whose outline lies within `tolerance` of `point`, and the topmost such
/// shape in it; `None` when a Shaper Group that [`group_at`] finds at `point` lies above it.
fn outline_at(d: &Document, selection: &vectorcraft_doc::Selection, point: Point, tolerance: f64) -> Option<(NodeId, NodeId)> {
let mut hit = None;
let editable = d.editable();
d.walk(|n| {
if n.extras().shaper.is_none() || !editable(n.id) {
return;
}
let picked = selection.contains(n.id) || selection.objects.iter().any(|id| d.parent_of(*id) == Some(n.id));
let on_outline =
|s: &&Arc<Node>| b::node_outline(s).is_some_and(|(path, _)| path.nearest(point).is_some_and(|(_, _, _, _, dist)| dist <= tolerance));
let source = if picked { sources(n).iter().rev().filter(|s| s.visible && !s.locked).find(on_outline).map(|s| s.id) } else { None };
if let Some(source) = source {
hit = Some((n.id, source));
} else if n.geometric_bounds().is_some_and(|b| b.inflate(6.0, 6.0).contains(point)) {
hit = None;
}
});
hit
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
let point = point_param(p, "point").filter(|p| finite(*p)).ok_or_else(|| bad("shaper.select", "missing point"))?;
let st = s.doc()?;
let source = bool_or(p, "source", false);
let tolerance = number_or(p, "tolerance", 3.0, "shaper.select")?;
if !tolerance.is_finite() || !(0.0..=1000.0).contains(&tolerance) {
return Err(bad("shaper.select", "invalid tolerance"));
}
// In Construction mode a source pick stays in the group whose source shapes are isolated.
let isolated =
st.isolation.and_then(|i| st.doc.parent_of(i)).filter(|g| st.doc.node(*g).and_then(source_group).is_some_and(|s| st.isolation == Some(s.id)));
let Some(group) = group_at(&st.doc, point, source, isolated.filter(|_| source)) else { return Ok(json!({"id": null})) };
// With a group or one of its faces selected, a click on one of its original shapes' outlines
// enters Construction mode with the topmost such shape selected, wherever the outline lies.
let outline = if source { None } else { outline_at(&st.doc, &st.selection, point, tolerance) };
let Some(group) = outline.map(|(g, _)| g).or_else(|| group_at(&st.doc, point, source, isolated.filter(|_| source))) else {
return Ok(json!({"id": null}));
};
let node = st.doc.node(group).ok_or(EngineError::NoNode(group))?;
let target = if source {
let source = source || outline.is_some();
let target = if let Some((_, id)) = outline {
id
} else if source {
sources(node)
.iter()
.rev()
Loaded 100 of 307 files, more files were not shown because too many files have changed in this diff. Show more