diff --git a/ROADMAP.md b/ROADMAP.md index 6cf80d3628..16bd8b1dab 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -131,6 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). diff --git a/apps/vectorcraft/src/control_server/tests.rs b/apps/vectorcraft/src/control_server/tests.rs index aad5d7d083..d991fd6028 100644 --- a/apps/vectorcraft/src/control_server/tests.rs +++ b/apps/vectorcraft/src/control_server/tests.rs @@ -58,7 +58,12 @@ fn idle_control_socket_releases_its_worker() { fn idle_expiry_closes_without_writing_a_line() { let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected")); let mut got = Vec::new(); - client.read_to_end(&mut got).unwrap(); + match client.read_to_end(&mut got) { + // On Windows the server's close can reach the client as a reset. + Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {} + Ok(_) => {} + Err(e) => panic!("reading the idle connection: {e}"), + } assert_eq!(String::from_utf8_lossy(&got), "", "the app wrote to an idle connection"); expect_socket_deadline(client, done, worker); } diff --git a/apps/vectorcraft/src/gpu.rs b/apps/vectorcraft/src/gpu.rs index 00f92405e3..d7d917ed42 100644 --- a/apps/vectorcraft/src/gpu.rs +++ b/apps/vectorcraft/src/gpu.rs @@ -753,13 +753,22 @@ enum FirstFrame { Shown, /// Overdue. Hung, + /// Overdue, but the UI is still building the first frame: the app's own work (on a slow + /// machine, or with antivirus reading every font file), not the adapter, which has been given + /// nothing to show yet. + Busy, } -/// The window's start after `frames` frames run, `since` its first frame was due. -fn first_frame(frames: u64, since: Duration, minimized: bool) -> FirstFrame { +/// The window's start after `frames` frames run, `since` its first frame was due and +/// `since_built` the first frame's UI pass ended (`None` while it runs). A frame counts once its +/// UI pass ends, before it is painted, so the adapter's time starts there: with no frame run, the +/// UI thread is in the app's code, and starting again without the adapter wouldn't help (#5160). +fn first_frame(frames: u64, since: Duration, since_built: Option, minimized: bool) -> FirstFrame { if frames >= 2 || minimized { FirstFrame::Shown - } else if since >= FIRST_FRAME_TIMEOUT { + } else if frames == 0 { + if since >= FIRST_FRAME_TIMEOUT { FirstFrame::Busy } else { FirstFrame::Wait } + } else if since_built.unwrap_or(since) >= FIRST_FRAME_TIMEOUT { FirstFrame::Hung } else { FirstFrame::Wait @@ -767,18 +776,34 @@ fn first_frame(frames: u64, since: Duration, minimized: bool) -> FirstFrame { } /// Watch the window's first frame from another thread: once it reaches the screen, clear the start -/// from [`START_FILE`]; when it hasn't reached the screen [`FIRST_FRAME_TIMEOUT`] after the app was -/// created ([`Startup::ready`]), start the app again without the adapter, as [`finish`] does for -/// one that failed, and end this process, whose UI thread is stuck in the graphics driver. +/// from [`START_FILE`]; when it hasn't reached the screen [`FIRST_FRAME_TIMEOUT`] after its UI pass +/// ended, start the app again without the adapter, as [`finish`] does for one that failed, and end +/// this process, whose UI thread is stuck in the graphics driver. A first frame still being built +/// that long is waited for, with a note in the log. pub fn watch_first_frame(startup: Arc) { + let mut built: Option = None; + let mut noted = false; let watch = move || loop { std::thread::sleep(Duration::from_millis(250)); let Some(due) = startup.ready.get() else { continue }; let ui = startup.ui.get(); let frames = ui.map_or(0, egui::Context::cumulative_frame_nr); + if frames >= 1 && built.is_none() { + built = Some(Instant::now()); + } let minimized = ui.and_then(|c| c.input(|i| i.viewport().minimized)).unwrap_or(false); - match first_frame(frames, due.elapsed(), minimized) { + match first_frame(frames, due.elapsed(), built.map(|t| t.elapsed()), minimized) { FirstFrame::Wait => continue, + FirstFrame::Busy => { + if !noted { + log::warn!( + "the window's first frame is still being built after {}s: waiting for it (the app's work, not the graphics adapter)", + FIRST_FRAME_TIMEOUT.as_secs() + ); + noted = true; + } + continue; + } FirstFrame::Shown => { startup.presented(); return; diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index b1511a232a..40d84934f3 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -366,14 +366,19 @@ fn gpus_without_pci_ids_are_told_apart_by_name() { fn a_first_frame_that_never_reaches_the_screen_hangs_its_adapter() { let s = Duration::from_secs; // The second frame began: the first was presented. - assert_eq!(first_frame(2, s(60), false), FirstFrame::Shown); - // Still drawing (or presenting) the first frame: waited for, then given up on (#964). - for frames in [0, 1] { - assert_eq!(first_frame(frames, s(3), false), FirstFrame::Wait); - assert_eq!(first_frame(frames, FIRST_FRAME_TIMEOUT, false), FirstFrame::Hung); - } + assert_eq!(first_frame(2, s(60), Some(s(1)), false), FirstFrame::Shown); + // The first frame built and not yet presented: waited for, then given up on (#964), counting + // from when its UI pass ended. + assert_eq!(first_frame(1, s(3), Some(s(1)), false), FirstFrame::Wait); + assert_eq!(first_frame(1, FIRST_FRAME_TIMEOUT, Some(FIRST_FRAME_TIMEOUT), false), FirstFrame::Hung); + assert_eq!(first_frame(1, s(45), Some(s(5)), false), FirstFrame::Wait, "a first frame built slowly gets its full time to show"); + assert_eq!(first_frame(1, FIRST_FRAME_TIMEOUT, None, false), FirstFrame::Hung); + // The first frame still being built: the app's work, not the adapter's (#5160). + assert_eq!(first_frame(0, s(3), None, false), FirstFrame::Wait); + assert_eq!(first_frame(0, FIRST_FRAME_TIMEOUT, None, false), FirstFrame::Busy); + assert_eq!(first_frame(0, s(600), None, false), FirstFrame::Busy, "never a restart without an adapter"); // A window minimized at the start may not draw again until restored. - assert_eq!(first_frame(1, s(60), true), FirstFrame::Shown); + assert_eq!(first_frame(1, s(60), Some(s(60)), true), FirstFrame::Shown); // A hung adapter is left out once, like one that failed. let skip = vec!["Dx12:10de:28a0".to_string()]; assert_eq!(restart_without(true, 1, Some("Dx12:10de:28a0"), &skip), None); diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 379d6fd242..2ca282d74c 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -44,19 +44,50 @@ macro_rules! dialog_settings { dialog_settings!(rfd::FileDialog, rfd::AsyncFileDialog); +/// On Linux and the BSDs the dialog is GTK's or the desktop portal's, which match a file type's +/// `*.ext` patterns case-sensitively. +const CASE_SENSITIVE_FILTERS: bool = + cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")); + +/// The extensions an open dialog's filter is given for `exts`: with `any_case`, each extension +/// that has a letter is followed by a pattern with each letter as a `[xX]` pair, so the filter for +/// `dib` also lists `image.DIB` and `image.Dib`. +fn open_extensions(exts: &[impl AsRef], any_case: bool) -> Vec { + let mut out = Vec::with_capacity(exts.len() * 2); + for e in exts { + let e = e.as_ref(); + out.push(e.to_string()); + if any_case && e.chars().any(|c| c.is_ascii_alphabetic()) { + out.push( + e.chars() + .map(|c| if c.is_ascii_alphabetic() { format!("[{}{}]", c.to_ascii_lowercase(), c.to_ascii_uppercase()) } else { c.to_string() }) + .collect(), + ); + } + } + out +} + /// `d` set up for `request`: its title, file types, folder and suggested name. fn dialog_for(d: D, request: &PickRequest) -> D { let pick = match request { PickRequest::Open(pick) | PickRequest::Save(pick) => pick, PickRequest::OpenMany => { return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { - d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts) + d.filter( + vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), + &open_extensions(exts, CASE_SENSITIVE_FILTERS), + ) }); } PickRequest::Folder => return d, }; + let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_)); let d = pick.filters.iter().fold(d, |d, (name, exts)| { - d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), exts) + d.filter( + vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), + &open_extensions(exts, any_case), + ) }); let d = match &pick.folder { Some(folder) => d.folder(folder), @@ -663,3 +694,84 @@ mod open_with_tests { assert_eq!(super::registry_default_path(windows::Win32::System::Registry::HKEY_CURRENT_USER, &key), None, "deleted"); } } + +#[cfg(test)] +mod dialog_tests { + use super::{CASE_SENSITIVE_FILTERS, DialogSettings, FilePick, PickRequest, dialog_for, fileio, open_extensions}; + + /// The file types a dialog was given, by label. + #[derive(Default)] + struct Filters(Vec<(String, Vec)>); + + impl DialogSettings for Filters { + fn parent(self, _window: &winit::window::Window) -> Self { + self + } + fn title(self, _title: &str) -> Self { + self + } + fn filter(mut self, name: &str, exts: &[impl ToString]) -> Self { + self.0.push((name.to_string(), exts.iter().map(ToString::to_string).collect())); + self + } + fn folder(self, _folder: &str) -> Self { + self + } + fn file_name(self, _name: &str) -> Self { + self + } + } + + /// Does the case-sensitive pattern `*.{ext}` match `name`? `ext` may hold literal characters, + /// `*` and `[..]` sets. + fn matches(ext: &str, name: &str) -> bool { + fn here(p: &[char], n: &[char]) -> bool { + match p.split_first() { + None => n.is_empty(), + Some(('*', rest)) => (0..=n.len()).any(|i| here(rest, &n[i..])), + Some(('[', rest)) => { + let Some(end) = rest.iter().position(|&c| c == ']') else { return false }; + n.split_first().is_some_and(|(c, n)| rest[..end].contains(c) && here(&rest[end + 1..], n)) + } + Some((c, rest)) => n.split_first().is_some_and(|(d, n)| d == c && here(rest, n)), + } + } + let pattern: Vec = format!("*.{ext}").chars().collect(); + here(&pattern, &name.chars().collect::>()) + } + + /// Where filters match case-sensitively, every extension of File › Open and Place lists files + /// whose extension is in capitals or mixed case, `image.DIB` and `image.Pns` included. + #[test] + fn open_and_place_filters_list_extensions_in_any_case() { + let all = fileio::open_filters().chain(fileio::place_filters()); + for (label, exts) in all { + let patterns = open_extensions(exts, true); + for ext in exts { + let mut mixed = ext.to_ascii_uppercase(); + mixed.replace_range(..1, &ext[..1]); + for name in [format!("a.{ext}"), format!("a.{}", ext.to_ascii_uppercase()), format!("a.{mixed}")] { + assert!(patterns.iter().any(|p| matches(p, &name)), "{label}: {patterns:?} don't match {name}"); + } + } + } + assert_eq!(open_extensions(&["dib", "jp2", "*"], true), ["dib", "[dD][iI][bB]", "jp2", "[jJ][pP]2", "*"]); + assert_eq!(open_extensions(&["dib", "PNS"], false), ["dib", "PNS"]); + } + + /// Open and Place dialogs get the any-case patterns on Linux and the BSDs; a save dialog's file + /// types stay as listed. + #[test] + fn open_dialogs_get_any_case_patterns_where_filters_are_case_sensitive() { + let dib = vec![FilePick::filter("BMP", &["bmp", "dib"])]; + let pick = FilePick { filters: dib.clone(), ..Default::default() }; + let expected = |any_case: bool| open_extensions(&["bmp", "dib"], any_case); + let opened = dialog_for(Filters::default(), &PickRequest::Open(pick.clone())).0; + assert_eq!(opened[0].1, expected(CASE_SENSITIVE_FILTERS)); + let saved = dialog_for(Filters::default(), &PickRequest::Save(pick)).0; + assert_eq!(saved, dib); + let placed = dialog_for(Filters::default(), &PickRequest::OpenMany).0; + let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS)); + assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first); + } +} diff --git a/contributors/people.toml b/contributors/people.toml index f4e508fdf5..405c471a23 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -201,3 +201,11 @@ sync_github_name = false [people.FrancoJacquet] real_name = "Franco Jacquet" + +[people.FractalEncrypt] +sync_github_name = true + +[people.sadkotheguest] +real_name = "Alexander Buraga" +display_name = "Alexander Buraga" +sync_github_name = false diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 652db3340b..794f92aeea 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -86,6 +86,9 @@ const TINT_STEPS: u32 = 16; const MIN_INK_LIGHTNESS_SPAN: f64 = 1.0 / 255.0; /// Most stops on a gradient's curve that [`Gradient::ink_tints`] finds tints for. const MAX_INK_TINTS: usize = 4096; +/// How many even steps [`Gradient::ink_mixes`] checks the lightness of two stops' display RGB mix +/// at, to tell whether it moves steadily from one stop's lightness to the other's. +const INK_MIX_STEPS: u32 = 64; /// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly /// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved @@ -401,8 +404,10 @@ impl Gradient { /// The weight is the one at which the two stops' colors mixed in display RGB have the OKLab /// lightness of the color on the curve there, found to [`TINT_STEPS`] halvings, or the mix /// position itself when the two colors' lightness differs by less than - /// [`MIN_INK_LIGHTNESS_SPAN`]. `None` for a Classic gradient, and when the curve has more than - /// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]). + /// [`MIN_INK_LIGHTNESS_SPAN`], or when the display RGB mix's lightness turns back somewhere + /// on the way from one color's lightness to the other's (checked at [`INK_MIX_STEPS`] even + /// steps), as from red to blue. `None` for a Classic gradient, and when the curve has more + /// than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]). pub fn ink_mixes(&self) -> Option> { use crate::libraries::srgb_to_oklab; if self.method.is_classic() || !self.fits_ink_tints() { @@ -414,8 +419,16 @@ impl Gradient { out.push((s.offset, i, 0.0, s.opacity)); let Some(n) = self.stops.get(i + 1) else { continue }; let (l0, l1) = (lightness(&s.color), lightness(&n.color)); + let mixed_lightness = |w: f32| lightness(&GradientMethod::Classic.mix(&s.color, &n.color, w)); + // The mix position itself when the lightness doesn't tell the mixes apart. + let by_position = (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN + || !(0..=INK_MIX_STEPS) + .map(|k| mixed_lightness(k as f32 / INK_MIX_STEPS as f32)) + .collect::>() + .windows(2) + .all(|w| (w[1] - w[0]) * (l1 - l0) >= 0.0); for v in perceptual_mixes(s, n) { - let weight = if (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN { + let weight = if by_position { v } else { let want = lightness(&self.method.mix(&s.color, &n.color, v)); @@ -423,7 +436,7 @@ impl Gradient { for _ in 0..TINT_STEPS { let mid = (lo + hi) / 2.0; // The mix at `mid` has not yet gone from stop `i`'s lightness to the wanted one. - if (lightness(&GradientMethod::Classic.mix(&s.color, &n.color, mid)) - want) * (l1 - l0) < 0.0 { + if (mixed_lightness(mid) - want) * (l1 - l0) < 0.0 { lo = mid; } else { hi = mid; diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 1e75feb335..1005b84300 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -585,3 +585,22 @@ fn ink_mixes_follow_the_perceptual_curve() { g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { magenta } else { Color::WHITE })).collect(); assert_eq!(g.ink_mixes(), None); } + +/// From red to blue the display RGB mix darkens past blue's lightness and comes back, so a +/// weight found by lightness near the blue stop would be a red-side one and the inks would jump +/// there. The weights are the mix positions instead, and reach the blue stop's inks steadily. +#[test] +fn ink_mixes_use_the_mix_position_when_the_lightness_turns_back() { + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red), GradientStop::new(1.0, blue)]); + g.method = GradientMethod::Perceptual; + let mixes = g.ink_mixes().expect("a Perceptual gradient's curve"); + assert_eq!(mixes[mixes.len() - 1], (1.0, 1, 0.0, 1.0), "the blue stop"); + let between: Vec<_> = mixes.iter().filter(|m| m.1 == 0 && m.0 > 0.0).collect(); + assert!(!between.is_empty(), "stops on the curve between red and blue: {mixes:?}"); + // With the midpoint at ½, a stop's offset on the curve is its mix position. + for (t, _, w, _) in &between { + assert!((w - t).abs() < 1e-6, "at {t}: weight {w}"); + } + assert!(mixes.windows(2).filter(|p| p[1].1 == 0).all(|p| p[0].2 <= p[1].2), "the weights rise: {mixes:?}"); +} diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index c9a6c5f56a..efd7f80b22 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -99,13 +99,15 @@ impl Document { } /// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working - /// copy of art the mask or the symbol already holds (the engine syncs it after every edit). + /// copy of art the mask or the symbol already holds (the engine syncs it after every edit). The + /// layer is removed wherever it is, also as a sublayer of another layer; an id that names + /// anything other than a layer is left alone. pub fn drop_edit_modes(&mut self) { - if let Some(me) = self.mask_edit.take() { - self.layers.retain(|l| l.id != me.layer); - } - if let Some(se) = self.symbol_edit.take() { - self.layers.retain(|l| l.id != se.layer); + let layers = [self.mask_edit.take().map(|me| me.layer), self.symbol_edit.take().map(|se| se.layer)]; + for id in layers.into_iter().flatten() { + if self.node(id).is_some_and(Node::is_layer) { + let _ = self.remove(id); + } } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index b59f661c21..2a51b662b3 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -40,6 +40,7 @@ pub mod live; pub mod live_paint; pub mod marks; mod mem; +pub use mem::{appearance_heap_bytes, paint_heap_bytes}; pub mod metadata; pub mod node; pub mod objects_on_path; @@ -67,6 +68,7 @@ mod symbols; pub use symbols::SymbolBoxes; pub mod text; pub mod trace; +pub mod twist; pub mod variables; pub mod xml_id; @@ -110,6 +112,7 @@ pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes}; pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource}; pub use style_libs::StyleLibrary; pub use text::FontHeightReference; +pub use text::GlyphChoice; pub use text::{ AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt, JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition, @@ -226,8 +229,9 @@ pub struct Document { #[serde(default, skip_serializing)] pub mask_edit: Option, /// Symbol editing mode, while active. Never saved (see [`Document::without_edit_modes`]): the - /// symbol already holds the art of its editing layer. - #[serde(default, skip_serializing)] + /// symbol already holds the art of its editing layer. Never read either: a value in file data + /// is dropped, so the layer it names is kept and saving does not write the value again. + #[serde(default, skip_serializing, deserialize_with = "skip::read_as_none")] pub symbol_edit: Option, next_id: u64, /// Foreign data preserved on round-trip. diff --git a/crates/doc/src/limits.rs b/crates/doc/src/limits.rs index 027148ade2..86c2e802a7 100644 --- a/crates/doc/src/limits.rs +++ b/crates/doc/src/limits.rs @@ -13,7 +13,9 @@ pub enum DocError { Invalid(String), } -pub const FORMAT_VERSION: u32 = 1; +/// The document version new documents get. Version 2: a positive Twist angle turns clockwise +/// ([`crate::twist`]). +pub const FORMAT_VERSION: u32 = 2; /// Node, slice and asset ids are handed out below this: no document gets near it by counting, so /// larger ids in a file are damage (or made by hand) and the counter never follows them (#1718). diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index a1268505fb..a938308226 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -98,7 +98,7 @@ impl Document { vec_bytes(g) + g.iter().map(|g: &SwatchGroup| g.name.capacity() + swatches_bytes(&g.swatches)).sum::() }); n += shared(&self.graphic_styles, &newer.graphic_styles, |g| { - vec_bytes(g) + g.iter().map(|g: &GraphicStyle| g.name.capacity() + appearance_heap(&g.appearance)).sum::() + vec_bytes(g) + g.iter().map(|g: &GraphicStyle| g.name.capacity() + appearance_heap_bytes(&g.appearance)).sum::() }); let styles = |s: &Vec| vec_bytes(s) + s.iter().map(|s| s.name.capacity() + map_bytes(&s.attrs)).sum::(); n += shared(&self.char_styles, &newer.char_styles, styles); @@ -245,7 +245,7 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize { let mut b = ALLOC + ARC + size_of::(); b += n.name.as_ref().map_or(0, String::capacity); if !other.is_some_and(|m| Shared::ptr_eq(&m.appearance, &n.appearance)) { - b += ALLOC + ARC + appearance_heap(&n.appearance); + b += ALLOC + ARC + appearance_heap_bytes(&n.appearance); } if let Some(e) = n.extras_box() { b += ALLOC + size_of::(); @@ -293,32 +293,53 @@ fn text_bytes(t: &TextObject) -> usize { + vec_bytes(&t.cached_baselines) } -/// The heap an appearance owns (not the appearance itself). -fn appearance_heap(a: &Appearance) -> usize { +/// Approximate retained memory of an appearance and its owned buffers, without serialization. +pub fn appearance_heap_bytes(a: &Appearance) -> usize { size_of::() + vec_bytes(&a.items) + a.items .iter() - .map(|i| match i { - AppearanceItem::Fill(f) => paint_heap(&f.paint), - AppearanceItem::Stroke(s) => paint_heap(&s.paint), + .map(|item| { + let paint = paint_heap_bytes(item.paint()); + let effects = effects_heap(item.effects()); + let stroke = match item { + AppearanceItem::Stroke(s) => { + s.dash.as_ref().map_or(0, |d| vec_bytes(&d.pattern)) + + s.profile.as_ref().map_or(0, |p| vec_bytes(&p.points)) + + s.pressure.as_ref().map_or(0, |p| vec_bytes(&p.points)) + + s.brush.as_ref().map_or(0, String::capacity) + } + _ => 0, + }; + paint + effects + stroke }) .sum::() - + vec_bytes(&a.effects) - + a.effects.iter().map(|e: &Effect| e.id.capacity() + json_bytes(&e.params)).sum::() + + effects_heap(&a.effects) } -fn paint_heap(p: &Paint) -> usize { +fn effects_heap(effects: &Vec) -> usize { + vec_bytes(effects) + effects.iter().map(|e| e.id.capacity() + json_bytes(&e.params)).sum::() +} + +/// Approximate heap retained by one paint, without serializing it. +pub fn paint_heap_bytes(p: &Paint) -> usize { match p { Paint::Solid { swatch, .. } => swatch.as_ref().map_or(0, String::capacity), - Paint::Gradient(g) => ALLOC + size_of_val(&**g) + vec_bytes(&g.gradient.stops), + Paint::Gradient(g) => { + ALLOC + + size_of_val(&**g) + + vec_bytes(&g.gradient.stops) + + g.gradient.stops.iter().map(|s| s.swatch.as_ref().map_or(0, String::capacity)).sum::() + + g.swatch.as_ref().map_or(0, String::capacity) + + g.freeform.as_ref().map_or(0, |f| vec_bytes(&f.points) + vec_bytes(&f.lines) + f.lines.iter().map(vec_bytes).sum::()) + } Paint::Pattern { pattern, .. } => pattern.capacity(), Paint::None => 0, } } fn swatches_bytes(s: &[Swatch]) -> usize { - ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap(&w.paint)).sum::() + ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::() } /// A vector's buffer (not what its elements own). diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 07899196c2..1af9fb2500 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -212,7 +212,10 @@ impl Node { /// [`Node::reach_bounds`] with symbol instances measured by their symbol's art box from /// `symbols`. An instance that only moves its art is measured as the art's visual box moved, /// and any other instance is measured as its geometric box ([`Node::geometric_bounds_with`]) - /// grown by the farthest a stroke in the art can reach. + /// grown by the farthest a stroke in the art can reach. For an instance placed through 9-slice + /// guides, that box also holds the art box placed by each cell's map + /// ([`crate::NineSliceMap::placement_bounds`]). An instance whose art holds an instance of a + /// symbol with 9-slice guides at any depth is measured as its art placed by its transform. pub fn reach_bounds_with(&self, symbols: &SymbolBoxes) -> Option { symbols.quickly(|| self.reach(Some(symbols))) } @@ -367,9 +370,14 @@ impl Node { Some((_, art)) if moves_only(*xf) => xf.transform_rect_bbox(art.visual), Some((s, art)) => { let placed = xf.transform_rect_bbox(art.geometric); - match s.placed_visual(symbol, *xf) { + match s.placed_visual(symbol, *xf).or_else(|| s.sliced_visual(symbol, *xf)) { Some(v) => v.union(placed), - None => placed.inflate(art.reach, art.reach), + // Art placed through 9-slice guides can draw outside `placed`. + None => s + .document() + .symbol_slice_map_of(symbol, art.geometric, *xf) + .map_or(placed, |m| m.placement_bounds(art.geometric).union(placed)) + .inflate(art.reach, art.reach), } } None => xf.transform_rect_bbox(SYMBOL_SQUARE), diff --git a/crates/doc/src/skip.rs b/crates/doc/src/skip.rs index 15f294c009..b26a1a7ac5 100644 --- a/crates/doc/src/skip.rs +++ b/crates/doc/src/skip.rs @@ -13,3 +13,8 @@ pub fn is_empty_vec(v: &[T]) -> bool { pub fn is_empty_map(v: &serde_json::Map) -> bool { v.is_empty() } +/// Read a field's value and drop it, giving `None`: for state that is never taken from a file. +pub fn read_as_none<'de, D: serde::Deserializer<'de>, T>(d: D) -> Result, D::Error> { + ::deserialize(d)?; + Ok(None) +} diff --git a/crates/doc/src/style_libs.rs b/crates/doc/src/style_libs.rs index 30aae49e1e..6eda3acef1 100644 --- a/crates/doc/src/style_libs.rs +++ b/crates/doc/src/style_libs.rs @@ -98,6 +98,10 @@ impl GraphicStyle { /// The extension (and `format` header) of graphic style library files. pub const STYLES_EXT: &str = "vcstyles"; +/// The version of the `.vcstyles` files [`write`] writes. Version 2: a positive Twist angle turns +/// clockwise ([`crate::twist`]). +const STYLES_VERSION: u32 = crate::twist::TWIST_CLOCKWISE_SINCE; + /// The file: a header around the library. #[derive(Serialize, Deserialize)] struct NativeFile { @@ -109,17 +113,21 @@ struct NativeFile { /// `lib` as a `.vcstyles` file. pub fn write(lib: &StyleLibrary) -> String { - let file = NativeFile { format: STYLES_EXT.into(), version: 1, library: lib.clone() }; + let file = NativeFile { format: STYLES_EXT.into(), version: STYLES_VERSION, library: lib.clone() }; serde_json::to_string_pretty(&file).unwrap_or_default() } -/// Read a `.vcstyles` file; an unnamed library is called `name`. +/// Read a `.vcstyles` file; an unnamed library is called `name`. A version 1 file was written by +/// an app that turned Twist counterclockwise: its Twist angles are negated. pub fn read(text: &str, name: &str) -> Result { let f: NativeFile = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("not a graphic style library: {e}"))?; if f.format != STYLES_EXT { return Err(format!("not a graphic style library (format `{}`)", f.format)); } let mut lib = f.library; + if f.version < STYLES_VERSION { + crate::twist::negate_library(&mut lib); + } if lib.name.trim().is_empty() { lib.name = name.into(); } diff --git a/crates/doc/src/symbol_nine_slice.rs b/crates/doc/src/symbol_nine_slice.rs index 8d7c108ab5..acc682872c 100644 --- a/crates/doc/src/symbol_nine_slice.rs +++ b/crates/doc/src/symbol_nine_slice.rs @@ -343,6 +343,20 @@ impl NineSliceMap { self.cell_xf(self.x.cell(q.x), self.y.cell(q.y)) } + /// A box that holds everything [`Self::place`] draws of art whose geometric box in symbol space + /// is `art`, before strokes and effects: `art` placed by each of the nine cells' maps. An object + /// that crosses a guide and draws symbol art is placed by the map of the cell its center is in, + /// so it can draw outside the box the corner cells place `art` in. + pub fn placement_bounds(&self, art: Rect) -> Rect { + let mut b = self.cell_xf(0, 0).transform_rect_bbox(art); + for j in 0..3 { + for i in 0..3 { + b = b.union(self.cell_xf(i, j).transform_rect_bbox(art)); + } + } + b + } + /// The guides in symbol space: the two x values and the two y values. fn cuts(&self) -> ([f64; 2], [f64; 2]) { let inv = self.natural.inverse(); @@ -704,6 +718,12 @@ impl Document { NineSliceMap::new(guides, art, self.symbol_natural_xf(name), xf) } + /// [`Self::symbol_slice_map`] with the guides cutting `art`, the symbol's art box already + /// measured. + pub(crate) fn symbol_slice_map_of(&self, name: &str, art: Rect, xf: Affine) -> Option { + NineSliceMap::new(self.symbol_nine_slice(name)?, art, self.symbol_natural_xf(name), xf) + } + /// Art `art` of symbol `name` (stained as the caller draws it) placed by an instance's /// transform `xf`, with strokes at their own weight: through the symbol's 9-slice guides when /// it has them ([`NineSliceMap::place`]), otherwise by `xf`. `None` when placing it through diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index 7e371c670e..2cf260cbec 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -23,6 +23,9 @@ const MAX_DEPTH: usize = 32; /// holding instances: past it, an estimate stands in ([`SymbolBoxes::effects_reach`]). const MAX_REACHES: usize = 4096; +/// A symbol's name and the bits of the linear part of a transform that places its art. +type Placing = (String, [u64; 4]); + /// A symbol's art measured in symbol space. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct ArtBox { @@ -37,6 +40,9 @@ pub(crate) struct ArtBox { /// The widest stroke of the objects with a visible brushed stroke in the art, or in the art /// of a symbol an instance in it shows: `None` when no object there has one. pub(crate) brush: Option, + /// Whether the art holds an instance of a symbol with 9-slice guides, or of a symbol whose art + /// holds one at any depth. + pub(crate) sliced: bool, } /// The art boxes of a document's symbols, which [`Node::geometric_bounds_with`], @@ -73,6 +79,14 @@ pub struct SymbolBoxes<'a> { unplaced: RefCell>, /// How many times [`Self::measure_art`] has run a measure on symbol art ([`Self::art_measured`]). runs: Cell, + /// The boxes [`Self::sliced_visual`] has measured, by symbol name and the bits of the linear + /// part of the transform that placed the art. + sliced: RefCell>>, + /// How many objects of symbol art [`Self::sliced_visual`] has placed, the art of opacity masks + /// included. + sliced_placed: Cell, + /// The most objects of symbol art [`Self::sliced_visual`] places: [`MAX_SYMBOL_NODES`]. + sliced_most: u64, } impl Document { @@ -90,6 +104,9 @@ impl Document { farthest: RefCell::default(), unplaced: RefCell::default(), runs: Cell::new(0), + sliced: RefCell::default(), + sliced_placed: Cell::new(0), + sliced_most: MAX_SYMBOL_NODES, } } } @@ -102,7 +119,11 @@ impl<'a> SymbolBoxes<'a> { /// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its /// art box alone. An instance that scales or turns stroked art then measures a little larger - /// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. + /// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The + /// visual box of an instance placed through 9-slice guides holds the art box placed by each + /// cell's map ([`crate::NineSliceMap::placement_bounds`]). An instance whose art holds an + /// instance of a symbol with 9-slice guides at any depth is measured as its art placed by its + /// transform ([`Self::sliced_visual`]). pub fn quick(self) -> Self { self.quick.set(true); self @@ -319,13 +340,64 @@ impl<'a> SymbolBoxes<'a> { if self.quick.get() { return None; } + self.place_and_measure(name, xf, most) + } + + /// [`Self::placed_visual`] in boxes made by [`Self::quick`] and while symbol art is measured + /// too, for a symbol whose art holds an instance of a symbol with 9-slice guides at any depth: + /// where that instance draws its art depends on the transform of each instance above it. The + /// art is placed once for each symbol and linear part of `xf`, and the box is moved by the rest + /// of `xf`. `None` for other symbols, when [`Self::placed_visual`] is `None` outside quick + /// boxes, and when placing the art would take the objects of the art these boxes have placed + /// for it past [`MAX_SYMBOL_NODES`], the art placed to measure the instances in placed art + /// included. The renderer draws no more objects of symbol art than that in one frame. + pub(crate) fn sliced_visual(&self, name: &str, xf: Affine) -> Option { + if !self.art(name)?.sliced { + return None; + } + let [a, b, c, d, e, f] = xf.as_coeffs(); + let (linear, moved) = (Affine::new([a, b, c, d, 0.0, 0.0]), Affine::translate((e, f))); + let key = (name.to_string(), [a, b, c, d].map(f64::to_bits)); + let cached = self.sliced.borrow().get(&key).copied(); + let v = match cached { + Some(v) => v, + None => { + // The most objects placing makes, the art of opacity masks included, is set aside + // while the art is placed and measured, and what placing did not make is given back. + let art = &self.doc.symbols.iter().find(|s| s.name == name)?.art; + let most = match self.doc.symbol_slice_map(name, linear) { + Some(m) => m.most_placed(art, self.doc), + None => art.count_with_masks() as u64, + }; + let used = self.sliced_placed.get(); + if used.saturating_add(most) > self.sliced_most { + return None; + } + self.sliced_placed.set(used + most); + let (v, placed) = self.place_and_count(name, linear, MAX_SYMBOL_NODES).unwrap_or((None, 0)); + self.sliced_placed.set(self.sliced_placed.get().saturating_sub(most.saturating_sub(placed))); + self.sliced.borrow_mut().insert(key, v); + v + } + }; + v.map(|v| moved.transform_rect_bbox(v)) + } + + /// The box [`Self::placed_visual_within`] returns outside quick boxes. + fn place_and_measure(&self, name: &str, xf: Affine, most: u64) -> Option { + self.place_and_count(name, xf, most).and_then(|(v, _)| v) + } + + /// [`Self::place_and_measure`], with the number of objects of the placed art, the art of + /// opacity masks included. `None` when the art is not placed. + fn place_and_count(&self, name: &str, xf: Affine, most: u64) -> Option<(Option, u64)> { self.measure_art(name, |art| { let art = match self.doc.symbol_slice_map(name, xf) { Some(m) if m.most_placed(art, self.doc) > most => return None, Some(m) => m.place(art, self.doc), None => self.doc.place_symbol_art(name, art, xf)?, }; - self.in_art(|| art.visual(Some(self))) + Some((self.in_art(|| art.visual(Some(self))), art.count_with_masks() as u64)) }) .flatten() } @@ -383,6 +455,7 @@ fn art_box(art: &Arc, symbols: &SymbolBoxes) -> Option { let reach = crate::live::max_outset(std::slice::from_ref(art), Some(symbols)); let mut effects = false; let mut brush: Option = None; + let mut sliced = false; art.walk(&mut |n| { let mut own = n.appearance.effects.iter().chain(n.appearance.items.iter().flat_map(|i| i.effects().iter())); effects |= own.any(|e| e.visible); @@ -395,9 +468,10 @@ fn art_box(art: &Arc, symbols: &SymbolBoxes) -> Option { if let Some(w) = symbols.brush_width(symbol) { brush = Some(brush.map_or(w, |b| b.max(w))); } + sliced |= symbols.doc.symbol_nine_slice(symbol).is_some() || symbols.art(symbol).is_some_and(|a| a.sliced); } }); - Some(ArtBox { geometric, visual, reach, effects, brush }) + Some(ArtBox { geometric, visual, reach, effects, brush, sliced }) } #[cfg(test)] @@ -447,6 +521,100 @@ mod tests { assert_eq!(scaled.reach_bounds_with(&s), Some(Rect::new(0.0, 0.0, 60.0, 30.0).inflate(reach, reach))); } + #[test] + fn quick_boxes_hold_art_that_9_slice_guides_move_past_the_instance() { + // A 100 × 100 frame with guides a quarter in, holding an instance of a bar from x 10 to 70. + // Scaled 2 times across, the bar crosses the left guide and is placed by the middle + // column's map, x → 3x − 50: it draws from x −20 to 160, past the frame's left edge at 0. + let mut d = Document::new(200.0, 200.0); + let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0); + symbol(&mut d, "Bar", vec![bar]); + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0); + let inner = instance(&mut d, "Bar", Affine::IDENTITY); + symbol(&mut d, "Panel", vec![frame, inner]); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + let panel = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0)); + let exact = panel.visual_bounds_with(&d.symbol_boxes()).unwrap(); + assert_eq!(exact, Rect::new(-20.0, 0.0, 200.0, 100.0)); + let quick = panel.visual_bounds_with(&d.symbol_boxes().quick()).unwrap(); + assert_eq!(quick.union(exact), quick, "{quick:?} holds {exact:?}"); + } + + #[test] + fn quick_boxes_hold_art_that_nested_9_slice_guides_move_past_the_instance() { + // The panel of the test above, in a symbol without guides: once at its natural size and + // once scaled 2 times across. Where the bar draws depends on the transform the holder's + // instance adds to the panel's. + let mut d = Document::new(200.0, 200.0); + let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0); + symbol(&mut d, "Bar", vec![bar]); + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0); + let inner = instance(&mut d, "Bar", Affine::IDENTITY); + symbol(&mut d, "Panel", vec![frame, inner]); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + let natural = instance(&mut d, "Panel", Affine::IDENTITY); + symbol(&mut d, "Holder", vec![natural]); + let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0)); + symbol(&mut d, "Wide holder", vec![wide]); + // The holder scaled 2 times across scales the panel 2 times across: the bar draws from x + // −20 to 160, as in the test above. + let holder = instance(&mut d, "Holder", Affine::scale_non_uniform(2.0, 1.0)); + let quick = holder.visual_bounds_with(&d.symbol_boxes().quick()).unwrap(); + let drawn = Rect::new(-20.0, 40.0, 160.0, 60.0); + assert_eq!(quick.union(drawn), quick, "{quick:?} holds {drawn:?}"); + let wide_holder = instance(&mut d, "Wide holder", Affine::scale(2.0)); + for n in [&holder, &wide_holder] { + let exact = n.visual_bounds_with(&d.symbol_boxes()).unwrap(); + assert!(exact.x0 < 0.0, "{exact:?} reaches past the frame's left edge"); + let quick = n.visual_bounds_with(&d.symbol_boxes().quick()).unwrap(); + assert_eq!(quick.union(exact), quick, "{quick:?} holds {exact:?}"); + let reach = n.reach_bounds_with(&d.symbol_boxes()).unwrap(); + assert_eq!(reach.union(exact), reach, "{reach:?} holds {exact:?}"); + } + } + + #[test] + fn quick_boxes_place_art_that_holds_9_slice_instances_a_bounded_number_of_times() { + // A frame with guides, and 16 levels of symbols that each hold an instance of the level + // below a little taller and one turned a little: the transforms that place the frame differ + // for each of the 2^16 ways down, so measuring every one would place art 2^17 times. + let mut d = Document::new(200.0, 200.0); + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0); + symbol(&mut d, "Level 0", vec![frame]); + d.set_symbol_nine_slice("Level 0", Some(crate::SymbolNineSlice::default())); + let (taller, turned) = (Affine::scale_non_uniform(1.0, 1.01), Affine::rotate(0.1)); + for i in 1..=16 { + let below = format!("Level {}", i - 1); + let pair = vec![instance(&mut d, &below, taller), instance(&mut d, &below, turned)]; + symbol(&mut d, &format!("Level {i}"), pair); + } + let top = instance(&mut d, "Level 16", taller); + // With room for 5,000 objects: each placement places at least one. + let s = SymbolBoxes { sliced_most: 5000, ..d.symbol_boxes().quick() }; + assert!(top.visual_bounds_with(&s).is_some()); + assert!(s.sliced_placed.get() <= 5000, "{} objects", s.sliced_placed.get()); + assert!(s.art_measured() <= 5000 + d.symbols.len(), "{} measures", s.art_measured()); + // Instances whose transforms differ only by a move place the art once. + let level = instance(&mut d, "Level 1", taller); + let moved = instance(&mut d, "Level 1", Affine::translate((5.0, 7.0)) * taller); + let s = d.symbol_boxes().quick(); + let b = level.visual_bounds_with(&s).unwrap(); + let measured = s.art_measured(); + assert_eq!(moved.visual_bounds_with(&s), Some(Affine::translate((5.0, 7.0)).transform_rect_bbox(b))); + assert_eq!(s.art_measured(), measured); + // The art of an opacity mask counts toward the limit: a group holding the framed + // instance, masked by a group of 10 rectangles, is 13 objects. + let mut framed = instance(&mut d, "Level 0", Affine::IDENTITY); + let squares = (0..10).map(|_| Arc::new(rect(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0), 0.0))).collect(); + let mask = Node::group(d.alloc_id(), squares); + framed.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(mask, true))); + symbol(&mut d, "Masked", vec![framed]); + let masked = instance(&mut d, "Masked", taller); + let s = d.symbol_boxes().quick(); + assert!(masked.visual_bounds_with(&s).is_some()); + assert_eq!(s.sliced_placed.get(), 13); + } + #[test] fn missing_symbols_and_symbols_inside_themselves_measure_as_the_square() { let mut d = Document::new(200.0, 200.0); diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 37e2d39bca..4b75b01497 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -451,3 +451,64 @@ fn pica_form_rejects_exponent_notation() { assert_eq!(Unit::Points.parse(s), None, "{s}"); } } + +/// Symbol editing of symbol "S" on `layer`. +fn symbol_edit_on(layer: NodeId) -> SymbolEdit { + SymbolEdit { + symbol: "S".into(), + layer, + instance: None, + xf: Affine::IDENTITY, + group: false, + changed: false, + back_isolation: None, + back_layer: None, + } +} + +/// The opacity-mask and symbol editing layers are left out of the saved document wherever they +/// are, also when `layer.move` made them sublayers of another layer. +#[test] +fn edit_mode_layers_are_dropped_as_sublayers_too() { + let mut d = Document::new(612.0, 792.0); + let host = d.layers[0].id; + let mask = d.add_layer(Some("Mask")); + let symbol = d.add_layer(Some("Symbol")); + d.move_node(mask, Some(host), 0).unwrap(); + d.move_node(symbol, Some(host), usize::MAX).unwrap(); + let object = d.alloc_id(); + d.mask_edit = Some(MaskEdit { object, layer: mask }); + d.symbol_edit = Some(symbol_edit_on(symbol)); + let saved = d.without_edit_modes(); + assert!(saved.node(mask).is_none(), "the mask editing layer is left out"); + assert!(saved.node(symbol).is_none(), "the symbol editing layer is left out"); + assert!(saved.node(host).is_some_and(|l| l.children().is_some_and(|c| c.is_empty()))); + assert!(saved.mask_edit.is_none() && saved.symbol_edit.is_none()); +} + +/// Symbol editing is never read from a file, so a layer that file data names as the editing layer +/// loads and stays in the document, and saving does not write the value again. +#[test] +fn symbol_edit_is_not_read_from_a_file() { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let mut v = serde_json::to_value(&d).unwrap(); + v["symbol_edit"] = serde_json::to_value(symbol_edit_on(layer)).unwrap(); + d = serde_json::from_value(v).unwrap(); + assert_eq!(d.symbol_edit, None); + assert!(d.extra.is_empty(), "not kept as an unknown key"); + d.drop_edit_modes(); + assert!(d.node(layer).is_some(), "the layer is kept"); + assert!(serde_json::to_value(&d).unwrap().get("symbol_edit").is_none(), "not saved again"); +} + +/// An opacity-mask editing id in file data that names art inside a layer, not a layer, leaves the +/// art in place. +#[test] +fn mask_edit_naming_art_leaves_it() { + let (mut d, a, b) = doc_with_rects(); + d.mask_edit = Some(MaskEdit { object: b, layer: a }); + d.drop_edit_modes(); + assert!(d.node(a).is_some() && d.node(b).is_some()); + assert_eq!(d.mask_edit, None); +} diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 064ecbda10..a2f21e856c 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -16,7 +16,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, ScriptMetrics}; +pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, ScriptMetrics}; pub use para_style::{ Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, SingleWordJustify, diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 5461f005ec..731480fed0 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -147,6 +147,28 @@ pub struct CharStyle { /// document's language (Document Setup). Saved only when set. #[serde(default, skip_serializing_if = "Option::is_none")] pub language: Option, + /// Another glyph of the font for the run's first character (Glyphs panel › Show › Alternates + /// for Current Selection). The text keeps the character; layout draws the chosen glyph while + /// the run starts with that character and is set in the face the choice names, and the + /// default glyph otherwise. Saved only when set. + #[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")] + pub glyph_alternate: Option, +} + +/// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it +/// belongs to, named by its PostScript name and version string, so that a glyph id is never used +/// in another font or another version of the font. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct GlyphChoice { + /// The character the glyph is drawn for. + pub ch: char, + /// The glyph id in the face. + pub gid: u32, + /// The face's PostScript name (`SourceSans3-Regular`). + pub font: String, + /// The face's version string (`Version 3.052`); empty when it has none. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub version: String, } /// What a character's font size measures ([`CharStyle::font_height_reference`]): the em square @@ -420,6 +442,7 @@ impl Default for CharStyle { font_height_reference: FontHeightReference::EmBox, no_break: false, language: None, + glyph_alternate: None, } } } diff --git a/crates/doc/src/twist.rs b/crates/doc/src/twist.rs new file mode 100644 index 0000000000..8865fd2a9b --- /dev/null +++ b/crates/doc/src/twist.rs @@ -0,0 +1,231 @@ +//! The Twist effect's angle in saved documents. A positive angle turns clockwise on the page in +//! VectorCraft 0.21.0 and later; earlier releases turned it counterclockwise. Documents of version +//! 2 ([`TWIST_CLOCKWISE_SINCE`]) turn clockwise. Version 1 documents written before 0.21.0 have +//! their Twist angles negated when they open, so they draw as they were saved +//! ([`Document::migrate_twist_angles`], [`written_clockwise`]), and a save for an earlier app +//! negates them back ([`Document::store_legacy_twist_angles`]). Graphic style library files +//! (`.vcstyles`) of version 1 have their Twist angles negated when they are read +//! ([`crate::style_libs::read`]); [`crate::style_libs::write`] writes version 2. + +use std::sync::Arc; + +use serde_json::{Map, Value, json}; + +use crate::style_libs::StyleLibrary; +use crate::{Appearance, Document, Effect, Node}; + +/// The Twist effect's id. +pub const TWIST: &str = "distort.twist"; + +/// The first document version whose Twist angles turn clockwise for a positive value. +pub const TWIST_CLOCKWISE_SINCE: u32 = 2; + +/// The first release (major, minor) whose Twist turned clockwise for a positive angle. +const CLOCKWISE_RELEASE: (u64, u64) = (0, 21); + +/// Did the app named by a native file's `generator` (`"VectorCraft 0.21.0"`) turn Twist effects +/// clockwise for a positive angle? It did from 0.21.0. Any other value, or none, is an earlier +/// app (DrawCraft included). +pub fn written_clockwise(generator: Option<&str>) -> bool { + let Some(version) = generator.and_then(|g| g.strip_prefix("VectorCraft ")) else { return false }; + let mut parts = version.split('.').map(|p| p.parse::().ok()); + match (parts.next().flatten(), parts.next().flatten()) { + (Some(major), Some(minor)) => (major, minor) >= CLOCKWISE_RELEASE, + _ => false, + } +} + +/// The angle a Twist effect without a readable one draws with (`vectorcraft-effects` reads a +/// missing or unreadable `angle` as this). +const DEFAULT_ANGLE: f64 = 10.0; + +/// The key of `Document::unknown` that holds the brush definitions (`vectorcraft-brush`'s +/// `DOC_KEY`), whose art can carry effects. +const BRUSHES_KEY: &str = "brushes"; + +/// The angle a Twist effect with `params` draws with, read as `vectorcraft-effects` reads it: a +/// number, the number a string starts with, or a boolean as 1 or 0; anything else (or a value +/// that is not finite) is [`DEFAULT_ANGLE`]. +fn angle(params: &Value) -> f64 { + let v = match params.get("angle") { + Some(Value::Number(n)) => n.as_f64(), + Some(Value::String(s)) => { + let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect(); + t.parse().ok() + } + Some(Value::Bool(b)) => Some(if *b { 1.0 } else { 0.0 }), + _ => None, + }; + v.filter(|v| v.is_finite()).unwrap_or(DEFAULT_ANGLE) +} + +/// Write the negated angle a Twist effect with `params` draws with into `params`, as a number. +fn negate_params(params: &mut Value) { + // `0.0 - a` rather than `-a`: an angle of 0 stays 0, not -0. + let turned = Value::from(0.0 - angle(params)); + match params { + Value::Object(m) => { + m.insert("angle".into(), turned); + } + p => *p = json!({ "angle": turned }), + } +} + +fn has_twist(fx: &[Effect]) -> bool { + fx.iter().any(|e| e.id == TWIST) +} + +fn appearance_has_twist(a: &Appearance) -> bool { + has_twist(&a.effects) || a.items.iter().any(|i| has_twist(i.effects())) +} + +fn negate_appearance(a: &mut Appearance) { + for e in a.effects.iter_mut().chain(a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) { + if e.id == TWIST { + negate_params(&mut e.params); + } + } +} + +/// The appearances a Shaper Group's face and edge edits paint with. +fn shaper_appearances(n: &Node) -> impl Iterator { + let s = n.extras().shaper.as_deref(); + let faces = s.into_iter().flat_map(|s| s.faces.iter().filter_map(|f| f.paint.as_ref())); + let edges = s.into_iter().flat_map(|s| s.edges.iter().filter_map(|e| e.paint.as_ref())); + faces.chain(edges) +} + +/// Does `n`'s subtree (opacity-mask art and Shaper edits included) hold a Twist effect? +fn node_has_twist(n: &Node) -> bool { + appearance_has_twist(&n.appearance) + || n.extras().mask.as_ref().is_some_and(|m| node_has_twist(&m.art)) + || shaper_appearances(n).any(appearance_has_twist) + || n.children().is_some_and(|c| c.iter().any(|c| node_has_twist(c))) +} + +/// Negate the Twist angles of `a`'s subtree, copying only the nodes on the way to them. +fn negate_node(a: &mut Arc) { + if !node_has_twist(a) { + return; + } + let n = Arc::make_mut(a); + if appearance_has_twist(&n.appearance) { + negate_appearance(&mut n.appearance); + } + if let Some(x) = n.extras_if_any() { + if let Some(m) = x.mask.as_mut() { + negate_node(&mut m.art); + } + if let Some(s) = x.shaper.as_mut() { + let faces = s.faces.iter_mut().filter_map(|f| f.paint.as_mut()); + for p in faces.chain(s.edges.iter_mut().filter_map(|e| e.paint.as_mut())) { + negate_appearance(p); + } + } + } + for c in n.children_mut().into_iter().flatten() { + negate_node(c); + } +} + +fn is_twist_json(m: &Map) -> bool { + m.get("id").and_then(Value::as_str) == Some(TWIST) +} + +/// Does JSON `v` (brush definitions) hold a Twist effect? +fn json_has_twist(v: &Value) -> bool { + match v { + Value::Object(m) => is_twist_json(m) || m.values().any(json_has_twist), + Value::Array(a) => a.iter().any(json_has_twist), + _ => false, + } +} + +/// Negate the Twist angles in JSON `v`: every object whose `id` is [`TWIST`] is a serialized +/// [`Effect`] (object ids are numbers). +fn negate_json(v: &mut Value) { + match v { + Value::Object(m) if is_twist_json(m) => negate_params(m.entry("params").or_insert(Value::Null)), + Value::Object(m) => m.values_mut().for_each(negate_json), + Value::Array(a) => a.iter_mut().for_each(negate_json), + _ => {} + } +} + +/// Negate every Twist angle of a graphic style library: its styles' and its patterns' art. +pub(crate) fn negate_library(lib: &mut StyleLibrary) { + for g in &mut lib.styles { + negate_appearance(&mut g.appearance); + } + for p in &mut lib.patterns { + p.art.iter_mut().for_each(negate_node); + } +} + +impl Document { + /// A document before version [`TWIST_CLOCKWISE_SINCE`] that holds a Twist effect: when + /// `written_clockwise` (asked only then; see [`written_clockwise`]) says the app that saved it + /// turned Twist counterclockwise, negate its Twist angles, so it draws as it was saved. A later + /// version is left as it is, and the document's version is not changed. It recurses through + /// the art, once per level of nesting. + pub fn migrate_twist_angles(&mut self, written_clockwise: impl FnOnce() -> bool) { + if self.version >= TWIST_CLOCKWISE_SINCE || !self.has_twist() || written_clockwise() { + return; + } + self.negate_twist_angles(); + } + + /// The reverse of [`Document::migrate_twist_angles`], for saving for an app that turned Twist + /// counterclockwise: negate the Twist angles and mark the document version 1. Call it on a + /// document whose angles turn clockwise, as every opened or new document's do, whatever + /// version another conversion for that save has marked it already. + pub fn store_legacy_twist_angles(&mut self) { + self.version = TWIST_CLOCKWISE_SINCE - 1; + if self.has_twist() { + self.negate_twist_angles(); + } + } + + /// Does any Twist effect sit where [`Document::negate_twist_angles`] negates them? + fn has_twist(&self) -> bool { + let mut roots = self + .layers + .iter() + .chain(self.symbols.iter().map(|s| &s.art)) + .chain(self.graph_designs.iter().map(|g| &g.art)) + .chain(self.patterns.iter().flat_map(|p| p.art.iter())) + .chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter())); + roots.any(|r| node_has_twist(r)) + || self.graphic_styles.iter().any(|g| appearance_has_twist(&g.appearance)) + || self.unknown.get(BRUSHES_KEY).is_some_and(json_has_twist) + } + + /// Negate every Twist angle: in the art of the layers, symbols, graph designs, pattern + /// swatches and the pattern definition that pattern editing's Cancel puts back (opacity-mask + /// art and Shaper edits included), in the graphic styles and in the brush definitions. + fn negate_twist_angles(&mut self) { + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + negate_node(root); + } + if self.graphic_styles.iter().any(|g| appearance_has_twist(&g.appearance)) { + for g in self.graphic_styles.iter_mut() { + negate_appearance(&mut g.appearance); + } + } + if self.unknown.get(BRUSHES_KEY).is_some_and(json_has_twist) + && let Some(b) = self.unknown.get_mut(BRUSHES_KEY) + { + negate_json(b); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/doc/src/twist/tests.rs b/crates/doc/src/twist/tests.rs new file mode 100644 index 0000000000..699be66cb4 --- /dev/null +++ b/crates/doc/src/twist/tests.rs @@ -0,0 +1,186 @@ +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect, shapes}; + +use super::*; +use crate::shaper::{FaceEdit, FaceSelector, ShaperSpec}; +use crate::{GraphicStyle, OpacityMask, PatternDef, Symbol}; + +fn fx(id: &str, params: Value) -> Effect { + Effect { id: id.into(), params, visible: true } +} + +/// An appearance with a Twist of `params` on the object and on its fill, and a Roughen. +fn twisted_appearance(params: &Value) -> Appearance { + let mut a = Appearance::default_art(); + a.effects.push(fx(TWIST, params.clone())); + a.effects.push(fx("distort.roughen", json!({"size": 5}))); + a.items[0].effects_mut().push(fx(TWIST, params.clone())); + a +} + +fn twisted(d: &mut Document, params: &Value) -> Node { + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), twisted_appearance(params)) +} + +/// A version 1 document with Twist effects of `params` everywhere one is stored: on a path, in a +/// group, in an opacity mask's art, in a Shaper edit, in a symbol, a pattern swatch and a graphic +/// style, and `brush` in a brush definition. Its first layer holds the art; its last has no +/// Twist. +fn document(params: &Value, brush: &Value) -> Document { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let path = twisted(&mut d, params); + d.insert(Some(l), 0, path).unwrap(); + let inner = twisted(&mut d, params); + let group = Node::group(d.alloc_id(), vec![Arc::new(inner)]); + d.insert(Some(l), 1, group).unwrap(); + let mask_art = twisted(&mut d, params); + let mut masked = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()); + masked.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, true))); + d.insert(Some(l), 2, masked).unwrap(); + let mut shaper = Node::group(d.alloc_id(), vec![]); + let face = FaceEdit { + selector: FaceSelector { sources: vec![0], anchor: Point::ZERO }, + erase: false, + erase_edges: false, + paint_source: None, + merge: None, + paint: Some(twisted_appearance(params)), + }; + shaper.extras_mut().shaper = Some(Box::new(ShaperSpec { faces: vec![face], edges: vec![] })); + d.insert(Some(l), 3, shaper).unwrap(); + let art = twisted(&mut d, params); + d.symbols.push(Symbol { name: "S".into(), art: Arc::new(art), dynamic: false }); + let art = twisted(&mut d, params); + d.patterns.push(PatternDef::new("P", vec![Arc::new(art)])); + d.graphic_styles.push(GraphicStyle::new("G", twisted_appearance(params))); + d.unknown.insert(BRUSHES_KEY.into(), json!([{"name": "B", "art": {"id": 99, "appearance": {"effects": [brush]}}}])); + d.add_layer(None); + d.version = 1; + d +} + +/// The angle each Twist effect of the saved document draws with, in the order the JSON lists them. +fn angles(d: &Document) -> Vec { + fn walk(v: &Value, out: &mut Vec) { + match v { + Value::Object(m) => { + if is_twist_json(m) { + out.push(angle(m.get("params").unwrap_or(&Value::Null))); + } + m.values().for_each(|c| walk(c, out)); + } + Value::Array(a) => a.iter().for_each(|c| walk(c, out)), + _ => {} + } + } + let mut out = vec![]; + walk(&serde_json::to_value(d).unwrap(), &mut out); + out +} + +#[test] +fn a_version_1_document_from_before_0_21_has_its_twist_angles_negated() { + let mut d = document(&json!({"angle": 30}), &json!({"id": TWIST})); + let before = angles(&d); + // Two per path, shaper edit and style; one in the brush. + assert_eq!(before.len(), 15, "{before:?}"); + assert_eq!(before.iter().filter(|&&a| a == DEFAULT_ANGLE).count(), 1, "{before:?}"); + d.migrate_twist_angles(|| false); + assert_eq!(d.version, 1, "the caller sets the version"); + assert_eq!(angles(&d), before.iter().map(|a| -a).collect::>()); + let roughen = serde_json::to_string(&d).unwrap().matches(r#""id":"distort.roughen","params":{"size":5}"#).count(); + assert_eq!(roughen, 7, "other effects are left alone"); +} + +#[test] +fn a_document_that_turned_clockwise_is_left_as_it_is() { + let mut d = document(&json!({"angle": 30}), &json!({"id": TWIST, "params": {"angle": 30}})); + let before = d.clone(); + d.migrate_twist_angles(|| true); + assert_eq!(d, before, "version 1, written by 0.21.0 or later"); + d.version = 2; + let before = d.clone(); + d.migrate_twist_angles(|| panic!("a version 2 document's writer is not asked about")); + assert_eq!(d, before, "version 2"); +} + +#[test] +fn the_writer_is_asked_about_only_when_a_twist_is_stored() { + let mut d = Document::new(10.0, 10.0); + d.version = 1; + let before = d.clone(); + d.migrate_twist_angles(|| panic!("a document without a Twist needs no answer")); + assert_eq!(d, before); +} + +#[test] +fn angles_are_read_as_the_effect_reads_them() { + let read = |params: Value| { + let mut e = fx(TWIST, params); + negate_params(&mut e.params); + e.params + }; + assert_eq!(read(json!({"angle": 30, "x": 1})), json!({"angle": -30.0, "x": 1})); + assert_eq!(read(json!({"angle": "45 deg"})), json!({"angle": -45.0})); + assert_eq!(read(json!({"angle": true})), json!({"angle": -1.0})); + assert_eq!(read(json!({})), json!({"angle": -10.0})); + assert_eq!(read(Value::Null), json!({"angle": -10.0})); + let zero = read(json!({"angle": 0})); + assert!(zero["angle"].as_f64().is_some_and(|a| a == 0.0 && a.is_sign_positive()), "{zero}"); +} + +#[test] +fn only_the_art_holding_a_twist_is_copied() { + let mut d = document(&json!({"angle": 30}), &json!({"id": TWIST})); + let plain = d.layers.last().cloned().unwrap(); + let twisted = d.layers[0].clone(); + d.migrate_twist_angles(|| false); + assert!(Arc::ptr_eq(d.layers.last().unwrap(), &plain), "a layer without a Twist is not copied"); + assert!(!Arc::ptr_eq(&d.layers[0], &twisted)); +} + +#[test] +fn storing_for_an_earlier_app_and_reading_back_round_trips() { + let original = document(&json!({"angle": 30.0}), &json!({"id": TWIST, "params": {"angle": -12.5}})); + let mut d = original.clone(); + d.migrate_twist_angles(|| false); + d.version = 2; + let current = d.clone(); + assert_eq!(angles(¤t), angles(&original).iter().map(|a| -a).collect::>()); + d.store_legacy_twist_angles(); + assert_eq!(d, original); + d.migrate_twist_angles(|| false); + d.version = 2; + assert_eq!(d, current); + // Another conversion for the same save may have marked the document version 1 already. + d.version = 1; + d.store_legacy_twist_angles(); + assert_eq!(d, original); +} + +#[test] +fn a_version_1_style_library_has_its_twist_angles_negated() { + let lib = StyleLibrary { name: "L".into(), styles: vec![GraphicStyle::new("G", twisted_appearance(&json!({"angle": 30.0})))], patterns: vec![] }; + let text = crate::style_libs::write(&lib); + assert!(text.contains(r#""version": 2"#), "{text}"); + assert_eq!(crate::style_libs::read(&text, "x").unwrap(), lib, "a version 2 file reads as written"); + let old = crate::style_libs::read(&text.replacen(r#""version": 2"#, r#""version": 1"#, 1), "x").unwrap(); + let fx = &old.styles[0].appearance.effects; + assert_eq!(fx[0].params, json!({"angle": -30.0})); + assert_eq!(fx[1], lib.styles[0].appearance.effects[1]); + assert_eq!(old.styles[0].appearance.items[0].effects()[0].params, json!({"angle": -30.0})); +} + +#[test] +fn releases_from_0_21_turned_twist_clockwise() { + for g in ["VectorCraft 0.21.0", "VectorCraft 0.21.4", "VectorCraft 0.22.0-dev", "VectorCraft 1.0.0"] { + assert!(written_clockwise(Some(g)), "{g}"); + } + for g in ["VectorCraft 0.20.0", "VectorCraft 0.9.12", "DrawCraft 0.1.0", "VectorCraft", "VectorCraft x.y", "vectorcraft 0.21.0"] { + assert!(!written_clockwise(Some(g)), "{g}"); + } + assert!(!written_clockwise(None)); +} diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 9af1cfffd3..fbbf3b0a90 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -77,7 +77,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, outset, raster_effects}; +pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects}; pub use reshape::{ SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape, diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index f8590bbb2e..a1d8df2d61 100644 --- a/crates/effects/src/raster.rs +++ b/crates/effects/src/raster.rs @@ -366,7 +366,7 @@ pub fn blend_mode(s: &str) -> BlendMode { } /// An effect's `color` parameter (`"#rrggbb"`, `[r, g, b]` 0..1 or a colour object). -pub(crate) fn color_param(p: &Value, default: Color) -> Color { +pub fn color_param(p: &Value, default: Color) -> Color { match p.get("color") { Some(Value::String(s)) => Color::from_hex(s).unwrap_or(default), Some(Value::Array(a)) if a.len() >= 3 => { diff --git a/crates/engine/examples/anchor_bench.rs b/crates/engine/examples/anchor_bench.rs new file mode 100644 index 0000000000..877526b109 --- /dev/null +++ b/crates/engine/examples/anchor_bench.rs @@ -0,0 +1,320 @@ +//! `cargo run --release -p vectorcraft-engine --example anchor_bench` prints the wall time of the +//! engine steps of editing anchors with Direct Selection, on three synthetic documents: one closed path of +//! 50,000 anchors, 2,000 closed paths of 50 anchors each, and one open path of 200,000 anchors. +//! `ITERS` sets the runs per step (default 7); each row is the median in ms. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind}; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{Affine, Anchor, PathData, Point, SubPath, Vec2}; +use vectorcraft_render::{RenderOptions, Renderer}; + +/// Anchors are 10 pt apart and their handles 3 pt long, along the path. +const STEP: f64 = 10.0; +const HANDLE: f64 = 3.0; + +/// A test document: its paths, an anchor to hover, click and drag, a point on a segment, and a +/// marquee from an empty point over about 10,000 anchors. +struct Shape { + name: &'static str, + doc: Document, + ids: Vec, + anchor: (NodeId, usize), + segment: Point, + marquee: (Point, Point), +} + +/// A closed path of `n` smooth anchors around `center`. +fn circle(center: Point, n: usize) -> PathData { + let r = n as f64 * STEP / std::f64::consts::TAU; + let anchors = (0..n) + .map(|i| { + let t = i as f64 / n as f64 * std::f64::consts::TAU; + let p = center + Vec2::new(r * t.cos(), r * t.sin()); + Anchor::smooth(p, p + Vec2::new(-t.sin(), t.cos()) * HANDLE) + }) + .collect(); + PathData::single(SubPath::new(anchors, true)) +} + +fn add(doc: &mut Document, path: PathData) -> NodeId { + let l = doc.layers.first().map(|l| l.id); + let id = doc.alloc_id(); + doc.insert(l, usize::MAX, Node::path(id, path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap(); + id +} + +fn one_outline() -> Shape { + let n = 50_000; + let mut doc = Document::new(1600.0, 1200.0); + let id = add(&mut doc, circle(Point::ZERO, n)); + let r = n as f64 * STEP / std::f64::consts::TAU; + let a = 72f64.to_radians(); + let mid = (n / 2) as f64 / n as f64 * std::f64::consts::TAU; + let next = (n / 2 + 1) as f64 / n as f64 * std::f64::consts::TAU; + let segment = Point::new(r * (mid.cos() + next.cos()) / 2.0, r * (mid.sin() + next.sin()) / 2.0); + Shape { + name: "one closed path, 50,000 anchors", + doc, + ids: vec![id], + anchor: (id, n / 2), + segment, + marquee: (Point::new(r + 50.0, -5.0), Point::new(r * a.cos() - 1.0, r * a.sin() + 1.0)), + } +} + +fn many_paths() -> Shape { + let mut doc = Document::new(1600.0, 1200.0); + let ids: Vec = + (0..2000).map(|i| add(&mut doc, circle(Point::new((i % 50) as f64 * 200.0 + 100.0, (i / 50) as f64 * 200.0 + 100.0), 50))).collect(); + let r = 50.0 * STEP / std::f64::consts::TAU; + // Path 1,025 (row 20, column 25), its anchors 0 and 1. + let c = Point::new(25.0 * 200.0 + 100.0, 20.0 * 200.0 + 100.0); + let t = std::f64::consts::TAU / 50.0; + let segment = c + Vec2::new(r * (1.0 + t.cos()) / 2.0, r * t.sin() / 2.0); + Shape { + name: "2,000 closed paths, 50 anchors each", + doc, + anchor: (ids[1025], 0), + ids, + segment, + marquee: (Point::ZERO, Point::new(10_000.0, 800.0)), + } +} + +fn long_open_path() -> Shape { + let n = 200_000; + let mut doc = Document::new(1600.0, 1200.0); + let anchors = (0..n) + .map(|i| { + let p = Point::new(i as f64 * STEP, 0.0); + Anchor::smooth(p, p + Vec2::new(HANDLE, 0.0)) + }) + .collect(); + let id = add(&mut doc, PathData::single(SubPath::new(anchors, false))); + Shape { + name: "one open path, 200,000 anchors", + doc, + ids: vec![id], + anchor: (id, n / 2), + segment: Point::new((n / 2) as f64 * STEP + STEP / 2.0, 0.0), + marquee: (Point::new(-5.0, -20.0), Point::new(99_995.0, 30.0)), + } +} + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(mut ms: Vec) -> f64 { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +fn time(mut f: impl FnMut()) -> f64 { + median( + (0..iters()) + .map(|_| { + let t = Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + }) + .collect(), + ) +} + +fn ev(kind: PointerKind, p: Point) -> PointerEvent { + PointerEvent::new(kind, p.x, p.y) +} + +fn exec(s: &mut Session, cmd: &str, p: Value) { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")); +} + +fn anchor_at(s: &Session, (id, ai): (NodeId, usize)) -> Anchor { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[ai] +} + +/// The anchors selected: those direct-selected, and every anchor of a path selected whole. +fn selected_anchors(s: &Session) -> usize { + let st = s.doc().unwrap(); + let count = |id: &NodeId| st.doc.node(*id).and_then(|n| n.path_data()).map_or(0, |pd| pd.anchors().count()); + st.selection.objects.iter().map(|id| st.selection.partial(*id).map_or_else(|| count(id), |set| set.len())).sum() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn row(name: &str, ms: f64) { + println!(" {name:<58} {ms:>10.3} ms"); +} + +/// Select `count` anchors: the first ones of the first path, or the first anchors of as many +/// paths as needed. +fn select_count(s: &mut Session, shape: &Shape, count: usize) { + exec(s, "select.none", json!({})); + let mut left = count; + for id in &shape.ids { + if left == 0 { + break; + } + let n = s.doc().unwrap().doc.node(*id).unwrap().path_data().unwrap().subpaths[0].anchors.len(); + let take = left.min(n); + let refs: Vec<[usize; 2]> = (0..take).map(|i| [0, i]).collect(); + exec(s, "select.anchors", json!({"id": id.0, "anchors": refs, "mode": "add"})); + left -= take; + } +} + +fn bench(shape: Shape) { + println!("{}", shape.name); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + let mut s = Session::new(); + s.add_document(shape.doc.clone(), None); + s.select_tool("directSelection", view).unwrap(); + let a = anchor_at(&s, shape.anchor).p; + let none = Mods::default(); + { + let doc = s.doc().unwrap().doc.clone(); + let opt = vectorcraft_doc::hit::HitOptions { tol: 3.0, clip_outlines: true, ..Default::default() }; + row("hit test at an anchor", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, a, opt))))); + row("hit test at a segment", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, shape.segment, opt))))); + row("hit test beside the path", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, shape.segment + Vec2::new(0.0, 40.0), opt))))); + } + + // Hover with nothing selected, then with one anchor of the path selected. + for selected in [false, true] { + if selected { + exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"})); + } + let what = if selected { "one anchor selected" } else { "nothing selected" }; + row(&format!("hover over an anchor, {what}"), time(|| drop(s.pointer(&ev(PointerKind::Move, a), view).unwrap()))); + row(&format!("cursor over an anchor, {what}"), time(|| _ = black_box(s.cursor(a, none, view)))); + row(&format!("hover over a segment, {what}"), time(|| drop(s.pointer(&ev(PointerKind::Move, shape.segment), view).unwrap()))); + row(&format!("cursor over a segment, {what}"), time(|| _ = black_box(s.cursor(shape.segment, none, view)))); + } + + // A click that selects one anchor. + exec(&mut s, "select.none", json!({})); + row( + "click that selects one anchor", + time(|| { + s.pointer(&ev(PointerKind::Down, a), view).unwrap(); + s.pointer(&ev(PointerKind::Up, a), view).unwrap(); + }), + ); + assert_eq!(selected_anchors(&s), 1, "the click selects one anchor"); + + // One anchor dragged: each pointer move, then the release. + let undo = undo_len(&s); + s.pointer(&ev(PointerKind::Down, a), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, a + Vec2::new(0.0, 20.0)), view).unwrap(); + let mut y = 20.0; + row( + "anchor drag, one pointer move", + time(|| { + y += 1.0; + s.pointer(&ev(PointerKind::Drag, a + Vec2::new(0.0, y)), view).unwrap(); + }), + ); + let t = Instant::now(); + s.pointer(&ev(PointerKind::Up, a + Vec2::new(0.0, y)), view).unwrap(); + row("anchor drag, release (commit)", t.elapsed().as_secs_f64() * 1000.0); + assert_eq!(undo_len(&s), undo + 1, "the anchor drag records one step"); + exec(&mut s, "edit.undo", json!({})); + + // The selected anchor's outgoing handle dragged. + exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"})); + let h = anchor_at(&s, shape.anchor).h_out; + let undo = undo_len(&s); + s.pointer(&ev(PointerKind::Down, h), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, h + Vec2::new(0.0, 20.0)), view).unwrap(); + let mut y = 20.0; + row( + "handle drag, one pointer move", + time(|| { + y += 1.0; + s.pointer(&ev(PointerKind::Drag, h + Vec2::new(0.0, y)), view).unwrap(); + }), + ); + let t = Instant::now(); + s.pointer(&ev(PointerKind::Up, h + Vec2::new(0.0, y)), view).unwrap(); + row("handle drag, release (commit)", t.elapsed().as_secs_f64() * 1000.0); + assert_eq!(undo_len(&s), undo + 1, "the handle drag records one step"); + assert_eq!(anchor_at(&s, shape.anchor).p, a, "the handle drag leaves the anchor in place"); + exec(&mut s, "edit.undo", json!({})); + + // A marquee over about 10,000 anchors. + let (m0, m1) = shape.marquee; + let ms = time(|| { + exec(&mut s, "select.none", json!({})); + s.pointer(&ev(PointerKind::Down, m0), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, m0.lerp(m1, 0.5)), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, m1), view).unwrap(); + s.pointer(&ev(PointerKind::Up, m1), view).unwrap(); + }); + row(&format!("marquee over {} anchors (press to release)", selected_anchors(&s)), ms); + + // Select All with Direct Selection. + row("Select All", time(|| exec(&mut s, "select.all", json!({})))); + row("tool overlays, everything selected", time(|| drop(s.overlays(view)))); + + // Nudges of 1, 1,000 and every anchor, and Undo and Redo of each. + let total: usize = shape.ids.iter().map(|id| s.doc().unwrap().doc.node(*id).unwrap().path_data().unwrap().subpaths[0].anchors.len()).sum(); + for count in [1, 1000, total] { + select_count(&mut s, &shape, count); + row(&format!("nudge of {count} anchors"), time(|| exec(&mut s, "path.moveAnchors", json!({"dx": 1, "dy": 0})))); + row(&format!("undo of a nudge of {count} anchors"), time(|| exec(&mut s, "edit.undo", json!({})))); + row(&format!("redo of a nudge of {count} anchors"), time(|| exec(&mut s, "edit.redo", json!({})))); + } + + // The render of the document after one anchor moves (the renderer warm). + exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"})); + let opts = RenderOptions::default(); + let mut r = Renderer::new(); + let at = Affine::translate(Vec2::new(800.0 - a.x, 600.0 - a.y)); + r.render(&s.doc().unwrap().doc, 1600, 1200, at, &opts); + let ms = median( + (0..iters()) + .map(|_| { + exec(&mut s, "path.moveAnchors", json!({"dx": 0, "dy": 1})); + let doc = s.doc().unwrap().doc.clone(); + let t = Instant::now(); + drop(r.render(&doc, 1600, 1200, at, &opts)); + t.elapsed().as_secs_f64() * 1000.0 + }) + .collect(), + ); + row("render 1600x1200 around the anchor after it moves", ms); + let doc = s.doc().unwrap().doc.clone(); + row("render 1600x1200 around the anchor, nothing changed", time(|| drop(r.render(&doc, 1600, 1200, at, &opts)))); + + // Delete of one anchor, undone after each run. + let ms = median( + (0..iters()) + .map(|_| { + exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"})); + let t = Instant::now(); + exec(&mut s, "edit.clear", json!({})); + let ms = t.elapsed().as_secs_f64() * 1000.0; + exec(&mut s, "edit.undo", json!({})); + ms + }) + .collect(), + ); + row("Delete of one anchor", ms); +} + +fn main() { + bench(one_outline()); + bench(many_paths()); + bench(long_open_path()); +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 1af3693ca5..b1b9efd60b 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -168,9 +168,9 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) } } -/// Objects are selected, or the Artboard tool is chosen (Copy and Cut take its artboard). -pub fn has_selection_or_artboard_tool(s: &Session) -> std::result::Result<(), String> { - if s.tool_id() == "artboard" { has_doc(s) } else { has_selection(s) } +/// Objects or ruler guides are selected, or the Artboard tool is chosen (what Copy and Cut take). +pub fn has_selection_guides_or_artboard_tool(s: &Session) -> std::result::Result<(), String> { + if s.tool_id() == "artboard" { has_doc(s) } else { has_selection_or_guides(s) } } /// Objects or ruler guides are selected (what Delete and the arrow keys act on). pub fn has_selection_or_guides(s: &Session) -> std::result::Result<(), String> { @@ -484,9 +484,10 @@ pub fn matrix_param(p: &Value, key: &str) -> Option { } /// A colour from `"#rrggbb"`, a colour key (`"cmyk 0 100 100 0"`, `"lab 55 60 40"`), `[r,g,b]` (0..1), /// `{"c":..,"m":..,"y":..,"k":..}` (percent when any component is above 1, else 0..1), `{"gray":..}` or `{"l":..,"a":..,"b":..}` (CIE Lab: L 0..100, a and b about -/// −128..127). +/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`). pub fn color_value(v: &Value) -> Option { match v { + Value::String(s) if hex_with_alpha(s) => None, // A hex, or a colour key ("cmyk 0 100 100 0", as Recolor Artwork lists colours). Value::String(s) => Color::from_hex(s).or_else(|| vectorcraft_color::recolor::ColorKey::parse(s).map(|k| k.color())), Value::Array(a) if a.len() >= 3 => Some(Color::rgb(a[0].as_f64()? as f32, a[1].as_f64()? as f32, a[2].as_f64()? as f32)), @@ -512,6 +513,23 @@ pub fn color_value(v: &Value) -> Option { } } +/// Is `s` a hex color with an alpha part: eight or four hex digits, with or without the `#`? +/// [`Color::from_hex`] reads `#rrggbbaa` as `#rrggbb`, without the alpha. +pub(crate) fn hex_with_alpha(s: &str) -> bool { + let s = s.trim(); + let h = s.strip_prefix('#').unwrap_or(s); + matches!(h.len(), 4 | 8) && h.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// The color `p` gives for `key`, read by [`color_value`]: `None` when `p` leaves it out or gives +/// null. Any other value that is not a color is an error: "bad color {v}". +pub(crate) fn color_param(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key).filter(|v| !v.is_null()) { + None => Ok(None), + Some(v) => color_value(v).map(Some).ok_or_else(|| bad(cmd, format!("bad color {v}"))), + } +} + /// `v` as an object id: an error unless it is a non-negative integer. fn object_id(v: &Value) -> Result { v.as_u64().map(NodeId).ok_or_else(|| EngineError::Other(format!("object ids are non-negative integers, not {v}"))) diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 02f8864423..ac9597cbd8 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -7,6 +7,7 @@ mod color; mod document; mod pathtools; mod pen; +mod select; mod typetools; use super::CommandSpec; @@ -19,6 +20,7 @@ pub fn specs() -> Vec { v.extend(document::specs()); v.extend(pathtools::specs()); v.extend(pen::specs()); + v.extend(select::specs()); v.extend(typetools::specs()); v } diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index d1ed6c84a7..ac8947cb4a 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -59,7 +59,7 @@ pub fn specs() -> Vec { "Find Nearest Swatch", ["Object", "Plug-ins", "Color Effects"], None, - "{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}", + "{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up, #rrggbbaa and #rgba refused; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}", has_doc, nearest::find ), diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 30548b80a7..52f7f3168e 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -1,9 +1,11 @@ //! Document Tools (`addon.document.*`), a built-in add-on: Save a Timestamped Copy writes a copy of //! the document named with the date and time through File › Save a Copy's save; New Symbols from //! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a -//! copy of every open document to one folder as Save a Copy does (#4920). Its submenu (Object › Plug-ins › -//! Document Tools) is the UI's. +//! copy of every open document to one folder as Save a Copy does (#4920); Batch Trace Folder traces +//! each image of a folder and saves the results to another ([`batch_trace`], #4921). Its submenu +//! (Object › Plug-ins › Document Tools) is the UI's. +mod batch_trace; #[cfg(test)] mod tests; @@ -14,7 +16,7 @@ use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolRegistration}; use super::super::brushsym::{instance_in_place, normalize, place_xf, store_symbol}; use super::super::fileio::{self, SaveMode}; -use super::super::{CommandSpec, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or}; +use super::super::{CommandSpec, always, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or}; use crate::{Result, Session}; /// The most numbers (`-2`, `-3`…) tried after a timestamped name that is taken. @@ -40,6 +42,15 @@ pub fn specs() -> Vec { has_doc, export_all_open ), + cmd!( + "addon.document.batchTraceFolder", + "Batch Trace Folder", + ["Object", "Plug-ins", "Document Tools"], + None, + "{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as . (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)", + always, + batch_trace::batch_trace_folder + ), cmd!( "addon.document.symbolsFromLayers", "New Symbols from Layers", diff --git a/crates/engine/src/cmd/addons/document/batch_trace.rs b/crates/engine/src/cmd/addons/document/batch_trace.rs new file mode 100644 index 0000000000..0340fca183 --- /dev/null +++ b/crates/engine/src/cmd/addons/document/batch_trace.rs @@ -0,0 +1,127 @@ +//! Batch Trace Folder (`addon.document.batchTraceFolder`, #4921): each image in a folder is opened, +//! traced with a preset (and expanded when asked), saved into a destination folder under its own +//! name, and closed again, whether it traced or not. + +use serde_json::Value; +#[cfg(not(target_arch = "wasm32"))] +use serde_json::json; + +#[cfg(not(target_arch = "wasm32"))] +use super::super::super::fileio; +use super::super::super::{Result, Session, bad}; +#[cfg(not(target_arch = "wasm32"))] +use super::super::super::{bool_or, str_param}; + +/// The command id. +pub(super) const ID: &str = "addon.document.batchTraceFolder"; + +#[cfg(target_arch = "wasm32")] +pub(super) fn batch_trace_folder(_: &mut Session, _: &Value) -> Result { + Err(bad(ID, "no file system here")) +} + +#[cfg(not(target_arch = "wasm32"))] +/// The image files a batch traces, by extension. +const IMAGE_EXTS: [&str; 10] = ["png", "jpg", "jpeg", "tif", "tiff", "bmp", "gif", "webp", "psd", "psb"]; +#[cfg(not(target_arch = "wasm32"))] +/// Caps on a batch (folders and MCP payloads are untrusted). +pub(super) const MAX_FILES: usize = 500; +#[cfg(not(target_arch = "wasm32"))] +const MAX_DEPTH: usize = 8; +#[cfg(not(target_arch = "wasm32"))] +const FORMATS: [&str; 5] = ["vectorcraft", "svg", "pdf", "ai", "eps"]; + +#[cfg(not(target_arch = "wasm32"))] +/// The image files in `folder` (and its subfolders with `deep`), sorted. +fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec) -> Result<()> { + if depth > MAX_DEPTH { + return Err(bad(ID, format!("folders deeper than {MAX_DEPTH} levels"))); + } + let max = MAX_FILES.saturating_mul(2); + let (entries, truncated) = fileio::list_dir(folder, max)?; + // The listing is cut before it is sorted, so a cut one could skip any image: refuse it. + if truncated { + return Err(bad(ID, format!("{folder}: more than {max} files and folders"))); + } + let mut subdirs = vec![]; + for e in entries { + let name = e.get("name").and_then(Value::as_str).unwrap_or(""); + if name.is_empty() || name.starts_with('.') { + continue; + } + let path = std::path::Path::new(folder).join(name).to_string_lossy().into_owned(); + match e.get("kind").and_then(Value::as_str) { + Some("file") if IMAGE_EXTS.contains(&fileio::extension(&path).as_str()) => out.push(path), + Some("folder") if deep => subdirs.push(path), + _ => {} + } + if out.len() > MAX_FILES { + return Err(bad(ID, format!("more than {MAX_FILES} images"))); + } + } + for d in subdirs { + images(&d, deep, depth + 1, out)?; + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result { + let folder = str_param(p, "folder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `folder`"))?; + let dest = str_param(p, "destinationFolder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `destinationFolder`"))?; + let format = str_param(p, "format").unwrap_or("vectorcraft"); + if !FORMATS.contains(&format) { + return Err(bad(ID, format!("`format` must be one of {}", FORMATS.join(", ")))); + } + let preset = str_param(p, "preset").unwrap_or("Default").to_string(); + let presets = s.execute("imageTrace.presets", &json!({}))?; + if !presets["presets"].as_array().into_iter().flatten().any(|q| q["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&preset))) { + return Err(bad(ID, format!("no tracing preset `{preset}` (see imageTrace.presets)"))); + } + let trace = if bool_or(p, "expand", false) { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; + fileio::may_read(&folder)?; + fileio::may_write(&dest)?; + let mut files = vec![]; + images(&folder, bool_or(p, "includeSubdirs", false), 0, &mut files)?; + files.sort(); + if files.is_empty() { + return Err(bad(ID, "no images in the folder")); + } + std::fs::create_dir_all(&dest).map_err(|e| bad(ID, format!("{dest}: {e}")))?; + let ext = fileio::save_format(Some(format), None).map_err(|e| bad(ID, e))?.extensions.first().copied().unwrap_or(format); + let active = s.active_index(); + let (mut traced, mut failed, mut taken) = (vec![], vec![], Vec::::new()); + for path in &files { + let opened_before = s.documents().len(); + let one = |s: &mut Session| -> Result { + s.execute("document.open", &json!({ "path": path }))?; + s.execute("select.all", &json!({}))?; + s.execute(trace, &json!({ "preset": preset }))?; + let stem = fileio::file_stem(path); + // Names this batch already took count as taken, as do files on disk. + let free = super::free_name(&dest, &stem, ext, |o| taken.iter().any(|t| t == o) || std::path::Path::new(o).exists()) + .ok_or_else(|| bad(ID, "every numbered name for the result is taken"))?; + s.execute("document.save", &json!({ "path": free, "format": format }))?; + Ok(free) + }; + let result = one(s); + // The image's document closes whatever happened, so a failure leaves no tab behind. + if s.documents().len() > opened_before + && let Some(i) = s.active_index() + { + // A just-opened image has no work to lose; if closing fails, one extra tab stays open. + let _ = s.execute("file.close", &json!({ "index": i })); + } + match result { + Ok(out) => { + taken.push(out.clone()); + traced.push(json!({ "path": path, "output": out })); + } + Err(e) => failed.push(json!({ "path": path, "error": e.to_string() })), + } + } + if let Some(i) = active.filter(|i| *i < s.documents().len()) { + s.set_active(i); + } + Ok(json!({ "traced": traced, "failed": failed, "format": format })) +} diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index 562a389e8a..a1bc5afff6 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -1,5 +1,5 @@ //! Document Tools' commands: the timestamped copy's name and place with the document left as it -//! was, symbols made of layers, and bad params refused. +//! was, symbols made of layers, a folder of images traced, and bad params refused. use std::path::{Path, PathBuf}; @@ -276,3 +276,77 @@ fn export_all_open_documents_keeps_every_page_and_artboard() { assert!(w > 19.0 && w < 30.0, "the SVG shows the art (the square on the second artboard), not the first artboard: viewBox {view}"); let _ = std::fs::remove_dir_all(&dir); } + +/// A 24×24 white PNG with a dark (or red) square in it. +#[cfg(not(target_arch = "wasm32"))] +fn png(path: &Path, dark: bool) { + let mut img = image::RgbaImage::from_pixel(24, 24, image::Rgba([255, 255, 255, 255])); + for y in 6..18 { + for x in 6..18 { + img.put_pixel(x, y, if dark { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([200, 30, 30, 255]) }); + } + } + img.save(path).unwrap(); +} + +/// #4921: each image of the folder is traced and saved under its own name; a file that isn't an +/// image is left alone, one that can't be read is reported, and every document the batch opened +/// is closed again, the active one staying active. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn batch_trace_folder_traces_and_saves_each_image() { + const C: &str = "addon.document.batchTraceFolder"; + let dir = folder("batch-trace"); + let (src, out) = (dir.join("in"), dir.join("out")); + std::fs::create_dir_all(&src).unwrap(); + png(&src.join("logo.png"), true); + png(&src.join("mark.png"), false); + std::fs::write(src.join("notes.txt"), "not an image").unwrap(); + std::fs::write(src.join("broken.png"), b"not a png").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let docs = s.documents().len(); + let r = s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg", "expand": true})).unwrap(); + assert_eq!(r["traced"].as_array().unwrap().len(), 2, "{r}"); + assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}"); + assert!(r["failed"][0]["path"].as_str().unwrap().ends_with("broken.png")); + let mut names: Vec = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, ["logo.svg", "mark.svg"]); + let svg = std::fs::read_to_string(out.join("logo.svg")).unwrap(); + assert!(svg.contains(" Vec { + vec![cmd!( + "addon.select.byArtboards", + "Select by Artboards", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", + has_doc, + by_artboards + )] +} + +fn by_artboards(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.select.byArtboards"; + let relation = text_param(p, "relation", C)?.unwrap_or("overlap"); + if !RELATIONS.contains(&relation) { + return Err(bad(C, "`relation` must be overlap, inside or outside")); + } + let listed = p.get("artboards").ok_or_else(|| bad(C, "missing `artboards`"))?; + let indices = point_indices(listed).ok_or_else(|| bad(C, "`artboards` must be a list of artboard indices"))?; + if indices.is_empty() { + return Err(bad(C, "choose at least one artboard")); + } + let st = s.doc()?; + let rects = + indices.iter().map(|i| st.doc.artboards.get(*i).map(|a| a.rect)).collect::>>().ok_or_else(|| bad(C, "no such artboard"))?; + let symbols = st.doc.symbol_boxes(); + let ids: Vec = selectable(&st.doc, st.isolation) + .into_iter() + .filter(|id| { + let Some(n) = st.doc.node(*id) else { return false }; + match relation { + "inside" => n.geometric_bounds_with(&symbols).is_some_and(|b| { + rects.iter().any(|r| { + vectorcraft_doc::artboard_holds(*r, Point::new(b.x0, b.y0)) && vectorcraft_doc::artboard_holds(*r, Point::new(b.x1, b.y1)) + }) + }), + "outside" => !rects.iter().any(|r| on_artboard(n, &symbols, *r)), + _ => rects.iter().any(|r| on_artboard(n, &symbols, *r)), + } + }) + .collect(); + s.select(|_, sel| sel.set(ids))?; + Ok(json!({ "count": s.doc()?.selection.objects.len() })) +} diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs new file mode 100644 index 0000000000..bea05ff9e2 --- /dev/null +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -0,0 +1,128 @@ +//! Select by Artboards. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; + +use crate::Session; + +const C: &str = "addon.select.byArtboards"; + +/// A document with three 100 × 100 artboards in a row, 50 pt apart: 0 at x 0, 1 at x 150, 2 at x 300. +fn three_boards() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for x in [150, 300] { + s.execute("artboard.new", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap(); + } + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +fn pick(s: &mut Session, p: Value) -> Vec { + s.execute("select.none", &json!({})).unwrap(); + let r = s.execute(C, &p).unwrap(); + let mut ids = s.doc().unwrap().selection.objects.clone(); + assert_eq!(r["count"], json!(ids.len())); + ids.sort(); + ids +} + +#[test] +fn selects_by_overlap_inside_and_outside_several_artboards() { + let mut s = three_boards(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); // inside 0 + let ab = rect(&mut s, 90.0, 40.0, 80.0, 20.0); // across 0 and 1 + let b = rect(&mut s, 160.0, 10.0, 20.0, 20.0); // inside 1 + let c = rect(&mut s, 310.0, 10.0, 20.0, 20.0); // inside 2 + let off = rect(&mut s, 0.0, 200.0, 20.0, 20.0); // on no board + let edge = rect(&mut s, 0.0, 0.0, 100.0, 100.0); // flush with board 0 + let want = |mut v: Vec| { + v.sort(); + v + }; + assert_eq!(pick(&mut s, json!({"artboards": [0, 1]})), want(vec![a, ab, b, edge])); + assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "overlap"})), want(vec![a, ab, b, edge])); + // Wholly within one board, edges included; straddling two boards is not inside either. + assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "inside"})), want(vec![a, b, edge])); + assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "outside"})), want(vec![c, off])); + assert_eq!(pick(&mut s, json!({"artboards": [2], "relation": "outside"})), want(vec![a, ab, b, off, edge])); + // One board does what All on Active Artboard does. + for i in 0..3u64 { + s.execute("select.allOnArtboard", &json!({"artboard": i})).unwrap(); + let mut on = s.doc().unwrap().selection.objects.clone(); + on.sort(); + assert_eq!(pick(&mut s, json!({"artboards": [i]})), on, "board {i}"); + } + // A board listed twice counts once. + assert_eq!(pick(&mut s, json!({"artboards": [2, 2]})), vec![c]); +} + +#[test] +fn hidden_locked_and_isolated_art_follow_select_all() { + let mut s = three_boards(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let hidden = rect(&mut s, 40.0, 10.0, 20.0, 20.0); + let locked = rect(&mut s, 70.0, 10.0, 20.0, 20.0); + let far = rect(&mut s, 0.0, 300.0, 20.0, 20.0); + s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap(); + s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap(); + assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![a]); + assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![far]); + // Art held by a locked artboard is left out. + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![]); + s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap(); + // In isolation mode only the isolated group's objects are looked at. + let b = rect(&mut s, 20.0, 50.0, 10.0, 10.0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": g})).unwrap(); + let mut both = vec![a, b]; + both.sort(); + assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), both); + assert_eq!(pick(&mut s, json!({"artboards": [1]})), vec![]); +} + +#[test] +fn bad_params_are_errors_and_leave_the_selection() { + let mut s = three_boards(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + for p in [ + json!({}), + json!({"artboards": []}), + json!({"artboards": [3]}), + json!({"artboards": [-1]}), + json!({"artboards": [0.5]}), + json!({"artboards": "0"}), + json!({"artboards": [0], "relation": "near"}), + json!({"artboards": [0], "relation": 1}), + json!({"artboards": [0], "relatoin": "inside"}), + ] { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{p}"); + } +} + +#[test] +fn a_symbol_instance_is_measured_by_its_art() { + // The symbol's art, (100, 60) to (140, 80), drawn 50 pt up and left: (50, 10) to (90, 30), on + // the 200 × 120 artboard, while the 20 × 20 square around the instance's origin lies off it. + let svg = r##""##; + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "far.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap(); + let mut instance = None; + s.doc().unwrap().doc.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. }) { + instance = Some(n.id); + } + }); + let instance = instance.unwrap(); + assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![instance]); + assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), vec![instance]); + assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![]); +} diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index 320dce6b9f..a478b8c00b 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -46,7 +46,7 @@ pub fn specs() -> Vec { "Text Tweaker", ["Object", "Plug-ins", "Type Tools"], None, - "{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}", + "{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}", has_selection, text_tweaker )] @@ -97,6 +97,7 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result { for (id, a, b, _) in ranges { let t = text_ref(s, id)?; let text = t.plain_text(); + let (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b)); let chars: Vec = text.char_indices().filter(|&(i, c)| (a..b).contains(&i) && !(skip && (c.is_whitespace() || c.is_control()))).map(|(i, _)| i).collect(); seen += chars.len(); diff --git a/crates/engine/src/cmd/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs index 6c56f67694..7f05cb823a 100644 --- a/crates/engine/src/cmd/addons/typetools/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -124,6 +124,16 @@ fn a_range_changes_only_its_characters() { assert_eq!(tracking, [0.0, 100.0, 200.0, 300.0, 0.0]); } +#[test] +fn a_range_inside_a_multibyte_character_uses_character_boundaries() { + let mut s = session(); + let id = text(&mut s, "éx"); + let out = s.execute(C, &json!({"id": id.0, "start": 1, "end": 2, "attribute": "tracking", "from": 100, "to": 300})).unwrap(); + assert_eq!(out["count"], 1); + let tracking: Vec = styles(&s, id).iter().map(|(_, st)| st.tracking).collect(); + assert_eq!(tracking, [100.0, 0.0]); +} + #[test] fn random_values_stay_in_range_and_repeat_with_the_seed() { let mut s = session(); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 990a4d97de..8fb5734efd 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row (a copy of its top fill; type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids` and no `target: \"contents\"`, the new fill is a copy of that row, right above it, and becomes the active row", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row", has_doc, |s, p| add_item(s, p, true) ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row (a copy of its top stroke, else the default stroke)", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt", has_doc, |s, p| add_item(s, p, false) ), @@ -357,11 +357,23 @@ pub(crate) fn appearances_differ(d: &vectorcraft_doc::Document, ids: &[NodeId]) /// Indices `idx` of the first target's items (aligned with `aligned`) in each of `ids`: the first /// target's own, and in each other one the items equal to them there (see [`SharedStack`]), each -/// index on its own: one the targets don't share is left out of the others (never taken as the -/// same index there). Not aligned, or one target: the same indices in each. +/// index and each target on its own: an index a target doesn't share with the first is left out +/// of that target (never taken as the same index there), whatever the other targets have. Not +/// aligned, or one target: the same indices in each. pub(crate) fn items_per_target(d: &vectorcraft_doc::Document, ids: &[NodeId], idx: &[usize], aligned: bool) -> Vec> { - match shared_stack(d, ids).filter(|_| aligned) { - Some(sh) => (0..ids.len()).map(|k| if k == 0 { idx.to_vec() } else { idx.iter().filter_map(|i| sh.item_in(*i, k)).collect() }).collect(), + let aps: Option> = ids.iter().map(|id| d.node(*id).map(|n| &*n.appearance)).collect(); + match aps.filter(|aps| aligned && aps.len() >= 2) { + Some(aps) => aps + .iter() + .enumerate() + .map(|(k, ap)| match aps.first() { + Some(first) if k > 0 => { + let sh = SharedStack::of(&[*first, *ap]); + idx.iter().filter_map(|i| sh.item_in(*i, 1)).collect() + } + _ => idx.to_vec(), + }) + .collect(), None => vec![idx.to_vec(); ids.len()], } } @@ -507,8 +519,8 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result { fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?; let defaults = s.paint.clone(); - // The panel's active Fill row, when the new fill goes on the selection: the new fill is a copy - // of that row, right above it in each target that has it (others get a copy of their top fill). + // The panel's active Fill row, when the new fill goes on the selection: the new fill takes that + // row's paint, right above it in each target that has it (others take their top fill's paint). // Where the new item went in on the active item's object, when it is an image. let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied()); // The active row is a row of the active object's stack, which need not come first in `ids` @@ -547,8 +559,9 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { } continue; } - // A copy of the top fill (stroke); without one, type's characters' and otherwise the - // default paint, so a new fill on a group or type shows. + // The top fill's (stroke's) paint; without one, type's characters' and otherwise the + // default paint, so a new fill on a group or type shows. A new stroke takes the top + // stroke's weight when that stroke has paint, at least 1 pt. let paint = match (n.appearance.paint_at(None, fill), &n.kind) { (Some(p), _) => p.clone(), (None, NodeKind::Text(_)) => super::paint::proxy_paint(n, !fill, None), diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index f5da40e7b4..a6505a057b 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -19,7 +19,7 @@ use super::edit::{outermost, selected_roots}; use super::pathops::{remove_each, separate}; use super::swatch::{anchor, names_param}; use super::{ - CommandSpec, Result, Session, bad, check_numbers, cmd, color_value, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok, + CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok, str_param, switch_or, }; use crate::EngineError; @@ -304,7 +304,7 @@ pub fn specs() -> Vec { "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color?, keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}", + "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}", has_doc, symbol_adjust ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 3bc167ffa1..77a61c58a4 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1,7 +1,7 @@ use super::dynamic::{fit_overrides, type_id, type_param}; use super::{ Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result, - SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_value, ids_json, json, + SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json, name_param, number_or, ok, remove_each, roots, selection_art, separate, set_unknown, str_param, switch_or, }; @@ -834,7 +834,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0; let alt = switch_or(p, "alt", false, C)?; let st = s.doc()?; - let color = match p.get("color").and_then(color_value) { + let color = match color_param(p, "color", C)? { Some(c) => crate::cmd::paint::new_color(s, p, c), None => s.paint.fill.color().unwrap_or(Color::BLACK), }; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index abc828b311..442b68c583 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Gap Options", [], None, - "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", + "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", has_selection_or_ids, lp_gap_options ), @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Live Paint Bucket", [], None, - "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}", + "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}", has_doc, lp_fill ), diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 29933309e9..13186ed2ef 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -93,11 +93,28 @@ pub struct Clipboard { /// The artboards copied with the Artboard tool (`artboard.copy`); `nodes` are then their art. /// Pasting adds a copy of each with the art. pub artboards: Vec, + /// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on + /// no layer: pasting puts them on the layer new art goes to, moved as the objects are. + pub guides: Vec, } impl Clipboard { pub fn is_empty(&self) -> bool { - self.nodes.is_empty() && self.artboards.is_empty() + self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty() + } + + /// Does it hold art (objects or artboards) for other apps? Ruler guides stay in VectorCraft: + /// a Copy of guides alone empties the system clipboard (#3226). + pub fn has_art(&self) -> bool { + !self.nodes.is_empty() || !self.artboards.is_empty() + } + + /// One newly made clipboard object and the source document resources it uses. Type-range + /// Copy builds an object from selected runs rather than copying a whole document node. + pub fn from_node(st: &DocState, node: Node) -> Self { + let mut clip = Self::gather(&st.doc, vec![node]); + clip.source_doc = Some(st.uid); + clip } /// Objects `roots` of `st`'s document with their resources, source artboard and layers. @@ -195,7 +212,7 @@ impl Clipboard { /// The objects as standalone SVG (`None` when there are none). pub fn svg(&self) -> Option { - if self.is_empty() { + if !self.has_art() { return None; } let d = self.to_document(); diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index b2e1114e1a..f4c096d9be 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -286,7 +286,7 @@ impl Clipboard { /// The MIME types of [`Self::flavours`], without making them. pub fn flavour_types(&self, svg: bool, pdf: bool) -> Vec<&'static str> { - if self.is_empty() { + if !self.has_art() { return vec![]; } let text = (svg && self.image_bytes() <= COPY_TEXT_IMAGE_BYTES) || self.nodes.iter().all(type_only); diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 4ab859740b..d70a81700f 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -116,7 +116,7 @@ pub fn specs() -> Vec { "Color Guide", [], None, - "{color, rule: complementary|complementary2|splitComplementary|leftComplement|rightComplement|analogous|analogous2|monochromatic|shades|triad|triad2|triad3|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast2|highContrast3|pentagram (or its label), steps?: 1..20 (4), variation?: \"tintsShades\"|\"warmCool\"|\"vividMuted\", amount?: 0..100 (50; how far the outermost steps go), limitTo?: swatch library id or name; or \"document\" (the document's swatches): every colour snaps to its nearest colour there (ΔE 2000)} the Color Guide for a base colour → {rule, colors: [\"#rrggbb\", the base first], grid: [per colour, 2·steps+1 variations from shades/cool/muted to tints/warm/vivid with the colour itself in the centre]}", + "{color (#rrggbbaa and #rgba are refused), rule: complementary|complementary2|splitComplementary|leftComplement|rightComplement|analogous|analogous2|monochromatic|shades|triad|triad2|triad3|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast2|highContrast3|pentagram (or its label), steps?: 1..20 (4), variation?: \"tintsShades\"|\"warmCool\"|\"vividMuted\", amount?: 0..100 (50; how far the outermost steps go), limitTo?: swatch library id or name; or \"document\" (the document's swatches): every colour snaps to its nearest colour there (ΔE 2000)} the Color Guide for a base colour → {rule, colors: [\"#rrggbb\", the base first], grid: [per colour, 2·steps+1 variations from shades/cool/muted to tints/warm/vivid with the colour itself in the centre]}", always, harmony ), diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 0cf1a0ec7e..9842cfbe96 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Convert Color", [], None, - "{color, to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}", + "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}", always, convert_color ), @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "Gamut Warning", [], None, - "{ids?|id?, colors?: [color]} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}", + "{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}", has_doc, gamut_check ), @@ -319,17 +319,138 @@ pub(crate) fn convert_mode(s: &mut Session, p: &Value) -> Result { changed = set_color_mode(d, mode, convert, intent, grays); Ok(()) })?; + if convert { + if s.in_interaction() && s.batch_stash.is_none() { + if let Some(it) = &mut s.doc_mut()?.interaction { + it.deferred_color_mode = Some(DeferredColorMode { mode, intent, grays }); + } + } else { + let before = new_art_colors_before(s)?; + convert_new_art_colors(s, mode, intent, grays)?; + record_new_art_colors(s, before)?; + } + } else if s.batch_stash.is_some() || s.doc()?.undo_group.is_some() { + let before = new_art_colors_before(s)?; + record_new_art_colors(s, before)?; + } Ok(json!({ "changed": changed })) } -/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks -/// included), symbols, graph designs, pattern tiles (the tile that pattern editing's Cancel puts -/// back included), graphic styles, brushes (their art and a Hue Shift key color) and swatches -/// through the color settings (`intent`, default: theirs) → how many colors of the art (opacity -/// masks included), symbols, graph designs and pattern tiles changed; the colors of graphic -/// styles and brushes convert without being counted. Gray colors stay -/// Gray (they print on the black plate in either mode); RGB grays are colors like any other and -/// separate through the CMYK profile, unless `grays` puts them on the black plate. Lab colors +/// The validated conversion choices of the current tentative color-mode preview. +#[derive(Clone, Copy, Debug)] +pub(crate) struct DeferredColorMode { + mode: ColorMode, + intent: Option, + grays: Grays, +} + +/// Complete the deferred new-art conversion before the interaction becomes an Undo step. +pub(crate) fn commit_new_art_colors(s: &mut Session) -> Result<()> { + let pending = + s.doc()?.interaction.as_ref().filter(|it| it.preview.is_some() && it.color_mode_paints.is_none()).and_then(|it| it.deferred_color_mode); + if let Some(DeferredColorMode { mode, intent, grays }) = pending { + let before = new_art_colors_before(s)?; + convert_new_art_colors(s, mode, intent, grays)?; + record_new_art_colors(s, before)?; + } + Ok(()) +} + +fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> { + let after = s.paint.clone(); + if before != after || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() { + let st = s.doc_mut()?; + let slot = if let Some(it) = &mut st.interaction { + Some(&mut it.color_mode_paints) + } else { + st.history.undo.last_mut().map(|e| &mut e.color_mode_paints) + }; + if let Some(slot) = slot { + match slot { + Some((_, end)) => *end = after, + slot => *slot = Some((before, after)), + } + } + if st.interaction.is_none() { + if let Some(e) = st.history.undo.last_mut() { + e.recost_paints(); + } + st.history.trim(); + } + } + Ok(()) +} + +fn new_art_colors_before(s: &Session) -> Result { + let st = s.doc()?; + Ok(st.undo_group.as_ref().map(|g| &g.paint).or_else(|| st.interaction.as_ref().map(|it| &it.paint)).cloned().unwrap_or_else(|| s.paint.clone())) +} + +/// Convert the fill and stroke that new art takes, and the colors of its template appearance +/// (paints and effect colors), as [`set_color_mode`] converted the active document's art. The +/// command records their original values for Undo. Previews defer this until acceptance; +/// a batch converts immediately and restores the values itself when it fails. +fn convert_new_art_colors(s: &mut Session, mode: ColorMode, intent: Option, grays: Grays) -> Result<()> { + let d = &s.doc()?.doc; + let bases = global_bases(d); + let conv = mode_converter(mode, intent, grays); + let mut f = |col: &Color, link: proof::Link| mode_color(col, link, &bases, &conv); + map_paint_colors(&mut s.paint.fill, &mut f); + map_paint_colors(&mut s.paint.stroke, &mut f); + if let Some(a) = s.paint.appearance.as_mut() { + for it in &mut a.items { + let paint = match it { + vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint, + vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint, + }; + map_paint_colors(paint, &mut f); + } + map_effect_colors(a, &mut f); + } + Ok(()) +} + +/// How Document Color Mode converts a color to `mode` through the color settings (`intent`, +/// default: theirs): Gray and Lab colors stay as they are; with `grays` on the black plate, an RGB +/// gray becomes K only in CMYK. +fn mode_converter(mode: ColorMode, intent: Option, grays: Grays) -> impl Fn(&Color) -> Color { + let c = cms::active(); + let intent = intent.unwrap_or(c.settings().intent); + let model = if mode == ColorMode::Cmyk { Model::Cmyk } else { Model::Rgb }; + let k_only = model == Model::Cmyk && grays == Grays::Black; + move |col: &Color| match col { + Color::Gray { .. } | Color::Lab { .. } => *col, + // Grey ink percentage, then K only (a Gray colour's CMYK). + Color::Rgb { .. } if k_only && Neutral::of(col).is_some() => c.convert(&c.convert(col, Model::Gray, intent), Model::Cmyk, intent), + _ => c.convert(col, model, intent), + } +} + +/// The name and color of each global swatch of `d`, for [`mode_color`]. +fn global_bases(d: &vectorcraft_doc::Document) -> Vec<(String, Color)> { + d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect() +} + +/// The color Document Color Mode gives `col` (swatch link `link`): a tint of a global swatch in +/// `bases` (already converted) is that swatch's color at its tint; any other color goes through +/// `conv` ([`mode_converter`]). +fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &dyn Fn(&Color) -> Color) -> Color { + match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) { + Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint), + _ => conv(col), + } +} + +/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks, +/// effect colors and the series paints and label styles that graphs keep included), symbols, +/// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included), +/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and +/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art +/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern +/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray +/// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any +/// other and separate through the CMYK profile, unless `grays` puts them on the black plate +/// ([`mode_converter`]). Lab colors /// (spot color definitions) are device independent and fit either mode. A tint of a global /// swatch becomes the converted swatch's color at its tint. Document Color Mode and /// `document.open {colorMode}` both convert this way. @@ -338,16 +459,7 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, if !convert { return 0; } - let c = cms::active(); - let intent = intent.unwrap_or(c.settings().intent); - let model = if mode == ColorMode::Cmyk { Model::Cmyk } else { Model::Rgb }; - let k_only = model == Model::Cmyk && grays == Grays::Black; - let conv = |col: &Color| match col { - Color::Gray { .. } | Color::Lab { .. } => *col, - // Grey ink percentage, then K only (a Gray colour's CMYK). - Color::Rgb { .. } if k_only && Neutral::of(col).is_some() => c.convert(&c.convert(col, Model::Gray, intent), Model::Cmyk, intent), - _ => c.convert(col, model, intent), - }; + let conv = mode_converter(mode, intent, grays); for sw in d.swatches_iter_mut() { match &mut sw.paint { Paint::Solid { color, .. } => *color = conv(color), @@ -360,13 +472,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, } } // Tints are their converted swatch's colour at their tint (exact ink percentages). - let bases: Vec<(String, Color)> = d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect(); + let bases = global_bases(d); let changed = std::cell::Cell::new(0usize); let mut count = |col: &Color, link: proof::Link| { - let n = match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) { - Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint), - _ => conv(col), - }; + let n = mode_color(col, link, &bases, &conv); if n != *col { changed.set(changed.get() + 1); } @@ -384,12 +493,15 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, } // The reply counts the colors of the document's art only, not those of the graphic styles and brushes. let in_art = changed.get(); - for it in d.graphic_styles.iter_mut().flat_map(|g| &mut g.appearance.items) { - let paint = match it { - vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint, - vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint, - }; - map_paint_colors(paint, &mut count); + for g in &mut d.graphic_styles { + for it in &mut g.appearance.items { + let paint = match it { + vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint, + vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint, + }; + map_paint_colors(paint, &mut count); + } + map_effect_colors(&mut g.appearance, &mut count); } // Convert each brush's art. A Hue Shift key color takes the converted color of the art color // it matches (a tint of a global swatch included), so the key still matches the converted art; @@ -438,19 +550,28 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, in_art } -/// [`proof::map_node_colors`] over `n`'s subtree and the art of every opacity mask in it. +/// [`proof::map_node_colors`] over `n`'s subtree, then [`map_more_colors`]. fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { proof::map_node_colors(n, f); - map_mask_colors(n, f); + map_more_colors(n, f); } -fn map_mask_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { - if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) { - map_art_colors(Arc::make_mut(&mut mask.art), f); +/// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the +/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps +/// ([`map_graph_colors`]) and the art of every opacity mask. +fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + map_effect_colors(&mut n.appearance, f); + if let Some(e) = n.extras_if_any() { + if let Some(g) = e.graph.as_deref_mut() { + map_graph_colors(g, f); + } + if let Some(mask) = e.mask.as_deref_mut() { + map_art_colors(Arc::make_mut(&mut mask.art), f); + } } if let Some(ch) = n.children_mut() { for c in ch.iter_mut() { - map_mask_colors(Arc::make_mut(c), f); + map_more_colors(Arc::make_mut(c), f); } } } @@ -461,7 +582,46 @@ fn matches_key(c: &Color, key: &Color) -> bool { c.to_rgb().iter().zip(key.to_rgb()).map(|(a, b)| (a - b).abs()).sum::() < 0.02 } -/// `f` applied to a solid paint's color or a gradient's stop colors, given their swatch link. +/// `f` applied to the `color` of each effect in appearance `a` (the object's effects and those of +/// each fill and stroke) that has one ([`super::params::effect_color`]). An effect that draws its +/// default color stores the new color as its own. The light colors of the 3D effects stay as they +/// are. +fn map_effect_colors(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut()); + for e in a.effects.iter_mut().chain(items) { + if !(e.params.is_object() || e.params.is_null()) { + continue; + } + let Some(color) = super::params::effect_color(&e.id, &e.params) else { continue }; + let n = f(&color, None); + if n == color { + continue; + } + match &mut e.params { + Value::Object(m) => { + m.insert("color".into(), json!(n)); + } + p => *p = json!({ "color": n }), + } + } +} + +/// `f` applied to the series paints and the label styles that graph `g` keeps, which its marks and +/// labels take each time it is drawn again. +fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + for p in g.series_paints.iter_mut() { + for paint in [&mut p.fill, &mut p.stroke].into_iter().flatten() { + map_paint_colors(paint, f); + } + } + let styles = &mut g.label_styles; + for st in [&mut styles.values, &mut styles.categories, &mut styles.legend].into_iter().flatten() { + map_paint_colors(&mut st.fill, f); + map_paint_colors(&mut st.stroke, f); + } +} + +/// `f` applied to solid, gradient-stop and freeform-control colors, with any swatch link. fn map_paint_colors(p: &mut Paint, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { match p { Paint::Solid { color, swatch, tint } => *color = f(color, swatch.as_deref().map(|s| (s, *tint))), @@ -469,6 +629,11 @@ fn map_paint_colors(p: &mut Paint, f: &mut dyn FnMut(&Color, proof::Link) -> Col for st in &mut g.gradient.stops { st.color = f(&st.color, st.swatch.as_deref().map(|s| (s, st.tint))); } + if let Some(freeform) = &mut g.freeform { + for point in &mut freeform.points { + point.color = f(&point.color, None); + } + } } _ => {} } @@ -510,7 +675,9 @@ fn convert_color(_: &mut Session, p: &Value) -> Result { fn gamut_check(s: &mut Session, p: &Value) -> Result { let mut cols: Vec = vec![]; if let Some(a) = p.get("colors").and_then(Value::as_array) { - cols.extend(a.iter().filter_map(color_value)); + for v in a { + cols.push(color_value(v).ok_or_else(|| bad("color.gamutCheck", format!("bad color {v}")))?); + } } else { let st = s.doc()?; let ids = targets(s, p)?; diff --git a/crates/engine/src/cmd/colortheme.rs b/crates/engine/src/cmd/colortheme.rs index 9321fc12bc..b61432aea1 100644 --- a/crates/engine/src/cmd/colortheme.rs +++ b/crates/engine/src/cmd/colortheme.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Save Theme", ["Window", "Color Themes"], None, - "{colors: [1–5 colours] | color + rule (a harmony rule id or label, see color.harmony: its 5-colour theme from that base colour, base first), rule?: the rule it was made with, name?: (default \"Theme N\"), replace?: a saved theme's name (overwrite that theme in place, e.g. after editing it; it may be renamed), color?: one colour (as colors: [colour])} save a colour theme to the local theme library (the preferences) → {name, count: themes saved}", + "{colors: [1–5 colours] (#rrggbbaa and #rgba are refused) | color + rule (a harmony rule id or label, see color.harmony: its 5-colour theme from that base colour, base first), rule?: the rule it was made with, name?: (default \"Theme N\"), replace?: a saved theme's name (overwrite that theme in place, e.g. after editing it; it may be renamed), color?: one colour (as colors: [colour])} save a colour theme to the local theme library (the preferences) → {name, count: themes saved}", always, save ), diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 65a6ee0c37..00ea88ea64 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -706,6 +706,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result { super::paint::check_keep_model(p, "text.create")?; check_numbers(p, &["size"], "text.create")?; check_switches(p, &["vertical", "placeholder"], "text.create")?; + super::color_param(p, "color", "text.create")?; if let Some(a) = p.get("area") { check_numbers(a, &["width", "height"], "text.create")?; } diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index f566f1635e..fc146fdec8 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Symbol Instance", ["Select", "Same"], None, - "{} select the instances of the symbol of the first selected object that can be selected; objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group or layer are passed over → {count}", + "{} select the instances of the symbol of the first selected object that can be selected, including a group member selected on its own; when that object is not a symbol instance, such as a group, nothing is selected; objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated (new art while it stays selected excepted), or outside the isolated group or layer are passed over → {count}", has_selection, |s, _| same(s, "select.same.symbolInstance", |a, b| match (&a.kind, &b.kind) { (NodeKind::SymbolInstance { symbol: x, .. }, NodeKind::SymbolInstance { symbol: y, .. }) => x == y, @@ -256,7 +256,7 @@ pub fn specs() -> Vec { "Document Color Mode", ["File", "Document Color Mode"], None, - "{mode: \"cmyk\"|\"rgb\", convert?: true (convert every color of the art (opacity masks included), symbols, graph designs, pattern tiles, graphic styles, brushes and swatches through the color settings; swatch links kept; Gray colors stay Gray, on the black plate), intent?, grays?: \"profile\" (default: RGB grays separate through the CMYK profile like any color, into four-color grays and a rich black) | \"black\" (to CMYK, RGB grays with R = G = B go on the black plate only, K = their gray value)} → {changed: how many colors of the art, symbols, graph designs and pattern tiles changed; the colors of graphic styles and brushes are not counted}", + "{mode: \"cmyk\"|\"rgb\", convert?: true (convert every color of the art (opacity masks, effect colors and graphs' series and label paints included), symbols, graph designs, pattern tiles, graphic styles (their effect colors included), brushes, swatches and the paints new art takes through the color settings, together in one undo step (Undo restores their original values; Redo reapplies the conversion); swatch links kept; Gray colors stay Gray, on the black plate), intent?, grays?: \"profile\" (default: RGB grays separate through the CMYK profile like any color, into four-color grays and a rich black) | \"black\" (to CMYK, RGB grays with R = G = B go on the black plate only, K = their gray value)} → {changed: how many colors of the art, symbols, graph designs and pattern tiles changed; the colors of graphic styles and brushes are not counted}", has_doc, super::colormgmt::convert_mode ), @@ -337,7 +337,7 @@ fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool) /// object inside two selected objects is given twice. The walk stops when `f` returns false. fn each_selected_text(s: &Session, mut f: impl FnMut(NodeId) -> bool) { fn inside(n: &Node, f: &mut impl FnMut(NodeId) -> bool) -> bool { - if !n.visible || n.locked { + if !n.visible || n.locked || n.is_template() { return true; } if matches!(n.kind, NodeKind::Text(_)) && !f(n.id) { diff --git a/crates/engine/src/cmd/docsetup.rs b/crates/engine/src/cmd/docsetup.rs index f5cb1d6b72..894d9b90ae 100644 --- a/crates/engine/src/cmd/docsetup.rs +++ b/crates/engine/src/cmd/docsetup.rs @@ -17,7 +17,7 @@ pub fn specs() -> Vec { "Document Setup", [], None, - "{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup", + "{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup", has_doc, setup )] diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f252d09ff9..41276c2326 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -10,8 +10,8 @@ use vectorcraft_geom::{Affine, Point, Vec2}; use super::clipboard::SwatchChoices; use super::{ CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, cmd, f64_or, f64_req, - finite_numbers, has_clipboard, has_doc, has_selection, has_selection_or_artboard_tool, has_selection_or_guides, id_param, index, ok, point_param, - str_param, + finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index, ok, + point_param, str_param, }; use crate::{Clipboard, EngineError, inspect}; @@ -125,8 +125,24 @@ pub fn specs() -> Vec { always, undo_group_end ), - cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{} (the Artboard tool chosen: artboard.cut)", has_selection_or_artboard_tool, cut), - cmd!("edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{} (the Artboard tool chosen: artboard.copy)", has_selection_or_artboard_tool, copy), + cmd!( + "edit.cut", + "Cut", + ["Edit"], + Some("Cmd+X"), + "{} (selected ruler guides go too; the Artboard tool chosen: artboard.cut)", + has_selection_guides_or_artboard_tool, + cut + ), + cmd!( + "edit.copy", + "Copy", + ["Edit"], + Some("Cmd+C"), + "{} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy → {copied, guides}", + has_selection_guides_or_artboard_tool, + copy + ), cmd!( "edit.paste", "Paste", @@ -177,7 +193,7 @@ pub fn specs() -> Vec { "Clear", ["Edit"], Some("Delete"), - "{ids?} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides)", + "{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides)", has_selection_or_guides, clear ), @@ -487,6 +503,9 @@ fn undo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + let paints = e.color_mode_paints.clone(); + turned.color_mode_paints = e.color_mode_paints; + turned.recost_paints(); st.history.redo.push(turned); st.history.trim(); st.revision += 1; @@ -499,6 +518,9 @@ fn undo(s: &mut Session, _: &Value) -> Result { leave_isolation_if_gone(st); super::globaledit::follow_history(st); st.drop_stale_variables_highlight(); + if let Some((before, _)) = paints { + s.paint = before; + } Ok(json!({ "undone": label })) } @@ -516,6 +538,9 @@ fn redo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + let paints = e.color_mode_paints.clone(); + turned.color_mode_paints = e.color_mode_paints; + turned.recost_paints(); st.history.undo.push(turned); st.history.trim(); st.revision += 1; @@ -527,6 +552,9 @@ fn redo(s: &mut Session, _: &Value) -> Result { leave_isolation_if_gone(st); super::globaledit::follow_history(st); st.drop_stale_variables_highlight(); + if let Some((_, after)) = paints { + s.paint = after; + } Ok(json!({ "redone": label })) } @@ -640,9 +668,35 @@ fn copy(s: &mut Session, _: &Value) -> Result { if s.tool_id() == "artboard" { return super::panelcmds::artboard_copy(s, &json!({}), false); } - let roots = selected_roots(s)?; - s.clipboard = Clipboard::copy(s.doc()?, &roots); - Ok(json!({ "copied": s.clipboard.nodes.len() })) + let st = s.doc()?; + // Selected ruler guides come along (#3226), as canvas guides: their layer and artboard stay + // behind. + let guides: Vec = st + .selection + .guides + .iter() + .filter_map(|i| st.doc.guides.get(*i)) + .map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, ..g.clone() }) + .collect(); + let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { selected_roots(s)? }; + let st = s.doc()?; + let mut clip = Clipboard::copy(st, &roots); + // Guides alone: the artboard the first one belongs to, or crosses, is where in-place pastes + // measure from, as the objects' artboard is. + if clip.nodes.is_empty() + && let Some(g) = st.selection.guides.first().and_then(|i| st.doc.guides.get(*i)) + { + let board = g.artboard.and_then(|id| st.doc.artboards.iter().find(|a| a.id == id)).or_else(|| { + st.doc + .artboards + .iter() + .find(|a| if g.vertical { (a.rect.x0..=a.rect.x1).contains(&g.pos) } else { (a.rect.y0..=a.rect.y1).contains(&g.pos) }) + }); + clip.source_artboard = board.map(|a| a.rect); + } + clip.guides = guides; + s.clipboard = clip; + Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() })) } fn cut(s: &mut Session, p: &Value) -> Result { @@ -651,9 +705,15 @@ fn cut(s: &mut Session, p: &Value) -> Result { } // Copy promotes a compound member to its compound. Cut must remove the same objects it // copied, while Clear on its own deletes exactly the selected members. + // Ruler guides selected on their own: Copy takes them, Clear removes them. + if s.doc()?.selection.is_empty() { + copy(s, p)?; + return clear(s, &json!({})); + } let ids = selected_roots(s)?; copy(s, p)?; - if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids })) } else { clear(s, &json!({})) } + // The selected ruler guides it copied go with the objects, in the same undo step (#3226). + if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids, "guides": true })) } else { clear(s, &json!({ "guides": true })) } } fn clear(s: &mut Session, p: &Value) -> Result { @@ -667,8 +727,9 @@ fn clear(s: &mut Session, p: &Value) -> Result { return super::docmenu::guide_remove(s, &json!({})); } let st = s.doc()?; - // Guides selected with the art go with it (not when ids are given). - let with_guides = explicit.is_none(); + // Guides selected with the art go with it (not when ids are given, unless `guides` says so: + // Cut, which names the objects it copied). + let with_guides = explicit.is_none() || bool_or(p, "guides", false); let targets = explicit.unwrap_or_else(|| st.selection.in_paint_order(&st.doc)); // Keep the selected ids themselves, without promoting compound members. Delete a selected // ancestor just once; its selected descendants leave with it. Layers themselves are kept. @@ -838,6 +899,13 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho // In place, in front, in back: onto the active artboard when the UI names it. _ => vec![onto_artboard(&st.doc, p, clip)], }; + // Guides alone don't follow a plain paste's offset or the view centre: they stay where they + // were. With objects they move as the objects do. + let guide_placements: Vec = if !clip.nodes.is_empty() || !matches!(mode, PasteMode::Offset | PasteMode::Library | PasteMode::Drag) { + placements.clone() + } else { + vec![Affine::IDENTITY] + }; let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| { let imported = clip.import_into(d, choices, same_doc); // Draw Inside: the clip group of the object drawn into, made on the first paste. @@ -885,6 +953,20 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho } } sel.set(new_ids.iter().copied()); + // Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a + // paste of guides alone keeps them where they were, but onto another artboard or every + // artboard as the in-place pastes put art); they are selected with the objects. + let guide_layer = parent.and_then(|p| if d.node(p).is_some_and(Node::is_layer) { Some(p) } else { d.layer_containing(p) }); + for xf in &guide_placements { + let dv = xf.translation(); + for g in &clip.guides { + let pos = g.pos + if g.vertical { dv.x } else { dv.y }; + if pos.is_finite() { + sel.guides.push(d.guides.len()); + d.guides.push(vectorcraft_doc::Guide { pos, layer: guide_layer, ..g.clone() }); + } + } + } // Pasted type arrives without the layout bounds cache: fill it so boxes and alignment are // right away (opening the file later would, but paste must not depend on a reopen). super::typecmd::refresh_bounds_of(d, &new_ids); @@ -899,6 +981,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho } Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), + "guides": clip.guides.len() * guide_placements.len(), "artboard": artboards.first(), "artboards": artboards, "added": imported.added, diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 76f408d221..7c828221b1 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -108,7 +108,7 @@ mod export_names; mod formats; #[cfg(not(target_arch = "wasm32"))] -use access::list_dir; +pub(crate) use access::list_dir; pub use access::write_file_with; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::{Placed, copy_new, file_metadata}; @@ -120,7 +120,7 @@ pub(crate) use access::{drive_share_of, share_of}; #[cfg(test)] pub(crate) use access::{drive_share_path, share_path, touched}; #[cfg(not(target_arch = "wasm32"))] -use access::{may_read, may_write}; +pub(crate) use access::{may_read, may_write}; pub use commands::specs; pub use export_names::artboard_file_names; pub(crate) use export_names::{default_name, merge, unique_file_names, with_black_output, write_or_return}; diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index ffe34acfd0..4dce2023bb 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -10,7 +10,7 @@ use super::{EngineError, Result, Session, Value, bad, json}; /// `path` checked for reading against the automation roots in force. #[cfg(not(target_arch = "wasm32"))] -pub(super) fn may_read(path: &str) -> Result<()> { +pub(crate) fn may_read(path: &str) -> Result<()> { #[cfg(test)] touch(path); crate::file_access::check_read(path).map_err(EngineError::Other) @@ -44,7 +44,7 @@ pub(crate) fn touched(f: impl FnOnce() -> T) -> (T, Vec) { /// `path` checked for writing against the automation roots in force. #[cfg(not(target_arch = "wasm32"))] -pub(super) fn may_write(path: &str) -> Result<()> { +pub(crate) fn may_write(path: &str) -> Result<()> { crate::file_access::check_write(path).map_err(EngineError::Other) } @@ -169,7 +169,7 @@ pub(super) fn file_list(_: &mut Session, p: &Value) -> Result { /// The entries of folder `path`, sorted by name: at most `max`, and whether there were more. A /// link isn't followed: its target may lie outside the automation roots. #[cfg(not(target_arch = "wasm32"))] -pub(super) fn list_dir(path: &str, max: usize) -> Result<(Vec, bool)> { +pub(crate) fn list_dir(path: &str, max: usize) -> Result<(Vec, bool)> { may_read(path)?; let dir = std::fs::read_dir(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; let mut entries: Vec<(String, Value)> = vec![]; @@ -195,7 +195,7 @@ pub(super) fn list_dir(path: &str, max: usize) -> Result<(Vec, bool)> { } #[cfg(target_arch = "wasm32")] -pub(super) fn list_dir(_: &str, _: usize) -> Result<(Vec, bool)> { +pub(crate) fn list_dir(_: &str, _: usize) -> Result<(Vec, bool)> { Err(EngineError::Other("no file system here".into())) } diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 3dc3a51d9c..60f8be3297 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -15,12 +15,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let artboard = p.get("artboard").and_then(Value::as_u64); // What an error rolls back besides the documents: session-level state a step may change // (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group). - let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone()); // A drag or typing still in progress is a step of its own, as before Undo: the batch's steps // would otherwise run inside it and take its baseline as theirs (#1697). - if s.active().is_some() { + if s.active().is_some() && !s.previewing { super::super::edit::settle_interaction(s)?; } + let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone()); // The documents as they are now, whole: what a failed step brings back. Their art, history, // file, format and saved state share their data with the open ones until a step changes them. let start = s.docs.clone(); @@ -47,10 +47,18 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { } }; // Each document the steps edited keeps them as one undo step. - s.remember_pending_paint(); - for st in &mut s.docs { - if let Some(it) = st.interaction.take() { - st.keep_interaction(it); + if !s.previewing { + s.remember_pending_paint(); + for st in &mut s.docs { + if let Some(mut it) = st.interaction.take() { + // Redo restores the new-art colors the whole batch left, not the ones right after a + // color-mode step. + if let Some((_, after)) = &mut it.color_mode_paints { + after.clone_from(&s.paint); + s.batch_paint_docs.push(st.uid); + } + st.keep_interaction(it); + } } } // The batch journals itself, whichever document it ends in. @@ -58,7 +66,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { if let Some(o) = entry.as_object_mut() { o.insert("commands".into(), Value::Array(cmds)); } - s.journal.push(("command.batch".into(), entry)); + if !s.previewing { + s.journal.push(("command.batch".into(), entry)); + } Ok(json!({ "results": results })) } @@ -104,6 +114,9 @@ fn run_steps( let held: Vec<(u64, Arc)> = s.docs.iter().filter(|st| st.undo_group.is_some()).map(|st| (st.uid, st.doc.clone())).collect(); let (v, noted) = s.execute_step(&id, ¶ms).map_err(|e| EngineError::Other(format!("batch step {} (`{id}`) failed: {e}", results.len())))?; + if s.previewing && s.active().map(|d| d.uid) != start { + return Err(bad("command.batch", "a batch preview cannot switch documents")); + } grouped.push(step_groups(s, start, &held)); // The step's journal entry records what it took from the preferences or the clock (a // save's date, a new document's), as a command of its own would. diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index f269f0fc0f..5b734c5a26 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", has_doc, export::export ), diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index eca365ca16..2b1de2eda4 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -165,18 +165,18 @@ pub fn load(name: &str, bytes: &[u8]) -> Result { /// of its art, which it carries: its layers and hidden objects as they were, and the art outside /// its artboard (its PDF part has only what is on the artboards), as an EPS of the editor is read. /// Anything else as it was. `unit`: the size in points of a unit of the PDF part's user space (its -/// first page's `UserUnit`) → (document, warnings, whether its layers were read). `private`: the -/// editor's copy ([`editing_copy`]). +/// first page's `UserUnit`) → (document, warnings, whether its layers were read). `layers`: the +/// editor's copy ([`editing_copy`]), as far as it was decoded and read. fn through_editing_data( - private: Option<&[u8]>, + layers: Option, opts: &LoadOptions, doc: Document, warnings: Vec, unit: f64, ) -> (Document, Vec, bool) { - let Some(private) = private else { return (doc, warnings, false) }; + let Some(layers) = layers else { return (doc, warnings, false) }; let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines; - let (doc, mut warnings, read) = vectorcraft_eps::layered_ai(private, doc, warnings, outlined, opts.trust_editing_data, unit); + let (doc, mut warnings, read) = vectorcraft_eps::layered_ai_from(layers, doc, warnings, outlined, opts.trust_editing_data, unit); // The layers weren't read (or couldn't be): the notes of reading the PDF part still hold. if !read { return (doc, warnings, false); @@ -216,6 +216,14 @@ fn reads_editing_copy(opts: &LoadOptions) -> bool { opts.pages.is_none() && opts.layers && opts.editing_data } +/// May a file opened with `opts` open from the editor's own copy of its art without its PDF part +/// being imported ([`vectorcraft_eps::ai_layers_alone`]): it reads the editor's copy, on the pages' +/// trim boxes (the crop box asked for, as a file with the editor's copy opens on them), with its +/// type as text? +fn reads_layers_alone(opts: &LoadOptions) -> bool { + reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines +} + /// The editor's own copy of its art that `opened` carries (as [`vectorcraft_pdf::illustrator_data`] /// reads it), when `opts` read it ([`reads_editing_copy`]). fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option> { @@ -365,41 +373,68 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result Ok(o) => super::pdfimport::import(bytes, o, opts, format.id != "pdf"), Err(e) => Err(err(e)), }; - let read = restore_or_import(editing, || match imported() { - Ok(r) => { - // The editor's copy, read once the import is done with the pages. - let private = opened.as_ref().ok().and_then(|o| editing_copy(o, opts)); - // Pages of text alone: the editing copy alone where it reads, as for a file - // saved without its PDF part (#1387: else the page, which is the art). So too - // pages that draw nothing at all: there is no page art to check the layers - // against, and the empty page would lose all of it. - // A page is empty only when nothing on it was skipped (an image that can't be - // decoded draws nothing either): its notes are at most the page's own. - let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w)); - let alone = (r.only_text || empty) - .then(|| private.as_deref().map(editing_copy_alone)) - .flatten() - .and_then(|read| read.ok()) - .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)); - let (doc, warnings, read) = match alone { - Some((doc, warnings)) => (doc, warnings, true), - None => through_editing_data(private.as_deref(), opts, r.document, r.warnings, r.user_unit), - }; - editing_data = read; - Ok((doc, warnings)) + let read = restore_or_import(editing, || { + // Type all from the text document and nothing that needs the PDF part: the layers + // alone, the PDF part not imported. Else what was read of the layers is kept for + // reading them with the PDF part. + let mut layers = None; + if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?))) + { + let pages = o.trim_pages(); + match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit) { + Ok((mut doc, warnings)) => { + doc.setup.bleed = pages.bleed; + editing_data = true; + return Ok((doc, warnings)); + } + Err(read) => layers = Some(read), + } + } + match imported() { + Ok(r) => { + // The editor's copy, read once the import is done with the pages, unless + // its layers were read before it. + let private = layers.is_none().then(|| opened.as_ref().ok().and_then(|o| editing_copy(o, opts))).flatten(); + // Pages of text alone: the editing copy alone where it reads, as for a file + // saved without its PDF part (#1387: else the page, which is the art). So too + // pages that draw nothing at all: there is no page art to check the layers + // against, and the empty page would lose all of it. + // A page is empty only when nothing on it was skipped (an image that can't be + // decoded draws nothing either): its notes are at most the page's own. + let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w)); + let copy_alone = || match &private { + Some(private) => Some(editing_copy_alone(private)), + None if layers.is_some() => opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p)), + None => None, + }; + let alone = (r.only_text || empty) + .then(copy_alone) + .flatten() + .and_then(|read| read.ok()) + .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)); + let (doc, warnings, read) = match alone { + Some((doc, warnings)) => (doc, warnings, true), + None => { + let layers = layers.or_else(|| private.as_deref().map(vectorcraft_eps::AiLayers::decode)); + through_editing_data(layers, opts, r.document, r.warnings, r.user_unit) + } + }; + editing_data = read; + Ok((doc, warnings)) + } + // Saved without its PDF part: the editing copy is all the file has (`pages` that + // name every page read it as the whole file). + Err(e) if is_placeholder(&e) => opened + .as_ref() + .ok() + .and_then(|o| from_editing_data_alone(o, opts)) + .unwrap_or(Err(e)) + .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)) + .inspect(|_| editing_data = true), + // A PDF part that can't be read (a stream the import refuses): the editing copy + // alone where it reads, else the error. + Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e), } - // Saved without its PDF part: the editing copy is all the file has (`pages` that - // name every page read it as the whole file). - Err(e) if is_placeholder(&e) => opened - .as_ref() - .ok() - .and_then(|o| from_editing_data_alone(o, opts)) - .unwrap_or(Err(e)) - .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)) - .inspect(|_| editing_data = true), - // A PDF part that can't be read (a stream the import refuses): the editing copy - // alone where it reads, else the error. - Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e), })?; // The File Info of a file read from its pages or its editing copy. if !read.2 { diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index 1331d6f894..2f9312259c 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -109,7 +109,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[ name: "editingData", ty: "boolean", default: "true", - description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, paths, fills and strokes, colors, swatches and artboards, with type, gradients, patterns, images, symbols, clipping and live objects as plain filled and stroked paths, without transparency (written only with every artboard, as Preserve Editing is)", + description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, swatches, artboards, the transparency of objects and layers, objects' opacity masks, and clipping groups and layers clipped by a path, with type, gradients, patterns, images, symbols, other clipping objects and live objects as plain filled and stroked paths (written only with every artboard, as Preserve Editing is)", }, FormatOption { name: "aiVersion", diff --git a/crates/engine/src/cmd/fileio/pxrread.rs b/crates/engine/src/cmd/fileio/pxrread.rs index eb7957ad92..fc3a32f155 100644 --- a/crates/engine/src/cmd/fileio/pxrread.rs +++ b/crates/engine/src/cmd/fileio/pxrread.rs @@ -24,8 +24,8 @@ const TRUNCATED: &str = "the Pixar file is cut short"; /// define. const DAMAGED: &str = "the Pixar file's header is damaged"; -/// The message for encoded tile data with a packet the format doesn't define, or one that runs -/// past the end of its scan line. +/// The message for a tile pointer into the header or the tile pointer table, and for encoded tile +/// data with a packet the format doesn't define, or one that runs past the end of its scan line. const BAD_DATA: &str = "the Pixar file's image data is damaged"; /// The channel bits of the picture format field (header byte 424): R, G, B and A, stored in this @@ -115,7 +115,9 @@ pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result Result= bytes.len() { return Err(TRUNCATED.into()); } + // Tile data follows the tile pointer table; a pointer into the header or the table would + // read them as pixels. + if pointer < table_end { + return Err(BAD_DATA.into()); + } let (x0, y0) = (n % across * tile_w, n / across * tile_h); // The part of the tile inside the picture; the pixels of border tiles past its edges are // stored and skipped. diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 16049850c0..0f97a58627 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -1221,10 +1221,16 @@ fn half_outlined_line(y: f64, rest: &str, mode: u8) -> String { /// text document (a line starting at (14, 65)), then `more` of a story the text document doesn't /// have. Without `story` the file has no text document. fn half_outlined_ai(story: Option<&str>, more: usize, type_content: &str) -> Vec { + half_outlined_ai_on(story, more, type_content, "", |page| page) +} + +/// [`half_outlined_ai`] with the editing data's comments `head` before its art, whose page is +/// `page_of` the 200 × 100 pt page it draws on (other boxes, more entries). +fn half_outlined_ai_on(story: Option<&str>, more: usize, type_content: &str, head: &str, page_of: impl FnOnce(PdfPage) -> PdfPage) -> Vec { let text = |story: u32| format!("/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n{story} /StoryIndex ,\n;\n"); let texts: String = std::iter::once(text(0)).chain((0..more).map(|_| text(99))).collect(); let mut body = - format!("%AI3_TemplateBox: 100 50 100 50\n{}", ai::layer("Art", &format!("0.5 g\n{}f\n{texts}", ai::rect(120.0, 20.0, 160.0, 60.0)))); + format!("{head}%AI3_TemplateBox: 100 50 100 50\n{}", ai::layer("Art", &format!("0.5 g\n{}f\n{texts}", ai::rect(120.0, 20.0, 160.0, 60.0)))); if let Some(story) = story { // The story's one line starts at the canvas center (8191.5, the template box's center) moved // to (14, 65): its y runs down the page. @@ -1255,7 +1261,7 @@ fn half_outlined_ai(story: Option<&str>, more: usize, type_content: &str) -> Vec }; let cmap = "begincmap\n1 begincodespacerange\n<00> \nendcodespacerange\n1 beginbfchar\n<41> \nendbfchar\nendcmap\n"; pdf_with( - &[page], + &[page_of(page)], &[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len()), &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None, ) @@ -1287,6 +1293,12 @@ fn texts(s: &Session) -> Vec { /// (art x 10 to 90 and 110 to 190, y 10 to 90), then a band across the first frame (y 30 to 70), /// made a wrap object with no offset when `wrap` is set. fn wrapped_thread_ai(wrap: bool) -> Vec { + ai::ai(&wrapped_thread_data(wrap.then_some(0.0)), PLACEHOLDER) +} + +/// The editing data of [`wrapped_thread_ai`], compressed, with the band a wrap object of `offset` +/// when one is given. +fn wrapped_thread_data(offset: Option) -> Vec { // The template box is centred at (100, 50), the canvas centre 8191.5: y runs down the canvas. let canvas = |x: f64, y: f64| (x + 8091.5, 8241.5 - y); let rect = |x0: f64, y0: f64, x1: f64, y1: f64| { @@ -1306,14 +1318,47 @@ fn wrapped_thread_ai(wrap: bool) -> Vec { ); let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); let frame = |f: u32| format!("/AI11Text :\n0 /FreeUndo ,\n{f} /FrameIndex ,\n0 /StoryIndex ,\n;\n"); - let dict = if wrap { "%_/ArtDictionary :\n%_0 /Real (AI11TextWrapOffset) ,\n%_0 /Bool (AI11TextWrapInvert) ,\n%_;\n%_\n" } else { "" }; + let dict = offset + .map(|o| format!("%_/ArtDictionary :\n%_{o} /Real (AI11TextWrapOffset) ,\n%_0 /Bool (AI11TextWrapInvert) ,\n%_;\n%_\n")) + .unwrap_or_default(); let art = format!("{}{}0.5 g\n{}f\n{dict}", frame(0), frame(1), ai::rect(10.0, 30.0, 90.0, 70.0)); let body = format!( "%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", ai::layer("Art", &art), lines.join("\n") ); - ai::ai(&compressed(ai::editing_data(200.0, 100.0, &body).as_bytes()), PLACEHOLDER) + compressed(ai::editing_data(200.0, 100.0, &body).as_bytes()) +} + +/// The wrap offset of the first frame of `doc`'s threaded type, as its text resolves it. +fn first_frame_wrap_offset(doc: &vectorcraft_doc::Document) -> f64 { + match &doc.node(doc.text_threads[0][0]).unwrap().kind { + NodeKind::Text(t) => t.wrap[0].wrap.offset, + _ => panic!("area type"), + } +} + +/// A `.ai` in units of 10 points whose threaded area type flows around a wrap object of a 2 unit +/// offset opens with the type flowing round it 20 pt off, its PDF part read or not, and when its +/// PDF part can't be read. The default graphic styles of a file without its own aren't scaled. +#[test] +fn wrapped_type_in_units_of_ten_points_flows_round_the_wrap_at_its_size_in_points() { + let private = wrapped_thread_data(Some(2.0)); + let page = "0.5 g 10 30 80 40 re f"; + let refused = ai::ai_with_entries_and_content(&private, page, "/UserUnit 10", REFUSED_CONTENT); + // On the trim boxes the PDF part is imported, and the refused stream stops it. + let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }; + let files = [(ai::ai_with(&private, page, "/UserUnit 10"), LoadOptions::default()), (refused, trim)]; + for (file, opts) in &files { + let loaded = load_with("thread.ai", file, opts).unwrap(); + assert!(loaded.editing_data, "{:?}", loaded.warnings); + assert!((first_frame_wrap_offset(&loaded.doc) - 20.0).abs() < 0.01, "{:?}", loaded.warnings); + } + let loaded = load_with("thread.ai", &files[1].0, &files[1].1).unwrap(); + assert!(loaded.warnings.iter().any(|w| w.starts_with("the PDF part couldn't be read")), "{:?}", loaded.warnings); + // The file has no graphic styles of its own: the default ones aren't scaled either way. + let read = load_with("thread.ai", &files[0].0, &files[0].1).unwrap(); + assert_eq!(loaded.doc.graphic_styles, read.doc.graphic_styles); } /// Threaded area type below a wrap object flows around it when the file opens: the text the wrap @@ -1358,6 +1403,77 @@ fn type_from_the_text_document_opens_without_the_pdf_parts_note_on_outlines() { assert!(!r["warnings"].as_array().unwrap().contains(&without_outlines_note(1)), "{r}"); } +/// A `.ai` whose text document makes all of its type, with nothing unread, opens from its layers +/// without its PDF part being imported: a page that draws more than the layers isn't compared with +/// them. On its trim box it takes the pages' bleed, and pages in units of 10 points draw it ten +/// times as large, as when its PDF part is imported. With type the text document can't make, +/// editing data on a large canvas, its type asked for as outlines, another box or pages picked, the +/// PDF part is imported as before. +#[test] +fn type_all_from_the_text_document_opens_without_importing_the_pdf_part() { + let line = half_outlined_line(65.0, "rst draft", 0); + // The page draws a red square the layers don't have. + let differs = half_outlined_ai(Some("first draft"), 0, &format!("{line} 1 0 0 rg 20 20 30 30 re f")); + let mut s = Session::new(); + let before = vectorcraft_pdf::imports_of(&differs); + let loaded = load_with("draft.ai", &differs, &LoadOptions::default()).unwrap(); + assert_eq!(vectorcraft_pdf::imports_of(&differs), before, "{:?}", loaded.warnings); + assert!(loaded.editing_data, "{:?}", loaded.warnings); + assert!(!loaded.warnings.iter().any(|w| w.contains("differently")), "{:?}", loaded.warnings); + let r = open(&mut s, "draft.ai", &differs, json!({})).unwrap(); + assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}"); + assert_eq!(texts(&s), ["first draft"], "{r}"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the square and the type, without the page's red square: {r}"); + // A 10 pt bleed round the trim box, the art drawn in the trim box. + let bled = half_outlined_ai_on(Some("first draft"), 0, &line, "", |p| PdfPage { + media: [0.0, 0.0, 220.0, 120.0], + bleed: Some([0.0, 0.0, 220.0, 120.0]), + trim: Some([10.0, 10.0, 210.0, 110.0]), + content: format!("1 0 0 1 10 10 cm {}", p.content), + ..p + }); + let before = vectorcraft_pdf::imports_of(&bled); + let loaded = load_with("bled.ai", &bled, &LoadOptions::default()).unwrap(); + assert_eq!(vectorcraft_pdf::imports_of(&bled), before); + assert_eq!(loaded.doc.setup.bleed, [10.0; 4]); + // Pages of 10 pt units. + let large = half_outlined_ai_on(Some("first draft"), 0, &line, "", |p| PdfPage { entries: format!("{} /UserUnit 10", p.entries), ..p }); + let before = vectorcraft_pdf::imports_of(&large); + let loaded = load_with("large.ai", &large, &LoadOptions::default()).unwrap(); + assert_eq!(vectorcraft_pdf::imports_of(&large), before); + let board = loaded.doc.artboards[0].rect; + assert!((board.width() - 2000.0).abs() < 0.01 && (board.height() - 1000.0).abs() < 0.01, "{board:?}"); + // Opened on the trim boxes with the PDF part imported and compared, as before, both files have + // the same artboards and bleed. + for file in [&bled, &large] { + let alone = load_with("draft.ai", file, &LoadOptions::default()).unwrap(); + let compared = load_with("draft.ai", file, &LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }).unwrap(); + assert!(compared.editing_data, "{:?}", compared.warnings); + let boards = |d: &vectorcraft_doc::Document| d.artboards.iter().map(|a| a.rect).collect::>(); + assert_eq!(boards(&alone.doc), boards(&compared.doc)); + assert_eq!(alone.doc.setup.bleed, compared.doc.setup.bleed); + assert_eq!(names(&alone.doc.layers), names(&compared.doc.layers)); + // The file has no graphic styles of its own: the default ones aren't scaled. + assert_eq!(alone.doc.graphic_styles, compared.doc.graphic_styles); + } + // The PDF part is imported, once. + let unmade = half_outlined_ai(Some("first draft"), 1, &line); + // Editing data on a large canvas reads at its own scale when the file has no PDF part. + let canvas = half_outlined_ai_on(Some("first draft"), 0, &line, "%AI24_LargeCanvasScale: 2\n", |p| p); + let cases = [ + (&unmade, LoadOptions::default()), + (&canvas, LoadOptions::default()), + (&differs, LoadOptions { text_as: vectorcraft_pdf::TextAs::Outlines, ..Default::default() }), + (&differs, LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }), + (&differs, LoadOptions { pages: Some("1".into()), ..Default::default() }), + ]; + for (file, opts) in cases { + let before = vectorcraft_pdf::imports_of(file); + load_with("draft.ai", file, &opts).unwrap(); + assert_eq!(vectorcraft_pdf::imports_of(file) - before, 1, "{opts:?}"); + } +} + /// A text object that takes the page's type lacks the glyphs next to it that the page kept as /// outlines: a note counts such objects, in place of the PDF part's notes. Stroked glyphs that /// come in with the stroked type keep the PDF part's notes. diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index 7b9f9774f3..ae7c66aa8b 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -453,27 +453,173 @@ fn ai_files_carry_an_editing_copy_for_other_apps() { } /// A `.ai` whose editing copy for other apps differs from the VectorCraft document it carries (the -/// copy has no transparency) opens in VectorCraft from the VectorCraft document. +/// copy leaves the live effect out) opens in VectorCraft from the VectorCraft document. #[test] fn an_ai_file_opens_from_its_vectorcraft_document_when_the_editing_copy_differs() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); - s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap(); - s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); - let bytes = b64(&s.execute("document.export", &json!({"format": "ai"})).unwrap()); - let opacities = |doc: &vectorcraft_doc::Document| { + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id]})).unwrap(); + let r = s.execute("document.export", &json!({"format": "ai"})).unwrap(); + assert!(r["warnings"].to_string().contains("live effects"), "{r}"); + let bytes = b64(&r); + let effects = |doc: &vectorcraft_doc::Document| { let mut out = vec![]; doc.walk(|n| { if matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }) { - out.push(n.opacity); + out.push(n.appearance.effects.len()); } }); out }; let copy = load::load_with("art.ai", &bytes, &LoadOptions { native: false, trust_editing_data: true, ..Default::default() }).unwrap(); assert!(copy.editing_data && !copy.restored); - assert_eq!(opacities(©.doc), [1.0]); + assert_eq!(effects(©.doc), [0]); let opened = load::load_with("art.ai", &bytes, &LoadOptions::default()).unwrap(); assert!(opened.restored); - assert_eq!(opacities(&opened.doc), [0.5]); + assert_eq!(effects(&opened.doc), [1]); +} + +/// The layers, groups, compound paths and paths of `doc` with their names, visibility, geometric +/// bounds (rounded), transparency, clipping and opacity masks, one line each; a mask's art after +/// its object. +fn see_through_outline(doc: &vectorcraft_doc::Document) -> Vec { + use vectorcraft_doc::NodeKind; + fn walk(nodes: &[std::sync::Arc], depth: usize, out: &mut Vec) { + for n in nodes { + let kind = match &n.kind { + NodeKind::Layer { clip, .. } => format!("layer clip={clip}"), + NodeKind::Group { clip, .. } => format!("group clip={clip}"), + NodeKind::Compound { .. } => "compound".into(), + NodeKind::Path { clipping, .. } => format!("path clipping={clipping}"), + _ => "other".into(), + }; + let b = n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64)); + let mask = n.extras().mask.clone(); + out.push(format!( + "{depth} {kind} {:?} {} {b:?} {} {:?} isolate={} {:?} shape={} mask={:?}", + n.name, + n.visible, + (n.opacity * 100.0).round(), + n.blend, + n.isolate, + n.knockout, + n.knockout_shape, + mask.as_ref().map(|m| (m.clip, m.invert, m.disabled, m.linked)) + )); + if let Some(m) = mask { + walk(std::slice::from_ref(&m.art), depth + 1, out); + } + walk(n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out); + } + } + let mut out = vec![]; + walk(&doc.layers, 0, &mut out); + out +} + +/// A document of two artboards (the art on the first) with a compound path at 70% in Screen, a +/// clipping group at 50% in Multiply, a named group (isolated, knockout on, knockout shape) and a +/// square with an opacity mask that doesn't clip on layer `Layer 1`, and layer `Cut` (40%, +/// clipping) holding two squares. +fn see_through_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64| { + id(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) + }; + // A compound path at 70% in Screen. + let (a, b) = (rect(&mut s, 10.0, 10.0, 40.0, 40.0), rect(&mut s, 20.0, 20.0, 20.0, 20.0)); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 70, "blend": "Screen"})).unwrap(); + // A clipping group at 50% in Multiply. + let (art, clip) = (rect(&mut s, 60.0, 10.0, 60.0, 40.0), rect(&mut s, 70.0, 20.0, 30.0, 20.0)); + s.execute("select.set", &json!({"ids": [art, clip]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50, "blend": "Multiply"})).unwrap(); + // A named group, isolated, knockout on, whose opacity defines the knockout shape. + let (a, b) = (rect(&mut s, 60.0, 60.0, 30.0, 30.0), rect(&mut s, 75.0, 75.0, 30.0, 30.0)); + let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + s.execute("object.setProps", &json!({"ids": [g], "name": "Knock", "opacity": 80, "isolate": true, "knockout": "on", "knockoutShape": true})) + .unwrap(); + // A square with an opacity mask that doesn't clip. + let masked = rect(&mut s, 130.0, 10.0, 40.0, 40.0); + s.execute("paint.setFill", &json!({"color": "#808080"})).unwrap(); + let mask = rect(&mut s, 140.0, 20.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [masked, mask]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({"clip": false})).unwrap(); + // A clipping layer at 40%. + let cut = id(s.execute("layer.new", &json!({"name": "Cut"})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + rect(&mut s, 10.0, 100.0, 80.0, 60.0); + rect(&mut s, 30.0, 110.0, 40.0, 40.0); + s.execute("layer.clippingMask.toggle", &json!({})).unwrap(); + s.execute("object.setProps", &json!({"ids": [cut], "opacity": 40})).unwrap(); + s +} + +/// The editing copy of `bytes` read alone, checked against its page. +fn editing_copy(bytes: &[u8]) -> vectorcraft_doc::Document { + let l = load::load_with("art.ai", bytes, &LoadOptions { native: false, ..Default::default() }).unwrap(); + assert!(l.editing_data && !l.restored, "{:?}", l.warnings); + assert!(!l.warnings.iter().any(|w| w.contains("editing data")), "{:?}", l.warnings); + l.doc +} + +/// `nodes` as the editing copy reads them back: an opacity mask's art that isn't a group comes +/// back as a plain group holding it. +fn mask_art_grouped(nodes: &mut [std::sync::Arc]) { + use vectorcraft_doc::{Node, NodeKind}; + for n in nodes { + let n = std::sync::Arc::make_mut(n); + if let Some(m) = n.extras_mut().mask.as_mut() + && !matches!(m.art.kind, NodeKind::Group { .. }) + { + let art = m.art.clone(); + m.art = std::sync::Arc::new(Node::new(art.id, NodeKind::Group { children: vec![art], clip: false })); + } + if let Some(c) = n.children_mut() { + mask_art_grouped(c); + } + } +} + +/// Transparency, a compound path, a clipping group, an opacity mask and a clipping layer come back +/// from the editing copy for other apps alone, its page matching it, with every save option that +/// writes the copy; the version 7 `.ai` keeps the compound path and the clipping group. +#[test] +fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() { + let mut s = see_through_session(); + let mut before = (*s.doc().unwrap().doc).clone(); + // The mask's art is one path; it reads back as a group holding the path. + let mut arts = vec![]; + before.walk(|n| arts.extend(n.extras().mask.as_ref().map(|m| matches!(m.art.kind, vectorcraft_doc::NodeKind::Path { .. })))); + assert_eq!(arts, [true]); + mask_art_grouped(&mut before.layers); + let want = see_through_outline(&before); + for opts in [json!({"format": "ai"}), json!({"format": "ai", "compress": false}), json!({"format": "ai", "pdfCompatible": true})] { + let bytes = b64(&s.execute("document.export", &opts).unwrap()); + assert_eq!(see_through_outline(&editing_copy(&bytes)), want, "{opts}"); + } + // Each artboard in a file of its own: the first holds all the art. + let path = tmp("see-through.ai"); + let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap(); + let files: Vec = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); + assert_eq!(files.len(), 3, "{r}"); + for f in &files { + let copy = editing_copy(&std::fs::read(f).unwrap()); + if f.ends_with("-2.ai") { + assert!(copy.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "{f} {:#?}", see_through_outline(©)); + } else { + assert_eq!(see_through_outline(©), want, "{f}"); + } + } + // Version 7 has no transparency; it keeps the compound path and the clipping group. + let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": 7})).unwrap(); + let legacy = load::load_with("art.ai", &b64(&r), &LoadOptions::default()).unwrap(); + let kinds = see_through_outline(&legacy.doc); + assert!(kinds.iter().any(|l| l.contains(" compound ")) && kinds.iter().any(|l| l.contains("group clip=true")), "{kinds:#?}"); } diff --git a/crates/engine/src/cmd/fileio/tests_pxrread.rs b/crates/engine/src/cmd/fileio/tests_pxrread.rs index 0562aacbb7..f9e89e38f1 100644 --- a/crates/engine/src/cmd/fileio/tests_pxrread.rs +++ b/crates/engine/src/cmd/fileio/tests_pxrread.rs @@ -361,3 +361,17 @@ fn damaged_files_are_refused_with_a_message() { assert!(!is_pxr(&bad), "{bad:?}"); } } + +#[test] +fn tile_pointers_into_the_header_or_table_are_refused() { + // Tile data follows the tile pointer table, which ends at byte 520 in a one-tile picture. + let rgb = one(head(2, 1, RGB, 2), &[1, 2, 3, 4, 5, 6]); + for pointer in [4u32, 511, 512, 519] { + let mut inside = rgb.clone(); + inside[512..516].copy_from_slice(&pointer.to_le_bytes()); + let e = raster_image(&inside).err().expect("refused").to_string(); + assert_eq!(e, "the Pixar file's image data is damaged", "a pointer to byte {pointer}"); + } + // A pointer at the table's end reads. + assert_eq!(pixels(&rgb), [[1, 2, 3, 255], [4, 5, 6, 255]]); +} diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs index ac04dc94c2..21b5245aef 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Add Freeform Point", [], None, - "{at: [x,y] (document coordinates), color? (default: the gradient's colour there), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}", + "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}", has_doc, add_point ), @@ -28,7 +28,7 @@ pub fn specs() -> Vec { "Edit Freeform Point", [], None, - "{index? (default: the selected point), at?: [x,y] (document coordinates), color?, keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}", + "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}", has_doc, set_point ), diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 52daa9b747..2fddbe9635 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image, except that PDF writes one with spot color stops in its inks when every other stop is paper white, CMYK or gray; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear or radial, has spot color stops, every other stop is paper white or written in CMYK or gray (a CMYK document, or an export that converts colors to a CMYK destination profile, writes RGB and Lab stops in CMYK), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", has_doc, edit_gradient ), diff --git a/crates/engine/src/cmd/halftone.rs b/crates/engine/src/cmd/halftone.rs index a205adc46c..bd6afd4663 100644 --- a/crates/engine/src/cmd/halftone.rs +++ b/crates/engine/src/cmd/halftone.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Vector Halftone…", ["Object"], None, - "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_selection, halftone )] diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3c7d00cb53..6b21673af6 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -83,7 +83,7 @@ pub fn specs() -> Vec { "Layer Options…", ["Window", "Layers"], None, - "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step", + "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step", has_doc, set_props ), @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "New Artboard", ["Window", "Artboards"], None, - "{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1)} (default place: right of the last)", + "{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1)} (default place: right of the last)", has_doc, artboard_new ), @@ -155,7 +155,7 @@ pub fn specs() -> Vec { "Artboard Options…", ["Window", "Artboards"], None, - "{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}", + "{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}", has_doc, artboard_set ), @@ -297,7 +297,8 @@ pub(crate) fn make_layer(d: &mut Document, name: Option<&str>) -> Node { NewLayers::of(d).make(d, name) } -/// A layer colour: a preset index (0–26), `#rrggbb` or a preset's name (any case). +/// A layer colour: a preset index (0–26), `#rrggbb` or a preset's name (any case). A hex color +/// with an alpha part (`#rrggbbaa` or `#rgba`) is an error. pub(super) fn layer_color_param(v: &Value) -> std::result::Result { match v { Value::Number(n) => match n.as_u64() { @@ -308,7 +309,13 @@ pub(super) fn layer_color_param(v: &Value) -> std::result::Result Vec { "Add to Library", [], None, - "{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}", + "{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}", has_doc, add ), diff --git a/crates/engine/src/cmd/live.rs b/crates/engine/src/cmd/live.rs index be2b694cdc..be02c16b1b 100644 --- a/crates/engine/src/cmd/live.rs +++ b/crates/engine/src/cmd/live.rs @@ -20,7 +20,7 @@ use super::edit::selected_roots; use super::expand::gradient_sampler; use super::pathops::Beside; use super::{ - CommandSpec, EngineError, Result, Session, always, bad, check_numbers, check_switches, cmd, color_value, f64_or, f64_req, finite_numbers, + CommandSpec, EngineError, Result, Session, always, bad, check_numbers, check_switches, cmd, color_param, f64_or, f64_req, finite_numbers, has_doc, has_multi, has_selection, id_param, named_ids, number_or, ok, str_param, switch_or, }; diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 5f438c8f5b..99c813fa3e 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -245,7 +245,7 @@ pub fn specs() -> Vec { "Set Mesh Point Color", [], None, - "{id, index | points: [index…] | items: [{id, index | points}…], color?, keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)", + "{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)", has_doc, mesh_set_color ), @@ -272,7 +272,7 @@ pub fn specs() -> Vec { "Add Mesh Line", [], None, - "{id, x, y, color?, keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}", + "{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}", has_doc, mesh_add_line ), diff --git a/crates/engine/src/cmd/live/mesh.rs b/crates/engine/src/cmd/live/mesh.rs index e00c074bcd..87a7af3578 100644 --- a/crates/engine/src/cmd/live/mesh.rs +++ b/crates/engine/src/cmd/live/mesh.rs @@ -4,7 +4,7 @@ use super::common::{fix_ids, ids_json, is_mesh, replace_with, roots_param, selec use super::envelope::{outline_of, rows_cols}; use super::{ Color, Document, EngineError, EnvelopeKind, GradientMesh, MeshAppearance, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, bad, - check_numbers, color_value, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param, + check_numbers, color_param, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param, }; // ---------- Gradient mesh ---------- @@ -232,7 +232,7 @@ pub(super) fn mesh_set_color(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["opacity"], C)?; crate::cmd::paint::check_keep_model(p, C)?; let items = point_items(p, C)?; - let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c)); + let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c)); let opacity = p.get("opacity").and_then(Value::as_f64); if color.is_none() && opacity.is_none() { return Err(bad(C, "missing `color` or `opacity`")); @@ -283,7 +283,7 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result { crate::cmd::paint::check_keep_model(p, C)?; check_numbers(p, &["tolerance"], C)?; let tol = f64_or(p, "tolerance", 0.0).max(0.0); - let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c)); + let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c)); let index = with_mesh(s, p, C, "Add Mesh Line", true, |m| { let i = m.add_lines_at(q, tol).ok_or_else(|| bad(C, "point is outside the mesh"))?; if let Some(c) = color { diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 73cf96c9ba..e608bb43c2 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -115,7 +115,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\", antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -347,7 +347,7 @@ fn other_layers(s: &mut Session, lock: bool) -> Result { } /// Returns the objects [`super::select::walk_selectable`] visits that are not among the selected objects `roots` and -/// hold none of them. A selected layer's objects count as selected. The walk goes into a plain group, but not a Shaper +/// hold none of them. A selected layer and its objects count as selected. The walk goes into a plain group, but not a Shaper /// group, that holds a selected object. With `lock`, it also goes into a clip group or compound path that holds one, /// and includes guide paths while `guides_locked`. Without `lock`, guide paths and the objects that hold one are left /// out while `guides_locked`; a clip group, Shaper group, compound path and every other object that holds a selected @@ -360,14 +360,32 @@ fn unselected( guides_locked: bool, lock: bool, ) -> Vec { + /// Pushes the visible guide paths in `n`, `n` included, locked ones too. + fn shown_guides(n: &vectorcraft_doc::Node, out: &mut Vec) { + if !n.visible { + return; + } + if matches!(n.kind, NodeKind::Path { guide: true, .. }) { + out.push(n.id); + } + for c in n.children().into_iter().flatten() { + shown_guides(c, out); + } + } let mut roots: HashSet = roots.iter().copied().collect(); - roots.extend(selection.iter().filter_map(|id| d.node(*id)).filter(|n| n.is_layer()).flat_map(|l| l.layer_art(true))); + let layers = || selection.iter().filter_map(|id| d.node(*id)).filter(|n| n.is_layer()); + roots.extend(layers().map(|l| l.id)); + roots.extend(layers().flat_map(|l| l.layer_art(true))); let mut kept: Vec = roots.iter().copied().collect(); if guides_locked && !lock { super::select::walk_selectable(d, iso, |n| { if matches!(n.kind, NodeKind::Path { guide: true, .. }) { kept.push(n.id); } + // The walk skips locked objects, so the guide paths in them are looked for here. + for c in n.children().into_iter().flatten().filter(|c| c.locked) { + shown_guides(c, &mut kept); + } true }); } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 3abe60b541..0772bf5b14 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 0c0a81ed90..1ca9bf2339 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -303,16 +303,30 @@ fn is_effect_color(v: &Value) -> bool { pub(crate) fn check_effect_color(id: &str, effect: &str, params: &Value) -> Result<()> { let key = "color"; let Some(v) = params.get(key) else { return Ok(()) }; - if effect.starts_with(vectorcraft_plugins::effect::PREFIX) { - return Ok(()); - } - let takes_color = vectorcraft_render::effects::effect_info(effect).is_some_and(|info| info.defaults.get(key).is_some_and(Value::is_string)); - if takes_color && !is_effect_color(v) { + if effect_takes_color(effect) && !is_effect_color(v) { return Err(bad(id, format!("`{key}` must be a #rrggbb color"))); } Ok(()) } +/// Does built-in effect `effect` have a `color` parameter (one whose default is a string)? Plug-in +/// effects have none here. +pub(crate) fn effect_takes_color(effect: &str) -> bool { + !effect.starts_with(vectorcraft_plugins::effect::PREFIX) + && vectorcraft_render::effects::effect_info(effect).is_some_and(|info| info.defaults.get("color").is_some_and(Value::is_string)) +} + +/// The color that built-in effect `effect` draws with `params`: their `color`, else the effect's +/// default color. `None` when the effect has no `color` parameter ([`effect_takes_color`]) or +/// `params` hold a `color` it can't read ([`is_effect_color`]). +pub(crate) fn effect_color(effect: &str, params: &Value) -> Option { + if !effect_takes_color(effect) || params.get("color").is_some_and(|v| !is_effect_color(v)) { + return None; + } + let merged = vectorcraft_render::effects::merged_params(effect, params); + Some(vectorcraft_render::effects::color_param(&merged, vectorcraft_color::Color::BLACK)) +} + /// The `channel` in `params` of Levels or Curves (`effect`), as command `id` was given it: a /// parameter error naming the channels unless the effect reads it /// ([`vectorcraft_render::effects::is_channel`]); the effect draws any other value as RGB. diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index f1bc3e501a..2def5ce9ea 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1189,7 +1189,9 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result { ok() } -pub(crate) fn delete_anchors(s: &mut Session, _: &Value) -> Result { +pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { + // `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step. + let with_guides = p.get("guides").and_then(Value::as_bool).unwrap_or(false); let st = s.doc()?; let sel = st.selection.anchors.clone(); let segments = st.selection.segments.clone(); @@ -1197,6 +1199,10 @@ pub(crate) fn delete_anchors(s: &mut Session, _: &Value) -> Result { // also catches part of another path must still delete those whole objects. let whole = st.selection.whole(); s.edit("Clear", |d, selection| { + if with_guides { + let gone = selection.guides.clone(); + d.retain_guides(selection, |i, _| !gone.contains(&i)); + } let targets: BTreeSet = whole.into_iter().filter(|id| d.node(*id).is_some_and(|n| !n.is_layer())).collect(); let whole_ids: Vec = targets .iter() diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 610b50c2d6..cd03a41512 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -185,7 +185,7 @@ impl FilterRun { if let Some(data) = out.document_data { d.set_plugin_data(&m.id, data); } - sel.set(ids.iter().copied()); + sel.set(ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable))); Ok(ids) })?; Ok(json!({"plugin": m.id, "ids": ids.iter().map(|i| i.0).collect::>()})) @@ -432,7 +432,7 @@ pub fn specs() -> Vec { "Run Plug-in", [], None, - "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [..] (default: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths are left out): it may change, delete or add objects, as one undo step; the result is selected. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}", + "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [..] (default: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}", has_doc, run ), diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 1759372d0a..f4996f4ad0 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null, exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}", has_doc, apply ), @@ -255,13 +255,14 @@ enum Match { } impl Match { - /// A colour key, a hex (`#rrggbb`) or a colour value. + /// A colour key, a hex (`#rrggbb`) or a colour value. `None` for a hex color with an alpha + /// part (`#rrggbbaa` or `#rgba`). fn of(v: &Value) -> Option { if let Some(s) = v.as_str() { if let Some(k) = ColorKey::parse(s) { return Some(Match::Key(k)); } - return Color::from_hex(s).map(|c| Match::Hex(c.to_hex())); + return Color::from_hex(s).filter(|_| !super::hex_with_alpha(s)).map(|c| Match::Hex(c.to_hex())); } color_value(v).map(|c| Match::Key(ColorKey::of(&c))) } diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 6cc8e3839a..0f16246dff 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Select by Color", [], None, - "{fill?: colour, stroke?: colour (as paint.setFill's color; at least one)} select the objects whose fill (and stroke) reads as that colour in #rrggbb, as document.inspect reports colours, whatever its swatch or tint; with both, the objects that match both. No object needs to be selected first; Select > Reselect repeats it → {count}", + "{fill?: colour, stroke?: colour (as paint.setFill's color, #rrggbbaa and #rgba refused; at least one)} select the objects whose fill (and stroke) reads as that colour in #rrggbb, as document.inspect reports colours, whatever its swatch or tint; with both, the objects that match both. No object needs to be selected first; Select > Reselect repeats it → {count}", has_doc, select_color ), @@ -321,21 +321,19 @@ fn all_on_artboard(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let i = p.get("artboard").and_then(Value::as_u64).map_or(0, index); let r = st.doc.artboards.get(i).map(|a| a.rect).ok_or_else(|| bad("select.allOnArtboard", "no such artboard"))?; - // Symbol instances are measured by their art. let symbols = st.doc.symbol_boxes(); - let ids: Vec = selectable(&st.doc, st.isolation) - .into_iter() - .filter(|id| { - st.doc - .node(*id) - .and_then(|n| n.geometric_bounds_with(&symbols)) - .is_some_and(|b| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center())) - }) - .collect(); + let ids: Vec = + selectable(&st.doc, st.isolation).into_iter().filter(|id| st.doc.node(*id).is_some_and(|n| on_artboard(n, &symbols, r))).collect(); s.select(|_, sel| sel.set(ids.iter().copied()))?; ok() } +/// Is `n` on the artboard at `r`, as All on Active Artboard takes it: its geometric bounds (a +/// symbol instance's measured by its art) overlap the artboard, or its center is on it. +pub(crate) fn on_artboard(n: &Node, symbols: &vectorcraft_doc::SymbolBoxes, r: vectorcraft_geom::Rect) -> bool { + n.geometric_bounds_with(symbols).is_some_and(|b| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center())) +} + fn none(s: &mut Session, _: &Value) -> Result { s.select(|_, sel| sel.clear())?; ok() @@ -819,8 +817,16 @@ fn same_attribute(s: &mut Session, p: &Value) -> Result { fn same_layers(s: &mut Session, _: &Value) -> Result { let st = s.doc()?; - // The layers or sublayers the selected objects are on (art in their sublayers too). - let layers: BTreeSet = st.selection.objects.iter().filter_map(|id| st.doc.layer_containing(*id)).collect(); + // The layers or sublayers the selected objects are on (art in their sublayers too). A selected + // object that `is_selectable` does not accept adds no layer. + let locks = st.doc.locked_artboards(); + let layers: BTreeSet = st + .selection + .objects + .iter() + .filter(|id| is_selectable(&st.doc, st.isolation, &locks, **id)) + .filter_map(|id| st.doc.layer_containing(*id)) + .collect(); let mut on = BTreeSet::new(); for l in layers.iter().filter_map(|l| st.doc.node(*l)) { l.walk(&mut |n| { diff --git a/crates/engine/src/cmd/slices.rs b/crates/engine/src/cmd/slices.rs index 1adc147c56..cc8598a5cc 100644 --- a/crates/engine/src/cmd/slices.rs +++ b/crates/engine/src/cmd/slices.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Slice Options…", ["Object", "Slice"], None, - "{kind?: \"image\"|\"noImage\"|\"htmlText\" (object slices of type only), name?, url?, target?, message?, alt?: (image), text?: cell text; HTML allowed (noImage), background?: \"\"|\"matte\"|\"#rrggbb\", hAlign?: \"default\"|\"left\"|\"center\"|\"right\", vAlign?: \"default\"|\"top\"|\"middle\"|\"baseline\"|\"bottom\"} set the selected slices' options as one undo step; no options: read them → the first slice's {kind, name, url, target, message, alt, text, background, hAlign, vAlign, htmlText: whether HTML Text applies}", + "{kind?: \"image\"|\"noImage\"|\"htmlText\" (object slices of type only), name?, url?, target?, message?, alt?: (image), text?: cell text; HTML allowed (noImage), background?: \"\"|\"matte\"|\"#rrggbb\" (#rrggbbaa and #rgba are refused), hAlign?: \"default\"|\"left\"|\"center\"|\"right\", vAlign?: \"default\"|\"top\"|\"middle\"|\"baseline\"|\"bottom\"} set the selected slices' options as one undo step; no options: read them → the first slice's {kind, name, url, target, message, alt, text, background, hAlign, vAlign, htmlText: whether HTML Text applies}", slices_targeted, options ), @@ -513,6 +513,7 @@ impl Edits { "" | "none" => Ok(String::new()), "matte" => Ok("matte".to_string()), _ => vectorcraft_color::Color::from_hex(&b) + .filter(|_| !super::hex_with_alpha(&b)) .map(|c| c.to_hex()) .ok_or_else(|| bad(C, "`background` must be \"\", \"matte\" or #rrggbb")), }) diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 4aa0c0b472..7944e59a0d 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "New Swatch", ["Window", "Swatches"], None, - "{name?, color? | colors?: [colour] (one swatch each, in one undo step) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}", + "{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}", has_doc, swatch_new ), @@ -38,7 +38,7 @@ pub fn specs() -> Vec { "New Color Group", ["Window", "Swatches"], None, - "{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}", + "{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}", has_doc, swatch_new_group ), @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Swatch Options", ["Window", "Swatches"], None, - "{name, newName?, color? (e.g. {l, a, b} for a Lab colour), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient}, {swatch} or {pattern}) replacing the swatch's colour; gradient or pattern with one of the same kind} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}", + "{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient}, {swatch} or {pattern}) replacing the swatch's colour; gradient or pattern with one of the same kind} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}", has_doc, swatch_edit ), @@ -130,7 +130,7 @@ pub fn specs() -> Vec { "Edit Color Group", ["Window", "Swatches"], None, - "{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}", + "{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}", has_doc, swatch_edit_group ), @@ -316,7 +316,8 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result { let colors: Vec = p .get("colors") .and_then(Value::as_array) - .map(|a| a.iter().filter_map(color_value).map(|c| super::paint::new_color(s, p, c)).collect()) + .map(|a| a.iter().map(|v| color_value(v).map(|c| super::paint::new_color(s, p, c)).ok_or_else(|| bad(C, format!("bad color {v}")))).collect()) + .transpose()? .unwrap_or_default(); let from_art = bool_or(p, "fromArtwork", false); let to_global = from_art && bool_or(p, "toGlobal", true); diff --git a/crates/engine/src/cmd/tabs.rs b/crates/engine/src/cmd/tabs.rs index 193ced2f79..570a93c77a 100644 --- a/crates/engine/src/cmd/tabs.rs +++ b/crates/engine/src/cmd/tabs.rs @@ -69,6 +69,23 @@ fn apply(s: &mut Session, p: &Value, stops: Vec, label: &str) -> Result let ids = text_targets(s, p, "text.tabs.set")?; let range = TextRange::parse(p, "text.tabs.set")?; let n = stops.len(); + // A typing session ends here as `s.edit` would end it, whether or not the stops then change: + // the typing is its own undo step. + if !s.previewing && super::typing_in_progress(s) { + super::settle_interaction(s)?; + } + // Every targeted paragraph already holds these stops: no edit and no undo step. + let doc = &s.doc()?.doc; + let unchanged = ids.iter().all(|id| match doc.node(*id).map(|node| &node.kind) { + Some(NodeKind::Text(t)) => match para_span(range, t) { + None => t.para_styles().all(|pa| pa.tabs == stops), + Some(mut r) => r.all(|i| t.para_at(i).tabs == stops), + }, + _ => true, + }); + if unchanged { + return Ok(json!({ "stops": n })); + } s.edit(label, |d, _| { for id in &ids { if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { @@ -114,6 +131,60 @@ mod tests { assert_eq!(s.execute("text.tabs.get", &json!({})).unwrap()["stops"], json!([])); } + /// Setting the stops every targeted paragraph already holds records no undo step. When one + /// targeted paragraph holds other stops, the command still sets them all. + #[test] + fn setting_the_same_stops_records_no_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb\nc\td"})).unwrap(); + let stops = json!({"stops": [{"position": 0}, {"position": 20, "leader": "."}]}); + s.execute("text.tabs.set", &stops).unwrap(); + let undo = |s: &Session| s.active().unwrap().history.undo.len(); + let before = undo(&s); + s.execute("text.tabs.set", &stops).unwrap(); + s.execute("text.tabs.set", &json!({"stops": [{"position": 20, "leader": "."}, {"position": 0}]})).unwrap(); + assert_eq!(undo(&s), before); + s.execute("text.tabs.clear", &json!({})).unwrap(); + s.execute("text.tabs.clear", &json!({})).unwrap(); + assert_eq!(undo(&s), before + 1); + // The second paragraph (bytes 4 on) takes other stops; setting the first paragraph's stops + // on both paragraphs changes the second. + s.execute("text.tabs.set", &stops).unwrap(); + s.execute("text.tabs.set", &json!({"stops": [{"position": 50}], "start": 4, "end": 4})).unwrap(); + let before = undo(&s); + s.execute("text.tabs.set", &stops).unwrap(); + assert_eq!(undo(&s), before + 1); + assert_eq!(s.execute("text.tabs.get", &json!({"start": 4})).unwrap()["stops"][1]["position"], json!(20.0)); + } + + /// Setting the stops the paragraphs already hold, while the Type tool is typing, still ends the + /// typing session: the typing is its own undo step, as when the stops change. + #[test] + fn setting_the_same_stops_ends_the_typing() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + + use crate::ViewInfo; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb"})).unwrap()["id"].as_u64().unwrap(); + let stops = json!({"stops": [{"position": 40}], "ids": [id]}); + s.execute("text.tabs.set", &stops).unwrap(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, b.x1 - 1.0, b.center().y), v).unwrap(); + } + s.tool_text("!", v).unwrap(); + assert!(crate::cmd::typing_in_progress(&s)); + let steps = s.active().unwrap().history.undo.len(); + s.execute("text.tabs.set", &stops).unwrap(); + assert!(!crate::cmd::typing_in_progress(&s)); + let labels: Vec = s.active().unwrap().history.undo.iter().map(|e| e.label.clone()).collect(); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Typing"))); + } + /// #1877: a leader set the way the Tabs panel sets it fills the tab's gap with its dots. #[test] fn tab_leader_fills_the_gap_with_its_characters() { diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 03943029ea..465e02b459 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -53,6 +53,24 @@ pub fn specs() -> Vec { has_doc, touch_type ), + cmd!( + "text.setGlyphAlternate", + "Glyphs", + [], + None, + "{id, start: byte (a character of it), gid: glyph id|null} draw that one character with another glyph of its font as one undo step, what a double-click in the Glyphs panel's Show › Alternates for Current Selection does: gid is one of the glyphs text.glyphAlternates lists for it; its own default glyph, or null, puts the default glyph back. The text keeps the character, and its other attributes do not change. The choice is saved with the character's style and names the face it was made in (PostScript name and version): set in another font or version, or after the font goes missing, the character takes its default glyph; typed characters take their default glyphs. Choosing the glyph the character already draws is not an edit. An error when the character's font is not available, the glyph is not one of its alternates, or the character's style does not draw it (All Caps, Small Caps, another numeral system) → {id, start, end (the character's bytes), gid (the glyph drawn)}", + has_doc, + set_glyph_alternate + ), + cmd!( + query "text.glyphAlternates", + "Glyphs", + [], + None, + "{id, start: byte (a character of it)} the alternate glyphs of that character in its font, what the Glyphs panel's Show › Alternates for Current Selection lists: from the font's OpenType GSUB table, the glyphs that single and alternate substitutions put in place of the character's default glyph, `aalt` first, then `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99`, `hist`, `jalt`, `nalt`, `ornm` and `titl`, each glyph once, the default glyph only when `aalt` lists it → {char, font: family, style: style, default: glyph id, chosen: glyph id (the glyph drawn now), alternates: [{gid, feature}]} (empty when the font has none for it; an error when the character's font is not available)", + has_doc, + glyph_alternates + ), cmd!( query "text.getRange", "Get Text Range", @@ -930,8 +948,8 @@ impl CharChange { /// Type › Enable Missing Glyph Protection: after a font change, the characters of `runs` their new /// font has no glyph for, but their font `before` the change had, keep that font: its family, -/// style, version and Variable Font settings. -pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec) { +/// style, version and Variable Font settings. Returns the byte ranges that kept their font, in order. +pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec) -> Vec<(usize, usize)> { fn chars(runs: &[TextRun]) -> impl Iterator { runs.iter() .scan(0, |at, r| { @@ -963,6 +981,7 @@ pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec _ => keep.push((at, end, old)), } } + let kept = keep.iter().map(|(a, b, _)| (*a, *b)).collect(); for (a, b, old) in keep { edit::style_range(runs, a, b, |st| { st.font_family.clone_from(&old.font_family); @@ -971,6 +990,30 @@ pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec st.font_axes.clone_from(&old.font_axes); }); } + kept +} + +/// The runs of `runs` from byte `a` to `b`, leaving out the ranges `kept` (in order) that Missing +/// Glyph Protection gave their earlier font: the characters a font command set its font on. +pub(crate) fn unprotected_runs(runs: &[TextRun], a: usize, b: usize, kept: &[(usize, usize)]) -> Vec { + let mut out = vec![]; + let mut at = a; + for &(k0, k1) in kept { + if k1 <= at { + continue; + } + if k0 >= b { + break; + } + if k0 > at { + out.extend(edit::slice_runs(runs, at, k0)); + } + at = k1; + } + if at < b { + out.extend(edit::slice_runs(runs, at, b)); + } + out } fn set_range_style(s: &mut Session, p: &Value) -> Result { @@ -1021,12 +1064,10 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { } let before = protect.then(|| t.runs.clone()); edit::style_range(&mut t.runs, a, b, |st| change.apply(st)); - if let Some(before) = before { - protect_missing_glyphs(&before, &mut t.runs); - } + let kept = before.map(|before| protect_missing_glyphs(&before, &mut t.runs)).unwrap_or_default(); if sets_font { - // Empty text has one run, which the empty range styles. - let styled = if a == b { t.runs.clone() } else { edit::slice_runs(&t.runs, a, b) }; + // Empty text has one run, which the empty range styles. Characters that kept their font aren't the command's. + let styled = if a == b { t.runs.clone() } else { unprotected_runs(&t.runs, a, b, &kept) }; set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style))); } refresh_bounds(t); @@ -1085,6 +1126,144 @@ pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &ve if em > 0.0 { drawn_gap(original).zip(drawn_gap(&base)).map_or(0.0, |(a, b)| (a - b) * 1000.0 / em) } else { 0.0 } } +/// The character at byte `start` of `p` in text object `t`, its bytes and its font's face. An error +/// when there is no character there, it is an inline graphic, or its font is not available. +fn glyph_target(t: &TextObject, p: &Value, c: &str) -> Result<(char, std::ops::Range, std::sync::Arc)> { + check_numbers(p, &["start"], c)?; + let start = byte_param(p, "start").ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?; + let mut at = 0; + for run in &t.runs { + let end = at + run.text.len(); + if (at..end).contains(&start) { + let ch = run.text.get(start - at..).and_then(|s| s.chars().next()).ok_or_else(|| bad(c, format!("no character at byte {start}")))?; + if run.inline.is_some() { + return Err(bad(c, "an inline graphic has no glyphs")); + } + let db = vectorcraft_text::FontDb::global(); + let face = db.style_face(&run.style).filter(|_| db.has_family(&run.style.font_family)); + let face = face.ok_or_else(|| bad(c, format!("the font {} is not available", run.style.font_family)))?; + return Ok((ch, start..start + ch.len_utf8(), face)); + } + at = end; + } + Err(bad(c, format!("no character at byte {start}"))) +} + +fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.setGlyphAlternate"; + let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let gid = match p.get("gid") { + None => return Err(bad(C, "missing `gid` (a glyph id, or null for the default glyph)")), + Some(Value::Null) => None, + Some(v) => Some(v.as_u64().and_then(|g| u32::try_from(g).ok()).ok_or_else(|| bad(C, format!("`gid` must be a glyph id, not {v}")))?), + }; + let t = text_ref(s, id)?; + let (ch, bytes, face) = glyph_target(&t, p, C)?; + let default = face.glyph_for(ch); + let holder = t + .runs + .iter() + .scan(0, |at, r| { + let start = *at; + *at += r.text.len(); + Some((start..*at, r)) + }) + .find(|(bytes_of_run, _)| bytes_of_run.contains(&bytes.start)); + let styled = + holder.as_ref().is_some_and(|(_, r)| r.style.all_caps || (r.style.small_caps.is_some() && ch.is_lowercase()) || r.style.digits.map(ch) != ch); + // The glyph the character is drawn with when it holds no choice, drawn alone in its face: a + // feature of its style (`salt`, a stylistic set) can draw another glyph than the default one. + // The default glyph is then kept as a choice, so that it is drawn. A character that is not laid + // out (overflowing text) is shaped alone in its style and writing direction. A character that starts a longer + // grapheme (a letter and its combining marks) is drawn in the grapheme's cluster, and is shaped + // with the grapheme. Of a cluster of several glyphs (a mark, a vowel sign drawn before the + // letter), the character's glyph is its default glyph or one of its alternates. + let plain = t.plain_text(); + let grapheme = plain.get(bytes.start..edit::next_cluster(&plain, bytes.start).max(bytes.end)).map_or_else(|| ch.to_string(), str::to_owned); + let listed = face.alternates(ch); + let own_glyph = |lay: &vectorcraft_text::TextLayout, at: usize| { + let cluster: Vec = lay + .glyphs + .iter() + .filter(|g| g.byte == at && [bytes.len(), grapheme.len()].contains(&g.len) && g.font_id == face.id()) + .map(|g| g.gid) + .collect(); + match cluster[..] { + [one] => Some(one), + _ => cluster.into_iter().find(|&g| g == default || listed.iter().any(|a| a.gid == g)), + } + }; + let alone_in_face = |lay: &vectorcraft_text::TextLayout| { + let found = lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len)); + found.map(|_| own_glyph(lay, bytes.start)) + }; + let unchosen = match holder.as_ref().filter(|_| !styled) { + None => None, + Some((_, run)) => { + let mut probe = t.clone(); + edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = None); + let db = vectorcraft_text::FontDb::global(); + alone_in_face(&vectorcraft_text::layout(db, &probe)).unwrap_or_else(|| { + let st = CharStyle { glyph_alternate: None, ..run.style.clone() }; + let mut single = TextObject::point(Point::ZERO, &grapheme, st); + single.vertical = t.vertical; + own_glyph(&vectorcraft_text::layout(db, &single), 0) + }) + } + }; + let substituted = unchosen.is_some_and(|g| g != default); + let choice = match gid.filter(|g| *g != default || substituted) { + None => None, + Some(g) if g == default || face.alternates(ch).iter().any(|a| a.gid == g) => Some(face.choice(ch, g)), + Some(g) => return Err(bad(C, format!("glyph {g} is not an alternate of {ch} in {} {}", face.family, face.style))), + }; + let drawn = choice.as_ref().map_or(unchosen.unwrap_or(default), |c| c.gid); + // The run holding the character. The request changes nothing when the choice is the one the + // character's run holds and that run holds the character alone; otherwise the edit splits the + // run, so that the following text does not take the character into a ligature. + let held = holder.as_ref().filter(|(bytes_of_run, _)| bytes_of_run.start == bytes.start).and_then(|(_, r)| r.style.glyph_alternate.clone()); + let alone = holder.as_ref().is_some_and(|(bytes_of_run, _)| *bytes_of_run == bytes); + // A choice that the character's style keeps from being drawn (All Caps, Small Caps, another + // numeral system) is an error, not an edit that leaves the page as it was. The style decides + // for a character outside its frame too; one that is laid out is checked in the layout. + if let Some(c) = &choice { + let shown = || { + let mut probe = t.clone(); + edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = Some(c.clone())); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe); + lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len)).map(|g| g.gid) + }; + if styled || shown().is_some_and(|g| g != c.gid) { + return Err(bad( + C, + format!("glyph {} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system)", c.gid), + )); + } + } + if held == choice && (choice.is_none() || alone) { + return Ok(json!({"id": id.0, "start": bytes.start, "end": bytes.end, "gid": drawn})); + } + s.edit("Glyphs", |d, _| { + let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?; + edit::style_range(&mut t.runs, bytes.start, bytes.end, |st| st.glyph_alternate = choice.clone()); + refresh_bounds(t); + Ok(()) + })?; + Ok(json!({"id": id.0, "start": bytes.start, "end": bytes.end, "gid": drawn})) +} + +fn glyph_alternates(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.glyphAlternates"; + let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let t = text_ref(s, id)?; + let (ch, bytes, face) = glyph_target(&t, p, C)?; + let default = face.glyph_for(ch); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let chosen = lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len)).map_or(default, |g| g.gid); + let alternates: Vec = face.alternates(ch).iter().map(|a| json!({"gid": a.gid, "feature": String::from_utf8_lossy(&a.feature)})).collect(); + Ok(json!({"char": ch.to_string(), "font": face.family, "style": face.style, "default": default, "chosen": chosen, "alternates": alternates})) +} + fn touch_type(s: &mut Session, p: &Value) -> Result { const C: &str = "text.touchType"; let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; @@ -1330,6 +1509,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { super::paint::check_keep_model(p, C)?; check_numbers(p, &["size"], C)?; check_switches(p, &["vertical", "placeholder"], C)?; + super::color_param(p, "color", C)?; let style = super::create::new_type_style(s, p); let text = str_param(p, "text").unwrap_or("").to_string(); let start = match point_param(p, "at") { diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 517af3a7b6..c6442c193a 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -51,14 +51,14 @@ const fn spec(id: &'static str, label: &'static str, menu: &'static [&'static st } macro_rules! style_cmds { - ($kind:expr, $p:literal, $menu:literal, $what:literal) => { + ($kind:expr, $p:literal, $menu:literal, $what:literal, $bounds:literal) => { vec![ spec(concat!($p, ".list"), concat!($what, " Styles"), &[], "{} → {styles: [{name, attrs, uses}]}", |s, _| list(s, $kind), false), spec( concat!($p, ".new"), concat!("New ", $what, " Style"), &["Window", "Type", $menu], - "{name? (trimmed, as rename trims `to`), attrs?: {…} (default: selected text), id?, start?: byte, end?: byte} → {name}; a nonempty character range samples its first selected character; start alone keeps insertion affinity; paragraph styles sample start", + concat!("{name? (trimmed, as rename trims `to`), attrs?: {…} (default: selected text), id?, start?: byte, end?: byte} → {name}; a nonempty character range samples its first selected character; start alone keeps insertion affinity; paragraph styles sample start", $bounds), |s, p| new(s, p, $kind), true, ), @@ -82,7 +82,7 @@ macro_rules! style_cmds { concat!($p, ".setAttrs"), concat!($what, " Style Options"), &[], - "{name, attrs: {…}} replace the style's attributes; users keep their overrides", + concat!("{name, attrs: {…}} replace the style's attributes; users keep their overrides", $bounds), |s, p| set_attrs(s, p, $kind), true, ), @@ -116,16 +116,22 @@ macro_rules! style_cmds { } pub fn specs() -> Vec { - let mut v = style_cmds!(Kind::Char, "charStyle", "Character Styles", "Character"); + let mut v = style_cmds!( + Kind::Char, + "charStyle", + "Character Styles", + "Character", + "; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt" + ); v.push(spec( "charStyle.edit", "Edit Character Style", &[], - "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides", + "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt", |s, p| edit_style(s, p, Kind::Char), true, )); - v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph")); + v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph", "")); v } @@ -155,6 +161,8 @@ fn to_attrs(v: &T) -> Map { /// from a style instead leaves the text's own value alone. pub fn char_attrs(v: &CharStyle) -> Map { let mut m = to_attrs(v); + // A chosen glyph belongs to one character, not to a reusable character style. + m.remove("glyphAlternate"); for (k, x) in [ ("font_version", json!(v.font_version)), ("fontAxes", json!(v.font_axes)), @@ -270,11 +278,9 @@ fn restyle( new: &Map, base: &Map, ) -> T { - let Some(full) = to_map(cur) else { return cur.clone() }; - let mut m = attrs(cur); - if let Some(name) = full.get("style_name") { - m.insert("style_name".into(), name.clone()); - } + // Starts from every key `cur` writes, so values no style sets (a glyph choice) are kept. + let Some(mut m) = to_map(cur) else { return cur.clone() }; + m.extend(attrs(cur)); for (k, v) in new { if old.get(k).is_none_or(|o| m.get(k) == Some(o)) { m.insert(k.clone(), v.clone()); @@ -492,8 +498,27 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma let c = kind.cmd(verb); let full = match kind { Kind::Char => { + if m.contains_key("glyphAlternate") { + return Err(bad(&c, "`glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it)")); + } let mut st = with_attrs(&CharStyle::default(), m, &c)?; let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key); + for (key, value, lo, hi) in + [("size", st.size, 0.1, 1296.0), ("h_scale", st.h_scale, 1.0, 10000.0), ("v_scale", st.v_scale, 1.0, 10000.0)] + { + if changed(key) && !(lo..=hi).contains(&value) { + return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); + } + } + if changed("leading") && st.leading.is_some_and(|value| !(0.1..=5000.0).contains(&value)) { + return Err(bad(&c, "`leading` must be from 0.1 to 5000, or null for Auto")); + } + let shift_max = 1296.0; + for (key, value) in [("baseline_shift", st.baseline_shift), ("tcyUpDown", st.tcy_up_down), ("tcyLeftRight", st.tcy_left_right)] { + if changed(key) && !(-shift_max..=shift_max).contains(&value) { + return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max))); + } + } // A language of the list, stored as its tag (as text.setFormat takes it). if let Some(l) = &st.language && kept.and_then(|k| k.get("language")) != m.get("language") diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 19da4c8ab0..7c0fd99638 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -1,5 +1,42 @@ use super::*; +#[test] +fn captured_character_style_excludes_a_one_character_glyph_choice() { + let style = CharStyle { + glyph_alternate: Some(vectorcraft_doc::GlyphChoice { ch: 'a', gid: 42, font: "Test-Regular".into(), version: "1".into() }), + ..Default::default() + }; + assert!(!char_attrs(&style).contains_key("glyphAlternate")); + assert!(style.glyph_alternate.is_some(), "the selected text keeps its direct glyph choice"); +} + +#[test] +fn character_style_edit_keeps_a_linked_runs_glyph_choice() { + let (mut s, id) = session_with_text("Styled"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + let choice = vectorcraft_doc::GlyphChoice { ch: 'S', gid: 42, font: "Test-Regular".into(), version: "1".into() }; + if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(NodeId(id)).map(|n| &mut n.kind) { + t.runs[0].style.glyph_alternate = Some(choice.clone()); + } + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"size": 18}})).unwrap(); + let run = &runs(&s, id)[0]; + assert_eq!((run.style.style_name.as_deref(), run.style.size), (Some("Body"), 18.0)); + assert_eq!(run.style.glyph_alternate, Some(choice), "the style edit keeps the run's own glyph choice"); +} + +/// A glyph choice given to a character style is an error, not a value the style drops. +#[test] +fn character_style_attributes_refuse_a_glyph_choice() { + let (mut s, _) = session_with_text("Styled"); + let choice = json!({"ch": "S", "gid": 42, "font": "Test-Regular", "version": "1"}); + let err = s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24, "glyphAlternate": choice}})).unwrap_err(); + assert!(err.to_string().contains("glyphAlternate"), "{err}"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24}})).unwrap(); + let err = s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"glyphAlternate": choice}})).unwrap_err(); + assert!(err.to_string().contains("glyphAlternate"), "{err}"); +} + fn session_with_text(text: &str) -> (Session, u64) { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); @@ -335,6 +372,54 @@ fn character_style_color_and_features_are_checked() { assert_eq!(s.doc().unwrap().history.undo.len(), undo); } +#[test] +fn character_style_dimensions_are_checked_before_a_definition_changes() { + let (mut s, _) = session_with_text("Text"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for attrs in [ + json!({"size": 0.0}), + json!({"size": 1296.1}), + json!({"leading": 0.0}), + json!({"leading": 5000.1}), + json!({"h_scale": 0.0}), + json!({"h_scale": 0.9}), + json!({"h_scale": 10000.1}), + json!({"v_scale": 0.0}), + json!({"v_scale": 0.9}), + json!({"v_scale": 10000.1}), + json!({"baseline_shift": -1296.1}), + json!({"baseline_shift": 1296.1}), + json!({"tcyUpDown": 1296.1}), + json!({"tcyLeftRight": -1296.1}), + ] { + let key = attrs.as_object().unwrap().keys().next().unwrap(); + for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] { + let params = match cmd { + "charStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": attrs}), + "charStyle.new" => json!({"name": "Other", "attrs": attrs}), + _ => json!({"name": "Body", "attrs": attrs}), + }; + let error = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(error.contains(&format!("`{key}`")), "{cmd} {attrs}: {error}"); + } + } + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + + s.execute( + "charStyle.setAttrs", + &json!({"name": "Body", "attrs": { + "size": 1296.0, "leading": 5000.0, + "h_scale": 1.0, "v_scale": 10000.0, + "baseline_shift": -1296.0, + "tcyUpDown": 1296.0, "tcyLeftRight": -1296.0 + }}), + ) + .unwrap(); +} + #[test] fn text_style_rejects_doubly_signed_feature_tags() { let (mut s, id) = session_with_text("Text"); @@ -776,7 +861,8 @@ fn para_style_redefined_to_the_defaults_updates_its_paragraphs() { } /// The same for character styles: Auto kerning and the Roman baseline alignment, which the -/// run's JSON leaves out, are captured and reach the style's users. +/// run's JSON leaves out, are captured and reach the style's users. A glyph choice belongs to +/// one character, so it is not a reusable style attribute. #[test] fn char_style_redefined_to_the_defaults_updates_its_text() { use vectorcraft_doc::CharAlign; @@ -794,9 +880,11 @@ fn char_style_redefined_to_the_defaults_updates_its_text() { s.execute("text.setFormat", &json!({"ids": [source], "kerning": "auto", "charAlign": "romanBaseline"})).unwrap(); s.execute("charStyle.redefine", &json!({"name": "Body", "id": source})).unwrap(); assert_eq!((kerning(&s), aligns(&s)), ([None, None, Some(60.0)], [CharAlign::RomanBaseline; 3])); - assert_eq!(defined(&s, 0), settable::(), "Redefine captures every attribute"); + let mut reusable = settable::(); + reusable.remove("glyphAlternate"); + assert_eq!(defined(&s, 0), reusable, "Redefine captures every reusable attribute"); s.execute("charStyle.new", &json!({"name": "Copy", "id": local})).unwrap(); - assert_eq!(defined(&s, 1), settable::(), "New captures every attribute"); + assert_eq!(defined(&s, 1), reusable, "New captures every reusable attribute"); s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"kerning": 10, "charAlign": "emBoxTop"}})).unwrap(); assert_eq!((kerning(&s), aligns(&s)), ([Some(10.0), Some(10.0), Some(60.0)], [CharAlign::EmBoxTop; 3])); s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"charAlign": "romanBaseline"}})).unwrap(); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index d4a58c34d3..519d282e84 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -87,7 +87,7 @@ pub fn specs() -> Vec { "Area Type Options…", ["Type"], None, - "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", + "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", has_selection, area_options ), @@ -123,7 +123,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), @@ -874,16 +874,16 @@ fn set_style(s: &mut Session, p: &Value) -> Result { st.features = super::textedit::change_features(&st.features, c); } }); - if let Some(before) = before { - super::textedit::protect_missing_glyphs(&before, &mut t.runs); - } + let kept = before.map(|before| super::textedit::protect_missing_glyphs(&before, &mut t.runs)).unwrap_or_default(); if font.is_some() || style.is_some() { - // All the text: every run, the one run of empty text included. + // All the text: every run, the one run of empty text included. Characters that kept their font aren't the + // command's. let styled = match range { - None => t.runs.clone(), + None if kept.is_empty() => t.runs.clone(), + None => super::textedit::unprotected_runs(&t.runs, 0, vectorcraft_text::edit::runs_len(&t.runs), &kept), Some(r) => { let (a, b) = r.bytes(t); - vectorcraft_text::edit::slice_runs(&t.runs, a, b) + super::textedit::unprotected_runs(&t.runs, a, b, &kept) } }; set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style))); @@ -1080,46 +1080,74 @@ fn area_options(s: &mut Session, p: &Value) -> Result { let t = area_text(s.doc()?.doc.node(first)).ok_or_else(|| bad(C, "select area type (text in a frame)"))?; area_options_json(t) }; + // Checked once up front (its errors don't depend on the frame); each frame resolves `fit` + // against its own setting below. let cur = area_text(s.doc()?.doc.node(first)).map(|t| t.area.clone()).unwrap_or_default(); - let fit = fit_param(p, cur.fit, C)?; - let mut v = serde_json::to_value(&cur).map_err(|e| EngineError::Other(e.to_string()))?; + fit_param(p, cur.fit, C)?; + let fit_given = p.get("fit").is_some_and(|v| !v.is_null()) || p.get("fitMinPercent").is_some_and(|v| !v.is_null()); let size = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).map(|x| x.clamp(1.0, 100_000.0)); - let (w, mut h) = (size("width"), size("height")); - let mut changed = w.is_some() || h.is_some() || fit.is_some(); - if let (Some(o), Some(src)) = (v.as_object_mut(), p.as_object()) { - for (k, val) in src.iter().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())) { - o.insert(k.clone(), val.clone()); - changed = true; - } - } - if !changed { + let (w, h) = (size("width"), size("height")); + let given: Vec<(&String, &Value)> = p.as_object().into_iter().flatten().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())).collect(); + if w.is_none() && h.is_none() && !fit_given && given.is_empty() { return options(s); } - let mut opts: vectorcraft_doc::AreaOptions = serde_json::from_value(v).map_err(|e| bad(C, e.to_string()))?; - opts.rows = opts.rows.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS); - opts.columns = opts.columns.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS); - let finite = |x: f64| if x.is_finite() { x } else { 0.0 }; - opts.gutter = finite(opts.gutter).clamp(0.0, 10_000.0); - // A gutter given alone is the rows' and the columns'. - if p.get("gutter").is_some() && p.get("rowGutter").is_none() { - opts.row_gutter = None; - } - opts.row_gutter = opts.row_gutter.map(|g| finite(g).clamp(0.0, 10_000.0)).filter(|g| *g != opts.gutter); - opts.inset = finite(opts.inset).clamp(0.0, 10_000.0); - opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0); - opts.fit = fit.unwrap_or(cur.fit); - if opts.fit == AreaFit::AutoHeight { + // Each area type takes the options given over its own (#3759): setting one option on several + // frames leaves their other options as they were. + let merged = |own: &vectorcraft_doc::AreaOptions| -> Result { + let mut v = serde_json::to_value(own).map_err(|e| EngineError::Other(e.to_string()))?; + if let Some(o) = v.as_object_mut() { + for (k, val) in &given { + o.insert((*k).clone(), (*val).clone()); + } + } + let mut opts: vectorcraft_doc::AreaOptions = serde_json::from_value(v).map_err(|e| bad(C, e.to_string()))?; + opts.rows = opts.rows.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS); + opts.columns = opts.columns.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS); + let finite = |x: f64| if x.is_finite() { x } else { 0.0 }; + opts.gutter = finite(opts.gutter).clamp(0.0, 10_000.0); + // A gutter given alone is the rows' and the columns'. + if p.get("gutter").is_some() && p.get("rowGutter").is_none() { + opts.row_gutter = None; + } + opts.row_gutter = opts.row_gutter.map(|g| finite(g).clamp(0.0, 10_000.0)).filter(|g| *g != opts.gutter); + opts.inset = finite(opts.inset).clamp(0.0, 10_000.0); + opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0); + // Each frame's fit from its own (`fitMinPercent` alone changes only Shrink Text frames). + opts.fit = fit_param(p, own.fit, C)?.unwrap_or(own.fit); + Ok(opts) + }; + let d = &s.doc()?.doc; + let planned: Vec<(NodeId, vectorcraft_doc::AreaOptions)> = ids + .iter() + .filter_map(|id| area_text(d.node(*id)).map(|t| (*id, &t.area))) + .map(|(id, own)| merged(own).map(|o| (id, o))) + .collect::>()?; + let apply = |t: &mut TextObject, opts: &vectorcraft_doc::AreaOptions| { + t.area = opts.clone(); // Auto Size sets the height (Illustrator's dialog turns the Height field off). - h = None; + let h = if opts.fit == AreaFit::AutoHeight { None } else { h }; + // A resized frame has laid its text out again; otherwise the new options do here. + if !size_area(t, w, h) { + refresh_bounds(t); + } + }; + // Options that change nothing (the vertical alignment already set, `fitMinPercent` on frames + // without Shrink Text) add no undo step and keep redo, frame sizes and Auto Size included. + let unchanged = planned.iter().all(|(id, opts)| match d.node(*id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => { + let mut after = t.clone(); + apply(&mut after, opts); + after == *t + } + _ => true, + }); + if unchanged { + return options(s); } s.edit("Area Type Options", |d, _| { - for id in &ids { + for (id, opts) in &planned { if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { - t.area = opts.clone(); - // A resized frame has laid its text out again; otherwise the new options do here. - if !size_area(t, w, h) { - refresh_bounds(t); - } + apply(t, opts); } } Ok(()) diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 20945f7702..4748dcc8d9 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -1762,3 +1762,46 @@ fn area_options_set_a_gutter_between_rows_of_its_own() { s.execute("text.areaOptions", &json!({"rowGutter": null})).unwrap(); assert_eq!(area(&s).row_gutter, None); } + +/// #3759: an option given for several area types goes onto each one's own options: the others +/// stay as each had them, not copied from the first. +#[test] +fn area_options_for_several_frames_change_only_what_is_given() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let make = |s: &mut Session, x: f64| { + s.execute("text.create", &json!({"x": x, "y": 10, "text": "A", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (make(&mut s, 10.0), make(&mut s, 200.0)); + s.execute("text.areaOptions", &json!({"ids": [a], "columns": 3, "gutter": 6})).unwrap(); + s.execute("text.areaOptions", &json!({"ids": [b], "inset": 4})).unwrap(); + s.execute("text.areaOptions", &json!({"ids": [a, b], "verticalAlign": "bottom"})).unwrap(); + let area = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.area.clone(), + k => panic!("{k:?}"), + }; + let (oa, ob) = (area(&s, a), area(&s, b)); + assert_eq!((oa.vertical_align, ob.vertical_align), (vectorcraft_doc::VerticalAlign::Bottom, vectorcraft_doc::VerticalAlign::Bottom)); + assert_eq!((oa.columns, oa.gutter, oa.inset), (3, 6.0, 0.0)); + assert_eq!((ob.columns, ob.inset), (1, 4.0), "b keeps its own options"); +} + +/// `fitMinPercent` alone changes only the frames that shrink text to fit, each from its own +/// setting (#3759). +#[test] +fn fit_min_percent_for_several_frames_keeps_each_frames_fit() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let make = |s: &mut Session, x: f64| { + s.execute("text.create", &json!({"x": x, "y": 10, "text": "A", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap() + }; + let (plain, shrink) = (make(&mut s, 10.0), make(&mut s, 200.0)); + s.execute("text.areaOptions", &json!({"ids": [shrink], "fit": "shrinkText"})).unwrap(); + s.execute("text.areaOptions", &json!({"ids": [plain, shrink], "fitMinPercent": 30})).unwrap(); + let fit = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.area.fit, + k => panic!("{k:?}"), + }; + assert_eq!(fit(&s, plain), vectorcraft_doc::AreaFit::None, "the plain frame doesn't start shrinking"); + assert_eq!(fit(&s, shrink), vectorcraft_doc::AreaFit::ShrinkText { min_percent: 30.0 }); +} diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index af0f313ea1..9e641a6e6a 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Save for Web", [], None, - "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity} (colours as the preview's colors[].source), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", + "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", has_doc, export ), @@ -329,6 +329,7 @@ impl ColorTable { list.iter() .map(|h| { vectorcraft_color::Color::from_hex(h) + .filter(|_| !super::hex_with_alpha(h)) .map(|c| { let [r, g, b, _] = c.to_rgba8(1.0); [r, g, b] diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index 9e4969e27a..bac865c71b 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Sample Color", [], None, - "{color, stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", + "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", has_doc, sample_color ), diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 5ed2abe1ce..34592575c3 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -318,6 +318,16 @@ impl DocState { _ => it.selection, }; self.push_undo(it.label, it.doc, selection); + if let Some(paints) = it.color_mode_paints + && let Some(e) = self.history.undo.last_mut() + { + match &mut e.color_mode_paints { + Some((_, after)) => *after = paints.1, + slot => *slot = Some(paints), + } + e.recost_paints(); + self.history.trim(); + } self.revision += 1; } } diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index ec53acd5ba..cb84e108ed 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -9,8 +9,8 @@ pub struct HistoryEntry { pub doc: Arc, /// The selection as it was, shared with the neighbouring steps that have the same one. pub selection: Arc, - /// Roughly the memory this step keeps of its own: what of `doc` the step after it (or the - /// document now) doesn't share ([`Document::retained_bytes`]). + /// Roughly the memory this step keeps of its own: the unshared document data + /// ([`Document::retained_bytes`]) plus owned color-mode paint snapshots. pub bytes: usize, /// The same the other way round: what that next state keeps that `doc` doesn't share. Undoing /// (redoing) this step makes a step that keeps the next state: this is its `bytes`. @@ -19,6 +19,10 @@ pub struct HistoryEntry { next: usize, /// The template and name `label` was made from ([`Session::edit_named`]). pub(crate) named: Option, + /// Original and converted new-art colors, only for steps that change document color mode. + pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, + /// Owned new-art snapshots included in both directional estimates. + color_mode_bytes: usize, } /// A step name made by filling the `{name}` placeholder of a template with a name @@ -45,7 +49,17 @@ impl HistoryEntry { pub(crate) fn kept(label: String, doc: Arc, selection: Arc, next: &Document) -> Self { doc.drop_lookup_cache(); let (bytes, next_bytes) = doc.retained_bytes_each(next); - HistoryEntry { label, doc, selection, bytes, next_bytes, next: std::ptr::from_ref(next) as usize, named: None } + HistoryEntry { + label, + doc, + selection, + bytes, + next_bytes, + next: std::ptr::from_ref(next) as usize, + named: None, + color_mode_paints: None, + color_mode_bytes: 0, + } } /// The template and name the step's label was made from, while the label is still the one @@ -66,12 +80,42 @@ impl HistoryEntry { return Self::kept(label, doc, selection, now); } doc.drop_lookup_cache(); - HistoryEntry { label, doc, selection, bytes: costs.next_bytes, next_bytes: costs.bytes, next: Arc::as_ptr(now) as usize, named: None } + HistoryEntry { + label, + doc, + selection, + bytes: costs.next_bytes, + next_bytes: costs.bytes, + next: Arc::as_ptr(now) as usize, + named: None, + color_mode_paints: None, + color_mode_bytes: 0, + } } - /// The figures [`HistoryEntry::turned`] reuses. + /// Recount the separately owned paints after a color-mode step or group changes them. + pub(crate) fn recost_paints(&mut self) { + let owned = |p: &vectorcraft_tools::PaintDefaults| { + std::mem::size_of::() + + vectorcraft_doc::paint_heap_bytes(&p.fill) + + vectorcraft_doc::paint_heap_bytes(&p.stroke) + + p.appearance.as_ref().map_or(0, vectorcraft_doc::appearance_heap_bytes) + + p.style.as_ref().map_or(0, String::capacity) + }; + let bytes = self.color_mode_paints.as_ref().map_or(0, |(before, after)| owned(before).saturating_add(owned(after))); + self.bytes = self.bytes.saturating_sub(self.color_mode_bytes).saturating_add(bytes); + self.next_bytes = self.next_bytes.saturating_sub(self.color_mode_bytes).saturating_add(bytes); + self.color_mode_bytes = bytes; + } + + /// The document-only figures [`HistoryEntry::turned`] reuses. Its paint snapshots are + /// attached and counted separately, so swapping direction never doubles their cost. pub(crate) fn costs(&self) -> StepCosts { - StepCosts { bytes: self.bytes, next_bytes: self.next_bytes, next: self.next } + StepCosts { + bytes: self.bytes.saturating_sub(self.color_mode_bytes), + next_bytes: self.next_bytes.saturating_sub(self.color_mode_bytes), + next: self.next, + } } } @@ -140,7 +184,9 @@ impl History { /// merged into it, or an undo group extended it). pub(crate) fn recost_last(&mut self, now: &Document) { if let Some(e) = self.undo.last_mut() { - (e.bytes, e.next_bytes) = e.doc.retained_bytes_each(now); + let (before, after) = e.doc.retained_bytes_each(now); + e.bytes = before.saturating_add(e.color_mode_bytes); + e.next_bytes = after.saturating_add(e.color_mode_bytes); e.next = std::ptr::from_ref(now) as usize; } } diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index b1d11a4793..1de58228a2 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -8,6 +8,13 @@ pub struct Interaction { /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, pub preview: Option<(String, Value)>, + /// A replaced or canceled preview restores these new-art paints from before the interaction. + pub(crate) paint: vectorcraft_tools::PaintDefaults, + /// An accepted batch preview uses these final paints after changing the document color mode. + pub(crate) preview_paint: Option, + /// Conversion of new-art paints waits until a color-mode preview is accepted. + pub(crate) deferred_color_mode: Option, + pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, /// Per-document state restored on cancel (current layer, highlighted Layers panel rows, /// isolation). pub active_layer: Option, @@ -53,6 +60,8 @@ pub(crate) struct PreviewCopies { /// An open undo group ([`Session::begin_undo_group`]): the edits made in it are one undo step. #[derive(Clone, Debug)] pub struct UndoGroup { + /// The new-art paints from before the group's first command. + pub(crate) paint: vectorcraft_tools::PaintDefaults, /// The document before the group's first edit, as the undo step that edit recorded keeps it. pub(crate) first: Option>, /// The numbers of the journal entries made in the group's document while it was open: a canceled @@ -83,4 +92,8 @@ pub struct UndoScope { /// that the group's undo step keeps, as they were when the scope began; `None` when the scope /// opened the group. pub(crate) joined: Option<(Arc, Selection, Option>)>, + /// The new-art colors and the group's color-mode history metadata at the scope's start. + /// Only used when cancelling a joined scope that converted those colors. + pub(crate) paint: vectorcraft_tools::PaintDefaults, + pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 14db3a2cdb..7a77a1920b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -157,6 +157,10 @@ pub struct Session { /// groups: for each step, the documents ([`DocState::uid`]) whose undo groups it belongs to, and /// the index of the document it left active when it changed the active document. pub(crate) batch_steps: Option, Option)>>, + /// After `command.batch` kept a color-mode step's new-art colors, until the top-level command + /// has inherited the selection's appearance: the documents ([`DocState::uid`]) whose newest + /// history step takes the colors the batch finally left. + pub(crate) batch_paint_docs: Vec, /// While [`Session::place_read`] runs `file.place`: the file read for it, which the command /// places instead of reading the file; `None` otherwise. pub(crate) place_hand_off: Option, diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rs index 51ffbd0986..44b1bd86a9 100644 --- a/crates/engine/src/link_watch.rs +++ b/crates/engine/src/link_watch.rs @@ -17,7 +17,8 @@ //! update, or answering No, leaves the link modified until the file changes again. use std::collections::{BTreeSet, HashMap, HashSet}; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; use serde_json::{Value, json}; @@ -27,8 +28,21 @@ use crate::{Result, Session}; pub type Stamp = (u64, u128); /// Stamps of a document's linked files taken on a worker thread: (document uid, [(file, -/// object ids, stamp)]). -pub type LinkScan = Arc, Option)>)>>>; +/// object ids, stamp)]), the condition the worker signals when it ends, and whether it has. +pub type LinkScan = Arc<(Mutex, Option)>)>>, Condvar, AtomicBool)>; + +/// Held by a look's worker: marks the look as ended and wakes [`Session::wait_link_scan`] when +/// dropped, whether the worker returned or unwound. +struct Ended(LinkScan); + +impl Drop for Ended { + fn drop(&mut self) { + let (done, finished, ended) = &*self.0; + let _held = done.lock().unwrap_or_else(PoisonError::into_inner); + ended.store(true, Ordering::SeqCst); + finished.notify_all(); + } +} /// The stamp of the linked file stored as `path` in the document saved at `doc_path`; `None` when /// there is no file, its path isn't followed ([`crate::cmd::fileio::document_path`]) or @@ -79,12 +93,14 @@ impl Session { let out = slot.clone(); let scope = crate::file_access::ScopeHandle::capture(); let spawned = std::thread::Builder::new().name("link-watch".into()).spawn(move || { + // Marks the look as ended when the worker returns or unwinds. + let _ended = Ended(out.clone()); let stamps = scope.run(|| { crate::file_access::confine(crate::file_access::current().or(opened_by).as_ref(), || { files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect() }) }); - *out.lock().unwrap_or_else(PoisonError::into_inner) = Some((uid, stamps)); + *out.0.lock().unwrap_or_else(PoisonError::into_inner) = Some((uid, stamps)); }); if spawned.is_ok() { self.link_scan = Some(slot); @@ -94,11 +110,21 @@ impl Session { /// Apply a finished look (`None` while there is none, or it is still running): see /// [`Session::apply_link_stamps`]. pub fn poll_link_scan(&mut self) -> Option> { - let (uid, stamps) = self.link_scan.as_ref()?.lock().unwrap_or_else(PoisonError::into_inner).take()?; + let (uid, stamps) = self.link_scan.as_ref()?.0.lock().unwrap_or_else(PoisonError::into_inner).take()?; self.link_scan = None; Some(self.apply_link_stamps(uid, stamps, false)) } + /// Block until the look in flight has ended (at once when none is running), so that the next + /// [`Session::poll_link_scan`] applies its stamps. A look whose worker stopped without stamps + /// ends too, and the poll then returns `None`. For tests that drive the look step by step. + pub fn wait_link_scan(&self) { + let Some(scan) = &self.link_scan else { return }; + let (done, finished, ended) = &**scan; + let guard = done.lock().unwrap_or_else(PoisonError::into_inner); + drop(finished.wait_while(guard, |stamps| stamps.is_none() && !ended.load(Ordering::SeqCst)).unwrap_or_else(PoisonError::into_inner)); + } + /// Compare the stamps of document `uid`'s linked files with the ones last seen and act on /// the changed ones as Update Links says (`update`: read them again regardless). Returns /// `{updated: [ids], ask: [ids], modified: [ids]}`: read again, to offer (Ask When Modified), diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 6e462e029c..6b048e6fa3 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -77,6 +77,7 @@ impl Session { explicit_undo_group: None, batch_stash: None, batch_steps: None, + batch_paint_docs: Vec::new(), place_hand_off: None, queue_hand_off: None, place_queue_roots: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 71f70d25a0..da285eb3d3 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -225,6 +225,7 @@ impl Session { cmd::settle_interaction(self)?; } self.clear_deferred_overlay_cache(); + let paint = self.paint.clone(); let st = self.doc_mut()?; if st.interaction.is_some() { return Ok(()); @@ -234,6 +235,10 @@ impl Session { doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), preview: None, + paint, + preview_paint: None, + color_mode_paints: None, + deferred_color_mode: None, active_layer: st.active_layer, layer_rows: st.layer_rows.clone(), variables_highlight: st.variables_highlight.clone(), @@ -246,10 +251,10 @@ impl Session { /// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview). pub fn preview(&mut self, cmd: &str, params: &Value) -> Result { - { + let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; - let Some(it) = &st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; + let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; // Undoing the previous preview counts as a change, so views redraw even when the command // below returns without an edit. let selection_changed = st.selection != *it.selection; @@ -257,6 +262,11 @@ impl Session { st.revision += 1; } st.doc = it.doc.clone(); + let restore_paint = cmd == "command.batch" || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch"); + let paint = it.paint.clone(); + it.preview_paint = None; + it.color_mode_paints = None; + it.deferred_color_mode = None; if selection_changed { st.selection.clone_from(&it.selection); } @@ -264,30 +274,54 @@ impl Session { // even when the preview fails. deselect_hidden(&menu, &st.doc, &mut st.selection); cmd::globaledit::follow_history(st); + (paint, restore_paint) + }; + if restore_paint { + self.paint = paint.clone(); } - // The previous preview's paint is undone with it. self.pending_paint = None; let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params)); let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p)); + // A selected object's converted appearance must not replace the current paints while + // this tentative color-mode preview is still cancellable. + let color_mode_paint = matches!(cmd, "file.documentColorMode" | "object.convertDocumentColorMode").then(|| self.paint.clone()); let outer = std::mem::replace(&mut self.previewing, true); let r = self.execute(cmd, params); self.previewing = outer; + if let Some(paint) = color_mode_paint { + self.paint = paint; + } let params = self.noted(params); + let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone()); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { // A failed preview leaves the document at the snapshot, so nothing is left to commit // (not even an earlier successful preview, which the reset above already undid). it.preview = r.is_ok().then(|| (cmd.to_string(), params)); + if it.color_mode_paints.is_some() { + it.preview_paint = batch_paint.clone(); + } + } + if batch_paint.is_some() && self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.preview_paint.is_some()) { + self.paint = paint; } r } pub fn commit_interaction(&mut self) -> Result<()> { self.clear_deferred_overlay_cache(); + if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) { + self.paint = paint; + } self.remember_pending_paint(); + cmd::colormgmt::commit_new_art_colors(self)?; + let paint = self.paint.clone(); let st = self.doc_mut()?; let Some(mut it) = st.interaction.take() else { return Ok(()) }; let Some(preview) = it.preview.take() else { return Ok(()) }; + if let Some((_, after)) = &mut it.color_mode_paints { + after.clone_from(&paint); + } let perspective_again = it.perspective_again.take(); let copy = preview.0 == "object.transform" && preview.1.get("copy").and_then(Value::as_bool).unwrap_or(false); // Alt pressed or released during a move drag turns it into a copy or back: name it for @@ -353,6 +387,14 @@ impl Session { pub fn cancel_interaction(&mut self) -> Result<()> { self.clear_deferred_overlay_cache(); self.pending_paint = None; + if let Some(paint) = self + .active() + .and_then(|st| st.interaction.as_ref()) + .filter(|it| it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch")) + .map(|it| it.paint.clone()) + { + self.paint = paint; + } let menu = self.menu.clone(); let st = self.doc_mut()?; st.undo_interaction(); diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index f4ebd87c42..f993ac5857 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -107,9 +107,31 @@ impl Session { let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs()); let open = (self.depth == 0).then(|| self.docs.iter().map(|d| d.uid).collect::>()); let r = if self.depth == 0 { self.run_guarded(id, run) } else { self.run_nested(run) }; + if r.is_err() && self.depth == 0 { + self.batch_paint_docs.clear(); + } let r = r?; if self.depth == 0 { - self.inherit_new_art(); + // A color-mode history step restores exact new-art colors; selection inheritance + // must not immediately replace that restoration. + let restored = self.active().is_some_and(|d| match id { + "edit.undo" => d.history.redo.last().is_some_and(|e| e.color_mode_paints.is_some()), + "edit.redo" => d.history.undo.last().is_some_and(|e| e.color_mode_paints.is_some()), + _ => false, + }); + if !restored { + self.inherit_new_art(); + } + for uid in std::mem::take(&mut self.batch_paint_docs) { + if let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) + && let Some(e) = st.history.undo.last_mut() + && let Some((_, after)) = &mut e.color_mode_paints + { + after.clone_from(&self.paint); + e.recost_paints(); + st.history.trim(); + } + } } if let Some(open) = open { self.open_undo_groups_in_new_documents(&open); diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index c5f3f1595e..831f550bed 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -13,10 +13,11 @@ impl Session { /// [`Session::begin_undo_group`] with the undo step named `label` (else after its first edit). pub fn begin_named_undo_group(&mut self, label: Option) { + let paint = self.paint.clone(); if let Some(st) = self.active_mut() && st.undo_group.is_none() { - st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label }); + st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint }); } } @@ -27,9 +28,10 @@ impl Session { /// entry that made the document stays. pub(super) fn open_undo_groups_in_new_documents(&mut self, open: &[u64]) { let Some(label) = &self.explicit_undo_group else { return }; + let paint = self.paint.clone(); for st in &mut self.docs { if !open.contains(&st.uid) && st.undo_group.is_none() { - st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone() }); + st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone() }); } } } @@ -91,12 +93,26 @@ impl Session { continue; } let Some(g) = st.undo_group.take() else { continue }; + // Redo of a group that changed document color mode restores the new-art colors the + // whole group left, not the ones right after the conversion. + if !cancel + && let Some(first) = &g.first + && let Some(e) = st.history.undo.last_mut().filter(|e| Arc::ptr_eq(&e.doc, first)) + && let Some((_, after)) = &mut e.color_mode_paints + { + after.clone_from(&self.paint); + e.recost_paints(); + st.history.trim(); + } // Only while the group's step is still the newest one. if cancel && let Some(first) = g.first && st.history.undo.last().is_some_and(|e| Arc::ptr_eq(&e.doc, &first)) && let Some(e) = st.history.undo.pop() { + if let Some((before, _)) = e.color_mode_paints { + self.paint = before; + } st.doc = e.doc; st.selection = Arc::unwrap_or_clone(e.selection); deselect_hidden(&self.menu, &st.doc, &mut st.selection); @@ -194,11 +210,17 @@ impl Session { let journal = self.journal.len(); let st = self.active()?; let uid = st.uid; + let color_mode_paints = st + .undo_group + .as_ref() + .and_then(|g| g.first.as_ref()) + .and_then(|first| st.history.undo.last().filter(|e| Arc::ptr_eq(&e.doc, first)).and_then(|e| e.color_mode_paints.clone())); + let paint = self.paint.clone(); let joined = st.undo_group.as_ref().map(|g| (st.doc.clone(), st.selection.clone(), g.first.clone())); if joined.is_none() { self.begin_undo_group(); } - Some(UndoScope { uid, journal, joined }) + Some(UndoScope { uid, journal, joined, paint, color_mode_paints }) } /// End `scope` in its own document, whichever document is active now; undo groups open in other @@ -219,13 +241,19 @@ impl Session { if !cancel || !newest { return; } + let colors_changed = st.history.undo.last().and_then(|e| e.color_mode_paints.as_ref()) != scope.color_mode_paints.as_ref(); match &first { // The scope's first edit recorded the group's step. None => { st.history.undo.pop(); g.first = None; } - Some(f) if g.first.as_ref().is_some_and(|now| Arc::ptr_eq(now, f)) => {} + Some(f) if g.first.as_ref().is_some_and(|now| Arc::ptr_eq(now, f)) => { + if let Some(e) = st.history.undo.last_mut() { + e.color_mode_paints = scope.color_mode_paints; + e.recost_paints(); + } + } Some(_) => return, } st.doc = doc; @@ -235,6 +263,9 @@ impl Session { deselect_hidden(&menu, &st.doc, &mut st.selection); st.history.recost_last(&st.doc); st.revision += 1; + if colors_changed { + self.paint = scope.paint; + } self.journal.truncate(scope.journal); // The next commands take the cut entries' numbers, so no open undo group keeps them. for g in self.docs.iter_mut().filter_map(|st| st.undo_group.as_mut()) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3f6a653c99..a1fa3e0487 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -67,6 +67,7 @@ mod gradient; mod gradpanel; mod gradpresets; mod gradspan; +mod guide_clipboard; mod halftone; mod history_mem; mod ids_without_selection; diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index a49bae19a3..9bed4eb343 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; -use vectorcraft_doc::{AppearanceItem, Node}; +use vectorcraft_doc::{AppearanceItem, FillLayer, Node}; use crate::*; @@ -288,8 +288,8 @@ fn add_fill_and_stroke_copy_the_top_ones() { assert_eq!(node(&s, id).appearance.items.len(), 3); } -/// With a fill row active, Add New Fill puts a copy of that row right above it and makes the copy -/// the active row; the rows above it stay where they are. +/// With a fill row active, Add New Fill puts a fill with that row's paint right above it and makes +/// the new fill the active row; the rows above it stay where they are. #[test] fn add_fill_copies_the_active_fill_row_right_above_it() { let mut s = session(); @@ -323,8 +323,60 @@ fn add_fill_copies_the_active_fill_row_right_above_it() { assert_eq!(s.appearance_item(), Some(0)); } +/// With a fill row active, Add New Fill given `id` alone also puts a copy of the top fill on top, +/// and the active row stays. +#[test] +fn add_fill_with_id_leaves_the_active_fill_row_alone() { + let mut s = session(); + let id = rect(&mut s, 100.0); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setItem", json!({"index": 2, "color": "#0000ff"})); // [red, Stroke, blue] + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "appearance.addFill", json!({"id": id.0})); + let n = node(&s, id); + assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::>(), ["fill", "stroke", "fill", "fill"]); + assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000"); + assert_eq!(fill_paint(&n, 3).color().unwrap().to_hex(), "#0000ff"); + assert_eq!(s.appearance_item(), Some(0)); +} + +/// Add New Stroke copies the top stroke's weight but makes the new stroke at least 1 pt. +#[test] +fn add_stroke_is_at_least_one_point() { + let mut s = session(); + let id = rect(&mut s, 100.0); + run(&mut s, "stroke.set", json!({"weight": 0.5})); + run(&mut s, "appearance.addStroke", json!({})); // [Fill, Stroke, Stroke] + let n = node(&s, id); + assert_eq!(stroke(&n, 1).width, 0.5); + assert_eq!(stroke(&n, 2).width, 1.0); +} + +/// The new fill above the active fill row takes only the row's paint: the row's opacity, blend +/// mode, visibility, overprint and effects are not copied (Duplicate Item copies those). +#[test] +fn add_fill_takes_only_the_active_fill_rows_paint() { + let mut s = session(); + let id = rect(&mut s, 100.0); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "appearance.setItem", json!({"index": 0, "opacity": 40, "blend": "multiply", "visible": false})); + run(&mut s, "effect.apply", json!({"effect": "distort.roughen", "item": 0})); + run(&mut s, "object.setOverprint", json!({"fill": true, "item": 0})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "appearance.addFill", json!({})); + let n = node(&s, id); + assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::>(), ["fill", "fill", "stroke"]); + let (AppearanceItem::Fill(row), AppearanceItem::Fill(copy)) = (&n.appearance.items[0], &n.appearance.items[1]) else { + panic!("the first two rows are not fills") + }; + assert_eq!((row.opacity, row.blend, row.visible, row.overprint), (0.4, BlendMode::Multiply, false, true)); + assert_eq!(row.effects.len(), 1); + assert_eq!(copy, &FillLayer::new(row.paint.clone())); +} + /// In a mixed selection the active fill row goes above itself in the first object; an object that -/// doesn't share that row gets a copy of its top fill on top, as without an active row. +/// doesn't share that row gets a fill with its top fill's paint on top, as without an active row. #[test] fn add_fill_above_an_unshared_active_row_tops_the_other_objects() { let mut s = session(); @@ -463,6 +515,45 @@ fn reduce_to_basic_keeps_the_active_row_of_the_first_selected_object() { assert_eq!(fill_paint(&node(&s, a), 0).color().unwrap().to_hex(), "#0000ff"); } +/// Three objects with equal stacks, the third's lower fill changed; the lower, green fill row of +/// the first is active, selected a, b, c. +fn three_with_one_changed(s: &mut Session) -> [NodeId; 3] { + let ids = [rect(s, 50.0), rect(s, 200.0), rect(s, 300.0)]; + run(s, "select.set", json!({"ids": ids.map(|id| id.0)})); + run(s, "appearance.addFill", json!({})); + run(s, "appearance.setItem", json!({"index": 0, "color": "#00ff00"})); + run(s, "appearance.setItem", json!({"index": 2, "color": "#ff0000"})); // [Fill green, Stroke, Fill red] + run(s, "appearance.setItem", json!({"index": 0, "color": "#0000ff", "ids": [ids[2].0]})); + run(s, "appearance.setActiveItem", json!({"index": 0})); + ids +} + +/// The active row is matched in each other object on its own: one object without an equal row +/// does not stop another that has one from keeping it. +#[test] +fn reduce_to_basic_keeps_the_active_row_in_each_object_that_has_it() { + let mut s = session(); + let [a, b, c] = three_with_one_changed(&mut s); + run(&mut s, "appearance.reduceToBasic", json!({})); + assert_eq!(fill_paint(&node(&s, a), 0).color().unwrap().to_hex(), "#00ff00"); + assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#00ff00"); + assert_eq!(fill_paint(&node(&s, c), 0).color().unwrap().to_hex(), "#ff0000"); +} + +/// Add New Fill puts its copy of the active row right above that row in each object that has an +/// equal row, even when another selected object has none. +#[test] +fn add_fill_copies_the_active_row_in_each_object_that_has_it() { + let mut s = session(); + let [a, b, _] = three_with_one_changed(&mut s); + run(&mut s, "appearance.addFill", json!({})); + for id in [a, b] { + let n = node(&s, id); + assert_eq!(fill_paint(&n, 1).color().unwrap().to_hex(), "#00ff00", "{:?}", n.appearance); + assert_eq!(fill_paint(&n, 3).color().unwrap().to_hex(), "#ff0000", "{:?}", n.appearance); + } +} + /// b `[Fill red, Fill white, Stroke]` above a `[Fill white, Stroke]`, selected b first: b's rows 1 /// and 2 equal a's rows 0 and 1. fn reversed_pair(s: &mut Session) -> (NodeId, NodeId) { diff --git a/crates/engine/src/tests/areafit.rs b/crates/engine/src/tests/areafit.rs index 57182baf35..b6d6883430 100644 --- a/crates/engine/src/tests/areafit.rs +++ b/crates/engine/src/tests/areafit.rs @@ -77,7 +77,7 @@ fn area_options_set_and_report_the_fit() { let n = undo_len(&s); let again = s.execute("text.areaOptions", &q).unwrap(); assert_eq!(again, q); - assert_eq!(undo_len(&s), n + 1); + assert_eq!(undo_len(&s), n, "options that change nothing add no undo step"); // Undo back to no fit. while text(&s, id).area.fit != AreaFit::None { s.execute("edit.undo", &json!({})).unwrap(); diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index c1f33ac974..7a28b922bf 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1405,6 +1405,26 @@ fn symbolism_adjustments() { assert!(s.execute("symbol.adjust", &json!({"tool": "nope", "points": at})).is_err()); } +/// The Symbol Stainer's `color` with an alpha part (`#rrggbbaa` or `#rgba`) is refused and changes +/// nothing, rather than staining with the current fill; `#rrggbb` still stains with it. +#[test] +fn a_stain_color_with_an_alpha_part_is_refused() { + let mut s = session(); + let (inst, _, b) = make_symbol(&mut s); + let c = b.center(); + let at = json!([[c.x, c.y]]); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for bad in ["#ff000080", "ff000080", "#f008"] { + assert!(s.execute("symbol.adjust", &json!({"tool": "stain", "points": at, "color": bad, "intensity": 10})).is_err(), "{bad}"); + } + assert_eq!(*s.doc().unwrap().doc, *before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + s.execute("symbol.adjust", &json!({"tool": "stain", "points": at, "color": "#ff0000", "intensity": 10})).unwrap(); + let f = node(&s, inst).appearance.fill().cloned().unwrap(); + assert_eq!(f.paint.color().map(|c| c.to_hex()).as_deref(), Some("#ff0000")); +} + /// In a CMYK document the Symbol Stainer's RGB `color` separates through the color settings, as /// `paint.setFill` stores it. #[test] diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 43234dcc9d..c6bd07ecff 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -2244,6 +2244,25 @@ fn live_paint_gap_detection_stops_paint_at_a_gap() { assert!(node(&s, g).extras().live_paint_gaps.is_none()); } +/// A Gap Preview Color with an alpha part (`#rrggbbaa` or `#rgba`) is refused and changes nothing; +/// `#rrggbb` and a layer color's name still set it. +#[test] +fn a_gap_color_with_an_alpha_part_is_refused() { + let mut s = session(); + let g = live_square_with_a_gap(&mut s); + let depth = s.doc().unwrap().history.undo.len(); + for bad in ["#00ff0080", "00ff0080", "#0f08"] { + let err = s.execute("livePaint.gapOptions", &json!({"id": g.0, "color": bad})).unwrap_err().to_string(); + assert!(err.contains(&format!("`{bad}` is not a colour (#rrggbb or a preset name)")), "{bad}: {err}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + assert_eq!(gap_options(&s, g).color, [0xff, 0x4f, 0x4f]); + s.execute("livePaint.gapOptions", &json!({"id": g.0, "color": "#00ff00"})).unwrap(); + assert_eq!(gap_options(&s, g).color, [0, 0xff, 0]); + s.execute("livePaint.gapOptions", &json!({"id": g.0, "color": "Green"})).unwrap(); + assert_eq!(gap_options(&s, g).color, [0x4f, 0xff, 0x4f]); +} + #[test] fn medium_and_large_gaps_stop_paint_at_wider_gaps() { // Squares whose ends stop 5 pt and 9 pt short of their starts: each size closes the gaps up diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index d1df8f5a16..cb6ca47c5d 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -114,6 +114,149 @@ fn swatch_links_survive_mode_conversion() { assert_eq!(color, sw, "object and swatch converted identically"); } +/// The process color the active color settings give `c` in CMYK (the default intent). +fn to_cmyk(c: Color) -> Color { + let cms = cms::active(); + cms.convert(&c, cms::Model::Cmyk, cms.settings().intent) +} + +/// A document with colors that no 8-bit hex value holds: a plain fill, a three-stop gradient, a +/// pattern fill, a global swatch on one object's fill and at a 50% tint on another's stroke, and a +/// spot swatch on a third object → (session, plain, gradient, patterned, the swatch's two users, +/// the spot user). +fn reusable_paints_document() -> (Session, [NodeId; 6]) { + let mut s = session(); + let plain = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(Color::rgb(0.123_457, 0.765_432, 0.333_333))); + let grad = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!("#000000")); + let stops = json!([ + {"offset": 0, "color": Color::rgb(0.912_345, 0.1, 0.2)}, + {"offset": 0.37, "color": Color::rgb(0.2, 0.876_543, 0.3)}, + {"offset": 1, "color": Color::rgb(0.3, 0.4, 0.654_321)}, + ]); + s.execute("paint.setFill", &json!({"ids": [grad.0], "gradient": {"kind": "linear", "stops": stops}})).unwrap(); + let tile = rect(&mut s, 40.0, 0.0, 10.0, 10.0, json!(Color::rgb(0.6, 0.111_111, 0.9))); + s.execute("object.pattern.make", &json!({"ids": [tile.0], "name": "Odd Tile", "edit": false})).unwrap(); + let patterned = rect(&mut s, 60.0, 0.0, 10.0, 10.0, json!("#000000")); + s.execute("paint.setFill", &json!({"ids": [patterned.0], "swatch": "Odd Tile"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Shared", "color": Color::rgb(0.271_937, 0.314_773, 0.583_119), "global": true})).unwrap(); + let filled = rect(&mut s, 0.0, 20.0, 10.0, 10.0, json!("#000000")); + s.execute("paint.setFill", &json!({"ids": [filled.0], "swatch": "Shared"})).unwrap(); + let stroked = rect(&mut s, 20.0, 20.0, 10.0, 10.0, json!("#000000")); + s.execute("paint.setStroke", &json!({"ids": [stroked.0], "swatch": "Shared", "tint": 50})).unwrap(); + s.execute("swatch.new", &json!({"name": "Spot Lab", "color": Color::Lab { l: 61.5, a: 42.25, b: -17.75 }, "global": true})).unwrap(); + s.execute("swatch.setSpot", &json!({"name": "Spot Lab"})).unwrap(); + let spot = rect(&mut s, 40.0, 20.0, 10.0, 10.0, json!("#000000")); + s.execute("paint.setFill", &json!({"ids": [spot.0], "swatch": "Spot Lab"})).unwrap(); + (s, [plain, grad, patterned, filled, stroked, spot]) +} + +/// RGB → CMYK → Undo gives back the document bit for bit (no conversion back through the +/// profile), and Redo gives back the converted one. +#[test] +fn rgb_cmyk_undo_restores_every_color_exactly() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let (mut s, _) = reusable_paints_document(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let converted = s.doc().unwrap().doc.clone(); + assert_ne!(*converted, *before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one Undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *converted); +} + +/// Each stop of a gradient converts on its own and keeps its offset. +#[test] +fn rgb_cmyk_converts_each_gradient_stop() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let (mut s, [_, grad, ..]) = reusable_paints_document(); + let Paint::Gradient(old) = fill_of(&s, grad) else { panic!("not a gradient") }; + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let Paint::Gradient(new) = fill_of(&s, grad) else { panic!("not a gradient") }; + assert_eq!(new.gradient.stops.len(), 3); + for (o, n) in old.gradient.stops.iter().zip(&new.gradient.stops) { + assert_eq!(n.offset, o.offset); + assert!(matches!(n.color, Color::Cmyk { .. }), "{:?}", n.color); + assert_eq!(n.color, to_cmyk(o.color)); + } +} + +/// A pattern's tile art converts, and the art filled with the pattern keeps it. +#[test] +fn rgb_cmyk_converts_a_pattern_tile() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let (mut s, [_, _, patterned, ..]) = reusable_paints_document(); + let tile = |s: &Session| s.doc().unwrap().doc.pattern("Odd Tile").unwrap().art[0].appearance.fill_paint().color().unwrap(); + let old = tile(&s); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + assert!(matches!(tile(&s), Color::Cmyk { .. }), "{:?}", tile(&s)); + assert_eq!(tile(&s), to_cmyk(old)); + assert!(matches!(fill_of(&s, patterned), Paint::Pattern { ref pattern, .. } if pattern == "Odd Tile"), "{:?}", fill_of(&s, patterned)); +} + +/// A global swatch used in two places converts once: both uses keep the link and take the +/// converted swatch color (the 50% tint at that tint), not a conversion of their own. +#[test] +fn rgb_cmyk_converts_a_shared_swatch_once() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let (mut s, [.., filled, stroked, _]) = reusable_paints_document(); + let shared = |s: &Session| s.doc().unwrap().doc.swatch("Shared").unwrap().paint.color().unwrap(); + let old = shared(&s); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let new = shared(&s); + assert_eq!(new, to_cmyk(old)); + assert_eq!(fill_of(&s, filled), Paint::Solid { color: new, swatch: Some("Shared".into()), tint: 1.0 }); + let stroke = s.doc().unwrap().doc.node(stroked).unwrap().appearance.stroke_paint(); + assert_eq!(stroke, Paint::Solid { color: new.tinted(0.5), swatch: Some("Shared".into()), tint: 0.5 }); +} + +/// A spot color defined in Lab stays a spot color: its Lab definition, its link and its own +/// plate are kept. +#[test] +fn rgb_cmyk_keeps_a_spot_color() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let (mut s, [.., spot]) = reusable_paints_document(); + let swatch = |s: &Session| s.doc().unwrap().doc.swatch("Spot Lab").unwrap().clone(); + let (old_swatch, old_fill) = (swatch(&s), fill_of(&s, spot)); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + assert_eq!(swatch(&s), old_swatch); + assert!(swatch(&s).spot); + assert_eq!(fill_of(&s, spot), old_fill); + let plates = s.execute("color.plates", &json!({})).unwrap(); + assert!(plates["plates"].as_array().unwrap().iter().any(|p| p["name"] == "Spot Lab"), "{plates}"); +} + +/// A spot color defined in RGB stays a spot color with its own plate, and its definition +/// converts like any other swatch: the fill that uses it and a 40% tint stroke both take the +/// converted definition. +#[test] +fn rgb_cmyk_converts_an_rgb_spot_definition() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Spot RGB", "color": Color::rgb(0.812_345, 0.234_567, 0.456_789), "global": true})).unwrap(); + s.execute("swatch.setSpot", &json!({"name": "Spot RGB"})).unwrap(); + let filled = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!("#000000")); + s.execute("paint.setFill", &json!({"ids": [filled.0], "swatch": "Spot RGB"})).unwrap(); + let stroked = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!("#000000")); + s.execute("paint.setStroke", &json!({"ids": [stroked.0], "swatch": "Spot RGB", "tint": 40})).unwrap(); + let swatch = |s: &Session| s.doc().unwrap().doc.swatch("Spot RGB").unwrap().clone(); + let old = swatch(&s).paint.color().unwrap(); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let sw = swatch(&s); + assert!(sw.spot); + let new = sw.paint.color().unwrap(); + assert!(matches!(new, Color::Cmyk { .. }), "{new:?}"); + assert_eq!(new, to_cmyk(old)); + assert_eq!(fill_of(&s, filled), Paint::Solid { color: new, swatch: Some("Spot RGB".into()), tint: 1.0 }); + let stroke = s.doc().unwrap().doc.node(stroked).unwrap().appearance.stroke_paint(); + assert_eq!(stroke, Paint::Solid { color: new.tinted(0.4), swatch: Some("Spot RGB".into()), tint: 0.4 }); + let plates = s.execute("color.plates", &json!({})).unwrap(); + assert!(plates["plates"].as_array().unwrap().iter().any(|p| p["name"] == "Spot RGB" && p["spot"] == true), "{plates}"); +} + #[test] fn gamut_check_flags_unprintable_colours() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); @@ -128,6 +271,10 @@ fn gamut_check_flags_unprintable_colours() { let r = s.execute("color.gamutCheck", &json!({"colors": ["#00ff00", {"c": 100, "m": 0, "y": 0, "k": 0}]})).unwrap(); assert_eq!(r["checked"], 2); assert_eq!(r["outOfGamut"].as_array().unwrap().len(), 1); + // A color it can't read, a hex color with an alpha part included, is an error, not skipped. + for bad in ["#0000ff80", "nope"] { + assert!(s.execute("color.gamutCheck", &json!({"colors": ["#00ff00", bad]})).is_err(), "{bad}"); + } } #[test] diff --git a/crates/engine/src/tests/guide_clipboard.rs b/crates/engine/src/tests/guide_clipboard.rs new file mode 100644 index 0000000000..d509dfa206 --- /dev/null +++ b/crates/engine/src/tests/guide_clipboard.rs @@ -0,0 +1,131 @@ +//! Copying and pasting ruler guides (#3226): selected guides go on the clipboard with the objects +//! or alone, and paste into another document or onto another artboard. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; + +use crate::*; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +/// The active document's guides: (vertical, pos, layer). +fn guides(s: &Session) -> Vec<(bool, f64, Option)> { + s.doc().unwrap().doc.guides.iter().map(|g| (g.vertical, g.pos, g.layer)).collect() +} + +#[test] +fn ruler_guides_copy_and_paste_into_another_document() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + run(&mut s, "guide.add", json!({"vertical": true, "pos": 120})); + run(&mut s, "guide.add", json!({"vertical": false, "pos": 80})); + run(&mut s, "guide.select", json!({"indexes": [0, 1]})); + let r = run(&mut s, "edit.copy", json!({})); + assert_eq!(r["guides"], 2); + // Into another document: the same places, on its current layer, selected, one undo step. + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + let layer = s.doc().unwrap().doc.layers[0].id; + let undo = s.doc().unwrap().history.undo.len(); + let r = run(&mut s, "edit.paste", json!({})); + assert_eq!(r["guides"], 2); + assert_eq!(guides(&s), [(true, 120.0, Some(layer)), (false, 80.0, Some(layer))], "where they were, not offset"); + assert_eq!(s.doc().unwrap().selection.guides, [0, 1]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + run(&mut s, "edit.undo", json!({})); + assert!(guides(&s).is_empty()); + // With an object, they move as it does (Paste offsets it by the Paste Offset preference). + run(&mut s, "document.activate", json!({"index": 0})); + let rect = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [rect]})); + run(&mut s, "guide.select", json!({"indexes": [0], "toggle": true})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "document.activate", json!({"index": 1})); + run(&mut s, "edit.paste", json!({"dx": 5, "dy": 7})); + assert_eq!(guides(&s).iter().map(|g| (g.0, g.1)).collect::>(), [(true, 125.0)]); +} + +#[test] +fn guides_paste_in_place_onto_another_artboard_and_cut_removes_them() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 100, "height": 100, "artboards": 2})); + let [a, b] = [0, 1].map(|i| s.doc().unwrap().doc.artboards[i].rect); + run(&mut s, "guide.add", json!({"vertical": true, "pos": a.x0 + 30.0})); + run(&mut s, "guide.select", json!({"indexes": [0]})); + // Cut takes the guide away and keeps it on the clipboard. + run(&mut s, "edit.cut", json!({})); + assert!(guides(&s).is_empty()); + // Paste in Place onto the second artboard: 30 pt into it. + run(&mut s, "edit.pasteInPlace", json!({"artboard": 1})); + assert_eq!(guides(&s).iter().map(|g| g.1).collect::>(), [b.x0 + 30.0]); + // Paste on All Artboards: one on each. + run(&mut s, "edit.pasteOnAllArtboards", json!({})); + let mut at: Vec = guides(&s).iter().map(|g| g.1).collect(); + at.sort_by(f64::total_cmp); + assert_eq!(at, [a.x0 + 30.0, b.x0 + 30.0, b.x0 + 30.0]); + // Cut with an object and a guide selected takes both away, in one undo step. + let rect = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap(); + let before = guides(&s).len(); + run(&mut s, "select.set", json!({"ids": [rect]})); + run(&mut s, "guide.select", json!({"indexes": [0], "toggle": true})); + let undo = s.doc().unwrap().history.undo.len(); + run(&mut s, "edit.cut", json!({})); + assert!(s.doc().unwrap().doc.node(NodeId(rect)).is_none()); + assert_eq!(guides(&s).len(), before - 1, "the selected guide goes too"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + // Cut with direct-selected anchors and a guide: the anchors and the guide go, one undo step. + let path = run(&mut s, "shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20}))["id"].as_u64().unwrap(); + run(&mut s, "guide.add", json!({"vertical": false, "pos": 90})); + let n = guides(&s).len(); + run(&mut s, "select.anchors", json!({"id": path, "anchors": [[0, 0]], "mode": "set"})); + run(&mut s, "guide.select", json!({"indexes": [n - 1], "toggle": true})); + let undo = s.doc().unwrap().history.undo.len(); + run(&mut s, "edit.cut", json!({})); + assert_eq!(guides(&s).len(), n - 1, "the guide goes with the anchors"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + // Nothing selected: Copy is off. + run(&mut s, "select.none", json!({})); + assert!(s.execute("edit.copy", &json!({})).is_err()); +} + +/// #3226 review: each paste adds guides of its own (a guide is its place and layer; there is no +/// id to share), on the layer new art goes to, so they take that layer's colour, visibility and +/// lock; and the SVG put on the system clipboard carries no guides. +#[test] +fn two_pastes_add_their_own_guides_on_the_current_layer_and_svg_has_none() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + run(&mut s, "guide.add", json!({"vertical": true, "pos": 120})); + run(&mut s, "guide.select", json!({"indexes": [0]})); + run(&mut s, "edit.copy", json!({})); + // Guides alone: no art for the system clipboard's SVG. + assert!(s.clipboard_svg().is_none(), "guides alone put no SVG on the system clipboard"); + assert!(s.clipboard.flavour_types(true, true).is_empty(), "nor any other format (the app empties the system clipboard)"); + let layer = NodeId(run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "edit.paste", json!({})); + assert_eq!(s.doc().unwrap().selection.guides, [1], "the first paste selects its own guide"); + run(&mut s, "edit.paste", json!({})); + assert_eq!(s.doc().unwrap().selection.guides, [2], "the second paste selects its own guide"); + let g = guides(&s); + assert_eq!(g.len(), 3, "two pastes, two more guides: {g:?}"); + assert_eq!((g[1].2, g[2].2), (Some(layer), Some(layer)), "on the layer new art goes to"); + // Moving the second pasted guide leaves the first where it is. + run(&mut s, "guide.move", json!({"index": 2, "pos": 200})); + assert_eq!(guides(&s).iter().map(|g| g.1).collect::>(), [120.0, 120.0, 200.0]); + // Hiding that layer hides the guides pasted on it: they follow its visibility (and lock). + run(&mut s, "layer.setProps", json!({"id": layer.0, "visible": false})); + let st = s.doc().unwrap(); + let shown: Vec = st.doc.guides.iter().map(|g| st.doc.guide_shown(g)).collect(); + assert_eq!(shown, [true, false, false]); + // With an object, the SVG holds the object and no guide. + run(&mut s, "layer.setProps", json!({"id": layer.0, "visible": true})); + let rect = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [rect]})); + run(&mut s, "guide.select", json!({"indexes": [0], "toggle": true})); + let r = run(&mut s, "edit.copy", json!({})); + assert_eq!(r["guides"], 1); + let svg = s.clipboard_svg().unwrap(); + assert!(svg.contains(" 256 * 1024), "both large templates count even without artwork"); + assert!(st.doc.layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty()))); + let retained = st.history.bytes(); + let after = s.paint.clone(); + for _ in 0..History::MIN_STEPS { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(s.doc().unwrap().history.redo.len(), History::MIN_STEPS); + assert!(s.doc().unwrap().history.redo.iter().all(|e| e.bytes > 256 * 1024)); + assert!(s.doc().unwrap().history.bytes().abs_diff(retained) < 64 * 1024, "turning entries must not double-count paint snapshots"); + for _ in 0..History::MIN_STEPS { + s.execute("edit.redo", &json!({})).unwrap(); + } + assert_eq!(s.paint, after); + assert!(s.doc().unwrap().history.bytes().abs_diff(retained) < 64 * 1024); + assert_eq!( + s.paint.appearance.as_ref().unwrap().effects[0].params["retainedTemplateData"], + original.appearance.unwrap().effects[0].params["retainedTemplateData"] + ); +} diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index 4052bf553a..f6b35716f6 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -375,6 +375,32 @@ fn layer_options_validate_and_template_locks_and_dims() { assert_eq!((summary["preview"].clone(), summary["dimImages"].clone()), (json!(false), json!(30))); } +/// A layer color with an alpha part (`#rrggbbaa` or `#rgba`) is refused by Layer Options, New +/// Layer and New Sublayer and changes nothing; `#rrggbb` and a preset name still set it. +#[test] +fn a_layer_color_with_an_alpha_part_is_refused() { + let mut s = session(); + let (layer, ..) = tree(&mut s); + let color = |s: &Session| match node(s, layer).kind { + NodeKind::Layer { color, .. } => color, + _ => panic!("not a layer"), + }; + let before = (color(&s), undos(&s)); + for bad in ["#ff000080", "ff000080", " #FF000080 ", "#f008"] { + let err = s.execute("layer.setProps", &json!({"id": layer.0, "color": bad})).unwrap_err().to_string(); + assert!(err.contains(&format!("`{bad}` is not a colour (#rrggbb or a preset name)")), "{bad}: {err}"); + assert!(s.execute("layer.new", &json!({"color": bad})).is_err(), "{bad}"); + assert!(s.execute("layer.newSublayer", &json!({"parent": layer.0, "color": bad})).is_err(), "{bad}"); + } + assert_eq!((color(&s), undos(&s)), before); + run(&mut s, "layer.setProps", json!({"id": layer.0, "color": "#ff0000"})); + assert_eq!(color(&s), LayerColor::Custom([0xff, 0, 0])); + run(&mut s, "layer.setProps", json!({"id": layer.0, "color": "Green"})); + assert_eq!(color(&s), LayerColor::Preset(2)); + let new = id(&run(&mut s, "layer.new", json!({"color": "#00ff00"}))); + assert!(matches!(node(&s, new).kind, NodeKind::Layer { color: LayerColor::Custom([0, 0xff, 0]), .. })); +} + #[test] fn new_layers_go_above_the_current_one_at_its_level() { let mut s = session(); diff --git a/crates/engine/src/tests/link_paths.rs b/crates/engine/src/tests/link_paths.rs index 2c96be935e..76bd7168aa 100644 --- a/crates/engine/src/tests/link_paths.rs +++ b/crates/engine/src/tests/link_paths.rs @@ -77,11 +77,8 @@ fn linked_files_on_other_computers_are_never_read() { } s.execute("links.updateChanged", &json!({})).unwrap(); s.start_link_scan(); - let t0 = std::time::Instant::now(); - while s.poll_link_scan().is_none() { - assert!(t0.elapsed().as_secs() < 10, "the look never finished"); - std::thread::yield_now(); - } + s.wait_link_scan(); + assert!(s.poll_link_scan().is_some(), "no look ran"); }); assert_eq!(far_reads(&seen), Vec::<&String>::new()); // The watch kept no stamp of them (`//tmp/…` would have one had it been looked at). diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index f3c44535a5..c355793d9b 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -290,6 +290,33 @@ fn perceptual_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() assert!(!pdf.contains("/Subtype/Image") && pdf.contains("/ShadingType 3") && pdf.contains("/DeviceN[/Cyan/Ink]/DeviceCMYK"), "radial"); } +#[test] +fn perceptual_spot_gradients_with_rgb_stops_in_a_cmyk_document_export_as_device_n_shadings() { + let (mut s, id) = setup(); + run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#00ff00"}], "method": "perceptual"})); + assert!(gradient(&s, id).gradient.stops.iter().any(|st| matches!(st.color, Color::Rgb { .. })), "an RGB stop"); + let (pdf, _) = pdf_of(&s); + assert!(pdf.contains("/Subtype/Image"), "an image in an RGB document"); + // A CMYK document, or a conversion to a CMYK destination, writes the RGB stop in CMYK: a + // DeviceN shading, not an image. + let mut cmyk = doc(&s).clone(); + cmyk.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let plain = vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() }; + let mut converted = plain.clone(); + converted.settings.output = vectorcraft_pdf::OutputSettings { + conversion: vectorcraft_pdf::ColorConversion::Destination, + destination: vectorcraft_pdf::DOCUMENT_CMYK.into(), + ..Default::default() + }; + for (what, d, opts) in [("CMYK document", &cmyk, &plain), ("CMYK destination", doc(&s), &converted)] { + let r = vectorcraft_pdf::export_with_report(d, opts).unwrap(); + let pdf = String::from_utf8_lossy(&r.bytes); + assert!(!pdf.contains("/Subtype/Image"), "{what}: no image"); + assert!(pdf.contains("/ShadingType 2") && pdf.contains("/Ink]/DeviceCMYK"), "{what}: a DeviceN shading with Ink"); + assert!(!r.warnings.iter().any(|w| w.contains("spot")), "{what}: {:?}", r.warnings); + } +} + #[test] fn spot_gradients_drawn_as_images_warn() { let (mut s, _) = setup(); @@ -321,3 +348,19 @@ fn spot_gradients_drawn_as_images_warn() { assert!(pdf.contains("/Subtype/Image") && !pdf.contains("/Separation"), "a process Perceptual gradient"); assert!(!spot_warning(&warnings), "{warnings:?}"); } + +#[test] +fn freeform_gradients_without_points_warn_about_spot_stops() { + let (mut s, id) = setup(); + run(&mut s, "paint.editGradient", with(ink_to_white(100.0), json!({"kind": "freeform"}))); + // A freeform field with no points of its own: the colors come from the stops, the first + // linked to the spot swatch. + let mut g = gradient(&s, id); + g.freeform = Some(vectorcraft_color::Freeform::default()); + g.gradient.stops[0].swatch = Some("Ink".into()); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(id).unwrap().appearance.set_fill(Paint::Gradient(Box::new(g))); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/Subtype/Image"), "an image"); + assert!(warnings.iter().any(|w| w.contains("spot colors in gradients exported as images")), "{warnings:?}"); +} diff --git a/crates/engine/src/tests/linkwatch.rs b/crates/engine/src/tests/linkwatch.rs index 8c866b8d9a..f1192e02d5 100644 --- a/crates/engine/src/tests/linkwatch.rs +++ b/crates/engine/src/tests/linkwatch.rs @@ -6,10 +6,13 @@ use serde_json::{Value, json}; use crate::tests_links::{BLUE, Folder, RED, centre_colour, place, png, session}; use crate::*; -/// Write `bytes` to `path` so its modification time moves even on coarse file systems. +/// Write `bytes` to `path`, dated 2 s after the file it replaces so its modification time moves +/// even on coarse file systems. fn save(path: &str, bytes: &[u8]) { - std::thread::sleep(std::time::Duration::from_millis(30)); + let stamp = std::fs::metadata(path).unwrap().modified().unwrap(); std::fs::write(path, bytes).unwrap(); + let later = std::fs::FileTimes::new().set_modified(stamp + std::time::Duration::from_secs(2)); + std::fs::OpenOptions::new().write(true).open(path).unwrap().set_times(later).unwrap(); } fn colour(s: &Session) -> [u8; 3] { @@ -19,14 +22,8 @@ fn colour(s: &Session) -> [u8; 3] { /// One background look, waited for. fn look(s: &mut Session) -> Value { s.start_link_scan(); - let t0 = std::time::Instant::now(); - loop { - if let Some(r) = s.poll_link_scan() { - return r.unwrap(); - } - assert!(t0.elapsed().as_secs() < 10, "the look never finished"); - std::thread::yield_now(); - } + s.wait_link_scan(); + s.poll_link_scan().expect("a look ran").unwrap() } #[test] diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index f500e2c398..1dc5f66bad 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -851,6 +851,28 @@ fn mesh_point_colour_move_and_undo() { assert!(s.execute("object.mesh.setPointColor", &json!({"id": a.0, "index": 99, "color": "#000000"})).is_err()); } +/// A mesh point's `color` with an alpha part (`#rrggbbaa` or `#rgba`) is refused and changes +/// nothing, also when `opacity` is given and when Add Mesh Line takes it; `#rrggbb` still sets it. +#[test] +fn a_mesh_point_color_with_an_alpha_part_is_refused() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a]); + s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for bad in ["#00ff0080", "00ff0080", "#0f08"] { + let set = json!({"id": a.0, "index": 3, "color": bad, "opacity": 0.5}); + assert!(s.execute("object.mesh.setPointColor", &set).is_err(), "{bad}"); + assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 50, "y": 50, "color": bad})).is_err(), "{bad}"); + } + assert_eq!(*s.doc().unwrap().doc, *before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + s.execute("object.mesh.setPointColor", &json!({"id": a.0, "index": 3, "color": "#00ff00"})).unwrap(); + assert_eq!(mesh_of(&s, a).points[3].color.to_hex(), "#00ff00"); + s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 50, "y": 50, "color": "#00ff00"})).unwrap(); +} + /// `object.mesh.movePoints` moves just the points it names (their handles with them), over one or /// several meshes, as one undo step; `object.mesh.setPointColor` colours and fades several points /// alike. A bad index, a non-number or a move past the coordinate range fails and changes nothing diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index fe0783a135..d14502659b 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -865,6 +865,51 @@ fn hide_unselected_artwork_keeps_groups_with_locked_guides_and_the_selected_laye assert_eq!(selected(&s), [other]); } +/// While Lock Guides is on, Hide › Unselected Artwork keeps a group visible when it holds a guide path that is locked +/// itself, and hides the group's other members one by one. +#[test] +fn hide_unselected_artwork_keeps_groups_with_a_locked_guide_path() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let guide = rect(&mut s, 40.0, 0.0, 10.0, 10.0); + let x = rect(&mut s, 60.0, 0.0, 10.0, 10.0); + sel(&mut s, &[guide, x]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + sel(&mut s, &[guide]); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("layer.setProps", &json!({"id": guide.0, "locked": true})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + sel(&mut s, &[a]); + assert_eq!(s.execute("object.hide.unselected", &json!({})).unwrap(), json!({"count": 1})); + assert_eq!([a, g, guide, x].map(|id| node(&s, id).visible), [true, true, true, false]); +} + +/// Hide › Unselected Artwork keeps a group visible when it holds a selected layer whose art is all locked, and hides the +/// group's other members one by one. +#[test] +fn hide_unselected_artwork_keeps_a_group_that_holds_a_selected_layer() { + let mut s = session(); + let b = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let y = rect(&mut s, 20.0, 0.0, 10.0, 10.0); + let z = rect(&mut s, 40.0, 0.0, 10.0, 10.0); + sel(&mut s, &[y]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + let sub = s + .edit("nest", |d, _| { + let id = d.alloc_id(); + d.insert(Some(g), usize::MAX, Node::layer(id, "Sub", vectorcraft_doc::LayerColor::Preset(1))) + .map_err(|e| EngineError::Other(e.to_string()))?; + let art = d.remove(z).map_err(|e| EngineError::Other(e.to_string()))?; + d.insert(Some(id), 0, (*art).clone()).map_err(|e| EngineError::Other(e.to_string()))?; + Ok(id) + }) + .unwrap(); + s.execute("layer.setProps", &json!({"id": z.0, "locked": true})).unwrap(); + sel(&mut s, &[sub]); + assert_eq!(s.execute("object.hide.unselected", &json!({})).unwrap(), json!({"count": 2})); + assert_eq!([b, g, y, sub, z].map(|id| node(&s, id).visible), [false, true, false, true, true]); +} + /// Lock Unselected Artwork locks `b`, `n` in the group that holds selected `m`, `p` on another layer, and the clip /// group's unselected members `c1` and clipping path `c3` in one undo step labeled "Lock". The clip group container, /// `c2`, the selected objects, group `g`, hidden object `h` and art `q` on a locked layer stay unlocked. `k` was locked @@ -2049,6 +2094,41 @@ fn select_same_font_takes_its_reference_from_the_isolated_group_on_a_selected_la assert!(!got.contains(&outside)); } +/// A template sublayer inside a selected sublayer of the isolated layer gives no type for the +/// reference of the font Same commands, so the reference is the first type that can be selected. +#[test] +fn select_same_font_ignores_type_on_a_template_sublayer_inside_the_isolated_layer() { + let mut s = session(); + let typed = + |s: &mut Session, y: f64, font: &str| id_of(&s.execute("text.create", &json!({"x": 0, "y": y, "text": "type", "font": font})).unwrap()); + let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap()); + let sub = id_of(&s.execute("layer.newSublayer", &json!({"parent": l2.0})).unwrap()); + let template = id_of(&s.execute("layer.newSublayer", &json!({"parent": sub.0, "bottom": true})).unwrap()); + s.execute("layer.setCurrent", &json!({"id": template.0})).unwrap(); + let on_template = typed(&mut s, 20.0, "Arial"); + s.execute("layer.setProps", &json!({"id": template.0, "template": true})).unwrap(); + s.execute("layer.setProps", &json!({"id": template.0, "locked": false})).unwrap(); + assert!(s.doc().unwrap().doc.node(template).is_some_and(|n| n.is_template() && !n.locked)); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let courier = typed(&mut s, 60.0, "Courier"); + let other_courier = typed(&mut s, 100.0, "Courier"); + let arial = typed(&mut s, 140.0, "Arial"); + let doc = &s.doc().unwrap().doc; + let order: Vec = doc.node(sub).unwrap().children().unwrap().iter().map(|c| c.id).collect(); + assert_eq!(order, vec![template, courier, other_courier, arial]); + assert!(doc.ancestry(on_template).unwrap().contains(&template), "{:?}", doc.ancestry(on_template)); + s.execute("object.isolate", &json!({"id": l2.0})).unwrap(); + sel(&mut s, &[sub]); + assert_eq!(s.doc().unwrap().isolation, Some(l2)); + assert_eq!(s.execute("select.same.fontFamily", &json!({})).unwrap()["count"], 2); + let mut got = selected(&s); + got.sort(); + let mut want = vec![courier, other_courier]; + want.sort(); + assert_eq!(got, want); + assert!(!got.contains(&arial) && !got.contains(&on_template)); +} + /// Select › Same › Symbol Instance takes its reference from the first selected object that can be /// selected: an instance that is hidden, locked, on a template layer or outside the isolated group /// is passed over. @@ -2096,6 +2176,44 @@ fn select_same_symbol_instance_skips_objects_that_cannot_be_selected() { assert_eq!(selected(&s), vec![a1, on_template]); } +/// Select › Same › Symbol Instance takes as its reference the first selected object that can be +/// selected, whatever its kind: an instance inside a selected group, and an instance just placed +/// on a locked artboard while it stays selected. A first object that is not an instance matches +/// nothing, so the selection is cleared. +#[test] +fn select_same_symbol_instance_reference_can_be_any_selectable_object() { + const C: &str = "select.same.symbolInstance"; + let mut s = session(); + let place = |s: &mut Session, name: &str, x: f64| id_of(&s.execute("symbol.place", &json!({"name": name, "x": x, "y": 200})).unwrap()); + rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let a1 = id_of(&s.execute("symbol.new", &json!({"name": "A"})).unwrap()); + rect(&mut s, 50.0, 0.0, 20.0, 20.0); + let b1 = id_of(&s.execute("symbol.new", &json!({"name": "B"})).unwrap()); + let b2 = place(&mut s, "B", 200.0); + let plain = rect(&mut s, 0.0, 100.0, 20.0, 20.0); + // A path selected before an instance is the reference, and no instance matches it. + sel(&mut s, &[plain, b1]); + assert_eq!(s.execute(C, &json!({})).unwrap()["count"], 0); + assert!(selected(&s).is_empty()); + // An instance inside a group, selected on its own, is the reference. + sel(&mut s, &[b1, plain]); + s.execute("object.group", &json!({})).unwrap(); + sel(&mut s, &[b1]); + assert_eq!(s.execute(C, &json!({})).unwrap()["count"], 2); + let mut got = selected(&s); + got.sort(); + let mut want = vec![b1, b2]; + want.sort(); + assert_eq!(got, want); + // An instance placed on a locked artboard is the reference while it stays selected. + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + let a2 = place(&mut s, "A", 1100.0); + assert_eq!(selected(&s), vec![a2]); + assert_eq!(s.execute(C, &json!({})).unwrap()["count"], 2); + assert_eq!(selected(&s), vec![a1, a2]); +} + /// Select › Same › Text Fill & Stroke Color selects the type with characters whose fill and stroke /// both match the first character of the selected type: the same fill with another stroke, or the /// same stroke with another fill, is left out, and in type with several runs one run has to match @@ -2427,6 +2545,8 @@ fn select_color_matches_fill_and_stroke_without_a_selection() { assert_eq!(pick(&mut s, json!({"fill": "#000000"})), vec![a, t, empty]); assert!(s.execute("select.color", &json!({})).is_err()); assert!(s.execute("select.color", &json!({"fill": "not a colour"})).is_err()); + assert!(s.execute("select.color", &json!({"fill": "#00000080"})).is_err(), "a hex color with an alpha part"); + assert!(s.execute("select.color", &json!({"stroke": "#ff000080"})).is_err(), "a hex color with an alpha part"); } #[test] @@ -2681,6 +2801,50 @@ fn select_menu_commands_leave_out_an_isolated_group_hidden_or_locked_since() { assert_eq!(selected(&s), vec![]); } +/// All on Same Layers takes the layers only of the selected objects that can be selected: an +/// object that is hidden or locked, on a template layer, or outside the isolated group adds no +/// layer. When the selection holds no such object, the command selects nothing. +#[test] +fn select_all_on_same_layers_skips_objects_that_cannot_be_selected() { + let mut s = session(); + let [hidden, a] = [0.0, 20.0].map(|x| rect(&mut s, x, 0.0, 10.0, 10.0)); + s.execute("layer.new", &json!({"top": true})).unwrap(); + let [b, c, d] = [0.0, 20.0, 40.0].map(|x| rect(&mut s, x, 40.0, 10.0, 10.0)); + let same = |s: &mut Session, from: &[NodeId]| { + sel(s, from); + assert_eq!(selected(s), from, "select.set keeps {from:?}"); + s.execute("select.object.allOnSameLayers", &json!({})).unwrap(); + let mut v = selected(s); + v.sort(); + v + }; + assert_eq!(same(&mut s, &[a, b]), vec![hidden, a, b, c, d]); + // A hidden or locked object on the first layer adds no layer. + for (on, off) in [ + (json!({"id": hidden.0, "visible": false}), json!({"id": hidden.0, "visible": true})), + (json!({"id": hidden.0, "locked": true}), json!({"id": hidden.0, "locked": false})), + ] { + s.execute("layer.setProps", &on).unwrap(); + assert_eq!(same(&mut s, &[hidden, b]), vec![b, c, d], "{on}"); + s.execute("layer.setProps", &off).unwrap(); + } + // An object on a template layer adds no layer. + let l3 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap()); + let on_template = rect(&mut s, 0.0, 80.0, 10.0, 10.0); + s.execute("layer.setProps", &json!({"id": l3.0, "template": true})).unwrap(); + assert_eq!(same(&mut s, &[on_template, b]), vec![b, c, d]); + // An object outside the isolated group adds no layer, even though its layer holds the group. + sel(&mut s, &[c, d]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + assert_eq!(same(&mut s, &[b]), vec![]); + assert_eq!(same(&mut s, &[c]), vec![c, d]); + s.execute("object.exitIsolation", &json!({})).unwrap(); + // With no object that can be selected, nothing is selected. + s.execute("layer.setProps", &json!({"id": hidden.0, "visible": false})).unwrap(); + assert_eq!(same(&mut s, &[hidden, on_template]), vec![]); +} + /// The selection after command `c` runs with nothing selected. fn select_from_none(s: &mut Session, c: &str) -> Vec { s.execute("select.none", &json!({})).unwrap(); diff --git a/crates/engine/src/tests/nativefile.rs b/crates/engine/src/tests/nativefile.rs index 4f67890b17..5b9973e563 100644 --- a/crates/engine/src/tests/nativefile.rs +++ b/crates/engine/src/tests/nativefile.rs @@ -186,6 +186,40 @@ fn newer_keys_and_legacy_profiles_survive_open_and_save() { assert_eq!(v2["document"]["unknown"]["colorProfiles"]["rgb"], "sRGB IEC61966-2.1"); } +/// A version 1 document saved before VectorCraft 0.21.0 turned its Twist effects counterclockwise +/// for a positive angle. It opens with the angles negated, so its art turns as it did; saved +/// again it is a version 2 document, and saved for an older file version it is version 1 again. +#[test] +fn a_version_1_documents_twist_turns_as_it_was_saved() { + use vectorcraft_doc::{Appearance, Document, Effect, Node}; + use vectorcraft_geom::{PathData, Point, Rect, SubPath}; + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let right = PathData::single(SubPath::polyline(&[Point::new(55.0, 50.0), Point::new(56.0, 50.0)], false)); + let mut a = Appearance::default_art(); + a.effects.push(Effect { id: "distort.twist".into(), params: json!({"angle": 45}), visible: true }); + d.insert(Some(l), 0, Node::path(id, right.clone(), a)).unwrap(); + let mut j = json_of(&vectorcraft_format::save(&d, false)); + j["document"]["version"] = json!(1); + j["generator"] = json!("VectorCraft 0.20.0"); + let mut s = Session::new(); + open(&mut s, "old.vectorcraft", &serde_json::to_vec(&j).unwrap()); + let doc = &s.doc().unwrap().doc; + let n = doc.layers[0].children().and_then(|c| c.first()).cloned().unwrap(); + let turned = vectorcraft_render::effects::apply_geometry(&n.appearance.effects, &right, Rect::new(0.0, 0.0, 100.0, 100.0)); + // Counterclockwise on the page takes a point right of the center up (y runs down). + let p = turned.subpaths[0].anchors[0].p; + assert!(p.y < 49.5, "{p:?}"); + let again = json_of(&saved(&mut s, json!({}))); + assert_eq!(again["document"]["version"], 2); + assert!(again.to_string().contains(r#""angle":-45.0"#), "{again}"); + // Saved for an older file version, it is version 1 with its angle as 0.20.0 saved it. + let older = json_of(&saved(&mut s, json!({"version": 3}))); + assert_eq!(older["document"]["version"], 1); + assert!(older.to_string().contains(r#""angle":45.0"#), "{older}"); +} + /// A save records the date the document was made in, so the same commands twice gave different /// bytes (#2880). A pinned date makes them identical — `file.new {created}` here, and /// `SOURCE_DATE_EPOCH` for an export that takes no date param. diff --git a/crates/engine/src/tests/opacitymask.rs b/crates/engine/src/tests/opacitymask.rs index c2db4f3688..206ef7e66d 100644 --- a/crates/engine/src/tests/opacitymask.rs +++ b/crates/engine/src/tests/opacitymask.rs @@ -6,7 +6,7 @@ use serde_json::{Value, json}; use vectorcraft_geom::Affine; use vectorcraft_render::{RenderOptions, Renderer}; -use vectorcraft_tools::{PointerEvent, PointerKind}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; use crate::cmd::maskedit::MASK_EDIT_LAYER; use crate::tests::{history, select_with_a_step_to_redo}; @@ -234,6 +234,31 @@ fn empty_point_type_is_not_saved_into_the_mask() { } } +/// The same while a Cmd/Ctrl press has lent the Selection tool to the Type tool: the command before +/// the release gives the Type tool back first, so the empty point type is still discarded. +#[test] +fn empty_point_type_is_not_saved_into_the_mask_during_a_cmd_press() { + for cmd in ["transparency.stopEditingOpacityMask", "object.exitIsolation"] { + let mut s = session(); + s.prefs.placeholder_text = false; + let obj = editing_mask(&mut s); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 250.0, 250.0), v).unwrap(); + } + let press = Mods { cmd: true, ..Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 280.0).with_mods(press), v).unwrap(); + assert_eq!(s.tool_id(), "selection", "{cmd}: the press lends the Selection tool"); + s.execute(cmd, &json!({})).unwrap(); + assert_eq!(s.tool_id(), "type", "{cmd}: the Type tool is back"); + assert!(!s.tool_wants_text(), "{cmd}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 280.0).with_mods(press), v).unwrap(); + let art = &mask(&s, obj).unwrap().art; + assert!(art.children().is_none() && !matches!(art.kind, vectorcraft_doc::NodeKind::Text(_)), "{cmd}: the mask keeps only the square"); + } +} + /// Releasing the masks of a group and of an object inside it puts each mask's art directly above /// its object, as releasing one mask at a time does. #[test] diff --git a/crates/engine/src/tests/paintproxy.rs b/crates/engine/src/tests/paintproxy.rs index 9ddbc288eb..a9e832bb36 100644 --- a/crates/engine/src/tests/paintproxy.rs +++ b/crates/engine/src/tests/paintproxy.rs @@ -217,6 +217,19 @@ fn live_previews_remember_only_the_committed_colour() { assert_eq!(hexes(&s), ["#300000"], "a preview undone by a failed one is forgotten"); } +#[test] +fn ordinary_preview_keeps_paint_changed_during_the_interaction() { + let mut s = session(); + rect(&mut s); + s.begin_interaction("Move").unwrap(); + s.preview("paint.setFill", &json!({"color": "#123456"})).unwrap(); + let paint = s.paint.clone(); + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + assert_eq!(s.paint, paint); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint, paint); +} + #[test] fn focus_false_keeps_the_active_proxy() { let mut s = session(); diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index fabf5cc54f..e6b4ca3d02 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -162,6 +162,56 @@ fn artboard_color_is_set_and_cleared_in_one_undo_step() { assert_eq!(*s.doc().unwrap().doc, *before, "a bad color changes nothing"); } +/// A color param given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without +/// the `#`) is refused and changes nothing: a Rasterize background, an artboard's color, a fill or +/// stroke, a swatch's colors and the color of new type. `#rrggbb`, a color key and `[r, g, b]` +/// still set the color. +#[test] +fn a_color_with_an_alpha_part_is_refused() { + let mut s = session(); + let id = rect(&mut s); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for bad in ["#ff000080", "ff000080", " #FF000080 ", "#f008"] { + for (cmd, p) in [ + ("object.rasterize", json!({"ppi": 72, "background": bad})), + ("artboard.setProps", json!({"index": 0, "color": bad})), + ("artboard.new", json!({"color": bad})), + ("paint.setFill", json!({"ids": [id.0], "color": bad})), + ("paint.setStroke", json!({"ids": [id.0], "color": bad})), + ("swatch.new", json!({"name": "Half", "color": bad})), + ("swatch.new", json!({"colors": ["#00ff00", bad]})), + ("swatch.newGroup", json!({"name": "Half", "colors": ["#00ff00", bad]})), + ("text.create", json!({"x": 10, "y": 10, "text": "a", "color": bad})), + ("text.createInPath", json!({"path": id.0, "mode": "area", "text": "a", "color": bad})), + ("document.export", json!({"format": "png", "background": bad})), + ("document.export", json!({"format": "gif", "matte": bad})), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + } + assert_eq!(*s.doc().unwrap().doc, *before, "a color with an alpha part changes nothing"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "and records no undo step"); + s.execute("artboard.setProps", &json!({"index": 0, "color": "#ff0000"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards[0].color.map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + let fill = node(&s, id).appearance.fill_paint(); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "cmyk 0 100 100 0"})).unwrap(); + assert!(node(&s, id).appearance.fill_paint() != fill && node(&s, id).appearance.fill_paint().color().is_some()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": [0, 0, 1]})).unwrap(); + assert_eq!(node(&s, id).appearance.fill_paint().color().map(|c| c.to_hex()).as_deref(), Some("#0000ff")); + s.execute("swatch.new", &json!({"name": "Pure Green", "color": "#00ff00"})).unwrap(); + let green = s.doc().unwrap().doc.swatches.iter().find(|w| w.name == "Pure Green").map(|w| w.paint.clone()); + assert_eq!(green.and_then(|p| p.color()).map(|c| c.to_hex()).as_deref(), Some("#00ff00")); + let t = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a", "color": "#ff0000"})).unwrap(); + let NodeKind::Text(t) = node(&s, NodeId(t["id"].as_u64().unwrap())).kind else { panic!("not type") }; + assert_eq!(t.runs[0].style.fill.color().map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + s.execute("document.export", &json!({"format": "png", "background": "#ff0000"})).unwrap(); + s.execute("document.export", &json!({"format": "gif", "matte": "#ff0000"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72, "background": "#ff0000"})).unwrap(); +} + /// The native format writes an artboard's background color and reads it back. An artboard without /// one is written as before, with no `color` key. #[test] diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index a23e621b93..544dcce96a 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -5,7 +5,7 @@ use vectorcraft_color::Paint; use vectorcraft_doc::pattern::{PATTERN_EDIT_LAYER, RepeatKind, TileType}; use vectorcraft_doc::{Node, NodeKind}; use vectorcraft_geom::{Point, Rect}; -use vectorcraft_tools::{PointerEvent, PointerKind}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; use crate::tests_menucmds::place_undecodable_png; use crate::*; @@ -134,6 +134,72 @@ fn empty_point_type_is_not_saved_into_the_pattern() { } } +/// The same while a Cmd/Ctrl press has lent the Selection tool to the Type tool: Done or Exit +/// Isolation Mode before the release gives the Type tool back first, so the empty point type is +/// still discarded, and the release that follows leaves the tile as it is. +#[test] +fn empty_point_type_is_not_saved_into_the_pattern_during_a_cmd_press() { + for cmd in ["object.pattern.done", "object.exitIsolation"] { + let mut s = session(); + s.prefs.placeholder_text = false; + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 200.0, 200.0), v).unwrap(); + } + let press = Mods { cmd: true, ..Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 300.0).with_mods(press), v).unwrap(); + assert_eq!(s.tool_id(), "selection", "{cmd}: the press lends the Selection tool"); + s.execute(cmd, &json!({})).unwrap(); + assert_eq!(s.tool_id(), "type", "{cmd}: the Type tool is back"); + assert!(!s.tool_wants_text(), "{cmd}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0).with_mods(press), v).unwrap(); + let art = &doc(&s).pattern("P").unwrap().art; + assert_eq!(art.len(), 1, "{cmd}: the tile keeps only the square"); + assert!(!matches!(art[0].kind, NodeKind::Text(_)), "{cmd}"); + } +} + +/// Done during a drag of the lent Selection tool keeps the drag as its own step before the tile is +/// saved, so no drag is left open for the release to end. With Real-time Drawing and Editing off, +/// the drag's last position is applied first, as the release would apply it. +#[test] +fn done_during_a_lent_selection_drag_keeps_the_drag_as_its_own_step() { + for real_time in [true, false] { + let mut s = session(); + s.prefs.placeholder_text = false; + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time})).unwrap(); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); + let st = s.doc().unwrap(); + let b = st.doc.bounds_of(&st.selection.objects, false).expect("the tile art is selected"); + let c = b.center(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 200.0, 200.0), v).unwrap(); + } + let press = Mods { cmd: true, ..Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, c.x, c.y).with_mods(press), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, c.x + 20.0, c.y).with_mods(press), v).unwrap(); + assert!(s.in_interaction(), "{real_time}: the lent Selection tool drags the square"); + s.execute("object.pattern.done", &json!({})).unwrap(); + assert!(!s.in_interaction(), "{real_time}: the drag is kept before the tile is saved"); + assert_eq!(s.tool_id(), "type", "{real_time}"); + s.pointer(&PointerEvent::new(PointerKind::Up, c.x + 20.0, c.y).with_mods(press), v).unwrap(); + let labels = s.doc().unwrap().history.undo.iter().map(|e| e.label.as_str()).collect::>(); + assert_eq!(labels.last(), Some(&"Done Editing Pattern"), "{real_time}: {labels:?}"); + assert!(labels.contains(&"Move"), "{real_time}: {labels:?}"); + let art = &doc(&s).pattern("P").unwrap().art; + assert_eq!(art.len(), 1, "{real_time}: the tile keeps only the square"); + assert!(!matches!(art[0].kind, NodeKind::Text(_)), "{real_time}"); + } +} + #[test] fn cancel_new_pattern_removes_it() { let mut s = session(); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index e2bc451d97..1d0926f53a 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -102,6 +102,26 @@ fn object_filters_add_replace_and_generate_objects() { assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().last().unwrap().id, made); } +/// A generator can make guides and lock what it adds, in its one undo step; those objects are left +/// out of the selection that follows, as Make Guides and Object › Lock leave them. +#[test] +fn filters_make_guides_and_locked_objects_left_unselected() { + let mut s = session(); + let out = json!({"objects": [ + {"path": triangle(), "name": "Guide", "guide": true}, + {"path": triangle(), "name": "Locked", "locked": true}, + {"path": triangle(), "name": "Plain"}]}); + install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.guides", "filter", "{}"), &out.to_string())); + let undo = s.doc().unwrap().history.undo.len(); + let r = run(&mut s, "plugin.run", json!({"id": "test.engine.guides"})); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert!(matches!(node(&s, ids[0]).kind, vectorcraft_doc::NodeKind::Path { guide: true, .. })); + assert!(node(&s, ids[1]).locked); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, [ids[2]]); + assert_eq!(st.history.undo.len(), undo + 1); +} + #[test] fn failing_plugins_leave_the_document_and_history_alone() { let mut s = session(); diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index b590e3c289..87b943d6c1 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -1474,6 +1474,29 @@ fn missing_glyph_protection_keeps_the_version_of_the_font_kept() { assert_eq!(versions, [moved.clone(), kept, moved]); } +/// The font warning of `text.setStyle` and `text.setRangeStyle` names only the fonts the command +/// set: a character that keeps an unavailable font through Missing Glyph Protection isn't reported. +#[test] +fn missing_glyph_protection_leaves_the_font_kept_out_of_the_warning() { + let (from, to, c) = ("No Such Font Family", "JetBrains Mono", '\u{180}'); + let db = vectorcraft_text::FontDb::global(); + // The unavailable family is drawn in the fallback font, which has the character; the new font is installed and lacks it. + let installed = db.resolve(to, "Regular").is_some_and(|(_, m)| m == vectorcraft_text::FontMatch::Exact); + if !installed || !db.face(from, "Regular").is_some_and(|f| f.covers(c)) || db.face(to, "Regular").is_some_and(|f| f.covers(c)) { + return; // The fonts installed here cover other characters. + } + let mut s = new_doc(); + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 50, "text": "a\u{180}c", "font": from})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + for change in [json!({"font": to}), json!({"id": id.0, "start": 0, "end": 4, "font": to})] { + let cmd = if change.get("id").is_some() { "text.setRangeStyle" } else { "text.setStyle" }; + let out = s.execute(cmd, &change).unwrap(); + assert_eq!(style_at(&s, id, 1).font_family, from, "{cmd}: the character keeps its font"); + assert_eq!(out.get("warning"), None, "{cmd}: {out}"); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + // ---------- #394, fourth batch ---------- /// Type › Type Object Selection by Path Only (#394): on, a click among point type's glyphs no diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index cff302503d..541f961b81 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -292,6 +292,12 @@ fn methods_and_bad_params() { select_all(&mut s); assert!(s.execute("recolor.apply", &json!({"map": {"#ff0000": "#00ff00"}, "method": "nope"})).is_err()); assert!(s.execute("recolor.apply", &json!({"map": {"#ff0000": "nonsense"}})).is_err()); + // A current or new color with an alpha part (`#rrggbbaa` or `#rgba`) is refused. + let undo = s.doc().unwrap().history.undo.len(); + for (from, to) in [("#ff000080", "#00ff00"), ("ff000080", "#00ff00"), ("#ff0000", "#00ff0080"), ("#ff0000", "#0f08")] { + assert!(s.execute("recolor.apply", &json!({"map": {from: to}})).is_err(), "{from} {to}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); assert!(s.execute("recolor.apply", &json!({})).is_err()); run(&mut s, "select.none", json!({})); assert!(s.execute("recolor.apply", &json!({"map": {}})).is_err(), "needs art or a group"); diff --git a/crates/engine/src/tests/slices.rs b/crates/engine/src/tests/slices.rs index eee1a47694..1576f50ce3 100644 --- a/crates/engine/src/tests/slices.rs +++ b/crates/engine/src/tests/slices.rs @@ -199,6 +199,8 @@ fn slice_options_set_read_and_undo_in_one_step() { assert_eq!(slices(&mut s)[0]["name"], "cell"); assert!(s.execute("object.slice.options", &json!({"kind": "htmlText"})).is_err(), "HTML Text is for type"); assert!(s.execute("object.slice.options", &json!({"background": "pink-ish"})).is_err()); + assert!(s.execute("object.slice.options", &json!({"background": "#00ff0080"})).is_err(), "a hex color with an alpha part"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); run(&mut s, "edit.undo", json!({})); assert_eq!(s.doc().unwrap().doc.slices[0].options, Default::default()); // An object slice of type can be HTML Text. diff --git a/crates/engine/src/tests/swatches.rs b/crates/engine/src/tests/swatches.rs index 406c269262..c0145d20d4 100644 --- a/crates/engine/src/tests/swatches.rs +++ b/crates/engine/src/tests/swatches.rs @@ -192,6 +192,694 @@ fn document_color_mode_converts_the_tile_that_pattern_cancel_puts_back() { assert_eq!(tile, [red]); } +/// The `color` stored in each effect of `a` (the object's, then each fill's and stroke's) that has +/// one, read as a color, and the `lightColor` of each effect that has one. +fn effect_colors(a: &vectorcraft_doc::Appearance) -> (Vec, Vec) { + let effects: Vec<&vectorcraft_doc::Effect> = a.effects.iter().chain(a.items.iter().flat_map(|i| i.effects())).collect(); + let colors = effects + .iter() + .filter_map(|e| e.params.get("color")) + .map(|v| v.as_str().map_or_else(|| serde_json::from_value(v.clone()).unwrap(), |h| Color::from_hex(h).unwrap())) + .collect(); + (colors, effects.iter().filter_map(|e| e.params.get("lightColor").cloned()).collect()) +} + +/// Document Color Mode converts the colors that effects draw with, on objects (the effects of a +/// fill included) and in graphic styles, as it converts the art. An effect that drew its default +/// color keeps the converted default as its own; the light color of a 3D effect stays RGB. The +/// reply counts the object's effect colors, and one undo step takes them back. +#[test] +fn document_color_mode_converts_effect_colors() { + let build = |effects: bool| { + let mut s = session(); + let id = rect(&mut s); + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [id.0]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [id.0]})); + if effects { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": {"color": "#ff0000"}})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "stylize.outerGlow", "item": null})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "stylize.innerGlow", "item": 0, "params": {"color": "#ff0000"}})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "threeD.rotate", "item": null})); + // The Outer Glow draws its default color, as in a file that leaves `color` out. + s.edit("Default color", |d, _| { + let glow = &mut d.node_mut(id).unwrap().appearance.effects[1]; + assert_eq!(glow.id, "stylize.outerGlow"); + if let Some(p) = glow.params.as_object_mut() { + p.remove("color"); + } + Ok(()) + }) + .unwrap(); + } + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "graphicStyle.new", json!({"name": "Glow"})); + (s, id) + }; + let (mut s, id) = build(true); + let object = |s: &Session| effect_colors(&doc(s).node(id).unwrap().appearance); + let style = |s: &Session| effect_colors(&doc(s).graphic_style("Glow").unwrap().appearance); + let before = (object(&s), style(&s)); + assert_eq!(before.0.0.len(), 2, "the Outer Glow stores no color: {before:?}"); + assert_eq!(before.1.0.len(), 2, "{before:?}"); + let undo = s.doc().unwrap().history.undo.len(); + + let changed = run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}))["changed"].as_u64().unwrap(); + let red = first_fill(doc(&s).node(id).unwrap()); + assert!(matches!(red, Color::Cmyk { .. }), "{red:?}"); + for (colors, lights) in [object(&s), style(&s)] { + assert_eq!(colors.len(), 3, "{colors:?}"); + // Drop Shadow, then the Outer Glow's default yellow, then the fill's Inner Glow. + assert_eq!([colors[0], colors[2]], [red; 2]); + assert!(matches!(colors[1], Color::Cmyk { .. }), "{colors:?}"); + assert_eq!(lights, [json!("#ffffff")]); + } + // The three effect colors on the object count; those of the graphic style, like its paints, do not. + let (mut plain, _) = build(false); + let without = run(&mut plain, "file.documentColorMode", json!({"mode": "cmyk"}))["changed"].as_u64().unwrap(); + assert_eq!(changed, without + 3); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!((object(&s), style(&s)), before); +} + +/// Document Color Mode converts the series paints and label styles a graph keeps, so a graph drawn +/// again after the switch paints its series and labels in the new mode. +#[test] +fn document_color_mode_converts_the_paints_a_graph_keeps() { + let mut s = session(); + let red = rect(&mut s); + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [red.0]})); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let id = NodeId( + run(&mut s, "graph.create", json!({"type": "column", "x": 10, "y": 10, "width": 60, "height": 40, "csv": csv}))["id"].as_u64().unwrap(), + ); + let part = |s: &Session, name: &str| -> vectorcraft_doc::Node { + let g = doc(s).node(id).unwrap(); + g.children().unwrap().iter().find(|c| c.name.as_deref() == Some(name)).map(|c| (**c).clone()).unwrap_or_else(|| panic!("no {name}")) + }; + let series = part(&s, "2024").id; + let label = part(&s, "Axes").children().unwrap().iter().find(|c| matches!(c.kind, vectorcraft_doc::NodeKind::Text(_))).unwrap().id; + for target in [series, label] { + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [target.0]})); + } + let kept = |s: &Session| -> Vec { + let g = doc(s).node(id).unwrap().extras().graph.as_deref().unwrap().clone(); + let labels = [g.label_styles.values, g.label_styles.categories, g.label_styles.legend]; + let labels = labels.into_iter().flatten().map(|st| st.fill.color().unwrap()); + g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).collect() + }; + let before = kept(&s); + assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 2]); + let undo = s.doc().unwrap().history.undo.len(); + + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + let cmyk = first_fill(doc(&s).node(red).unwrap()); + assert!(matches!(cmyk, Color::Cmyk { .. }), "{cmyk:?}"); + assert_eq!(kept(&s), [cmyk; 2]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + // Drawn again from new data, the series keeps the converted color. + run(&mut s, "graph.setData", json!({"id": id.0, "rows": [[2, 3], [4, 5]]})); + let marks = part(&s, "2024"); + assert!(marks.children().unwrap().iter().all(|m| m.appearance.fill_paint().color() == Some(cmyk)), "{marks:?}"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(kept(&s), before); +} + +/// Document Color Mode converts the fill and stroke that new art takes, so an object drawn after +/// the switch gets the same colors in the new mode as the art drawn before it. +#[test] +fn document_color_mode_converts_the_colors_new_art_takes() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"color": "#0000ff"})); + let old = rect(&mut s); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + let paints = |a: &vectorcraft_doc::Appearance| (a.fill_paint().color(), a.stroke().and_then(|st| st.paint.color())); + let converted = paints(&doc(&s).node(old).unwrap().appearance); + assert!(matches!(converted, (Some(Color::Cmyk { .. }), Some(Color::Cmyk { .. }))), "{converted:?}"); + assert_eq!(paints(&s.new_art()), converted); + let new = rect(&mut s); + assert_eq!(paints(&doc(&s).node(new).unwrap().appearance), converted); + + // As a `command.batch` step too; a batch that fails leaves them as they were. + for fails in [false, true] { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"color": "#0000ff"})); + let before = paints(&s.new_art()); + let mut steps = vec![json!({"command": "file.documentColorMode", "params": {"mode": "cmyk"}})]; + if fails { + steps.push(json!({"command": "no.such.command"})); + } + let r = s.execute("command.batch", &json!({"commands": steps})); + assert_eq!(r.is_err(), fails, "{r:?}"); + assert_eq!(paints(&s.new_art()), if fails { before } else { converted }, "fails {fails}"); + } +} + +#[test] +fn color_mode_undo_restores_original_new_art_colors_and_redo_reapplies_them() { + for batch in [false, true] { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + run(&mut s, "paint.setStroke", json!({"color": "#123456"})); + let before = s.paint.clone(); + if batch { + run( + &mut s, + "command.batch", + json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}} + ]}), + ); + } else { + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + } + let after = s.paint.clone(); + assert_ne!(before.fill, after.fill); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before, "batch {batch}: exact original values"); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after, "batch {batch}"); + let id = rect(&mut s); + assert_eq!(doc(&s).node(id).unwrap().appearance.fill_paint(), after.fill); + } +} + +#[test] +fn color_mode_batch_undo_restores_paints_from_before_the_batch() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + let before = s.paint.clone(); + run( + &mut s, + "command.batch", + json!({"commands": [ + {"command": "paint.setFill", "params": {"color": "#0000ff"}}, + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}} + ]}), + ); + let after = s.paint.clone(); + assert_ne!(before.fill, after.fill); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); +} + +#[test] +fn color_mode_group_undo_restores_paints_from_before_the_group() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + let before = s.paint.clone(); + s.begin_undo_group(); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + s.end_undo_group(false); + let after = s.paint.clone(); + assert_ne!(before.fill, after.fill); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); +} + +/// Undo and Redo of an undo group that converts the document color mode and then changes the +/// stroke weight of new art restore the whole new-art template, not only its paints. +#[test] +fn color_mode_group_undo_restores_the_new_art_stroke_weight() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + let before = s.paint.clone(); + s.begin_undo_group(); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + run(&mut s, "stroke.set", json!({"weight": 7})); + s.end_undo_group(false); + let after = s.paint.clone(); + assert_eq!(after.stroke_width, 7.0); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); +} + +/// With New Art Has Basic Appearance off, Redo of a batch that converts the color mode and then +/// applies an effect to the selected object restores the appearance new art took from that object. +#[test] +fn color_mode_batch_redo_keeps_the_appearance_new_art_inherited() { + let mut s = session(); + run(&mut s, "prefs.set", json!({"key": "newArtBasic", "value": false})); + rect(&mut s); + run( + &mut s, + "command.batch", + json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "effect.apply", "params": {"effect": "stylize.dropShadow"}} + ]}), + ); + let after = s.paint.clone(); + assert!(after.appearance.is_some()); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); +} + +/// Redo of a batch or undo group that converts the document color mode and then changes the paints +/// new art takes restores the paints as the whole step left them. +#[test] +fn color_mode_redo_of_a_group_restores_the_paints_the_group_left() { + let converted = { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + s.paint.clone() + }; + for batch in [false, true] { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + let before = s.paint.clone(); + if batch { + run( + &mut s, + "command.batch", + json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "paint.setFill", "params": {"color": "#0000ff"}} + ]}), + ); + } else { + s.begin_undo_group(); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + s.end_undo_group(false); + } + let after = s.paint.clone(); + assert_ne!(after.fill, converted.fill, "batch {batch}"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before, "batch {batch}"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after, "batch {batch}: the group's final paints"); + } +} + +fn color_mode_restores_paints_when_conversion_changes_none(batch: bool, convert: bool) { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"none": true})); + run(&mut s, "paint.setStroke", json!({"none": true})); + let before = s.paint.clone(); + assert!(before.fill.is_none()); + assert!(before.stroke.is_none()); + if batch { + run( + &mut s, + "command.batch", + json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk", "convert": convert}}, + {"command": "paint.setFill", "params": {"color": "#0000ff"}} + ]}), + ); + } else { + s.begin_undo_group(); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk", "convert": convert})); + assert_eq!(s.paint, before, "the conversion leaves both paints unchanged"); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + s.end_undo_group(false); + } + let after = s.paint.clone(); + assert_ne!(after.fill, before.fill); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk); + run(&mut s, "edit.undo", json!({})); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before, "batch {batch}: undo restores the group's starting paints"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk); + assert_eq!(s.paint, after, "batch {batch}: redo restores the group's final paints"); +} + +#[test] +fn color_mode_group_restores_paints_when_conversion_changes_none() { + color_mode_restores_paints_when_conversion_changes_none(false, true); +} + +#[test] +fn color_mode_batch_restores_paints_when_conversion_changes_none() { + color_mode_restores_paints_when_conversion_changes_none(true, true); +} + +#[test] +fn color_mode_group_without_conversion_restores_paints() { + color_mode_restores_paints_when_conversion_changes_none(false, false); +} + +#[test] +fn color_mode_batch_without_conversion_restores_paints() { + color_mode_restores_paints_when_conversion_changes_none(true, false); +} + +#[test] +fn color_mode_ungrouped_skips_unchanged_paint_snapshot() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"none": true})); + run(&mut s, "paint.setStroke", json!({"none": true})); + let before = s.paint.clone(); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + assert_eq!(s.paint, before); + assert!(s.doc().unwrap().history.undo.last().unwrap().color_mode_paints.is_none()); + run(&mut s, "edit.undo", json!({})); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk); + assert_eq!(s.paint, before); +} + +/// A failing batch that settles a pending color-mode preview keeps the converted paints with the +/// converted document. +#[test] +fn a_failed_batch_keeps_the_paints_of_a_settled_color_mode_preview() { + let converted = { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + s.paint.clone() + }; + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + s.begin_interaction("Document Color Mode").unwrap(); + s.preview("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let r = s.execute("command.batch", &json!({"commands": [{"command": "no.such.command", "params": {}}]})); + assert!(r.is_err()); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk); + assert_eq!(s.paint, converted); +} + +#[test] +fn canceling_a_batch_preview_restores_the_document_and_paints() { + let mut s = color_mode_preview_session(false); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + let journal = s.journal.len(); + s.begin_interaction("Batch Preview").unwrap(); + s.preview("command.batch", &json!({"commands": [{"command": "file.documentColorMode", "params": {"mode": "cmyk"}}]})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + assert_eq!(s.journal.len(), journal); +} + +#[test] +fn accepting_a_batch_preview_restores_new_art_paints_on_undo_and_redo() { + let mut s = color_mode_preview_session(false); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + let journal = s.journal.len(); + s.begin_interaction("Batch Preview").unwrap(); + s.preview("command.batch", &json!({"commands": [{"command": "file.documentColorMode", "params": {"mode": "cmyk"}}]})).unwrap(); + assert_eq!(s.paint, before); + s.commit_interaction().unwrap(); + let after = s.paint.clone(); + assert_ne!(after.fill, before.fill); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1); + assert_eq!(s.journal.len(), journal + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk); + assert_eq!(s.paint, after); +} + +#[test] +fn batch_preview_with_later_paint_restores_or_keeps_the_final_paint() { + let commands = json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "paint.setFill", "params": {"color": "#123456"}} + ]}); + let mut expected = color_mode_preview_session(false); + run(&mut expected, "command.batch", commands.clone()); + let final_paint = expected.paint.clone(); + + let mut s = color_mode_preview_session(false); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + let journal = s.journal.len(); + s.begin_interaction("Batch Preview").unwrap(); + s.preview("command.batch", &commands).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + assert_eq!(s.journal.len(), journal); + + s.begin_interaction("Batch Preview").unwrap(); + s.preview("command.batch", &commands).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(s.paint, final_paint); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1); + assert_eq!(s.journal.len(), journal + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, final_paint); +} + +#[test] +fn failed_batch_preview_leaves_no_document_paint_or_journal_change() { + let mut s = color_mode_preview_session(false); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + let journal = s.journal.len(); + s.begin_interaction("Batch Preview").unwrap(); + s.preview( + "command.batch", + &json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "paint.setFill", "params": {"color": "#654321"}} + ]}), + ) + .unwrap(); + let result = s.preview( + "command.batch", + &json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "paint.setFill", "params": {"color": "#123456"}}, + {"command": "no.such.command", "params": {}} + ]}), + ); + assert!(result.is_err()); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before); + s.cancel_interaction().unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + assert_eq!(s.journal.len(), journal); +} + +#[test] +fn batch_preview_restores_paint_when_mode_conversion_does_not_change_it() { + let mut s = session(); + s.paint.fill = Paint::None; + s.paint.stroke = Paint::None; + s.paint.appearance = None; + let before = s.paint.clone(); + let commands = json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "paint.setFill", "params": {"color": "#123456"}} + ]}); + s.begin_interaction("Batch Preview").unwrap(); + s.preview("command.batch", &commands).unwrap(); + s.commit_interaction().unwrap(); + let after = s.paint.clone(); + assert_ne!(after, before); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); +} + +#[test] +fn batch_preview_that_switches_documents_rolls_back_every_step() { + let mut s = color_mode_preview_session(false); + let before = s.paint.clone(); + let journal = s.journal.len(); + let docs = s.docs.len(); + let active = s.active; + s.begin_interaction("Batch Preview").unwrap(); + let result = s.preview( + "command.batch", + &json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "file.new", "params": {"width": 100, "height": 100}} + ]}), + ); + assert!(result.is_err()); + assert_eq!(s.docs.len(), docs); + assert_eq!(s.active, active); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before); + s.cancel_interaction().unwrap(); + assert_eq!(s.journal.len(), journal); +} + +#[test] +fn color_mode_undo_restores_template_paints_and_effect_colors() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + run(&mut s, "paint.setStroke", json!({"color": "#123456"})); + let mut appearance = s.new_art(); + appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: json!({"color":"#d37a42"}), visible: true }); + s.paint.appearance = Some(appearance); + let before = s.paint.clone(); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + let after = s.paint.clone(); + assert_ne!(before.appearance, after.appearance); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); + let id = rect(&mut s); + assert_eq!(doc(&s).node(id).unwrap().appearance.effects, after.appearance.unwrap().effects); +} + +#[test] +fn color_mode_cancelled_joined_scope_restores_paints_and_history_metadata() { + for converted_before_scope in [false, true] { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + let original = s.paint.clone(); + s.begin_undo_group(); + rect(&mut s); + if converted_before_scope { + run(&mut s, "file.documentColorMode", json!({"mode":"cmyk"})); + } + let before_scope = s.paint.clone(); + let mode = doc(&s).color_mode; + let scope = s.begin_undo_scope().unwrap(); + run(&mut s, "file.documentColorMode", json!({"mode": if converted_before_scope {"rgb"} else {"cmyk"}})); + s.end_undo_scope(scope, true); + assert_eq!(s.paint, before_scope); + assert_eq!(doc(&s).color_mode, mode); + s.end_undo_group(false); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, if converted_before_scope { original } else { before_scope.clone() }); + run(&mut s, "edit.redo", json!({})); + assert_eq!(doc(&s).color_mode, mode); + assert_eq!(s.paint, before_scope, "redo must not reapply the cancelled conversion"); + } +} + +fn color_mode_preview_session(selected: bool) -> Session { + let mut s = session(); + if selected { + rect(&mut s); + } + run(&mut s, "paint.setFill", json!({"color": "#808080"})); + run(&mut s, "paint.setStroke", json!({"color": "#123456"})); + let mut appearance = s.new_art(); + appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: json!({"color":"#d37a42"}), visible: true }); + s.paint.appearance = Some(appearance); + s +} + +#[test] +fn color_mode_preview_commit_converts_new_art_once_and_keeps_exact_history() { + for selected in [false, true] { + let mut s = color_mode_preview_session(selected); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + let mut expected = color_mode_preview_session(false); + expected.paint = before.clone(); + run(&mut expected, "file.documentColorMode", json!({"mode":"cmyk", "grays":"black"})); + // The template is intentionally independent from selected artwork. + let after = expected.paint.clone(); + s.begin_interaction("Document Color Mode").unwrap(); + for grays in ["profile", "black", "profile", "black"] { + s.preview("file.documentColorMode", &json!({"mode":"cmyk", "grays":grays})).unwrap(); + assert_eq!(s.paint, before, "preview must leave new-art paints tentative"); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + } + s.commit_interaction().unwrap(); + assert_eq!(s.paint, after); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1); + let e = s.doc().unwrap().history.undo.last().unwrap(); + assert_eq!(e.color_mode_paints, Some((before.clone(), after.clone()))); + let history_bytes = e.bytes; + assert!(history_bytes >= 2 * std::mem::size_of::()); + for _ in 0..3 { + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.doc().unwrap().history.redo.last().unwrap().color_mode_paints, Some((before.clone(), after.clone()))); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().bytes, history_bytes); + } + s.commit_interaction().unwrap(); + assert_eq!(s.paint, after, "a second commit cannot convert twice"); + } +} + +#[test] +fn color_mode_preview_cancel_replacement_and_failure_do_not_convert_new_art() { + for finish in ["cancel", "noop", "failed", "mode-only"] { + let mut s = color_mode_preview_session(true); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + s.begin_interaction("Document Color Mode").unwrap(); + s.preview("file.documentColorMode", &json!({"mode":"cmyk"})).unwrap(); + match finish { + "cancel" => s.cancel_interaction().unwrap(), + "noop" => { + s.preview("file.documentColorMode", &json!({"mode":"rgb"})).unwrap(); + s.commit_interaction().unwrap(); + } + "failed" => { + assert!(s.preview("file.documentColorMode", &json!({"mode":"invalid"})).is_err()); + s.commit_interaction().unwrap(); + } + _ => { + s.preview("file.documentColorMode", &json!({"mode":"cmyk", "convert":false})).unwrap(); + s.commit_interaction().unwrap(); + } + } + assert_eq!(s.paint, before, "{finish}"); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + usize::from(finish == "mode-only"), "{finish}"); + } +} + +#[test] +fn color_mode_preview_commit_joins_paint_history_and_group_cancel_restores_it() { + for cancel in [false, true] { + let mut s = color_mode_preview_session(false); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + s.begin_undo_group(); + // Existing grouped metadata must keep its original snapshot when the preview commits. + run(&mut s, "file.documentColorMode", json!({"mode":"cmyk"})); + s.begin_interaction("Document Color Mode").unwrap(); + s.preview("object.convertDocumentColorMode", &json!({"mode":"rgb"})).unwrap(); + s.commit_interaction().unwrap(); + let after = s.paint.clone(); + let e = s.doc().unwrap().history.undo.last().unwrap(); + assert_eq!(e.color_mode_paints, Some((before.clone(), after.clone()))); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1); + s.end_undo_group(cancel); + if cancel { + assert_eq!(s.paint, before); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + } else { + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); + } + } +} + #[test] fn grouped_spot_swatches_print_on_their_own_plate() { let mut s = session(); @@ -529,6 +1217,82 @@ fn global_swatch_edits_reach_opacity_mask_art() { assert_eq!(mask_fill(&s).color(), Some(Color::rgb(1.0, 1.0, 1.0))); } +#[test] +fn color_mode_converts_freeform_defaults_templates_and_stored_graph_paints() { + use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint}; + let mut s = session(); + let id = NodeId( + run( + &mut s, + "graph.create", + json!({"type":"column", "x":0, "y":0, "width":60, "height":40, + "csv":",2024\nQ1,3\nQ2,5"}), + )["id"] + .as_u64() + .unwrap(), + ); + let mut gradient = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![])); + gradient.set_freeform(Freeform { + points: vec![ + FreeformPoint::new((0.0, 0.0).into(), Color::rgb(0.8, 0.2, 0.1)), + FreeformPoint::new((20.0, 10.0).into(), Color::rgb(0.1, 0.3, 0.9)), + ], + lines: vec![vec![0, 1]], + ..Default::default() + }); + let paint = Paint::Gradient(Box::new(gradient)); + s.edit("Stored graph paint", |d, _| { + d.node_mut(id).unwrap().extras_mut().graph.as_mut().unwrap().series_paints = + vec![vectorcraft_doc::SeriesPaint { fill: Some(paint.clone()), stroke: Some(paint.clone()), ..Default::default() }]; + Ok(()) + }) + .unwrap(); + s.paint.fill = paint.clone(); + s.paint.stroke = paint.clone(); + s.paint.stroke_width = 1.0; + s.paint.appearance = None; + s.paint.appearance = Some(s.new_art()); + let before = s.paint.clone(); + let stored = |s: &Session| doc(s).node(id).unwrap().extras().graph.as_ref().unwrap().series_paints.clone(); + let before_graph = stored(&s); + run(&mut s, "file.documentColorMode", json!({"mode":"cmyk"})); + let after = s.paint.clone(); + let after_graph = stored(&s); + let converted = |paint: &Paint| { + let Paint::Gradient(g) = paint else { panic!("expected gradient") }; + assert!(g.gradient.stops.iter().all(|p| matches!(p.color, Color::Cmyk { .. }))); + assert!(g.freeform.as_ref().unwrap().points.iter().all(|p| matches!(p.color, Color::Cmyk { .. }))); + }; + converted(&after.fill); + converted(&after.stroke); + converted(&after.appearance.as_ref().unwrap().fill_paint()); + converted(&after.appearance.as_ref().unwrap().stroke().unwrap().paint); + converted(after_graph[0].fill.as_ref().unwrap()); + converted(after_graph[0].stroke.as_ref().unwrap()); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + assert_eq!(stored(&s), before_graph); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); + assert_eq!(stored(&s), after_graph); + let new = rect(&mut s); + let new_fill = doc(&s).node(new).unwrap().appearance.fill_paint(); + converted(&new_fill); + let control_colors = |paint: &Paint| { + let Paint::Gradient(g) = paint else { panic!("expected gradient") }; + g.freeform.as_ref().unwrap().points.iter().map(|p| p.color).collect::>() + }; + assert_eq!(control_colors(&new_fill), control_colors(&after.fill)); + run(&mut s, "graph.setData", json!({"id":id.0, "rows":[[2], [4]]})); + assert_eq!(stored(&s), after_graph); + let graph = doc(&s).node(id).unwrap(); + let series = graph.children().unwrap().iter().find(|n| n.name.as_deref() == Some("2024")).unwrap(); + for mark in series.children().unwrap() { + converted(&mark.appearance.fill_paint()); + converted(&mark.appearance.stroke().unwrap().paint); + } +} + /// The fills of graph design "Bar" and of the art of brush "Holder", as `place: color, link`. fn fills_outside_the_layers(s: &Session) -> Vec { let d = doc(s); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index fa73e9d50c..923cd1d12a 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -2294,3 +2294,292 @@ fn a_family_without_its_style_takes_its_closest_style() { s.execute("text.setStyle", &json!({"ids": [set.0], "font": FAMILY})).unwrap(); assert_eq!(style(&s, set), "W6", "a style the family has is kept"); } + +/// The Glyphs panel's Show › Alternates for Current Selection: `text.glyphAlternates` lists a +/// character's alternates and `text.setGlyphAlternate` draws one of them, a glyph no character maps +/// to, in place of that character alone, as one undo step that native files keep. +#[test] +fn a_glyph_alternate_replaces_one_character_through_undo_and_reopen() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(alternates_font(true).expect("the test font builds")); + let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let face = db.face(alternates_family(true), "Regular").expect("the test face"); + let g = |c| face.glyph_for(c); + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xaay", "size": 20, "font": alternates_family(true)})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 4, "underline": true})).unwrap(); + let gids = |t: &TextObject| vectorcraft_text::layout(db, t).glyphs.iter().map(|g| g.gid).collect::>(); + assert_eq!(gids(&obj(&s, id)), [g('x'), g('a'), g('a'), g('y')]); + + let listed = s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 2})).unwrap(); + assert_eq!((listed["char"].clone(), listed["default"].clone(), listed["chosen"].clone()), (json!("a"), json!(g('a')), json!(g('a')))); + assert_eq!(listed["alternates"][1], json!({"gid": u1, "feature": "aalt"})); + assert_eq!(listed["font"], json!(alternates_family(true))); + + // Create Outlines, undone at once: the bounds of the outlines. + let outlines = |s: &mut Session| { + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let group = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let bounds: Vec = d.node(NodeId(group)).unwrap().children().unwrap().iter().filter_map(|c| c.geometric_bounds()).collect(); + s.execute("edit.undo", &json!({})).unwrap(); + bounds + }; + let default = outlines(&mut s); + + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 2, "gid": u1})).unwrap(); + assert_eq!(r, json!({"id": id.0, "start": 2, "end": 3, "gid": u1})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert_eq!(undo_labels(&s).last().map(String::as_str), Some("Glyphs")); + let t = obj(&s, id); + assert_eq!(t.plain_text(), "xaay", "the text keeps the character"); + assert!(t.runs.iter().all(|r| r.style.underline), "its other attributes are kept"); + assert_eq!(gids(&t), [g('x'), g('a'), u1, g('y')], "the second a alone"); + assert_eq!(s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 2})).unwrap()["chosen"], json!(u1)); + + assert_ne!(outlines(&mut s), default, "Create Outlines draws the chosen glyph"); + + // Native files keep the choice. + let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc); + let opened = vectorcraft_format::load(&bytes).unwrap(); + let NodeKind::Text(reopened) = &opened.node(id).unwrap().kind else { panic!("text missing") }; + assert_eq!(gids(reopened), [g('x'), g('a'), u1, g('y')], "reopened"); + // A font that is not installed draws the fallback font's default glyph. + let mut missing = (**reopened).clone(); + for r in &mut missing.runs { + r.style.font_family = "No Such Font Family".into(); + } + let fallback = db.face("No Such Font Family", "Regular").expect("the fallback face"); + assert_eq!(gids(&missing)[2], fallback.glyph_for('a'), "a missing font: the default glyph"); + + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(gids(&obj(&s, id)), [g('x'), g('a'), g('a'), g('y')], "undone"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(gids(&obj(&s, id)), [g('x'), g('a'), u1, g('y')], "redone"); + + // The default glyph puts the character back, as null does. + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 2, "gid": g('a')})).unwrap(); + assert_eq!(r["gid"], json!(g('a'))); + assert!(obj(&s, id).runs.iter().all(|r| r.style.glyph_alternate.is_none())); + s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": u1})).unwrap(); + s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": null})).unwrap(); + assert_eq!(gids(&obj(&s, id)), [g('x'), g('a'), g('a'), g('y')]); + + let err = |s: &mut Session, p: Value| s.execute("text.setGlyphAlternate", &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({"id": id.0, "start": 2, "gid": g('z')})).contains("is not an alternate")); + assert!(err(&mut s, json!({"id": id.0, "start": 3, "gid": u1})).contains("is not an alternate"), "y has none"); + assert!(err(&mut s, json!({"id": id.0, "start": 4, "gid": u1})).contains("no character at byte 4")); + assert!(err(&mut s, json!({"id": id.0, "start": 2})).contains("missing `gid`")); + assert!(err(&mut s, json!({"id": id.0, "start": 2, "gid": -1})).contains("must be a glyph id")); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 2, "end": 3, "font": "No Such Font Family"})).unwrap(); + assert!(err(&mut s, json!({"id": id.0, "start": 2, "gid": u1})).contains("is not available")); + assert!(s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 2})).unwrap_err().to_string().contains("is not available")); +} + +/// The glyph already drawn, chosen again, and null for a character drawn with its default glyph +/// leave the document and its undo history as they are. An empty run before the character does +/// not stand in for the character's own choice. +#[test] +fn a_glyph_alternate_already_drawn_is_not_an_edit() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(alternates_font(true).expect("the test font builds")); + let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let face = db.face(alternates_family(true), "Regular").expect("the test face"); + let mut s = session(); + let create = |s: &mut Session, y: f64| { + let r = s.execute("text.create", &json!({"x": 100, "y": y, "text": "xaay", "size": 20, "font": alternates_family(true)})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) + }; + let id = create(&mut s, 100.0); + s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 2, "gid": u1})).unwrap(); + let state = |s: &Session| (s.doc().unwrap().history.undo.len(), s.doc().unwrap().revision); + let before = state(&s); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 2, "gid": u1})).unwrap(); + assert_eq!(r, json!({"id": id.0, "start": 2, "end": 3, "gid": u1})); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": null})).unwrap(); + assert_eq!(r, json!({"id": id.0, "start": 1, "end": 2, "gid": face.glyph_for('a')})); + assert_eq!(state(&s), before, "no edit"); + + // An empty run that holds the choice, as a file may have, right before the first a. + let other = create(&mut s, 150.0); + let mut runs = obj(&s, other).runs; + let mut empty = vectorcraft_doc::TextRun { text: String::new(), ..runs[0].clone() }; + empty.style.glyph_alternate = Some(face.choice('a', u1)); + runs = vec![ + vectorcraft_doc::TextRun { text: "x".into(), ..runs[0].clone() }, + empty, + vectorcraft_doc::TextRun { text: "aay".into(), ..runs[0].clone() }, + ]; + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let Some(NodeKind::Text(text)) = doc.node_mut(other).map(|n| &mut n.kind) else { panic!("text") }; + text.runs = runs; + s.execute("text.setGlyphAlternate", &json!({"id": other.0, "start": 1, "gid": u1})).unwrap(); + let gids: Vec = vectorcraft_text::layout(db, &obj(&s, other)).glyphs.iter().map(|g| g.gid).collect(); + assert_eq!(gids[1], u1, "the a takes the choice: {gids:?}"); + + // A run that holds the choice and goes on past its first character, as a file may have: the + // request splits it, so the character is shaped alone. + let shared = create(&mut s, 200.0); + let mut runs = obj(&s, shared).runs; + let mut chosen = vectorcraft_doc::TextRun { text: "aay".into(), ..runs[0].clone() }; + chosen.style.glyph_alternate = Some(face.choice('a', u1)); + runs = vec![vectorcraft_doc::TextRun { text: "x".into(), ..runs[0].clone() }, chosen]; + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let Some(NodeKind::Text(text)) = doc.node_mut(shared).map(|n| &mut n.kind) else { panic!("text") }; + text.runs = runs; + let before = state(&s); + s.execute("text.setGlyphAlternate", &json!({"id": shared.0, "start": 1, "gid": u1})).unwrap(); + assert_eq!(state(&s).0, before.0 + 1, "an edit"); + let texts: Vec = obj(&s, shared).runs.iter().map(|r| r.text.clone()).collect(); + assert_eq!(texts, ["x", "a", "ay"]); +} + +/// A glyph the character's style keeps from being drawn (here All Caps draws the a as A) is an +/// error, and the document and its undo history are left as they were. +#[test] +fn a_glyph_alternate_that_the_style_does_not_draw_is_an_error() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; + let _fonts = crate::adding_fonts(); + vectorcraft_text::FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xaay", "size": 20, "font": alternates_family(true)})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 4, "allCaps": true})).unwrap(); + let state = |s: &Session| (s.doc().unwrap().history.undo.len(), s.doc().unwrap().revision); + let before = state(&s); + let err = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": u1})).unwrap_err(); + assert!(err.to_string().contains("is not drawn"), "{err}"); + assert_eq!(state(&s), before, "no edit"); + assert!(obj(&s, id).runs.iter().all(|r| r.style.glyph_alternate.is_none())); +} + +/// With a style feature that draws another glyph (`salt` draws the a as b), choosing the default +/// glyph draws it, and `gid: null` takes the choice away and reports the glyph the feature draws. +#[test] +fn the_default_glyph_chosen_under_a_substituting_feature_is_drawn() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(alternates_font(true).expect("the test font builds")); + let face = db.face(alternates_family(true), "Regular").expect("the test face"); + let g = |c| face.glyph_for(c); + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xaay", "size": 20, "font": alternates_family(true)})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 4, "features": ["salt"]})).unwrap(); + let gids = |s: &Session| vectorcraft_text::layout(db, &obj(s, id)).glyphs.iter().map(|g| g.gid).collect::>(); + assert_eq!(gids(&s), [g('x'), g('b'), g('b'), g('y')], "salt draws each a as b"); + + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": g('a')})).unwrap(); + assert_eq!(r["gid"], json!(g('a'))); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert_eq!(gids(&s), [g('x'), g('a'), g('b'), g('y')], "the first a draws its default glyph"); + assert_eq!(s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 1})).unwrap()["chosen"], json!(g('a'))); + + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": null})).unwrap(); + assert_eq!(r["gid"], json!(g('b')), "the glyph salt draws"); + assert_eq!(gids(&s), [g('x'), g('b'), g('b'), g('y')]); + + // A character that overflows its area is not laid out: the choice is kept for when it is. + let area = json!({"x": 0, "y": 300, "text": "xa", "size": 20, "font": alternates_family(true), "area": {"width": 200, "height": 4}}); + let boxed = NodeId(s.execute("text.create", &area).unwrap()["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": boxed.0, "start": 0, "end": 2, "features": ["salt"]})).unwrap(); + assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows"); + s.execute("text.setGlyphAlternate", &json!({"id": boxed.0, "start": 1, "gid": g('a')})).unwrap(); + let held: Vec<_> = obj(&s, boxed).runs.iter().filter_map(|r| r.style.glyph_alternate.as_ref().map(|c| c.gid)).collect(); + assert_eq!(held, [g('a')], "the default glyph is kept as the choice"); +} + +/// A character followed by a combining mark is drawn in one cluster with the mark: with `salt`, +/// `gid: null` reports the glyph the feature draws, also when the text overflows, and choosing the +/// default glyph draws it. +#[test] +fn the_glyph_drawn_for_a_character_with_a_combining_mark_is_reported() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(alternates_font(true).expect("the test font builds")); + let face = db.face(alternates_family(true), "Regular").expect("the test face"); + let g = |c| face.glyph_for(c); + let mut s = session(); + let text = "xa\u{331}y"; + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": text, "size": 20, "font": alternates_family(true)})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": text.len(), "features": ["salt"]})).unwrap(); + let lay = vectorcraft_text::layout(db, &obj(&s, id)); + let at = lay.glyphs.iter().find(|gl| gl.byte == 1).expect("the a is laid out"); + assert_eq!((at.gid, at.len), (g('b'), 3), "salt draws the a as b, in one cluster with its mark"); + + let state = |s: &Session| (s.doc().unwrap().history.undo.len(), s.doc().unwrap().revision); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": null})).unwrap(); + assert_eq!(r["gid"], json!(g('b')), "the glyph salt draws"); + let undo = state(&s).0; + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 1, "gid": g('a')})).unwrap(); + assert_eq!(r["gid"], json!(g('a'))); + assert_eq!(state(&s).0, undo + 1, "one undo step"); + let lay = vectorcraft_text::layout(db, &obj(&s, id)); + assert_eq!(lay.glyphs.iter().find(|gl| gl.byte == 1).map(|gl| gl.gid), Some(g('a')), "the a draws its default glyph"); + + let area = json!({"x": 0, "y": 300, "text": "xa\u{331}", "size": 20, "font": alternates_family(true), "area": {"width": 200, "height": 4}}); + let boxed = NodeId(s.execute("text.create", &area).unwrap()["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": boxed.0, "start": 0, "end": 4, "features": ["salt"]})).unwrap(); + assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows"); + let r = s.execute("text.setGlyphAlternate", &json!({"id": boxed.0, "start": 1, "gid": null})).unwrap(); + assert_eq!(r["gid"], json!(g('b')), "the overflowing a is shaped with its mark"); +} + +/// Vertical type draws `vert` glyphs (the test font's `vert` draws ! as I). A character of +/// vertical type that overflows its area is shaped as vertical type, so choosing its default glyph +/// keeps the choice. +#[test] +fn the_default_glyph_chosen_in_overflowing_vertical_type_is_kept() { + use vectorcraft_text::test_fonts::{VERTICAL_PUNCTUATION_FAMILY, vertical_punctuation_font}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(vertical_punctuation_font(true).expect("the test font builds")); + let face = db.face(VERTICAL_PUNCTUATION_FAMILY, "Regular").expect("the test face"); + let g = |c| face.glyph_for(c); + let mut s = session(); + let text = |area: Value| json!({"x": 0, "y": 0, "text": "!!", "size": 20, "font": VERTICAL_PUNCTUATION_FAMILY, "vertical": true, "area": area}); + let open = NodeId(s.execute("text.create", &text(json!({"width": 200, "height": 200}))).unwrap()["id"].as_u64().unwrap()); + let gids: Vec<_> = vectorcraft_text::layout(db, &obj(&s, open)).glyphs.iter().map(|g| g.gid).collect(); + assert_eq!(gids, [g('I'), g('I')], "vert draws each ! as I"); + + let boxed = NodeId(s.execute("text.create", &text(json!({"width": 4, "height": 4}))).unwrap()["id"].as_u64().unwrap()); + assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows"); + let r = s.execute("text.setGlyphAlternate", &json!({"id": boxed.0, "start": 0, "gid": g('!')})).unwrap(); + assert_eq!(r["gid"], json!(g('!'))); + let held: Vec<_> = obj(&s, boxed).runs.iter().filter_map(|r| r.style.glyph_alternate.as_ref().map(|c| c.gid)).collect(); + assert_eq!(held, [g('!')], "the default glyph is kept as the choice"); +} + +#[test] +fn glyph_alternates_query_reports_the_fallback_glyph_that_is_drawn() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(alternates_font(true).expect("the test font builds")); + let requested = db.face(alternates_family(true), "Regular").expect("the test face"); + let fallback = db.face("Inter", "Regular").expect("the bundled fallback face"); + let ch = 'Ƃ'; + assert_eq!(requested.glyph_for(ch), 0); + assert_ne!(fallback.glyph_for(ch), 0); + let mut s = session(); + let id = NodeId( + s.execute("text.create", &json!({"x": 0, "y": 0, "text": ch.to_string(), "font": alternates_family(true)})).unwrap()["id"].as_u64().unwrap(), + ); + let glyph = vectorcraft_text::layout(db, &obj(&s, id)).glyphs.remove(0); + assert_ne!(glyph.font_id, requested.id()); + assert_ne!(glyph.gid, 0); + let query = s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 0})).unwrap(); + assert_eq!(query["chosen"], json!(glyph.gid), "the query reports the visible fallback glyph"); + assert!(query["alternates"].as_array().unwrap().is_empty()); +} diff --git a/crates/engine/src/tests/typearea.rs b/crates/engine/src/tests/typearea.rs index 623eaa5a42..9ada8b7194 100644 --- a/crates/engine/src/tests/typearea.rs +++ b/crates/engine/src/tests/typearea.rs @@ -508,3 +508,25 @@ fn area_type_options_set_the_text_flow() { assert_eq!((text(&s, id).area.flow, second(&s)), (TextFlow::Columns, (0.0, 160.0))); assert!(cmd::find_command("text.areaOptions").unwrap().params.contains("flow?: columns|rows")); } + +/// #3759: options that change nothing (the vertical alignment already set, or +/// `fitMinPercent` alone on a frame without Shrink Text) add no undo step and keep redo; a size +/// change with them still applies. +#[test] +fn unchanged_area_type_options_add_no_undo_step() { + let mut s = session(); + let id = area(&mut s, 40.0, 40.0, 200.0, 300.0, "Short story"); + sel(&mut s, &[id]); + s.execute("text.areaOptions", &json!({"verticalAlign": "bottom"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("text.areaOptions", &json!({"verticalAlign": "center"})).unwrap(); + let n = undo_len(&s); + let before = text(&s, id); + s.execute("text.areaOptions", &json!({"verticalAlign": "center"})).unwrap(); + s.execute("text.areaOptions", &json!({"fitMinPercent": 40})).unwrap(); + assert_eq!(undo_len(&s), n, "no step for options already set"); + assert_eq!(text(&s, id), before); + // A real change still counts, and a new width with an unchanged option too. + s.execute("text.areaOptions", &json!({"verticalAlign": "center", "width": 180})).unwrap(); + assert_eq!(undo_len(&s), n + 1); +} diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index c16896ac7d..bdd474612f 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -373,7 +373,9 @@ fn image_size_region_and_metadata() { json!({"format": "bmp"}), json!({"colors": "many"}), json!({"matte": "plaid"}), + json!({"matte": "#ffff0080"}), json!({"colorTable": {"locked": ["nope"]}}), + json!({"colorTable": {"transparent": ["#ff000080"]}}), json!({"artboard": 3}), json!({"preset": "Nope"}), ] { diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index ee83e72d68..18e8da3d59 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -861,9 +861,22 @@ impl Session { /// End the Type tool's text editing before a command saves the art of an editing layer (pattern /// editing's Done, Stop Editing Opacity Mask): point type its click placed that is still empty is - /// discarded first, so it is not saved into the pattern tile or the mask. + /// discarded first, so it is not saved into the pattern tile or the mask. A selection tool that a + /// Cmd press lent is given back first, so the Type tool behind it ends its edit too; a drag of the + /// lent tool is kept as its own step, as its release would keep it. pub(crate) fn end_text_edit(&mut self) { - if self.in_tool_actions || !self.tool.wants_text() { + if self.in_tool_actions { + return; + } + if self.lender.is_some() { + if let Err(e) = self.apply_actions(vec![Action::Commit]) { + log::warn!("keeping the lent tool's drag before ending the text edit: {e}"); + } + if let Err(e) = self.give_back_tool(self.last_view) { + log::warn!("giving back the lent tool before ending the text edit: {e}"); + } + } + if !self.tool.wants_text() { return; } let acts = self.with_tool_cx(self.last_view, |t, cx| t.deactivate(cx)); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 45f6b47680..3010901ca7 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -236,6 +236,9 @@ fn structured_junk() { ("select.anchorsMany", json!({"items": [{"id": 2, "anchors": [[0, 0]]}], "mode": "subtract"})), ("select.anchorsMany", json!({"items": [], "mode": 7})), ("select.toggle", json!({"ids": [2, u64::MAX, "x"]})), + ("addon.select.byArtboards", json!({"artboards": [0, u64::MAX, -1, "x", null, 1.5], "relation": "inside"})), + ("addon.select.byArtboards", json!({"artboards": [1e308], "relation": [1]})), + ("addon.select.byArtboards", json!({"artboards": {"a": 1}, "relation": "outside"})), ("object.transform", json!({"matrix": [0, 0, 0, 0, 0, 0]})), ("object.transform", json!({"matrix": [1e308, 1e308, 1e308, 1e308, 1e308, 1e308]})), ("object.transform", json!({"matrix": [1, 2, 3]})), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 4d1a328fda..cbe713e444 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2733,6 +2733,16 @@ fn editing_text() -> String { square(40), "50 10 m 60 10 L 60 20 L 50 20 L h W f".into(), "Q".into(), + // Transparency: a path's, a group's state block, and an object's opacity mask. + "0 0 1 0 k\n2 0.5 0 0 1 Xy".into(), + square(86), + "0 Ae\nu".into(), + square(90), + "U\n0 0.4 1 1 1 Xy\n0 0 Xd\n6 () XW".into(), + square(94), + "%_/ArtDictionary :\n%_/Mask :\n%_X=\n%_0 g\n%_94 10 m\n%_98 10 L\n%_98 14 L\n%_f\n%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n\ + %_0 /Bool (Inverted) ,\n%_0 /Bool (Disabled) ,\n%_1 /Bool (Linked) ,\n%_; (AI9_Mask) ,\n%_;" + .into(), // Smooth and corner anchors by the case of each segment's operator, back to the start. "10 50 m 20 60 30 50 40 50 c 45 50 50 55 v 55 60 60 60 Y 60 50 l 50 40 30 40 10 50 C s".into(), "70 50 m 80 50 l 80 60 L 70 60 y h S".into(), @@ -2761,7 +2771,8 @@ fn editing_text() -> String { format!( "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n{PATTERN}{PALETTE}{}{}%%Trailer\n", layer("One", 1, &format!("{body}\n{}", layer("Sub", 1, &square(70)))), - layer("Two", 0, &square(80)) + // A layer's own state block after its last compound path. + layer("Two", 0, &format!("{}\n*u\n{}\n{}\n*U\n1 0.6 1 2 1 Xy\n0 0 Xd\n7 () XW", square(80), square(84), square(88))) ) } diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index bdcefb56b4..43b82f1272 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -24,9 +24,9 @@ //! dictionary's `/Recorded` part and the canvas size as its `AIDocumentCanvasSize`, on `%_` //! lines. //! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed 0 1 colorIndex r g b 0 -//! dimPercent 0 Lb` (14 operands; a color that isn't one of the preset layer colors has the -//! index -1), `(name) Ln`, the layer's name as an XML id in an `/ArtDictionary`, its art and -//! sublayers, `LB`, `%AI5_EndLayer--`. +//! dimPercent clipping Lb` (14 operands; a color that isn't one of the preset layer colors has the +//! index -1; `clipping` is 1 for a clipping layer), `(name) Ln`, the layer's name as an XML id in an +//! `/ArtDictionary`, its art and sublayers, `LB`, `%AI5_EndLayer--`. //! - Colors: `g` gray, `k` CMYK, `c m y k r g b Xa` RGB (Lab is written as RGB); a spot color //! `c m y k (name) tint x` (CMYK) or `c m y k r g b|L a b (name) tint 1|2 Xx` (RGB or Lab); a //! global process color `… (name) tint model Xk`; Registration `1 1 1 1 ([Registration]) tint @@ -34,18 +34,31 @@ //! - State before each object: locked `A`, hidden `Xw` (`1` or `0`). An object's name follows it as //! an `/ArtDictionary` whose `AI10_ArtUID` is the name as an XML id. Guides are `(N) *`, the //! path, `(N) *` (`(n) *` when closed). +//! - Transparency: `mode opacity isolate knockout shape Xy` (the blending mode's number, Knockout +//! Group 0 off, 1 on, 2 neutral), written when it changes: in a path's paint after its colors, +//! before a guide, and after a group's end (`U` or `Q`) followed by `0 0 Xd` and `6 () XW`; a +//! group without transparency of its own ends `9 () XW`. A layer's comes after its art: `Xy`, +//! `0 0 Xd`, `7 () XW`, before `LB`. +//! - Compound paths: `*u`, the subpaths, `*U` (§5.3.5). Clipping groups: `q`, the art, the clipping +//! path last with `h` (or `H` when open) and `W` before its painting operator, `Q` (§5.6.2); a +//! clipping layer's clipping path is written the same way, last in the layer. +//! - Opacity masks: an `AI9_Mask` entry in the object's `/ArtDictionary`, a `/Mask` dictionary +//! holding the mask's art between `X=` and `X+` on `%_` lines, `(Art) ,`, and `Clipping`, +//! `Inverted`, `Disabled` and `Linked` as `/Bool` entries. //! //! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at //! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the //! artboards together are centered; each artboard's `RulerOrigin` is its top-left corner there, and //! `%AI3_TemplateBox` holds the canvas's center in art space. What the form above can't hold is written as plain filled and stroked paths, each such //! loss a warning: type as its outlines and its inline graphics' art, gradients as their average color, pattern fills as their -//! tiles cut to the shape, clipping groups and clipping layers as their art cut to the clipping -//! path (the clipping path's fill cut too, its stroke not), images as their outlines filled with +//! tiles cut to the shape, clipping groups and clipping layers whose clipping object isn't a path, +//! and the clipping groups inside them, as their art cut to that object (its fill cut too, its +//! stroke not), images as their outlines filled with //! their average color, symbols and live objects as their art (symbol art past //! [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects in all left out), strokes a plain line can't draw //! as their filled outlines, several fills or strokes as a group of a path for each, gradient and -//! pattern swatches, transparency and live effects other than geometry effects left out. +//! pattern swatches, the opacity and blending modes of single fills and strokes, opacity masks on +//! layers and opacity masks nested too deep, and live effects other than geometry effects left out. //! //! The data streams hold the program compressed with Zstandard after `%AI24_ZStandard_Data`, with //! the version numbers of the newest files users sent ([`private_data`]). diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 5a355fe3df..dcf928df56 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -3,10 +3,10 @@ use std::sync::Arc; use vectorcraft_color::swatch::{Swatch, SwatchGroup}; -use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; use vectorcraft_doc::{ - Appearance, AppearanceItem, Artboard, Dash, Document, FillLayer, ImageBlob, ImageObject, LayerColor, LineCap, LineJoin, Node, NodeKind, - StrokeLayer, Symbol, + Appearance, AppearanceItem, Artboard, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, + OpacityMask, StrokeLayer, Symbol, }; use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; @@ -223,6 +223,24 @@ fn view(nodes: &[Arc], depth: usize, out: &mut Vec) { } out.push(s); } + // The compound path's own paint and its members' points (the paint is the compound path's). + NodeKind::Compound { rule, .. } => { + let mut s = format!("{head} compound {rule:?}"); + for c in n.children().map(Vec::as_slice).unwrap_or_default() { + for sp in c.path_data().map(|p| p.subpaths.as_slice()).unwrap_or_default() { + let r2 = |v: f64| format!("{:.2}", v + 0.0); + s += &format!(" [closed={}", sp.closed); + for a in &sp.anchors { + s += &format!(" {},{}", r2(a.p.x), r2(a.p.y)); + } + s += "]"; + } + } + for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) { + s += &format!(" {}", paint(it.paint())); + } + out.push(s); + } other => out.push(format!("{head} {other:?}")), } } @@ -584,8 +602,8 @@ fn hidden_layers_open_hidden() { assert!(text.contains("%AI5_NumLayers: 3\n%AI5_OpenViewLayers: 776\n"), "{text}"); } -/// A 200 × 100 document of what slice 1 writes as plain paths: a gradient fill, a clipping group, -/// a compound path, an image, type, a symbol instance and a half-transparent square. +/// A 200 × 100 document of what the data holds as plain paths: a gradient fill, a compound path, +/// an image, type and a symbol instance. fn unsupported() -> Document { let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; @@ -597,24 +615,6 @@ fn unsupported() -> Document { let shaded = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), fill(Paint::Gradient(Box::new(GradientPaint::new(g))))); doc.insert(Some(layer), usize::MAX, shaded).unwrap(); - let clip = Node::new( - doc.alloc_id(), - NodeKind::Path { - path: shapes::rectangle(Rect::new(40.0, 10.0, 50.0, 30.0)), - rule: FillRule::NonZero, - live: None, - clipping: true, - guide: false, - }, - ); - let clipped = Node::path( - doc.alloc_id(), - shapes::rectangle(Rect::new(35.0, 15.0, 60.0, 25.0)), - Appearance::basic(solid(Color::gray(0.5)), solid(Color::BLACK), 1.0), - ); - let mut window = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(clipped)], clip: true }); - window.name = Some("Window".into()); - doc.insert(Some(layer), usize::MAX, window).unwrap(); let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(70.0, 10.0, 90.0, 30.0)), Appearance::default()); let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(75.0, 15.0, 85.0, 25.0)), Appearance::default()); let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); @@ -648,9 +648,6 @@ fn unsupported() -> Document { doc.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((150.0, 10.0)) }); doc.insert(Some(layer), usize::MAX, instance).unwrap(); - let mut faded = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(170.0, 10.0, 190.0, 30.0)), fill(solid(Color::BLACK))); - faded.opacity = 0.5; - doc.insert(Some(layer), usize::MAX, faded).unwrap(); doc } @@ -668,7 +665,7 @@ fn paths(nodes: &[Arc], out: &mut Vec) { fn art_the_slice_does_not_cover_is_written_as_plain_paths() { let doc = unsupported(); let out = export_ai_editing(&doc, &opts()).unwrap(); - for w in [writer::GRADIENTS, writer::CLIPPING, writer::IMAGES, writer::TYPE, writer::LIVE, writer::TRANSPARENCY] { + for w in [writer::GRADIENTS, writer::IMAGES, writer::TYPE, writer::LIVE] { assert!(out.warnings.iter().any(|x| x == w), "{w}: {:?}", out.warnings); } let back = read_back(&doc); @@ -682,22 +679,15 @@ fn art_the_slice_does_not_cover_is_written_as_plain_paths() { _ => "other", }) .collect(); - assert_eq!(kinds, ["path", "group", "compound", "path", "group", "group", "path"]); + assert_eq!(kinds, ["path", "compound", "path", "group", "group"]); let mut all = vec![]; paths(layer, &mut all); assert!(all.iter().all(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }))); // The gradient as its average color. assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.5, 0.5)))); - // The clipping group: the gray fill and the black stroke's outline, cut to the 10 × 20 clip. - let window = &layer[1]; - assert_eq!(window.name.as_deref(), Some("Window")); - let b = window.visual_bounds().unwrap(); - assert!((b.x0 - 40.0).abs() < 0.01 && (b.x1 - 50.0).abs() < 0.01, "{b:?}"); // The image's outline filled with its pixels' average. - assert_eq!(paint(layer[3].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.0, 0.5)))); - assert_eq!(layer[3].visual_bounds().map(|b| (r3(b.x0), r3(b.y0), r3(b.x1), r3(b.y1))), Some((r3(100.0), r3(10.0), r3(120.0), r3(20.0)))); - // The half-transparent square, opaque. - assert_eq!(layer[6].opacity, 1.0); + assert_eq!(paint(layer[2].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.0, 0.5)))); + assert_eq!(layer[2].visual_bounds().map(|b| (r3(b.x0), r3(b.y0), r3(b.x1), r3(b.y1))), Some((r3(100.0), r3(10.0), r3(120.0), r3(20.0)))); } #[test] @@ -878,7 +868,10 @@ fn a_layer_with_crop_marks_keeps_its_art_and_gets_the_marks() { assert_eq!(back.layers[0].name, name); let members = back.layers[0].children().unwrap(); assert_eq!(members.len(), 2, "clipping {clipping}: the square and the marks"); - assert!(matches!(members[0].kind, NodeKind::Path { .. })); + // A clipping layer's art is a clipping group, outside which the marks lie. + let expected = + if clipping { matches!(members[0].kind, NodeKind::Group { clip: true, .. }) } else { matches!(members[0].kind, NodeKind::Path { .. }) }; + assert!(expected && matches!(back.layers[0].kind, NodeKind::Layer { clip: false, .. }), "clipping {clipping}"); assert!(matches!(members[1].kind, NodeKind::Group { .. })); // The marks lie around the square, outside a clipping path. let marks = members[1].visual_bounds().unwrap(); @@ -1029,3 +1022,655 @@ fn a_document_without_an_artboard_is_an_error() { doc.artboards.push(Artboard { rect: Rect::new(0.0, 0.0, 0.0, 10.0), ..Document::new(1.0, 1.0).artboards[0].clone() }); assert!(export_ai_editing(&doc, &opts()).is_err()); } + +// ---------- transparency, compound paths, clipping, opacity masks ---------- + +/// A rectangle filled with `c`. +fn square(doc: &mut Document, r: Rect, c: Color) -> Node { + Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::basic(solid(c), Paint::None, 0.0)) +} + +/// A clipping path of `path`, unpainted. +fn clipping(doc: &mut Document, path: PathData) -> Node { + Node::new(doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: true, guide: false }) +} + +fn named(mut n: Node, name: &str) -> Node { + n.name = Some(name.into()); + n +} + +fn see_through(mut n: Node, opacity: f32, blend: BlendMode) -> Node { + (n.opacity, n.blend) = (opacity, blend); + n +} + +fn group(doc: &mut Document, children: Vec, clip: bool) -> Node { + Node::new(doc.alloc_id(), NodeKind::Group { children: children.into_iter().map(Arc::new).collect(), clip }) +} + +/// A 200 × 100 document of what the transparency, compound path and clipping forms hold. Layer +/// `Clear` (60%, Multiply, isolated) holds, bottom first: a path at 50% in Screen whose opacity +/// defines the knockout shape; a group at 40%, isolated, knockout on, whose opacity defines the +/// knockout shape, of a square and a square at 75% in Overlay; a group with knockout off; a group of +/// a square in each blending mode; a clipping group at 50%; a clipping group whose clipping path +/// is an even-odd compound path; a clipping group holding a clipping group; a named path with an +/// inverted opacity mask that doesn't clip; a group with a disabled opacity mask; and a compound +/// path at 70% in Screen whose opacity defines the knockout shape last. The layer's opacity +/// defines the knockout shape too. Layer `Cut` clips by its first path. Layer `Plain` holds an +/// opaque path. +fn transparent() -> Document { + let mut doc = Document::new(200.0, 100.0); + doc.swatches = vec![Swatch { name: "Blue".into(), paint: solid(Color::rgb(0.0, 0.0, 1.0)), global: false, spot: false }].into(); + doc.swatch_groups = vec![].into(); + doc.layers.clear(); + let clear = doc.add_layer(Some("Clear")); + let cut = doc.add_layer(Some("Cut")); + let plain = doc.add_layer(Some("Plain")); + let red = Color::rgb(1.0, 0.0, 0.0); + let blue = Color::rgb(0.0, 0.0, 1.0); + let mut art = vec![]; + + let mut shine = see_through(square(&mut doc, Rect::new(5.0, 5.0, 25.0, 25.0), red), 0.5, BlendMode::Screen); + shine.knockout_shape = true; + art.push(named(shine, "Shine")); + let a = square(&mut doc, Rect::new(30.0, 5.0, 50.0, 25.0), red); + let b = see_through(square(&mut doc, Rect::new(35.0, 10.0, 55.0, 30.0), blue), 0.75, BlendMode::Overlay); + let mut knock = see_through(group(&mut doc, vec![a, b], false), 0.4, BlendMode::Normal); + (knock.isolate, knock.knockout, knock.knockout_shape) = (true, Knockout::On, true); + art.push(named(knock, "Knock")); + let a = square(&mut doc, Rect::new(60.0, 5.0, 70.0, 15.0), red); + let b = square(&mut doc, Rect::new(65.0, 10.0, 75.0, 20.0), blue); + let mut off = group(&mut doc, vec![a, b], false); + off.knockout = Knockout::Off; + art.push(off); + let modes: Vec = BlendMode::ALL + .iter() + .enumerate() + .map(|(i, m)| { + let x = 5.0 + 11.0 * i as f64; + see_through(square(&mut doc, Rect::new(x, 40.0, x + 10.0, 50.0), red), 0.5, *m) + }) + .collect(); + art.push(group(&mut doc, modes, false)); + let clip = clipping(&mut doc, shapes::rectangle(Rect::new(90.0, 5.0, 100.0, 25.0))); + let inside = square(&mut doc, Rect::new(85.0, 10.0, 110.0, 20.0), blue); + art.push(named(see_through(group(&mut doc, vec![named(clip, "Edge"), inside], true), 0.5, BlendMode::Normal), "Window")); + // The subpaths of a compound clipping path are clipping paths, as the reader marks them. + let outer = clipping(&mut doc, shapes::rectangle(Rect::new(115.0, 5.0, 135.0, 25.0))); + let inner = clipping(&mut doc, shapes::rectangle(Rect::new(120.0, 10.0, 130.0, 20.0))); + let compound_clip = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + let green = square(&mut doc, Rect::new(110.0, 0.0, 140.0, 30.0), Color::rgb(0.0, 1.0, 0.0)); + art.push(group(&mut doc, vec![compound_clip, green], true)); + let deep_clip = clipping(&mut doc, shapes::rectangle(Rect::new(145.0, 5.0, 160.0, 25.0))); + let deep = square(&mut doc, Rect::new(140.0, 0.0, 170.0, 30.0), red); + let deep = group(&mut doc, vec![deep_clip, deep], true); + let outer_clip = clipping(&mut doc, shapes::rectangle(Rect::new(150.0, 0.0, 165.0, 20.0))); + art.push(group(&mut doc, vec![outer_clip, deep], true)); + let gray = square(&mut doc, Rect::new(5.0, 60.0, 15.0, 70.0), Color::gray(0.5)); + let white = square(&mut doc, Rect::new(15.0, 60.0, 25.0, 70.0), Color::rgb(1.0, 1.0, 1.0)); + let mask_art = group(&mut doc, vec![gray, white], false); + let mut masked = named(square(&mut doc, Rect::new(0.0, 55.0, 30.0, 75.0), blue), "Masked"); + masked.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(mask_art), clip: false, invert: true, disabled: false, linked: true })); + art.push(masked); + let off_art = square(&mut doc, Rect::new(40.0, 60.0, 50.0, 70.0), Color::gray(0.25)); + let in_faded = square(&mut doc, Rect::new(35.0, 55.0, 60.0, 75.0), red); + let mut faded = group(&mut doc, vec![in_faded], false); + faded.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(off_art), clip: true, invert: false, disabled: true, linked: false })); + art.push(faded); + let o = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(70.0, 55.0, 90.0, 75.0)), Appearance::default()); + let i = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(75.0, 60.0, 85.0, 70.0)), Appearance::default()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(o), Arc::new(i)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance::basic(solid(red), Paint::None, 0.0).into(); + ring.knockout_shape = true; + art.push(named(see_through(ring, 0.7, BlendMode::Screen), "Ring")); + for n in art { + doc.insert(Some(clear), usize::MAX, n).unwrap(); + } + + let edge = clipping(&mut doc, shapes::rectangle(Rect::new(100.0, 40.0, 150.0, 90.0))); + doc.insert(Some(cut), usize::MAX, named(edge, "Edge")).unwrap(); + for (r, c) in [(Rect::new(90.0, 35.0, 130.0, 70.0), red), (Rect::new(120.0, 60.0, 160.0, 95.0), blue)] { + let n = square(&mut doc, r, c); + doc.insert(Some(cut), usize::MAX, n).unwrap(); + } + let opaque = square(&mut doc, Rect::new(170.0, 60.0, 190.0, 80.0), blue); + doc.insert(Some(plain), usize::MAX, opaque).unwrap(); + for (i, l) in doc.layers.iter_mut().enumerate() { + let l = Arc::make_mut(l); + match i { + 0 => { + (l.opacity, l.blend, l.isolate, l.knockout_shape) = (0.6, BlendMode::Multiply, true, true); + } + 1 => { + if let NodeKind::Layer { clip, .. } = &mut l.kind { + *clip = true; + } + } + _ => {} + } + } + doc +} + +/// The transparency, clipping and opacity masks of every object, one line each, the masks' art +/// after their objects. +fn looks(nodes: &[Arc], depth: usize, out: &mut Vec) { + for n in nodes { + let kind = match &n.kind { + NodeKind::Layer { clip, .. } => format!("layer clip={clip}"), + NodeKind::Group { clip, .. } => format!("group clip={clip}"), + NodeKind::Path { clipping, .. } => format!("path clipping={clipping}"), + NodeKind::Compound { .. } => "compound".into(), + _ => "other".into(), + }; + let mut s = format!( + "{depth} {:?} {kind} {} {:?} isolate={} {:?} shape={}", + n.name, + r3(f64::from(n.opacity)), + n.blend, + n.isolate, + n.knockout, + n.knockout_shape + ); + let mask = n.extras().mask.clone(); + if let Some(m) = &mask { + s += &format!(" mask(clip={} invert={} disabled={} linked={})", m.clip, m.invert, m.disabled, m.linked); + } + out.push(s); + if let Some(m) = mask { + view(std::slice::from_ref(&m.art), depth + 1, out); + } + looks(n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out); + } +} + +fn all_looks(doc: &Document) -> Vec { + let mut out = vec![]; + looks(&doc.layers, 0, &mut out); + out +} + +/// Fails with the lines where `got` and `want` differ. +fn same_lines(got: &[String], want: &[String]) { + let differ: Vec = (0..got.len().max(want.len())) + .filter(|&i| got.get(i) != want.get(i)) + .map(|i| format!("line {i}:\n got {:?}\n want {:?}", got.get(i), want.get(i))) + .collect(); + assert!(differ.is_empty(), "{}", differ.join("\n")); +} + +/// `nodes` as the reader reads them back: an opacity mask's art that isn't a group comes back as +/// a group holding it. +fn mask_art_grouped(nodes: &mut [Arc]) { + for n in nodes { + let n = Arc::make_mut(n); + if let Some(m) = n.extras_mut().mask.as_mut() + && !matches!(m.art.kind, NodeKind::Group { .. }) + { + let art = m.art.clone(); + m.art = Arc::new(Node::new(art.id, NodeKind::Group { children: vec![art], clip: false })); + } + if let Some(c) = n.children_mut() { + mask_art_grouped(c); + } + } +} + +#[test] +fn transparency_clipping_and_masks_are_read_back() { + let mut doc = transparent(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + same_lines(&lines(&back), &lines(&doc)); + // The disabled mask's art is one path: it reads back as a group holding the path. + let mask_arts = |d: &Document| { + let mut out = vec![]; + d.walk(|n| { + if let Some(m) = &n.extras().mask { + out.push(match &m.art.kind { + NodeKind::Group { children, .. } => format!("group of {}", children.len()), + NodeKind::Path { .. } => "path".into(), + _ => "other".into(), + }); + } + }); + out + }; + assert_eq!( + (mask_arts(&doc), mask_arts(&back)), + (vec!["group of 2".to_string(), "path".into()], vec!["group of 2".to_string(), "group of 1".into()]) + ); + mask_art_grouped(&mut doc.layers); + same_lines(&all_looks(&back), &all_looks(&doc)); +} + +#[test] +fn transparency_clipping_and_masks_write_the_same_bytes_again() { + let doc = transparent(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + assert_eq!(private_data(&doc, &opts()).unwrap().0, private_data(&doc, &opts()).unwrap().0); + // What the reader reads back is written as the same program. + let again = String::from_utf8(export_ai_editing(&read_back(&doc), &opts()).unwrap().program).unwrap(); + let first = String::from_utf8(first.program).unwrap(); + same_lines(&again.lines().map(String::from).collect::>(), &first.lines().map(String::from).collect::>()); +} + +#[test] +fn transparency_is_written_in_its_forms() { + let p = program(&transparent()); + // A path's in its paint, after its colors; Screen is 2. + assert!(p.contains(" Xa\n0 O\n2 0.5 0 0 1 Xy\n0 XR\n"), "{p}"); + // A compound path's in its paint before `*u`, its knockout shape kept. + let (ring, _) = p.rsplit_once("*u\n").unwrap(); + assert!(ring.ends_with(" O\n2 0.7 0 0 1 Xy\n1 XR\n"), "{ring}"); + // A group's after its end and its name, then `Xd` and the object's own state marker. + let knock = "U\n%_/ArtDictionary :\n%_/XMLUID : (Knock) ; (AI10_ArtUID) ,\n%_;\n%_\n0 0.4 1 1 1 Xy\n0 0 Xd\n6 () XW\n"; + assert!(p.contains(knock), "{p}"); + // A group without transparency of its own. + assert!(p.contains("U\n9 () XW\n"), "{p}"); + // A clipping group: the clipping path last, then `W`. + let window = "h\nW\nn\n%_/ArtDictionary :\n%_/XMLUID : (Edge) ; (AI10_ArtUID) ,\n%_;\n%_\nQ\n\ + %_/ArtDictionary :\n%_/XMLUID : (Window) ; (AI10_ArtUID) ,\n%_;\n%_\n0 0.5 0 2 0 Xy\n0 0 Xd\n6 () XW\n"; + assert!(p.contains(window), "{p}"); + // A layer's after its art, with the layer's state marker; its knockout neutral (2). + assert!(p.contains("1 0.6 1 2 1 Xy\n0 0 Xd\n7 () XW\nLB\n"), "{p}"); + // A clipping layer: its last `Lb` flag, its clipping path last. + assert!(p.contains(" 0 50 1 Lb\n(Cut) Ln\n") && p.contains(" 0 50 0 Lb\n(Plain) Ln\n"), "{p}"); + let (_, cut) = p.split_once("(Cut) Ln").unwrap(); + // The name `Edge` is taken by the clipping group's path: this one is numbered. + let edge = "h\nW\nn\n%_/ArtDictionary :\n%_/XMLUID : (Edge_00000000000000000001_) ; (AI10_ArtUID) ,\n%_;\n%_\n"; + assert!(cut.split_once("LB\n").unwrap().0.ends_with(edge), "{cut}"); + // The next layer's first path sets the state back. + let (_, cut) = p.split_once("(Cut) Ln").unwrap(); + assert!(cut.split_once("\nf\n").unwrap().0.contains(" Xa\n0 O\n0 1 0 0 0 Xy\n0 XR\n"), "{cut}"); + // The mask in the object's dictionary, after its name. + assert!(p.contains("%_/XMLUID : (Masked) ; (AI10_ArtUID) ,\n%_/Mask :\n%_X=\n"), "{p}"); + assert!( + p.contains( + "%_X+\n%_(Art) ,\n%_0 /Bool (Clipping) ,\n%_1 /Bool (Inverted) ,\n%_0 /Bool (Disabled) ,\n%_1 /Bool (Linked) ,\n%_; (AI9_Mask) ,\n" + ), + "{p}" + ); +} + +/// A clipping path filled and stroked keeps its stroke; the reader reads its fill as a path of +/// its own under the clipped art, as the file's PDF page draws it. +#[test] +fn a_painted_clipping_path_is_written_with_its_paint() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0))); + clip.appearance = Appearance::basic(solid(Color::rgb(1.0, 1.0, 0.0)), solid(Color::BLACK), 2.0).into(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 40.0, 20.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let p = program(&doc); + assert!(p.contains("h\nW\nb\nQ\n"), "{p}"); + let back = read_back(&doc); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + let painted: Vec<(bool, Option, Option)> = children + .iter() + .map(|c| { + let clipping = matches!(c.kind, NodeKind::Path { clipping: true, .. }); + (clipping, c.appearance.fill().map(|f| paint(&f.paint)), c.appearance.stroke().map(|s| paint(&s.paint))) + }) + .collect(); + assert_eq!( + painted, + [ + (true, None, Some(paint(&solid(Color::BLACK)))), + (false, Some(paint(&solid(Color::rgb(1.0, 1.0, 0.0)))), None), + (false, Some(paint(&solid(Color::rgb(0.0, 0.0, 1.0)))), None) + ] + ); +} + +/// A clipping path without points hides what it clips. +#[test] +fn an_empty_clipping_path_hides_the_art() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let clip = clipping(&mut doc, PathData::new(vec![])); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 40.0, 20.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + // The art is hidden, as it is drawn: the group comes back empty. + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::CLIPPING), "{:?}", out.warnings); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{art:?}"); + assert!(matches!(&art[0].kind, NodeKind::Group { children, .. } if children.is_empty()), "{art:?}"); +} + +/// A clipping group without members is written as an empty group, and reads back as one. +#[test] +fn an_empty_clipping_group_is_an_empty_group() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let g = see_through(group(&mut doc, vec![], true), 0.5, BlendMode::Normal); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let p = program(&doc); + assert!(p.contains("\nu\nU\n0 0.5 0 2 0 Xy\n0 0 Xd\n6 () XW\n") && !p.contains("\nq\n"), "{p}"); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{art:?}"); + assert!(matches!(&art[0].kind, NodeKind::Group { children, clip: false } if children.is_empty()), "{art:?}"); + assert_eq!(art[0].opacity, 0.5); +} + +/// A clipping path's paint that the path can't carry itself keeps the path's opacity. +#[test] +fn a_clipping_paths_other_paint_keeps_its_opacity() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0))); + let g = Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.0))], + ); + clip.appearance = Appearance::basic(Paint::Gradient(Box::new(GradientPaint::new(g))), Paint::None, 0.0).into(); + clip.opacity = 0.5; + let inside = square(&mut doc, Rect::new(0.0, 0.0, 40.0, 20.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::CLIP_PAINT), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == writer::CLIP_PAINT_MASKS), "{:?}", out.warnings); + // With an opacity mask, which stays on the clipping path: a warning says so. + let mut masked = doc.clone(); + let art = square(&mut masked, Rect::new(10.0, 10.0, 20.0, 20.0), Color::gray(0.5)); + if let Some(c) = Arc::make_mut(&mut masked.layers[0]).children_mut() + && let Some(NodeKind::Group { children, .. }) = c.first_mut().map(|g| &mut Arc::make_mut(g).kind) + { + Arc::make_mut(&mut children[0]).extras_mut().mask = Some(Box::new(OpacityMask::new(art, true))); + } + let out = export_ai_editing(&masked, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::CLIP_PAINT_MASKS), "{:?}", out.warnings); + // Two fills at the clipping path's 50% are a group at 50% of the two at 100%, as the canvas + // draws them together. + let mut two = doc.clone(); + if let Some(c) = Arc::make_mut(&mut two.layers[0]).children_mut() + && let Some(NodeKind::Group { children, .. }) = c.first_mut().map(|g| &mut Arc::make_mut(g).kind) + { + let clip = Arc::make_mut(&mut children[0]); + let mut items = clip.appearance.items.clone(); + items.push(AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(1.0, 0.0, 0.0))))); + clip.appearance = Appearance { items, ..Appearance::default() }.into(); + } + let back = read_back(&two); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + let fills = &children[1]; + assert!(matches!(fills.kind, NodeKind::Group { clip: false, .. }) && fills.opacity == 0.5, "{fills:?}"); + assert_eq!(fills.children().unwrap().iter().map(|c| c.opacity).collect::>(), [1.0, 1.0]); + // A locked clipping path's fill is locked too, the art it clips not. + let mut locked = doc.clone(); + if let Some(c) = Arc::make_mut(&mut locked.layers[0]).children_mut() + && let Some(NodeKind::Group { children, .. }) = c.first_mut().map(|g| &mut Arc::make_mut(g).kind) + { + Arc::make_mut(&mut children[0]).locked = true; + } + let back = read_back(&locked); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + assert_eq!(children.iter().map(|c| c.locked).collect::>(), [true, true, false]); + let back = read_back(&doc); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + // The clipping path, its fill as a path under the art, the art. + let fill = &children[1]; + assert!(matches!(fill.kind, NodeKind::Path { clipping: false, .. })); + assert_eq!((fill.opacity, paint(fill.appearance.items[0].paint())), (0.5, paint(&solid(Color::rgb(0.5, 0.5, 0.5))))); +} + +/// A clipping path's stroke that a plain line can't draw goes over the clipped art, its fill under it. +#[test] +fn a_clipping_paths_other_stroke_goes_over_the_art() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0))); + let g = Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.0))], + ); + let mut stroke = StrokeLayer::new(solid(Color::rgb(1.0, 0.0, 0.0)), 4.0); + stroke.dash = Some(Dash { pattern: vec![2.0, 2.0], offset: 0.0, align_corners: true }); + clip.appearance = Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(g))))), AppearanceItem::Stroke(stroke)], + ..Appearance::default() + } + .into(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 40.0, 20.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let back = read_back(&doc); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + let colors: Vec = children.iter().skip(1).map(|c| paint(c.appearance.items.first().map_or(&Paint::None, |i| i.paint()))).collect(); + // The fill (its average) under the blue art, the red stroke's dots over it. + assert_eq!(colors.first(), Some(&paint(&solid(Color::rgb(0.5, 0.5, 0.5)))), "{colors:?}"); + assert_eq!(colors.get(1), Some(&paint(&solid(Color::rgb(0.0, 0.0, 1.0)))), "{colors:?}"); + assert!(colors.len() > 2 && colors.iter().skip(2).all(|c| *c == paint(&solid(Color::rgb(1.0, 0.0, 0.0)))), "{colors:?}"); +} + +/// An unpainted path with transparency of its own after a compound path: the compound path keeps its own. +#[test] +fn an_unpainted_paths_transparency_after_a_compound_path_is_its_own() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let o = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), Appearance::default()); + let i = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(15.0, 15.0, 25.0, 25.0)), Appearance::default()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(o), Arc::new(i)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance::basic(solid(Color::BLACK), Paint::None, 0.0).into(); + doc.insert(Some(layer), usize::MAX, ring).unwrap(); + let bare = see_through( + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(50.0, 10.0, 70.0, 30.0)), Appearance::default()), + 0.5, + BlendMode::Multiply, + ); + doc.insert(Some(layer), usize::MAX, bare).unwrap(); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!((art[0].opacity, art[0].blend, art[1].opacity, art[1].blend), (1.0, BlendMode::Normal, 0.5, BlendMode::Multiply)); +} + +/// Opacity masks in mask art nested past the limit are left out, not written empty. +#[test] +fn opacity_masks_nested_too_deep_are_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut n = square(&mut doc, Rect::new(10.0, 10.0, 20.0, 20.0), Color::gray(0.5)); + for _ in 0..12 { + let mut owner = square(&mut doc, Rect::new(10.0, 10.0, 20.0, 20.0), Color::gray(0.5)); + owner.extras_mut().mask = Some(Box::new(OpacityMask::new(n, true))); + n = owner; + } + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::DEEP_MASKS), "{:?}", out.warnings); + let p = String::from_utf8(out.program).unwrap().replace("\r\n", "\n"); + assert!(!p.contains("%_X=\n%_X+\n"), "no empty mask"); + // The masks within the limit are read back, one in the art of the other. + let back = read_back(&doc); + let mut n = back.layers[0].children().unwrap()[0].clone(); + let mut depth = 0; + while let Some(m) = n.extras().mask.clone() { + depth += 1; + n = match &m.art.kind { + NodeKind::Group { children, .. } if children.len() == 1 => children[0].clone(), + _ => m.art.clone(), + }; + } + assert_eq!(depth, 8); +} + +#[test] +fn a_clipping_object_other_than_a_path_cuts_the_art() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let t = vectorcraft_doc::TextObject::point( + vectorcraft_geom::Point::new(10.0, 70.0), + "Type", + vectorcraft_doc::CharStyle { size: 18.0, fill: solid(Color::BLACK), ..vectorcraft_doc::CharStyle::default() }, + ); + let t = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![t, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::CLIPPING), "{:?}", out.warnings); + assert!(!String::from_utf8(out.program).unwrap().contains("\nq\n")); + // The type's black fill under the blue square, both cut to the type: within its line, + // narrower than the square. + assert_eq!(cut_to_type(&read_back(&doc).layers[0]), ["black", "blue"]); +} + +/// The colors of the paths `layer` holds, in paint order, each kind once, after checking that they +/// all lie within the line of type `Type` set at (10, 70) in 18 points. +fn cut_to_type(layer: &Node) -> Vec<&'static str> { + let mut all = vec![]; + paths(layer.children().unwrap(), &mut all); + let b = all.iter().filter_map(|n| n.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert!(b.x0 >= 9.0 && b.x1 < 100.0 && b.y0 > 40.0 && b.y1 < 80.0, "{b:?}"); + let mut colors = vec![]; + for n in &all { + let c = match n.appearance.fill().map(|f| paint(&f.paint)) { + Some(p) if p == paint(&solid(Color::BLACK)) => "black", + Some(p) if p == paint(&solid(Color::rgb(0.0, 0.0, 1.0))) => "blue", + _ => "other", + }; + if colors.last() != Some(&c) { + colors.push(c); + } + } + colors +} + +/// A clipping layer whose clipping object isn't a path is written as a layer that doesn't clip, +/// holding its art cut to that object. +#[test] +fn a_clipping_layer_clipped_by_type_is_not_written_as_a_clipping_layer() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let t = vectorcraft_doc::TextObject::point( + vectorcraft_geom::Point::new(10.0, 70.0), + "Type", + vectorcraft_doc::CharStyle { size: 18.0, fill: solid(Color::BLACK), ..vectorcraft_doc::CharStyle::default() }, + ); + let t = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, t).unwrap(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.0, 0.0, 1.0)); + doc.insert(Some(layer), usize::MAX, inside).unwrap(); + if let NodeKind::Layer { clip, .. } = &mut Arc::make_mut(&mut doc.layers[0]).kind { + *clip = true; + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::CLIPPING), "{:?}", out.warnings); + let p = String::from_utf8(out.program).unwrap().replace("\r\n", "\n"); + assert!(p.contains(" 0 50 0 Lb\n") && !p.contains(" 0 50 1 Lb\n") && !p.contains("\nW\n"), "{p}"); + let back = read_back(&doc); + assert!(matches!(back.layers[0].kind, NodeKind::Layer { clip: false, .. })); + assert_eq!(cut_to_type(&back.layers[0]), ["black", "blue"]); +} + +/// An empty clipping layer is written as an empty layer. +#[test] +fn an_empty_clipping_layer_is_an_empty_layer() { + let mut doc = Document::new(200.0, 100.0); + if let NodeKind::Layer { clip, .. } = &mut Arc::make_mut(&mut doc.layers[0]).kind { + *clip = true; + } + let p = program(&doc); + assert!(p.contains(" 0 50 0 Lb\n(Layer 1) Ln\n") && !p.contains("\nu\n"), "{p}"); + let back = read_back(&doc); + assert!(back.layers[0].children().is_none_or(Vec::is_empty), "{:?}", back.layers[0]); +} + +/// A guide takes its own transparency, not the one of the object before it. +#[test] +fn guides_keep_their_own_transparency() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let bright = see_through(square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb(1.0, 0.0, 0.0)), 0.5, BlendMode::Screen); + doc.insert(Some(layer), usize::MAX, bright).unwrap(); + for (r, opacity, blend) in + [(Rect::new(20.0, 20.0, 40.0, 40.0), 1.0, BlendMode::Normal), (Rect::new(50.0, 20.0, 70.0, 40.0), 0.4, BlendMode::Multiply)] + { + let mut g = clipping(&mut doc, shapes::rectangle(r)); + g.kind = NodeKind::Path { path: shapes::rectangle(r), rule: FillRule::NonZero, live: None, clipping: false, guide: true }; + doc.insert(Some(layer), usize::MAX, see_through(g, opacity, blend)).unwrap(); + } + let back = read_back(&doc); + let got: Vec<(bool, f32, BlendMode)> = + back.layers[0].children().unwrap().iter().map(|n| (matches!(n.kind, NodeKind::Path { guide: true, .. }), n.opacity, n.blend)).collect(); + assert_eq!(got, [(false, 0.5, BlendMode::Screen), (true, 1.0, BlendMode::Normal), (true, 0.4, BlendMode::Multiply)]); +} + +/// The transparency a group's last member or a group's state block sets carries over to the object +/// after the group, which then writes no `Xy` of its own when it has the same. +#[test] +fn objects_after_a_group_keep_their_transparency() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let red = Color::rgb(1.0, 0.0, 0.0); + let screen = |doc: &mut Document, x: f64| see_through(square(doc, Rect::new(x, 0.0, x + 10.0, 10.0), red), 0.5, BlendMode::Screen); + // A plain group whose last member is at 50% in Screen, then a path the same. + let a = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), red); + let b = screen(&mut doc, 10.0); + let plain = group(&mut doc, vec![a, b], false); + let after_plain = screen(&mut doc, 30.0); + // A group at 40% with knockout off, then a path at 40%. + let c = square(&mut doc, Rect::new(50.0, 0.0, 60.0, 10.0), red); + let mut faint = see_through(group(&mut doc, vec![c], false), 0.4, BlendMode::Normal); + faint.knockout = Knockout::Off; + let after_faint = see_through(square(&mut doc, Rect::new(70.0, 0.0, 80.0, 10.0), red), 0.4, BlendMode::Normal); + for n in [plain, after_plain, faint, after_faint] { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let p = program(&doc); + // No `Xy` between the groups' state blocks and the paths after them: the second square's, the + // third's (opaque, after the second) and the second group's. + let after = |block: &str| p.split_once(block).unwrap().1.split_once("\nf\n").unwrap().0.to_string(); + assert!(!after("U\n9 () XW\n").contains("Xy"), "{p}"); + assert!(!after("U\n0 0.4 0 0 0 Xy\n0 0 Xd\n6 () XW\n").contains("Xy"), "{p}"); + assert_eq!(p.matches(" Xy\n").count(), 3, "{p}"); + same_lines(&all_looks(&read_back(&doc)), &all_looks(&doc)); +} + +#[test] +fn transparency_of_single_fills_and_layer_masks_is_reported_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut fill = FillLayer::new(solid(Color::BLACK)); + fill.opacity = 0.5; + let n = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance { items: vec![AppearanceItem::Fill(fill)], ..Appearance::default() }, + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::gray(0.5)); + Arc::make_mut(&mut doc.layers[0]).extras_mut().mask = Some(Box::new(OpacityMask::new(art, true))); + let out = export_ai_editing(&doc, &opts()).unwrap(); + for w in [writer::ITEM_TRANSPARENCY, writer::LAYER_MASKS] { + assert!(out.warnings.iter().any(|x| x == w), "{w}: {:?}", out.warnings); + } + // A disabled one too. + if let Some(m) = Arc::make_mut(&mut doc.layers[0]).extras_mut().mask.as_mut() { + m.disabled = true; + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|x| x == writer::LAYER_MASKS), "{:?}", out.warnings); + // A clipping path's fill of its own opacity. + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0))); + let mut fill = FillLayer::new(solid(Color::BLACK)); + fill.opacity = 0.5; + clip.appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Appearance::default() }.into(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 20.0, 20.0), Color::gray(0.5)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|x| x == writer::ITEM_TRANSPARENCY), "{:?}", out.warnings); +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index e0afd03660..99f8cb607d 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use vectorcraft_color::cms::Cms; use vectorcraft_color::swatch::{REGISTRATION, Swatch}; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{AppearanceItem, Document, FillLayer, LAYER_COLORS, LayerColor, Node, NodeKind, StrokeLayer}; +use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LAYER_COLORS, LayerColor, Node, NodeKind, OpacityMask, StrokeLayer}; use vectorcraft_effects::stroke; use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape, SubPath}; use vectorcraft_pathops::BoolOp; @@ -28,18 +28,78 @@ pub(super) const TYPE: &str = "type is written as its outlines in the editing da pub(super) const GRADIENTS: &str = "gradients are written as their average color in the editing data for other apps"; const PATTERNS: &str = "pattern fills are written as their tiles cut to the shape in the editing data for other apps"; pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps"; -pub(super) const CLIPPING: &str = - "clipping groups and clipping layers are written as their art cut to the clipping path in the editing data for other apps"; +pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps"; +pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps"; +pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; pub(super) const IMAGES: &str = "images are written as their outlines filled with their average color in the editing data for other apps"; pub(super) const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; -pub(super) const TRANSPARENCY: &str = "transparency (opacity, blending modes, opacity masks) is left out of the editing data for other apps"; +pub(super) const ITEM_TRANSPARENCY: &str = + "the opacity and blending modes of single fills and strokes are left out of the editing data for other apps"; +pub(super) const LAYER_MASKS: &str = "opacity masks on layers are left out of the editing data for other apps"; +pub(super) const DEEP_MASKS: &str = + "opacity masks more than 8 deep in opacity masks, symbols, live objects and pattern tiles are left out of the editing data for other apps"; +const GROUPED_LAYER: &str = + "the transparency and opacity masks of layers that an effect made into a group are left out of the editing data for other apps"; pub(super) const EFFECTS: &str = "live effects other than geometry effects are left out of the editing data for other apps"; const SWATCHES: &str = "gradient and pattern swatches are left out of the editing data for other apps"; pub(super) const SYMBOL_LIMIT: &str = "symbol instances past 16,000,000 objects of symbol art in all are left out of the editing data for other apps"; const TEMPLATES: &str = "template layers are written as dimmed layers that don't print in the editing data for other apps"; +/// The transparency `mode opacity isolate knockout shape Xy` sets: the blending mode ([`blend_code`]), +/// the opacity, Isolate Blending, Knockout Group (0 off, 1 on, 2 neutral) and Opacity & Mask Define +/// Knockout Shape. It stays set for the objects that follow, as the lock and hidden state do; a +/// group, a clipping group or a layer takes it after its end. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Xy { + blend: BlendMode, + opacity: f32, + isolate: bool, + knockout: Knockout, + shape: bool, +} + +impl Xy { + /// The state before any `Xy`, and an opaque path's. + const OPAQUE: Xy = Xy { blend: BlendMode::Normal, opacity: 1.0, isolate: false, knockout: Knockout::Off, shape: false }; + /// A group's or a layer's without transparency of its own (no `Xy` after its end). + const PLAIN: Xy = Xy { knockout: Knockout::Neutral, ..Self::OPAQUE }; + + /// `n`'s transparency. + fn of(n: &Node) -> Xy { + let opacity = if n.opacity.is_finite() { n.opacity.clamp(0.0, 1.0) } else { 1.0 }; + Xy { blend: n.blend, opacity, isolate: n.isolate, knockout: n.knockout, shape: n.knockout_shape } + } + + /// As a path's own: isolation and knockout are a group's. + fn object(self) -> Xy { + Xy { isolate: false, knockout: Knockout::Off, ..self } + } +} + +/// The number `Xy` gives blending mode `b`. +fn blend_code(b: BlendMode) -> u8 { + match b { + BlendMode::Normal => 0, + BlendMode::Multiply => 1, + BlendMode::Screen => 2, + BlendMode::Overlay => 3, + BlendMode::SoftLight => 4, + BlendMode::HardLight => 5, + BlendMode::ColorDodge => 6, + BlendMode::ColorBurn => 7, + BlendMode::Darken => 8, + BlendMode::Lighten => 9, + BlendMode::Difference => 10, + BlendMode::Exclusion => 11, + BlendMode::Hue => 12, + BlendMode::Saturation => 13, + BlendMode::Color => 14, + BlendMode::Luminosity => 15, + } +} + pub(super) struct Writer<'a> { doc: &'a Document, /// The document → art space. @@ -49,6 +109,12 @@ pub(super) struct Writer<'a> { pub(super) warnings: Vec, /// The lock and hidden state (`A`, `Xw`) the last operators set; `None` at a layer's start. state: Option<(bool, bool)>, + /// The transparency the last `Xy` set; `None` when it isn't known (after an opacity mask, whose + /// art's last `Xy` stays set). + gs: Option, + /// Where the state block of the group ended last starts and ends in [`Self::body`]. + block_start: usize, + block_end: usize, /// The region the art being written is cut to (a clipping path's, in document space). clip: Option, /// Symbols, live objects and pattern tiles being written inside one another. @@ -72,6 +138,9 @@ impl<'a> Writer<'a> { body: String::new(), warnings: vec![], state: None, + gs: Some(Xy::OPAQUE), + block_start: 0, + block_end: usize::MAX, clip: None, nest: 0, ids: HashSet::new(), @@ -115,9 +184,12 @@ impl<'a> Writer<'a> { return self.write_layer(n, &[]); } let members = n.children().map(Vec::as_slice).unwrap_or_default(); - self.transparency(n); + self.effects(n); match members.iter().find(|c| c.is_layer()) { Some(l) => { + if Xy::of(n) != Xy::PLAIN || n.extras().mask.is_some() { + self.warn(GROUPED_LAYER); + } // The group took the layer's name. The added art is outside the layer's clipping. let layer = Node { name: l.name.clone().or_else(|| n.name.clone()), ..(**l).clone() }; let added: Vec> = members.iter().filter(|c| !c.is_layer()).cloned().collect(); @@ -131,8 +203,9 @@ impl<'a> Writer<'a> { } } - /// A layer or sublayer: `%AI5_BeginLayer`, its options `Lb`, its name `Ln` and as an XML id, its art, then - /// `after` (outside its clipping path when it clips), `LB`, `%AI5_EndLayer--`. + /// A layer or sublayer: `%AI5_BeginLayer`, its options `Lb`, its name `Ln` and as an XML id, its art (its + /// clipping path last, with `W`, when it clips), `after` (outside the clipping path), its transparency + /// (`Xy`, `0 0 Xd`, `7 () XW`) when it has any, `LB`, `%AI5_EndLayer--`. fn write_layer(&mut self, n: &Node, after: &[Arc]) { let NodeKind::Layer { color, template, printable, children, clip, preview, dim_images } = &n.kind else { return }; let [r, g, b] = match color { @@ -146,25 +219,36 @@ impl<'a> Writer<'a> { if *template { self.warn(TEMPLATES); } - self.transparency(n); + self.effects(n); + if n.extras().mask.is_some() { + self.warn(LAYER_MASKS); + } let flag = |b: bool| u8::from(b); let dim = dim_images.unwrap_or(50); let name = n.name.as_deref().unwrap_or("Layer"); + // The last flag makes the layer a clipping layer: its top object clips the rest. Only a + // clipping path or compound path, outside any art cut to a clipping object, is written as + // one ([`Self::clip_group`] writes the others). + let clips = *clip && after.is_empty() && self.clip.is_none() && children.first().is_some_and(|c| clip_path(c).is_some()); let _ = writeln!( self.body, - "%AI5_BeginLayer\n{} {} {} {} {} 0 1 {index} {r} {g} {b} 0 {dim} 0 Lb\n{} Ln", + "%AI5_BeginLayer\n{} {} {} {} {} 0 1 {index} {r} {g} {b} 0 {dim} {} Lb\n{} Ln", flag(n.visible), flag(*preview), flag(!n.locked), flag(*printable && !*template), flag(dim_images.is_some() || *template), + flag(clips), ps::bytes(name.as_bytes()), ); self.xml_id(if name.is_empty() { "Layer" } else { name }); self.state = None; - if *clip { - self.warn(CLIPPING); - self.clip_contents(children); + if clips { + self.clipped(children); + } else if *clip && !children.is_empty() { + // The added art lies outside the clipping path, or the clipping object isn't a path: + // the clipped art is a clipping group, or a group of the art cut to the object. + self.clip_group(children, Xy::PLAIN); } else { for c in children { self.node(c); @@ -173,6 +257,12 @@ impl<'a> Writer<'a> { for c in after { self.node(c); } + let xy = Xy::of(n); + if xy != Xy::PLAIN { + // Always written: the layer takes the `Xy` its own state block has. + self.write_xy(xy); + self.line("0 0 Xd\n7 () XW"); + } self.line("LB\n%AI5_EndLayer--"); // The reader's state carries over into the art that follows. self.state = None; @@ -193,59 +283,86 @@ impl<'a> Writer<'a> { self.state = Some((locked, hidden)); } - /// Warn when `n` has transparency or effects the data leaves out. - fn transparency(&mut self, n: &Node) { - if n.opacity < 1.0 || n.blend != BlendMode::Normal || n.extras().mask.as_ref().is_some_and(|m| !m.disabled) { - self.warn(TRANSPARENCY); + /// Set the transparency of the object that follows to `xy` (`Xy`, when it isn't set already). + fn set_xy(&mut self, xy: Xy) { + if self.gs != Some(xy) { + self.write_xy(xy); } + } + + /// `mode opacity isolate knockout shape Xy`. + fn write_xy(&mut self, xy: Xy) { + let knockout = match xy.knockout { + Knockout::Off => 0, + Knockout::On => 1, + Knockout::Neutral => 2, + }; + let _ = write!(self.body, "{} ", blend_code(xy.blend)); + ps::push_num(&mut self.body, f64::from(xy.opacity)); + let _ = writeln!(self.body, " {} {knockout} {} Xy", u8::from(xy.isolate), u8::from(xy.shape)); + self.gs = Some(xy); + } + + /// The end `close` (`U` or `Q`) of a group of transparency `xy`, then its state block: when it + /// has transparency of its own, `Xy`, `0 0 Xd` and `6 () XW`; else `9 () XW`. The group's + /// dictionary goes between the two ([`Self::node`]). + fn end_group(&mut self, close: &str, xy: Xy) { + self.line(close); + self.block_start = self.body.len(); + if xy == Xy::PLAIN { + self.line("9 () XW"); + } else { + self.write_xy(xy); + self.line("0 0 Xd\n6 () XW"); + } + self.block_end = self.body.len(); + } + + /// Warn when `n` has effects the data leaves out. + fn effects(&mut self, n: &Node) { let items = n.appearance.items.iter().filter(|i| i.visible()).flat_map(|i| i.effects()); if n.appearance.effects.iter().chain(items).any(|e| e.visible) { self.warn(EFFECTS); } } - /// One object, its state before it and its name after it. + /// One object: its state before it, its transparency, and its name and opacity mask after it. fn node(&mut self, n: &Node) { if let NodeKind::Layer { .. } = n.kind { return self.write_layer(n, &[]); } - self.transparency(n); + self.effects(n); self.state(n.locked, !n.visible); + let xy = Xy::of(n); let start = self.body.len(); match &n.kind { NodeKind::Layer { .. } => {} - NodeKind::Group { children, clip } => { + NodeKind::Group { children, clip: true } => self.clip_group(children, xy), + NodeKind::Group { children, clip: false } => { self.line("u"); - if *clip { - self.warn(CLIPPING); - self.clip_contents(children); - } else { - for c in children { - self.node(c); - } + for c in children { + self.node(c); } - self.line("U"); + self.end_group("U", xy); } NodeKind::Path { path, rule, guide, .. } => { if *guide { + // Its own transparency, not the one the object before it set. + if path.subpaths.iter().any(|sp| !sp.anchors.is_empty()) { + self.set_xy(xy.object()); + } ai_ops::guide(&mut self.body, self.to_art, path, true); } else { - self.shape(n, path, *rule); + self.shape(n, path, *rule, xy); } } - NodeKind::Compound { children, rule } => { - let mut subpaths = vec![]; - for p in children.iter().filter_map(|c| c.path_data()) { - subpaths.extend(p.subpaths.iter().cloned()); - } - self.shape(n, &PathData::new(subpaths), *rule); - } - NodeKind::Text(_) => self.text(n), + NodeKind::Compound { rule, .. } => self.shape(n, &compound_path(n), *rule, xy), + NodeKind::Text(_) => self.text(n, xy), NodeKind::Image(im) => { let bounds = PathData::from_bezpath(&(im.xf * Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1))); let color = image_average(self.doc.image_blob(im).map(|b| b.bytes.as_slice())); self.warn(IMAGES); - self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(color))); + self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(color)), xy); } NodeKind::SymbolInstance { symbol, xf } => { self.warn(LIVE); @@ -284,7 +401,7 @@ impl<'a> Writer<'a> { self.warn(SYMBOL_LIMIT); } } - self.line("U"); + self.end_group("U", xy); } NodeKind::Blend { .. } | NodeKind::Envelope { .. } @@ -302,23 +419,53 @@ impl<'a> Writer<'a> { } self.nest -= 1; } - self.line("U"); + self.end_group("U", xy); } } if self.body.len() > start { - self.name(n); + // A group's dictionary goes between its end and its state block. + let block = (self.block_end == self.body.len() && self.block_start >= start).then(|| self.body.split_off(self.block_start)); + self.block_end = usize::MAX; + self.dictionary(n); + if let Some(b) = block { + self.body.push_str(&b); + } } } - /// `n`'s name, after it (see [`Self::xml_id`]). - fn name(&mut self, n: &Node) { - let Some(name) = n.name.as_deref().filter(|s| !s.is_empty()) else { return }; - self.xml_id(name); + /// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]) + /// or an opacity mask (`AI9_Mask`, see [`Self::mask`]). + fn dictionary(&mut self, n: &Node) { + let name = n.name.as_deref().filter(|s| !s.is_empty()); + let mut mask = n.extras().mask.as_deref(); + // Masks nested too deep are left out (an empty mask would hide the object). + if mask.is_some() && self.nest >= MAX_NEST { + self.warn(DEEP_MASKS); + mask = None; + } + if name.is_none() && mask.is_none() { + return; + } + self.body.push_str("%_/ArtDictionary :\n"); + if let Some(name) = name { + let id = self.take_id(name); + let _ = writeln!(self.body, "%_/XMLUID : {} ; (AI10_ArtUID) ,", ps::bytes(id.as_bytes())); + } + if let Some(m) = mask { + self.mask(m); + } + self.body.push_str("%_;\n%_\n"); } - /// An `/ArtDictionary` whose `AI10_ArtUID` is `name` as an XML id, numbered (`_` and 20 - /// digits, `_`) when a layer or another object has that id. + /// An `/ArtDictionary` whose `AI10_ArtUID` is `name` as an XML id. fn xml_id(&mut self, name: &str) { + let id = self.take_id(name); + let _ = writeln!(self.body, "%_/ArtDictionary :\n%_/XMLUID : {} ; (AI10_ArtUID) ,\n%_;\n%_", ps::bytes(id.as_bytes())); + } + + /// `name` as an XML id no layer or object has yet, numbered (`_` and 20 digits, `_`) when one + /// has it. + fn take_id(&mut self, name: &str) -> String { let base = vectorcraft_doc::xml_id::from_object_name(name); let mut id = base.clone(); let next = self.next.entry(base.clone()).or_insert(0); @@ -327,7 +474,150 @@ impl<'a> Writer<'a> { id = format!("{base}_{next:020}_"); } self.ids.insert(id.clone()); - let _ = writeln!(self.body, "%_/ArtDictionary :\n%_/XMLUID : {} ; (AI10_ArtUID) ,\n%_;\n%_", ps::bytes(id.as_bytes())); + id + } + + /// An opacity mask, as an entry of its object's dictionary: `/Mask :`, `X=`, its art on `%_` + /// lines (from the state a dictionary's art starts in: unlocked, shown, opaque), `X+`, `(Art) ,`, + /// its options as the `/Bool` entries `Clipping`, `Inverted`, `Disabled` and `Linked`, and + /// `; (AI9_Mask) ,`. The art is in document coordinates, as the object's is. + fn mask(&mut self, m: &OpacityMask) { + let outer = std::mem::take(&mut self.body); + let (state, clip) = (self.state, self.clip.take()); + (self.state, self.gs) = (Some((false, false)), Some(Xy::OPAQUE)); + // A plain group holding the art is the group the art is read into. + let art = &m.art; + let plain = matches!(art.kind, NodeKind::Group { clip: false, .. }) + && Xy::of(art) == Xy::PLAIN + && art.visible + && !art.locked + && art.name.as_deref().is_none_or(str::is_empty) + && art.extras().mask.is_none(); + let members = match art.children() { + Some(c) if plain => c.as_slice(), + _ => std::slice::from_ref(art), + }; + self.nest += 1; + for c in members { + self.node(c); + } + self.nest -= 1; + let lines = std::mem::replace(&mut self.body, outer); + self.body.push_str("%_/Mask :\n%_X=\n"); + for l in lines.lines() { + if !l.starts_with("%_") { + self.body.push_str("%_"); + } + self.body.push_str(l); + self.body.push('\n'); + } + self.body.push_str("%_X+\n%_(Art) ,\n"); + for (key, on) in [("Clipping", m.clip), ("Inverted", m.invert), ("Disabled", m.disabled), ("Linked", m.linked)] { + let _ = writeln!(self.body, "%_{} /Bool ({key}) ,", u8::from(on)); + } + self.body.push_str("%_; (AI9_Mask) ,\n"); + // The dictionary ends with the state before it, except the transparency its art set last. + (self.state, self.gs, self.clip, self.block_end) = (state, None, clip, usize::MAX); + } + + /// Warn that art is cut to clipping object `first` when it isn't a path or compound path (a path + /// without points cuts everything away, as it clips everything away). + fn warn_cut(&mut self, first: Option<&Arc>) { + if first.is_some_and(|c| !matches!(c.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. })) { + self.warn(CLIPPING); + } + } + + /// A clipping group: `q`, its members, its clipping path or compound path last (the top object: + /// a mask shows the objects beneath it, §5.6.2) with `W`, `Q`, then the group's transparency. + /// `Q` sets back the state at `q`. A clipping object of another kind cuts the members instead, + /// in a group ([`Self::clip_contents`]). A clipping group without members is an empty group. + fn clip_group(&mut self, children: &[Arc], xy: Xy) { + if self.clip.is_some() || children.first().is_none_or(|c| clip_path(c).is_none()) { + self.warn_cut(children.first()); + // Inside art cut to a clipping object, a clipping path cuts its art too. + if self.clip.is_some() && !children.is_empty() { + self.warn(CLIPPING); + } + self.line("u"); + self.clip_contents(children); + return self.end_group("U", xy); + } + let at_q = (self.state, self.gs); + self.line("q"); + self.clipped(children); + (self.state, self.gs) = at_q; + self.end_group("Q", xy); + } + + /// The members of a clipping group or layer, the first one clipping the others: the others, + /// then the first one as the clipping path (see [`Self::clip_group`]), its name after it. Fills + /// and strokes the clipping path can't paint itself are paths of their own, the fills under the + /// others and the strokes over them. + fn clipped(&mut self, children: &[Arc]) { + let Some((first, rest)) = children.split_first() else { return }; + let Some((path, rule)) = clip_path(first) else { + self.warn_cut(Some(first)); + return self.clip_contents(children); + }; + let painted = plain_paint(first); + if visible_items(first).iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) { + self.warn(ITEM_TRANSPARENCY); + } + // Paint the clipping path can't carry: its fills under the others, its strokes over them. + let (fills, strokes): (Vec<&AppearanceItem>, Vec<&AppearanceItem>) = + if painted.is_none() { visible_items(first).into_iter().partition(|i| matches!(i, AppearanceItem::Fill(_))) } else { (vec![], vec![]) }; + if painted.is_none() { + self.warn(CLIP_PAINT); + if first.extras().mask.is_some() && !visible_items(first).is_empty() { + self.warn(CLIP_PAINT_MASKS); + } + } + self.clip_paint_part(first, &path, rule, &fills); + for c in rest { + self.node(c); + } + self.clip_paint_part(first, &path, rule, &strokes); + let (fill, stroke) = painted.unwrap_or_default(); + self.state(first.locked, !first.visible); + let start = self.body.len(); + self.paint_state(fill, stroke, Xy::of(first).object(), rule); + let op = paint_op(fill.is_some(), stroke.is_some()); + let subpaths: Vec<&SubPath> = path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).collect(); + let several = subpaths.len() > 1; + if several { + self.line("*u"); + } + for sp in subpaths { + ai_ops::subpath(&mut self.body, self.to_art, sp); + let op = if sp.closed { op } else { op.to_ascii_uppercase() }; + let _ = writeln!(self.body, "{}\nW\n{op}", if sp.closed { 'h' } else { 'H' }); + } + if several { + self.line("*U"); + } + if self.body.len() > start { + self.dictionary(first); + } + } + + /// The fills or the strokes `items` of clipping path `first` (outline `path`) that it can't paint + /// itself, locked and hidden as it is, with its transparency once for all of them: one object, + /// or a group of an object for each (as the canvas draws them, [`Node::clip_paint`]). + fn clip_paint_part(&mut self, first: &Node, path: &PathData, rule: FillRule, items: &[&AppearanceItem]) { + if items.is_empty() { + return; + } + self.state(first.locked, !first.visible); + let xy = Xy::of(first); + if let [one] = items { + return self.item(path, rule, one, xy); + } + self.line("u"); + for i in items { + self.item(path, rule, i, Xy::PLAIN); + } + self.end_group("U", xy); } /// A container's members, the first one's outline cutting the others: its fills painted @@ -362,63 +652,49 @@ impl<'a> Writer<'a> { // ---------- paths ---------- - /// A path's fills and strokes: one object with one fill and a plain stroke over it where it - /// can be, else a group of an object for each (in paint order). - fn shape(&mut self, n: &Node, path: &PathData, rule: FillRule) { + /// A path's fills and strokes, with the path's transparency `xy`: one object with one fill and + /// a plain stroke over it where it can be, else a group of an object for each (in paint order). + fn shape(&mut self, n: &Node, path: &PathData, rule: FillRule, xy: Xy) { if path.is_empty() { return; } - let items: Vec<&AppearanceItem> = n - .appearance - .items - .iter() - .filter(|i| match i { - AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(), - AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0 && s.width.is_finite(), - }) - .collect(); + let items = visible_items(n); if items.iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) { - self.warn(TRANSPARENCY); + self.warn(ITEM_TRANSPARENCY); } - let solid = |p: &Paint| matches!(p, Paint::Solid { .. }); - match items.as_slice() { - [] => self.path_object(path, rule, None, None), - [AppearanceItem::Fill(f)] if solid(&f.paint) => self.path_object(path, rule, Some(f), None), - [AppearanceItem::Stroke(s)] if direct_stroke(s) => self.path_object(path, rule, None, Some(s)), - [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] if solid(&f.paint) && direct_stroke(s) => { - self.path_object(path, rule, Some(f), Some(s)) - } - [one] => self.item(path, rule, one), - items => { + match (plain_paint(n), items.as_slice()) { + (Some((fill, stroke)), _) => self.path_object(path, rule, fill, stroke, xy), + (None, [one]) => self.item(path, rule, one, xy), + (None, items) => { self.line("u"); for i in items { - self.item(path, rule, i); + self.item(path, rule, i, Xy::PLAIN); } - self.line("U"); + self.end_group("U", xy); } } } - /// One fill or stroke of a path as an object of its own. - fn item(&mut self, path: &PathData, rule: FillRule, item: &AppearanceItem) { + /// One fill or stroke of a path as an object of its own, of transparency `xy`. + fn item(&mut self, path: &PathData, rule: FillRule, item: &AppearanceItem, xy: Xy) { match item { - AppearanceItem::Fill(f) => self.fill_object(path, rule, f), - AppearanceItem::Stroke(s) if direct_stroke(s) => self.path_object(path, rule, None, Some(s)), + AppearanceItem::Fill(f) => self.fill_object(path, rule, f, xy), + AppearanceItem::Stroke(s) if direct_stroke(s) => self.path_object(path, rule, None, Some(s), xy), AppearanceItem::Stroke(s) => { self.warn(STROKES); - if self.brush_art(path, s) { + if self.brush_art(path, s, xy) { return; } let outline = stroke::outline_region(path, rule, s); let fill = FillLayer { overprint: s.overprint, ..FillLayer::new(s.paint.clone()) }; - self.fill_object(&outline, FillRule::NonZero, &fill); + self.fill_object(&outline, FillRule::NonZero, &fill, xy); } } } - /// A brushed stroke `st` of `path` as a group of its brush's art. False when it has no brush - /// the document knows (or brushes nest too deep). - fn brush_art(&mut self, path: &PathData, st: &StrokeLayer) -> bool { + /// A brushed stroke `st` of `path` as a group of its brush's art, of transparency `xy`. False + /// when it has no brush the document knows (or brushes nest too deep). + fn brush_art(&mut self, path: &PathData, st: &StrokeLayer, xy: Xy) -> bool { if self.nest >= MAX_NEST { return false; } @@ -435,27 +711,27 @@ impl<'a> Writer<'a> { if let Some((locked, hidden)) = state { self.state(locked, hidden); } - self.line("U"); + self.end_group("U", xy); self.nest -= 1; true } - /// A fill as an object of its own: a gradient as its average color, a pattern as its tiles - /// cut to the path. - fn fill_object(&mut self, path: &PathData, rule: FillRule, f: &FillLayer) { + /// A fill as an object of its own, of transparency `xy`: a gradient as its average color, a + /// pattern as its tiles cut to the path. + fn fill_object(&mut self, path: &PathData, rule: FillRule, f: &FillLayer, xy: Xy) { match &f.paint { - Paint::Solid { .. } => self.path_object(path, rule, Some(f), None), + Paint::Solid { .. } => self.path_object(path, rule, Some(f), None, xy), Paint::Gradient(g) => { self.warn(GRADIENTS); let flat = FillLayer { paint: Paint::solid(average(&g.gradient)), ..f.clone() }; - self.path_object(path, rule, Some(&flat), None); + self.path_object(path, rule, Some(&flat), None, xy); } Paint::Pattern { pattern, xf } => { self.warn(PATTERNS); let doc = self.doc; let Some(def) = doc.pattern(pattern).filter(|_| self.nest < MAX_NEST) else { let flat = FillLayer { paint: Paint::solid(Color::gray(0.5)), ..f.clone() }; - return self.path_object(path, rule, Some(&flat), None); + return self.path_object(path, rule, Some(&flat), None, xy); }; let tiles = def.instances_in(*xf, path.to_bezpath().bounding_box()); // More tiles than a fill places come back as none: the shape is filled gray, as a @@ -463,7 +739,7 @@ impl<'a> Writer<'a> { if tiles.is_empty() && !def.art.is_empty() { self.warn(PATTERN_TILES); let flat = FillLayer { paint: Paint::solid(Color::gray(0.5)), ..f.clone() }; - return self.path_object(path, rule, Some(&flat), None); + return self.path_object(path, rule, Some(&flat), None, xy); } let outer = self.clip.clone(); let region = self.cut(path, rule); @@ -477,7 +753,7 @@ impl<'a> Writer<'a> { if let Some((locked, hidden)) = state { self.state(locked, hidden); } - self.line("U"); + self.end_group("U", xy); self.nest -= 1; self.clip = outer; } @@ -485,39 +761,39 @@ impl<'a> Writer<'a> { } } - /// A path object painted with `fill` (a color) and `stroke` (a plain line of a color) over - /// it; several subpaths make a compound path. Where the art is cut to a clipping path, the - /// fill is the path's region cut to it and the stroke its outline cut to it, filled. - fn path_object(&mut self, path: &PathData, rule: FillRule, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>) { + /// A path object of transparency `xy` painted with `fill` (a color) and `stroke` (a plain line + /// of a color) over it; several subpaths make a compound path. Where the art is cut to a + /// clipping path, the fill is the path's region cut to it and the stroke its outline cut to it, + /// filled. + fn path_object(&mut self, path: &PathData, rule: FillRule, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>, xy: Xy) { if self.clip.is_none() { - return self.plain_object(path, rule, fill, stroke); + return self.plain_object(path, rule, fill, stroke, xy.object()); } let both = fill.is_some() && stroke.is_some(); + let own = if both { Xy::OPAQUE } else { xy.object() }; if both { self.line("u"); } if fill.is_some() || stroke.is_none() { let region = self.cut(path, rule); - self.plain_object(®ion, FillRule::NonZero, fill, None); + self.plain_object(®ion, FillRule::NonZero, fill, None, own); } if let Some(s) = stroke { let outline = stroke::outline_region(path, rule, s); let region = self.cut(&outline, FillRule::NonZero); let fill = FillLayer { overprint: s.overprint, ..FillLayer::new(s.paint.clone()) }; - self.plain_object(®ion, FillRule::NonZero, Some(&fill), None); + self.plain_object(®ion, FillRule::NonZero, Some(&fill), None, own); } if both { - self.line("U"); + self.end_group("U", xy); } } - /// [`Self::path_object`] without cutting: the paint (`O`/`R` overprint, line style), `XR`, - /// each subpath's points and painting operator (`*u` … `*U` around several). - fn plain_object(&mut self, path: &PathData, rule: FillRule, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>) { - let subpaths: Vec<&SubPath> = path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).collect(); - if subpaths.is_empty() { - return; - } + /// The paint of a path of transparency `xy` filled by `rule`: its fill color and `O`, its stroke + /// color and `R`, `Xy`, the line style, `XR`. Without paint, `XR` comes first: an `Xy` right + /// after a group or compound path would be theirs. + fn paint_state(&mut self, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>, xy: Xy, rule: FillRule) { + let rule = if rule == FillRule::EvenOdd { "1 XR" } else { "0 XR" }; if let Some(f) = fill { self.color(&f.paint, false); self.line(if f.overprint { "1 O" } else { "0 O" }); @@ -525,15 +801,27 @@ impl<'a> Writer<'a> { if let Some(s) = stroke { self.color(&s.paint, true); self.line(if s.overprint { "1 R" } else { "0 R" }); + } + if fill.is_none() && stroke.is_none() { + self.line(rule); + return self.set_xy(xy); + } + self.set_xy(xy); + if let Some(s) = stroke { ai_ops::line_style(&mut self.body, s); } - self.line(if rule == FillRule::EvenOdd { "1 XR" } else { "0 XR" }); - let op = match (fill.is_some(), stroke.is_some()) { - (true, true) => 'b', - (true, false) => 'f', - (false, true) => 's', - (false, false) => 'n', - }; + self.line(rule); + } + + /// [`Self::path_object`] without cutting: the paint ([`Self::paint_state`]), each subpath's + /// points and painting operator (`*u` … `*U` around several). + fn plain_object(&mut self, path: &PathData, rule: FillRule, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>, xy: Xy) { + let subpaths: Vec<&SubPath> = path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).collect(); + if subpaths.is_empty() { + return; + } + self.paint_state(fill, stroke, xy, rule); + let op = paint_op(fill.is_some(), stroke.is_some()); let several = subpaths.len() > 1; if several { self.line("*u"); @@ -554,8 +842,9 @@ impl<'a> Writer<'a> { /// Type `n` as a group of what Type › Create Outlines makes of it /// ([`vectorcraft_effects::outline_text`]): each run's glyphs with their underline and /// strikethrough, its color glyphs, and the object's own fills and strokes; then its inline - /// graphics as their symbols' art where the layout places them, as the PDF page draws them. - fn text(&mut self, n: &Node) { + /// graphics as their symbols' art where the layout places them, as the PDF page draws them; + /// the group has the type's transparency `xy`. + fn text(&mut self, n: &Node, xy: Xy) { self.warn(TYPE); self.line("u"); let doc = self.doc; @@ -605,7 +894,7 @@ impl<'a> Writer<'a> { if let Some((locked, hidden)) = state { self.state(locked, hidden); } - self.line("U"); + self.end_group("U", xy); } // ---------- color ---------- @@ -778,6 +1067,63 @@ fn direct_stroke(s: &StrokeLayer) -> bool { matches!(s.paint, Paint::Solid { .. }) && stroke::is_plain(s) } +/// `n`'s fills and strokes that paint. +fn visible_items(n: &Node) -> Vec<&AppearanceItem> { + n.appearance + .items + .iter() + .filter(|i| match i { + AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(), + AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0 && s.width.is_finite(), + }) + .collect() +} + +/// `n`'s paint as one path object paints: no paint, a fill of a color, a plain line of a color, +/// or both, the line over the fill; `None` when it has other paint. +fn plain_paint(n: &Node) -> Option<(Option<&FillLayer>, Option<&StrokeLayer>)> { + let solid = |p: &Paint| matches!(p, Paint::Solid { .. }); + match visible_items(n).as_slice() { + [] => Some((None, None)), + [AppearanceItem::Fill(f)] if solid(&f.paint) => Some((Some(f), None)), + [AppearanceItem::Stroke(s)] if direct_stroke(s) => Some((None, Some(s))), + [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] if solid(&f.paint) && direct_stroke(s) => Some((Some(f), Some(s))), + _ => None, + } +} + +/// The painting operator of a closed subpath (§5.3.3): `b` fill and stroke, `f` fill, `s` +/// stroke, `n` neither; an open one's is upper case. +fn paint_op(fill: bool, stroke: bool) -> char { + match (fill, stroke) { + (true, true) => 'b', + (true, false) => 'f', + (false, true) => 's', + (false, false) => 'n', + } +} + +/// The subpaths of compound path `n`'s members, as one path. +fn compound_path(n: &Node) -> PathData { + let mut subpaths = vec![]; + for p in n.children().map(Vec::as_slice).unwrap_or_default().iter().filter_map(|c| c.path_data()) { + subpaths.extend(p.subpaths.iter().cloned()); + } + PathData::new(subpaths) +} + +/// The outline and fill rule a clipping path or compound path `n` clips by; `None` for other +/// clipping objects and for a path without points (it clips everything away, see +/// [`Writer::clip_contents`]). +fn clip_path(n: &Node) -> Option<(PathData, FillRule)> { + let (path, rule) = match &n.kind { + NodeKind::Path { path, rule, guide: false, .. } => (path.clone(), *rule), + NodeKind::Compound { rule, .. } => (compound_path(n), *rule), + _ => return None, + }; + path.subpaths.iter().any(|sp| !sp.anchors.is_empty()).then_some((path, rule)) +} + /// The image `bytes` decoded, when its header gives at most [`MAX_AVERAGED_PIXELS`] pixels; the /// decoder may allocate at most 8 bytes a pixel. fn decode_bounded(bytes: &[u8]) -> Option { diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index f122812715..aefb80ccb1 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -71,7 +71,7 @@ use interp::{Fault, Interp}; use obj::PsError; pub(crate) use native::scale_document; -pub use native::{ai_alone, ai_alone_on_page, is_loss, layered_ai}; +pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_layers_alone, is_loss, layered_ai, layered_ai_from}; pub use text::family_style; /// The page of a PostScript file without a bounding box (US Letter). diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index f7e1f8893d..3904e6aabe 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -126,8 +126,9 @@ pub(super) enum BrushError { } /// The strings of a plug-in object's section (`section`: what follows `%AI8_BeginPluginObject`): -/// its plug-in name, its name and its parameters, joined. `None` with fewer than two strings. -pub(super) fn plugin_strings(section: &[u8]) -> Option<(String, String, String)> { +/// its plug-in name, its name and its parameters, joined. The name is `None` with one string, and +/// the whole is `None` with none. +pub(super) fn plugin_strings(section: &[u8]) -> Option<(String, Option, String)> { let mut lex = Lexer::new(section); let mut strings = vec![]; let mut params = vec![]; @@ -142,8 +143,9 @@ pub(super) fn plugin_strings(section: &[u8]) -> Option<(String, String, String)> } } } - let [kind, name]: [String; 2] = strings.try_into().ok()?; - Some((kind, name, obj::text(¶ms))) + let mut strings = strings.into_iter(); + let kind = strings.next()?; + Some((kind, strings.next(), obj::text(¶ms))) } /// The brush manager's order (`params`: its parameters): the kind and name of each brush. Pairs diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 6435c2dc69..a3eda140e5 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -310,10 +310,13 @@ struct Reader<'a> { /// dictionary (its name, its opacity mask and the mask's art). mesh_ended: bool, /// A layer's own state (`Xy` after its art, before `LB`), until something says the art moves on. - layer_state: Option<(f32, BlendMode, bool, Knockout)>, + layer_state: Option<(f32, BlendMode, bool, Knockout, bool)>, /// The state a mesh or blend had before an `Xy` right after its end, which is the layer's /// instead when the layer's `LB` follows rather than their own `6 () XW`. mesh_undo: Option<(f32, BlendMode, bool, Knockout)>, + /// The state a layer's last group or compound path had before an `Xy` right after its end, + /// which is the layer's instead when the layer's own `7 () XW` follows. + container_undo: Option<(f32, BlendMode, bool, Knockout, bool)>, /// Painted copies of clipping paths that have a fill (drawn under what they clip). clip_fills: HashSet, /// Groups closed as an object's drawn look (`9 () XW`). @@ -476,6 +479,7 @@ impl<'a> Reader<'a> { mesh_ended: false, layer_state: None, mesh_undo: None, + container_undo: None, styles: HashMap::new(), style_list: vec![], style_links: vec![], diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 09d056a4e2..2273f087ba 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -183,10 +183,12 @@ impl<'a> Reader<'a> { // The compound path's paint is its last path's (a gradient's instance wraps only // that one); the last painted one, should the last have none. let shown = kids.iter().rev().find(|k| !k.appearance.items.is_empty()).or(kids.last())?; - let (appearance, opacity, blend, rule) = (shown.appearance.clone(), shown.opacity, shown.blend, path_rule(shown)); + let (appearance, opacity, blend, shape, rule) = + (shown.appearance.clone(), shown.opacity, shown.blend, shown.knockout_shape, path_rule(shown)); for k in &mut kids { k.opacity = 1.0; k.blend = BlendMode::Normal; + k.knockout_shape = false; k.visible = true; k.locked = false; } @@ -194,6 +196,7 @@ impl<'a> Reader<'a> { n.appearance = appearance; n.opacity = opacity; n.blend = blend; + n.knockout_shape = shape; Some(n) } @@ -234,6 +237,7 @@ impl<'a> Reader<'a> { self.pending_unread_stroke = false; let mut f = self.close("LB", |k| matches!(k, Kind::Layer(_)))?; let state = self.layer_state.take(); + self.container_undo = None; // An `Xy` right after the layer's last mesh or blend, then `LB`: the layer's, not theirs. if let (Some(_), Some(before)) = (state, self.mesh_undo.take()) && let Some(mesh) = f.children.last_mut().filter(|n| matches!(n.kind, NodeKind::Mesh(_) | NodeKind::Blend { .. })) @@ -251,8 +255,8 @@ impl<'a> Reader<'a> { layer.visible = a.visible; layer.locked = a.locked; // The layer's own opacity, blend and knockout, written after its art (#2003). - if let Some((opacity, blend, isolate, knockout)) = state { - (layer.opacity, layer.blend, layer.isolate, layer.knockout) = (opacity, blend, isolate, knockout); + if let Some((opacity, blend, isolate, knockout, shape)) = state { + (layer.opacity, layer.blend, layer.isolate, layer.knockout, layer.knockout_shape) = (opacity, blend, isolate, knockout, shape); } match self.frames.last_mut() { Some(parent) => { diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index e2c9df048b..b1c9db39d3 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -518,16 +518,23 @@ impl<'a> Reader<'a> { } /// A plug-in object (`section`: what follows `%AI8_BeginPluginObject`): the brush manager's - /// order or a brush ([`brush`]); other objects are left alone. + /// order or a brush ([`brush`]); other objects are left alone. A brush without a name is counted + /// as not read. fn plugin_object(&mut self, section: &[u8]) { let Some((kind, name, params)) = brush::plugin_strings(section) else { return }; if kind == brush::MANAGER { - self.brush_objects = true; - self.brush_order = brush::parse_brush_manager(¶ms); + if name.is_some() { + self.brush_objects = true; + self.brush_order = brush::parse_brush_manager(¶ms); + } return; } let Some(tool) = brush::tool(&kind) else { return }; self.brush_objects = true; + let Some(name) = name else { + self.brushes_unread += 1; + return; + }; if self.brush_drafts.len() >= brush::MAX_BRUSHES { self.brushes_unread += 1; return; diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 9c5878fe05..5d47ce16fa 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -256,18 +256,13 @@ impl<'a> Reader<'a> { "Xd" if group_ended => { let gs = self.gs.clone(); if let Some(n) = self.last_object().filter(|n| matches!(n.kind, NodeKind::Group { .. })) { - (n.opacity, n.blend, n.isolate, n.knockout) = (gs.opacity, gs.blend, gs.isolate, gs.knockout); + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = + (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); } } "Xw" => self.gs.hidden = Self::nums(&vals).last() == Some(&1.0), "A" => self.gs.locked = Self::nums(&vals).last() == Some(&1.0), - "XW" => { - // An object's own state block ends `6 () XW`: an `Xy` after a mesh's end was the mesh's. - if Self::nums(&vals).last() == Some(&6.0) && self.mesh_undo.take().is_some() { - self.layer_state = None; - } - self.style_marker(&vals, hidden) - } + "XW" => self.state_marker(&vals, hidden), // Gradients. "Bd" => self.gradient_def = GradientDef::begin(&vals), "Bs" | "BD" => {} @@ -509,9 +504,37 @@ impl<'a> Reader<'a> { if !matches!(w, "J" | "j" | "w" | "M" | "d" | "XR") { self.layer_state = None; self.mesh_undo = None; + self.container_undo = None; } } + /// `n (style) XW`: the end of a state block, or a style marker ([`Self::style_marker`]). + fn state_marker(&mut self, vals: &[V], hidden: bool) { + let code = Self::nums(vals).last().copied(); + // An object's own state block ends `6 () XW`: an `Xy` after a mesh's end was the mesh's. + if code == Some(6.0) && self.mesh_undo.take().is_some() { + self.layer_state = None; + } + match code { + Some(6.0) => self.container_undo = None, + Some(7.0) => self.layer_state_block(), + _ => {} + } + self.style_marker(vals, hidden) + } + + /// `7 () XW` ends a layer's own state block (after its art, before `LB`): an `Xy` that went to + /// the layer's last group or compound path, right after its end, was the layer's. + fn layer_state_block(&mut self) { + let Some(before) = self.container_undo.take() else { return }; + let gs = &self.gs; + let state = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); + let Some(Frame { kind: Kind::Layer(_), children, .. }) = self.frames.last_mut() else { return }; + let Some(n) = children.last_mut().filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. })) else { return }; + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = before; + self.layer_state = Some(state); + } + /// `mode opacity isolate knockout shape Xy`; after a group's end, the group's too, and right /// after a gradient mesh's `/End X!` or a blend's record (before their `Xd` and `6 () XW`), /// theirs, unless the layer's `LB` follows: then it is the layer's (see `end_layer`). @@ -537,20 +560,18 @@ impl<'a> Reader<'a> { let before = (n.opacity, n.blend, n.isolate, n.knockout); (n.opacity, n.blend, n.isolate, n.knockout) = (gs.opacity, gs.blend, gs.isolate, gs.knockout); self.mesh_undo = Some(before); - self.layer_state = in_layer.then_some((gs.opacity, gs.blend, gs.isolate, gs.knockout)); - } else if self.last_object().is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. })) { - if let Some(n) = self.last_object() { - n.opacity = gs.opacity; - n.blend = gs.blend; - n.isolate = gs.isolate; - n.knockout = gs.knockout; - } + self.layer_state = in_layer.then_some((gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape)); + } else if let Some(n) = self.last_object().filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. })) { + let before = (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape); + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); + // The layer's instead when the layer's `7 () XW` follows (`layer_state_block`). + self.container_undo = in_layer.then_some(before); self.layer_state = None; } else { // After a layer's art and before its `LB`: the layer's own state (#2003). Kept until // an operator that isn't part of the state block (or the `LB` that takes it) says the // art moves on, so a path's state before its paint isn't read as its layer's. - self.layer_state = in_layer.then_some((gs.opacity, gs.blend, gs.isolate, gs.knockout)); + self.layer_state = in_layer.then_some((gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape)); } self.note_state(); } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index eb46288c42..fabf97a5db 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -965,6 +965,30 @@ fn a_layer_keeps_its_own_transparency() { } } +#[test] +fn a_layers_state_after_its_last_group_or_compound_path_is_the_layers() { + // GUARDS: the layer's `Xy` right after its last group or compound path, before the layer's + // `0 0 Xd` and `7 () XW`, went to that group or compound path, and the layer stayed opaque. + let a = rect_path(0.0, 0.0, 10.0, 10.0); + let b = rect_path(2.0, 2.0, 8.0, 8.0); + let layer_block = "1 0.6 1 2 1 Xy\n0 0 Xd\n7 () XW\n"; + for last in [format!("0 Ae\nu\n{RED}{a}f\nU\n"), format!("0 Ae\n*u\n{RED}{a}f\n{b}f\n*U\n")] { + let doc = read_ok(&layer(&format!("{last}{layer_block}"))).doc; + let l = &doc.layers[0]; + assert_eq!( + (l.opacity, l.blend, l.isolate, l.knockout, l.knockout_shape), + (0.6, BlendMode::Multiply, true, Knockout::Neutral, true), + "{last}" + ); + let n = &art(&doc)[0]; + assert_eq!((n.opacity, n.blend, n.isolate, n.knockout_shape), (1.0, BlendMode::Normal, false, false), "{last}"); + // The group's own state block (`6 () XW`) keeps it the group's. + let doc = read_ok(&layer(&format!("{last}1 0.6 1 2 1 Xy\n0 0 Xd\n6 () XW\n"))).doc; + assert_eq!(doc.layers[0].opacity, 1.0, "{last}"); + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].knockout_shape), (0.6, true), "{last}"); + } +} + #[test] fn a_layers_state_keeps_through_the_stroke_style_written_in_it() { // GUARDS: a layer's state block can have the stroke style between its `Xy` and `Xd`; read as @@ -5224,6 +5248,20 @@ fn a_file_whose_brushes_are_all_left_out_has_none() { assert!(vectorcraft_brush::library(&r.doc).is_empty()); } +/// A brush object that ends after its plug-in name is counted as a brush left out, and the file +/// gets no default brushes. +#[test] +fn a_brush_object_without_a_name_is_counted_as_left_out() { + let nameless = format!("%AI5_Begin_NonPrinting\nNp\n%AI8_BeginPluginObject\n({CALLIGRAPHIC})\n%AI8_EndPluginObject\n%AI5_End_NonPrinting--\n"); + let r = read_ok(&format!("{nameless}{}", layer(""))); + assert!(vectorcraft_brush::library(&r.doc).is_empty(), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.ends_with("Brushes panel (1)")), "{:?}", r.warnings); + let r = read_ok(&format!("{}{nameless}{}", plugin_object(CALLIGRAPHIC, "Nib", NIB), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + assert_eq!(lib.iter().map(|b| b.name.as_str()).collect::>(), ["Nib"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.ends_with("Brushes panel (1)")), "{:?}", r.warnings); +} + /// A gradient's `Br` (a stop's ramp) isn't a brush: the gradient keeps its stops. #[test] fn a_gradients_br_is_not_a_brush() { diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index 354196555d..ed1b97616f 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -23,7 +23,9 @@ //! before; on a layer that doesn't show it is left out of that layer, with a warning. The page is //! also the safety net: when the layers' art looks different from it (one draws an object the //! other doesn't, or much of it differs; an EPS whose page is its art's box has nothing printed -//! outside it), the page is used. +//! outside it), the page is used. A `.ai` whose text document makes all of its type, with no +//! object unread and nothing else that the page would decide, opens from its layers without its +//! PDF part being imported, so nothing is compared ([`ai_layers_alone`]). //! //! Where a file doesn't match what this module expects, it is left alone and its page is imported. @@ -52,7 +54,7 @@ use build::{Frame, MADE, prune_unseen}; use compare::{ MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour, }; -pub use layers::{ai_alone, ai_alone_on_page, layered_ai}; +pub use layers::{AiLayers, ai_alone, ai_alone_on_page, ai_layers_alone, layered_ai, layered_ai_from}; pub(super) use layers::{layered, program_alone}; pub use slots::is_loss; #[cfg(test)] diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 31be3af5a8..1498c730a0 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -76,14 +76,98 @@ pub(super) fn build_on_page(data: &[u8], page: (f64, f64), unit: f64) -> Result< }; let in_units = |r: Option, k: f64| k.is_finite() && k > 1.0 && fits(r, k) && !fits(r, 1.0); let scale = [unit, structure.canvas_scale].into_iter().find(|&k| in_units(board, k) || (!fits(board, 1.0) && in_units(art, k))); + let styles = structure.styles_read; let (mut doc, notes) = build_from(structure, data, None, Page::Artboard, false, false, 1.0)?; if let Some(k) = scale { - // The graphic styles here are all the file's, drawn in its units too. - scale_document(&mut doc, k, true); + // The graphic styles read from the file are drawn in its units too. + scale_document(&mut doc, k, styles); + relayout_wrapped(&mut doc); } Ok((doc, notes)) } +/// A document read from the editing copy and its notes, or why it can't be read. +pub(super) type Built = Result<(Document, Vec), String>; + +/// [`build`] of a `.ai` without importing its PDF part, whose pages (each its trim box in points, +/// width and height) are `pages` and are in units of `unit` points: the document read from +/// `structure` (the editing copy `data` read) with nothing compared with the pages, when the file's +/// text document makes the type of every text object (at least one shows, and none is type that a +/// look draws), no object is unread or has another placement or drawn art that the page would +/// choose, and its artboards are the pages, one for one and of their size, in points or in the pages' +/// units ([`page_scale_alone`]). The document is drawn at that scale. Else `Err(structure)`, for +/// [`build_from`] with the page. +pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f64, f64)], unit: f64) -> Result> { + let Some(scale) = page_scale_alone(&structure, pages, unit).filter(|_| nothing_waits_on_page(&structure) && type_all_made(&structure, data)) + else { + return Err(Box::new(structure)); + }; + let styles = structure.styles_read; + let built = build_from(structure, data, None, Page::Artboard, false, false, 1.0).map(|(mut doc, notes)| { + if scale != 1.0 { + // The graphic styles read from the file are drawn in its units too. + scale_document(&mut doc, scale, styles); + relayout_wrapped(&mut doc); + } + (doc, notes) + }); + Ok(built) +} + +/// Is nothing in `structure` waiting on the page: no object unread (the page's art takes its +/// place), no placed file with another placement, no live envelope with the drawn art it replaced +/// (the comparison with the page chooses between them)? +fn nothing_waits_on_page(structure: &Structure) -> bool { + structure.unread.is_empty() + && structure.unread_elsewhere.is_empty() + && structure.placed_elsewhere.is_empty() + && structure.envelopes_drawn.is_empty() +} + +/// Does the text document of `data` (read as `structure`) make the type of every text object, those +/// that don't show included, with at least one that shows, and none of them type that a look draws? +fn type_all_made(structure: &Structure, data: &[u8]) -> bool { + let mut infos = vec![]; + collect_slots(&structure.doc.layers, true, &mut infos); + if !infos.iter().any(|i| i.shown) || infos.iter().any(|i| i.look.is_some()) { + return false; + } + let frames = ai::text_frames(data); + for info in &mut infos { + info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(structure.to_doc * p.clone()))); + } + let Some(texts) = Texts::read(data) else { return false }; + let mut read: std::collections::BTreeMap>> = Default::default(); + let stories: Vec>> = infos + .iter() + .map(|i| { + let n = i.story?; + read.entry(n).or_insert_with(|| texts.story(n as usize).map(Arc::new)).clone() + }) + .collect(); + // A slot without its story is made from nothing; past the text `build_from` reads, nothing is + // made either: it refuses the file. + if stories.iter().any(Option::is_none) || stories.iter().flatten().map(|s| s.len()).sum::() > MAX_TEXT { + return false; + } + let template = structure.template.map(|t| ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0)); + make_slots(&infos, &stories, template, structure.to_doc, &mut vec![]).iter().all(Option::is_some) +} + +/// The scale at which the artboards of `structure` are the pages `pages` (each its width and height +/// in points), one for one and in order, each within half a point: 1 when they are in points, else +/// `unit` (the pages' `UserUnit`) when they are in those units, as [`page_scale`] finds it with the +/// page. `None` when they aren't the pages, and for a file that declares a large canvas scale (a +/// `.ai` saved without its PDF part reads one at that scale, [`super::ai_alone`]). +fn page_scale_alone(structure: &Structure, pages: &[(f64, f64)], unit: f64) -> Option { + let boards = &structure.doc.artboards; + if boards.is_empty() || boards.len() != pages.len() || structure.canvas_scale != 1.0 { + return None; + } + let fits = |k: f64| boards.iter().zip(pages).all(|(b, (w, h))| (b.rect.width() - w / k).abs() <= 0.5 && (b.rect.height() - h / k).abs() <= 0.5); + [1.0, unit].into_iter().find(|&k| k.is_finite() && k >= 1.0 && fits(k)) +} + /// [`build`] from `structure`, the editing copy `data` already read. pub(super) fn build_from( structure: Structure, diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index bb88aa1244..26cca96c0f 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -1,4 +1,4 @@ -use super::build::{PAGE_MOVE, Page, build, build_from, build_on_page}; +use super::build::{PAGE_MOVE, Page, build, build_from, build_on_page, build_without_page}; use super::slots::LAYERS_UNREAD; use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect, Vec2, ai}; @@ -110,11 +110,24 @@ fn layer_tree(nodes: &[Arc]) -> Vec> { /// units comes in `unit` times as large, and so does the artboard layout `place_pages` takes from /// it. pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec, outlined: bool, trust: bool, unit: f64) -> (Document, Vec, bool) { + layered_ai_from(AiLayers::decode(private), visible, warnings, outlined, trust, unit) +} + +/// [`layered_ai`] of the editing copy `layers`, as far as it was already decoded and read. +pub fn layered_ai_from( + layers: AiLayers, + visible: Document, + warnings: Vec, + outlined: bool, + trust: bool, + unit: f64, +) -> (Document, Vec, bool) { let unread = |mut all: Vec, why: &str| { all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part")); all }; - let data = match ai::decode_private(private) { + let AiLayers { data, structure } = layers; + let data = match data { Ok(data) => data, Err(why) => return (visible, unread(warnings, &why), false), }; @@ -137,7 +150,10 @@ pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec, outl use_variables(&data, &mut visible, &mut all); (visible, all, false) }; - match build(&data, Some(&visible), Page::Artboard, outlined, trust, unit) { + let built = structure + .unwrap_or_else(|| ai::read(&data, false).map(Box::new)) + .and_then(|structure| build_from(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit)); + match built { // An image too large for the editing data's reader would be missing from the layers, while // the PDF part has it: the file comes in as its PDF part instead (#1479). Ok((_, notes)) if notes.iter().any(|n| n == ai::IMAGE_TOO_LARGE) => { @@ -153,6 +169,51 @@ pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec, outl } } +/// The `.ai` whose editing copy is `private` (as [`layered_ai`] takes it) from its layers alone, +/// without its PDF part, whose pages (each its trim box in points, width and height) are `pages` +/// and are in units of `unit` points (its first page's `UserUnit`): the document and the notes of +/// reading it, when the file's text document makes all of its type and nothing in its layers needs +/// the PDF part (see `build_without_page`). Nothing is compared with the PDF part. Else, as the +/// error, what was decoded and read of the editing copy, for [`layered_ai_from`] once the PDF part +/// is imported. +pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64) -> Result<(Document, Vec), AiLayers> { + let data = match ai::decode_private(private) { + Ok(data) => data, + Err(why) => return Err(AiLayers { data: Err(why), structure: None }), + }; + if !has_layers(&data) { + return Err(AiLayers { data: Ok(data), structure: None }); + } + let structure = match ai::read(&data, false) { + Ok(structure) => structure, + Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)) }), + }; + match build_without_page(structure, &data, pages, unit) { + // An image too large for the editing data's reader is missing from the layers: the PDF + // part has it (as in `layered_ai`). + Ok(Ok((doc, notes))) if !notes.iter().any(|n| n == ai::IMAGE_TOO_LARGE) => Ok((doc, notes)), + Ok(_) => Err(AiLayers { data: Ok(data), structure: None }), + Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)) }), + } +} + +/// A `.ai`'s editing copy decoded, and its layers read when they were, for [`layered_ai_from`]: +/// what [`ai_layers_alone`] read isn't decoded or read again. +pub struct AiLayers { + /// The editing copy decoded, or why it can't be. + data: Result, String>, + /// Its layers read with [`ai::read`] as [`layered_ai`] reads them, or why they can't be; `None` + /// when they are still to be read. + structure: Option, String>>, +} + +impl AiLayers { + /// The editing copy `private` (as [`layered_ai`] takes it), decoded. + pub fn decode(private: &[u8]) -> Self { + Self { data: ai::decode_private(private), structure: None } + } +} + /// `doc` (a file read as its page or PDF part, in place of its layers) with the variables, data /// sets, active data set and lock of the variable library of its editing data `data`, as [`build`] /// gives a document read from the layers, and the note about what of the library wasn't read diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 8fe04326c3..51d2447523 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -44,7 +44,8 @@ mod tiff; pub use ai_editing::{AiEditingOptions, AiEditingOutput, CREATOR_VERSION, export_ai_editing, private_data as ai_private_data}; pub use import::{ - Imported, POSTSCRIPT_ERRORS, ai_alone, ai_alone_on_page, family_style, import, import_trusting, import_with, is_loss, layered_ai, page, + AiLayers, Imported, POSTSCRIPT_ERRORS, ai_alone, ai_alone_on_page, ai_layers_alone, family_style, import, import_trusting, import_with, is_loss, + layered_ai, layered_ai_from, page, }; pub use legacy_ai::{HiddenObjects, LegacyAiOptions, LegacyAiOutput, export_legacy_ai}; pub use print::{PrintJob, PrintPage, print}; diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 57a5cfc952..65c10ba802 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -29,6 +29,13 @@ //! `data`. Every version loads, and [`save_with`] writes any of them for older apps (under the //! format name `drawcraft`, which every version reads). Readers reject files whose `version` is //! newer than they support. +//! +//! The document has a version of its own (`document.version`, [`vectorcraft_doc::FORMAT_VERSION`]), +//! which readers do not check. A version 2 document's Twist effects turn clockwise for a positive +//! angle. A version 1 document's Twist angles are negated when it opens, unless the file is of +//! [`VERSION`] and its `generator` is VectorCraft 0.21.0 or later, which turned them clockwise +//! already; [`save_with`] writes a version 1 document with them negated back for an older file +//! version ([`vectorcraft_doc::twist`]). #![forbid(unsafe_code)] #[cfg(not(target_arch = "wasm32"))] @@ -244,6 +251,10 @@ fn body(doc: &Document, o: &SaveOptions) -> Result { if version < 3 { d.store_legacy_color_profiles(); } + // Apps that read only older file versions predate 0.21.0 and turn Twist the other way. + if version < VERSION { + d.store_legacy_twist_angles(); + } let v1 = if version == 1 { let mut v = serde_json::to_value(&d).map_err(encode_err)?; legacy::anchors_to_v1(&mut v); @@ -489,7 +500,7 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result vectorcraft_doc::node::with_buffered_value_budget(max_values, || Contents::::read(file.json())) }) }; - let f = vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, read).map_err(|e| match e { + let mut f = vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, read).map_err(|e| match e { ReadError::Json(e) => { let why = if e.to_string().contains("recursion limit") { format!("its objects are nested too deep ({e})") } else { e.to_string() }; FormatError::NotVectorcraft(why) @@ -498,6 +509,12 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result e => FormatError::NotVectorcraft(e.to_string()), })?; let info = FileInfo { version: f.version, legacy: f.format == LEGACY_EXTENSION }; + // A version 1 document saved before VectorCraft 0.21.0, or for an app before it (an older file + // version): its Twist angles turned the other way. The app that wrote it is read from the JSON + // before the data after it is taken; the walk's depth is bounded by the JSON reader's nesting + // limit. + let current_file = f.version >= VERSION; + f.document.migrate_twist_angles(|| current_file && vectorcraft_doc::twist::written_clockwise(generator(file.json()).as_deref())); // The bytes after the JSON, read in one pass: the images' first, then the profiles'. let entries: Vec<[u64; 2]> = f.images.values().chain(f.profiles.values()).filter_map(|i| i.blob).collect(); let tail = file.entries(&entries)?; @@ -520,7 +537,11 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result } doc.images.insert(k, blob); } - // Saved mid-edit by an older version: drop the opacity-mask editing layer. + // Saved mid-edit by an older version: drop the opacity-mask editing layer. Those versions + // removed it only as a top-level layer, so an id naming anything else is ignored. + if doc.mask_edit.is_some_and(|me| !doc.layers.iter().any(|l| l.id == me.layer)) { + doc.mask_edit = None; + } doc.drop_edit_modes(); // Saved before per-fill/stroke overprint: the Overprint Black list becomes overprint flags. doc.migrate_overprint_black(); @@ -559,6 +580,8 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result // labels and the character styles, within the ranges `document.setup` takes (after the depth // limit: the walk recurses). doc.keep_scripts_in_range(); + // The conversions above bring an older document to today's version. + doc.version = doc.version.max(vectorcraft_doc::FORMAT_VERSION); let profiles = f .profiles .into_iter() @@ -574,6 +597,37 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result Ok(NativeFile { doc, depth_notes, info, profiles }) } +/// The file's first `generator` member, the app that wrote it (`None`: it has none, it is not a +/// string, or the file is not an object of members). The other members, and any further +/// `generator`, are skipped without being kept, as reading the file skips them. +fn generator(json: &[u8]) -> Option { + struct Generator(Option); + struct Members; + impl<'de> serde::de::Visitor<'de> for Members { + type Value = Generator; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a file's members") + } + fn visit_map>(self, mut m: A) -> Result { + let mut first: Option = None; + while let Some(key) = m.next_key::>()? { + if key == "generator" && first.is_none() { + first = Some(m.next_value()?); + } else { + m.next_value::()?; + } + } + Ok(Generator(first.and_then(|v| v.as_str().map(str::to_owned)))) + } + } + impl<'de> serde::Deserialize<'de> for Generator { + fn deserialize>(d: D) -> Result { + d.deserialize_map(Members) + } + } + serde_json::from_slice::(json).ok()?.0 +} + /// The bytes of the member of the file's head `pick` picks (only that entry of the data after /// the JSON is kept). fn head_member(bytes: &[u8], pick: impl FnOnce(Head) -> Option) -> Option> { @@ -853,6 +907,66 @@ mod tests { assert!(why.contains("more than 100 values before its type"), "{why}"); } + /// A version 1 document written before VectorCraft 0.21.0 (or by an app the file does not + /// name) has its Twist angles negated when it opens; one written by 0.21.0 or later, and a + /// version 2 document, keep them. Each opens as version 2. A save for an older file version + /// negates them back. + #[test] + fn twist_angles_follow_the_document_version_and_generator() { + use vectorcraft_doc::Effect; + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mut a = Appearance::default_art(); + a.effects.push(Effect { id: "distort.twist".into(), params: serde_json::json!({"angle": 30.0}), visible: true }); + d.insert(Some(l), 0, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), a)).unwrap(); + let angle = |d: &Document| d.node(id).and_then(|n| n.appearance.effects[0].params["angle"].as_f64()); + let current = save(&d, false); + let back = load(¤t).unwrap(); + assert_eq!((back.version, angle(&back)), (2, Some(30.0)), "a version 2 document is read as saved"); + let opened = |generator: Option<&str>| { + let mut v: serde_json::Value = serde_json::from_slice(¤t).unwrap(); + v["document"]["version"] = 1.into(); + match generator { + Some(g) => v["generator"] = g.into(), + None => { + v.as_object_mut().unwrap().remove("generator"); + } + } + let d = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + (d.version, angle(&d)) + }; + for g in [Some("VectorCraft 0.20.0"), Some("VectorCraft 0.9.12"), Some("DrawCraft 0.1.0"), Some("VectorCraft"), None] { + assert_eq!(opened(g), (2, Some(-30.0)), "{g:?}"); + } + for g in ["VectorCraft 0.21.0", "VectorCraft 0.21.3", "VectorCraft 1.0.0"] { + assert_eq!(opened(Some(g)), (2, Some(30.0)), "{g}"); + } + // A file may repeat `generator`: the first one names the app. + let mut v: serde_json::Value = serde_json::from_slice(¤t).unwrap(); + v["document"]["version"] = 1.into(); + v["generator"] = "VectorCraft 0.21.0".into(); + let text = serde_json::to_string(&v).unwrap(); + let first = r#""generator":"VectorCraft 0.21.0""#; + let twice = text.replacen(first, &format!(r#"{first},"generator":"DrawCraft 0.1.0""#), 1); + assert_ne!(twice, text); + assert_eq!(angle(&load(twice.as_bytes()).unwrap()), Some(30.0)); + v["generator"] = "VectorCraft 0.20.0".into(); + let old = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + let again = load(&save(&old, false)).unwrap(); + assert_eq!((again.version, angle(&again)), (2, Some(-30.0)), "saved again, it is version 2"); + // Saved for an older file version (apps before 0.21.0): version 1 with the angle negated + // back, whatever the generator, and it reopens as it was. + for version in MIN_VERSION..VERSION { + let bytes = save_with(&d, &SaveOptions { version, ..SaveOptions::default() }).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(v["document"]["version"], 1, "file version {version}"); + assert!(String::from_utf8_lossy(&bytes).contains(r#""angle":-30.0"#), "file version {version}"); + let back = load(&bytes).unwrap(); + assert_eq!((back.version, angle(&back)), (2, Some(30.0)), "file version {version}"); + } + } + #[test] fn rejects_foreign_and_future() { assert!(load(b"{}").is_err()); diff --git a/crates/format/tests/it/native_v3.rs b/crates/format/tests/it/native_v3.rs index 5475f39fb0..6a96fae79d 100644 --- a/crates/format/tests/it/native_v3.rs +++ b/crates/format/tests/it/native_v3.rs @@ -157,6 +157,24 @@ fn keys_from_newer_versions_round_trip() { check_native_roundtrip(&d).unwrap(); } +/// An opacity-mask editing state in a file drops the editing layer it names only when that is a +/// top-level layer, as files saved mid-edit have it: a sublayer it names loads and stays. +#[test] +fn saved_mask_editing_drops_only_a_top_level_layer() { + let mut d = Document::new(612.0, 792.0); + let host = d.layers[0].id; + let sub = d.add_layer(Some("Sub")); + d.move_node(sub, Some(host), 0).unwrap(); + let top = d.add_layer(Some("Mask")); + for (layer, kept) in [(sub, true), (top, false)] { + let mut v = json_of(&save(&d, false)); + v["document"]["mask_edit"] = json!({"object": host, "layer": layer}); + let back = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + assert_eq!(back.node(layer).is_some(), kept, "layer {layer:?}"); + assert!(back.mask_edit.is_none() && back.node(host).is_some()); + } +} + /// The paragraph composer is saved only when it isn't the default (Every-line) and reads back. #[test] fn text_composer_round_trips() { diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index d836d2e021..b1847d9ce3 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -580,17 +580,43 @@ impl PathData { pub fn is_closed(&self) -> bool { !self.subpaths.is_empty() && self.subpaths.iter().all(|s| s.closed) } - /// Nearest point on any segment: (subpath, segment, t, point, distance). + /// Nearest point on any segment: (subpath, segment, t, point, distance). Of segments at the + /// same distance, the first one wins. + /// + /// `p` is first projected onto a segment that starts or ends at the anchor nearest to it. A + /// segment whose control-point box lies farther from `p` than that distance, or than the nearest + /// point found so far, is then skipped without projecting `p` onto it. A segment is never + /// skipped when `p` or one of its control points is past [`NEAREST_SKIP_LIMIT`] in x or y, or + /// not finite. pub fn nearest(&self, p: Point) -> Option<(usize, usize, f64, Point, f64)> { + // Segment `seg` of `sp`, as `SubPath::segment` builds it, without its remainder operations. + let segment = |sp: &SubPath, seg: usize| { + let (a, b) = (&sp.anchors[seg], &sp.anchors[if seg + 1 == sp.anchors.len() { 0 } else { seg + 1 }]); + CubicBez::new(a.p, a.h_out, b.h_in, b.p) + }; + let mut seed: Option<(f64, CubicBez)> = None; + for sp in self.subpaths.iter().filter(|sp| sp.segment_count() > 0) { + for (k, a) in sp.anchors.iter().enumerate() { + let d = (a.p - p).hypot2(); + if seed.is_none_or(|s| d < s.0) { + seed = Some((d, segment(sp, k.min(sp.segment_count() - 1)))); + } + } + } + let mut bound = seed.map_or(f64::INFINITY, |(_, c)| c.nearest(p, 1e-6).distance_sq.sqrt()); let mut best: Option<(usize, usize, f64, Point, f64)> = None; for (si, sp) in self.subpaths.iter().enumerate() { for seg in 0..sp.segment_count() { - let c = sp.segment(seg); + if box_gap(&segment(sp, seg), p).is_some_and(|g| g > bound) { + continue; + } + let c = segment(sp, seg); let n = c.nearest(p, 1e-6); let q = c.eval(n.t); let d = n.distance_sq.sqrt(); if best.is_none_or(|b| d < b.4) { best = Some((si, seg, n.t, q, d)); + bound = bound.min(d); } } } @@ -614,6 +640,27 @@ impl PathData { } } +/// The largest x or y, in size, of a point and a segment's control points for which +/// [`PathData::nearest`] may skip the segment without projecting the point onto it. +const NEAREST_SKIP_LIMIT: f64 = 1e100; + +/// The distance from `p` to the box of `c`'s control points, which holds every point of the +/// segment, less a rounding margin, so that no point of the segment is nearer to `p`. None when `p` +/// or a control point is past [`NEAREST_SKIP_LIMIT`] in x or y, or not finite. +fn box_gap(c: &CubicBez, p: Point) -> Option { + let xs = [c.p0.x, c.p1.x, c.p2.x, c.p3.x]; + let ys = [c.p0.y, c.p1.y, c.p2.y, c.p3.y]; + if !xs.iter().chain(&ys).chain(&[p.x, p.y]).all(|v| v.abs() <= NEAREST_SKIP_LIMIT) { + return None; + } + let (x0, x1) = (xs.iter().copied().fold(f64::INFINITY, f64::min), xs.iter().copied().fold(f64::NEG_INFINITY, f64::max)); + let (y0, y1) = (ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max)); + let margin = [x0, x1, y0, y1, p.x, p.y].iter().fold(1.0f64, |m, v| m.max(v.abs())) * 1e-9; + let dx = ((x0 - p.x).max(p.x - x1) - margin).max(0.0); + let dy = ((y0 - p.y).max(p.y - y1) - margin).max(0.0); + Some(dx.hypot(dy)) +} + /// The largest x or y, in size, of a segment's control points for which its length is measured. /// Document coordinates are far inside it; past it (or not finite) the integrator's arithmetic /// overflows and it subdivides without end. @@ -751,6 +798,102 @@ mod tests { assert!((d - 3.0).abs() < 1e-6); } + /// [`PathData::nearest`] without skipping any segment: every segment projected, the first of + /// equal distances kept. + fn nearest_exhaustive(pd: &PathData, p: Point) -> Option<(usize, usize, f64, Point, f64)> { + let mut best: Option<(usize, usize, f64, Point, f64)> = None; + for (si, sp) in pd.subpaths.iter().enumerate() { + for seg in 0..sp.segment_count() { + let c = sp.segment(seg); + let n = c.nearest(p, 1e-6); + let d = n.distance_sq.sqrt(); + if best.is_none_or(|b| d < b.4) { + best = Some((si, seg, n.t, c.eval(n.t), d)); + } + } + } + best + } + + #[test] + fn nearest_matches_every_segment_projected() { + // A fixed linear congruential sequence, so each run tests the same paths and points. + let mut state = 0x2545_f491_4f6c_dd1du64; + let mut next = move |n: u64| { + state = state.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (state >> 33) % n + }; + let mut compared = 0; + for _ in 0..400 { + // Anchors and handles on a coarse grid, so that many points are equally near two + // segments and the first of them has to win. + let subpaths = (0..next(4)) + .map(|_| { + let anchors = (0..next(9)) + .map(|_| { + let p = Point::new(next(9) as f64 * 5.0, next(9) as f64 * 5.0); + if next(3) == 0 { + let h = |v: u64| (v as f64 - 3.0) * 5.0; + Anchor::with_handles(p, p + kurbo::Vec2::new(h(next(7)), h(next(7))), p + kurbo::Vec2::new(h(next(7)), h(next(7)))) + } else { + Anchor::corner(p) + } + }) + .collect(); + SubPath::new(anchors, next(2) == 0) + }) + .collect(); + let pd = PathData { subpaths }; + for _ in 0..30 { + let p = Point::new(next(101) as f64 * 0.5 - 5.0, next(101) as f64 * 0.5 - 5.0); + assert_eq!(pd.nearest(p), nearest_exhaustive(&pd, p), "{pd:?} at {p:?}"); + compared += 1; + } + } + assert_eq!(compared, 12_000); + } + + #[test] + fn nearest_on_open_closed_compound_one_anchor_and_empty_paths() { + let pts = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + let open = PathData::single(SubPath::polyline(&pts, false)); + let closed = square(); + let mut compound = square(); + compound.subpaths.push(SubPath::polyline(&[Point::new(20.0, 0.0), Point::new(30.0, 0.0)], false)); + let one = PathData::single(SubPath::new(vec![Anchor::corner(Point::new(5.0, 5.0))], true)); + let empty = PathData::default(); + let probes = [Point::new(5.0, 5.0), Point::new(-2.0, 5.0), Point::new(25.0, 1.0), Point::new(10.0, 10.0), Point::new(1e6, -1e6)]; + for pd in [&open, &closed, &compound, &one, &empty] { + for p in probes { + assert_eq!(pd.nearest(p), nearest_exhaustive(pd, p), "{pd:?} at {p:?}"); + } + } + // The center of the square is 5 from every side, and the first side wins. + assert_eq!(closed.nearest(Point::new(5.0, 5.0)).map(|n| (n.0, n.1, n.4)), Some((0, 0, 5.0))); + // The closing side of the closed square is nearer than the open path's segments. + assert_eq!(closed.nearest(Point::new(-2.0, 5.0)).map(|n| (n.1, n.4)), Some((3, 2.0))); + assert_eq!(open.nearest(Point::new(-2.0, 5.0)).map(|n| n.1), Some(0)); + assert_eq!(compound.nearest(Point::new(25.0, 1.0)).map(|n| (n.0, n.1, n.4)), Some((1, 0, 1.0))); + assert_eq!(one.nearest(Point::new(5.0, 5.0)), None); + assert_eq!(empty.nearest(Point::new(5.0, 5.0)), None); + } + + #[test] + fn nearest_with_huge_or_non_finite_coordinates_matches_every_segment_projected() { + let far = [1e200, -1e300, f64::INFINITY, f64::NAN]; + for v in far { + // A far segment first, then the segments with the huge coordinate, then nearer ones. + let mut pd = PathData::single(SubPath::polyline(&[Point::new(100.0, 100.0), Point::new(110.0, 100.0)], false)); + pd.subpaths.push(SubPath::polyline(&[Point::new(20.0, 0.0), Point::new(v, 5.0), Point::new(30.0, 0.0)], false)); + pd.subpaths.extend(square().subpaths); + pd.subpaths.push(SubPath::polyline(&[Point::new(40.0, 0.0), Point::new(50.0, 0.0)], false)); + for p in [Point::new(5.0, -1.0), Point::new(45.0, 1.0), Point::new(25.0, 0.0), Point::new(v, 0.0), Point::new(1e150, 1e150)] { + // Debug output, so that a NaN distance compares equal to itself. + assert_eq!(format!("{:?}", pd.nearest(p)), format!("{:?}", nearest_exhaustive(&pd, p)), "{v} at {p:?}"); + } + } + } + #[test] fn reverse_flips_area_sign() { let mut p = square(); diff --git a/crates/pathops/proptest-regressions/planar/tests.txt b/crates/pathops/proptest-regressions/planar/tests.txt new file mode 100644 index 0000000000..2587908e1f --- /dev/null +++ b/crates/pathops/proptest-regressions/planar/tests.txt @@ -0,0 +1,7 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 799771bbae95181944a44d3a40559928606eb57d3d6a3cf4916ed37bc9bf2c15 # shrinks to shapes = [Shape { path: PathData { subpaths: [SubPath { anchors: [Anchor { p: (20.0, 85.0), h_in: (20.0, 87.76142374915396), h_out: (20.0, 82.23857625084604), kind: Smooth }, Anchor { p: (25.0, 80.0), h_in: (22.23857625084603, 80.0), h_out: (27.76142374915397, 80.0), kind: Smooth }, Anchor { p: (30.0, 85.0), h_in: (30.0, 82.23857625084604), h_out: (30.0, 87.76142374915396), kind: Smooth }, Anchor { p: (25.0, 90.0), h_in: (27.76142374915397, 90.0), h_out: (22.23857625084603, 90.0), kind: Smooth }], closed: true }] }, rule: EvenOdd, key: 0 }, Shape { path: PathData { subpaths: [SubPath { anchors: [Anchor { p: (10.0, 80.0), h_in: (10.0, 91.04569499661588), h_out: (10.0, 68.95430500338412), kind: Smooth }, Anchor { p: (30.0, 60.0), h_in: (18.95430500338413, 60.0), h_out: (41.04569499661587, 60.0), kind: Smooth }, Anchor { p: (50.0, 80.0), h_in: (50.0, 68.95430500338412), h_out: (50.0, 91.04569499661588), kind: Smooth }, Anchor { p: (30.0, 100.0), h_in: (41.04569499661587, 100.0), h_out: (18.95430500338413, 100.0), kind: Smooth }], closed: true }] }, rule: EvenOdd, key: 0 }, Shape { path: PathData { subpaths: [SubPath { anchors: [Anchor { p: (30.0, 85.0), h_in: (30.0, 87.76142374915396), h_out: (30.0, 82.23857625084604), kind: Smooth }, Anchor { p: (35.0, 80.0), h_in: (32.23857625084603, 80.0), h_out: (37.76142374915397, 80.0), kind: Smooth }, Anchor { p: (40.0, 85.0), h_in: (40.0, 82.23857625084604), h_out: (40.0, 87.76142374915396), kind: Smooth }, Anchor { p: (35.0, 90.0), h_in: (37.76142374915397, 90.0), h_out: (32.23857625084603, 90.0), kind: Smooth }], closed: true }] }, rule: EvenOdd, key: 0 }] diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index 13476fbbc0..5e6f55135a 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -330,7 +330,18 @@ impl CoverIds { /// enclosing contour of its mask, as in that mask's own pass; an outer contour always starts a face /// of its own, even inside a hole of its mask (an island left in a cutout is a separate face, not /// part of the frame around it). -fn face_groups(c: &linesweeper::topology::Contours, owner: &[usize]) -> Vec<(usize, Vec)> { +/// +/// The sweep's tree of contours is wrong where it cut a loop off a contour at a point the contour +/// visits twice and the loop isn't nested in it: two holes touching at a point (the second comes +/// out an island inside the first), or an outer contour touching its own hole (it comes out an +/// island inside the hole). Such a loop winds the same way as the contour it was cut from, against +/// its flag ([`Contour::outer`](linesweeper::topology::Contour::outer)), and the pass is then +/// grouped by where the contours lie instead ([`face_groups_by_winding`]). +fn face_groups(c: &Contours, owner: &[usize]) -> Vec<(usize, Vec)> { + let areas: Vec = c.contours().map(|ct| ct.path.area()).collect(); + if c.contours().zip(&areas).any(|(ct, &a)| ct.outer != (a > 0.0)) { + return face_groups_by_winding(c, owner, &areas); + } let mut children = vec![Vec::new(); owner.len()]; let mut roots = Vec::new(); for (i, &m) in owner.iter().enumerate() { @@ -358,6 +369,47 @@ fn face_groups(c: &linesweeper::topology::Contours, owner: &[usize]) -> Vec<(usi .collect() } +/// [`face_groups`] without the sweep's tree: each hole (a contour whose area in `areas` isn't +/// positive) goes with the smallest outer contour of its mask around it, and each outer contour, +/// or hole with none around it, starts a face. Faces come in the order of their first contour, +/// each with its contours in pass order. +fn face_groups_by_winding(c: &Contours, owner: &[usize], areas: &[f64]) -> Vec<(usize, Vec)> { + let boxes: Vec = c.contours().map(|ct| ct.path.bounding_box()).collect(); + let outer = |i: usize| areas.get(i).is_some_and(|&a| a > 0.0); + let mut root: Vec = (0..owner.len()).collect(); + for (i, ct) in c.contours().enumerate() { + // Contours of one mask share no edge, so the middle of a hole's first piece is strictly + // inside or outside each outer contour of its mask. + let (false, Some(p), Some(b)) = (outer(i), ct.path.segments().next().map(|s| s.eval(0.5)), boxes.get(i)) else { + continue; + }; + let around = c + .contours() + .enumerate() + .filter(|&(j, o)| { + outer(j) && owner.get(j) == owner.get(i) && boxes.get(j).is_some_and(|bj| bj.union(*b) == *bj) && o.path.winding(p) != 0 + }) + .min_by(|(j, _), (k, _)| areas.get(*j).unwrap_or(&f64::INFINITY).total_cmp(areas.get(*k).unwrap_or(&f64::INFINITY))) + .map(|(j, _)| j); + if let (Some(j), Some(r)) = (around, root.get_mut(i)) { + *r = j; + } + } + let mut slot: Vec> = vec![None; owner.len()]; + let mut groups: Vec<(usize, Vec)> = Vec::new(); + for (i, &r) in root.iter().enumerate() { + let (Some(s), Some(&m)) = (slot.get_mut(r), owner.get(r)) else { continue }; + let k = *s.get_or_insert_with(|| { + groups.push((m, Vec::new())); + groups.len() - 1 + }); + if let Some((_, g)) = groups.get_mut(k) { + g.push(ContourIdx(i)); + } + } + groups +} + /// A point as a map key (the arrangement's vertices are exact). fn vertex_key(p: Point) -> (u64, u64) { (p.x.to_bits(), p.y.to_bits()) @@ -1020,6 +1072,31 @@ mod tests { .prop_map(|(p, even_odd, key)| Shape::new(p, if even_odd { FillRule::EvenOdd } else { FillRule::NonZero }, key)) } + /// Contours that touch at a point, which the sweep's tree of contours gets wrong + /// ([`face_groups`]): each face keeps its holes, and no hole is a face of its own. + #[test] + fn contours_touching_at_a_point_keep_their_faces() { + let sorted = |shapes: &[Shape]| { + let mut v: Vec<(Vec, f64)> = + regions(shapes).iter().map(|r| (r.sources.clone(), crate::area(&r.path, FillRule::NonZero))).collect(); + v.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); + v + }; + // A frame whose cutout corner (60,110) touches its hole: the sweep makes the frame an + // island inside the hole. + let mut frame = rect(50.0, 100.0, 80.0, 130.0); + frame.subpaths.extend(rect(60.0, 110.0, 65.0, 115.0).subpaths); + let s = [Shape::new(rect(20.0, 70.0, 60.0, 110.0), FillRule::NonZero, 0), Shape::new(frame, FillRule::EvenOdd, 0)]; + assert_eq!(sorted(&s), [(vec![0], 1500.0), (vec![0, 1], 100.0), (vec![1], 775.0)]); + // Two holes touching at (30,50): the sweep makes the second an island inside the first. + let s = [ + Shape::new(rect(0.0, 0.0, 100.0, 100.0), FillRule::NonZero, 0), + Shape::new(rect(20.0, 40.0, 30.0, 50.0), FillRule::NonZero, 0), + Shape::new(rect(30.0, 50.0, 40.0, 60.0), FillRule::NonZero, 0), + ]; + assert_eq!(sorted(&s), [(vec![0], 9800.0), (vec![0, 1], 100.0), (vec![0, 2], 100.0)]); + } + #[test] fn crossing_strips_match_one_mask_at_a_time() { let mut v = Vec::new(); diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index d1d05d4dff..654d7d5cb7 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -1075,3 +1075,22 @@ fn many_lines_stay_quick() { assert!(faces.len() > 500, "{}", faces.len()); assert!(started.elapsed().as_secs_f64() < 5.0, "{:?}", started.elapsed()); } + +#[test] +fn holes_touching_at_a_point_stay_holes() { + // Two small circles inside a big one, touching each other at (30,85): the big circle's face + // has both as holes, and every face and region is one of the three. + let circle = |cx: f64, cy: f64, r: f64| Shape::new(shapes::ellipse(Rect::new(cx - r, cy - r, cx + r, cy + r)), FillRule::EvenOdd, 0); + let closed = [circle(25.0, 85.0, 5.0), circle(30.0, 80.0, 20.0), circle(35.0, 85.0, 5.0)]; + let (big, small) = (400.0 * std::f64::consts::PI, 25.0 * std::f64::consts::PI); + let (faces, _) = live_paint(&closed); + let regions = crate::regions(&closed); + for found in [&faces, ®ions] { + let mut sizes: Vec<(Vec, f64)> = found.iter().map(|r| (r.sources.clone(), area(r))).collect(); + sizes.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(sizes.iter().map(|s| s.0.clone()).collect::>(), [vec![0, 1], vec![1], vec![1, 2]], "{sizes:?}"); + for ((_, a), want) in sizes.iter().zip([small, big - 2.0 * small, small]) { + assert!((a - want).abs() < 0.5, "{a} vs {want}: {sizes:?}"); + } + } +} diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 6bd298a078..66ff8b6e39 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -9,7 +9,7 @@ description = "VectorCraft PDF export and import" workspace = true [features] -# `vectorcraft_pdf::reads_of` for other crates' tests (dev-dependencies only). +# `vectorcraft_pdf::reads_of` and `imports_of` for other crates' tests (dev-dependencies only). read-count = [] [dependencies] diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index e8dfd4a07d..379ebbd506 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -431,7 +431,7 @@ impl Exporter<'_> { /// in process colors, so the spot inks have no plate of their own. fn warn_spot_image(&mut self, g: &vectorcraft_color::GradientPaint) { let doc = self.doc; - let from_stops = g.gradient.kind != GradientKind::Freeform || g.freeform.is_none(); + let from_stops = g.gradient.kind != GradientKind::Freeform || !g.has_freeform_points(); if from_stops && g.gradient.stops.iter().any(|s| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot))) { self.warn( "spot colors in gradients exported as images (freeform or dithered gradients, and Perceptual ones with RGB or Lab stops or too many stops) are written in process colors", diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index ff04da781d..6423578af1 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -38,6 +38,8 @@ mod state; #[cfg(test)] pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical}; +#[cfg(any(test, feature = "read-count"))] +pub use entry::imports_of; pub use entry::{ INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 3f521c0265..687fcb1566 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -221,6 +221,16 @@ fn read_with_reader_options(bytes: &[u8], opts: &ImportOptions, reader: &craft_p read_opened(bytes, opts, reader, &original) } +/// How many times each buffer's pages have been imported, by its address (tests). +#[cfg(any(test, feature = "read-count"))] +static IMPORTS: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// How many times the pages of `bytes`, at its address, have been imported on any thread (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn imports_of(bytes: &[u8]) -> usize { + IMPORTS.lock().ok().and_then(|i| i.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0) +} + /// [`read_with_reader_options`] of `original`, the PDF `bytes` read with `reader`. fn read_opened( bytes: &[u8], @@ -228,6 +238,11 @@ fn read_opened( reader: &craft_pdf::OpenOptions, original: &craft_pdf::syntax::Pdf, ) -> Result { + #[cfg(any(test, feature = "read-count"))] + if let Ok(mut imports) = IMPORTS.lock() { + let n = imports.entry(bytes.as_ptr() as usize).or_default(); + *n = n.saturating_add(1); + } let picked = crate::pages::picked(opts, original.pages().len())?; let mut ocgs = Ocgs::read(original); let route = opts.layers && !ocgs.list.is_empty(); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index d39fc0b95d..ca7e44ae7a 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -76,6 +76,8 @@ pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_w pub use encrypt::Encryption; pub use export::{export, export_with_report, page_areas}; pub use file_info::{FileInfo, file_info}; +#[cfg(any(test, feature = "read-count"))] +pub use import::imports_of; pub use import::{ INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, @@ -83,8 +85,8 @@ pub use import::{ #[cfg(any(test, feature = "read-count"))] pub use pages::reads_of; pub use pages::{ - IllustratorData, Opened, PageInfo, PdfInfo, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info, is_postscript, - open_pdf, + IllustratorData, Opened, PageInfo, PdfInfo, TrimPages, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info, + is_postscript, open_pdf, }; pub use piece_info::{PRIVATE_CHUNK, PrivateData}; pub use post::{THUMBNAIL_SIZE, Thumbnail}; diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index b5cee4b1bc..013d09f22d 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -280,6 +280,36 @@ impl Opened { pub fn page_count(&self) -> usize { self.pdf.pages().len() } + + /// The pages' trim boxes and bleed, as an import of every page on its trim box takes them, + /// without importing any page's art. + pub fn trim_pages(&self) -> TrimPages { + let pages = self.pdf.pages(); + let mut bleed = [0.0; 4]; + for page in pages.iter() { + for (side, b) in bleed.iter_mut().zip(self::bleed(page)) { + *side = f64::max(*side, b); + } + } + TrimPages { + sizes: pages.iter().map(|page| frame(page, CropTo::Trim).1).map(|r| (r.width(), r.height())).collect(), + user_unit: pages.first().map_or(1.0, |page| f64::from(page.user_unit())), + bleed, + } + } +} + +/// A PDF's pages as an import on their trim boxes sizes them ([`Opened::trim_pages`]). +#[derive(Clone, Debug, PartialEq)] +pub struct TrimPages { + /// Each page's trim box (its crop box when it has none) in points, rotated as the page shows: + /// width and height. + pub sizes: Vec<(f64, f64)>, + /// The size in points of a unit of the first page's user space (its `UserUnit`). + pub user_unit: f64, + /// The bleed of the pages, `[top, bottom, left, right]` in points: on each side, the widest + /// of the pages' bleed, as the import makes it the document's bleed. + pub bleed: [f64; 4], } /// Preserve the application's existing accepted file sizes. Ordinary stream decoding still diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 6d47c55113..18ffeb335b 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -113,6 +113,33 @@ pub enum ParamSpec { #[serde(default = "list_max")] max_items: usize, }, + /// A color (a color button that opens a color picker). Its default, and a value passed to + /// `plugin.run`, is a color object as paints hold one (`{"model": "rgb", "r", "g", "b"}`, or + /// `cmyk`, `gray`, `lab`) or a hex string (`"#3a7bd5"`); the plug-in always gets a color object. + Color { + /// As the manifest gives it (`null`: black), read with [`color_value`] when used, so a hex + /// default follows the working RGB space in use then, not the one at install. + #[serde(default)] + default: Value, + }, +} + +/// A color parameter's value: a color object, or a hex string (display sRGB, converted into the +/// active working RGB space as the color picker's choices are), its components clamped into range. +pub fn color_value(v: &Value) -> Option { + use vectorcraft_color::{Color, cms}; + let c = match v { + Value::String(s) => match Color::from_hex(s)? { + Color::Rgb { r, g, b } => { + let [r, g, b] = cms::active().srgb_to_rgb([r, g, b]); + Color::rgb(r, g, b) + } + other => other, + }, + Value::Object(_) => serde_json::from_value(v.clone()).ok()?, + _ => return None, + }; + Some(crate::objects::clamp_color(c)) } fn int_min() -> i64 { @@ -154,6 +181,7 @@ impl ParamSpec { ParamSpec::Choice { options, default } => json!(default.clone().or_else(|| options.first().cloned()).unwrap_or_default()), ParamSpec::Text { default, max_length } => json!(default.chars().take(*max_length).collect::()), ParamSpec::NumberList { min, max, default, .. } => json!(default.iter().map(|x| x.clamp(*min, *max)).collect::>()), + ParamSpec::Color { default } => serde_json::to_value(color_value(default).unwrap_or_default()).unwrap_or_default(), } } @@ -173,6 +201,9 @@ impl ParamSpec { } Ok(()) } + ParamSpec::Color { default } if !default.is_null() && color_value(default).is_none() => { + bad("a color default must be a color object or a hex string such as \"#3a7bd5\"") + } ParamSpec::Text { default, max_length } if !(1..=MAX_TEXT).contains(max_length) || default.chars().count() > *max_length => { bad(&format!("`maxLength` must be 1-{MAX_TEXT}, and the default no longer")) } @@ -321,6 +352,7 @@ impl Manifest { ParamSpec::NumberList { min, max, min_items, max_items, .. } => { format!("{k}: {min_items} to {max_items} numbers {min}..{max} ({})", p.spec.default_value()) } + ParamSpec::Color { default } => format!("{k}: color object or hex ({})", color_value(default).unwrap_or_default().to_hex()), }) .collect(); format!("{{{}}}", parts.join(", ")) @@ -382,6 +414,10 @@ impl Manifest { let numbers: Option> = items.iter().map(|x| x.as_f64().filter(|f| f.is_finite()).map(|f| f.clamp(*min, *max))).collect(); json!(numbers.ok_or_else(|| wrong("a list of numbers"))?) } + ParamSpec::Color { .. } => { + let c = color_value(v).ok_or_else(|| wrong("a color object or a hex string such as \"#3a7bd5\""))?; + serde_json::to_value(c).map_err(|e| Error::Params(format!("`{k}`: {e}")))? + } }; out.insert(k.clone(), resolved); } @@ -580,6 +616,67 @@ mod tests { ); } + /// A color's default and value may be a color object or a hex string; the plug-in always gets + /// a color object, its components clamped. Without a default it is black. + #[test] + fn colors_resolve_to_color_objects() { + let m = Manifest::parse( + br##"{"id":"org.example.grid","name":"Grid","kind":"filter","params":{ + "line":{"type":"color","default":"#ff0000"}, + "ink":{"type":"color","default":{"model":"cmyk","c":1,"m":0,"y":0,"k":2}}, + "plain":{"type":"color"}}}"##, + ) + .unwrap(); + assert_eq!( + Value::Object(m.defaults()), + json!({"line": {"model": "rgb", "r": 1.0, "g": 0.0, "b": 0.0}, + "ink": {"model": "cmyk", "c": 1.0, "m": 0.0, "y": 0.0, "k": 1.0}, + "plain": {"model": "rgb", "r": 0.0, "g": 0.0, "b": 0.0}}) + ); + let p = m.resolve_params(&json!({"line": "#0000ff", "ink": {"model": "gray", "k": 0.5}})).unwrap(); + assert_eq!(p["line"], json!({"model": "rgb", "r": 0.0, "g": 0.0, "b": 1.0})); + assert_eq!(p["ink"], json!({"model": "gray", "k": 0.5})); + for bad in [json!({"line": "not a color"}), json!({"line": 3}), json!({"line": {"model": "hsv", "h": 1}})] { + assert!(m.resolve_params(&bad).is_err(), "{bad}"); + } + assert!(m.params_doc().starts_with("{line: color object or hex (#ff0000)")); + assert!(Manifest::parse(br#"{"id":"a","name":"x","kind":"filter","params":{"c":{"type":"color","default":"nope"}}}"#).is_err()); + } + + /// A hex color is display sRGB: in a wide-gamut working RGB space it becomes the working RGB + /// color that shows as that hex, read when used, while the manifest keeps the default as written. + #[test] + fn hex_colors_follow_the_working_rgb_space() { + const CHILD: &str = "VECTORCRAFT_TEST_PLUGIN_COLOR_PROFILE"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: exercise this profile in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "manifest::tests::hex_colors_follow_the_working_rgb_space", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated color profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::{Color, cms}; + let m = + Manifest::parse(br##"{"id":"org.example.grid","name":"Grid","kind":"filter","params":{"line":{"type":"color","default":"#3a7bd5"}}}"##) + .unwrap(); + cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + for c in [m.defaults()["line"].clone(), m.resolve_params(&json!({"line": "#3a7bd5"})).unwrap()["line"].clone()] { + let c: Color = serde_json::from_value(c).unwrap(); + assert_ne!(c, Color::rgb8(0x3a, 0x7b, 0xd5), "converted into the working space"); + assert_eq!(c.to_hex(), "#3a7bd5", "shows as the hex given"); + } + assert_eq!(serde_json::to_value(&m).unwrap()["params"]["line"]["default"], json!("#3a7bd5"), "kept as written"); + cms::set_active(&cms::ColorSettings::default()).unwrap(); + } + #[test] fn up_to_256_parameters_with_at_most_64_outside_groups() { let manifest = |n: usize, grouped: usize| { diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index db743af15c..037591f8bc 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -52,6 +52,10 @@ pub struct OutObject { /// The object's effects, in order, replacing its own (not its fills' or strokes'). The host /// admits them before they reach the document ([`AdmitEffects`]). pub effects: Option>, + /// Makes the object a guide (`true`, as View › Guides › Make Guides does) or a plain path. + pub guide: Option, + /// Locks or unlocks the object (as Object › Lock and Unlock do). + pub locked: Option, } /// One stroke of an [`OutObject`]. `None` fields keep the stroke's value (a new stroke's @@ -195,7 +199,7 @@ fn unit(v: f32) -> f32 { } /// `c` with its components in range. -fn clamp_color(c: Color) -> Color { +pub(crate) fn clamp_color(c: Color) -> Color { match c { Color::Rgb { r, g, b } => Color::Rgb { r: unit(r), g: unit(g), b: unit(b) }, Color::Cmyk { c, m, y, k } => Color::Cmyk { c: unit(c), m: unit(m), y: unit(y), k: unit(k) }, @@ -320,6 +324,11 @@ fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result if let Some(op) = opt(o, "opacity") { out.opacity = Some(unit(op.as_f64().ok_or_else(|| out_err(at, "`opacity` must be a number"))? as f32)); } + let flag = |key: &str| -> Result> { + opt(o, key).map(|v| v.as_bool().ok_or_else(|| out_err(at, format!("`{key}` must be true or false")))).transpose() + }; + out.guide = flag("guide")?; + out.locked = flag("locked")?; Ok(out) } @@ -573,12 +582,48 @@ fn write(doc: &mut Document, n: &mut Node, o: OutObject, at: &str, admit: AdmitE if let Some(effects) = o.effects { n.appearance.effects = admit(&effects, n).map_err(|why| out_err(&format!("{at}.effects"), why))?; } + if let Some(on) = o.guide { + set_guide(n, on); + } + if let Some(locked) = o.locked { + n.locked = locked; + } Ok(()) } +/// Makes path or compound path `n` a guide or a plain path, as Make Guides and Release Guides do: a +/// compound path's members carry the flag. +fn set_guide(n: &mut Node, on: bool) { + match &mut n.kind { + NodeKind::Path { guide, clipping: false, .. } => *guide = on, + NodeKind::Compound { children, .. } => { + for c in children.iter_mut() { + set_guide(Arc::make_mut(c), on); + } + } + _ => {} + } +} + +/// Whether `n` is a guide: a guide path, or a compound path of guide paths. +fn is_guide(n: &Node) -> bool { + match &n.kind { + NodeKind::Path { guide, .. } => *guide, + NodeKind::Compound { children, .. } => !children.is_empty() && children.iter().all(|c| is_guide(c)), + _ => false, + } +} + +/// Whether a filter's result `n` is selected after the run: locked objects and guides aren't, as +/// Object › Lock and Make Guides leave them deselected. +pub fn selectable(n: &Node) -> bool { + !n.locked && !is_guide(n) +} + /// The paths and compound paths a filter reads from the selection `selected`, in paint order: -/// selected ones, and those inside selected groups and layers; hidden, locked, guide and clipping -/// paths are left out (so are paths inside compound paths, blends and other live objects). +/// selected ones, and those inside selected groups and layers; hidden, locked, guide (compound +/// guides too) and clipping paths are left out (so are paths inside compound paths, blends and +/// other live objects). pub fn filter_targets(doc: &Document, selected: &[NodeId]) -> Vec { fn visit(list: &[Arc], sel: &HashSet, inside: bool, out: &mut Vec) { for n in list { @@ -587,7 +632,7 @@ pub fn filter_targets(doc: &Document, selected: &[NodeId]) -> Vec { } let picked = inside || sel.contains(&n.id); match &n.kind { - NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. } if picked => out.push(n.id), + NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. } if picked && !is_guide(n) => out.push(n.id), NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => visit(children, sel, picked, out), _ => {} } diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index c937120f87..74219a31bb 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -151,6 +151,46 @@ fn geometry_type_and_strokes_change() { assert!(n.appearance.stroke().is_none()); } +/// A compound path made a guide is left out of a later filter's inputs, as guide paths are; a +/// plain compound path is still one of them. +#[test] +fn compound_guides_are_not_filter_targets() { + let (mut d, _, layer) = doc(); + let two = PathData::new(square(0.0).subpaths.into_iter().chain(square(2.0).subpaths).collect()); + let out = json!({"objects": [{"type": "compound", "path": two.clone(), "guide": true}, {"type": "compound", "path": two}]}); + let made = apply_output(&mut d, &[], decode_json(out).unwrap(), Some(layer), &keep).unwrap(); + let targets = filter_targets(&d, &[layer]); + assert!(!targets.contains(&made[0]), "the compound guide"); + assert!(targets.contains(&made[1]), "the plain compound path"); +} + +/// `guide` and `locked` make objects guides (a compound path's members too) and lock them, or undo +/// both; locked objects and guides are not [`selectable`]. Other values are refused. +#[test] +fn objects_become_guides_and_lock() { + let (mut d, ids, layer) = doc(); + let two = PathData::new(square(0.0).subpaths.into_iter().chain(square(2.0).subpaths).collect()); + let out = json!({"objects": [ + {"id": ids[0].0, "guide": true}, + {"id": ids[1].0, "locked": true}, + {"name": "G", "type": "compound", "path": two, "guide": true, "locked": true}]}); + let made = apply_output(&mut d, &ids[..2], decode_json(out).unwrap(), Some(layer), &keep).unwrap(); + let a = d.node(ids[0]).unwrap(); + assert!(matches!(a.kind, NodeKind::Path { guide: true, .. }) && !a.locked && !selectable(a)); + let b = d.node(ids[1]).unwrap(); + assert!(b.locked && matches!(b.kind, NodeKind::Path { guide: false, .. }) && !selectable(b)); + let g = d.node(made[2]).unwrap(); + let NodeKind::Compound { children, .. } = &g.kind else { panic!("not a compound: {:?}", g.kind) }; + assert!(g.locked && children.iter().all(|c| matches!(c.kind, NodeKind::Path { guide: true, .. }))); + // And back: a plain, unlocked, selectable path. + let out = json!({"objects": [{"id": ids[0].0, "guide": false, "locked": false}]}); + apply_output(&mut d, &ids[..1], decode_json(out).unwrap(), None, &keep).unwrap(); + assert!(selectable(d.node(ids[0]).unwrap())); + for bad in [json!({"guide": 1}), json!({"locked": "yes"})] { + assert!(decode_json(json!({"objects": [bad]})).is_err(), "{bad}"); + } +} + /// A paint handed back as it was keeps its swatch link and any other is unlinked; a pattern paint /// must name a pattern the document has. #[test] diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index c01f27a3f8..81b7198937 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -1,6 +1,6 @@ use super::options::{AntiAlias, RenderOptions}; use super::threads::single_threaded_context; -use super::{Affine, Arc, BezPath, Document, FillRule, HashMap, Ink, Node, Rect, RenderContext, SymbolBoxes, TextObject, live}; +use super::{Affine, Arc, BezPath, Document, FillRule, HashMap, Ink, Node, Rect, RenderContext, StrokeLayer, SymbolBoxes, TextObject, live}; /// Hasher for pointer-keyed caches: a multiply-xorshift (SipHash showed up in frame profiles). #[derive(Default, Clone, Copy)] @@ -30,11 +30,14 @@ pub(crate) type PtrMap = HashMap, pub(crate) outline: Arc, pub(crate) stamp: u64, + pub(crate) crop: Option, } /// The slices of a stroke whose gradient runs along or across it, each with its paint and bounds. @@ -142,6 +145,16 @@ impl Frame<'_> { (self.opts.anti_alias == AntiAlias::Type).then(|| self.view * t.xf) } + /// Stroke `st` as this frame draws it: a copy without its dashes when the frame draws dashed + /// lines as solid lines ([`RenderOptions::solid_dashes`]), else `st` itself. + pub(crate) fn stroke<'s>(&self, st: &'s StrokeLayer) -> std::borrow::Cow<'s, StrokeLayer> { + if self.opts.solid_dashes && st.dash.is_some() { + std::borrow::Cow::Owned(StrokeLayer { dash: None, ..st.clone() }) + } else { + std::borrow::Cow::Borrowed(st) + } + } + /// A render context for drawing this frame's art offscreen (on the calling thread), with its /// edge smoothing: hard edges must not depend on where the art is drawn. pub(crate) fn offscreen_context(&self, w: u16, h: u16) -> RenderContext { diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index eb5c698019..a49817cd06 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -54,7 +54,7 @@ impl Renderer { let split_frame; let (f, screen) = match content.kept.and_then(|k| k.frame.map(|frame| (k.window, frame))) { Some((window, (view, px))) => { - split_frame = Frame { view, px, ..*f }; + split_frame = Frame { view, visible: window, px, ..*f }; (&split_frame, view.transform_rect_bbox(window)) } None => (f, Rect::new(0.0, 0.0, ctx.width() as f64, ctx.height() as f64)), @@ -382,7 +382,7 @@ impl Renderer { } /// The inputs a raster of `n`'s content, which reads `reads`, is drawn with in frame `f`: the - /// color settings, the edge smoothing, the document's raster effects resolution (which a + /// color settings, the edge smoothing, whether dashed strokes draw as solid lines, the document's raster effects resolution (which a /// Rasterize or De-Interlace anywhere in the content follows), the knockout `n` inherits and, /// while `n` holds the isolated group, isolation mode; the pattern definitions, symbols and /// brush library it reads; for images and placed documents their pixels and files, the @@ -398,6 +398,8 @@ impl Renderer { (doc.cms, f.opts.anti_alias.threshold(), self.knockout, f.doc.raster_effects_ppi.to_bits()).hash(&mut h); // Cached effects on containers can include paths made into guides. f.opts.hide_guides.hash(&mut h); + // Cached effects can include dashed strokes drawn as solid lines. + f.opts.solid_dashes.hash(&mut h); if let Some((isolated, path)) = self.isolation_path(f) && n.id != isolated && path.contains(&n.id) @@ -580,7 +582,10 @@ impl Renderer { None => (x0, y0, w, h, k), }; let mut off = f.offscreen_context(w, h); - let shifted = Frame { mt: false, view: Affine::scale(k) * Affine::translate((-x0, -y0)) * f.view, px: f.px / k, ..*f }; + let view = Affine::scale(k) * Affine::translate((-x0, -y0)) * f.view; + // Art is culled against, and long strokes outlined around, the offscreen's own area. + let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(w), f64::from(h))); + let shifted = Frame { mt: false, view, visible, px: f.px / k, ..*f }; self.inside_layer(|r| draw(r, &mut off, &shifted, None)); off.flush(); let mut pm = vello_cpu::Pixmap::new(w, h); @@ -637,6 +642,7 @@ impl Renderer { let outline = match item { AppearanceItem::Fill(_) => ig.clone(), AppearanceItem::Stroke(st) => { + let st = &*f.stroke(st); let w = effects::stroke::aligned_width(st, effects::stroke::is_closed(ig)); effects::stroke::line_outline(&effects::stroke::stroke_pieces(ig, st).line, st, w, f.px * 0.25) } diff --git a/crates/render/src/options.rs b/crates/render/src/options.rs index 595f9797b3..93d0f07b9a 100644 --- a/crates/render/src/options.rs +++ b/crates/render/src/options.rs @@ -134,6 +134,9 @@ pub struct RenderOptions { /// Appearance of Black's Rich Black: pure CMYK black (black ink alone at 100%) shows as RGB /// black. Off, it shows through the CMYK profile, a dark grey, as other colours do. pub rich_black: bool, + /// Dashed strokes draw as solid lines, without their dashes (the Navigator's Draw Dashed Lines + /// as Solid Lines). Off, they draw their dashes. + pub solid_dashes: bool, } /// The opacity of the art around an isolated group or layer. @@ -219,6 +222,7 @@ impl Default for RenderOptions { interacting: false, dragging: false, rich_black: false, + solid_dashes: false, } } } diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index b9ce01a7b3..003a08807d 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -254,8 +254,10 @@ const PNG_WINDOW_AND_STEP: u64 = (32 << 10) + (8 << 10); /// The most memory `r` takes in its buffers to read its image a row at a time: the stream buffer /// holds the rows already read up to [`PNG_KEPT_ROWS`] or four rows, whichever is more, the previous -/// and current rows, and [`PNG_WINDOW_AND_STEP`], and may have up to twice that reserved; a copy of -/// a stored row and the row given out come on top. `None` when a row given out doesn't fit memory. +/// and current rows, and [`PNG_WINDOW_AND_STEP`]. The buffer grows by doubling its reservation, +/// and while it grows its old reservation and the new one, up to twice the size it holds, are both +/// allocated: three times that size at most. A copy of a stored row and the row given out come on +/// top. `None` when a row given out doesn't fit memory. fn png_row_scratch(r: &png::Reader>) -> Option { let info = r.info(); // A filter byte and the row's samples, in whole bytes. @@ -263,7 +265,7 @@ fn png_row_scratch(r: &png::Reader>) -> Option { let out = u64::try_from(r.output_line_size(info.width)?).ok()?; let kept = (stored * 4).next_multiple_of(64).max(PNG_KEPT_ROWS); let stream = kept + stored * 2 + PNG_WINDOW_AND_STEP; - Some(stream * 2 + stored + out) + Some(stream * 3 + stored + out) } /// The largest size of at most `w`×`h` pixels, keeping their proportions, whose pixels take at most diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index db5ab2d6bc..1e07075e71 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -23,6 +23,9 @@ mod nodes; mod paint; mod text; +#[cfg(test)] +pub(crate) use paint::{CROP_STROKES, crop_line}; + impl Renderer { pub fn new() -> Self { Self { @@ -318,6 +321,7 @@ impl Renderer { let visible = inv.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); let px = 1.0 / view.determinant().abs().sqrt().max(1e-12); let mut ctx = single_threaded_context(w, h); + ctx.set_aliasing_threshold(opts.anti_alias.threshold()); let symbols = doc.symbol_boxes().quick(); let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, plates: None }; self.begin_frame(); @@ -358,6 +362,7 @@ impl Renderer { let s = (w as f64 - 2.0).max(1.0) / b.width().max(b.height()).max(1e-6); let view = Affine::translate((w as f64 / 2.0, w as f64 / 2.0)) * Affine::scale(s) * Affine::translate(-b.center().to_vec2()); let mut ctx = single_threaded_context(w, w); + ctx.set_aliasing_threshold(opts.anti_alias.threshold()); if let Some(bg) = background { ctx.set_paint(peniko::Color::from_rgba8(bg[0], bg[1], bg[2], bg[3])); ctx.fill_rect(&kurbo::Rect::new(0.0, 0.0, w as f64, w as f64)); diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index 3214ffe58d..00d9153c1b 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -97,6 +97,13 @@ impl Renderer { chars: Option<(&Arc, usize)>, bounds: Rect, ) { + // A stroke drawn without its dashes is a copy, not the document's stroke: its outline is + // made here and not kept with the document's outlines. + let drawn = f.stroke(st); + let (st, chars) = match &drawn { + std::borrow::Cow::Owned(solid) => (solid, None), + std::borrow::Cow::Borrowed(st) => (*st, chars), + }; let pieces = effects::stroke::stroke_pieces(bp, st); // The line and its heads overlap: they take the opacity once, in one layer, instead of // each folding it into its paint. @@ -253,14 +260,27 @@ impl Renderer { } let node = self.cur.clone().filter(|n| owns_stroke(n, st))?; let key = (self.stroke_owner(Arc::as_ptr(&node) as usize), st as *const StrokeLayer as usize, width.to_bits(), level); + let v = f.visible; + let holds = |crop: Option| crop.is_none_or(|r| r.x0 <= v.x0 && r.y0 <= v.y0 && r.x1 >= v.x1 && r.y1 >= v.y1); if let Some(e) = self.strokes.get_mut(&key) && Arc::ptr_eq(&e.node, &node) + && holds(e.crop) { e.stamp = self.stamp; return Some(e.outline.clone()); } - let outline = expand(); - self.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp }); + // A long stroke without dashes or a width profile is outlined only in and around the view, + // with a margin of the view's own size on each side ([`crop_line`]). + let region = v.inflate(v.width(), v.height()); + let tol = 2f64.powi(level); + let cropped = (crops() && line.elements().len() > CROP_ELEMENTS && st.dash.is_none() && st.profile.is_none()) + .then(|| crop_line(line, region, crop_reach(st, width, f.px, tol), width)) + .flatten(); + let (outline, crop) = match cropped { + Some(part) => (Arc::new(effects::stroke::line_outline(&part, st, width, tol)), Some(region)), + None => (expand(), None), + }; + self.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop }); Some(outline) } @@ -271,3 +291,95 @@ impl Renderer { if self.made_again { 0 } else { address } } } + +/// The stroke lines with more path elements than this are outlined in and around the view only +/// ([`crop_line`]). +pub(crate) const CROP_ELEMENTS: usize = 1024; + +#[cfg(test)] +thread_local! { + /// Whether long strokes are outlined near the view only on this thread ([`crop_line`]). + pub(crate) static CROP_STROKES: std::cell::Cell = const { std::cell::Cell::new(true) }; +} + +fn crops() -> bool { + #[cfg(test)] + return CROP_STROKES.with(std::cell::Cell::get); + #[cfg(not(test))] + true +} + +/// How far stroke `st` at `width` can paint from its path, at a join or a cap, with two output +/// pixels (`px`) and the outline's tolerance `tol` added. +pub(crate) fn crop_reach(st: &StrokeLayer, width: f64, px: f64, tol: f64) -> f64 { + let corner = if st.join == vectorcraft_doc::LineJoin::Miter { st.miter_limit.max(std::f64::consts::SQRT_2) } else { std::f64::consts::SQRT_2 }; + width / 2.0 * corner + 2.0 * px + tol +} + +/// The stroke line `line` without the segments whose control points' box lies more than `reach` +/// from `region`, for outlining a stroke of `width` that is drawn only in `region`. A subpath that +/// loses some of its segments is replaced by its runs of kept segments, each an open subpath; a +/// closed one is walked from a removed segment, so that a run passes through the point where it +/// starts and ends. A closed subpath that a stroke of `width` can cross over (`width` at least the +/// smaller side of its bounds) keeps all its segments, and so does a subpath with no segments. +/// `None` when every segment is kept. +pub(crate) fn crop_line(line: &BezPath, region: Rect, reach: f64, width: f64) -> Option { + use kurbo::{PathEl, PathSeg}; + let near = region.inflate(reach, reach); + let keep = |s: &PathSeg| { + let pts: &[kurbo::Point] = match s { + PathSeg::Line(l) => &[l.p0, l.p1], + PathSeg::Quad(q) => &[q.p0, q.p1, q.p2], + PathSeg::Cubic(c) => &[c.p0, c.p1, c.p2, c.p3], + }; + // A coordinate that is not a number keeps the segment. + !(pts.iter().all(|p| p.x < near.x0) + || pts.iter().all(|p| p.x > near.x1) + || pts.iter().all(|p| p.y < near.y0) + || pts.iter().all(|p| p.y > near.y1)) + }; + let els = line.elements(); + let mut starts: Vec = els.iter().enumerate().filter(|(_, e)| matches!(e, PathEl::MoveTo(_))).map(|(i, _)| i).collect(); + if starts.first() != Some(&0) { + starts.insert(0, 0); + } + let mut out = BezPath::new(); + let mut cut = false; + for (k, &start) in starts.iter().enumerate() { + let Some(sub) = els.get(start..starts.get(k + 1).copied().unwrap_or(els.len())) else { continue }; + let segs = || kurbo::segments(sub.iter().copied()); + let (total, kept) = segs().fold((0, 0), |(t, n), s| (t + 1, n + usize::from(keep(&s)))); + let closed = sub.iter().any(|e| matches!(e, PathEl::ClosePath)); + let crosses = || { + let b = BezPath::from_vec(sub.to_vec()).bounding_box(); + width >= b.width().min(b.height()) + }; + if kept == total || closed && crosses() { + out.extend(sub.iter().copied()); + continue; + } + cut = true; + let first = if closed { segs().position(|s| !keep(&s)).map_or(0, |i| i + 1) } else { 0 }; + let mut open = false; + for s in segs().skip(first).chain(segs().take(first)) { + if !keep(&s) { + open = false; + continue; + } + if !open { + out.move_to(match s { + PathSeg::Line(l) => l.p0, + PathSeg::Quad(q) => q.p0, + PathSeg::Cubic(c) => c.p0, + }); + open = true; + } + match s { + PathSeg::Line(l) => out.line_to(l.p1), + PathSeg::Quad(q) => out.quad_to(q.p1, q.p2), + PathSeg::Cubic(c) => out.curve_to(c.p1, c.p2, c.p3), + } + } + } + cut.then_some(out) +} diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index d97de7a3c9..c82daf32d9 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -21,6 +21,7 @@ mod fxzoom; mod isolation; mod knockout; mod layeropts; +mod longstroke; mod memory; mod objectfx; mod placed_document; @@ -377,6 +378,49 @@ fn a_scaled_instance_is_culled_by_the_effects_in_its_art_as_placed() { assert_eq!(img.pixel(5, 50), [255, 0, 0, 255]); } +#[test] +fn an_instance_is_culled_by_the_art_its_9_slice_guides_move() { + // A 100 × 100 frame with guides a quarter in, holding an instance of a red bar from x 10 to + // 70. Scaled 2 times across, the bar crosses the left guide and is placed by the middle + // column's map, x → 3x − 50: moved 110 pt right, it draws from x 90 to 270 while the frame + // starts at x 110, out of view. + let mut d = Document::new(100.0, 100.0); + let bar = rect_node(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Bar".into(), art: Arc::new(bar) }); + let frame = rect_node(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::None, Paint::None, 0.0); + let inner = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY }); + let art = Node::group(d.alloc_id(), vec![Arc::new(frame), Arc::new(inner)]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Panel".into(), art: Arc::new(art) }); + d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default())); + let (id, l) = (d.alloc_id(), d.layers[0].id); + let xf = Affine::translate((110.0, 0.0)) * Affine::scale_non_uniform(2.0, 1.0); + d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Panel".into(), xf })).unwrap(); + let img = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + assert_eq!(img.pixel(95, 50), [255, 0, 0, 255]); +} + +#[test] +fn an_instance_is_culled_by_the_art_nested_9_slice_guides_move() { + // The panel of the test above at its natural size, in a symbol without guides. The holder's + // instance scales the panel 2 times across and moves it 110 pt right: the bar draws from x 90 + // to 270 while the frame starts at x 110, out of view. + let mut d = Document::new(100.0, 100.0); + let bar = rect_node(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Bar".into(), art: Arc::new(bar) }); + let frame = rect_node(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::None, Paint::None, 0.0); + let inner = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY }); + let art = Node::group(d.alloc_id(), vec![Arc::new(frame), Arc::new(inner)]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Panel".into(), art: Arc::new(art) }); + d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default())); + let panel = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Panel".into(), xf: Affine::IDENTITY }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Holder".into(), art: Arc::new(panel) }); + let (id, l) = (d.alloc_id(), d.layers[0].id); + let xf = Affine::translate((110.0, 0.0)) * Affine::scale_non_uniform(2.0, 1.0); + d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Holder".into(), xf })).unwrap(); + let img = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + assert_eq!(img.pixel(95, 50), [255, 0, 0, 255]); +} + #[test] fn an_instance_with_a_geometry_effect_is_culled_by_its_reshaped_art() { // The art, (0, 0) to (20, 20), drawn from (-100, 10) is out of view, and the Transform effect @@ -885,6 +929,25 @@ fn node_thumbnail_reports_the_size_it_draws() { } } +/// A node rendered with `AntiAlias::None` has hard edges, as a page render with that option does. +#[test] +fn node_renders_follow_the_anti_alias_option() { + let mut d = Document::new(100.0, 100.0); + let id = d.alloc_id(); + let n = Node::path(id, shapes::ellipse(Rect::new(10.3, 10.3, 60.6, 60.6)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let node = Arc::new(n.clone()); + let hard = RenderOptions { anti_alias: AntiAlias::None, ..Default::default() }; + let partial = |img: &Rendered| img.pixels.chunks(4).any(|p| p[3] != 0 && p[3] != 255); + let drawn = |img: &Rendered| img.pixels.chunks(4).any(|p| p[3] == 255); + let mut r = Renderer::new(); + assert!(partial(&r.render_node(&d, &node, 100, 100, Affine::IDENTITY).unwrap()), "art anti-aliasing has partial edge pixels"); + assert!(partial(&r.render_node_thumbnail(&d, &n, 37, None).unwrap()), "art anti-aliasing has partial edge pixels"); + let img = r.render_node_with(&d, &node, 100, 100, Affine::IDENTITY, &hard).unwrap(); + assert!(drawn(&img) && !partial(&img), "render_node_with: every alpha is 0 or 255"); + let thumb = r.render_node_thumbnail_with(&d, &n, 37, None, &hard).unwrap(); + assert!(drawn(&thumb) && !partial(&thumb), "render_node_thumbnail_with: every alpha is 0 or 255"); +} + #[test] fn opacity_mask_with_undecodable_image_leaves_out_object() { use vectorcraft_doc::{Effect, ImageBlob, ImageObject, NodeKind, OpacityMask}; @@ -1272,6 +1335,43 @@ fn invalid_dash_pattern_strokes_solid() { } } +/// With `solid_dashes` a dashed stroke draws as the same stroke without dashes, on its own and as +/// the silhouette of a drop shadow; without it the dashes stay. +#[test] +fn solid_dashes_draw_dashed_strokes_as_solid_lines() { + let line = |dash: bool, shadow: bool| { + let mut d = Document::new(100.0, 100.0); + let mut bp = BezPath::new(); + bp.move_to((10.0, 50.0)); + bp.line_to((90.0, 50.0)); + let id = d.alloc_id(); + let mut n = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&bp), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 6.0)); + let st = n.appearance.stroke_mut().unwrap(); + st.dash = dash.then(|| vectorcraft_doc::Dash { pattern: vec![8.0, 8.0], ..Default::default() }); + if shadow { + let params = serde_json::json!({"x": 4, "y": 4, "blur": 1, "opacity": 100}); + st.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params, visible: true }); + } + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d + }; + let opts = |solid_dashes: bool| RenderOptions { background: Some([255, 255, 255, 255]), solid_dashes, ..Default::default() }; + let draw = |d: &Document, solid: bool| Renderer::new().render(d, 100, 100, Affine::IDENTITY, &opts(solid)); + for shadow in [false, true] { + let solid = draw(&line(false, shadow), false); + assert_ne!(draw(&line(true, shadow), false).pixels, solid.pixels, "the dashes show without the option (shadow: {shadow})"); + assert_eq!(draw(&line(true, shadow), true).pixels, solid.pixels, "the dashes go with the option (shadow: {shadow})"); + assert_eq!(draw(&line(false, shadow), true).pixels, solid.pixels, "a solid stroke is unchanged (shadow: {shadow})"); + } + // One renderer that draws the shadow both ways makes its raster again for each setting. + let (dashed, mut r) = (line(true, true), Renderer::new()); + let fresh = |solid: bool| draw(&dashed, solid).pixels; + for solid in [false, true, false] { + assert_eq!(r.render(&dashed, 100, 100, Affine::IDENTITY, &opts(solid)).pixels, fresh(solid), "reused renderer, solid: {solid}"); + } +} + /// An image that can't be decoded is counted on the thread that tried to decode it: an export /// compares [`decode_failures`] before and after it draws, so another thread's failure meanwhile is /// not its own. @@ -1648,43 +1748,43 @@ fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec { #[test] fn a_png_past_the_allowance_draws_at_reduced_size() { use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; - let img = image::ImageBuffer::, _>::from_fn(256, 400, |x, _| { - if x < 128 { image::Rgba([51400, 10280, 10280, 65535]) } else { image::Rgba([10280, 10280, 51400, 65535]) } + let img = image::ImageBuffer::, _>::from_fn(400, 400, |x, _| { + if x < 200 { image::Rgba([51400, 10280, 10280, 65535]) } else { image::Rgba([10280, 10280, 51400, 65535]) } }); let png = encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png); - // 256 × 400 is 409,600 bytes as RGBA; 252 × 395 is the largest within 400,000. - assert_eq!(with_allowance(400_000, || paint::reduced_size(&png)), Some((252, 395))); + // 400 × 400 is 640,000 bytes as RGBA; 387 × 387 is the largest within 600,000. + assert_eq!(with_allowance(600_000, || paint::reduced_size(&png)), Some((387, 387))); assert_eq!(paint::reduced_size(&png), None, "within the 2 GB allowance"); - let mut d = Document::new(256.0, 400.0); + let mut d = Document::new(400.0, 400.0); d.images.insert("over".into(), ImageBlob::new("image/png", png)); let id = d.alloc_id(); let im = - ImageObject { key: "over".into(), width: 256, height: 400, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + ImageObject { key: "over".into(), width: 400, height: 400, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); let failed = decode_failures(); // As on screen, where an image that can't be decoded draws as a crossed box. let screen = RenderOptions { smooth_images: false, mark_undecoded_images: true, ..Default::default() }; - let r = with_allowance(400_000, || Renderer::new().render(&d, 256, 400, Affine::IDENTITY, &screen)); + let r = with_allowance(600_000, || Renderer::new().render(&d, 400, 400, Affine::IDENTITY, &screen)); assert_eq!(decode_failures(), failed); - assert_eq!((r.pixel(32, 200), r.pixel(224, 200)), ([200, 40, 40, 255], [40, 40, 200, 255])); - // 256 × 256 at 16 bits a sample is 524,288 bytes decoded and 262,144 as RGBA: past 400,000 as + assert_eq!((r.pixel(50, 200), r.pixel(350, 200)), ([200, 40, 40, 255], [40, 40, 200, 255])); + // 300 × 300 at 16 bits a sample is 720,000 bytes decoded and 360,000 as RGBA: past 600,000 as // decoded and within it as RGBA, it is read a row at a time at its own size. - let small = image::ImageBuffer::, _>::from_pixel(256, 256, image::Rgba([51400, 10280, 10280, 65535])); + let small = image::ImageBuffer::, _>::from_pixel(300, 300, image::Rgba([51400, 10280, 10280, 65535])); let small = encoded(image::DynamicImage::ImageRgba16(small), image::ImageFormat::Png); - assert_eq!(with_allowance(400_000, || paint::reduced_size(&small)), Some((256, 256))); - let pm = with_allowance(400_000, || paint::decode_pixmap(&small)).expect("read a row at a time"); + assert_eq!(with_allowance(600_000, || paint::reduced_size(&small)), Some((300, 300))); + let pm = with_allowance(600_000, || paint::decode_pixmap(&small)).expect("read a row at a time"); let c = pm.sample(3, 3); - assert_eq!((pm.width(), pm.height(), [c.r, c.g, c.b, c.a]), (256, 256, [200, 40, 40, 255])); - // A row is read only while the reader's buffers fit the allowance. Below 4,096 columns of 16-bit - // RGBA they take 344,069 bytes and 44 a column: 1,271 columns take 399,993 bytes, within 400,000, - // and 1,272 columns take 400,037 and are not decoded (their samples, 8 bytes a pixel, are past - // it too). + assert_eq!((pm.width(), pm.height(), [c.r, c.g, c.b, c.a]), (300, 300, [200, 40, 40, 255])); + // A row is read only while the reader's buffers fit the allowance, counting the stream buffer + // three times for the moment it grows. Below 4,096 columns of 16-bit RGBA they take 516,103 + // bytes and 60 a column: 1,398 columns take 599,983 bytes, within 600,000, and 1,399 columns + // take 600,043 and are not decoded (their samples, 8 bytes a pixel, are past it too). let wide = |w: u32| { - let img = image::ImageBuffer::, _>::from_pixel(w, 40, image::Rgba([51400, 10280, 10280, 65535])); + let img = image::ImageBuffer::, _>::from_pixel(w, 60, image::Rgba([51400, 10280, 10280, 65535])); encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png) }; - assert_eq!(with_allowance(400_000, || paint::reduced_size(&wide(1271))), Some((1271, 40))); - assert_eq!(with_allowance(400_000, || paint::reduced_size(&wide(1272))), None); + assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1398))), Some((1398, 60))); + assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1399))), None); // An image of more pixels than the allowance has bytes is not read: 1,000 × 400 8-bit gray // pixels are drawn at 500 × 200 within 400,000 bytes, and 1,000 × 401 are not. let gray = |h: u32| encoded(image::DynamicImage::ImageLuma8(image::GrayImage::from_pixel(1000, h, image::Luma([90]))), image::ImageFormat::Png); @@ -1732,13 +1832,13 @@ fn a_reduced_decode_counts_what_reading_takes_beside_the_images_paints_hold() { // Decoded whole: 14,400 bytes of RGB and a 16-row band of 8,960 bytes, beside a 73 × 54 result // of 15,768 bytes. let jpeg = encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), image::ImageFormat::Jpeg); - // Read a row at a time: 355,333 bytes in the reader's buffers for 256 columns of 16-bit RGBA, - // beside a 252 × 395 result of 398,160 bytes. + // Read a row at a time: 540,103 bytes in the reader's buffers for 400 columns of 16-bit RGBA, + // beside a 387 × 387 result of 599,076 bytes. let png = encoded( - image::DynamicImage::ImageRgba16(image::ImageBuffer::from_pixel(256, 400, image::Rgba([51400, 10280, 10280, 65535]))), + image::DynamicImage::ImageRgba16(image::ImageBuffer::from_pixel(400, 400, image::Rgba([51400, 10280, 10280, 65535]))), image::ImageFormat::Png, ); - for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 400_000, 398_160 + 355_333, (252, 395))] { + for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 600_000, 599_076 + 540_103, (387, 387))] { let failed = decode_failures(); let none = with_allowance(allowance, || with_room(room - 1, || paint::decode_pixmap_or_why(bytes))); assert_eq!(none.err(), Some(paint::Undecoded::NoRoom), "not decoded with a byte too few, and tried again later"); diff --git a/crates/render/src/tests/longstroke.rs b/crates/render/src/tests/longstroke.rs new file mode 100644 index 0000000000..ef7a449d3f --- /dev/null +++ b/crates/render/src/tests/longstroke.rs @@ -0,0 +1,225 @@ +//! A long stroke without dashes or a width profile is outlined in and around the view only +//! (`crop_line`), and draws the same pixels as when it is outlined whole. + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, LineCap, LineJoin, Node, StrokeLayer}; +use vectorcraft_geom::{PathData, Point, Vec2}; + +use crate::renderer::{CROP_STROKES, crop_line}; +use crate::*; + +const SIZE: u32 = 200; + +/// A document holding `path` stroked with `st` and no fill. +fn doc(path: &BezPath, st: StrokeLayer) -> Document { + let mut d = Document::new(1000.0, 1000.0); + let n = Node::path(d.alloc_id(), PathData::from_bezpath(path), Appearance { items: vec![AppearanceItem::Stroke(st)], ..Default::default() }); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +fn stroke(width: f64, join: LineJoin, cap: LineCap) -> StrokeLayer { + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), width); + st.join = join; + st.cap = cap; + st.miter_limit = 10.0; + st +} + +/// The view that shows `at` in the middle of the 200×200 frame. +fn view_at(at: Point) -> Affine { + Affine::translate((100.0 - at.x, 100.0 - at.y)) +} + +fn render(r: &mut Renderer, d: &Document, at: Point) -> Rendered { + r.render(d, SIZE, SIZE, view_at(at), &RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }) +} + +/// What a renderer that outlines every stroke whole draws. +fn whole(d: &Document, at: Point) -> Rendered { + CROP_STROKES.with(|c| c.set(false)); + let mut r = Renderer::new(); + let img = render(&mut r, d, at); + CROP_STROKES.with(|c| c.set(true)); + assert!(r.strokes.values().all(|e| e.crop.is_none()), "the reference outlines the stroke whole"); + img +} + +/// 3,000 anchors 8 pt apart, up and down by 30 pt, every third segment curved: sharp miter joins. +fn zigzag() -> BezPath { + let mut bp = BezPath::new(); + let at = |i: usize| Point::new(i as f64 * 8.0, if i.is_multiple_of(2) { 0.0 } else { 30.0 }); + bp.move_to(at(0)); + for i in 1..3000 { + if i % 3 == 0 { + bp.curve_to(at(i - 1) + Vec2::new(6.0, 0.0), at(i) + Vec2::new(-6.0, 10.0), at(i)); + } else { + bp.line_to(at(i)); + } + } + bp +} + +/// A closed polygon of `n` anchors round a circle of radius `r` about the origin. +fn ring(n: usize, r: f64) -> BezPath { + let mut bp = BezPath::new(); + for i in 0..n { + let t = i as f64 / n as f64 * std::f64::consts::TAU; + let p = Point::new(r * t.cos(), r * t.sin()); + if i == 0 { bp.move_to(p) } else { bp.line_to(p) } + } + bp.close_path(); + bp +} + +#[test] +fn a_long_stroke_draws_the_same_pixels_outlined_near_the_view() { + let mut inside = stroke(8.0, LineJoin::Round, LineCap::Butt); + inside.align = vectorcraft_doc::StrokeAlign::Inside; + // The ring starts at (5000, 0): the second view is on its start and end. + let cases = [ + ("zigzag, miter joins, square caps", doc(&zigzag(), stroke(6.0, LineJoin::Miter, LineCap::Square)), Point::new(12_000.0, 15.0), true), + ("ring, round joins", doc(&ring(4000, 5000.0), stroke(12.0, LineJoin::Round, LineCap::Round)), Point::new(0.0, 5000.0), true), + ("ring through its start, bevel joins", doc(&ring(4000, 5000.0), stroke(5.0, LineJoin::Bevel, LineCap::Butt)), Point::new(5000.0, 0.0), true), + ("ring, inside stroke", doc(&ring(4000, 5000.0), inside), Point::new(-5000.0, 0.0), true), + ]; + for (what, d, at, crops) in &cases { + let mut r = Renderer::new(); + let img = render(&mut r, d, *at); + assert_eq!(r.strokes.values().any(|e| e.crop.is_some()), *crops, "{what}: outlined near the view"); + assert!(img.pixels == whole(d, *at).pixels, "{what}: the same pixels as the whole outline"); + // A view inside the region kept around the first one reuses the outline; one beyond it + // outlines the stroke again. + for step in [Point::new(60.0, 40.0), Point::new(450.0, 0.0), Point::new(-900.0, 300.0)] { + let next = *at + step.to_vec2(); + assert!(render(&mut r, d, next).pixels == whole(d, next).pixels, "{what}, moved by {step:?}: the same pixels"); + } + } +} + +/// A zigzag of 3,000 anchors 8 pt apart between y = 60 and y = 550, through the bottom of a view +/// on y = 0. +fn tall_zigzag() -> BezPath { + let mut bp = BezPath::new(); + let at = |i: usize| Point::new(i as f64 * 8.0, if i.is_multiple_of(2) { 60.0 } else { 550.0 }); + bp.move_to(at(0)); + for i in 1..3000 { + bp.line_to(at(i)); + } + bp +} + +#[test] +fn a_long_stroke_under_a_wide_blur_draws_the_same_pixels_while_dragging_on_threads() { + // While dragging on threads, a drop shadow this large is drawn through a filter layer whose + // offscreen reaches 602 px past the view: the parts of the stroke that far away feed the blur. + let mut d = Document::new(1000.0, 1000.0); + let shadow = serde_json::json!({"x": 0, "y": 0, "blur": 400, "opacity": 100, "mode": "normal"}); + let look = Appearance { items: vec![AppearanceItem::Stroke(stroke(20.0, LineJoin::Round, LineCap::Butt))], ..Default::default() }; + let n = Node::path(d.alloc_id(), PathData::from_bezpath(&tall_zigzag()), look); + // The shadow is the group's: the path itself draws as a plain path. + let mut g = Node::group(d.alloc_id(), vec![n.into()]); + g.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: shadow, visible: true }); + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let at = Point::new(12_000.0, 0.0); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), dragging: true, ..Default::default() }; + let draw = |crops: bool| { + CROP_STROKES.with(|c| c.set(crops)); + let mut r = Renderer::new(); + r.threads = 2; + let img = r.render(&d, SIZE, SIZE, view_at(at), &opts); + CROP_STROKES.with(|c| c.set(true)); + (img, r.strokes.values().any(|e| e.crop.is_some())) + }; + let ((near, cropped), (all, _)) = (draw(true), draw(false)); + assert!(cropped, "outlined near the view"); + assert!(all.pixel(100, 0)[0] < 250, "the shadow shows above the stroke: {:?}", all.pixel(100, 0)); + assert!(near.pixels == all.pixels, "the same pixels as the whole outline"); +} + +#[test] +fn a_member_below_the_view_casts_its_wide_shadow_while_dragging_on_threads() { + // A 400 pt shadow of a group whose only member, a rectangle, lies 50 pt below the view. + let mut d = Document::new(1000.0, 1000.0); + let shadow = serde_json::json!({"x": 0, "y": 0, "blur": 400, "opacity": 100, "mode": "normal"}); + let look = Appearance { items: vec![AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK)))], ..Default::default() }; + let n = Node::path(d.alloc_id(), PathData::from_bezpath(&Rect::new(-1000.0, 150.0, 1000.0, 550.0).to_path(0.1)), look); + let mut g = Node::group(d.alloc_id(), vec![n.into()]); + g.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: shadow, visible: true }); + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), dragging: true, ..Default::default() }; + let mut r = Renderer::new(); + r.threads = 2; + let img = r.render(&d, SIZE, SIZE, view_at(Point::ZERO), &opts); + assert!(img.pixel(100, 199)[0] < 200, "the shadow shows at the bottom of the view: {:?}", img.pixel(100, 199)); +} + +#[test] +fn a_long_stroke_is_outlined_near_the_view_only() { + let d = doc(&zigzag(), stroke(6.0, LineJoin::Miter, LineCap::Square)); + let at = Point::new(12_000.0, 15.0); + let mut r = Renderer::new(); + render(&mut r, &d, at); + let near = r.strokes.values().map(|e| e.outline.elements().len()).sum::(); + CROP_STROKES.with(|c| c.set(false)); + let mut full = Renderer::new(); + render(&mut full, &d, at); + CROP_STROKES.with(|c| c.set(true)); + let all = full.strokes.values().map(|e| e.outline.elements().len()).sum::(); + assert!(near > 0 && near * 10 < all, "{near} outline elements near the view, {all} for the whole stroke"); +} + +#[test] +fn a_stroke_a_wide_stroke_crosses_over_stays_whole() { + // A closed sliver 4 pt tall: a 10 pt stroke covers it from side to side. + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + for i in 1..=2000 { + bp.line_to((f64::from(i) * 10.0, 0.0)); + } + bp.line_to((20_000.0, 4.0)); + bp.line_to((0.0, 4.0)); + bp.close_path(); + let d = doc(&bp, stroke(10.0, LineJoin::Miter, LineCap::Butt)); + let at = Point::new(20_000.0, 2.0); + let mut r = Renderer::new(); + let img = render(&mut r, &d, at); + assert!(r.strokes.values().all(|e| e.crop.is_none())); + assert!(img.pixels == whole(&d, at).pixels); +} + +fn path(svg: &str) -> BezPath { + BezPath::from_svg(svg).unwrap() +} + +#[test] +fn crop_line_keeps_the_runs_of_segments_near_the_region() { + let region = Rect::new(0.0, 0.0, 100.0, 100.0); + let crop = |svg: &str| crop_line(&path(svg), region, 5.0, 1.0).map(|bp| bp.to_svg()); + // Nothing to leave out: an empty path, one segment, a path in the region. + assert_eq!(crop(""), None); + assert_eq!(crop("M10,10 L90,90"), None); + assert_eq!(crop("M10,10 L90,90 L10,90 Z"), None); + // A segment within the reach of the region stays; one beyond it goes, and the open path is cut. + assert_eq!(crop("M50,50 L104,50 L200,50 L300,50").as_deref(), Some("M50,50 L104,50 L200,50")); + assert_eq!(crop("M50,50 L200,50 L300,50 L400,50").as_deref(), Some("M50,50 L200,50")); + // A curve whose control point reaches the region stays. + assert_eq!(crop("M200,0 C50,50 300,0 400,0 L500,0").as_deref(), Some("M200,0 C50,50 300,0 400,0")); + // Two runs, each its own open subpath. + assert_eq!(crop("M50,10 L300,10 L300,90 L50,90").as_deref(), Some("M50,10 L300,10 M300,90 L50,90")); + // Every segment goes. + assert_eq!(crop("M300,300 L400,400").as_deref(), Some("")); + // A closed subpath is walked from a segment it loses: its start stays inside one run. + assert_eq!(crop("M50,50 L50,500 L500,500 L500,50 Z").as_deref(), Some("M500,50 L50,50 L50,500")); + // A subpath with no segments stays, and so does an untouched subpath beside a cut one. + assert_eq!(crop("M900,900 M10,10 L20,20 M50,50 L300,50 L400,50").as_deref(), Some("M900,900 M10,10 L20,20 M50,50 L300,50")); + // A closed subpath that the stroke crosses over keeps all its segments. + assert_eq!(crop_line(&path("M50,0 L50,2 L500,2 L500,0 Z"), region, 5.0, 3.0), None); + // A coordinate that is not a number keeps its segment. + let mut nan = path("M50,50 L300,50 L400,50"); + nan.line_to((f64::NAN, 50.0)); + assert!(crop_line(&nan, region, 5.0, 1.0).is_some_and(|bp| bp.elements().iter().any(|e| e.end_point().is_some_and(|p| p.x.is_nan())))); +} diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 5fc015039f..387a1a3420 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -83,9 +83,12 @@ impl Writer<'_> { let t = &*heights; let inline = t.runs.iter().any(|r| r.inline.is_some()); // Ruby is written as outlines with its base text: a reader's can't place it. So are - // small capitals, superscript and subscript and tab leaders, which SVG text doesn't draw (#3869). - let unwritable = t.runs.iter().any(|r| r.style.small_caps.is_some() || r.style.position != vectorcraft_doc::CharPosition::Normal) - || std::iter::once(&t.para).chain(&t.paras).any(|p| p.tabs.iter().any(|tab| !tab.leader.is_empty())); + // small capitals, superscript and subscript and tab leaders, which SVG text doesn't draw (#3869), + // and a glyph chosen for a character, which a reader's draws with the default glyph. + let unwritable = + t.runs.iter().any(|r| { + r.style.small_caps.is_some() || r.style.position != vectorcraft_doc::CharPosition::Normal || r.style.glyph_alternate.is_some() + }) || std::iter::once(&t.para).chain(&t.paras).any(|p| p.tabs.iter().any(|tab| !tab.leader.is_empty())); let outlined = self.opts.outline_text || t.vertical || !t.ruby.is_empty() || (inline && matches!(t.kind, TextKind::OnPath { .. })) || unwritable; let chars = |w: &mut Self, n: &Node| if outlined { w.text_outlines(n, t) } else { w.text(n, t) }; diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index 3107a1f44a..eee6e2fbf5 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -176,6 +176,24 @@ fn digits_are_written_as_drawn() { assert!(!text.contains("page 4") && !text.contains("page ٥"), "{svg}"); } +/// A character drawn with a chosen glyph is written as outlines: a reader's `` would draw the +/// default glyph. +#[test] +fn a_chosen_glyph_is_written_as_outlines() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; + let db = vectorcraft_text::FontDb::global(); + db.add_font(alternates_font(true).unwrap()); + let [u1, ..] = unencoded_glyphs().unwrap(); + let face = db.face(alternates_family(true), "Regular").unwrap(); + let plain = CharStyle { font_family: alternates_family(true).into(), ..style(12.0) }; + let chosen = CharStyle { glyph_alternate: Some(face.choice('a', u1)), ..plain.clone() }; + let svg = export(&area_doc(vec![run("xay", plain.clone())], 280.0, Justify::Left), &ExportOptions::default()); + assert!(svg.contains("` element's 12. diff --git a/crates/text/src/edit.rs b/crates/text/src/edit.rs index 1dcb40f01c..a4505f9596 100644 --- a/crates/text/src/edit.rs +++ b/crates/text/src/edit.rs @@ -49,24 +49,31 @@ pub fn style_at(runs: &[TextRun], byte: usize) -> CharStyle { } /// Style for text typed over `start..end` (Illustrator: the first replaced character's style, or -/// the character before the caret). +/// the character before the caret), without a glyph choice ([`CharStyle::glyph_alternate`]): +/// typed characters take their default glyphs. pub fn insertion_style(runs: &[TextRun], start: usize, end: usize) -> CharStyle { - if end > start { - // The character at `start` (not the one before it). - let mut off = 0; - for r in runs { - if start < off + r.text.len() { - return r.style.clone(); + let mut style = 'found: { + if end > start { + // The character at `start` (not the one before it). + let mut off = 0; + for r in runs { + if start < off + r.text.len() { + break 'found r.style.clone(); + } + off += r.text.len(); } - off += r.text.len(); } - } - style_at(runs, start) + style_at(runs, start) + }; + style.glyph_alternate = None; + style } /// Merge adjacent runs with equal styles and drop empty runs (keeping one run so the object /// remembers its style). Inline graphic runs never merge: each stays one [`INLINE_CHAR`]; one -/// whose text is anything else (malformed input) becomes plain text. +/// whose text is anything else (malformed input) becomes plain text. A run with a glyph choice +/// ([`CharStyle::glyph_alternate`]) is not merged into the run before it, and loses the choice +/// when its text does not start with the character the choice is for. pub fn normalize(runs: &mut Vec) { let first_style = runs.first().map(|r| r.style.clone()); let mut out: Vec = Vec::with_capacity(runs.len()); @@ -77,8 +84,13 @@ pub fn normalize(runs: &mut Vec) { if r.inline.is_some() && !is_inline_text(&r.text) { r.inline = None; } + if r.style.glyph_alternate.as_ref().is_some_and(|c| !r.text.starts_with(c.ch)) { + r.style.glyph_alternate = None; + } match out.last_mut() { - Some(l) if l.style == r.style && l.inline.is_none() && r.inline.is_none() => l.text.push_str(&r.text), + Some(l) if l.style == r.style && l.inline.is_none() && r.inline.is_none() && r.style.glyph_alternate.is_none() => { + l.text.push_str(&r.text) + } _ => out.push(r), } } @@ -100,7 +112,8 @@ fn split_at(runs: &mut Vec, byte: usize) -> usize { if byte < off + len { let at = floor_char(&runs[i].text, byte - off); let tail = runs[i].text.split_off(at); - let style = runs[i].style.clone(); + // A glyph choice is for the run's first character, which stays in the head. + let style = CharStyle { glyph_alternate: None, ..runs[i].style.clone() }; // An inline graphic is one character: a split lands before it (`at` == 0), the empty // head is dropped by `normalize` and the tail keeps the graphic. let inline = runs[i].inline.clone(); @@ -177,7 +190,12 @@ pub fn slice_runs(runs: &[TextRun], start: usize, end: usize) -> Vec { off = re; continue; } - out.push(TextRun { text: t.to_string(), style: r.style.clone(), inline: r.inline.clone() }); + let mut style = r.style.clone(); + // A glyph choice is for the run's first character. + if floor_char(&r.text, a - rs) > 0 { + style.glyph_alternate = None; + } + out.push(TextRun { text: t.to_string(), style, inline: r.inline.clone() }); } off = re; } diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 1972577ef5..d42e8f3516 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -17,6 +17,7 @@ use crate::GlyphImage; use crate::colr::ColourContent; use vectorcraft_doc::color::Color; +mod alternates; mod build; mod cache; mod db; @@ -30,6 +31,7 @@ mod stylistic_sets; mod traits; mod wanted; +pub use alternates::GlyphAlternate; pub use build::style_weight; #[cfg(test)] use cache::GlyphCache; diff --git a/crates/text/src/fontdb/alternates.rs b/crates/text/src/fontdb/alternates.rs new file mode 100644 index 0000000000..2a582bbe71 --- /dev/null +++ b/crates/text/src/fontdb/alternates.rs @@ -0,0 +1,165 @@ +//! The alternate glyphs a face's `GSUB` table gives one character: the Glyphs panel's Show › +//! Alternates for Current Selection. The application finds the character's default glyph in the +//! `cmap` and looks it up in the coverage of each lookup of the features that substitute one glyph +//! for another, as the OpenType registry describes `aalt`. +//! +//! + +use skrifa::MetadataProvider; +use skrifa::raw::TableProvider; +use skrifa::raw::tables::gsub::{AlternateSubstFormat1, SingleSubst, SubstitutionSubtables}; +use vectorcraft_doc::GlyphChoice; + +use super::FontFace; + +/// One glyph [`FontFace::alternates`] lists: its id and the feature it was found in (`aalt`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct GlyphAlternate { + pub gid: u32, + pub feature: [u8; 4], +} + +/// Caps on what a damaged or very large `GSUB` table can make [`FontFace::alternates`] read: +/// feature records, lookups per feature and in all, subtables per lookup and in all, glyphs per +/// alternate set and glyphs listed in all. +const MAX_FEATURES: usize = 4096; +const MAX_FEATURE_LOOKUPS: usize = 256; +const MAX_LOOKUPS: usize = 4096; +const MAX_SUBTABLES: usize = 256; +const MAX_SUBTABLE_READS: usize = 16384; +const MAX_SET: usize = 512; +const MAX_ALTERNATES: usize = 1024; + +/// The other discretionary features that substitute one glyph for another (historical forms, +/// justification alternates, alternate annotation forms, ornaments, titling), after `cv99`, in +/// tag order. +const OTHER_FEATURES: [&[u8; 4]; 5] = [b"hist", b"jalt", b"nalt", b"ornm", b"titl"]; + +/// Where the glyphs of feature `tag` come in the list: `aalt`, `salt`, `ss01` to `ss20`, `swsh`, +/// `cv01` to `cv99`, then [`OTHER_FEATURES`]. `None` for a feature that is not listed. +fn feature_rank(tag: [u8; 4]) -> Option<(u8, u8)> { + let number = |t: &[u8]| std::str::from_utf8(t).ok().filter(|s| s.bytes().all(|b| b.is_ascii_digit())).and_then(|s| s.parse::().ok()); + match &tag { + b"aalt" => Some((0, 0)), + b"salt" => Some((1, 0)), + [b's', b's', ..] => number(&tag[2..]).filter(|n| (1..=20).contains(n)).map(|n| (2, n)), + b"swsh" => Some((3, 0)), + [b'c', b'v', ..] => number(&tag[2..]).filter(|n| (1..=99).contains(n)).map(|n| (4, n)), + _ => OTHER_FEATURES.iter().position(|t| **t == tag).map(|i| (5, i as u8)), + } +} + +impl FontFace { + /// The face's alternate glyphs for `c`, from its `GSUB` table: the glyphs single substitutions + /// (lookup type 1) and alternate substitutions (type 3, the whole set in the font's order), in + /// extension lookups (type 7) too, put in place of `c`'s default glyph. `aalt` comes first, + /// then `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99`, `hist`, `jalt`, `nalt`, `ornm` and + /// `titl`; within a feature its lookups go in lookup order. A glyph found again is left out. + /// The default glyph is listed only when `aalt` lists it. Ligatures and contextual + /// substitutions are not read. Empty when the face does not map `c`, has no `GSUB` table, or + /// the table cannot be read; glyph ids past the face's glyph count are left out. + pub fn alternates(&self, c: char) -> Vec { + let mut out: Vec = vec![]; + let Some(f) = self.skrifa() else { return out }; + let Some(default) = f.charmap().map(c) else { return out }; + let Ok(gsub) = f.gsub() else { return out }; + let (Ok(features), Ok(lookups)) = (gsub.feature_list(), gsub.lookup_list()) else { return out }; + let glyphs = f.maxp().map_or(0, |m| u32::from(m.num_glyphs())); + // The lookups of the listed features, by rank and lookup index. + // The listed feature records are read in rank order, so the cap on lookups in all leaves + // out the lowest ranked ones. + let records = features.feature_records(); + let mut ranked: Vec<((u8, u8), usize, [u8; 4])> = records + .iter() + .take(MAX_FEATURES) + .enumerate() + .filter_map(|(i, r)| { + let tag = r.feature_tag().to_be_bytes(); + feature_rank(tag).map(|rank| (rank, i, tag)) + }) + .collect(); + ranked.sort_unstable_by_key(|r| (r.0, r.1)); + let mut wanted: Vec<((u8, u8), u16, [u8; 4])> = vec![]; + for (rank, i, tag) in ranked { + let room = MAX_LOOKUPS.saturating_sub(wanted.len()); + if room == 0 { + break; + } + let Some(record) = records.get(i) else { continue }; + let Ok(feature) = record.feature(features.offset_data()) else { continue }; + wanted.extend(feature.lookup_list_indices().iter().take(MAX_FEATURE_LOOKUPS.min(room)).map(|i| (rank, i.get(), tag))); + } + wanted.sort_unstable_by_key(|w| (w.0, w.1)); + wanted.dedup_by_key(|w| (w.0, w.1)); + let mut push = |gid: u32, feature: [u8; 4]| { + let listed = gid != default.to_u32() || feature == *b"aalt"; + if listed && gid < glyphs && out.len() < MAX_ALTERNATES && !out.iter().any(|a| a.gid == gid) { + out.push(GlyphAlternate { gid, feature }); + } + }; + let all = lookups.lookups(); + let mut reads = MAX_SUBTABLE_READS; + for (_, index, tag) in wanted { + if reads == 0 { + break; + } + let Ok(subtables) = all.get(usize::from(index)).and_then(|l| l.subtables()) else { continue }; + let n = MAX_SUBTABLES.min(reads); + // A glyph takes the first subtable of a lookup whose coverage holds it. + match subtables { + SubstitutionSubtables::Single(s) => { + if let Some(gid) = s.iter().take(n).inspect(|_| reads -= 1).flatten().find_map(|t| single(&t, default.to_u32())) { + push(gid, tag); + } + } + SubstitutionSubtables::Alternate(s) => { + if let Some(set) = s.iter().take(n).inspect(|_| reads -= 1).flatten().find_map(|t| alternate_set(&t, default.to_u32())) { + set.into_iter().for_each(|gid| push(gid, tag)); + } + } + _ => {} + } + } + out + } + + /// How many glyphs the face has (its `maxp` table; 0 when it can't be read). + pub fn glyph_count(&self) -> u32 { + self.skrifa().and_then(|f| f.maxp().ok()).map_or(0, |m| u32::from(m.num_glyphs())) + } + + /// Does this face draw `choice` for character `c`? It does when the choice is for `c`, names + /// this face's PostScript name and version, and its glyph id is one of the face's glyphs. + pub fn draws(&self, choice: &GlyphChoice, c: char) -> bool { + choice.ch == c && choice.version == self.version && choice.gid < self.glyph_count() && choice.font == self.postscript_name() + } + + /// `c` drawn with glyph `gid` of this face ([`CharStyle::glyph_alternate`]). + /// + /// [`CharStyle::glyph_alternate`]: vectorcraft_doc::CharStyle::glyph_alternate + pub fn choice(&self, c: char, gid: u32) -> GlyphChoice { + GlyphChoice { ch: c, gid, font: self.postscript_name(), version: self.version.clone() } + } +} + +/// The glyph single substitution `t` puts in place of `gid`, when its coverage holds `gid`. +fn single(t: &SingleSubst<'_>, gid: u32) -> Option { + match t { + SingleSubst::Format1(t) => { + t.coverage().ok()?.get(skrifa::GlyphId::new(gid))?; + // The delta is added modulo 65536. + Some((gid as i32 + i32::from(t.delta_glyph_id())).rem_euclid(0x1_0000) as u32) + } + SingleSubst::Format2(t) => { + let i = t.coverage().ok()?.get(skrifa::GlyphId::new(gid))?; + t.substitute_glyph_ids().get(usize::from(i)).map(|g| u32::from(g.get().to_u16())) + } + } +} + +/// The alternate set of alternate substitution `t` for `gid`, when its coverage holds `gid`. +fn alternate_set(t: &AlternateSubstFormat1<'_>, gid: u32) -> Option> { + let i = t.coverage().ok()?.get(skrifa::GlyphId::new(gid))?; + let set = t.alternate_sets().get(usize::from(i)).ok()?; + Some(set.alternate_glyph_ids().iter().take(MAX_SET).map(|g| u32::from(g.get().to_u16())).collect()) +} diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 0d8eb0e3fd..1b14dd6dcb 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -152,6 +152,32 @@ impl FontDb { list } + /// Whether the installed fonts are cataloged, so lookups by family name no longer wait for + /// the scan. Always true on wasm, which has no installed fonts. + pub fn installed_fonts_ready(&self) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + self.cataloged.get().is_some() + } + #[cfg(target_arch = "wasm32")] + true + } + + /// [`FontDb::menu_family_list`] without waiting for the installed fonts' scan: until it ends, + /// the families already loaded (the bundled fonts and any loaded meanwhile), sorted, without + /// the hidden ones. For what is built every frame, such as the menu bar's Type › Font, so the + /// window's first frame doesn't wait for the scan of a large font library (#5483). + /// [`FontDb::generation`] changes when the scan ends. + pub fn menu_family_list_now(&self) -> Arc<[String]> { + if self.installed_fonts_ready() { + return self.menu_family_list(); + } + let mut v: Vec = self.read_faces().iter().map(|f| f.family.clone()).filter(|f| !f.starts_with('.')).collect(); + v.sort_by_key(|a| a.to_lowercase()); + v.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); + v.into() + } + /// How a font menu labels `family`: the English name when `english` is on (Preferences › Type › /// Show Font Names in English, the default), else the font's native-language name when it has /// one. The document and commands still use the English family ([`Self::canonical`]). diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 38688b8ce5..b814506e6d 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -327,10 +327,14 @@ impl Ctx<'_> { } else if self.vertical && stands_upright(g) { let next = self.out.glyphs.len(); let after_base = self.out.glyphs.last().is_some_and(|p| p.byte == g.byte && p.line == line && p.len > 0); + // Baseline shift moves it across the column at any Character Rotation: the shift is + // taken off before the turn and put back after it. + let shift = pre * Point::new(0.0, -g.bshift) - pre * Point::ZERO; + let (shift, unshift) = (Affine::translate(shift), Affine::translate(-shift)); if let Some((_, _, turn, after)) = cluster.filter(|c| c.0 == g.byte && c.1 == next && after_base && g.len > 0) { // A later glyph of an upright glyph's cluster: set after it as the shaper placed // it, and turned with it. - m = turn * Affine::translate((after - origin.x, 0.0)) * m; + m = shift * turn * Affine::translate((after - origin.x, 0.0)) * unshift * m; self.upright_cluster = Some((g.byte, next + 1, turn, after)); } else { // Turned about the centre of its cell, which the column's centre line runs through: @@ -342,7 +346,7 @@ impl Ctx<'_> { // turning point instead would move it across the column too). let turn = Affine::translate((-g.lead, 0.0)) * Affine::rotate_about(-std::f64::consts::FRAC_PI_2, Point::new(origin.x + cell * 0.5, origin.y - upright_centre(g, cell, em))); - m = turn * m; + m = shift * turn * unshift * m; // Its own advance across, from where the cell centres it: where the shaper set the // next glyph of its cluster. let across = g.face.advance(g.gid) * g.sx; diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs index 8f01a5d32b..372c70b2fd 100644 --- a/crates/text/src/layout/vertical.rs +++ b/crates/text/src/layout/vertical.rs @@ -1,14 +1,24 @@ use super::flow::flow; use super::region::Region; -use super::{Affine, Ctx, Punct, Range, Rect, SGlyph, Tcy, TextLayout, TextObject, VerticalAlign, is_cjk, punct}; +use super::{Affine, Ctx, Punct, Range, Rect, SGlyph, Tcy, TextLayout, TextObject, VerticalAlign, continues_cluster, is_cjk, punct}; /// System Layout on or Fractional Widths off: each character that takes space advances by a whole /// number of points, at least one, so small type does not collapse onto itself. A zero advance (a -/// tate-chu-yoko continuation, a zero-width mark) stays zero. +/// tate-chu-yoko continuation, a zero-width mark) stays zero. Right to left, a cluster with manual +/// kerning moves by the difference the kerning makes to its rounded advance, so the rounding +/// changes the space before the next character in reading order and not the space after the one +/// before it. pub(super) fn whole_character_widths(glyphs: &mut [SGlyph]) { - for g in glyphs { - if g.adv.is_finite() && g.adv > 0.0 { - g.adv = g.adv.round().max(1.0); + let whole = |adv: f64| if adv.is_finite() && adv > 0.0 { adv.round().max(1.0) } else { adv }; + for cluster in glyphs.chunk_by_mut(|a, b| continues_cluster(Some(a), Some(b))) { + // The cluster's last glyph carries the manual kerning in its advance. + let (adv, shift) = cluster.last().map_or((0.0, 0.0), |g| (g.adv, g.kern_shift)); + let rounded_shift = Some(whole(adv) - whole(adv - shift)).filter(|s| s.is_finite()).unwrap_or(shift); + for g in cluster { + g.adv = whole(g.adv); + if shift != 0.0 { + g.kern_shift = rounded_shift; + } } } } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index eb9f14bf3a..54333a83cf 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -35,8 +35,8 @@ pub use bitmap::GlyphImage; pub use craft_fonts::{CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont}; pub use features::{EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by}; pub use fontdb::{ - FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, IcfMargins, PlatformFontFiles, StylisticSet, WantedFont, WantedFonts, - app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, + FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, IcfMargins, PlatformFontFiles, StylisticSet, WantedFont, + WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 3311a8aa44..6ecd515db3 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -34,7 +34,8 @@ pub(crate) struct SGlyph { pub dx: f64, pub dy: f64, /// Right to left: the run's manual kerning, which moves the glyph right along the baseline, - /// outside its Character Rotation. 0 otherwise. + /// outside its Character Rotation; with whole-point advances, the difference the kerning makes + /// to the cluster's rounded advance. 0 otherwise. pub kern_shift: f64, /// Outline scale (font units -> points). pub sx: f64, @@ -474,12 +475,17 @@ pub(crate) fn shape_range( type Profile = Vec<(f64, f64, f64, f64)>; type CachedProfile = (Profile, (f64, f64)); -fn outline_profile(db: &FontDb, g: &SGlyph, cache: &mut HashMap<(u32, u32), Option>>) -> Option> { - let key = (g.face.id(), g.gid); +fn outline_profile( + db: &FontDb, + face: &FontFace, + gid: u32, + cache: &mut HashMap<(u32, u32), Option>>, +) -> Option> { + let key = (face.id(), gid); cache .entry(key) .or_insert_with(|| { - let path = db.outline(&g.face, g.gid); + let path = db.outline(face, gid); let bounds = path.bounding_box(); if path.elements().is_empty() || path.elements().len() > 512 @@ -534,6 +540,65 @@ fn profile_edges(lines: &[(f64, f64, f64, f64)], y: f64, sx: f64, sy: f64, dx: f (left.is_finite() && right.is_finite()).then_some((left, right)) } +/// The ink gaps between glyph outline `a` and glyph outline `b` placed `advance` after it, at 24 +/// heights between `low` and `high` where both have ink, sorted. Each outline is placed by its +/// (scale x, scale y, offset x, offset y). +fn ink_gaps( + a: &[(f64, f64, f64, f64)], + b: &[(f64, f64, f64, f64)], + left: (f64, f64, f64, f64), + right: (f64, f64, f64, f64), + advance: f64, + low: f64, + high: f64, +) -> Vec { + let mut gaps = Vec::new(); + if !low.is_finite() || !high.is_finite() || high <= low || !advance.is_finite() { + return gaps; + } + for j in 0..24 { + let y = low + (high - low) * (f64::from(j) + 0.5) / 24.0; + if let (Some((_, ar)), Some((bl, _))) = + (profile_edges(a, y, left.0, left.1, left.2, left.3), profile_edges(b, y, right.0, right.1, right.2, right.3)) + { + let gap = advance + bl - ar; + if gap.is_finite() { + gaps.push(gap); + } + } + } + gaps.sort_by(f64::total_cmp); + gaps +} + +/// How far an Optical pair moves toward the reference gap (1 = all the way). +const OPTICAL_PULL: f64 = 0.6; +/// The narrowest ink gap an Optical correction leaves, as a fraction of the reference gap. +const OPTICAL_FLOOR: f64 = 0.3; +/// The most an Optical correction tightens and loosens a pair, in em. +const OPTICAL_MAX_TIGHTEN: f64 = 0.12; +const OPTICAL_MAX_LOOSEN: f64 = 0.06; +/// The reference gap of a face that has none of the reference pairs, in em. +const OPTICAL_FALLBACK_GAP: f64 = 0.08; + +/// The face's own spacing between two straight stems, in font units: the median ink gap of `nn`, +/// or of `HH`, then `oo`, when the face doesn't map the letter. `None` when it has none of them. +fn reference_gap(db: &FontDb, face: &FontFace, cache: &mut HashMap<(u32, u32), Option>>) -> Option { + let upem = face.units_per_em(); + ['n', 'H', 'o'].into_iter().filter(|&c| face.covers(c)).find_map(|c| { + let gid = face.glyph_for(c); + let profile = outline_profile(db, face, gid, cache)?; + let place = (1.0, 1.0, 0.0, 0.0); + let gaps = ink_gaps(&profile.0, &profile.0, place, place, face.advance(gid), profile.1.0, profile.1.1); + let gap = gaps.get(gaps.len() / 2).copied()?; + (gap.is_finite() && gap > 0.0 && gap < upem).then_some(gap) + }) +} + +/// The correction to an Optical pair's advance: the pair's median ink gap moves part of the way +/// ([`OPTICAL_PULL`]) toward `target`, the face's reference gap in the drawn size, its narrowest +/// gap stays at least [`OPTICAL_FLOOR`] of `target` where the pair allows it, and the change is +/// rounded to one font unit and limited to [`OPTICAL_MAX_TIGHTEN`] and [`OPTICAL_MAX_LOOSEN`]. #[allow(clippy::too_many_arguments)] fn profile_correction( a: &[(f64, f64, f64, f64)], @@ -541,40 +606,39 @@ fn profile_correction( left: (f64, f64, f64, f64), right: (f64, f64, f64, f64), advance: f64, + target: f64, em: f64, upem: f64, low: f64, high: f64, ) -> Option { - if !low.is_finite() || !high.is_finite() || high <= low || !em.is_finite() || em <= 0.0 || !upem.is_finite() || upem <= 0.0 { + if !em.is_finite() || em <= 0.0 || !upem.is_finite() || upem <= 0.0 || !target.is_finite() || target <= 0.0 { return None; } - let mut gaps = Vec::new(); - for j in 0..24 { - let y = low + (high - low) * (f64::from(j) + 0.5) / 24.0; - if let (Some((_, ar)), Some((bl, _))) = - (profile_edges(a, y, left.0, left.1, left.2, left.3), profile_edges(b, y, right.0, right.1, right.2, right.3)) - { - gaps.push(advance + bl - ar); - } - } - if gaps.is_empty() { - return None; - } - gaps.sort_by(f64::total_cmp); - let gap = gaps.get(gaps.len() / 2).copied().unwrap_or(0.0); + let gaps = ink_gaps(a, b, left, right, advance, low, high); + let (Some(&narrowest), Some(&gap)) = (gaps.first(), gaps.get(gaps.len() / 2)) else { return None }; + let pulled = OPTICAL_PULL * (target - gap); + let correction = pulled.max(OPTICAL_FLOOR * target - narrowest).clamp(-OPTICAL_MAX_TIGHTEN * em, OPTICAL_MAX_LOOSEN * em); let unit = em / upem; - let correction = ((0.08 * em - gap).clamp(-0.25 * em, 0.25 * em) / unit).round() * unit; - let correction = correction.clamp(-0.25 * em, 0.25 * em); + let correction = ((correction / unit).round() * unit).clamp(-OPTICAL_MAX_TIGHTEN * em, OPTICAL_MAX_LOOSEN * em); correction.is_finite().then_some(correction) } -/// Move each Optical pair toward an ink gap of 0.08 em, at 24 overlapping vertical slices. -/// The median avoids a single narrow tip deciding the entire pair. Corrections are rounded to -/// one font unit and limited to 1/4 em in either direction. Missing ink gives zero correction. +/// Does `c` take part in Optical spacing? Ideographs, kana, hangul and the fullwidth and CJK +/// punctuation forms sit on the em grid and dashes join end to end: they keep the font's spacing. +fn optical_spaces(c: char) -> bool { + !matches!(c.script(), Script::Han | Script::Hiragana | Script::Katakana | Script::Hangul | Script::Bopomofo | Script::Yi) + && !matches!(c, '\u{3000}'..='\u{303F}' | '\u{3200}'..='\u{33FF}' | '\u{FE30}'..='\u{FE4F}' | '\u{FF00}'..='\u{FFEF}') + && !matches!(c, '-' | '\u{2010}'..='\u{2015}' | '\u{2E3A}' | '\u{2E3B}' | '\u{FE58}' | '\u{FE63}' | '\u{FF0D}') +} + +/// Move each Optical pair part of the way toward the face's own stem spacing (see +/// [`reference_gap`] and [`profile_correction`]), measured at 24 overlapping vertical slices. The +/// median avoids a single narrow tip deciding the entire pair. Missing ink gives zero correction. fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range, &CharStyle)]) { let mut cache = HashMap::new(); let mut corrections: HashMap<[u64; 15], Option> = HashMap::new(); + let mut references: HashMap> = HashMap::new(); let shaped_advances: Vec = glyphs.iter().map(|g| g.adv).collect(); for i in 0..glyphs.len().saturating_sub(1) { let Some((a, b)) = glyphs.get(i).zip(glyphs.get(i + 1)) else { continue }; @@ -627,6 +691,8 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range< || right.inline.is_some() || left.ch == '\n' || right.ch == '\n' + || !optical_spaces(left.ch) + || !optical_spaces(right.ch) { continue; } @@ -659,7 +725,12 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range< left.face.upem.to_bits(), ]; let correction = *corrections.entry(key).or_insert_with(|| { - let (Some(a), Some(b)) = (outline_profile(db, left, &mut cache), outline_profile(db, right, &mut cache)) else { return None }; + let reference = *references.entry(left.face.id()).or_insert_with(|| reference_gap(db, &left.face, &mut cache)); + let reference = reference.map_or(OPTICAL_FALLBACK_GAP * em, |gap| gap * left.sx); + let (Some(a), Some(b)) = (outline_profile(db, &left.face, left.gid, &mut cache), outline_profile(db, &right.face, right.gid, &mut cache)) + else { + return None; + }; let low = (a.1.0 * left.sy + left_y).max(b.1.0 * right.sy + right_y); let high = (a.1.1 * left.sy + left_y).min(b.1.1 * right.sy + right_y); profile_correction( @@ -668,6 +739,7 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range< (left.sx, left.sy, left_x, left_y), (right.sx, right.sy, right_x, right_y), advance, + reference, em, left.face.upem, low, @@ -742,6 +814,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { font_height_reference, no_break, language, + glyph_alternate, } = a; *font_family == b.font_family && *font_style == b.font_style @@ -760,6 +833,10 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { && *font_height_reference == b.font_height_reference && *no_break == b.no_break && *language == b.language + // A choice applies to the first character of its source run. Even equal choices on + // neighboring runs must shape separately so ligatures cannot absorb either character. + && glyph_alternate.is_none() + && b.glyph_alternate.is_none() && ligatures_suppressed_by(*tracking) == ligatures_suppressed_by(b.tracking) } @@ -1135,15 +1212,75 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe if !inside_clusters.is_empty() { return shape_apart(inside_clusters, out); } + // A run's chosen character that the font joins with the characters after it in the run (an f + // with a chosen glyph in a `fi` ligature) is shaped apart from them, so the choice is drawn. + // A character that starts a longer grapheme (a letter with combining marks, a Hangul syllable + // of jamo) stays whole. + let ligated: Vec = runs + .get(source_runs.clone()) + .unwrap_or_default() + .iter() + .filter(|(r, s)| { + let ch = first_char(r.start); + s.glyph_alternate.as_ref().is_some_and(|c| face.draws(c, ch)) && !upper && s.digits.map(ch) == ch && range.contains(&r.start) + }) + .map(|(r, _)| { + let grapheme = text.get(r.start..).and_then(|s| s.graphemes(true).next()).map_or(0, str::len); + (r.start + first_char(r.start).len_utf8(), r.start + grapheme, r.end) + }) + .filter(|&(b, grapheme_end, end)| b == grapheme_end && b < end && b < range.end && cluster_starts.binary_search(&b).is_err()) + .map(|(b, ..)| b) + .collect(); + if !ligated.is_empty() { + return shape_apart(ligated, out); + } let n = raw.len(); + // Cluster end: the next larger cluster value in the segment, else the segment end. + let cluster_end = |cl: usize| cluster_starts.get(cluster_starts.partition_point(|&c| c <= cl)).copied().unwrap_or(range.end); + // A glyph chosen for the run's first character replaces the one glyph shaped for it alone, + // drawn as typed (not All Caps, Small Caps or another numeral system), in the face the choice + // names. + let chosen_at = |gi: usize| { + let cl = raw[gi].1 as usize; + let (run, gst) = run_at(cl); + let ch = first_char(cl); + let last_in_cluster = gi + 1 == n || raw[gi + 1].1 as usize != cl; + let alone = last_in_cluster && (gi == 0 || raw[gi - 1].1 as usize != cl) && cluster_end(cl).saturating_sub(cl) == ch.len_utf8(); + gst.glyph_alternate + .as_ref() + .filter(|c| alone && !upper && gst.digits.map(ch) == ch && runs.get(run).is_some_and(|(r, _)| r.start == cl) && face.draws(c, ch)) + }; + // The font's positioning (pair kerning, mark placement) was applied to the default glyph, not + // to the chosen one: a character drawn with another glyph is shaped apart from its neighbors. + let mut chosen_apart: Vec = (0..n) + .filter(|&gi| chosen_at(gi).is_some_and(|c| c.gid != raw[gi].0)) + .flat_map(|gi| { + let cl = raw[gi].1 as usize; + [cl, cl + first_char(cl).len_utf8()] + }) + .filter(|&b| b > range.start && b < range.end) + .collect(); + if !chosen_apart.is_empty() { + chosen_apart.sort_unstable(); + chosen_apart.dedup(); + return shape_apart(chosen_apart, out); + } for (gi, &(gid, cl, xa, xo, yo)) in raw.iter().enumerate() { let cl = cl as usize; let (run, gst) = run_at(cl); - // Cluster end: the next larger cluster value in the segment, else the segment end. - let end = cluster_starts.get(cluster_starts.partition_point(|&c| c <= cl)).copied().unwrap_or(range.end); + let end = cluster_end(cl); let last_in_cluster = gi + 1 == n || raw[gi + 1].1 as usize != cl; let ch = first_char(cl); let mut adv = xa as f64 * k * hs; + // The chosen glyph takes its own advance. + let chosen = chosen_at(gi); + let gid = match chosen { + Some(c) => { + adv += (face.advance(c.gid) - face.advance(gid)) * k * hs; + c.gid + } + None => gid, + }; let mut kern_shift = 0.0; if ch == SOFT_HYPHEN || ch == '\u{2028}' { adv = 0.0; @@ -1204,16 +1341,38 @@ mod optical_tests { #[test] fn optical_side_profiles_tighten_loosen_and_stay_bounded() { + // 100 pt in a 1000-unit font: one font unit is 0.1 pt; the reference gap is 8 pt. let a = box_profile(0.0, 80.0); let b = box_profile(0.0, 20.0); let place = (1.0, 1.0, 0.0, 0.0); - let tight = profile_correction(&a, &b, place, place, 120.0, 100.0, 1000.0, 0.0, 100.0).unwrap(); - let loose = profile_correction(&a, &b, place, place, 60.0, 100.0, 1000.0, 0.0, 100.0).unwrap(); - assert_eq!(tight, -25.0); - assert_eq!(loose, 25.0); - assert_eq!(profile_correction(&a, &b, place, place, 88.0, 100.0, 1000.0, 0.0, 100.0), Some(0.0)); - assert_eq!(profile_correction(&a, &b, place, place, 120.0, 100.0, 1000.0, 0.0, 100.0), Some(tight)); - assert_eq!(profile_correction(&a, &b, place, place, 120.0, 100.0, 1000.0, 100.0, 100.0), None); - assert_eq!(profile_correction(&[], &b, place, place, 120.0, 100.0, 1000.0, 0.0, 100.0), None); + let correct = |a: &[(f64, f64, f64, f64)], advance: f64, target: f64| { + profile_correction(a, &b, place, place, advance, target, 100.0, 1000.0, 0.0, 100.0) + }; + assert_eq!(correct(&a, 120.0, 8.0), Some(-12.0), "a 40 pt gap tightens by at most 0.12 em"); + assert_eq!(correct(&a, 60.0, 8.0), Some(6.0), "overlapping ink loosens by at most 0.06 em"); + assert_eq!(correct(&a, 88.0, 8.0), Some(0.0), "the reference gap itself is left alone"); + assert!((correct(&a, 98.0, 8.0).unwrap() - -6.0).abs() < 1e-9, "a pair moves 0.6 of the way toward the reference"); + assert!((correct(&a, 84.0, 8.0).unwrap() - 2.4).abs() < 1e-9, "a tight pair opens 0.6 of the way"); + assert_eq!(correct(&a, 88.0, 0.0), None); + assert_eq!(profile_correction(&a, &b, place, place, 120.0, 8.0, 100.0, 1000.0, 100.0, 100.0), None); + assert_eq!(profile_correction(&[], &b, place, place, 120.0, 8.0, 100.0, 1000.0, 0.0, 100.0), None); + + // A right side slanting from x 60 at the bottom to x 100 at the top: the median gap is + // near the 20 pt reference, but the top nearly touches. The floor keeps 0.3 of it. + let slanted = vec![(0.0, 0.0, 0.0, 100.0), (60.0, 0.0, 100.0, 100.0)]; + let correction = correct(&slanted, 100.0, 20.0).unwrap(); + let narrowest = ink_gaps(&slanted, &b, place, place, 100.0, 0.0, 100.0)[0]; + assert!(correction > 1.0, "the narrowest gap opens: {correction}"); + assert!(narrowest + correction >= 0.3 * 20.0 - 0.1, "{narrowest} + {correction}"); + } + + #[test] + fn ideographs_kana_fullwidth_forms_and_dashes_keep_the_font_spacing() { + for c in ['日', 'カ', 'な', '한', '、', 'W', '-', '\u{2014}', '\u{FF0D}'] { + assert!(!optical_spaces(c), "{c:?}"); + } + for c in ['A', 'v', '7', '.', 'Ω', 'Ж', 'א', 'ب', 'क'] { + assert!(optical_spaces(c), "{c:?}"); + } } } diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 2a6072762c..085bd6f0de 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -489,6 +489,130 @@ pub fn lam_alef_font(feature: &[u8; 4]) -> Option> { Some(builder.build()) } +/// The family of [`alternates_font`] with an `aalt` feature, and without one. +pub fn alternates_family(aalt: bool) -> &'static str { + if aalt { "Alttest Sans" } else { "Alttest Sans Noaalt" } +} + +/// Four glyphs of the bundled Source Sans 3 Regular that its `cmap` maps no character to, the +/// lowest ids first: the unencoded alternates of [`alternates_font`]. `None` when there are not +/// four. +pub fn unencoded_glyphs() -> Option<[u32; 4]> { + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let mapped: std::collections::HashSet = font.charmap().mappings().map(|(_, g)| g.to_u32()).collect(); + let glyphs = u32::from(font.maxp().ok()?.num_glyphs()); + let found: Vec = (1..glyphs).filter(|g| !mapped.contains(g)).take(4).collect(); + found.try_into().ok() +} + +/// The family of [`crowded_alternates_font`]. +pub const CROWDED_ALTERNATES_FAMILY: &str = "Crowdtest Sans"; + +/// The bundled Source Sans 3 Regular, its `cmap` kept, with a `GSUB` table whose 17 `cv01` feature +/// records each list a single substitution of `a` by `c` 256 times, followed by a `salt` record +/// whose single substitution gives `b`. Family [`CROWDED_ALTERNATES_FAMILY`]. `None` when it can't +/// be built. +pub fn crowded_alternates_font() -> Option> { + use write_fonts::tables::gsub::{Gsub, SingleSubst, SingleSubstFormat2, SubstitutionLookup, SubstitutionLookupList}; + use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord}; + use write_fonts::types::GlyphId16; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let family = CROWDED_ALTERNATES_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Crowdtest Sans Regular"), (5, "Version 1.000"), (6, "CrowdtestSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?)); + let a = gid('a')?; + let single = |to: GlyphId16| { + SubstitutionLookup::Single(Lookup::new( + Default::default(), + vec![SingleSubst::from(SingleSubstFormat2::new(CoverageFormat1::new(vec![a]).into(), vec![to]))], + )) + }; + let lookups = SubstitutionLookupList::new(vec![single(gid('c')?), single(gid('b')?)]); + let mut records: Vec = (0..17).map(|_| FeatureRecord::new(Tag::new(b"cv01"), Feature::new(None, vec![0; 256]))).collect(); + records.push(FeatureRecord::new(Tag::new(b"salt"), Feature::new(None, vec![1]))); + let indices = (0..records.len() as u16).collect(); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(indices)), vec![]))]); + builder.add_table(&Gsub::new(scripts, FeatureList::new(records), lookups)).ok()?; + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + +/// The bundled Source Sans 3 Regular, its `cmap` kept, with a `GSUB` table of alternates for `a` +/// and nothing else. With [`unencoded_glyphs`] `[u1, u2, u3, u4]`: `aalt` (alternate +/// substitution) lists a, u1 and b; `cv01` (single substitution) gives c; `salt` (single) gives b; +/// `smcp` (single) gives d; `ss01` (single, a glyph-id delta) gives u2; `ss02` (single, in an +/// extension lookup) gives u4; and `swsh` (alternate substitution) lists u3 and u1. Without `aalt` +/// the font has the others only. Family [`alternates_family`]. `None` when it can't be built. +pub fn alternates_font(aalt: bool) -> Option> { + use write_fonts::tables::gsub::{ + AlternateSet, AlternateSubstFormat1, ExtensionSubstFormat1, ExtensionSubtable, Gsub, SingleSubst, SingleSubstFormat1, SingleSubstFormat2, + SubstitutionLookup, SubstitutionLookupList, + }; + use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord}; + use write_fonts::types::GlyphId16; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let family = alternates_family(aalt); + let full = format!("{family} Regular"); + let postscript = format!("{}-Regular", family.replace(' ', "")); + let name = name_table(&[(1, family), (2, "Regular"), (4, &full), (5, "Version 1.000"), (6, &postscript)])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + let id = |g: u32| Some(GlyphId16::new(u16::try_from(g).ok()?)); + let gid = |c| id(charmap.map(c)?.to_u32()); + let [u1, u2, u3, u4] = unencoded_glyphs()?.map(id); + let (u1, u2, u3, u4, a) = (u1?, u2?, u3?, u4?, gid('a')?); + let cover = || CoverageFormat1::new(vec![a]); + let single = |to: GlyphId16| SingleSubst::from(SingleSubstFormat2::new(cover().into(), vec![to])); + let lookup = |subtable: SingleSubst| SubstitutionLookup::Single(Lookup::new(Default::default(), vec![subtable])); + let alternates = |set: Vec| { + SubstitutionLookup::Alternate(Lookup::new(Default::default(), vec![AlternateSubstFormat1::new(cover().into(), vec![AlternateSet::new(set)])])) + }; + let delta = i16::try_from(i32::from(u2.to_u16()) - i32::from(a.to_u16())).ok()?; + let extension = ExtensionSubtable::Single(ExtensionSubstFormat1::new(1, single(u4))); + // Lookups: 0 aalt, 1 cv01, 2 salt, 3 smcp, 4 ss01, 5 ss02, 6 swsh. + let lookups = SubstitutionLookupList::new(vec![ + alternates(vec![a, u1, gid('b')?]), + lookup(single(gid('c')?)), + lookup(single(gid('b')?)), + lookup(single(gid('d')?)), + lookup(SingleSubst::from(SingleSubstFormat1::new(cover().into(), delta))), + SubstitutionLookup::Extension(Lookup::new(Default::default(), vec![extension])), + alternates(vec![u3, u1]), + ]); + // Features sorted by tag, as OpenType requires. + let tags: [&[u8; 4]; 7] = [b"aalt", b"cv01", b"salt", b"smcp", b"ss01", b"ss02", b"swsh"]; + let records: Vec = tags + .iter() + .zip(0u16..) + .filter(|(t, _)| aalt || **t != b"aalt") + .map(|(t, i)| FeatureRecord::new(Tag::new(t), Feature::new(None, vec![i]))) + .collect(); + let indices = (0..records.len() as u16).collect(); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(indices)), vec![]))]); + builder.add_table(&Gsub::new(scripts, FeatureList::new(records), lookups)).ok()?; + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`ligature_caret_font`]. pub const LIGATURE_CARET_FAMILY: &str = "Carettest Sans"; @@ -706,16 +830,30 @@ pub const RIGHT_TO_LEFT_OPTICAL_FAMILY: &str = "Right-to-left Profile Sans"; /// Two Hebrew characters mapped to the bundled Source Sans 3 A and V outlines. pub fn right_to_left_optical_font() -> Option> { + remapped_source_sans(RIGHT_TO_LEFT_OPTICAL_FAMILY, "RtlProfileSans-Regular", &[('א', 'A'), ('ב', 'V')]) +} + +/// The family of [`ideograph_optical_font`]. +pub const IDEOGRAPH_OPTICAL_FAMILY: &str = "Ideograph Profile Sans"; + +/// Two ideographs, two kana and a fullwidth letter mapped to the bundled Source Sans 3 A, V, T, o +/// and W outlines: shapes Optical would space, on characters that keep the font's spacing. +pub fn ideograph_optical_font() -> Option> { + remapped_source_sans(IDEOGRAPH_OPTICAL_FAMILY, "IdeographProfileSans-Regular", &[('日', 'A'), ('本', 'V'), ('カ', 'T'), ('な', 'o'), ('W', 'W')]) +} + +/// A face named `family` that maps only the characters of `mapping` to the bundled Source Sans 3 +/// outlines of their letters, with no `GPOS` or `kern` table. +fn remapped_source_sans(family: &str, postscript: &str, mapping: &[(char, char)]) -> Option> { use write_fonts::tables::cmap::Cmap; const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); let font = skrifa::FontRef::new(BASE).ok()?; let charmap = font.charmap(); - let mapping = [('א', 'A'), ('ב', 'V')]; - let mappings = mapping.into_iter().map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); + let mappings = mapping.iter().map(|&(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); let cmap = Cmap::from_mappings(mappings.collect::>>()?).ok()?; - let family = RIGHT_TO_LEFT_OPTICAL_FAMILY; - let name = name_table(&[(1, family), (2, "Regular"), (4, "Right-to-left Profile Sans Regular"), (6, "RtlProfileSans-Regular")])?; + let full = format!("{family} Regular"); + let name = name_table(&[(1, family), (2, "Regular"), (4, full.as_str()), (6, postscript)])?; let mut builder = FontBuilder::new(); builder.add_table(&cmap).ok()?; builder.add_raw(Tag::new(b"name"), name); diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 002e4b921d..a5d8b50631 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -3,6 +3,7 @@ use kurbo::{Affine, Shape}; use vectorcraft_doc::{CharStyle, Justify, TextKind, TextRun}; use vectorcraft_geom::PathData; +mod alternates; mod axes; mod bidi; mod bitmaps; diff --git a/crates/text/src/tests/alternates.rs b/crates/text/src/tests/alternates.rs new file mode 100644 index 0000000000..cc70780eb3 --- /dev/null +++ b/crates/text/src/tests/alternates.rs @@ -0,0 +1,191 @@ +//! A face's alternate glyphs for a character (Glyphs panel › Show › Alternates for Current +//! Selection) and a glyph chosen for one character: read from a `GSUB` table built in code, set by +//! layout, kept by text edits. + +use kurbo::Point; +use vectorcraft_doc::{CharStyle, GlyphChoice, TextRun}; + +use crate::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; +use crate::*; + +fn db() -> FontDb { + let db = FontDb::with_font_dirs(vec![]); + db.add_font(alternates_font(true).expect("the test font builds")); + db.add_font(alternates_font(false).expect("the test font builds")); + db +} + +fn style(aalt: bool) -> CharStyle { + CharStyle { font_family: alternates_family(aalt).into(), size: 100.0, ..CharStyle::default() } +} + +#[test] +fn alternates_come_in_feature_order_once_each() { + let db = db(); + let [u1, u2, u3, u4] = unencoded_glyphs().expect("unencoded glyphs"); + let face = db.face(alternates_family(true), "Regular").expect("the test face"); + let g = |c| face.glyph_for(c); + let listed: Vec<(u32, [u8; 4])> = face.alternates('a').into_iter().map(|a| (a.gid, a.feature)).collect(); + assert_eq!( + listed, + [(g('a'), *b"aalt"), (u1, *b"aalt"), (g('b'), *b"aalt"), (u2, *b"ss01"), (u4, *b"ss02"), (u3, *b"swsh"), (g('c'), *b"cv01")], + "aalt first, then salt (b again, left out), ss01, ss02 (an extension lookup), swsh (u1 again, left out), cv01; smcp is not read" + ); + assert!(face.alternates('b').is_empty(), "b has no alternates"); + assert!(face.alternates('\u{E000}').is_empty(), "a character the face does not map"); + let plain = db.face(alternates_family(false), "Regular").expect("the test face"); + let listed: Vec = plain.alternates('a').into_iter().map(|a| a.gid).collect(); + assert_eq!(listed, [g('b'), u2, u4, u3, u1, g('c')], "without aalt the default glyph is not listed"); + let bundled = db.face(FALLBACK_FAMILY, "Regular").expect("the bundled face"); + assert!(bundled.alternates('a').iter().all(|a| a.gid < bundled.glyph_count())); +} + +/// The cap on lookups read in all leaves out the lowest ranked features: `salt` is read even when +/// the `cv01` records before it list more lookups than the cap. +#[test] +fn the_lookup_cap_keeps_the_higher_ranked_features() { + use crate::test_fonts::{CROWDED_ALTERNATES_FAMILY, crowded_alternates_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(crowded_alternates_font().expect("the test font builds")); + let face = db.face(CROWDED_ALTERNATES_FAMILY, "Regular").expect("the test face"); + let listed: Vec<(u32, [u8; 4])> = face.alternates('a').into_iter().map(|a| (a.gid, a.feature)).collect(); + assert_eq!(listed, [(face.glyph_for('b'), *b"salt"), (face.glyph_for('c'), *b"cv01")]); +} + +#[test] +fn a_chosen_glyph_is_drawn_for_its_character_only() { + let db = db(); + let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let face = db.face(alternates_family(true), "Regular").expect("the test face"); + let choice = face.choice('a', u1); + assert_eq!(choice, GlyphChoice { ch: 'a', gid: u1, font: "AlttestSans-Regular".into(), version: "Version 1.000".into() }); + let chosen = CharStyle { glyph_alternate: Some(choice.clone()), ..style(true) }; + let runs = |first: CharStyle| { + vec![TextRun { text: "aa".into(), style: first, inline: None }, TextRun { text: "ab".into(), style: style(true), inline: None }] + }; + let set = |runs: Vec| { + let mut t = TextObject::point(Point::ZERO, "", style(true)); + t.runs = runs; + layout(&db, &t).glyphs.into_iter().map(|g| (g.gid, g.advance)).collect::>() + }; + let a = face.glyph_for('a'); + let k = 100.0 / face.units_per_em(); + let drawn = set(runs(chosen.clone())); + let gids: Vec = drawn.iter().map(|g| g.0).collect(); + assert_eq!(gids, [u1, a, a, face.glyph_for('b')], "the run's first character only"); + assert!((drawn[0].1 - face.advance(u1) * k).abs() < 1e-6, "it takes the chosen glyph's advance: {drawn:?}"); + // A choice that does not hold for this text and face draws the default glyph. + let other = |f: &dyn Fn(&mut GlyphChoice)| { + let mut c = choice.clone(); + f(&mut c); + set(runs(CharStyle { glyph_alternate: Some(c), ..style(true) }))[0].0 + }; + assert_eq!(other(&|c| c.ch = 'b'), a, "a choice for another character"); + assert_eq!(other(&|c| c.version = "Version 2.000".into()), a, "another version of the font"); + assert_eq!(other(&|c| c.font = "OtherSans-Regular".into()), a, "another font"); + assert_eq!(other(&|c| c.gid = face.glyph_count()), a, "a glyph id past the face's glyphs"); + let elsewhere = CharStyle { font_family: alternates_family(false).into(), glyph_alternate: Some(choice.clone()), ..style(false) }; + assert_eq!(set(runs(elsewhere))[0].0, a, "the same glyph id in another face"); + let caps = CharStyle { all_caps: true, ..chosen.clone() }; + assert_eq!(set(runs(caps))[0].0, face.glyph_for('A'), "All Caps draws the capital"); +} + +#[test] +fn adjacent_characters_with_the_same_choice_keep_both_glyphs() { + let db = db(); + let face = db.face(alternates_family(true), "Regular").expect("the test face"); + let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let style = CharStyle { glyph_alternate: Some(face.choice('f', u1)), ..style(true) }; + let mut text = TextObject::point(Point::ZERO, "", style.clone()); + text.runs = vec![TextRun { text: "f".into(), style: style.clone(), inline: None }, TextRun { text: "f".into(), style, inline: None }]; + let glyphs = layout(&db, &text).glyphs; + assert_eq!(glyphs.iter().map(|g| g.gid).collect::>(), [u1, u1], "each chosen f draws independently"); +} + +/// A run "fi" whose f has a chosen glyph draws that glyph and the i, not the font's fi ligature. +#[test] +fn a_chosen_character_is_not_taken_into_a_ligature_in_its_run() { + use crate::test_fonts::{LIGATURE_CARET_FAMILY, ligature_caret_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(ligature_caret_font(None).expect("the test font builds")); + let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test face"); + let plain = CharStyle { font_family: LIGATURE_CARET_FAMILY.into(), size: 100.0, ..CharStyle::default() }; + let gids = |st: CharStyle| layout(&db, &TextObject::point(Point::ZERO, "fi", st)).glyphs.into_iter().map(|g| g.gid).collect::>(); + assert_eq!(gids(plain.clone()).len(), 1, "without a choice the font joins f and i"); + let i = face.glyph_for('i'); + let chosen = CharStyle { glyph_alternate: Some(face.choice('f', i)), ..plain }; + assert_eq!(gids(chosen), [i, i], "the f draws the chosen glyph and the i stays apart"); +} + +/// A run "f" + combining acute + "i" whose f has a chosen glyph is not split between the f and its +/// mark: the f and the mark stay one cluster, shaped as they are without a choice. +#[test] +fn a_chosen_character_that_starts_a_longer_grapheme_is_not_split_from_it() { + let db = FontDb::with_font_dirs(vec![]); + let face = db.face(FALLBACK_FAMILY, "Regular").expect("the bundled face"); + let plain = CharStyle { font_family: FALLBACK_FAMILY.into(), size: 100.0, ..CharStyle::default() }; + let glyphs = + |st: CharStyle| layout(&db, &TextObject::point(Point::ZERO, "f\u{301}i", st)).glyphs.into_iter().map(|g| (g.gid, g.byte)).collect::>(); + let shaped = glyphs(plain.clone()); + assert!(shaped.iter().filter(|g| g.1 == 0).count() >= 2, "the mark is shaped in the f's cluster: {shaped:?}"); + let chosen = CharStyle { glyph_alternate: Some(face.choice('f', face.glyph_for('i'))), ..plain }; + assert_eq!(glyphs(chosen), shaped, "the f and its mark are shaped together, as without a choice"); +} + +/// The font's pair kerning was looked up for the default glyph: a character drawn with another +/// glyph takes no part in it, before or after it. +#[test] +fn a_chosen_glyph_takes_no_kerning_found_for_the_default_glyph() { + use crate::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(pair_kerning_font().expect("the test font builds")); + let face = db.face(PAIR_KERNING_FAMILY, "Regular").expect("the test face"); + let st = CharStyle { font_family: PAIR_KERNING_FAMILY.into(), size: 100.0, ..CharStyle::default() }; + // Each glyph's id, advance and how far it is drawn from its pen position, in one run "AV" + // whose A is drawn with the glyph of `with` (the choice applies to the run's first character). + let set = |with: char| { + let style = CharStyle { glyph_alternate: Some(face.choice('A', face.glyph_for(with))), ..st.clone() }; + let t = TextObject::point(Point::ZERO, "AV", style); + layout(&db, &t).glyphs.into_iter().map(|g| (g.gid, g.advance, g.xf.as_coeffs()[4] - g.origin.x)).collect::>() + }; + let k = 100.0 / face.units_per_em(); + let plain = |c: char| face.advance(face.glyph_for(c)) * k; + let chosen = set('B'); + assert_eq!(chosen.iter().map(|g| g.0).collect::>(), [face.glyph_for('B'), face.glyph_for('V')]); + assert!((chosen[0].1 - plain('B')).abs() < 1e-6, "the chosen glyph keeps none of the A-V pair's advance: {chosen:?}"); + assert!(chosen[1].2.abs() < 1e-6, "the V after it is not moved by the A-V pair: {chosen:?}"); + // The default glyph chosen for the A keeps the pair: 6 pt off its advance, the V 10 pt left. + let same = set('A'); + assert!((same[0].1 - (plain('A') - 6.0)).abs() < 1e-6 && (same[1].2 + 10.0).abs() < 1e-6, "{same:?}"); +} + +#[test] +fn edits_keep_a_choice_on_its_character() { + let face = db().face(alternates_family(true), "Regular").expect("the test face"); + let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let choice = face.choice('a', u1); + let mut runs = vec![TextRun { text: "xaay".into(), style: style(true), inline: None }]; + edit::style_range(&mut runs, 1, 2, |st| st.glyph_alternate = Some(choice.clone())); + let texts = |runs: &[TextRun]| runs.iter().map(|r| (r.text.clone(), r.style.glyph_alternate.is_some())).collect::>(); + assert_eq!(texts(&runs), [("x".into(), false), ("a".into(), true), ("ay".into(), false)]); + // The second a takes the same choice: a run of its own, not merged with the first. + edit::style_range(&mut runs, 2, 3, |st| st.glyph_alternate = Some(choice.clone())); + assert_eq!(texts(&runs), [("x".into(), false), ("a".into(), true), ("a".into(), true), ("y".into(), false)]); + // Typed text takes the default glyph, also an a typed after a chosen one. + let caret = edit::replace_range(&mut runs, 2, 2, "a"); + assert_eq!(caret, 3); + assert_eq!(texts(&runs), [("x".into(), false), ("a".into(), true), ("a".into(), false), ("a".into(), true), ("y".into(), false)]); + // Styling part of a run keeps the choice on its first character only. + let mut runs = vec![TextRun { text: "ab".into(), style: CharStyle { glyph_alternate: Some(choice.clone()), ..style(true) }, inline: None }]; + edit::style_range(&mut runs, 1, 2, |st| st.underline = true); + assert_eq!(texts(&runs), [("a".into(), true), ("b".into(), false)]); + assert_eq!(texts(&edit::slice_runs(&runs, 0, 2)), [("a".into(), true), ("b".into(), false)]); + // Deleting the character drops its choice from the run that is left. + let mut runs = vec![TextRun { text: "ab".into(), style: CharStyle { glyph_alternate: Some(choice.clone()), ..style(true) }, inline: None }]; + edit::replace_range(&mut runs, 0, 1, ""); + assert_eq!(texts(&runs), [("b".into(), false)]); + let mut runs = vec![TextRun { text: "ab".into(), style: CharStyle { glyph_alternate: Some(choice), ..style(true) }, inline: None }]; + assert_eq!(texts(&edit::slice_runs(&runs, 1, 2)), [("b".into(), false)], "a copy from inside the run"); + edit::normalize(&mut runs); + assert_eq!(texts(&runs), [("ab".into(), true)]); +} diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 7ab8d9029c..d4068eb5da 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -308,6 +308,36 @@ fn a_background_scan_serves_the_first_lookup() { assert_eq!(db.load_system_fonts(), 2, "a rescan catalogs the two faces again"); } +/// The menu bar's Type › Font is built in the window's first frame, so its family list doesn't wait +/// for the scan of the installed fonts: a large library would hold the first frame past the +/// first-frame watchdog, and the app would never show its window (#5483). Once the scan ends, the +/// list has the installed fonts. +#[cfg(unix)] +#[test] +fn the_menu_family_list_now_does_not_wait_for_the_scan() { + let dir = font_dir("held-scan"); + // A named pipe with a font's name: the scan opens it and waits there until something writes. + let pipe = dir.join("Held.ttf"); + assert!(std::process::Command::new("mkfifo").arg(&pipe).status().unwrap().success()); + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![dir]))); + let generation = db.generation(); + db.scan_in_background(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send((db.installed_fonts_ready(), db.menu_family_list_now())); + }); + let listed = rx.recv_timeout(std::time::Duration::from_secs(10)); + // Let the scan go on whatever happened: the pipe is opened and closed with nothing written. + drop(std::fs::OpenOptions::new().write(true).open(&pipe).unwrap()); + let (ready, listed) = listed.expect("the list comes while the scan is held"); + assert!(!ready && !has(&listed, FAMILY), "before the scan ends, only the fonts already loaded"); + // Waits for the scan. + assert!(has(&db.menu_family_list(), FAMILY)); + assert!(db.installed_fonts_ready()); + assert_ne!(db.generation(), generation, "a menu built from the short list is built again"); + assert!(has(&db.menu_family_list_now(), FAMILY)); +} + #[test] fn the_family_list_is_shared_until_fonts_change() { let db = FontDb::with_font_dirs(vec![]); diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 092ed4c09f..f92ce67a6a 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -98,6 +98,36 @@ fn rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order() { } } +#[test] +fn rtl_manual_kerning_with_whole_point_widths_keeps_the_previous_character_in_place() { + // Reading order: alef (bytes 0..2), bet (2..4), gimel (4..6); bet carries the kerning, which + // is a fraction of a point. + for (system_layout, fractional_widths) in [(true, true), (false, false)] { + for value in [3.0, 4.0, 6.0, 7.0] { + let kerned = |value: f64| { + let mut t = TextObject::point(Point::ZERO, "אבג", CharStyle { size: 100.0, ..CharStyle::default() }); + t.system_layout = system_layout; + t.fractional_widths = fractional_widths; + edit::style_range(&mut t.runs, 2, 4, |s| s.kerning = Some(value)); + layout(db(), &t) + }; + let ink = |lay: &TextLayout, byte: usize| { + let g = lay.glyphs.iter().find(|g| g.byte == byte).unwrap(); + assert!(g.rtl && g.gid != 0, "byte {byte} is set right to left with a glyph of its own"); + (g.xf * Point::ZERO).x + }; + let (plain, spaced) = (kerned(0.0), kerned(value)); + let gap = |lay: &TextLayout, right: usize, left: usize| ink(lay, right) - ink(lay, left); + assert!( + (gap(&spaced, 0, 2) - gap(&plain, 0, 2)).abs() < 1e-9, + "alef, before bet in reading order, keeps its place (kerning {value}, System Layout {system_layout})" + ); + let wider = gap(&spaced, 2, 4) - gap(&plain, 2, 4); + assert!((wider - wider.round()).abs() < 1e-9, "bet moves from gimel by whole points: {wider} (kerning {value})"); + } + } +} + #[test] fn rtl_manual_kerning_on_a_rotated_character_moves_it_along_the_baseline() { // Reading order: alef (bytes 0..2), bet (2..4), gimel (4..6); bet is turned 90 degrees and @@ -172,6 +202,10 @@ fn optical_pair_after_separate_combining_mark_uses_base_outline() { #[test] fn optical_pair_after_rtl_separate_mark_uses_base_outline() { + if db().face("Noto Sans Arabic", "Regular").is_none_or(|f| f.family != "Noto Sans Arabic") { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + } let st = CharStyle { font_family: "Noto Sans Arabic".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; let shaped = |text: &str, manual: bool| { let mut style = st.clone(); @@ -195,6 +229,54 @@ fn optical_pair_after_rtl_separate_mark_uses_base_outline() { assert!((correction - plain_correction).abs() < 0.01, "the marked cluster uses the base outline"); } +/// Optical spaces pairs by the face's own stem spacing (#5336): straight pairs like `nn` keep the +/// font's spacing, diagonal pairs close up, and a line of ordinary text is no narrower than it +/// is with the font's spacing and no kerning. +#[test] +fn optical_keeps_the_fonts_stem_spacing_and_closes_diagonal_pairs() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let advances = |text: &str, kerning: Option| { + layout(db(), &TextObject::point(Point::ZERO, text, CharStyle { kerning, ..st.clone() })).glyphs.iter().map(|g| g.advance).collect::>() + }; + let width = |text: &str, kerning: Option| advances(text, kerning).iter().sum::(); + let (optical, zero) = (advances("nn", None), advances("nn", Some(0.0))); + assert!((optical[0] - zero[0]).abs() <= 0.11, "nn, the reference, keeps the font's spacing: {optical:?} {zero:?}"); + for pair in ["HH", "ll", "nl"] { + let (optical, zero) = (advances(pair, None), advances(pair, Some(0.0))); + assert!((optical[0] - zero[0]).abs() <= 3.0, "{pair} stays within 0.03 em of the font's spacing: {optical:?} {zero:?}"); + } + for pair in ["AV", "To", "Yo"] { + let (optical, zero) = (advances(pair, None), advances(pair, Some(0.0))); + assert!(optical[0] < zero[0] - 1.0, "{pair} closes up: {optical:?} {zero:?}"); + assert!(optical[0] >= zero[0] - 12.0 - 0.01, "{pair} tightens by at most 0.12 em: {optical:?} {zero:?}"); + } + for text in ["minimum", "Hamburgefonstiv", "illumination"] { + let (optical, zero) = (width(text, None), width(text, Some(0.0))); + assert!(optical >= zero * 0.97, "{text} is not squeezed: {optical} against {zero}"); + } +} + +/// Ideographs, kana and fullwidth forms keep the font's spacing under Optical, even where their +/// outlines would be spaced (the test face draws them with Latin outlines). +#[test] +fn optical_leaves_ideographs_kana_and_fullwidth_forms_alone() { + use crate::test_fonts::{IDEOGRAPH_OPTICAL_FAMILY, ideograph_optical_font}; + + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(ideograph_optical_font().unwrap()), 1); + let st = CharStyle { font_family: IDEOGRAPH_OPTICAL_FAMILY.into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let advances = |kerning: Option| { + layout(&db, &TextObject::point(Point::ZERO, "日本カなW日", CharStyle { kerning, ..st.clone() })) + .glyphs + .iter() + .map(|g| g.advance) + .collect::>() + }; + let (optical, zero) = (advances(None), advances(Some(0.0))); + assert_eq!(optical.len(), 6); + assert_eq!(optical, zero, "no ideograph, kana or fullwidth pair is corrected"); +} + #[test] fn recurring_optical_pairs_have_equal_corrections() { let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index 9c9d616815..c0a2b5e13f 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -343,6 +343,41 @@ fn tracking_spaces_upright_marks_without_moving_them_off_the_centre_line() { assert!((step - 24.0).abs() < 1e-6, "one em plus 200/1000 em of tracking: {step}"); } +/// Baseline shift moves an upright glyph across the column, as it moves a letter lying on its +/// side, at any Character Rotation, and leaves its neighbors where they are. The glyph turns about +/// its shifted pen position (`xf * pivot`), and `xf * unturned` places the shifted glyph without +/// its rotation. +#[test] +fn baseline_shift_moves_an_upright_glyph_across_the_column() { + let at = |byte: usize, rotation: f64, shift: f64| { + let mut t = vertical("§l§"); + edit::style_range(&mut t.runs, byte, byte + "§l§"[byte..].chars().next().map_or(1, char::len_utf8), |s| { + s.rotation = rotation; + s.baseline_shift = shift; + }); + layout(FontDb::global(), &t) + }; + let centre = |l: &TextLayout, byte: usize| l.glyphs.iter().find(|g| g.byte == byte).map(|g| g.outline.bounding_box().center()).unwrap(); + // The letter lying on its side moves across the column by the shift. + let across = centre(&at(2, 0.0, 10.0), 2) - centre(&at(2, 0.0, 0.0), 2); + assert!((across.x.abs() - 10.0).abs() < 1e-6 && across.y.abs() < 1e-6, "{across:?}"); + for rotation in [0.0, 30.0, 90.0, -90.0] { + let (plain, shifted) = (at(3, rotation, 0.0), at(3, rotation, 10.0)); + let moved = centre(&shifted, 3) - centre(&plain, 3); + assert!((moved - across).hypot() < 1e-6, "{rotation}°: {moved:?}, across {across:?}"); + for byte in [0, 2] { + assert!((centre(&shifted, byte) - centre(&plain, byte)).hypot() < 1e-6, "{rotation}°: byte {byte} moved"); + } + let (p, s) = (plain.glyphs.iter().find(|g| g.byte == 3).unwrap(), shifted.glyphs.iter().find(|g| g.byte == 3).unwrap()); + let turn_at = s.xf * s.pivot - p.xf * p.pivot; + assert!((turn_at - across).hypot() < 1e-6, "{rotation}°: turns about a point moved by {turn_at:?}"); + let unrotated = at(3, 0.0, 10.0); + let u = unrotated.glyphs.iter().find(|g| g.byte == 3).unwrap(); + let (a, b) = ((s.xf * s.unturned).as_coeffs(), u.xf.as_coeffs()); + assert!(a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-6), "{rotation}°: {a:?} vs {b:?}"); + } +} + /// Character panel menu › Tate-chu-yoko: a marked run stands across one em of the column, including /// a number longer than three digits and Latin letters. Unmarked text keeps the automatic rule /// (two or three digits only). Horizontal type stores the mark and does not move the letters. diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index c321975182..ffb3a6560b 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -51,7 +51,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; use vectorcraft_doc::hit::{HitKind, compound_part_at, hit_test, selected_hidden_at}; use vectorcraft_doc::{AnchorRef, Node, NodeId, NodeKind, Selection}; -use vectorcraft_geom::{Anchor, PathData, Point, Rect, Vec2}; +use vectorcraft_geom::{Anchor, PathData, PathSeg, Point, Rect, Vec2}; use crate::bbox::move_delta; use crate::corners::{self, CornerDrag, over_widget}; @@ -590,7 +590,17 @@ fn anchors_json(v: &[AnchorRef]) -> Value { /// The segments of `path` that marquee `r` crosses with neither of their anchors inside it, as /// (subpath, segment) pairs: the reference app selects a segment that a marquee is dragged "over /// part of" (). +/// Each segment is judged as `hit::intersects_rect` judges a path of that segment alone. A segment +/// whose anchors and handles all lie past one side of `r` is skipped without the exact test. fn crossed_segments(path: &PathData, r: Rect) -> Vec { + let (x0, x1, y0, y1) = (r.min_x(), r.max_x(), r.min_y(), r.max_y()); + let edges = [ + vectorcraft_geom::Line::new((r.x0, r.y0), (r.x1, r.y0)), + vectorcraft_geom::Line::new((r.x1, r.y0), (r.x1, r.y1)), + vectorcraft_geom::Line::new((r.x1, r.y1), (r.x0, r.y1)), + vectorcraft_geom::Line::new((r.x0, r.y1), (r.x0, r.y0)), + ]; + let degenerate = |x: Rect| x.width() == 0.0 || x.height() == 0.0; let mut out = vec![]; for (si, sp) in path.subpaths.iter().enumerate() { let n = sp.anchors.len(); @@ -600,8 +610,24 @@ fn crossed_segments(path: &PathData, r: Rect) -> Vec { if r.contains(a.p) || r.contains(b.p) { continue; } - let piece = PathData::single(vectorcraft_geom::SubPath::new(vec![*a, *b], false)); - if vectorcraft_geom::hit::intersects_rect(&piece, r) { + // A segment with no handles is drawn as a line, as `SubPath::to_bezpath_into` draws it. + let line = !a.has_out() && !b.has_in(); + let pts = if line { [a.p, b.p, b.p, b.p] } else { [a.p, a.h_out, b.h_in, b.p] }; + // A segment lies within the box of its anchors and handles. The comparisons are false + // for a NaN coordinate, so such a segment goes on to the exact test. + if pts.iter().all(|p| p.x < x0) || pts.iter().all(|p| p.x > x1) || pts.iter().all(|p| p.y < y0) || pts.iter().all(|p| p.y > y1) { + continue; + } + let piece = if line { + PathSeg::Line(vectorcraft_geom::Line::new(a.p, b.p)) + } else { + PathSeg::Cubic(vectorcraft_geom::CubicBez::new(a.p, a.h_out, b.h_in, b.p)) + }; + let bounds = vectorcraft_geom::path::segment_bounds(piece); + if bounds.intersect(r).area() <= 0.0 && !degenerate(bounds) && !degenerate(r) { + continue; + } + if edges.iter().any(|e| !piece.intersect_line(*e).is_empty()) { out.push((si, seg)); } } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index b7892cc2d3..ef60102200 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -587,6 +587,133 @@ fn a_marquee_over_part_of_a_segment_selects_it() { assert!(!drag(&mut g, Mods::default()).iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.segments"))); } +/// The segments `r` crosses, found by testing a two-anchor path built for each segment with +/// `hit::intersects_rect`. `crossed_segments` gives the same result without building the paths. +fn crossed_by_pieces(path: &PathData, r: Rect) -> Vec { + let mut out = vec![]; + for (si, sp) in path.subpaths.iter().enumerate() { + let n = sp.anchors.len(); + let count = if sp.closed { n } else { n.saturating_sub(1) }; + for seg in 0..count { + let (Some(a), Some(b)) = (sp.anchors.get(seg), sp.anchors.get((seg + 1) % n)) else { continue }; + if r.contains(a.p) || r.contains(b.p) { + continue; + } + let piece = PathData::single(vectorcraft_geom::SubPath::new(vec![*a, *b], false)); + if vectorcraft_geom::hit::intersects_rect(&piece, r) { + out.push((si, seg)); + } + } + } + out +} + +/// A cubic segment from `p0` to `p3` with handles `p1` and `p2`, as an open path. +fn curve(p0: (f64, f64), p1: (f64, f64), p2: (f64, f64), p3: (f64, f64)) -> PathData { + let a = Anchor::with_handles(p0.into(), p0.into(), p1.into()); + let b = Anchor::with_handles(p3.into(), p2.into(), p3.into()); + PathData::single(vectorcraft_geom::SubPath::new(vec![a, b], false)) +} + +fn polyline(points: &[(f64, f64)], closed: bool) -> PathData { + let pts: Vec = points.iter().map(|p| (*p).into()).collect(); + PathData::single(vectorcraft_geom::SubPath::polyline(&pts, closed)) +} + +/// A Direct Selection marquee crosses a segment, with neither of its anchors inside, only where +/// the segment itself meets the marquee: a straight segment, a curve that reaches the marquee only +/// between its anchors, and not a curve whose handles reach it while the curve stays outside. +#[test] +fn a_marquee_crosses_a_segment_only_where_the_segment_meets_it() { + let line = polyline(&[(0.0, 0.0), (100.0, 0.0)], false); + assert_eq!(crossed_segments(&line, Rect::new(40.0, -10.0, 60.0, 10.0)), vec![(0, 0)], "across a straight segment"); + assert!(crossed_segments(&line, Rect::new(40.0, 5.0, 60.0, 10.0)).is_empty(), "beside it"); + // The curve rises to y = 67.5 between its anchors on y = 0; its handles reach y = 90. + let arch = curve((0.0, 0.0), (0.0, 90.0), (100.0, 90.0), (100.0, 0.0)); + assert_eq!(crossed_segments(&arch, Rect::new(40.0, 60.0, 60.0, 70.0)), vec![(0, 0)], "the curve crosses between its anchors"); + assert!(crossed_segments(&arch, Rect::new(40.0, 75.0, 60.0, 85.0)).is_empty(), "only the handles reach the marquee"); + // Within the curve's box, above the curve where it leaves (0, 0): at x = 10 it is near y = 42. + assert!(crossed_segments(&arch, Rect::new(0.5, 55.0, 10.0, 66.0)).is_empty(), "the curve's box reaches the marquee"); + assert!(crossed_segments(&arch, Rect::new(40.0, 95.0, 60.0, 105.0)).is_empty(), "the handles stop short of it"); +} + +/// A segment that touches the marquee's edge is crossed as `hit::intersects_rect` judges it: a +/// straight segment along the edge is crossed, and a curve whose top only touches it is not. +#[test] +fn a_marquee_touching_a_segment_crosses_it_as_the_hit_test_does() { + let along = polyline(&[(0.0, 10.0), (100.0, 10.0)], false); + let r = Rect::new(40.0, 10.0, 60.0, 20.0); + assert_eq!(crossed_segments(&along, r), crossed_by_pieces(&along, r)); + assert_eq!(crossed_segments(&along, r), vec![(0, 0)], "a straight segment along the edge"); + // The curve's top is at y = 67.5. + let arch = curve((0.0, 0.0), (0.0, 90.0), (100.0, 90.0), (100.0, 0.0)); + let r = Rect::new(40.0, 67.5, 60.0, 80.0); + assert_eq!(crossed_segments(&arch, r), crossed_by_pieces(&arch, r)); + assert!(crossed_segments(&arch, r).is_empty(), "a curve whose top touches the edge"); + let r = Rect::new(40.0, 67.0, 60.0, 80.0); + assert_eq!(crossed_segments(&arch, r), vec![(0, 0)], "the same curve a little into the marquee"); +} + +/// Empty and one-anchor paths have no segments to cross; an open path's last anchor has no +/// segment after it, a closed path's closing segment is crossed, and each subpath of a compound +/// path is tested with its own index. +#[test] +fn a_marquee_crosses_segments_of_open_closed_and_compound_paths() { + let r = Rect::new(-10.0, 40.0, 10.0, 60.0); + assert!(crossed_segments(&PathData::default(), r).is_empty(), "an empty path"); + for closed in [false, true] { + assert!(crossed_segments(&polyline(&[(0.0, 50.0)], closed), r).is_empty(), "one anchor (closed: {closed})"); + } + let square = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]; + assert!(crossed_segments(&polyline(&square, false), r).is_empty(), "an open path has no segment from its last anchor"); + assert_eq!(crossed_segments(&polyline(&square, true), r), vec![(0, 3)], "the closing segment"); + let mut compound = polyline(&square, true); + compound.subpaths.extend(polyline(&[(200.0, 0.0), (200.0, 100.0), (300.0, 100.0)], false).subpaths); + let r = Rect::new(190.0, 40.0, 210.0, 60.0); + assert_eq!(crossed_segments(&compound, r), vec![(1, 0)], "the second subpath"); + let wide = Rect::new(-10.0, 40.0, 210.0, 60.0); + assert_eq!(crossed_segments(&compound, wide), vec![(0, 1), (0, 3), (1, 0)], "both subpaths"); +} + +/// Over a grid of marquees, zero-width ones and ones touching anchors and edges included, +/// `crossed_segments` picks the same segments as testing a path built for each segment. +#[test] +fn crossed_segments_match_testing_a_path_for_each_segment() { + let mut compound = polyline(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true); + compound.subpaths.extend(curve((20.0, 20.0), (20.0, 90.0), (80.0, 90.0), (80.0, 20.0)).subpaths); + let mut loops = curve((0.0, 50.0), (150.0, -40.0), (-50.0, -40.0), (100.0, 50.0)); + loops.subpaths[0].closed = true; + let paths = [ + polyline(&[(0.0, 0.0), (100.0, 0.0)], false), + polyline(&[(0.0, 10.0), (100.0, 10.0)], false), + polyline(&[(0.0, 0.0), (100.0, 100.0)], false), + polyline(&[(50.0, -20.0), (50.0, 120.0), (90.0, 30.0)], false), + curve((0.0, 0.0), (0.0, 90.0), (100.0, 90.0), (100.0, 0.0)), + curve((0.0, 100.0), (30.0, -50.0), (70.0, 150.0), (100.0, 0.0)), + loops, + compound, + polyline(&[(30.0, 30.0)], true), + PathData::default(), + ]; + let sizes = [0.0, 5.0, 10.0, 35.0, 120.0]; + let mut crossings = 0; + for path in &paths { + for x in (-30..=120).step_by(5) { + for y in (-30..=120).step_by(5) { + for w in sizes { + for h in sizes { + let r = Rect::new(f64::from(x), f64::from(y), f64::from(x) + w, f64::from(y) + h); + let want = crossed_by_pieces(path, r); + assert_eq!(crossed_segments(path, r), want, "{r:?} over {path:?}"); + crossings += want.len(); + } + } + } + } + } + assert!(crossings > 1000, "the grid crosses segments ({crossings})"); +} + #[test] fn marquee_selects_ruler_guides() { let (mut d, id) = doc_with_rect(); diff --git a/crates/tools/src/touchtype.rs b/crates/tools/src/touchtype.rs index c1184d72a6..172487c197 100644 --- a/crates/tools/src/touchtype.rs +++ b/crates/tools/src/touchtype.rs @@ -58,7 +58,8 @@ struct CharBox { pivot: Point, /// A unit vector along its line in reading order. along: Vec2, - /// A unit vector up from its line, without its rotation: the way baseline shift moves it. + /// A unit vector up from its line, without its rotation: the way baseline shift moves it. For + /// a glyph standing upright in vertical type, the line's cross axis (right of its column). up: Vec2, /// The glyph's own x axis and its up axis (with its rotation), unit vectors. ex: Vec2, @@ -174,6 +175,11 @@ fn char_box(t: &TextObject, lay: &TextLayout, gi: usize) -> Option { } let quad = [m * Point::new(x0, y0), m * Point::new(x1, y0), m * Point::new(x1, y1), m * Point::new(x0, y1)]; let d = Vec2::new(g.angle.cos(), g.angle.sin()); + // Up from the glyph's frame without its rotation. For a glyph standing upright in vertical + // type, that up runs along the column, so the glyph takes the line's cross axis instead: the + // way baseline shift moves the column's sideways glyphs. + let up = unit(linear(m * g.unturned, Vec2::new(0.0, -1.0))); + let up = if d.cross(up).abs() > 1e-6 { up } else { Vec2::new(d.y, -d.x) }; let style = edit::slice_runs(&t.runs, g.byte, g.byte + g.len).first().map(|r| r.style.clone())?; Some(CharBox { start: g.byte, @@ -181,7 +187,7 @@ fn char_box(t: &TextObject, lay: &TextLayout, gi: usize) -> Option { pen, pivot: m * g.pivot, along: if g.rtl { -d } else { d }, - up: unit(linear(m * g.unturned, Vec2::new(0.0, -1.0))), + up, ex, ey, kerned: lay.glyphs.iter().any(|h| h.line == g.line && h.len > 0 && h.byte + h.len == g.byte && h.rtl == g.rtl), diff --git a/crates/tools/src/touchtype/tests.rs b/crates/tools/src/touchtype/tests.rs index 99388178ec..3b551950d1 100644 --- a/crates/tools/src/touchtype/tests.rs +++ b/crates/tools/src/touchtype/tests.rs @@ -176,6 +176,35 @@ fn a_character_rotated_near_a_quarter_turn_moves_across_its_line() { } } +/// In vertical type, a character standing upright (§) still splits a drag into kerning down its +/// column and baseline shift across it: down 10 pt and right 4 pt is `dx` 10 and `dy` 4. Every +/// arrow key nudges it. +#[test] +fn an_upright_character_in_vertical_type_moves_down_and_across_its_column() { + let (mut d, id, s) = doc_with_type(); + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + **t = TextObject::point(Point::new(100.0, 200.0), "l§", CharStyle { size: 40.0, ..Default::default() }); + t.vertical = true; + } + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = TouchTypeTool { target: Some((id, 1)), ..Default::default() }; + let q = quad(&t, &cx); + let at = q[0].midpoint(q[2]); + let acts = drag(&mut t, &cx, at, at + Vec2::new(4.0, 10.0)); + let p1 = preview(&acts[1]); + assert!(close(p1["dx"].as_f64().unwrap_or(0.0), 10.0) && close(p1["dy"].as_f64().unwrap_or(0.0), 4.0), "{p1}"); + for key in [ToolKey::Up, ToolKey::Down, ToolKey::Left, ToolKey::Right] { + let acts = t.key(&cx, key, Mods::default()); + let moved = match acts.first() { + Some(Action::Exec(c, v)) if c == "text.touchType" => v, + other => panic!("{key:?}: {other:?}"), + }; + let parts = [&moved["dx"], &moved["dy"]].map(|v| v.as_f64().unwrap_or(0.0).abs()); + assert!(close(parts[0] + parts[1], 1.0) && (close(parts[0], 0.0) || close(parts[1], 0.0)), "{key:?}: {moved}"); + } +} + /// In type scaled unevenly, a drag's parts are measured in document points: right 10 pt and up 4 /// pt of a quarter-turned character is `dx` 10 and `dy` 4. #[test] diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index 92895fea0a..d9c86240ad 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -7,6 +7,7 @@ pub mod document; pub mod enclosing_lasso; pub mod pathtools; pub mod pen; +pub mod select; pub mod typetools; use crate::menus::Item; @@ -20,6 +21,7 @@ pub fn plugin_menu() -> Vec { Item::Sub("Document Tools", document::menu()), Item::Sub("Enclosing Lasso", enclosing_lasso::menu()), Item::Sub("Path Precision Tools", pathtools::menu()), + Item::Sub("Selection Tools", select::menu()), Item::Sub("Smart Pen", pen::menu()), Item::Sub("Type Tools", typetools::menu()), Item::Sep, diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index 14723e417f..ad943f74e8 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -2,7 +2,8 @@ //! Save a Timestamped Copy, New Symbols from Layers and Convert Layers to Symbols (the same, with //! each layer's art replaced by an instance). Save a Timestamped Copy of a document never saved //! asks for the folder to put it in ([`save_copy`]). Export All Open Documents as PDF or SVG asks -//! for the folder the copies go in ([`export_all`], #4920). +//! for the folder the copies go in ([`export_all`], #4920). Batch Trace Folder asks for the folder of +//! images and then the folder the results go in ([`batch_trace`], #4921). use serde_json::{Value, json}; @@ -13,6 +14,8 @@ use crate::menus::Item; pub const SAVE_COPY: &str = "addon.document.saveTimestampedCopy"; /// Export All Open Documents. pub const EXPORT_ALL: &str = "addon.document.exportAllOpen"; +/// Batch Trace Folder. +pub const BATCH_TRACE: &str = "addon.document.batchTraceFolder"; /// New Symbols from Layers (Convert Layers to Symbols: with their art replaced by instances). const SYMBOLS: &str = "addon.document.symbolsFromLayers"; @@ -22,6 +25,7 @@ pub fn menu() -> Vec { Item::Cmd("Save a Timestamped Copy", SAVE_COPY, json!({})), Item::Cmd("Export All Open Documents as PDF", EXPORT_ALL, json!({ "format": "pdf" })), Item::Cmd("Export All Open Documents as SVG", EXPORT_ALL, json!({ "format": "svg" })), + Item::Cmd("Batch Trace Folder", BATCH_TRACE, json!({})), Item::Sep, Item::Cmd("New Symbols from Layers", SYMBOLS, json!({})), Item::Cmd("Convert Layers to Symbols", SYMBOLS, json!({ "replace": true })), @@ -62,5 +66,32 @@ pub(crate) fn export_all(app: &mut VectorcraftApp, p: &Value) -> Result Result { + let mut p = if p.is_object() { p.clone() } else { json!({}) }; + for key in ["folder", "destinationFolder"] { + if p.get(key).is_none() { + p[key] = json!(crate::picks::folder(app).ok_or("cancelled")?); + } + } + let r = app.session.execute(BATCH_TRACE, &p).map_err(|e| e.to_string())?; + let traced = r["traced"].as_array().map_or(0, Vec::len) as u64; + let failed = r["failed"].as_array().map_or(0, Vec::len) as u64; + // One count per message: a count inside another counted message would read as the wrong + // template when the status is translated. + let status = if failed == 0 { + crate::i18n::msg_n(traced, "Traced {n} image", "Traced {n} images", &[]) + } else if traced == 0 { + crate::i18n::msg_n(failed, "{n} image couldn't be traced", "{n} images couldn't be traced", &[]) + } else { + let failed = failed.to_string(); + crate::i18n::msg_n(traced, "Traced {n} image; not traced: {failed}", "Traced {n} images; not traced: {failed}", &[("failed", &failed)]) + }; + app.status(status); + Ok(r) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index 4a2f96bd20..69cb75091f 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -123,3 +123,29 @@ fn export_all_open_documents_writes_each_to_the_folder_picked() { assert!(app.session.execute(super::EXPORT_ALL, &json!({"folder": out, "format": "doc"})).is_err()); let _ = std::fs::remove_dir_all(&dir); } + +/// #4921: Batch Trace Folder from Object › Plug-ins › Document Tools asks for the folder of images, +/// then the destination, traces each image there and reports the count (a status the catalogs +/// translate); cancelling either does nothing. +#[test] +fn batch_trace_folder_asks_for_both_folders() { + let dir = folder("batch-trace"); + let (src, out) = (dir.join("in"), dir.join("out")); + std::fs::create_dir_all(&src).unwrap(); + image::RgbaImage::from_pixel(16, 16, image::Rgba([0, 0, 0, 255])).save(src.join("a.png")).unwrap(); + std::fs::write(src.join("b.png"), b"not a png").unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut picks = vec![out.to_string_lossy().into_owned(), src.to_string_lossy().into_owned()]; + app.services.pick_folder = Some(Box::new(move || picks.pop())); + click(&mut app, "Batch Trace Folder"); + assert!(out.join("a.vectorcraft").exists(), "{}", app.ui.status); + assert_eq!(app.ui.status, "Traced 1 image; not traced: 1"); + let de = crate::i18n::Lang::from_code("de").unwrap(); + assert_eq!(crate::i18n::message(de, &app.ui.status), "1 Bild nachgezeichnet; nicht nachgezeichnet: 1"); + assert_eq!(crate::i18n::message(de, "Traced 2 images"), "2 Bilder nachgezeichnet"); + assert_eq!(crate::i18n::message(de, "2 images couldn't be traced"), "2 Bilder konnten nicht nachgezeichnet werden"); + assert!(app.session.documents().is_empty(), "the images' documents are closed"); + app.services.pick_folder = Some(Box::new(|| None)); + assert_eq!(app.run(super::BATCH_TRACE, json!({})).unwrap_err(), "cancelled"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/addons/select.rs b/crates/ui-egui/src/addons/select.rs new file mode 100644 index 0000000000..8f6b258269 --- /dev/null +++ b/crates/ui-egui/src/addons/select.rs @@ -0,0 +1,200 @@ +//! Selection Tools in the interface: its submenu (Object › Plug-ins › Selection Tools) and the +//! Select by Artboards dialog (#5548), which lists the artboards with their number, name and size, +//! filters them by name, picks several, fits one in the window on double-click (#5549), and on OK +//! runs `addon.select.byArtboards` with the relation chosen. + +use egui::{Sense, Ui, vec2}; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::menus::Item; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::widgets; + +/// Select by Artboards, and its dialog's kind. +pub const COMMAND: &str = "addon.select.byArtboards"; +pub const KIND: &str = "selectByArtboards"; +/// The relations the dialog offers: (value, label). +const RELATIONS: [(&str, &str); 3] = [("overlap", "Overlapping"), ("inside", "Fully Inside"), ("outside", "Fully Outside")]; +const LABEL_W: f32 = 70.0; +const ROW_H: f32 = 22.0; +const NUMBER_W: f32 = 28.0; +const LIST_H: f32 = 220.0; + +/// Object › Plug-ins › Selection Tools. +pub fn menu() -> Vec { + vec![Item::Cmd("Select by Artboards…", COMMAND, Value::Null)] +} + +/// The dialog's fields to start with: the active artboard chosen, Overlapping. +pub(crate) fn fields(app: &VectorcraftApp) -> Value { + json!({ "artboards": [app.view().map_or(0, |v| v.artboard)], "relation": "overlap" }) +} + +pub(crate) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Select by Artboards").to_string(), + body, + confirm, + min_width: 360.0, + ok_enabled: Some(|_, d| !chosen(d).is_empty()), + ..DialogSpec::FORM +}; + +/// The artboards chosen in dialog `d`, in order. +fn chosen(d: &Dialog) -> Vec { + let mut v: Vec = + d.fields.get("artboards").and_then(Value::as_array).into_iter().flatten().filter_map(|i| usize::try_from(i.as_u64()?).ok()).collect(); + v.sort_unstable(); + v.dedup(); + v +} + +/// The indices of `names` whose name holds `query`, ignoring case (all of them for an empty query). +pub(crate) fn shown(names: &[String], query: &str) -> Vec { + let q = query.trim().to_lowercase(); + names.iter().enumerate().filter(|(_, n)| q.is_empty() || n.to_lowercase().contains(&q)).map(|(i, _)| i).collect() +} + +/// A click on row `i` of the rows `shown`: alone it chooses only that artboard of those shown, with Cmd/Ctrl it +/// toggles it, with Shift it adds the rows from the last one clicked (`anchor`) to it. Returns the +/// new anchor. +pub(crate) fn click(chosen: &mut Vec, anchor: Option, i: usize, shown: &[usize], shift: bool, command: bool) -> Option { + let at = |j: usize| shown.iter().position(|k| *k == j); + match (shift, anchor.and_then(at), at(i)) { + (true, Some(a), Some(b)) => { + chosen.extend(shown.iter().skip(a.min(b)).take(a.abs_diff(b) + 1)); + chosen.sort_unstable(); + chosen.dedup(); + return anchor; + } + _ if command => match chosen.iter().position(|j| *j == i) { + Some(p) => { + chosen.remove(p); + } + None => chosen.push(i), + }, + // Of the rows shown, only this one; rows the search hides keep their state. + _ => { + chosen.retain(|j| !shown.contains(j)); + chosen.push(i); + } + } + chosen.sort_unstable(); + Some(i) +} + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + let unit = app.session.general_unit(); + let boards: Vec<(String, f64, f64)> = app + .session + .active() + .map(|st| st.doc.artboards.iter().map(|a| (a.name.clone(), a.rect.width(), a.rect.height())).collect()) + .unwrap_or_default(); + let names: Vec = boards.iter().map(|b| b.0.clone()).collect(); + let query = widgets::search_field(ui, ui.scope_id().with("select-by-artboards-search"), "Search artboards"); + d.fields.insert("__search".into(), json!(query)); + let rows = shown(&names, &query); + let picked = chosen(d); + let (mut clicked, mut double) = (None, None); + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(LIST_H).auto_shrink([false, true]).show(ui, |ui| { + if rows.is_empty() { + ui.label(egui::RichText::new(tl!("No artboards match.")).color(t.text_dim)); + } + for &i in &rows { + let Some((name, w, h)) = boards.get(i) else { continue }; + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click()); + let on = picked.contains(&i); + if on { + ui.painter().rect_filled(r, 0.0, t.row_selected); + } else if resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover); + } + let font = egui::FontId::proportional(12.0); + let mid = r.left_center(); + let p = ui.painter(); + p.text(mid + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, (i + 1).to_string(), font.clone(), t.text_dim); + let size = format!("{} × {}", unit.number(*w), unit.format(*h)); + let size_at = r.right_center() - vec2(6.0, 0.0); + p.text(size_at, egui::Align2::RIGHT_CENTER, &size, font.clone(), t.text_dim); + p.with_clip_rect(r.with_max_x(size_at.x - 80.0)).text(mid + vec2(NUMBER_W, 0.0), egui::Align2::LEFT_CENTER, name, font, t.text); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, on, format!("{} {name} {size}", i + 1))); + if resp.double_clicked() { + double = Some(i); + } else if resp.clicked() { + clicked = Some((i, ui.input(|inp| inp.modifiers))); + } + } + }); + if let Some((i, m)) = clicked { + row_clicked(d, i, &rows, m); + } + if let Some(i) = double { + row_double_clicked(app, d, i); + } + let mut picked = chosen(d); + ui.add_space(4.0); + ui.horizontal(|ui| { + if widgets::flat_button_fit(ui, "Select All", 70.0).clicked() { + choose_shown(&mut picked, &rows, true); + } + if widgets::flat_button_fit(ui, "None", 50.0).clicked() { + choose_shown(&mut picked, &rows, false); + } + // Rows hidden by the search stay chosen: the count says how many are. + let count = crate::i18n::fmt(tl!("Chosen: {n} of {total}"), &[("n", &picked.len().to_string()), ("total", &boards.len().to_string())]); + ui.label(egui::RichText::new(count).color(t.text_dim)); + }); + d.fields.insert("artboards".into(), json!(picked)); + ui.add_space(6.0); + form::choice(ui, d, "relation", tl!("Select:"), (LABEL_W, 160.0), &RELATIONS); + false +} + +/// Select All (`on`) or None: choose every row `shown`, or none of them. Rows the search hides +/// keep their state. +pub(crate) fn choose_shown(chosen: &mut Vec, shown: &[usize], on: bool) { + if on { + chosen.extend(shown.iter().copied()); + chosen.sort_unstable(); + chosen.dedup(); + } else { + chosen.retain(|i| !shown.contains(i)); + } +} + +/// A click on row `i` of the rows `shown`, with modifier keys `m`: [`click`] on dialog `d`'s +/// chosen artboards. +pub(crate) fn row_clicked(d: &mut Dialog, i: usize, shown: &[usize], m: egui::Modifiers) { + let mut picked = chosen(d); + // What a double-click's first click changed, for its second to put back. + d.fields.insert("__before".into(), json!(picked)); + let anchor = d.fields.get("__anchor").and_then(Value::as_u64).and_then(|a| usize::try_from(a).ok()); + if let Some(a) = click(&mut picked, anchor, i, shown, m.shift, m.command) { + d.fields.insert("__anchor".into(), json!(a)); + } + d.fields.insert("artboards".into(), json!(picked)); +} + +/// A double-click on row `i`: artboard `i` becomes active and fits in the window, as a +/// double-click on its number in the Artboards panel does (`view.goToArtboard`). The dialog stays +/// open, and the artboards chosen are those chosen before the double-click. +pub(crate) fn row_double_clicked(app: &mut VectorcraftApp, d: &mut Dialog, i: usize) { + if let Some(before) = d.fields.remove("__before") { + d.fields.insert("artboards".into(), before); + } + // An artboard the list showed a frame ago can't be missing, and a failure only leaves the view. + app.run("view.goToArtboard", json!({ "index": i })).ok(); +} + +/// OK: select the objects and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + app.ui.dialog = None; + app.run(COMMAND, form::params(d)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/select/tests.rs b/crates/ui-egui/src/addons/select/tests.rs new file mode 100644 index 0000000000..a2c7ef4f3a --- /dev/null +++ b/crates/ui-egui/src/addons/select/tests.rs @@ -0,0 +1,107 @@ +use serde_json::json; +use vectorcraft_engine::Session; + +use super::{choose_shown, click, row_clicked, row_double_clicked, shown}; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +fn names(v: &[&str]) -> Vec { + v.iter().map(|s| s.to_string()).collect() +} + +#[test] +fn the_search_filters_artboards_by_name_ignoring_case() { + let n = names(&["Cover", "Page 2", "Back cover", "Inside"]); + assert_eq!(shown(&n, ""), vec![0, 1, 2, 3]); + assert_eq!(shown(&n, " COVER "), vec![0, 2]); + assert_eq!(shown(&n, "zzz"), Vec::::new()); +} + +#[test] +fn select_all_and_none_act_on_the_rows_shown() { + // Board 4 is chosen but hidden by the search: neither button touches it. + let mut c = vec![1, 4]; + choose_shown(&mut c, &[0, 1, 2], true); + assert_eq!(c, vec![0, 1, 2, 4]); + choose_shown(&mut c, &[0, 1, 2], false); + assert_eq!(c, vec![4]); +} + +#[test] +fn clicks_choose_toggle_and_extend_rows() { + let rows = [0, 2, 3, 5]; + let mut c = vec![]; + let a = click(&mut c, None, 2, &rows, false, false); + assert_eq!((c.clone(), a), (vec![2], Some(2))); + // Shift adds the rows shown between the last one clicked and this one. + let a = click(&mut c, a, 5, &rows, true, false); + assert_eq!((c.clone(), a), (vec![2, 3, 5], Some(2))); + // Cmd/Ctrl toggles a row. + let a = click(&mut c, a, 3, &rows, false, true); + assert_eq!((c.clone(), a), (vec![2, 5], Some(3))); + let a = click(&mut c, a, 0, &rows, false, true); + assert_eq!((c.clone(), a), (vec![0, 2, 5], Some(0))); + // A plain click chooses that row alone; Shift without an anchor does too. + let a = click(&mut c, a, 3, &rows, false, false); + assert_eq!((c.clone(), a), (vec![3], Some(3))); + let a = click(&mut c, None, 5, &rows, true, false); + assert_eq!((c.clone(), a), (vec![5], Some(5))); + // Board 4, chosen but hidden by the search, stays chosen through a plain click. + c.push(4); + click(&mut c, a, 2, &rows, false, false); + assert_eq!(c, vec![2, 4]); +} + +#[test] +fn select_by_artboards_lists_the_artboards_and_selects_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("artboard.new", json!({"x": 150, "y": 0, "width": 200, "height": 50, "name": "Banner"})).unwrap(); + let inside = app.run("shape.rectangle", json!({"x": 160, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Selection Tools"] && e.label == "Select by Artboards…").unwrap(); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(&mut app, &cmd, p); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.kind, super::KIND); + assert_eq!(d.fields["artboards"], json!([0]), "the active artboard is chosen"); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Select by Artboards", "Artboard 1", "Banner", "100 × 100 pt", "200 × 50 pt", "Chosen: 1 of 2", "Overlapping", "Select All", "None"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("artboards".into(), json!([])); + assert!(!(super::SPEC.ok_enabled.unwrap())(&app, app.ui.dialog.as_ref().unwrap()), "OK is off with nothing chosen"); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("artboards".into(), json!([1])); + d.fields.insert("relation".into(), json!("inside")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(inside)]); +} + +#[test] +fn double_clicking_a_row_fits_its_artboard_and_keeps_the_choice() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + for x in [150, 300] { + app.run("artboard.new", json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap(); + } + app.run("view.goToArtboard", json!({"index": 0})).unwrap(); + menus::invoke(&mut app, super::COMMAND, serde_json::Value::Null); + let mut d = app.ui.dialog.take().unwrap(); + d.fields.insert("artboards".into(), json!([0, 1])); + // The search shows boards 0 and 2: row 2 is the second row, but board 2 is the one fitted. + let rows = [0, 2]; + row_clicked(&mut d, 2, &rows, egui::Modifiers::NONE); + // Board 1, hidden by the search, stays chosen. + assert_eq!(d.fields["artboards"], json!([1, 2]), "the first click chooses the row among those shown"); + // The dialog frame lends the dialog to its body while the app still shows it. + app.ui.dialog = Some(d.clone()); + row_double_clicked(&mut app, &mut d, 2); + assert_eq!(d.fields["artboards"], json!([0, 1]), "the double-click puts the choice back"); + assert_eq!(app.view().unwrap().artboard, 2, "the artboard is active"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index fbcf1dd0c2..7826cdfe32 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -370,6 +370,12 @@ impl VectorcraftApp { } self.flush_clipboard_out(ctx); self.drain_inbox(); + // An action playing at Step by Step or Pause For runs its next step when it is due, after + // the control requests and opened files above: a Stop or a document switch they bring + // comes first. + if let Some(wait) = crate::panels::actions::tick_playback(self, now) { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); + } if self.viewport_hidden(ctx) && (self.needs_hidden_paint() || (!dialog_was_open && self.ui.dialog.is_some())) { // A plain repaint runs only logic in a hidden window: the ui that applies injected // input, shows a queued dialog or issues a capture needs this command. egui-winit @@ -494,6 +500,8 @@ impl VectorcraftApp { return; } crate::state::sync_zoom_stops_display_print_size(self.session.prefs.display_print_size); + // Whether this pass draws the last step of an action playing at Step by Step. + let step_held = crate::panels::actions::playback_held(self); let t0 = now_ms(); widgets::set_dialog_open(&ctx, self.ui.dialog.is_some()); // The canvas records this pass's IME caret geometry; a pass that draws no canvas has none. @@ -558,6 +566,10 @@ impl VectorcraftApp { if !ctx.will_discard() { self.perf.frame_ms = now_ms() - t0; self.issue_screenshots(&ctx); + // A hidden window's pass shows nothing, so the step waits for a pass the user sees. + if step_held && !self.viewport_hidden(&ctx) { + crate::panels::actions::playback_drawn(self); + } } let _ = json!(null); } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 6e4bfa38ee..06a9f488d3 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -401,6 +401,11 @@ fn canvas_cursor(app: &mut VectorcraftApp, ui: &Ui, view_info: vectorcraft_engin let space = ui.input(|i| i.key_down(egui::Key::Space)); let drag = ui.data(|d| d.get_temp::(drag_id())); let panning = matches!(drag, Some(Drag::Pan { .. })); + let tool_holds = drag.is_some_and(drag::tool_holds); + // A tool that holds the press (Pencil, a brush, a shape) keeps Space out of the way: the drag + // began before Space went down, so Space pans nothing, and the hand would promise a pan the + // drag does not do. + let space = space && !tool_holds; // A zoom drag keeps its cursor when Space is pressed (with or without Shift) or Cmd is let go. let zoom_drag = matches!(drag, Some(Drag::ZoomBox { .. } | Drag::ZoomScrub { .. })); let zooming = zoom_drag || if space { m.command } else { app.session.tool_id() == "zoom" }; @@ -420,8 +425,15 @@ fn canvas_cursor(app: &mut VectorcraftApp, ui: &Ui, view_info: vectorcraft_engin } else { None }; + // Cmd borrows a selection tool only at pointer-down. Pressed during another tool's drag, it + // cannot change the owner, so do not preview the borrowed tool's cursor. A drag that started + // with a borrowed selection tool keeps its Command modifier and cursor. + let mut cursor_mods = mods(m, space); + if tool_holds && !vectorcraft_tools::catalog::is_selection_tool(app.session.tool_id()) { + cursor_mods.cmd = false; + } // In Presentation Mode the pointer is the default one, with no tool cursor. - let tool_cursor = (app.ui.screen_mode < 3).then(|| view_cursor.or_else(|| hover_cursor(app, mods(m, space), view_info, hover_still))); + let tool_cursor = (app.ui.screen_mode < 3).then(|| view_cursor.or_else(|| hover_cursor(app, cursor_mods, view_info, hover_still))); let cur = if let Some(c) = tool_cursor.flatten() { let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("tool-cursor"))); // The loaded place cursor carries the file's thumbnail. diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 3f3c156edd..1980661b88 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -89,6 +89,46 @@ pub(super) fn tool_drag_mods_changed(ui: &Ui, m: Mods, backquote: bool) -> bool dragged && last.is_some_and(|l| l != held) } +/// Whether Backtick is held at the end of this frame, and whether it was at the end of the frame +/// before (`None` before the first). The canvas records it once a frame. +pub(super) fn backquote_seen(ui: &Ui) -> (bool, Option) { + let id = egui::Id::unique("canvas-backquote-seen"); + let now = ui.input(|i| i.key_down(egui::Key::Backtick)); + let before = ui.data_mut(|d| { + let before = d.get_temp::(id); + d.insert_temp(id, now); + before + }); + (now, before) +} + +/// Whether Backtick was held when `button` went up in this frame, with `before` its state at the end +/// of the frame before ([`backquote_seen`]). Its state as the frame began is the opposite of its +/// first press or release in the frame; when the window lost the focus first (which lets go of every +/// key without a release), it is `before`; with neither, it is its state now. The frame's presses, +/// releases and focus losses before the button-up then apply in the order they came. Without a +/// button-up in this frame, its state now. +pub(super) fn backquote_at_release(ui: &Ui, button: egui::PointerButton, before: Option) -> bool { + ui.input(|i| { + let now = i.key_down(egui::Key::Backtick); + // A press or release of Backtick (`Some(pressed)`), or a focus loss (`None`). + let step = |e: &egui::Event| match e { + egui::Event::Key { key: egui::Key::Backtick, pressed, repeat: false, .. } => Some(Some(*pressed)), + egui::Event::WindowFocused(false) => Some(None), + _ => None, + }; + let Some(up) = i.events.iter().position(|e| matches!(e, egui::Event::PointerButton { button: b, pressed: false, .. } if *b == button)) else { + return now; + }; + let start = match i.events.iter().find_map(step) { + Some(Some(down)) => !down, + Some(None) => before.unwrap_or(now), + None => now, + }; + i.events[..up].iter().filter_map(step).fold(start, |_, s| s.unwrap_or(false)) + }) +} + /// The pen pressure (0..1) of the press in progress: the force of this frame's pen or touch /// input, else the pressure in the host's feed while a pen is the pointer that moved last /// ([`crate::Services::stylus`]: [`StylusFeed::press`] for a new press, [`StylusFeed::held`] diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 3775edeb86..e0bd9f0292 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -1,7 +1,8 @@ use super::artboards::{artboard_name_at, begin_artboard_name_edit, name_press_id, select_named_artboard}; use super::drag::{ - FrameMove, HoverContext, apply_requests, dispatch, drag_art_out, drag_id, drag_layer_id, drag_pos_id, drop_press, mods, move_pose, on_canvas, - pen_pose, pen_pressure, tool_drag_doc_id, tool_drag_mods_changed, tool_drag_moved, tool_frame_moves, tool_holds, tool_press_doc_id, + FrameMove, HoverContext, apply_requests, backquote_at_release, backquote_seen, dispatch, drag_art_out, drag_id, drag_layer_id, drag_pos_id, + drop_press, mods, move_pose, on_canvas, pen_pose, pen_pressure, tool_drag_doc_id, tool_drag_mods_changed, tool_drag_moved, tool_frame_moves, + tool_holds, tool_press_doc_id, }; use super::view::{ HOLD_DELAY, HOLD_ZOOM, SCRUB_SLOP, SCRUB_ZOOM, WheelTurn, animated_zoom, pan_pixels, rotate_about, scroll_view, touch_gestures, trackpad_turn, @@ -19,7 +20,8 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo // double-taps) where it was seen last (#491). let at = hover.or_else(|| pointer.interact_pos().filter(|p| rect.contains(*p))); let view = app.view_info(); - let f = Pointing { resp, rect, pointer: &pointer, m, space, xf, v, view }; + let (_, backquote_before) = backquote_seen(ui); + let f = Pointing { resp, rect, pointer: &pointer, m, space, xf, v, view, backquote_before }; touch_gestures(app, ui, rect, view); // Pressed and held still, a pen or a finger opens the context menu (egui's long touch): the // tool's press is dropped, as a right-click presses nothing. @@ -186,6 +188,8 @@ struct Pointing<'a> { xf: Xf, v: View, view: vectorcraft_engine::ViewInfo, + /// Whether Backtick was held at the end of the frame before ([`backquote_seen`]). + backquote_before: Option, } /// Zoom around the pointer, and scroll ([`wheel`]); a trackpad rotation turns the view. Returns the pointer, the @@ -433,6 +437,8 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po dd.remove::(tool_drag_doc_id()); dd.remove::(tool_press_doc_id()); }); + // Backtick as it was at the button-up: a key pressed or released later in the frame does not count. + let backquote = backquote_at_release(ui, egui::PointerButton::Primary, f.backquote_before); match d { Drag::ZoomBox { start } => { let start = zoom_marquee_start(ui, start, before, p, space); @@ -472,7 +478,6 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po let (moves, last_pose) = tool_frame_moves(ui, app, true); let pen = move_pose(app, &xf, last_pose); if let Some(last) = last_drag { - let backquote = ui.input(|i| i.key_down(egui::Key::Backtick)); dispatch_frame_moves(app, ui, f, backquote, moves); if last != xf.to_doc(p) { let ev = PointerEvent { @@ -490,7 +495,7 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po kind: PointerKind::Up, pos: xf.to_doc(p), mods: mods(m, space), - backquote: ui.input(|i| i.key_down(egui::Key::Backtick)), + backquote, pressure: pen_pressure(ui, app, false), pen, }; @@ -501,30 +506,8 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po egui::DragAndDrop::clear_payload(ui.ctx()); let (pressure, pen) = (pen_pressure(ui, app, false), pen_pose(app, &xf)); let pos = xf.to_doc(p); - dispatch( - app, - &PointerEvent { - kind: PointerKind::Drag, - pos, - mods: mods(m, space), - backquote: ui.input(|i| i.key_down(egui::Key::Backtick)), - pressure, - pen, - }, - view, - ); - dispatch( - app, - &PointerEvent { - kind: PointerKind::Up, - pos, - mods: mods(m, space), - backquote: ui.input(|i| i.key_down(egui::Key::Backtick)), - pressure, - pen, - }, - view, - ); + dispatch(app, &PointerEvent { kind: PointerKind::Drag, pos, mods: mods(m, space), backquote, pressure, pen }, view); + dispatch(app, &PointerEvent { kind: PointerKind::Up, pos, mods: mods(m, space), backquote, pressure, pen }, view); } Drag::Art => { // Released over a panel: the move goes back. (The app ends it before the panels @@ -533,14 +516,7 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po let _ = app.session.cancel_interaction(); dispatch( app, - &PointerEvent { - kind: PointerKind::Up, - pos: Point::ZERO, - mods: Mods::default(), - backquote: ui.input(|i| i.key_down(egui::Key::Backtick)), - pressure: 1.0, - pen: None, - }, + &PointerEvent { kind: PointerKind::Up, pos: Point::ZERO, mods: Mods::default(), backquote, pressure: 1.0, pen: None }, view, ); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 0c9462818e..edfeebca41 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3051,6 +3051,67 @@ fn egui_backtick_drag_uses_key_state_at_release() { ); } +/// The release takes Backtick as it was at the button-up, when the key goes up or down later in the +/// same frame. +#[test] +fn backtick_changed_after_the_button_up_in_its_frame_does_not_change_the_release() { + use egui::Event; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let tile = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.run("object.pattern.make", json!({"ids": [tile], "name": "Dots", "width": 20, "height": 20})).unwrap(); + app.run("object.pattern.done", json!({})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"ids": [id], "swatch": "Dots"})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.select_tool("selection"); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let from = xf.to_screen(Point::new(125.0, 125.0)); + let to = xf.to_screen(Point::new(145.0, 125.0)); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let key = |pressed| Event::Key { key: egui::Key::Backtick, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + let node = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + let pattern_x = |node: &vectorcraft_doc::Node| { + let vectorcraft_color::Paint::Pattern { xf, .. } = node.appearance.fill_paint() else { panic!("pattern fill expected") }; + xf.as_coeffs()[4] + }; + let before = node(&app); + frame(&mut app, &ctx, vec![Event::PointerMoved(from), button(from, true)]); + frame(&mut app, &ctx, vec![key(true), Event::PointerMoved(to)]); + frame(&mut app, &ctx, vec![button(to, false), key(false)]); + let pattern_only = node(&app); + assert!(app.session.active().unwrap().interaction.is_none(), "committed"); + assert_eq!(pattern_only.geometric_bounds(), before.geometric_bounds(), "Backtick held at the button-up keeps geometry still"); + assert!((pattern_x(&pattern_only) - pattern_x(&before) - 20.0).abs() < 0.001, "Backtick held at the button-up moves the pattern"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(node(&app), before); + frame(&mut app, &ctx, vec![Event::PointerMoved(from), button(from, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(to)]); + frame(&mut app, &ctx, vec![button(to, false), key(true)]); + let ordinary = node(&app); + frame(&mut app, &ctx, vec![key(false)]); + assert!( + (ordinary.geometric_bounds().unwrap().x0 - before.geometric_bounds().unwrap().x0 - 20.0).abs() < 0.001, + "Backtick pressed after the button-up commits an ordinary move" + ); + assert!((pattern_x(&ordinary) - pattern_x(&before)).abs() < 0.001, "the ordinary move keeps the pattern matrix"); + // A focus loss after the button-up lets go of Backtick with no release event. + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(node(&app), before); + frame(&mut app, &ctx, vec![Event::PointerMoved(from), button(from, true)]); + frame(&mut app, &ctx, vec![key(true), Event::PointerMoved(to)]); + frame(&mut app, &ctx, vec![button(to, false), Event::WindowFocused(false)]); + let unfocused = node(&app); + assert_eq!(unfocused.geometric_bounds(), before.geometric_bounds(), "a focus loss after the button-up keeps geometry still"); + assert!((pattern_x(&unfocused) - pattern_x(&before) - 20.0).abs() < 0.001, "a focus loss after the button-up moves the pattern"); +} + #[test] fn mirror_axis_drag_uses_canvas_coordinates_in_a_zoomed_rotated_view() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -4949,6 +5010,74 @@ fn space_during_a_zoom_drag_keeps_the_zoom_cursor() { shown(&mut app, vec![space(false)]); } +/// Space pressed while the Pencil holds the press is ignored: the cursor keeps the pencil (its +/// crosshair stand-in) instead of turning into the hand, and the stroke goes on. Space pans only +/// when it is down at the press. Once the button is up, Space shows the hand again. +#[test] +fn space_during_a_pencil_drag_keeps_the_pencil_cursor() { + use egui::{CursorIcon, Event, Modifiers}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("pencil"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let c = app.canvas_rect.unwrap().center(); + let shown = |app: &mut VectorcraftApp, events: Vec| { + let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, focused: false, events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.platform_output.cursor_icon + }; + let space = |pressed| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + assert_eq!(shown(&mut app, vec![Event::PointerMoved(c)]), CursorIcon::Crosshair, "the pencil's cursor"); + shown(&mut app, vec![button(c, true)]); + shown(&mut app, vec![Event::PointerMoved(c + vec2(10.0, 5.0))]); + assert_eq!( + shown(&mut app, vec![space(true), Event::PointerMoved(c + vec2(40.0, 20.0))]), + CursorIcon::Crosshair, + "Space during the drawing drag is ignored" + ); + assert_eq!(shown(&mut app, vec![Event::PointerMoved(c + vec2(60.0, 30.0))]), CursorIcon::Crosshair, "still ignored while Space is held"); + shown(&mut app, vec![button(c + vec2(60.0, 30.0), false)]); + assert_eq!(shown(&mut app, vec![]), CursorIcon::Grab, "after the drag, Space shows the hand"); + shown(&mut app, vec![space(false)]); +} + +/// Cmd+Space pressed after a tool starts drawing does not borrow the Selection cursor: the +/// drawing tool still owns the drag. The Zoom cursor takes over once the button is released. +#[test] +fn cmd_space_mid_tool_drag_keeps_the_active_tool_cursor() { + use egui::{CursorIcon, Event, Modifiers}; + for tool in ["pencil", "rectangle", "pen"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool(tool); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let c = app.canvas_rect.unwrap().center(); + let shown = |app: &mut VectorcraftApp, events: Vec| { + let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, focused: false, events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.platform_output.cursor_icon + }; + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let space = |pressed| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::COMMAND }; + let tool_cursor = shown(&mut app, vec![Event::PointerMoved(c)]); + shown(&mut app, vec![button(c, true)]); + shown(&mut app, vec![Event::PointerMoved(c + vec2(10.0, 5.0))]); + let center = app.view().unwrap().center; + assert_eq!( + shown(&mut app, vec![Event::ModifiersChanged(Modifiers::COMMAND), space(true), Event::PointerMoved(c + vec2(40.0, 20.0))]), + tool_cursor, + "{tool}: Cmd+Space must keep the active drag's cursor" + ); + assert_eq!(app.view().unwrap().center, center, "{tool}: the view stays still during the drag"); + assert_eq!(shown(&mut app, vec![button(c + vec2(40.0, 20.0), false)]), CursorIcon::ZoomIn, "{tool}: Zoom returns after release"); + } +} + /// In a rotated view the Selection tool's marquee is drawn where the tool selects: through the /// screen corners of the document rectangle between the press and the pointer. #[test] diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index a40d88dfe5..df58c1be7a 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -142,9 +142,9 @@ const GLOBAL_EDIT_OPTIONS_WIDTH: f32 = 24.0; /// page places the options in the Control panel as well as in Properties /// (). /// It opens the Properties panel's Global Edit Options, which set the same session options, and is -/// off while Global Edit is on, as that panel's dropdown is. It sits after Recolor Artwork, ahead of -/// the X/Y/W/H fields that the bar leaves out when it runs short of room, and is left out only when -/// no room is left for it. +/// off and closed while Global Edit is on, as that panel's dropdown is. It sits after Recolor +/// Artwork, ahead of the X/Y/W/H fields that the bar leaves out when it runs short of room, and is +/// left out only when no room is left for it. fn global_edit_options(app: &mut VectorcraftApp, ui: &mut Ui) { if !crate::menus::enabled(app, "select.globalEdit") || ui.available_width() < GLOBAL_EDIT_OPTIONS_WIDTH { return; @@ -152,12 +152,32 @@ fn global_edit_options(app: &mut VectorcraftApp, ui: &mut Ui) { let on = app.session.active().is_some_and(|d| d.global_edit.is_some()); let options = widgets::icon_button_enabled(ui, "chevron-down", tl!("Global Edit Options"), false, !on, GLOBAL_EDIT_OPTIONS_WIDTH); egui::Popup::menu(&options) + .open_memory(crate::panels::properties::global_edit_options_open(&options, on)) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show(|ui| crate::panels::properties::global_edit_options(app, ui)); } -/// The room the Control bar's inline X/Y/W/H fields need; with less, only the Transform link shows. -const INLINE_TRANSFORM_WIDTH: f32 = 440.0; +/// The width of each of the Control bar's inline X/Y/W/H fields. +const INLINE_FIELD_WIDTH: f32 = 80.0; + +/// The keys and labels of the Control bar's inline X/Y/W/H fields, in their order. +const INLINE_FIELDS: [(&str, &str); 4] = [("x", "X:"), ("y", "Y:"), ("width", "W:"), ("height", "H:")]; + +/// The label of an inline X/Y/W/H field. +fn inline_label(t: &Tokens, lbl: &str) -> egui::RichText { + egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim) +} + +/// The room the Control bar's inline X/Y/W/H fields take: their labels as drawn in the current +/// language, the four fields, the W/H link and the item spacing ahead of each of them. With less, +/// only the Transform link shows. +fn inline_transform_width(ui: &Ui, t: &Tokens) -> f32 { + let measure = |text: egui::WidgetText| text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x; + let labels: f32 = INLINE_FIELDS.iter().map(|(_, lbl)| measure(inline_label(t, lbl).into())).sum(); + let fields = INLINE_FIELD_WIDTH * INLINE_FIELDS.len() as f32; + let items = 2 * INLINE_FIELDS.len() + 1; + labels + fields + crate::panels::transform::CONSTRAIN_LINK_SIZE + ui.spacing().item_spacing.x * items as f32 +} /// The Control bar (Window → Control), context-sensitive like Illustrator's. pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -262,6 +282,11 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); crate::panels::character::control_bar(app, ui); + // Area type: its vertical alignment in the frame (#3759). + if crate::panels::properties::vertical_align::buttons(app, ui, 24.0) { + ui.add_space(4.0); + ui.separator(); + } if sel.is_empty() { if widgets::flat_button(ui, tl!("Document Setup"), 112.0).clicked() { app.run("file.documentSetup", json!({})).ok(); @@ -284,28 +309,24 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { crate::panels::transform::link(app, ui); // The bounding box, rotated with rotated objects: its centre and its own sides. if let Some(b) = app.selection_box() - && ui.available_width() >= INLINE_TRANSFORM_WIDTH + && ui.available_width() >= inline_transform_width(ui, &t) { let c = b.center(); let origin = app.ruler_origin(); let link = crate::panels::transform::proportional(app, ui); let copy = crate::panels::transform::alt_enter_copies(app, ui); - for (k, lbl, v, offset) in [ - ("x", "X:", c.x, origin.x), - ("y", "Y:", c.y, origin.y), - ("width", "W:", b.rect.width(), 0.0), - ("height", "H:", b.rect.height(), 0.0), - ] { + let values = [(c.x, origin.x), (c.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)]; + for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) { // The W/H link sits between W and H. if k == "height" { crate::panels::transform::constrain_link(app, ui); } - widgets::field_label(ui, egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim)); + widgets::field_label(ui, inline_label(&t, lbl)); let (id, shown) = (("cb", k), Some(v - offset)); let set = if matches!(k, "width" | "height") { - widgets::size_field(ui, id, shown, units, 80.0) + widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH) } else { - widgets::num_field(ui, id, shown, units, 80.0) + widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH) }; if let Some(nv) = set { app.run("object.setBounds", json!({k: nv + offset, "reference": 4, "proportional": link, "copy": copy})).ok(); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 00c56ff67a..c9109a17fc 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1807,7 +1807,7 @@ fn the_control_bar_shows_the_distribute_buttons_for_two_or_more_objects() { /// The Control bar shows the Global Edit Options dropdown while Start Global Edit can run. Its /// options are the session's, which the Properties panel's dropdown also sets: Match Size from /// the Control bar narrows the Results and the objects Start Global Edit takes. The dropdown is off -/// while Global Edit is on, and absent when the selection cannot start it. +/// and closed while Global Edit is on, and absent when the selection cannot start it. #[test] fn the_control_bar_shows_the_global_edit_options() { crate::i18n::set_current(crate::i18n::Lang::EN); @@ -1860,9 +1860,14 @@ fn the_control_bar_shows_the_global_edit_options() { let nodes = frame(&mut app, vec![]); let button = find(&nodes, "Global Edit Options").unwrap_or_else(|| panic!("Global Edit on: the dropdown still shows")); assert!(button.is_disabled(), "the options are off while Global Edit is on"); + let results = |nodes: &Nodes| nodes.iter().any(|(_, n)| n.label().or(n.value()).is_some_and(|t| t.starts_with("Result"))); + assert!(!results(&nodes), "Global Edit starting closes the open options"); + assert!(!results(&frame(&mut app, vec![]))); + app.run("select.globalEdit", json!({})).unwrap(); + frame(&mut app, vec![]); + assert!(!results(&frame(&mut app, vec![])), "the options stay closed once Global Edit stops"); // At any width the button either fits inside the bar or is left out, and a wider bar never // leaves it out once a narrower one showed it. - app.run("select.globalEdit", json!({})).unwrap(); let mut seen = false; for width in (600..=2400).step_by(10) { let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width as f32, 300.0)); @@ -1881,3 +1886,51 @@ fn the_control_bar_shows_the_global_edit_options() { } assert!(seen, "a wide bar has room for it"); } + +/// At any width the Control bar shows the inline X, Y, W and H fields whole inside its right margin, +/// or leaves all four out and keeps the Transform link; a wider bar never leaves them out once a +/// narrower one showed them. +#[test] +fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { + crate::i18n::set_current(crate::i18n::Lang::EN); + for count in [1, 2] { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec<_> = (0..count) + .map(|i| app.run("shape.rectangle", json!({"x": 20 + 100 * i, "y": 20, "width": 40, "height": 30})).unwrap()["id"].clone()) + .collect(); + app.run("select.set", json!({ "ids": ids })).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut seen = false; + for width in (600..=2400).step_by(10) { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width as f32, 300.0)); + let mut nodes = Vec::new(); + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(&mut app, ui)); + out.textures_delta.clear(); + nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + } + let spacing = ctx.global_style().spacing.item_spacing.x; + // The right edge of the box of the field its label names. The text box sits inside the + // field's box with the same inset on both sides, and one item spacing after the label. + let right = |name: &str| { + let (id, label) = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::Label && n.value() == Some(name))?; + let input = nodes.iter().find(|(_, n)| n.labelled_by().contains(id)).and_then(|(_, n)| n.bounds())?; + let inset = input.x0 - label.bounds()?.x1 - f64::from(spacing); + Some(input.x1 + inset) + }; + let fields = ["X:", "Y:", "W:", "H:"].map(right); + assert!(fields.iter().all(Option::is_some) || fields.iter().all(Option::is_none), "{count} objects, {width}: {fields:?}"); + assert!(nodes.iter().any(|(_, n)| n.label() == Some("Transform")), "{count} objects, {width}: the Transform link shows"); + // The bar's content ends at its 10-point inner margin. + if let Some(h) = fields[3] { + assert!(h <= f64::from(width) - 10.0, "{count} objects, {width}: H ends at {h}"); + } + assert!(!seen || fields[3].is_some(), "{count} objects, {width}: left out after a narrower bar showed them"); + seen |= fields[3].is_some(); + } + assert!(seen, "{count} objects: a wide bar has room for the fields"); + } +} diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rs index d344f59e7d..84b5f1f01b 100644 --- a/crates/ui-egui/src/credits.rs +++ b/crates/ui-egui/src/credits.rs @@ -316,19 +316,20 @@ fn natural(ui: &egui::Ui, header: RichText, cells: impl Iterator) /// Opening column widths: each column's natural width, with the spare room shared out by `grow`, /// so the columns fill `room` exactly. When there is too little room, only the growing columns -/// give way, down to [`MIN_COLUMN`]. +/// give way, each in proportion to its width above [`MIN_COLUMN`], and none goes below that. fn fit_widths(natural: &[f32], grow: &[f32], room: f32) -> Vec { let spare = room - natural.iter().sum::(); let weight = grow.iter().sum::(); - let flexible: f32 = natural.iter().zip(grow).filter(|(_, g)| **g > 0.0).map(|(w, _)| *w).sum(); + let slack = |w: f32| (w - MIN_COLUMN).max(0.0); + let flexible: f32 = natural.iter().zip(grow).filter(|(_, g)| **g > 0.0).map(|(w, _)| slack(*w)).sum(); natural .iter() .zip(grow) .map(|(w, g)| { - if spare >= 0.0 && weight > 0.0 { + if *g > 0.0 && spare >= 0.0 { w + spare * g / weight } else if *g > 0.0 && flexible > 0.0 { - (w + spare * w / flexible).max(MIN_COLUMN) + w - (-spare).min(flexible) * slack(*w) / flexible } else { *w } @@ -337,26 +338,30 @@ fn fit_widths(natural: &[f32], grow: &[f32], room: f32) -> Vec { } /// A striped table whose columns open at [`fit_widths`], so it fills the width and nothing scrolls -/// sideways. Each column can be dragged wider or narrower at its edge. The last column fills -/// whatever width is left but never shrinks below its opening width, so widening a column grows -/// the table, as in a spreadsheet, instead of crushing the last one: only a table dragged wider -/// than the window scrolls sideways. Text too long for its column is clipped. +/// sideways. Every column, the last included, can be dragged wider or narrower at its right edge: +/// only a table dragged wider than the window scrolls sideways. Text too long for its column is +/// clipped. When a column's natural width or the window changes, the columns go back to a new fit, +/// dropping any dragged widths. fn fitted_table<'a>(ui: &'a mut egui::Ui, id: &str, natural: &[f32], grow: &[f32]) -> egui_extras::TableBuilder<'a> { // Every cell is followed by the item gap, and the vertical scrollbar keeps its margins. let s = ui.spacing(); let gaps = s.item_spacing.x * natural.len() as f32; let bar = s.scroll.bar_width + s.scroll.bar_inner_margin + s.scroll.bar_outer_margin; let widths = fit_widths(natural, grow, (ui.available_width() - gaps - bar).max(0.0)); + // The table keeps its own column widths, so a change in what they were fitted to has to clear + // them. A longer name can leave the fit itself unchanged, and scrolling can nudge the available + // width, so this compares the natural widths and the clip rect, which scrolling never moves. + let fit = egui::Id::unique(("credits_fit", id)); + let measured = (natural.to_vec(), ui.clip_rect().width()); + let refit = ui.data_mut(|d| d.get_temp::<(Vec, f32)>(fit)).as_ref() != Some(&measured); + ui.data_mut(|d| d.insert_temp(fit, measured)); let mut t = egui_extras::TableBuilder::new(ui).id_salt(id).striped(true).resizable(true).auto_shrink([false, false]).max_scroll_height(f32::INFINITY); - let last = widths.len().saturating_sub(1); - for (i, w) in widths.into_iter().enumerate() { - let c = if i == last { - egui_extras::Column::remainder().at_least(w.max(MIN_COLUMN)) - } else { - egui_extras::Column::initial(w).at_least(MIN_COLUMN) - }; - t = t.column(c.clip(true)); + if refit { + t.reset(); + } + for w in widths { + t = t.column(egui_extras::Column::initial(w).at_least(MIN_COLUMN).clip(true)); } t } @@ -631,4 +636,116 @@ mod tests { assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 0.0), [MIN_COLUMN, 40.0, 60.0]); assert_eq!(fit_widths(&[100.0, 40.0], &[0.0, 0.0], 50.0), [100.0, 40.0]); } + + #[test] + fn a_column_at_the_minimum_leaves_the_shortfall_to_the_others() { + let w = fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 140.0); + assert!((w.iter().sum::() - 140.0).abs() < 0.01, "the columns still fit the room: {w:?}"); + assert!(w.iter().all(|c| *c >= MIN_COLUMN), "no column goes below the minimum: {w:?}"); + assert_eq!(fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 0.0), [MIN_COLUMN, MIN_COLUMN, 50.0]); + } + + const WINDOW: f32 = 640.5; + const NATURAL: [f32; 3] = [120.0, 80.0, 80.0]; + const GROW: [f32; 3] = [1.0, 0.0, 0.0]; + + /// One frame of a table long enough to scroll; the rects of its header cells. + fn table_frame(ctx: &egui::Context, width: f32, natural: &[f32], events: Vec) -> Vec { + scrolled_frame(ctx, width, natural, 0.0, events) + } + + /// [`table_frame`], scrolled `offset` points sideways. + fn scrolled_frame(ctx: &egui::Context, width: f32, natural: &[f32], offset: f32, events: Vec) -> Vec { + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 300.0))); + let raw = egui::RawInput { screen_rect, events, ..Default::default() }; + let mut cells = Vec::new(); + let out = ctx.run_ui(raw, |ui| { + cells.clear(); + egui::ScrollArea::horizontal().auto_shrink([false, false]).horizontal_scroll_offset(offset).show(ui, |ui| { + fitted_table(ui, "test", natural, &GROW) + .header(20.0, |mut header| { + for _ in natural { + header.col(|ui| cells.push(ui.max_rect())); + } + }) + .body(|mut body| { + for _ in 0..40 { + body.row(20.0, |mut row| { + for _ in natural { + row.col(|ui| { + ui.label("x"); + }); + } + }); + } + }); + }); + }); + out.drop_without_applying_deltas(); + cells + } + + /// A new context with the table open and settled, and the rects of its header cells. + fn opened_table() -> (egui::Context, Vec) { + let ctx = egui::Context::default(); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let cells = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + (ctx, cells) + } + + /// Drags a column's right edge, which runs midway through the gap after `cell`, then lets go. + fn drag_edge(ctx: &egui::Context, cell: egui::Rect, by: f32) { + use egui::{Event, Modifiers, PointerButton}; + let start = egui::pos2(cell.right() + 4.0, cell.center().y); + let halfway = start + egui::vec2(by / 2.0, 0.0); + let end = start + egui::vec2(by, 0.0); + let moved = Event::PointerMoved; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + for event in [moved(start), button(start, true), moved(halfway), moved(end), button(end, false)] { + table_frame(ctx, WINDOW, &NATURAL, vec![event]); + } + } + + #[test] + fn every_column_can_be_dragged_at_its_right_edge_and_stays_there() { + let (_, opened) = opened_table(); + for (dragged, cell) in opened.iter().enumerate() { + let (ctx, _) = opened_table(); + drag_edge(&ctx, *cell, -30.0); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let after = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + for (column, (was, now)) in opened.iter().zip(&after).enumerate() { + let want = if column == dragged { was.width() - 30.0 } else { was.width() }; + assert!((now.width() - want).abs() < 1.0, "dragging column {dragged}: column {column} is {now:?}, was {was:?}"); + } + } + } + + #[test] + fn a_changed_fit_replaces_the_column_widths() { + let (ctx, opened) = opened_table(); + drag_edge(&ctx, opened[0], -30.0); + let longer_name = table_frame(&ctx, WINDOW, &[200.0, 80.0, 80.0], Vec::new()); + assert!((longer_name[0].width() - opened[0].width()).abs() < 1.0, "a longer name drops a dragged width: {longer_name:?}"); + let wider = table_frame(&ctx, WINDOW, &[120.0, 200.0, 80.0], Vec::new()); + let widths: Vec = wider.iter().map(|c| c.width().round()).collect(); + assert!(widths.ends_with(&[200.0, 80.0]), "a longer cell widens its column: {widths:?}"); + assert!(wider[2].right() < WINDOW, "the table still fits the window: {wider:?}"); + let narrower = table_frame(&ctx, 400.0, &NATURAL, Vec::new()); + assert!(narrower[2].right() < 400.0, "a narrower window refits the table: {narrower:?}"); + } + + #[test] + fn scrolling_sideways_keeps_dragged_widths() { + let (ctx, opened) = opened_table(); + drag_edge(&ctx, opened[0], 100.0); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let dragged = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + assert!((dragged[0].width() - opened[0].width() - 100.0).abs() < 1.0, "the drag took: {dragged:?}"); + for offset in [13.3, 27.77, 41.1, 0.6] { + scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new()); + let scrolled = scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new()); + assert!((scrolled[0].width() - dragged[0].width()).abs() < 1.0, "scrolled {offset}: {scrolled:?}"); + } + } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 67219de40a..099d6db583 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -9,6 +9,7 @@ mod about; pub mod action_batch; pub mod action_new; +pub mod action_playback; pub mod action_set_options; pub mod artboard_options; pub mod blend_options; @@ -63,6 +64,7 @@ pub mod live_paint_selection; pub mod missing_fonts; pub mod missing_links; pub(crate) mod modal; +pub mod navigator_panel_options; pub mod new_brush; pub mod new_color_group; mod new_document; @@ -140,7 +142,7 @@ pub(crate) use export_for_screens::{ import_presets as screen_import_presets, open_assets as open_export_for_screens_assets, preset_list as screen_preset_list, saved_options as screen_saved_options, saved_rows as screen_saved_rows, }; -pub(crate) use form::{humanize, number_list_text, read_number_list, unit_suffix}; +pub(crate) use form::{humanize, number_list_text, plugin_color_button, read_number_list, unit_suffix}; pub(crate) use new_document::preset_name; pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document, preset_card}; pub use png_options::open as open_raster_options; @@ -364,6 +366,7 @@ registry! { ActionBatch: [action_batch::KIND] => action_batch::SPEC, ActionSetOptions: [action_set_options::KIND] => action_set_options::SPEC, ActionNew: [action_new::KIND] => action_new::SPEC, + ActionPlayback: [action_playback::KIND] => action_playback::SPEC, SliceOptions: [slices::OPTIONS] => slices::OPTIONS_SPEC, DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC, EpsOptions: [eps_options::KIND] => eps_options::SPEC, @@ -405,6 +408,7 @@ registry! { PerspectivePlane: [perspective_plane::KIND] => perspective_plane::SPEC, LayerOptions: [layer_options::KIND] => layer_options::SPEC, LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC, + NavigatorPanelOptions: [navigator_panel_options::KIND] => navigator_panel_options::SPEC, PathfinderOptions: [pathfinder_options::KIND] => pathfinder_options::SPEC, RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, @@ -412,6 +416,7 @@ registry! { NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, SwatchLegend: [crate::addons::color::legend::KIND] => crate::addons::color::legend::SPEC, TextTweaker: [crate::addons::typetools::KIND] => crate::addons::typetools::SPEC, + SelectByArtboards: [crate::addons::select::KIND] => crate::addons::select::SPEC, ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE, crate::addons::arrange::OPACITY, crate::addons::arrange::SORT] => crate::addons::arrange::SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/dialogs/action_playback.rs b/crates/ui-egui/src/dialogs/action_playback.rs new file mode 100644 index 0000000000..67d6e35d41 --- /dev/null +++ b/crates/ui-egui/src/dialogs/action_playback.rs @@ -0,0 +1,48 @@ +//! Actions panel menu › Playback Options…: the speed actions play at (`ui.action.playbackOptions`). +//! +//! Fields: `speed` (`accelerated`, `step` or `pause`) and `seconds`, the pause between steps with +//! `pause`. OK sets them; an invalid value is an error, and the dialog stays open. + +use serde_json::{Value, json}; + +use super::DialogSpec; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Playback Options. +pub const KIND: &str = "actionPlayback"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Playback Options").into(), body, confirm, min_width: 260.0, ..DialogSpec::FORM }; + +/// Open Playback Options with the speed and pause actions play with now. +pub fn open(app: &mut VectorcraftApp) { + let o = app.ui.action_playback; + app.ui.dialog = Some(Dialog::new(KIND, json!({"speed": o.speed, "seconds": o.seconds}))); +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let speed = d.str("speed"); + for (value, label) in [("accelerated", tl!("Accelerated")), ("step", tl!("Step by Step"))] { + if widgets::radio(ui, label, speed == value, true) { + d.fields.insert("speed".into(), json!(value)); + } + } + ui.horizontal(|ui| { + let pause = tl!("Pause For"); + if widgets::radio(ui, pause, speed == "pause", true) { + d.fields.insert("speed".into(), json!("pause")); + } + let range = f64::from(*crate::panels::actions::PAUSE_SECONDS.start())..=f64::from(*crate::panels::actions::PAUSE_SECONDS.end()); + if let Some(n) = widgets::range_field_named(ui, "action-pause-seconds", Some(pause), d.f64("seconds", *range.start()), range, "s", 0, 50.0) { + d.fields.insert("seconds".into(), json!(n as u64)); + } + }); + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let params = json!({"speed": d.str("speed"), "seconds": d.fields.get("seconds").cloned().unwrap_or(Value::Null)}); + let r = app.run(crate::panels::actions::PLAYBACK_OPTIONS, params)?; + app.ui.dialog = None; + Ok(r) +} diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 38c425a81b..41530de0e9 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -264,23 +264,29 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { .or_else(|| v.as_str().and_then(|s| s.trim().parse::().ok())) .filter(|n| n.is_finite()) .ok_or_else(|| format!("{label} must be a number"))?; + // Character Style fields use the Character panel's visible ranges. + let max = match key { + "size" => 1296.0, + "leading" => 5000.0, + _ => vectorcraft_doc::MAX_COORD, + }; if ["size", "leading"].contains(&key) && n < 0.1 { return Err(format!("{label} must be a number of at least 0.1")); } - // The limits the document model keeps scales and baseline shift in. - let max = vectorcraft_doc::MAX_COORD; - if ["h_scale", "v_scale"].contains(&key) && !(n > 0.0 && n <= max) { - return Err(format!("{label} must be a number above 0 and at most {max}")); + if ["size", "leading"].contains(&key) && n > max { + return Err(format!("{label} must be a number at most {max}")); } - let min = -max; - if key == "baseline_shift" && !(min..=max).contains(&n) { - return Err(format!("{label} must be a number from {min} to {max}")); + if ["h_scale", "v_scale"].contains(&key) && !(1.0..=10000.0).contains(&n) { + return Err(format!("{label} must be a number from 1 to 10000")); + } + if key == "baseline_shift" && !(-1296.0..=1296.0).contains(&n) { + return Err(format!("{label} must be a number from -1296 to 1296")); } // Weight from 0 to the document limit, a tint from 0% to 100%. let (min, max) = match key { - "stroke_width" => (0.0, max), + "stroke_width" => (0.0, vectorcraft_doc::MAX_COORD), "fill_tint" | "stroke_tint" => (0.0, 100.0), - _ => (min, max), + _ => (0.0, 0.0), }; if ["stroke_width", "fill_tint", "stroke_tint"].contains(&key) && !(min..=max).contains(&n) { return Err(format!("{label} must be a number from {min} to {max}")); @@ -912,14 +918,17 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let params = json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs}); form::preview(app, ui, d, tl!("Character Style Options"), "charStyle.edit", params); } - Err(why) => { - ui.add_space(6.0); - ui.colored_label(crate::theme::Tokens::get(ui.ctx()).error, crate::i18n::message(crate::i18n::current(), &why)); - } + Err(why) => attrs_error(ui, &why), } false } +/// The message `edited_attrs` gave for a field value it does not accept, drawn under the dialog. +pub(crate) fn attrs_error(ui: &mut egui::Ui, why: &str) { + ui.add_space(6.0); + ui.colored_label(crate::theme::Tokens::get(ui.ctx()).error, crate::i18n::message(crate::i18n::current(), why)); +} + fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let attrs = edited_attrs(d)?; form::commit_preview(app, "charStyle.edit", json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs})) @@ -1135,13 +1144,15 @@ mod tests { } #[test] - fn advanced_numbers_outside_their_limits_are_errors() { + fn character_style_numbers_outside_their_limits_are_errors() { for (key, value, message) in [ - ("h_scale", "0", "Horizontal Scale must be a number above 0 and at most 4000000"), - ("h_scale", "-5", "Horizontal Scale must be a number above 0 and at most 4000000"), - ("v_scale", "4000001", "Vertical Scale must be a number above 0 and at most 4000000"), - ("baseline_shift", "4000001", "Baseline Shift must be a number from -4000000 to 4000000"), - ("baseline_shift", "-4000001", "Baseline Shift must be a number from -4000000 to 4000000"), + ("size", "1296.1", "Size must be a number at most 1296"), + ("leading", "5000.1", "Leading must be a number at most 5000"), + ("h_scale", "0", "Horizontal Scale must be a number from 1 to 10000"), + ("h_scale", "0.9", "Horizontal Scale must be a number from 1 to 10000"), + ("v_scale", "10000.1", "Vertical Scale must be a number from 1 to 10000"), + ("baseline_shift", "1296.1", "Baseline Shift must be a number from -1296 to 1296"), + ("baseline_shift", "-1296.1", "Baseline Shift must be a number from -1296 to 1296"), ("rotation", "inf", "Character Rotation must be a number"), ("h_scale", "wide", "Horizontal Scale must be a number"), ] { @@ -1150,10 +1161,15 @@ mod tests { assert_eq!(edited_attrs(&d).unwrap_err(), message, "{key} {value}"); } let mut d = dialog_for(json!({})); - for (key, value) in [("h_scale", "0.5"), ("v_scale", "4000000"), ("baseline_shift", "-4000000"), ("rotation", "-200")] { + for (key, value) in + [("size", "1296"), ("leading", "5000"), ("h_scale", "1"), ("v_scale", "10000"), ("baseline_shift", "-1296"), ("rotation", "-200")] + { d.fields.insert(key.into(), json!(value)); } - assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"h_scale": 0.5, "v_scale": 4000000.0, "baseline_shift": -4000000.0, "rotation": 160.0}))); + assert_eq!( + edited_attrs(&d).unwrap(), + attrs(json!({"size": 1296.0, "leading": 5000.0, "h_scale": 1.0, "v_scale": 10000.0, "baseline_shift": -1296.0, "rotation": 160.0})) + ); } #[test] @@ -1514,6 +1530,40 @@ mod tests { } } + #[test] + fn new_character_style_shows_size_and_leading_errors_before_ok() { + use egui_kittest::kittest::Queryable; + for (key, value) in [("size", json!(0)), ("leading", json!(0.05))] { + let mut app = app(); + app.run("ui.newCharStyle", json!({})).unwrap(); + let why = { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("section".into(), json!("basic")); + d.fields.insert(key.into(), value); + edited_attrs(d).unwrap_err() + }; + let shown = crate::i18n::message(crate::i18n::current(), &why); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + assert!(h.query_by_label(&shown).is_some(), "{key}: {shown} is not shown"); + let app = h.state_mut(); + let styles = app.session.doc().unwrap().doc.char_styles.len(); + assert!(super::super::confirm(app).is_err(), "{key} confirm"); + assert!(app.ui.dialog.is_some(), "{key} dialog stays open"); + assert_eq!(app.session.doc().unwrap().doc.char_styles.len(), styles, "{key} style count"); + } + } + #[test] fn invalid_number_keeps_last_valid_preview() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 15d0b7004d..273c0291ef 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -478,7 +478,11 @@ fn adjust_fields(ui: &mut egui::Ui, d: &mut Dialog) -> bool { for (key, label, width) in [("points", tl!("Points"), 220.0), ("color", tl!("Color"), 120.0)] { if d.fields.contains_key(key) { widgets::label_row(ui, label, LABEL_W, |ui| { - form::text(ui, d, key, width); + if key == "color" { + form::color_text(ui, d, key, width); + } else { + form::text(ui, d, key, width); + } }); } } @@ -710,13 +714,8 @@ fn drop_shadow_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc:: if widgets::radio(ui, tl!("Color"), !darkness, true) { d.fields.insert("shade".into(), json!("color")); } - ui.add_enabled_ui(!darkness, |ui| match d.fields.get("color") { - Some(Value::String(_)) | None => { - form::text(ui, d, "color", 128.0); - } - Some(other) => { - widgets::dim_label(ui, &other.to_string()); - } + ui.add_enabled_ui(!darkness, |ui| { + form::color_text(ui, d, "color", 128.0); }); ui.end_row(); if widgets::radio(ui, tl!("Darkness"), darkness, true) { diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 47567e51e7..004a964903 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -155,6 +155,31 @@ pub(super) fn text(ui: &mut egui::Ui, d: &mut Dialog, key: &str, width: f32) -> text_edit(ui, d, key, width).changed() } +/// A parameter value that is a color object (`{"model": "cmyk", …}`, as Document Color Mode or an +/// imported file stores an effect's color), read as a color. `None` for any other value. +pub(super) fn color_object(v: &Value) -> Option { + v.is_object().then(|| serde_json::from_value(v.clone()).ok()).flatten() +} + +/// [`text`] for a color parameter `key`: a color object ([`color_object`]) shows as its hex and +/// stays as it is until the text is edited; any other value that isn't text shows dimmed. +pub(super) fn color_text(ui: &mut egui::Ui, d: &mut Dialog, key: &str, width: f32) -> bool { + let Some(v) = d.fields.get(key).cloned() else { return text(ui, d, key, width) }; + if let Some(c) = color_object(&v) { + d.fields.insert(key.into(), json!(c.to_hex())); + let changed = text(ui, d, key, width); + if !changed { + d.fields.insert(key.into(), v); + } + return changed; + } + if v.is_string() { + return text(ui, d, key, width); + } + crate::widgets::dim_label(ui, &v.to_string()); + false +} + /// [`text`] for a row whose visible meaning is not the immediately preceding label widget /// (Export for Screens' Range field follows its radio buttons): screen readers name the field /// `name`, already translated. The pending label is still consumed, so it cannot name a later @@ -432,9 +457,19 @@ pub(super) fn param_fields( changed = true; } } - other => { - ui.label(egui::RichText::new(other.to_string()).color(t.text_dim).size(11.0)); - } + // A color object shows as its hex; typing in the field stores the typed text. + other => match color_object(&other) { + Some(c) => { + let mut s = c.to_hex(); + if ui.add(egui::TextEdit::singleline(&mut s).desired_width(140.0)).changed() { + d.fields.insert(k.clone(), json!(s)); + changed = true; + } + } + None => { + ui.label(egui::RichText::new(other.to_string()).color(t.text_dim).size(11.0)); + } + }, } }); ui.end_row(); @@ -598,9 +633,21 @@ fn value_field(ui: &mut egui::Ui, k: &str, label: &str, spec: &ParamSpec, cur: & let typed = crate::widgets::text_field_named(ui, ("plugin-list", k), Some(label), Some(&number_list_text(cur)), 160.0, 1); (typed.and_then(|text| read_number_list(&text, spec)), false) } + ParamSpec::Color { .. } => (plugin_color_button(ui, ("plugin-color", k), cur), false), } } +/// A plug-in `color` parameter's button, showing `cur` (a color object or hex) and opening the color +/// picker → the color picked, as the color object the plug-in gets: the picker's display sRGB in the +/// working RGB space, so the color shows as it was picked whatever the working profile. +pub(crate) fn plugin_color_button(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, cur: &Value) -> Option { + let [r, g, b, _] = vectorcraft_plugins::manifest::color_value(cur).unwrap_or_default().to_rgba8(1.0); + let mut rgb = [r, g, b]; + let changed = ui.push_id(id, |ui| ui.color_edit_button_srgb(&mut rgb).changed()).inner; + let picked = || crate::screen_color::sampled(&vectorcraft_color::cms::active(), rgb.map(|v| f32::from(v) / 255.0)); + changed.then(|| serde_json::to_value(picked()).unwrap_or_default()) +} + /// A `numberList` value as its field shows it: "45, 135". pub(crate) fn number_list_text(cur: &Value) -> String { let numbers: Vec = cur.as_array().into_iter().flatten().filter_map(Value::as_f64).map(number_text).collect(); @@ -755,7 +802,8 @@ pub(super) fn slider_rail_named( range: std::ops::RangeInclusive, track: &dyn Fn(f32) -> egui::Color32, ) { - let shown = crate::widgets::SliderValue::number(d.f64(key, 0.0), range.clone()); + // Whole numbers, as a drag sets them. + let shown = crate::widgets::SliderValue { decimals: Some(0), ..crate::widgets::SliderValue::number(d.f64(key, 0.0), range.clone()) }; slider_rail_valued(ui, d, key, name, range, Some(shown), track); } @@ -778,8 +826,9 @@ pub(super) fn slider_rail_valued( let units = shown.as_ref().map(|s| s.range.clone()); let (dragged, _, keyed) = crate::widgets::color_slider_stepped(ui, ("dlg-slider", key), name, shown, ((v - min) / (max - min)) as f32, SLIDER_WIDTH, track); - let keyed = - keyed.zip(units).map(|(k, u)| if u == range { k } else { (min + (k - u.start()) / (u.end() - u.start()) * (max - min)).clamp(min, max) }); + // Not clamped to the rail: a screen reader's set value can reach a number past it that the + // field holds. + let keyed = keyed.zip(units).map(|(k, u)| if u == range { k } else { min + (k - u.start()) / (u.end() - u.start()) * (max - min) }); if let Some(n) = dragged.map(|x| (min + x as f64 * (max - min)).round()).or(keyed).filter(|n| *n != held) { d.fields.insert(key.into(), json!(n)); } diff --git a/crates/ui-egui/src/dialogs/live_paint_bucket.rs b/crates/ui-egui/src/dialogs/live_paint_bucket.rs index e9267b0f39..c040cdcc31 100644 --- a/crates/ui-egui/src/dialogs/live_paint_bucket.rs +++ b/crates/ui-egui/src/dialogs/live_paint_bucket.rs @@ -13,7 +13,7 @@ use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_BUCKET_WIDTH_RANGE; -use super::tile_edge_color::resolve; +use super::tile_edge_color::{checked, resolve}; use super::{DialogSpec, form, run_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -78,8 +78,11 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// OK: set the tool's options. +/// OK: set the tool's options, or an error for a `color` that is not a color. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.contains_key("color") { + checked(&d.str("color"))?; + } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) } @@ -148,4 +151,24 @@ mod tests { app.select_tool(TOOL); assert!(!hover(&mut app, 151.0).iter().any(|o| matches!(o, Overlay::Path { .. }))); } + + /// A highlight color with an alpha part is refused and leaves the tool's options as they were; + /// `#rrggbb` still sets them. + #[test] + fn a_color_with_an_alpha_part_is_refused() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("color".into(), json!("#ff000080")); + d.fields.insert("width".into(), json!(8)); + let err = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(err, "`#ff000080` is not a colour (#rrggbb or a preset name)"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + let o = app.session.tool_options_of(TOOL); + assert_eq!((o["color"].as_str(), o["width"].as_f64()), (Some("#ff2a2a"), Some(4.0)), "nothing changes"); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of(TOOL)["color"], json!("#ff0000")); + } } diff --git a/crates/ui-egui/src/dialogs/live_paint_gaps.rs b/crates/ui-egui/src/dialogs/live_paint_gaps.rs index 98c7abfba5..e01a08e9a4 100644 --- a/crates/ui-egui/src/dialogs/live_paint_gaps.rs +++ b/crates/ui-egui/src/dialogs/live_paint_gaps.rs @@ -15,7 +15,7 @@ use vectorcraft_doc::{GapSize, LAYER_COLORS}; use vectorcraft_geom::{BezPath, Point}; use vectorcraft_tools::Overlay; -use super::tile_edge_color::resolve; +use super::tile_edge_color::{checked, has_alpha, resolve}; use super::{DialogSpec, form}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -116,7 +116,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); ui.add_space(6.0); form::check(ui, d, "closeGaps", tl!("Close Gaps With Paths")); - let p = params(d); + let mut p = params(d); + // OK refuses a color with an alpha part, so the preview leaves each group's own color. + if has_alpha(&d.str("color")) { + p["color"] = Value::Null; + } if let Some(r) = form::preview_result(app, ui, d, "Gap Options", CMD, p) { d.fields.insert(GAPS.into(), r["gaps"].clone()); } @@ -127,6 +131,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + checked(&d.str("color"))?; form::commit_preview(app, CMD, params(d)) } @@ -134,7 +139,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { /// off or another dialog is open). pub(crate) fn overlays(app: &VectorcraftApp) -> Vec { let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == KIND && d.bool("preview")) else { return vec![] }; - let [r, g, b, _] = resolve(&d.str("color")).unwrap_or(Color::BLACK).to_rgba8(1.0); + let [r, g, b, _] = checked(&d.str("color")).unwrap_or(Color::BLACK).to_rgba8(1.0); let gaps = d.fields.get(GAPS).and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); gaps.iter() .filter_map(|gap| { @@ -257,4 +262,57 @@ mod tests { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.str("size"), d.f64("custom", 0.0)), ("large".to_string(), GapSize::LARGE)); } + + /// A Gap Preview Color with an alpha part is refused and leaves the group's options as they + /// were; `#rrggbb` still sets them. + #[test] + fn a_color_with_an_alpha_part_is_refused() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let g = app.run("livePaint.make", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("color".into(), json!("#ff000080")); + d.fields.insert("detect".into(), json!(true)); + let depth = app.session.doc().unwrap().history.undo.len(); + let err = crate::dialogs::confirm(&mut app).unwrap_err(); + assert_eq!(err, "`#ff000080` is not a colour (#rrggbb or a preset name)"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + assert_eq!((options(&app, g), app.session.doc().unwrap().history.undo.len()), (GapOptions::default(), depth), "nothing changes"); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(options(&app, g).color, [0xff, 0, 0]); + } + + /// With Preview on, a Gap Preview Color with an alpha part is not previewed: the group keeps + /// its own color, the gaps draw in black, OK refuses the color and Cancel rolls the preview back. + #[test] + fn a_color_with_an_alpha_part_is_not_previewed() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + // An open path round a square, its end 2 pt short of its start. + let anchors = [(0, 0), (100, 0), (100, 100), (0, 100), (0, 2)].map(|(x, y)| json!({"x": x, "y": y})); + let p = app.run("path.create", json!({ "anchors": anchors })).unwrap(); + app.run("select.set", json!({"ids": [p["id"]]})).unwrap(); + let g = app.run("livePaint.make", json!({})).unwrap()["id"].as_u64().unwrap(); + let own = options(&app, g).color; + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("preview".into(), json!(true)); + d.fields.insert("detect".into(), json!(true)); + d.fields.insert("color".into(), json!("#ff000080")); + let depth = app.session.doc().unwrap().history.undo.len(); + frame(&mut app); + assert_eq!((options(&app, g).detect, options(&app, g).color), (true, own), "the group keeps its own color"); + let shown = overlays(&app); + assert!(matches!(&shown[..], [Overlay::Path { color: [0, 0, 0], .. }]), "{shown:?}"); + let err = crate::dialogs::confirm(&mut app).unwrap_err(); + assert_eq!(err, "`#ff000080` is not a colour (#rrggbb or a preset name)"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + crate::dialogs::cancel(&mut app); + let undo = app.session.doc().unwrap().history.undo.len(); + assert_eq!((options(&app, g), undo), (GapOptions::default(), depth), "Cancel rolls the preview back"); + } } diff --git a/crates/ui-egui/src/dialogs/live_paint_selection.rs b/crates/ui-egui/src/dialogs/live_paint_selection.rs index 8ba8cf49b4..a1a91ad2b7 100644 --- a/crates/ui-egui/src/dialogs/live_paint_selection.rs +++ b/crates/ui-egui/src/dialogs/live_paint_selection.rs @@ -12,7 +12,7 @@ use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_SELECT_WIDTH_RANGE; -use super::tile_edge_color::resolve; +use super::tile_edge_color::{checked, resolve}; use super::{DialogSpec, form, run_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -74,8 +74,11 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// OK: set the tool's options. +/// OK: set the tool's options, or an error for a `color` that is not a color. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.contains_key("color") { + checked(&d.str("color"))?; + } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) } @@ -139,4 +142,24 @@ mod tests { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.bool("selectFills"), d.str("color")), (false, "#4fff4f".to_string())); } + + /// A highlight color with an alpha part is refused and leaves the tool's options as they were; + /// `#rrggbb` still sets them. + #[test] + fn a_color_with_an_alpha_part_is_refused() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("color".into(), json!("#ff000080")); + d.fields.insert("width".into(), json!(8)); + let err = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(err, "`#ff000080` is not a colour (#rrggbb or a preset name)"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + let o = app.session.tool_options_of(TOOL); + assert_eq!((o["color"].as_str(), o["width"].as_f64()), (Some("#ff2a2a"), Some(4.0)), "nothing changes"); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of(TOOL)["color"], json!("#ff0000")); + } } diff --git a/crates/ui-egui/src/dialogs/navigator_panel_options.rs b/crates/ui-egui/src/dialogs/navigator_panel_options.rs new file mode 100644 index 0000000000..c3582ae59a --- /dev/null +++ b/crates/ui-egui/src/dialogs/navigator_panel_options.rs @@ -0,0 +1,101 @@ +//! Navigator panel › Panel Options…: the color the view box is drawn in, a preset or a custom +//! color, and Draw Dashed Lines as Solid Lines for the thumbnail. +//! +//! Fields: `color` (`#rrggbb`, or a preset's name such as "Light Red") and `solidDashes`. OK runs +//! `ui.navigatorPanelOptions` with them (kept with the UI state). + +use serde_json::{Value, json}; +use vectorcraft_color::Color; + +use super::swatch_options::{grid, label}; +use super::{DialogSpec, run_and_close}; +use crate::panels::navigator::{VIEW_BOX_RED, resolve, view_box_colors}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of the Navigator Panel Options. +pub const KIND: &str = "navigatorPanelOptions"; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Navigator Panel Options").into(), body, confirm, min_width: 300.0, ..DialogSpec::FORM }; + +/// `ui.navigatorPanelOptions` without options: open the dialog on the panel's options. +pub fn open(app: &mut VectorcraftApp) -> Result { + let o = &app.ui.navigator_panel; + app.ui.dialog = Some(Dialog::new(KIND, json!({ "color": o.color, "solidDashes": o.solid_dashes }))); + Ok(Value::Null) +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let [r, g, b] = resolve(&d.str("color")).unwrap_or(VIEW_BOX_RED); + let presets: Vec<(&str, [u8; 3])> = view_box_colors().collect(); + let preset = presets.iter().position(|(_, c)| *c == [r, g, b]); + let names: Vec<&str> = presets.iter().map(|(n, _)| *n).chain(["Custom"]).collect(); + grid(ui, |ui| { + label(ui, tl!("Color:")); + ui.horizontal(|ui| { + if let Some((_, [r, g, b])) = + widgets::dropdown(ui, "navigator-view-box", names[preset.unwrap_or(presets.len())], &names, 140.0).and_then(|i| presets.get(i)) + { + d.fields.insert("color".into(), json!(Color::rgb8(*r, *g, *b).to_hex())); + } + // Any other color (the preset list shows Custom then). + let mut rgb = [r, g, b]; + if ui.color_edit_button_srgb(&mut rgb).changed() { + d.fields.insert("color".into(), json!(Color::rgb8(rgb[0], rgb[1], rgb[2]).to_hex())); + } + }); + ui.end_row(); + }); + ui.add_space(8.0); + let solid = d.bool("solidDashes"); + if widgets::check(ui, tl!("Draw Dashed Lines as Solid Lines"), solid, true) { + d.fields.insert("solidDashes".into(), json!(!solid)); + } + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let params = json!({ "color": d.fields.get("color").cloned().unwrap_or(Value::Null), "solidDashes": d.bool("solidDashes") }); + run_and_close(app, "ui.navigatorPanelOptions", params) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + /// The dialog opens on the panel's options (Light Red and solid dashes off by default), and OK + /// sets a preset's or a custom color and Draw Dashed Lines as Solid Lines, kept with the UI + /// state; a value that is not a color is refused and leaves the options as they were. + #[test] + fn panel_options_set_the_view_box_color_and_solid_dashes() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.navigatorPanelOptions", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.str("color"), d.bool("solidDashes")), (KIND, "#ff3030".to_string(), false)); + // Drawn headlessly in the shared frame: the preset's name shows. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let set = |app: &mut VectorcraftApp, color: &str, solid: bool| { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("color".into(), json!(color)); + d.fields.insert("solidDashes".into(), json!(solid)); + super::super::confirm(app) + }; + assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true})); + assert!(app.ui.dialog.is_none()); + app.run("ui.navigatorPanelOptions", json!({})).unwrap(); + set(&mut app, "#0000FF", true).unwrap(); + assert_eq!(app.ui.navigator_panel.color, "#0000ff"); + app.run("ui.navigatorPanelOptions", json!({})).unwrap(); + assert!(set(&mut app, "nope", false).is_err()); + assert!(app.ui.navigator_panel.solid_dashes && app.ui.navigator_panel.color == "#0000ff", "a refused value changes nothing"); + let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); + assert_eq!(back.navigator_panel, app.ui.navigator_panel, "kept with the UI state"); + let old: crate::UiState = serde_json::from_value(json!({})).unwrap(); + assert_eq!(old.navigator_panel, crate::panels::navigator::PanelOptions::default(), "UI state saved without them"); + } +} diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 5d53ebe73e..1a4c393892 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -41,7 +41,8 @@ const PARAMS: [&str; 12] = [ "rasterEffectsPpi", "previewMode", ]; -/// The preset the fields were last filled from (its fields as `apply` set them). +/// The preset the fields were last filled from, as `apply` set them; a Recent or Saved card keeps +/// its own units here, which the units chosen in Preset Details don't change. const APPLIED: &str = "__applied"; /// Save Preset's name field is showing. const SAVING: &str = "__saving"; @@ -257,21 +258,50 @@ fn presets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = egui::vec2(12.0, 12.0); let (w, h, preset, units) = (d.f64("width", 0.0), d.f64("height", 0.0), d.str("preset"), unit(d)); + // The fields were last filled from this preset's card; Recent keeps one entry per size + // and units, so the units tell two entries of one size apart. + let chosen = d + .fields + .get(APPLIED) + .filter(|a| a.get("preset").and_then(Value::as_str) == Some(preset.as_str())) + .and_then(Value::as_object) + .cloned(); for s in &list { - // The built-in presets' cards show the chosen orientation (square sizes have none) - // and the units chosen in Preset Details; choosing one keeps both. Recent and Saved - // show each entry as it was made, so a portrait and a landscape A3 are two cards - // (#2860). - let mut s = DocSettings { units, ..s.clone() }; - if cat > 1 && ((w > h && s.height > s.width) || (h > w && s.width > s.height)) { - std::mem::swap(&mut s.width, &mut s.height); + // The built-in presets' cards show the chosen orientation (square sizes have none); + // Recent and Saved show each entry as it was made, so a portrait and a landscape A3 + // are two cards (#2860). + let mut card = s.clone(); + if cat > 1 && ((w > h && card.height > card.width) || (h > w && card.width > card.height)) { + std::mem::swap(&mut card.width, &mut card.height); } - let selected = d.fields.contains_key(APPLIED) && s.name == preset && s.width == w && s.height == h; - let card = preset_card(ui, &s, selected); - if card.clicked() || card.double_clicked() { - apply(d, &s); + // The built-in presets all share the units chosen in Preset Details. + if cat > 1 { + card.units = units; } - create |= card.double_clicked(); + let selected = chosen.as_ref().is_some_and(|a| { + a.get("preset").and_then(Value::as_str) == Some(card.name.as_str()) + && a.get("width").and_then(Value::as_f64) == Some(card.width) + && a.get("height").and_then(Value::as_f64) == Some(card.height) + && (cat > 1 || a.get("units").and_then(Value::as_str) == Some(s.units.label())) + }); + // The chosen card shows the units chosen in Preset Details, which the new document + // will have (#2078); the others keep their own, so choosing one document's units + // doesn't restyle the whole tab. + if selected { + card.units = units; + } + let resp = preset_card(ui, &card, selected); + if resp.clicked() || resp.double_clicked() { + apply(d, &card); + // The card is still the entry it was, whatever units it shows: its own units say + // which entry it is, so a chosen card stays chosen after a units change. + if cat < 2 + && let Some(Value::Object(a)) = d.fields.get_mut(APPLIED) + { + a.insert("units".into(), json!(s.units.label())); + } + } + create |= resp.double_clicked(); } }); }); diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index 3a769670f5..76b280b017 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -80,6 +80,9 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } }); super::char_style_options::reset_button(ui, d); + if let Err(why) = super::char_style_options::edited_attrs(d) { + super::char_style_options::attrs_error(ui, &why); + } return false; } grid(ui, |ui| { diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 2cc994be40..40a8db9cff 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -154,17 +154,23 @@ fn packaged(app: &mut VectorcraftApp, r: Result, web: bool, later let missing = r["missingLinks"].as_array().map_or(0, Vec::len); // The fonts left out: their license doesn't allow it, or they aren't on this computer. let fonts = r["skippedFonts"].as_array().into_iter().flatten().filter_map(|f| f["font"].as_str()).collect::>().join(", "); - let shown_note = package_status_note(missing, &fonts); let n = n as u64; if web { let (name, data) = (r["name"].as_str().unwrap_or("package.zip"), r["dataBase64"].as_str().unwrap_or_default()); let bytes = vectorcraft_format::base64_decode(data).ok_or("the package came back damaged")?; io::write_named(app, None, name, &bytes)?; - app.status(package_status(n, None, &shown_note)); + // The web shows no dialog, so the status line names every font left out. + app.status(package_status(n, None, &package_status_note(missing, &fonts))); return Ok(r); } let folder = r["folder"].as_str().unwrap_or_default().to_string(); - app.status(package_status(n, Some(&folder), &shown_note)); + // A dialog open now (another one, after a package written in the background) stays, and no + // dialog names the fonts left out, so the status line names every one of them. Otherwise the + // dialog names them all, and the status line may cut the list short. + let asks = app.ui.dialog.is_none(); + let listed = if asks { status_fonts(&fonts) } else { fonts.clone() }; + app.status(package_status(n, Some(&folder), &package_status_note(missing, &listed))); + let shown_note = package_dialog_note(missing, &fonts); let detail = if shown_note.is_empty() { crate::i18n::fmt( &crate::i18n::tn(n, "{n} file in {folder}. Show the package folder?", "{n} files in {folder}. Show the package folder?"), @@ -176,7 +182,7 @@ fn packaged(app: &mut VectorcraftApp, r: Result, web: bool, later &[("folder", &folder), ("note", &shown_note)], ) }; - if app.ui.dialog.is_none() { + if asks { ask(app, tl!("Package created"), &detail, "file.showPackage", json!({ "folder": folder })); } Ok(r) @@ -184,9 +190,10 @@ fn packaged(app: &mut VectorcraftApp, r: Result, web: bool, later /// The status bar's line for a package of `n` files written to `folder` (`None`: the web's /// download), with `note` from [`package_status_note`] when it isn't empty. With a note and a -/// folder, the note comes before the folder and the folder ends the line. Each catalog also has -/// `@msgplural` rows for the English line, shown after a language switch; the folder takes the rest -/// of the line after `) in `, so a folder name with spaces or parentheses stays whole. +/// folder, the note comes before the folder and the folder ends the line. The line is English +/// (the status bar translates it when it draws it): each catalog has `@msgplural` rows for it, and +/// the folder takes the rest of the line after `) in `, so a folder name with spaces or parentheses +/// stays whole. pub(super) fn package_status(n: u64, folder: Option<&str>, note: &str) -> String { let (one, other) = match (folder.is_some(), note.is_empty()) { (false, true) => ("Packaged {n} file", "Packaged {n} files"), @@ -194,20 +201,50 @@ pub(super) fn package_status(n: u64, folder: Option<&str>, note: &str) -> String (true, true) => ("Packaged {n} file in {folder}", "Packaged {n} files in {folder}"), (true, false) => ("Packaged {n} file {note} in {folder}", "Packaged {n} files {note} in {folder}"), }; - crate::i18n::fmt(&crate::i18n::tn(n, one, other), &[("folder", folder.unwrap_or_default()), ("note", note)]) + crate::i18n::msg_n(n, one, other, &[("folder", folder.unwrap_or_default()), ("note", note)]) } -/// Parenthetical notes in a package status (`(2 linked files not found)` …), -/// joined with spaces and without a leading space (#3494). +/// Parenthetical notes in a package status (`(2 linked files not found)` …), in English, +/// joined with spaces and without a leading space (#3494). The catalogs' `@msg` and `@msgplural` +/// rows for each note, and for one or two notes in parentheses, translate them where the status +/// bar draws the line. pub(super) fn package_status_note(missing: usize, fonts: &str) -> String { - let mut parts = Vec::new(); - if missing > 0 { - parts.push(format!("({})", crate::i18n::tn(missing as u64, "{n} linked file not found", "{n} linked files not found"))); + let missing = (missing > 0).then(|| crate::i18n::msg_n(missing as u64, "{n} linked file not found", "{n} linked files not found", &[])); + join_notes(missing, (!fonts.is_empty()).then(|| format!("fonts not copied: {fonts}"))) +} + +/// The most bytes of font names a package status lists next to the dialog that names them all. +const STATUS_FONTS: usize = 500; + +/// `fonts` (names joined with `, `) as the desktop's status line lists them while the Package +/// created dialog names them all: whole, or the names that fit in [`STATUS_FONTS`] bytes followed +/// by `, …`, so the line stays short enough for the status bar to translate it. +pub(super) fn status_fonts(fonts: &str) -> String { + if fonts.len() <= STATUS_FONTS { + return fonts.to_string(); } - if !fonts.is_empty() { - parts.push(format!("({})", crate::i18n::fmt(tl!("fonts not copied: {fonts}"), &[("fonts", fonts)]))); + let mut kept = String::new(); + for name in fonts.split(", ") { + if kept.len() + name.len() + 2 > STATUS_FONTS { + break; + } + if !kept.is_empty() { + kept.push_str(", "); + } + kept.push_str(name); } - parts.join(" ") + if kept.is_empty() { "…".to_string() } else { format!("{kept}, …") } +} + +/// [`package_status_note`] in the interface language, for the dialog shown when the package is made. +pub(super) fn package_dialog_note(missing: usize, fonts: &str) -> String { + let missing = (missing > 0).then(|| crate::i18n::tn(missing as u64, "{n} linked file not found", "{n} linked files not found")); + join_notes(missing, (!fonts.is_empty()).then(|| crate::i18n::fmt(tl!("fonts not copied: {fonts}"), &[("fonts", fonts)]))) +} + +/// Each note in parentheses, joined with spaces. +fn join_notes(missing: Option, fonts: Option) -> String { + [missing, fonts].into_iter().flatten().map(|note| format!("({note})")).collect::>().join(" ") } /// `file.showPackage {folder}`: show a package folder in the file manager. diff --git a/crates/ui-egui/src/dialogs/shape_builder_options.rs b/crates/ui-egui/src/dialogs/shape_builder_options.rs index 2262c94297..9393e0707e 100644 --- a/crates/ui-egui/src/dialogs/shape_builder_options.rs +++ b/crates/ui-egui/src/dialogs/shape_builder_options.rs @@ -13,7 +13,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; -use super::tile_edge_color::resolve; +use super::tile_edge_color::{checked, resolve}; use super::{DialogSpec, form, run_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -118,8 +118,11 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// OK: set the Shape Builder's options. +/// OK: set the Shape Builder's options, or an error for a `highlightColor` that is not a color. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.contains_key("highlightColor") { + checked(&d.str("highlightColor"))?; + } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); run_and_close(app, "tool.setOption", json!({ "tool": "shapeBuilder", "values": values })) } @@ -251,6 +254,25 @@ mod tests { assert_eq!(bounds, vec![[100.0, 100.0, 300.0, 100.0], [100.0, 100.0, 300.0, 200.0]]); } + /// A highlight color with an alpha part is refused and leaves the tool's options as they were; + /// `#rrggbb` still sets them. + #[test] + fn a_highlight_color_with_an_alpha_part_is_refused() { + let mut app = app(); + app.run("tool.options", json!({"tool": "shapeBuilder"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("highlightColor".into(), json!("#ff000080")); + d.fields.insert("highlightFill".into(), json!(false)); + let err = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(err, "`#ff000080` is not a colour (#rrggbb or a preset name)"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + let o = app.session.tool_options_of("shapeBuilder"); + assert_eq!((o["highlightColor"].as_str(), o["highlightFill"].as_bool()), (Some("#ff4f4f"), Some(true)), "nothing changes"); + app.ui.dialog.as_mut().unwrap().fields.insert("highlightColor".into(), json!("#00ff00")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of("shapeBuilder")["highlightColor"], json!("#00ff00")); + } + #[test] fn a_straight_line_drag_merges_only_the_regions_the_line_crosses() { // A wide rectangle and a tall one over the middle of its top edge: three regions, the wide diff --git a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs index d9665c2dc2..6b16fe6eb1 100644 --- a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs +++ b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs @@ -70,23 +70,28 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// `text.setFormat` parameters: the fields that differ from the values the dialog opened with, /// in points (a length typed with its unit, "1 mm", is converted) and kept within -1296..1296. -fn params(d: &Dialog) -> Map { +/// A blank field is left alone; a field that is not a length is an error. +fn params(d: &Dialog) -> Result, String> { let initial = d.fields.get(INITIAL).and_then(Value::as_object); let mut p = Map::new(); - for key in KEYS { - if !d.fields.contains_key(key) { - continue; - } - let v = d.f64(key, 0.0).clamp(*RANGE.start(), *RANGE.end()); + for (key, label) in KEYS.into_iter().zip(["Up/Down", "Left/Right"]) { + let v = match d.fields.get(key) { + None | Some(Value::Null) => continue, + Some(Value::String(s)) if s.trim().is_empty() => continue, + Some(Value::Number(n)) => n.as_f64(), + Some(Value::String(s)) => vectorcraft_doc::Unit::Points.parse(s), + Some(_) => None, + }; + let v = v.filter(|v| v.is_finite()).ok_or_else(|| format!("{label} must be a number"))?.clamp(*RANGE.start(), *RANGE.end()); if initial.and_then(|m| m.get(key)).and_then(Value::as_f64) != Some(v) { p.insert(key.into(), json!(v)); } } - p + Ok(p) } fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let p = params(d); + let p = params(d)?; app.ui.dialog = None; if p.is_empty() { return Ok(Value::Null); @@ -177,6 +182,30 @@ mod tests { assert_eq!(offsets(&app, id), [(0.0, 0.0)]); } + /// OK with a value that is not a length returns an error, keeps the dialog open and leaves + /// the characters alone; a blank field leaves its value alone. + #[test] + fn tate_chu_yoko_settings_dialog_rejects_a_value_that_is_not_a_length() { + let (mut app, id) = app(); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 4, "tcyUpDown": 4, "tcyLeftRight": 2})).unwrap(); + for (key, bad, message) in + [("tcyUpDown", json!("invalid"), "Up/Down must be a number"), ("tcyLeftRight", json!(true), "Left/Right must be a number")] + { + app.run("ui.tateChuYokoSettings", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert(key.into(), bad); + assert_eq!(super::super::confirm(&mut app), Err(message.to_string())); + assert!(app.ui.dialog.is_some()); + assert_eq!(offsets(&app, id), [(4.0, 2.0)]); + app.ui.dialog = None; + } + app.run("ui.tateChuYokoSettings", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("tcyUpDown".into(), json!(" ")); + d.fields.insert("tcyLeftRight".into(), json!(7)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(offsets(&app, id), [(4.0, 7.0)]); + } + /// While the Type tool edits text, OK sets the selected characters and returns the result. #[test] fn tate_chu_yoko_settings_dialog_sets_the_range_the_type_tool_selects() { diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4fc17b097e..c8b0bf6e21 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -199,6 +199,33 @@ fn effect_dialog_refuses_a_color_it_cannot_draw() { } } +/// After File › Document Color Mode, a Drop Shadow's, an Outer Glow's and a Shift to Color's +/// dialog show the converted color as its hex in an editable field, and OK without editing it +/// keeps the color. +#[test] +fn effect_dialogs_edit_a_color_that_document_color_mode_converted() { + for effect in ["stylize.dropShadow", "stylize.outerGlow", "adjust.shiftToColor"] { + let mut app = app(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("effect.apply", json!({"ids": [id], "effect": effect, "item": null, "params": {"color": "#ff0000"}})).unwrap(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let color = |app: &VectorcraftApp| { + app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params["color"].clone() + }; + let converted = color(&app); + let hex = serde_json::from_value::(converted.clone()) + .unwrap_or_else(|e| panic!("{effect}: {converted}: {e}")) + .to_hex(); + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert!(text.lines().any(|l| l.trim() == hex), "{effect}: no {hex} in {text}"); + assert!(!text.contains("\"model\""), "{effect}: {text}"); + confirm(&mut app).unwrap(); + assert_eq!(color(&app), converted, "{effect}"); + } +} + #[test] fn raster_filter_dialogs_preview_and_apply() { for (effect, key, value) in [ @@ -638,6 +665,35 @@ fn plugin_integer_field_with_small_bounds_keeps_numeric_editing() { } } +/// A plug-in's `color` parameter shows as a color button filled with its value, whether the value +/// is a color object or a hex string. +#[test] +fn plugin_color_parameter_shows_a_color_button() { + fn filled(shape: &egui::Shape, c: egui::Color32) -> bool { + match shape { + egui::Shape::Rect(r) => r.fill == c, + egui::Shape::Vec(shapes) => shapes.iter().any(|s| filled(s, c)), + _ => false, + } + } + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let m = vectorcraft_plugins::Manifest::parse( + br##"{"id":"test.grid","name":"Grid","kind":"filter","params":{"line":{"type":"color","default":"#000000"}}}"##, + ) + .unwrap(); + let want = egui::Color32::from_rgb(0x3a, 0x7b, 0xd5); + for cur in [json!({"model": "rgb", "r": 0x3a as f32 / 255.0, "g": 0x7b as f32 / 255.0, "b": 0xd5 as f32 / 255.0}), json!("#3a7bd5")] { + let mut d = Dialog::new(plugin::KIND, json!({ "line": cur })); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + form::schema_rows(ui, &mut d, &m); + }); + out.textures_delta.clear(); + assert!(out.shapes.iter().any(|s| filled(&s.shape, want)), "{cur}"); + } +} + #[test] fn a_dialog_opens_with_its_first_field_focused_so_typing_and_enter_apply() { let mut app = app(); @@ -1988,6 +2044,102 @@ fn the_blob_brush_tip_preview_is_a_named_slider_with_arrow_keys() { assert_eq!(angle(&app), -44.0, "the drag gives the preview the focus"); } +/// Screen readers can set the Blob Brush tip preview's Angle to a number: the slider offers the +/// set-value action, a fraction rounds to the whole degrees the field shows, a number past -180° to +/// 180° sets the nearer end, the last request in a frame wins, and a value that is not a finite +/// number leaves the Angle as it is. On a field past its rail's end, a set value can go as far as +/// the field's number. +#[test] +fn screen_readers_set_a_dialog_slider_number() { + use egui::accesskit::{Action, ActionData, ActionRequest, TreeId}; + let mut app = app(); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + let angle = |app: &VectorcraftApp| app.ui.dialog.as_ref().expect("Blob Brush Tool Options is open").f64("angle", f64::NAN); + let mut f = Frames::new(); + f.run(&mut app, vec![]); + let out = f.run(&mut app, vec![]); + let (node, ..) = slider_node(&out, "Angle"); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let advertised = nodes.iter().find(|(id, _)| *id == node).is_some_and(|(_, n)| n.supports_action(Action::SetValue)); + assert!(advertised, "the Angle slider offers the set-value action"); + let set = |value: f64| { + egui::Event::AccessKitActionRequest(ActionRequest { + action: Action::SetValue, + target_node: node, + target_tree: TreeId::ROOT, + data: Some(ActionData::NumericValue(value)), + }) + }; + f.run(&mut app, vec![set(30.0)]); + assert_eq!(angle(&app), 30.0); + f.run(&mut app, vec![set(12.4)]); + assert_eq!(angle(&app), 12.0, "the field shows whole degrees"); + let shown = crate::widgets::SliderValue::field(12.5, -180.0..=180.0, "°", 0).value; + f.run(&mut app, vec![set(12.5)]); + assert_eq!(angle(&app), shown, "as the field shows 12.5"); + f.run(&mut app, vec![set(500.0)]); + assert_eq!(angle(&app), 180.0, "past the end"); + f.run(&mut app, vec![set(-12.0), set(-90.0)]); + assert_eq!(angle(&app), -90.0, "the last request"); + f.run(&mut app, vec![set(f64::NAN)]); + assert_eq!(angle(&app), -90.0, "not a number"); + f.run(&mut app, vec![set(30.0), set(f64::INFINITY)]); + assert_eq!(angle(&app), -90.0, "the last request is not a finite number"); + let empty = ActionRequest { action: Action::SetValue, target_node: node, target_tree: TreeId::ROOT, data: None }; + f.run(&mut app, vec![set(30.0), egui::Event::AccessKitActionRequest(empty)]); + assert_eq!(angle(&app), -90.0, "the last request has no number"); + // A field past its rail's end extends the range screen readers get, and a set value can go + // that far: Transform Each's Horizontal Scale at 300% on a rail that ends at 200%. + app.ui.dialog = None; + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + app.ui.dialog.as_mut().expect("Transform Each is open").fields.insert("scaleH".into(), json!(300)); + let scale = |app: &VectorcraftApp| app.ui.dialog.as_ref().expect("Transform Each is open").f64("scaleH", f64::NAN); + f.run(&mut app, vec![]); + let out = f.run(&mut app, vec![]); + let (node, ..) = slider_node(&out, "Horizontal:"); + let set = |value: f64| { + egui::Event::AccessKitActionRequest(ActionRequest { + action: Action::SetValue, + target_node: node, + target_tree: TreeId::ROOT, + data: Some(ActionData::NumericValue(value)), + }) + }; + f.run(&mut app, vec![set(250.0)]); + assert_eq!(scale(&app), 250.0, "within the range screen readers get"); + f.run(&mut app, vec![set(400.0)]); + assert_eq!(scale(&app), 250.0, "past 250%, the range's end now"); + // The same for a Move slider in millimeters, whose rail ends at 1000 pt: with the field at + // 1200 pt, 400 mm sets about 1134 pt. + app.ui.dialog = None; + app.run("document.setUnits", json!({"units": "millimeters"})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + app.ui.dialog.as_mut().expect("Transform Each is open").fields.insert("moveH".into(), json!(1200)); + let mut f = Frames::new(); + f.run(&mut app, vec![]); + let out = f.run(&mut app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let mut horizontal = nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Slider && n.label() == Some("Horizontal:")); + let (node, _) = horizontal.nth(1).expect("the Move slider named Horizontal:"); + let request = + ActionRequest { action: Action::SetValue, target_node: *node, target_tree: TreeId::ROOT, data: Some(ActionData::NumericValue(400.0)) }; + f.run(&mut app, vec![egui::Event::AccessKitActionRequest(request)]); + let moved = app.ui.dialog.as_ref().expect("Transform Each is open").f64("moveH", f64::NAN); + assert!((moved - 400.0 * 72.0 / 25.4).abs() < 1e-6, "{moved} pt"); + // A slider without a field's places, Roughen's Detail, sets whole numbers as a drag does. + app.ui.dialog = None; + app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap(); + let mut f = Frames::new(); + f.run(&mut app, vec![]); + let out = f.run(&mut app, vec![]); + let (node, ..) = slider_node(&out, "Detail:"); + let request = + ActionRequest { action: Action::SetValue, target_node: node, target_tree: TreeId::ROOT, data: Some(ActionData::NumericValue(12.4)) }; + f.run(&mut app, vec![egui::Event::AccessKitActionRequest(request)]); + assert_eq!(app.ui.dialog.as_ref().expect("Roughen is open").f64("detail", f64::NAN), 12.0); +} + #[test] fn polar_grid_shared_canvas_click_defaults_units_counts_and_history() { use vectorcraft_doc::NodeId; diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index f658c31b00..891fb586be 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -106,6 +106,37 @@ fn export_as_png_picks_the_file_then_shows_png_options() { assert_eq!(&written.borrow()[0].1[16..20], 120u32.to_be_bytes(), "60 pt at 144 ppi"); } +/// File › Export › Export As PNG… exports the artboard in use, not the first (#5502), and each +/// artboard the Artboard tool has selected, one file each. +#[test] +fn export_as_png_exports_the_active_artboard() { + let (mut app, written) = app(2); + // The ellipse is on the first artboard; the second is empty. + let opaque = |bytes: &[u8]| image::load_from_memory(bytes).unwrap().to_rgba8().pixels().any(|p| p.0[3] > 0); + app.view_mut().unwrap().artboard = 1; + app.run("file.export.png", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["artboard"], json!(1)); + frame(&mut app); + confirm(&mut app).unwrap(); + assert!(!opaque(&written.borrow()[0].1), "the second artboard, which is empty"); + app.view_mut().unwrap().artboard = 0; + app.run("file.export.png", json!({})).unwrap(); + frame(&mut app); + confirm(&mut app).unwrap(); + assert!(opaque(&written.borrow()[1].1), "the first artboard, with the ellipse"); + // A choice given is kept. + app.run("file.export.png", json!({"useArtboards": false})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields.get("artboard").is_none_or(serde_json::Value::is_null)); + app.ui.dialog = None; + // Artboards the Artboard tool selected: one file each. + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([0, 1])); + app.run("file.export.png", json!({})).unwrap(); + frame(&mut app); + confirm(&mut app).unwrap(); + assert_eq!(names(&written)[2..], ["/out/Untitled-1-Artboard-1.png", "/out/Untitled-1-Artboard-2.png"]); +} + #[test] fn export_as_with_a_range_then_png_options_writes_one_file_per_artboard() { let (mut app, written) = app(3); diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index 816c6641d3..41253029a2 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -285,21 +285,82 @@ fn fonts_left_out_of_the_package_are_named() { assert!(app.ui.status.contains(gone), "{}", app.ui.status); } -/// The note on linked files left out of a package uses the form the language's plural rule picks -/// for the count. +/// A package made while the interface is in another language keeps its status line in English, +/// note included, so the status bar can show it in the language of the moment. The dialog shown +/// at once is in the interface language. +#[test] +fn a_package_status_is_stored_in_english() { + let dir = Folder::new("english"); + let mut app = saved(&dir); + app.run("text.create", json!({"x": 10, "y": 80, "text": "Gone", "font": "No Such Font Family"})).unwrap(); + app.run("ui.packageDialog", json!({})).unwrap(); + let out = dir.path("out"); + std::fs::create_dir_all(&out).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("folder".into(), json!(out)); + crate::i18n::set_current(crate::i18n::Lang::from_code("cs").unwrap()); + let r = confirm(&mut app); + crate::i18n::set_current(crate::i18n::Lang::EN); + r.unwrap(); + let status = &app.ui.status; + assert!(status.starts_with("Packaged "), "{status}"); + assert!(status.contains(&format!(" (fonts not copied: No Such Font Family Regular) in {out}")), "{status}"); + let detail = app.ui.dialog.as_ref().unwrap().str("detail"); + assert!(detail.contains("(nezkopírovaná písma: No Such Font Family Regular)"), "{detail}"); + assert!(detail.ends_with("Zobrazit složku balíčku?"), "{detail}"); +} + +/// The dialog's note on linked files left out of a package uses the form the language's plural +/// rule picks for the count. The status bar's note stays English. #[test] fn the_missing_links_note_uses_each_count_form() { let note = |code: &str, missing: usize| { crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); - let note = package::package_status_note(missing, ""); + let notes = (package::package_dialog_note(missing, ""), package::package_status_note(missing, "")); crate::i18n::set_current(crate::i18n::Lang::EN); - note + notes }; - assert_eq!(note("en", 1), "(1 linked file not found)"); - assert_eq!(note("en", 2), "(2 linked files not found)"); - assert_eq!(note("cs", 1), "(Nenalezen 1 propojený soubor)"); - assert_eq!(note("cs", 2), "(Nenalezeny 2 propojené soubory)"); - assert_eq!(note("cs", 5), "(Nenalezeno 5 propojených souborů)"); + assert_eq!(note("en", 1).0, "(1 linked file not found)"); + assert_eq!(note("en", 2).0, "(2 linked files not found)"); + assert_eq!(note("cs", 1).0, "(Nenalezen 1 propojený soubor)"); + assert_eq!(note("cs", 2).0, "(Nenalezeny 2 propojené soubory)"); + assert_eq!(note("cs", 5).0, "(Nenalezeno 5 propojených souborů)"); + assert_eq!(note("cs", 1).1, "(1 linked file not found)"); + assert_eq!(note("cs", 5).1, "(5 linked files not found)"); +} + +/// A long list of fonts left out is cut short in the desktop's status line, so the status bar can +/// still translate the line. The dialog names every font. +#[test] +fn a_long_list_of_fonts_left_out_is_cut_short_in_the_status() { + use crate::i18n::{Lang, message}; + let fonts = (0..200).map(|i| format!("Family {i} Regular")).collect::>().join(", "); + assert_eq!(package::status_fonts("Mono, Sans"), "Mono, Sans"); + let note = package::package_status_note(0, &package::status_fonts(&fonts)); + assert!(note.starts_with("(fonts not copied: Family 0 Regular, ") && note.ends_with(", …)"), "{note}"); + let shown = message(Lang::from_code("de").unwrap(), &package::package_status(3, Some("/out/card Folder"), ¬e)); + assert!(shown.starts_with("3 Dateien in /out/card Folder verpackt (nicht kopierte Schriften: Family 0 Regular, "), "{shown}"); + assert!(package::package_dialog_note(0, &fonts).contains("Family 199 Regular")); +} + +/// A package written in the background while another dialog is open shows no dialog, so its +/// status line names every font left out, however long the list. +#[test] +fn a_background_package_behind_another_dialog_names_every_font_in_the_status() { + let dir = Folder::new("fonts-behind"); + let gate = Gate::default(); + let (mut app, _files) = saved_with_worker(&dir, &gate); + for i in 0..30 { + app.run("text.create", json!({"x": 10, "y": 40 + i, "text": "Gone", "font": format!("No Such Font Family {i}")})).unwrap(); + } + package_dialog(&mut app, &dir.path("out")); + assert_eq!(confirm(&mut app).unwrap()["background"], true); + app.run("ui.packageDialog", json!({})).unwrap(); + gate.open(); + background::wait_all(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("package"), "the other dialog stays"); + let status = &app.ui.status; + assert!(status.contains("No Such Font Family 0 Regular") && status.contains("No Such Font Family 29 Regular"), "{status}"); + assert!(!status.contains('…'), "{status}"); } /// A package status written in English, for one file or several, with or without a folder and a @@ -330,16 +391,26 @@ fn an_english_package_status_is_translated_after_a_language_switch() { // The folder stays whole in the translated line, and the note's font is still named. assert!(folder.is_none_or(|f| shown.contains(f)), "{}: {shown}", lang.code()); assert_eq!(note.contains("Mono"), shown.contains("Mono"), "{}: {shown}", lang.code()); + // The notes are translated too. + assert!(!shown.contains("linked file") && !shown.contains("not copied"), "{}: {shown}", lang.code()); } } let de = Lang::from_code("de").unwrap(); assert_eq!( message(de, &package::package_status(1, Some("/out/card (draft)"), "(fonts not copied: Mono)")), - "1 Datei in /out/card (draft) verpackt (fonts not copied: Mono)" + "1 Datei in /out/card (draft) verpackt (nicht kopierte Schriften: Mono)" ); assert_eq!( message(de, &package::package_status(3, Some("/out/card (draft)"), "(1 linked file not found) (fonts not copied: Mono)")), - "3 Dateien in /out/card (draft) verpackt (1 linked file not found) (fonts not copied: Mono)" + "3 Dateien in /out/card (draft) verpackt (1 verknüpfte Datei nicht gefunden) (nicht kopierte Schriften: Mono)" + ); + assert_eq!( + message(de, &package::package_status(3, None, "(1 linked file not found) (fonts not copied: Mono)")), + "3 Dateien verpackt (1 verknüpfte Datei nicht gefunden) (nicht kopierte Schriften: Mono)" + ); + assert_eq!( + message(de, &package::package_status(3, None, "(2 linked files not found)")), + "3 Dateien verpackt (2 verknüpfte Dateien nicht gefunden)" ); let cs = Lang::from_code("cs").unwrap(); assert_eq!(message(cs, "Packaged 1 file in /out"), "Zabalen 1 soubor do /out"); diff --git a/crates/ui-egui/src/dialogs/tile_edge_color.rs b/crates/ui-egui/src/dialogs/tile_edge_color.rs index 3c78543466..62f3c5a4e1 100644 --- a/crates/ui-egui/src/dialogs/tile_edge_color.rs +++ b/crates/ui-egui/src/dialogs/tile_edge_color.rs @@ -32,6 +32,23 @@ pub(super) fn resolve(color: &str) -> Option { } } +/// Whether `color` is an 8-digit hex color, `#rrggbbaa` (with or without `#`). +pub(super) fn has_alpha(color: &str) -> bool { + let color = color.trim(); + let digits = color.strip_prefix('#').unwrap_or(color); + digits.len() == 8 && digits.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// `color` as [`resolve`] reads it, or an error naming the forms it takes. A hex color with an +/// alpha part (`#rrggbbaa` or `#rgba`) is an error. +pub(super) fn checked(color: &str) -> Result { + let refused = || format!("`{color}` is not a colour (#rrggbb or a preset name)"); + if has_alpha(color) { + return Err(refused()); + } + resolve(color).ok_or_else(refused) +} + fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let color = resolve(&d.str("color")).unwrap_or(Color::BLACK); let [r, g, b, _] = color.to_rgba8(1.0); @@ -58,7 +75,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let color = d.str("color"); - let hex = resolve(&color).ok_or_else(|| format!("`{color}` is not a colour (#rrggbb or a preset name)"))?.to_hex(); + let hex = checked(&color)?.to_hex(); run_and_close(app, "prefs.set", json!({ "key": "patternTileEdgeColor", "value": hex })) } @@ -90,4 +107,36 @@ mod tests { app.run("ui.tileEdgeColor", json!({})).unwrap(); assert!(set(&mut app, "nope").is_err()); } + + /// A hex color with an alpha part is refused and leaves the preference as it was; `#rrggbb` + /// still sets it. + #[test] + fn a_color_with_an_alpha_part_is_refused() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.tileEdgeColor", json!({})).unwrap(); + let before = app.session.prefs.pattern_tile_edge_color.clone(); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff000080")); + let err = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(err, "`#ff000080` is not a colour (#rrggbb or a preset name)"); + assert_eq!(app.session.prefs.pattern_tile_edge_color, before); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.prefs.pattern_tile_edge_color, "#ff0000"); + } + + /// The swatches the dialogs draw with `resolve` show an 8-digit color by its RGB, while + /// `checked` refuses it; preset names and `#rrggbb` pass both. + #[test] + fn only_checked_refuses_a_color_with_an_alpha_part() { + let red = Color::rgb8(0xff, 0, 0).to_rgba8(1.0); + assert_eq!(resolve("#ff000080").map(|c| c.to_rgba8(1.0)), Some(red)); + assert_eq!(resolve("ff000080").map(|c| c.to_rgba8(1.0)), Some(red)); + assert!(checked("#ff000080").is_err() && checked(" ff000080 ").is_err()); + assert!(checked("#f008").is_err()); + assert_eq!(checked("#ff0000").map(|c| c.to_rgba8(1.0)), Ok(red)); + for (name, [r, g, b]) in LAYER_COLORS.iter() { + assert_eq!(checked(name).map(|c| c.to_rgba8(1.0)), Ok([*r, *g, *b, 255]), "{name}"); + } + } } diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index d1984536fe..2f620a7dfa 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -677,18 +677,22 @@ mod input { "vectorcraft document windows input" } - fn input_hook(&mut self, _: &egui::Context, input: &mut egui::RawInput) { - if let Some(hook) = self.hook.as_ref().filter(|_| self.windows.contains(&input.viewport_id)) { - hook(input); + fn input_hook(&mut self, ctx: &egui::Context, input: &mut egui::RawInput) { + if self.windows.contains(&input.viewport_id) { + if let Some(hook) = &self.hook { + hook(input); + } + crate::font_menu::take_raw_wheel(ctx, input); } } } /// Run `hook` on the input of `windows` from their next frame on. pub(super) fn register(ctx: &egui::Context, hook: Option, windows: HashSet) { - if hook.is_none() && ctx.with_plugin(|_: &mut DocumentWindowInput| ()).is_none() { + if windows.is_empty() && ctx.with_plugin(|_: &mut DocumentWindowInput| ()).is_none() { return; } + crate::font_menu::ensure_native_wheel_layers(ctx); ctx.add_plugin(DocumentWindowInput::default()); ctx.with_plugin(|p: &mut DocumentWindowInput| { p.hook = hook; diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 7366cc1a37..5fbca5a2e9 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -447,6 +447,57 @@ struct WheelFields { pending: HashMap>, } +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone)] +struct WheelLayers(Arc Option + Send + Sync>); + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct WheelLayerSnapshot; + +#[cfg(not(target_arch = "wasm32"))] +impl egui::Plugin for WheelLayerSnapshot { + fn debug_name(&self) -> &'static str { + "font wheel viewport layers" + } + + fn on_end_pass(&mut self, ui: &mut Ui) { + let ctx = ui.ctx(); + let viewport = ctx.viewport_id(); + if viewport == egui::ViewportId::ROOT || ctx.data(|d| d.get_temp::(wheel_fields_id(viewport))).is_none() { + return; + } + let current_layers = ctx.viewport(|viewport| { + viewport.this_pass.widgets.layers().filter_map(|(layer, widgets)| (!widgets.is_empty()).then_some(*layer)).collect::>() + }); + let layers = ctx.memory(|m| { + m.layer_ids() + .filter(|layer| current_layers.contains(layer)) + .filter(|layer| m.areas().is_visible(layer)) + .filter_map(|layer| m.area_rect(layer.id).map(|rect| (layer, rect))) + .collect::>() + }); + let layers = layers + .into_iter() + .filter(|(layer, _)| egui::AreaState::load(ctx, layer.id).is_some_and(|state| state.interactable)) + .map(|(layer, rect)| (layer, ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect))) + .collect::>(); + ctx.data_mut(|d| { + d.insert_temp( + wheel_fields_id(viewport).with("layers"), + WheelLayers(Arc::new(move |p| layers.iter().rev().find(|(_, rect)| rect.contains(p)).map(|(layer, _)| *layer))), + ) + }); + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn ensure_native_wheel_layers(ctx: &egui::Context) { + if ctx.with_plugin(|_: &mut WheelLayerSnapshot| ()).is_none() { + ctx.add_plugin(WheelLayerSnapshot); + } +} + fn wheel_fields_id(viewport: egui::ViewportId) -> egui::Id { egui::Id::unique("font-wheel-fields").with(viewport) } @@ -535,6 +586,10 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { let Some(mut fields) = ctx.data(|d| d.get_temp::(key)) else { return }; if !ctx.input(|i| i.raw.viewports.contains_key(&raw.viewport_id)) { ctx.data_mut(|d| d.remove::(key)); + #[cfg(not(target_arch = "wasm32"))] + ctx.data_mut(|d| { + d.remove::(key.with("layers")); + }); return; } let frame = ctx.cumulative_frame_nr_for(raw.viewport_id); @@ -548,9 +603,28 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { fields.pending.clear(); } let line = ctx.options(|o| o.input_options.line_scroll_speed).max(1.0); - let mut pointer = fields.pointer.or_else(|| ctx.input(|i| i.pointer.latest_pos())); - let over = - |field: &WheelField, point: Option| point.is_some_and(|p| field.rect.contains(p) && ctx.layer_id_at(p) == Some(field.layer)); + let mut pointer = fields.pointer.or_else(|| ctx.input_for(raw.viewport_id, |i| i.pointer.latest_pos())); + #[cfg(not(target_arch = "wasm32"))] + let native_layers = ctx.data(|d| d.get_temp::(key.with("layers"))); + let over = |field: &WheelField, point: Option| { + point.is_some_and(|p| { + if !field.rect.contains(p) { + return false; + } + if ctx.viewport_id() == raw.viewport_id { + ctx.layer_id_at(p) == Some(field.layer) + } else { + #[cfg(not(target_arch = "wasm32"))] + { + native_layers.as_ref().is_some_and(|layers| (layers.0)(p) == Some(field.layer)) + } + #[cfg(target_arch = "wasm32")] + { + false + } + } + }) + }; // An activation batch belongs to the popup, including a release after a prior press. if fields.activation_pass != pass { fields.activation_pass = pass; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index cce9ebd4ef..284e70e095 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -841,6 +841,11 @@ font-technology Variable Променливи Double-click to edit the characters' paint Двойно щракване за редактиране на оцветяването на знаците Click to edit Щракнете за редактиране Double-click to edit Двойно щракване за редактиране + Alternates for Current Selection Алтернативи за текущата селекция + Select a character with the Type tool to see its alternates. Изберете знак с инструмента „Текст“, за да видите алтернативите му. + The selected character's font is not available. Шрифтът на избрания знак не е наличен. + No alternates for the selected character. Няма алтернативи за избрания знак. + Double-click to replace Двойно щракване за замяна Double-click to insert Двойно щракване за вмъкване Double-click to rename Двойно щракване за преименуване Double-click to target the contents Двойно щракване за насочване към съдържанието @@ -1597,6 +1602,10 @@ font-technology Variable Променливи Join Tool Инструмент „Свързване“ Justification… Подравняване… Justify all lines Двустранно подравняване на всички редове + Align Top Подравняване горе + Align Center Подравняване в средата + Align Bottom Подравняване долу + Justify Vertically Двустранно вертикално подравняване Justify with last line aligned center Двустранно подравняване с центриран последен ред Justify with last line aligned left Двустранно подравняване с ляво подравнен последен ред Justify with last line aligned right Двустранно подравняване с дясно подравнен последен ред @@ -1702,6 +1711,7 @@ font-technology Variable Променливи Ligatures are off while the text is tracked. Лигатурите са изключени, докато текстът е с проследяване. Light Светло Light Blue Светлосиньо + Light Red Светлочервено Lighten Изсветляване Lightness Светлина Limit Color Guide to Library Ограничаване на цветния справочник до библиотека @@ -1920,6 +1930,8 @@ font-technology Variable Променливи Name: Име: Navigate Навигация Navigator Навигатор + Navigator Panel Options Опции за панела „Навигатор“ + Draw Dashed Lines as Solid Lines Изчертаване на прекъснатите линии като плътни Needs the desktop app Изисква десктоп приложение Neutral Gradients Неутрални градиенти New Нов @@ -3666,6 +3678,12 @@ digits Malayalam Малаялам Scrub Numeric Fields by Dragging Плъзгане на числени полета чрез влачене @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} файл в {folder} {note}. Показване на папката на пакета?|{n} файла в {folder} {note}. Показване на папката на пакета? @plural {n} linked file not found|{n} linked files not found {n} свързан файл не е намерен|{n} свързани файла не са намерени +@msgplural {n} linked file not found|{n} linked files not found {n} свързан файл не е намерен|{n} свързани файла не са намерени +@msg fonts not copied: {fonts} некопирани шрифтове: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) ({n} свързан файл не е намерен)|({n} свързани файла не са намерени) +@msg (fonts not copied: {fonts}) (некопирани шрифтове: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} некопирани шрифтове: {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} свързано изображение е променено след запазването на този документ. Показване на новата версия?|{n} свързани изображения са променени след запазването на този документ. Показване на новите версии? @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} свързано изображение е променено на диска. Показване на новата версия?|{n} свързани изображения са променени на диска. Показване на новите версии? @@ -5495,6 +5513,10 @@ theme Appearance Външен вид Movie Clip Филмов клип @msg name is empty името е празно @msg an action is already recording вече се записва действие +@msg an action is already playing вече се възпроизвежда действие +@msg the action stopped playing: its document is no longer active действието спря: документът му вече не е активен +@msg speed must be accelerated, step or pause speed трябва да е accelerated, step или pause +@msg seconds must be a whole number from 1 to 60 seconds трябва да е цяло число от 1 до 60 @msg no such function key няма такъв функционален клавиш @msg no such color няма такъв цвят @msg {_1} cannot be used on Windows {_1} не може да се използва в Windows @@ -5645,6 +5667,11 @@ axis Y Axis Y ос Set Options Опции на набора Action Options… Опции на действието… Action Options Опции на действието + Playback Options… Опции за възпроизвеждане… + Playback Options Опции за възпроизвеждане + Accelerated Ускорено + Step by Step Стъпка по стъпка + Pause For Пауза за Rename Action Преименуване на действие New Action… Ново действие… New Action Ново действие @@ -6104,6 +6131,11 @@ breakText Glyphs Глифи Export All Open Documents as SVG Експортиране на всички отворени документи като SVG @msgplural Exported {n} document|Exported {n} documents Експортиран е {n} документ|Експортирани са {n} документа @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Експортиран е {n} документ; {title} не беше записан: {error}|Експортирани са {n} документа; {title} не беше записан: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Пакетно трасиране на папка +@msgplural Traced {n} image|Traced {n} images Трасирано е {n} изображение|Трасирани са {n} изображения +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} изображение не можа да бъде трасирано|{n} изображения не можаха да бъдат трасирани +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Трасирано е {n} изображение; нетрасирани: {failed}|Трасирани са {n} изображения; нетрасирани: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Тип на символа: Dynamic Symbol Динамичен символ @@ -6155,3 +6187,13 @@ breakText Glyphs Глифи Spike Връх Skip Spaces Пропускане на интервалите @msg The art is too large to copy as a picture: other apps get no PNG of it Графиката е твърде голяма, за да се копира като изображение: другите приложения не получават PNG от нея + +# Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). + Select by Artboards Избиране по работни области + Select by Artboards… Избиране по работни области… + Selection Tools Инструменти за избиране + Search artboards Търсене в работните области + Fully Inside Изцяло вътре + Fully Outside Изцяло извън + No artboards match. Няма съвпадащи работни области. + Chosen: {n} of {total} Избрани: {n} от {total} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 098c02cd40..d6e1bdb8ef 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -683,6 +683,8 @@ Update Changed Links Ažuriraj promijenjene veze Magic Wand Čarobni štapić Navigator Navigator + Navigator Panel Options Opcije panela navigatora + Draw Dashed Lines as Solid Lines Crtaj isprekidane linije kao pune Pattern Options Opcije uzorka Properties Svojstva Separations Preview Pregled separacija @@ -948,6 +950,10 @@ lighting Light Svjetlo Home Početna Import Keyboard Shortcuts… Uvezi prečice na tastaturi… Justify all lines Obostrano poravnaj sve redove + Align Top Poravnaj gore + Align Center Poravnaj u sredinu + Align Bottom Poravnaj dolje + Justify Vertically Obostrano poravnaj okomito Justify with last line aligned left Obostrano s posljednjim redom lijevo Keyboard Shortcut Conflicts Konflikti prečica na tastaturi Keyboard Shortcut Set Skup prečica na tastaturi @@ -1541,6 +1547,11 @@ digits Malayalam Malajalam Save Transparency Flattener Preset… Sačuvaj predložak spljoštavanja prozirnosti… Basic Latin Osnovna latinica Currency & Symbols Valuta i simboli + Alternates for Current Selection Alternative za trenutni odabir + Select a character with the Type tool to see its alternates. Odaberite znak alatom za tekst da vidite njegove alternative. + The selected character's font is not available. Font odabranog znaka nije dostupan. + No alternates for the selected character. Nema alternativa za odabrani znak. + Double-click to replace Dvostruki klik za zamjenu Double-click to insert Dvostruki klik za umetanje Entire Font Cijeli font glyph {id} glif {id} @@ -2396,6 +2407,7 @@ digits Malayalam Malajalam “{file}” is protected by a password. „{file}” je zaštićen lozinkom. Dim Images to: Zatamni slike na: Light Blue Svijetloplava + Light Red Svijetlocrvena Layers Panel Options Opcije panela slojeva Row Size: Veličina reda: Show Layers Only Prikaži samo slojeve @@ -2484,6 +2496,12 @@ digits Malayalam Malajalam Save the document first? Prvo sačuvati dokument? @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Datoteka u {folder}: {n} {note}. Prikazati folder paketa?|Datoteka u {folder}: {n} {note}. Prikazati folder paketa?|Datoteka u {folder}: {n} {note}. Prikazati folder paketa? @plural {n} linked file not found|{n} linked files not found Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n} +@msgplural {n} linked file not found|{n} linked files not found Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n} +@msg fonts not copied: {fonts} fontovi nisu kopirani: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (Povezanih datoteka nije pronađeno: {n})|(Povezanih datoteka nije pronađeno: {n})|(Povezanih datoteka nije pronađeno: {n}) +@msg (fonts not copied: {fonts}) (fontovi nisu kopirani: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} fontovi nisu kopirani: {fonts} Built-in presets are read-only: New… starts an editable copy. Ugrađeni predlošci su samo za čitanje: Novo… započinje kopiju koja se može uređivati. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} na radnoj ploči predstavlja {real} {unit} u sceni. @@ -5499,6 +5517,10 @@ mark-style Japanese Japanski Movie Clip Filmski klip @msg name is empty naziv je prazan @msg an action is already recording akcija se već snima +@msg an action is already playing akcija se već reproducira +@msg the action stopped playing: its document is no longer active reprodukcija akcije je zaustavljena: njen dokument više nije aktivan +@msg speed must be accelerated, step or pause speed mora biti accelerated, step ili pause +@msg seconds must be a whole number from 1 to 60 seconds mora biti cijeli broj od 1 do 60 @msg no such function key nema takve funkcijske tipke @msg no such color nema takve boje @msg {_1} cannot be used on Windows {_1} se ne može koristiti na Windowsu @@ -5668,6 +5690,11 @@ axis Y Axis Y osa Set Options Opcije skupa Action Options… Opcije akcije… Action Options Opcije akcije + Playback Options… Opcije reprodukcije… + Playback Options Opcije reprodukcije + Accelerated Ubrzano + Step by Step Korak po korak + Pause For Pauza od Rename Action Preimenuj akciju New Action… Nova akcija… New Action Nova akcija @@ -6138,6 +6165,11 @@ shape Open Otvoren Export All Open Documents as SVG Izvezi sve otvorene dokumente kao SVG @msgplural Exported {n} document|Exported {n} documents Izvezen je {n} dokument|Izvezena su {n} dokumenta|Izvezeno je {n} dokumenata @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Izvezen je {n} dokument; {title} nije zapisan: {error}|Izvezena su {n} dokumenta; {title} nije zapisan: {error}|Izvezeno je {n} dokumenata; {title} nije zapisan: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Paketno praćenje foldera +@msgplural Traced {n} image|Traced {n} images Praćena je {n} slika|Praćene su {n} slike|Praćeno je {n} slika +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} slika nije mogla biti praćena|{n} slike nisu mogle biti praćene|{n} slika nije moglo biti praćeno +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Praćena je {n} slika; nije praćeno: {failed}|Praćene su {n} slike; nije praćeno: {failed}|Praćeno je {n} slika; nije praćeno: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Vrsta simbola: Dynamic Symbol Dinamički simbol @@ -6189,3 +6221,13 @@ shape Open Otvoren Spike Šiljak Skip Spaces Preskoči razmake @msg The art is too large to copy as a picture: other apps get no PNG of it Grafika je prevelika da bi se kopirala kao slika: druge aplikacije ne dobijaju njen PNG + +# Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). + Select by Artboards Odabir po radnim pločama + Select by Artboards… Odabir po radnim pločama… + Selection Tools Alati za odabir + Search artboards Pretraži radne ploče + Fully Inside Potpuno unutra + Fully Outside Potpuno vani + No artboards match. Nijedna radna ploča ne odgovara. + Chosen: {n} of {total} Odabrano: {n} od {total} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 93fe3cb2b6..75b6b4ca3a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1200,6 +1200,11 @@ Double Slash Barra inclinada doble Double-click Doble clic Double-click to edit the characters' paint Feu doble clic per editar la pintura dels caràcters + Alternates for Current Selection Alternatives per a la selecció actual + Select a character with the Type tool to see its alternates. Selecciona un caràcter amb l’eina de text per veure’n les alternatives. + The selected character's font is not available. El tipus de lletra del caràcter seleccionat no està disponible. + No alternates for the selected character. No hi ha alternatives per al caràcter seleccionat. + Double-click to replace Feu doble clic per substituir Double-click to insert Feu doble clic per inserir Double-click to rename Feu doble clic per canviar el nom Double-click to target the contents Feu doble clic per apuntar al contingut @@ -2053,6 +2058,10 @@ digits Malayalam Malaiàlam Justification… Justificació… Justify Justifica Justify all lines Justifica totes les línies + Align Top Alinea a dalt + Align Center Alinea al mig + Align Bottom Alinea a baix + Justify Vertically Justifica verticalment Justify with last line aligned center Justifica amb l’última línia centrada Justify with last line aligned left Justifica amb l’última línia alineada a l’esquerra Justify with last line aligned right Justifica amb l’última línia alineada a la dreta @@ -2166,6 +2175,7 @@ digits Malayalam Malaiàlam Light Clar Light behind the object Llum darrere de l’objecte Light Blue Blau clar + Light Red Vermell clar Light Direction Direcció de la llum Light Gray Gris clar Light Intensity Intensitat de la llum @@ -2495,6 +2505,8 @@ digits Malayalam Malaiàlam Names the script builds as it runs: {count} Noms que l’script crea mentre s’executa: {count} Navigate Navega Navigator Navegador + Navigator Panel Options Opcions del panell Navegador + Draw Dashed Lines as Solid Lines Dibuixa les línies discontínues com a contínues Needs a choice Necessita una tria Needs a key Necessita una clau Needs Attention Only Només necessita atenció @@ -3784,6 +3796,11 @@ digits Malayalam Malaiàlam Set Options Defineix les opcions Action Options… Opcions de l’acció… Action Options Opcions de l’acció + Playback Options… Opcions de reproducció… + Playback Options Opcions de reproducció + Accelerated Accelerada + Step by Step Pas a pas + Pause For Pausa de Rename Action Canvia el nom de l’acció New Action… Acció nova… New Action Acció nova @@ -4730,6 +4747,12 @@ digits Malayalam Malaiàlam @plural {n} folder or file couldn't be read|{n} folders or files couldn't be read No s’ha pogut llegir {n} carpeta o fitxer|No s’han pogut llegir {n} carpetes o fitxers @plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones S’ha omès {n} carpeta, com ara les d’altres aplicacions, les del sistema i les ocultes|S’han omès {n} carpetes, com ara les d’altres aplicacions, les del sistema i les ocultes @plural {n} linked file not found|{n} linked files not found No s’ha trobat {n} fitxer enllaçat|No s’han trobat {n} fitxers enllaçats +@msgplural {n} linked file not found|{n} linked files not found No s’ha trobat {n} fitxer enllaçat|No s’han trobat {n} fitxers enllaçats +@msg fonts not copied: {fonts} tipus de lletra no copiats: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (No s’ha trobat {n} fitxer enllaçat)|(No s’han trobat {n} fitxers enllaçats) +@msg (fonts not copied: {fonts}) (tipus de lletra no copiats: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} imatge enllaçada ha canviat al disc. Voleu mostrar la versió nova?|{n} imatges enllaçades han canviat al disc. Voleu mostrar les versions noves? @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} imatge enllaçada ha canviat des que es va desar aquest document. Voleu mostrar la versió nova?|{n} imatges enllaçades han canviat des que es va desar aquest document. Voleu mostrar les versions noves? @plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regla més: l’exportació l’escriu.|{n} regles més: l’exportació les escriu totes. @@ -5031,6 +5054,7 @@ digits Malayalam Malaiàlam @msg Create Outlines: select text objects Crea contorns: seleccioneu objectes de text @msg damaged malmès @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) La recuperació de dades no té cap lloc on guardar còpies: configureu Preferències → Gestió de fitxers → Recuperació de dades → Carpeta (recoveryFolder) +@msg Data Recovery can't keep copies in {path}: {e} La recuperació de dades no pot guardar còpies a {path}: {e} @msg data the program reads is damaged or cut short, or the program asks for a position in a file that has none les dades que llegeix el programa estan malmeses o tallades, o el programa demana una posició en un fitxer que no en té @msg decimals must be {_1}–{_2} (got {_3}) els decimals han de ser {_1}–{_2} (rebut {_3}) @msg Dimension point is outside the canvas El punt de dimensió és fora del llenç @@ -5180,6 +5204,10 @@ digits Malayalam Malaiàlam @msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Els fitxers PSD multicanal no es poden llegir: deseu-los en mode RGB, CMYK o escala de grisos @msg name is empty el nom és buit @msg an action is already recording ja s’està enregistrant una acció +@msg an action is already playing ja s’està reproduint una acció +@msg the action stopped playing: its document is no longer active l’acció s’ha aturat: el seu document ja no és l’actiu +@msg speed must be accelerated, step or pause speed ha de ser accelerated, step o pause +@msg seconds must be a whole number from 1 to 60 seconds ha de ser un nombre enter de l’1 al 60 @msg no such function key no existeix aquesta tecla de funció @msg no such color no existeix aquest color @msg {_1} cannot be used on Windows {_1} no es pot fer servir al Windows @@ -6238,6 +6266,11 @@ breakText Glyphs Glifs Export All Open Documents as SVG Exporta tots els documents oberts com a SVG @msgplural Exported {n} document|Exported {n} documents S’ha exportat {n} document|S’han exportat {n} documents @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} S’ha exportat {n} document; no s’ha escrit {title}: {error}|S’han exportat {n} documents; no s’ha escrit {title}: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Traçat per lots d’una carpeta +@msgplural Traced {n} image|Traced {n} images S’ha traçat {n} imatge|S’han traçat {n} imatges +@msgplural {n} image couldn't be traced|{n} images couldn't be traced No s’ha pogut traçar {n} imatge|No s’han pogut traçar {n} imatges +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} S’ha traçat {n} imatge; no traçades: {failed}|S’han traçat {n} imatges; no traçades: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Tipus de símbol: Dynamic Symbol Símbol dinàmic @@ -6289,3 +6322,13 @@ breakText Glyphs Glifs Spike Pic Skip Spaces Omet els espais @msg The art is too large to copy as a picture: other apps get no PNG of it La il·lustració és massa gran per copiar-la com a imatge: les altres aplicacions no en reben cap PNG + +# Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). + Select by Artboards Selecciona per taulers + Select by Artboards… Selecciona per taulers… + Selection Tools Eines de selecció + Search artboards Cerca taulers + Fully Inside Totalment a dins + Fully Outside Totalment fora + No artboards match. Cap tauler no coincideix. + Chosen: {n} of {total} Triats: {n} de {total} diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs index 1be460212a..8999157286 100644 --- a/crates/ui-egui/src/i18n/catalog.rs +++ b/crates/ui-egui/src/i18n/catalog.rs @@ -35,6 +35,8 @@ struct Template { /// Bytes of literal text: a template with more of it is the more specific match. literal: usize, forms: Vec, + /// A `@msgplural` form: its `{n}` matches only a count. + counted: bool, } /// The placeholder values of a matched message template: placeholder name and value. @@ -46,7 +48,7 @@ const MAX_MESSAGE_LEN: usize = 2000; impl Template { /// `None` for a template that can't be matched reliably: no literal text, or two placeholders /// in a row (where one ends and the next begins is unknowable). - fn parse(source: &str, forms: Vec) -> Option