diff --git a/ROADMAP.md b/ROADMAP.md index b59eea470a..9b6adac135 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,6 +124,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-12-04: Raster Settings OK edits the objects selected when the dialog opened. It keeps the dialog open with the reason if its document is not active, was reverted or had an Undo, a Redo or a canceled edit that put back an earlier state, if a target was changed, deleted, locked or hidden, if another edit is in progress, or if the change is refused. Headline numbers unchanged. - 2026-12-04: Paste from CAD apps: on Windows, Paste reads the enhanced metafile CAD and office apps copy as vector art, and a `.dxf`, `.dwg` or HP-GL plot file copied in a file manager pastes as its drawing through the new command `clipboard.importCad` (#10819). Headline numbers unchanged. - 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips that starts again where the path turns back on itself at a cusp, a straight segment included (#10659). Headline numbers unchanged. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 8855d3f9e3..1bfb6b817a 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -196,8 +196,8 @@ USAGE: /// The usage text plus the formats `document.open` reads and `document.export` writes. fn usage() -> String { - use vectorcraft_engine::cmd::fileio::{OPEN_EXTS, export_extensions}; - format!("{USAGE}\nReadable formats: .{}\nWritable formats: .{}\n", OPEN_EXTS.join(", ."), export_extensions().join(", .")) + use vectorcraft_engine::cmd::fileio::{export_extensions, open_exts}; + format!("{USAGE}\nReadable formats: .{}\nWritable formats: .{}\n", open_exts().join(", ."), export_extensions().join(", .")) } /// Does a subcommand's `args` ask for the usage? `--help` or `-h` counts where an option goes, not as diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index d772397ce3..63135d00e5 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -799,6 +799,10 @@ fn main() -> std::process::ExitCode { // window, so eframe's windows are recorded as it makes and drops them (`quit_windows`). #[cfg(target_os = "linux")] let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(quit_windows::Hooks)), ..options }; + // Floating panels and dialogs that draw their own title bar stay borderless on Windows, as the + // main window does (`window_frame`, #10797). + #[cfg(all(windows, feature = "wgpu"))] + let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(window_frame::Hooks)), ..options }; #[cfg(feature = "wgpu")] let options = { let mut options = options; diff --git a/apps/vectorcraft/src/window_frame.rs b/apps/vectorcraft/src/window_frame.rs index e69806ac29..ba5d3d298d 100644 --- a/apps/vectorcraft/src/window_frame.rs +++ b/apps/vectorcraft/src/window_frame.rs @@ -22,10 +22,20 @@ //! monitor. In PhotoCraft the taskbar then did not show when the pointer reached its edge //! (storytold/photocraft#4845). On each edge with an auto-hidden taskbar the guard stops the window //! one pixel short of the monitor instead, as PhotoCraft does (storytold/photocraft#6878). +//! +//! Floating panels and dialogs that draw their own title bar (Preferences, a floating Color panel) +//! are undecorated winit windows as well, and on the same systems their content was drawn offset +//! by the caption and border too (#10797). `Hooks` records those windows as eframe makes them and +//! runs the same guard on each one in each of its frames. + +use std::collections::HashMap; +use std::sync::{Mutex, MutexGuard, PoisonError}; /// Run once per frame; a no-op once the window is borderless. pub type WindowFrameFn = Box; +#[cfg(all(windows, feature = "wgpu"))] +pub use platform::Hooks; pub use platform::service; #[cfg(all(windows, feature = "wgpu"))] @@ -49,6 +59,33 @@ mod platform { Some(Box::new(move || reapply(&hwnd))) } + /// The undecorated windows of floating panels and dialogs, which [`Hooks`] records. + static SECONDARY: std::sync::LazyLock> = std::sync::LazyLock::new(super::Viewports::default); + + /// Keeps the undecorated windows of floating panels and dialogs borderless, as [`service`] + /// keeps the main window: the guard runs when eframe makes such a window and before each of its + /// frames. Set as [`eframe::NativeOptions::viewport_hooks`]. + pub struct Hooks; + + impl eframe::ViewportHooks for Hooks { + fn window_created(&self, viewport: egui::ViewportId, window: &winit::window::Window) { + let hwnd = match window.window_handle().map(|h| h.as_raw()) { + Ok(RawWindowHandle::Win32(h)) => find_window(h.hwnd.get()), + _ => None, + }; + SECONDARY.created(viewport, window.is_decorated(), hwnd); + SECONDARY.with(viewport, reapply); + } + + fn window_destroyed(&self, viewport: egui::ViewportId) { + SECONDARY.destroyed(viewport); + } + + fn raw_input(&self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) { + SECONDARY.with(raw_input.viewport_id, reapply); + } + } + /// One pass of the per-frame guard: the styles winit put back come off again, and a parked /// maximize stays clear of the taskbar. fn reapply(hwnd: &HWND) { @@ -152,6 +189,55 @@ mod platform { } } +/// The windows of the undecorated floating panels and dialogs, by viewport, while eframe holds +/// them. A record holds `None` while [`Viewports::with`] has its window out. Platform-neutral so +/// it is tested everywhere. +#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] +struct Viewports(Mutex>>); + +impl Default for Viewports { + fn default() -> Self { + Self(Mutex::new(HashMap::new())) + } +} + +#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] +impl Viewports { + /// eframe made `viewport`'s window, with `handle`. It is recorded when it is an undecorated + /// window other than the main one, which [`service`] keeps; otherwise any earlier record of the + /// viewport is removed, so a window made again with the system title bar is left alone. + fn created(&self, viewport: egui::ViewportId, decorated: bool, handle: Option) { + let mut windows = self.lock(); + match handle { + Some(handle) if viewport != egui::ViewportId::ROOT && !decorated => windows.insert(viewport, Some(handle)), + _ => windows.remove(&viewport), + }; + } + + /// eframe dropped `viewport`'s window. + fn destroyed(&self, viewport: egui::ViewportId) { + self.lock().remove(&viewport); + } + + /// Runs `f` on `viewport`'s recorded window, if any. The window is taken out of its record + /// while `f` runs, so window messages that `f` sends and that reach the hooks again do not wait + /// on the lock. It goes back only if the record is still there and empty: a window dropped or + /// made again for the viewport in the meantime wins. + fn with(&self, viewport: egui::ViewportId, f: impl FnOnce(&H)) { + let Some(handle) = self.lock().get_mut(&viewport).and_then(Option::take) else { + return; + }; + f(&handle); + if let Some(slot @ None) = self.lock().get_mut(&viewport) { + *slot = Some(handle); + } + } + + fn lock(&self) -> MutexGuard<'_, HashMap>> { + self.0.lock().unwrap_or_else(PoisonError::into_inner) + } +} + /// How far a parked maximize reaches past a monitor or work-area edge: the resize border (about /// 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but being /// dragged or snapped, and is left alone. @@ -260,7 +346,64 @@ fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: & #[cfg(test)] mod tests { - use super::{Edge, clamped_rect, short_of_autohide_taskbars, taskbar_edge}; + use super::{Edge, Viewports, clamped_rect, short_of_autohide_taskbars, taskbar_edge}; + + fn viewport(name: &str) -> egui::ViewportId { + egui::ViewportId::from_hash_of(name) + } + + /// The windows `with` reaches for each viewport, in order. + fn reached(windows: &Viewports, viewports: &[egui::ViewportId]) -> Vec> { + viewports + .iter() + .map(|&id| { + let mut seen = None; + windows.with(id, |&h| seen = Some(h)); + seen + }) + .collect() + } + + /// Floating panels and dialogs with their own title bar are kept borderless (#10797); the main + /// window, which `service` keeps, and windows with the system title bar are not recorded. + #[test] + fn undecorated_floating_windows_are_recorded_until_dropped() { + let windows = Viewports::default(); + let (prefs, color, hang) = (viewport("Preferences"), viewport("Color"), viewport("Not responding")); + windows.created(egui::ViewportId::ROOT, false, Some(1)); + windows.created(prefs, false, Some(7)); + windows.created(color, false, Some(9)); + windows.created(hang, true, Some(11)); + assert_eq!(reached(&windows, &[egui::ViewportId::ROOT, prefs, color, hang]), [None, Some(7), Some(9), None]); + // Each frame reaches the window again. + assert_eq!(reached(&windows, &[prefs]), [Some(7)]); + windows.destroyed(prefs); + assert_eq!(reached(&windows, &[prefs, color]), [None, Some(9)]); + // A window made again with the system title bar, or without a handle, is left alone. + windows.created(color, true, Some(13)); + assert_eq!(reached(&windows, &[color]), [None]); + windows.created(color, false, Some(15)); + windows.created(color, false, None); + assert_eq!(reached(&windows, &[color]), [None]); + } + + /// A window dropped or made again while the guard runs on the old one is not brought back. + #[test] + fn a_window_dropped_or_made_again_during_the_guard_wins() { + let windows = Viewports::default(); + let prefs = viewport("Preferences"); + windows.created(prefs, false, Some(7)); + windows.with(prefs, |_| windows.destroyed(prefs)); + assert_eq!(reached(&windows, &[prefs]), [None]); + windows.created(prefs, false, Some(7)); + windows.with(prefs, |_| windows.created(prefs, false, Some(8))); + assert_eq!(reached(&windows, &[prefs]), [Some(8)]); + // The guard can reach the hooks again for the same viewport without waiting on itself. + let mut inner = None; + windows.with(prefs, |_| windows.with(prefs, |&h| inner = Some(h))); + assert_eq!(inner, None); + assert_eq!(reached(&windows, &[prefs]), [Some(8)]); + } #[test] fn a_maximize_covering_the_taskbar_is_trimmed_to_the_work_area() { diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs index b6e4b545c4..c49beecb99 100644 --- a/crates/cad/src/dwg.rs +++ b/crates/cad/src/dwg.rs @@ -13,6 +13,9 @@ use web_time::Instant; pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker}; +/// Whether this build decodes DWG drawings. Web builds and FreeBSD on 64-bit ARM have no DWG decoder. +pub const DECODES: bool = !cfg!(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))); + /// The worker argument after [`WORKER_ARG`] that gives its deadline in milliseconds since the UNIX epoch /// ([`use_own_worker_for`]). const WORKER_UNTIL_ARG: &str = "--dwg-worker-until"; diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index 5a5582efe1..bed5bef361 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -6,7 +6,7 @@ //! or with the drawing's origin on the artboard's bottom-left corner. Each DXF layer holding art //! becomes a layer (hidden, frozen, locked and non-plotting layers keep that), or all art goes on //! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid -//! hatches and solids become paths; text and multiline text point type; named blocks symbols +//! hatches, solids and regions become paths; text and multiline text point type; named blocks symbols //! (anonymous ones, such as dimensions, groups of their art). Colours (indexed and true colour), //! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve //! them. What can't come in is listed in the warnings. @@ -16,8 +16,10 @@ //! - `entity`: entities to items (geometry and properties). //! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths. //! - `text`: text values to plain text. +//! - `acis`: a region's solid-modeler data as its outline. //! - `build`: items to the document. +mod acis; mod build; mod curve; mod entity; @@ -237,3 +239,5 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result { mod tests; #[cfg(test)] mod tests_dwg; +#[cfg(test)] +mod tests_region; diff --git a/crates/cad/src/import/acis.rs b/crates/cad/src/import/acis.rs new file mode 100644 index 0000000000..581e168625 --- /dev/null +++ b/crates/cad/src/import/acis.rs @@ -0,0 +1,779 @@ +//! The solid-modeler data of a REGION as a filled outline: each face's loops of edges, in world x +//! and y (drawing units). The data comes as text (DXF before 2013, ciphered or not) or binary +//! (DXF 2013 and later keep it in the ACDSDATA section). +//! +//! The model is a list of records pointing at each other: a body holds lumps, a lump shells, a +//! shell faces, a face loops, a loop a ring of coedges. Each coedge uses an edge (forward or +//! reversed), and each edge runs between two vertices along a line, an ellipse or a spline. A +//! curve of any other kind comes in as a straight line between its vertices. +//! +//! The REGION groups are in the DXF Reference +//! (); which +//! DXF versions hold text and which binary data is in . + +use std::collections::HashMap; + +use kurbo::{BezPath, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathSeg}; +use vectorcraft_geom::{Affine, Point}; + +use super::curve; + +/// The most bytes of one region's data read. +pub(crate) const MAX_BYTES: usize = 16 << 20; +/// The most records one region's outline may visit: bodies, lumps, shells, faces and coedges +/// (a loop counts as one at least). +const MAX_VISITS: usize = 1_000_000; +/// The first bytes of binary data: ACIS's, or ASM's (DXF 2018 writes either). +const BINARY_MAGIC: [&[u8]; 2] = [b"ACIS BinaryFile", b"ASM BinaryFile4"]; +/// From this version on, every record starts with its attribute, a history number and one more +/// pointer; before it, with its attribute alone. +const LONG_HEADER_VERSION: u32 = 700; + +type P3 = [f64; 3]; +/// A B-spline: degree, knots, control points, weights (none: all 1). +type Spline = (usize, Vec, Vec, Option>); + +/// One value of a record. +#[derive(Clone, Debug, PartialEq)] +enum Tok { + Ptr(i64), + Num(f64), + Word(String), + /// `forward` (false) or `reversed` (true). + Sense(bool), + Open, + Close, +} + +/// A record: its type (`body`, `plane-surface`…) and its values after the ones every record +/// starts with. +#[derive(Debug)] +struct Rec { + kind: String, + toks: Vec, +} + +impl Rec { + /// The type `base` or one derived from it (`tedge-edge` is an edge). + fn is(&self, base: &str) -> bool { + self.kind == base || self.kind.strip_suffix(base).is_some_and(|k| k.ends_with('-')) + } + + /// The `n`th pointer (-1: none). + fn ptr(&self, n: usize) -> i64 { + self.toks.iter().filter_map(|t| if let Tok::Ptr(p) = t { Some(*p) } else { None }).nth(n).unwrap_or(-1) + } + + /// The sense right after the `n`th pointer: true when reversed (old files write 1). + fn sense_after(&self, n: usize) -> Option { + let mut ptrs = 0; + for t in &self.toks { + if ptrs > n { + return match t { + Tok::Sense(r) => Some(*r), + Tok::Num(v) if v.is_finite() => Some(*v != 0.0), + _ => None, + }; + } + if matches!(t, Tok::Ptr(_)) { + ptrs += 1; + } + } + None + } + + /// The numbers, in order. + fn nums(&self) -> Vec { + self.toks.iter().filter_map(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect() + } +} + +/// The records of one body, and how pointers find them. +struct Model { + recs: Vec, + /// Record number by index, when the records carry their own. + at: HashMap, +} + +impl Model { + fn get(&self, p: i64) -> Option<&Rec> { + if p < 0 { + return None; + } + if self.at.is_empty() { self.recs.get(usize::try_from(p).ok()?) } else { self.recs.get(*self.at.get(&p)?) } + } + + /// The record `p` points at when it is of type `base`. + fn get_is(&self, p: i64, base: &str) -> Option<&Rec> { + self.get(p).filter(|r| r.is(base)) + } + + /// The records of type `base` from `first` along their `next` pointer (pointer `next`), each + /// once. Missing records, wrong types and cycles outside coedge rings set `broken`. + fn chain(&self, first: i64, base: &str, next: usize, broken: &mut bool) -> Vec<&Rec> { + let mut out = vec![]; + let mut seen = std::collections::HashSet::new(); + let mut p = first; + while p >= 0 { + if !seen.insert(p) { + *broken |= base != "coedge"; + break; + } + let Some(r) = self.get_is(p, base) else { + *broken = true; + break; + }; + out.push(r); + p = r.ptr(next); + } + out + } +} + +/// A region's outline: its faces' loops, closed; `approximated` when an edge of a curve type +/// this reader doesn't draw came in as a straight line; `broken` when a topology chain breaks +/// off or a loop's ring of coedges doesn't come back to its first; `ambiguous` when an edge's +/// endpoint lies on separate parts of its curve. +#[derive(Debug)] +pub(crate) struct Outline { + pub path: BezPath, + pub approximated: bool, + pub broken: bool, + pub ambiguous: bool, +} + +/// Text data, ciphered as DXF writes it or not. +pub(crate) fn from_text(text: &str) -> Option { + if text.len() > MAX_BYTES { + return None; + } + let plain; + let text = if text.trim_start().starts_with(|c: char| c.is_ascii_digit()) { + text + } else { + plain = decipher(text); + &plain + }; + outline(&sat_model(text)?) +} + +/// Binary data. +pub(crate) fn from_binary(bytes: &[u8]) -> Option { + if bytes.len() > MAX_BYTES { + return None; + } + outline(&sab_model(bytes)?) +} + +/// DXF's cipher of text data undone: each printable character is mapped back, and the space +/// written after a mapped `A` (a caret, which DXF reads as a control code) is dropped. +fn decipher(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + out.push(match c { + ' ' | '\n' | '\r' | '\t' => c, + '@'..='_' => char::from(159 - c as u8), + c if c.is_ascii() && !c.is_ascii_control() => char::from(c as u8 ^ 0x5F), + c => c, + }); + if c == '^' && chars.peek() == Some(&' ') { + chars.next(); + } + } + out +} + +/// How many values every record starts with in data of `version`. +fn header_len(version: u32) -> usize { + if version >= LONG_HEADER_VERSION { 3 } else { 1 } +} + +/// A text value as a value. +fn sat_tok(w: &str) -> Tok { + match w { + "{" => Tok::Open, + "}" => Tok::Close, + "forward" | "forward_v" => Tok::Sense(false), + "reversed" | "reversed_v" => Tok::Sense(true), + _ => { + if let Some(p) = w.strip_prefix('$').and_then(|p| p.parse::().ok()) { + return Tok::Ptr(p); + } + match w.parse::() { + Ok(v) if v.is_finite() => Tok::Num(v), + _ => Tok::Word(w.to_string()), + } + } + } +} + +/// Does this line start a record (`[-] $ …`)? +fn starts_record(line: &str) -> bool { + let mut words = line.split_whitespace(); + let first = words.next().unwrap_or_default(); + let (kind, next) = if first.starts_with('-') && first[1..].parse::().is_ok() { + (words.next().unwrap_or_default(), words.next().unwrap_or_default()) + } else { + (first, words.next().unwrap_or_default()) + }; + kind.starts_with(|c: char| c.is_ascii_alphabetic()) && next.starts_with('$') +} + +/// Text data's records: a version line, product and tolerance lines, then records ending in `#`. +fn sat_model(text: &str) -> Option { + let version = text.split_whitespace().next()?.parse::().ok().filter(|v| v.is_finite() && *v >= 0.0)? as u32; + let skip = header_len(version); + let mut offset = text.find('\n')? + 1; + let start = loop { + let rest = text.get(offset..)?; + let line = rest.split('\n').next().unwrap_or_default(); + if starts_record(line) { + break offset; + } + offset += line.len() + 1; + }; + let body = text.get(start..)?; + let (mut recs, mut at) = (Vec::new(), HashMap::new()); + let mut cur: Vec = vec![]; + let (mut kind, mut index): (Option, Option) = (None, None); + let mut i = 0; + let b = body.as_bytes(); + while i < b.len() { + if b[i].is_ascii_whitespace() { + i += 1; + continue; + } + let end = b[i..].iter().position(u8::is_ascii_whitespace).map_or(b.len(), |n| i + n); + let word = body.get(i..end)?; + i = end; + // A counted string: `@`, a space, then n bytes. + if let Some(n) = word.strip_prefix('@').and_then(|n| n.parse::().ok()) { + let from = (i + 1).min(b.len()); + let to = from.checked_add(n)?.min(b.len()); + cur.push(Tok::Word(body.get(from..to)?.to_string())); + i = to; + continue; + } + let (word, ends) = match word.strip_suffix('#') { + Some(w) => (w, true), + None => (word, false), + }; + if !word.is_empty() { + match &kind { + None if index.is_none() && word.starts_with('-') && word[1..].parse::().is_ok() => { + index = word[1..].parse().ok(); + } + None => { + if word.starts_with("End-of-") || word.starts_with("Begin-of-") { + break; + } + kind = Some(word.to_string()); + } + Some(_) => cur.push(sat_tok(word)), + } + } + if ends { + let toks = cur.split_off(skip.min(cur.len())); + cur.clear(); + if let Some(n) = index.take() { + at.insert(n, recs.len()); + } + recs.push(Rec { kind: kind.take().unwrap_or_default(), toks }); + } + } + Some(Model { recs, at }) +} + +/// Reads binary data's little-endian values. +struct Bytes<'b> { + b: &'b [u8], + i: usize, +} + +impl Bytes<'_> { + fn take(&mut self, n: usize) -> Option<&[u8]> { + let s = self.b.get(self.i..self.i.checked_add(n)?)?; + self.i += n; + Some(s) + } + fn u8(&mut self) -> Option { + self.take(1).map(|s| s[0]) + } + fn i16(&mut self) -> Option { + self.take(2).map(|s| f64::from(i16::from_le_bytes([s[0], s[1]]))) + } + fn u16(&mut self) -> Option { + self.take(2).map(|s| usize::from(u16::from_le_bytes([s[0], s[1]]))) + } + fn i32(&mut self) -> Option { + self.take(4).map(|s| i32::from_le_bytes([s[0], s[1], s[2], s[3]])) + } + fn u32(&mut self) -> Option { + self.take(4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])) + } + fn f64(&mut self) -> Option { + let s = self.take(8)?; + Some(f64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]])) + } + fn text(&mut self, n: usize) -> Option { + self.take(n).map(|s| String::from_utf8_lossy(s).into_owned()) + } +} + +/// Binary data's records: the magic, four numbers (version first), product and tolerance values, +/// then records of tagged values, each type name made of its parts. +fn sab_model(b: &[u8]) -> Option { + let mut r = Bytes { b: BINARY_MAGIC.iter().find_map(|m| b.strip_prefix(*m))?, i: 0 }; + let version = r.u32()?; + r.take(12)?; + let skip = header_len(version); + let mut recs = vec![]; + let (mut parts, mut kind, mut cur): (Vec, Option, Vec) = (vec![], None, vec![]); + while r.i < r.b.len() { + let tag = r.u8()?; + let tok = match tag { + 0x02 => Tok::Num(f64::from(i8::from_le_bytes([r.u8()?]))), + 0x03 => Tok::Num(r.i16()?), + 0x04 | 0x15 => Tok::Num(f64::from(r.i32()?)), + 0x05 => Tok::Num(f64::from(f32::from_le_bytes(r.take(4)?.try_into().ok()?))), + 0x06 | 0x17 => Tok::Num(r.f64()?), + 0x07 => { + let n = usize::from(r.u8()?); + Tok::Word(r.text(n)?) + } + 0x08 => { + let n = r.u16()?; + Tok::Word(r.text(n)?) + } + 0x09 | 0x12 => { + let n = usize::try_from(r.u32()?).ok()?; + Tok::Word(r.text(n)?) + } + 0x0A => Tok::Sense(true), + 0x0B => Tok::Sense(false), + 0x0C => Tok::Ptr(i64::from(r.i32()?)), + 0x0D | 0x0E => { + let n = usize::from(r.u8()?); + let name = r.text(n)?; + if kind.is_some() { + Tok::Word(name) + } else { + parts.push(name); + if tag == 0x0D { + let k = parts.join("-"); + parts.clear(); + if k.starts_with("End-of-") || k.starts_with("Begin-of-") { + break; + } + kind = Some(k); + } + continue; + } + } + 0x0F => Tok::Open, + 0x10 => Tok::Close, + 0x11 => { + if let Some(k) = kind.take() { + let toks = cur.split_off(skip.min(cur.len())); + recs.push(Rec { kind: k, toks }); + } + cur.clear(); + continue; + } + 0x13 | 0x14 => { + for _ in 0..3 { + cur.push(Tok::Num(r.f64()?)); + } + continue; + } + 0x16 => { + for _ in 0..2 { + cur.push(Tok::Num(r.f64()?)); + } + continue; + } + _ => return None, + }; + // Values before the first record are the header's. + if kind.is_some() { + cur.push(tok); + } + } + Some(Model { recs, at: HashMap::new() }) +} + +/// A body's placement: `p · m · scale + t`. +#[derive(Clone, Copy)] +struct Xf { + m: [P3; 3], + scale: f64, + t: P3, +} + +impl Xf { + const IDENTITY: Xf = Xf { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], scale: 1.0, t: [0.0; 3] }; + + /// A `transform` record's: nine matrix numbers row by row, the translation, the scale. + fn read(r: &Rec) -> Option { + let n: Vec = r.toks.iter().map_while(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect(); + if n.iter().any(|v| !v.is_finite()) { + return None; + } + let v = |i: usize| n.get(i).copied(); + let row = |i: usize| Some([v(i)?, v(i + 1)?, v(i + 2)?]); + let scale = v(12)?; + Some(Xf { m: [row(0)?, row(3)?, row(6)?], t: row(9)?, scale }) + } + + fn vector(&self, p: P3) -> P3 { + let [a, b, c] = self.m; + std::array::from_fn(|i| (p[0] * a[i] + p[1] * b[i] + p[2] * c[i]) * self.scale) + } + + fn point(&self, p: P3) -> P3 { + let v = self.vector(p); + std::array::from_fn(|i| v[i] + self.t[i]) + } +} + +/// Seen from above: x and y. +fn flat(p: P3) -> Point { + Point::new(p[0], p[1]) +} + +fn sub(a: P3, b: P3) -> P3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn dot(a: P3, b: P3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn cross(a: P3, b: P3) -> P3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn p3(n: &[f64], i: usize) -> Option { + Some([*n.get(i)?, *n.get(i + 1)?, *n.get(i + 2)?]) +} + +/// Endpoints farther apart than rounding at their coordinate size allows. +fn endpoints_apart(a: Point, b: Point) -> bool { + a.distance(b) > 1e-6 * (1.0 + a.x.hypot(a.y).max(b.x.hypot(b.y))) +} + +/// Every face's loops of every body, as one path (filled even-odd). +fn outline(m: &Model) -> Option { + let mut o = Outline { path: BezPath::new(), approximated: false, broken: false, ambiguous: false }; + // Records visited at every level together: chains shared between records are walked again + // each time. + let mut visits = 0usize; + let mut spend = |n: usize| { + visits = visits.saturating_add(n.max(1)); + (visits <= MAX_VISITS).then_some(()) + }; + for body in m.recs.iter().filter(|r| r.is("body")) { + spend(1)?; + let xf = if body.ptr(2) == -1 { Xf::IDENTITY } else { Xf::read(m.get_is(body.ptr(2), "transform")?)? }; + for lump in m.chain(body.ptr(0), "lump", 0, &mut o.broken) { + spend(1)?; + for shell in m.chain(lump.ptr(1), "shell", 0, &mut o.broken) { + spend(1)?; + for face in m.chain(shell.ptr(2), "face", 0, &mut o.broken) { + spend(1)?; + for lp in m.chain(face.ptr(1), "loop", 0, &mut o.broken) { + let ring = m.chain(lp.ptr(1), "coedge", 0, &mut o.broken); + spend(ring.len())?; + let complete = ring.last().is_some_and(|c| c.ptr(0) == lp.ptr(1)); + o.broken |= !complete; + let mut bp = BezPath::new(); + for c in ring { + let edge = m.get_is(c.ptr(3), "edge")?; + let (seg, ambiguous) = edge_path(m, edge, c.sense_after(3)?, &xf, &mut o.approximated)?; + o.ambiguous |= ambiguous; + if let (Some(end), Some(start)) = + (bp.elements().last().and_then(|e| e.end_point()), seg.elements().first().and_then(|e| e.end_point())) + { + o.broken |= endpoints_apart(end, start); + } + super::entity::append(&mut bp, &seg); + if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS { + return None; + } + } + if !bp.elements().is_empty() { + if complete + && let (Some(end), Some(start)) = + (bp.elements().last().and_then(|e| e.end_point()), bp.elements().first().and_then(|e| e.end_point())) + { + o.broken |= endpoints_apart(end, start); + } + // A loop of one curve ending where it starts is split in two: as one + // segment, its start and end would become one anchor. + if let [seg] = bp.segments().collect::>()[..] + && !matches!(seg, PathSeg::Line(_)) + { + let (a, b) = seg.subdivide(); + bp = BezPath::from_path_segments([a, b].into_iter()); + } + bp.close_path(); + if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS { + return None; + } + o.path.extend(bp); + } + } + } + } + } + } + let ok = !o.path.elements().is_empty() && curve::bounds(&o.path).is_some(); + ok.then_some(o) +} + +/// A vertex's position. +fn vertex(m: &Model, p: i64) -> Option { + let v = m.get_is(p, "vertex")?; + let n = m.get_is(v.ptr(1), "point")?.nums(); + p3(&n, 0).filter(|p| p.iter().all(|c| c.is_finite())) +} + +/// The edge as a coedge runs it (`reversed`: from its end vertex to its start), from the first +/// point. +fn edge_path(m: &Model, edge: &Rec, reversed: bool, xf: &Xf, approximated: &mut bool) -> Option<(BezPath, bool)> { + let (sv, ev) = (vertex(m, edge.ptr(0))?, vertex(m, edge.ptr(1))?); + let closed = edge.ptr(0) == edge.ptr(1); + let (from, to) = if reversed { (ev, sv) } else { (sv, ev) }; + // Against the curve's own direction? + let back = edge.sense_after(3)? != reversed; + let drawn = match m.get(edge.ptr(3)) { + // Only -1 means the edge has no curve. + None => { + *approximated |= edge.ptr(3) != -1; + None + } + Some(c) if c.is("straight-curve") => None, + Some(c) => { + let bp = if c.is("ellipse-curve") { + ellipse(c, from, to, closed, back, xf).map(|bp| (bp, false)) + } else if c.is("intcurve-curve") { + spline(c, from, to, closed, back, xf) + } else { + None + }; + *approximated |= bp.is_none(); + bp + } + }; + if let Some(bp) = drawn { + return Some(bp); + } + let mut bp = BezPath::new(); + bp.move_to(flat(xf.point(from))); + bp.line_to(flat(xf.point(to))); + Some((bp, false)) +} + +/// An `ellipse-curve` (centre, normal, major axis, ratio) from `from` to `to`; the whole curve +/// when the edge starts and ends at one vertex. It runs counter-clockwise about its normal, +/// clockwise when `back`. +fn ellipse(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option { + let n = c.nums(); + let (centre, normal, major, ratio) = (p3(&n, 0)?, p3(&n, 3)?, p3(&n, 6)?, *n.get(9)?); + let len = dot(normal, normal).sqrt(); + if !(len > 1e-12 && ratio > 0.0 && ratio.is_finite() && dot(major, major) > 1e-24) { + return None; + } + let minor = cross(normal, major).map(|v| v / len * ratio); + let angle = |p: P3| { + let d = sub(p, centre); + (dot(d, minor) / dot(minor, minor)).atan2(dot(d, major) / dot(major, major)) + }; + let (a, b) = (angle(from), angle(to)); + let tau = std::f64::consts::TAU; + let sweep = match (closed, back) { + (true, false) => tau, + (true, true) => -tau, + (false, false) => (b - a).rem_euclid(tau), + (false, true) => -(a - b).rem_euclid(tau), + }; + let (o, u, v) = (flat(xf.point(centre)), flat(xf.vector(major)), flat(xf.vector(minor))); + curve::ellipse(Affine::new([u.x, u.y, v.x, v.y, o.x, o.y]), a, sweep) +} + +/// An `intcurve-curve`'s B-spline (`nubs`, or `nurbs` with weights): degree, form, the knots +/// with their multiplicities (without the end knots, or with them), the control points. +fn bspline(toks: &[Tok]) -> Option { + let at = toks.iter().position(|t| matches!(t, Tok::Word(w) if matches!(w.as_str(), "nubs" | "nurbs" | "nullbs")))?; + let rational = match &toks[at] { + Tok::Word(w) if w == "nurbs" => true, + Tok::Word(w) if w == "nubs" => false, + _ => return None, + }; + let num = |i: usize| if let Some(Tok::Num(v)) = toks.get(i) { Some(*v) } else { None }; + let degree = num(at + 1).filter(|d| (1.0..=32.0).contains(d))? as usize; + let count = num(at + 3).filter(|n| *n >= 1.0 && *n <= toks.len() as f64)? as usize; + let mut knots = vec![]; + let mut i = at + 4; + for _ in 0..count { + let (k, mult) = (num(i)?, num(i + 1)?); + if !(mult >= 1.0 && mult <= (degree + 1) as f64) { + return None; + } + knots.extend(std::iter::repeat_n(k, mult as usize)); + i += 2; + } + let stride = if rational { 4 } else { 3 }; + let values: Vec = toks[i.min(toks.len())..].iter().map_while(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect(); + let available = values.len() / stride; + // The data leaves out the first and last knots; data that keeps them has two points fewer. + let short = (knots.len() + 1).checked_sub(degree)?; + let n = if available >= short { + let (first, last) = (*knots.first()?, *knots.last()?); + knots.insert(0, first); + knots.push(last); + short + } else { + knots.len().checked_sub(degree + 1)? + }; + if n == 0 || n > available { + return None; + } + let pts = values.chunks(stride).take(n).map(|c| [c[0], c[1], c[2]]).collect(); + let weights = rational.then(|| values.chunks(stride).take(n).map(|c| c[3]).collect()); + Some((degree, knots, pts, weights)) +} + +/// The distinct parameters of a cubic's self-intersection, when both lie on the curve. +fn cubic_crossing(cubic: kurbo::CubicBez) -> Option<(f64, f64)> { + let b = (cubic.p1 - cubic.p0) * 3.0; + let c = (cubic.p2 - cubic.p1) * 3.0 - b; + let d = (cubic.p3 - cubic.p0) - b - c; + let det = c.cross(d); + if det == 0.0 { + return None; + } + // Dividing P(s) - P(t) by s - t gives b + c*u + d*(u*u - v) = 0, + // where u = s + t and v = s*t. + let u = -b.cross(d) / det; + let v = u * u - b.cross(c) / det; + let discriminant = u * u - 4.0 * v; + if !discriminant.is_finite() || discriminant <= 0.0 { + return None; + } + let root = discriminant.sqrt(); + let (s, t) = ((u - root) * 0.5, (u + root) * 0.5); + (0.0 <= s && s < t && t <= 1.0).then_some((s, t)) +} + +/// An `intcurve-curve` from `from` to `to` (the part of its spline between them), the whole +/// ring when the edge starts and ends at one vertex; also whether trimming is ambiguous. +fn spline(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option<(BezPath, bool)> { + // The curve's own sense comes before its data. + let open = c.toks.iter().position(|t| *t == Tok::Open)?; + let curve_back = c.toks[..open].contains(&Tok::Sense(true)); + let (degree, knots, pts, weights) = bspline(&c.toks[open..])?; + let ctrl: Vec = pts.into_iter().map(|p| flat(xf.point(p))).collect(); + let full = curve::nurbs(degree, &knots, &ctrl, weights.as_deref())?; + let back = back != curve_back; + let segs: Vec = full.segments().collect(); + let (first, last) = (segs.first()?.start(), segs.last()?.end()); + let ring = first.distance(last) <= 1e-9 * (1.0 + first.to_vec2().hypot()); + let mut lengths = vec![0.0]; + for s in &segs { + lengths.push(lengths.last()? + s.arclen(1e-9)); + } + let total = *lengths.last()?; + let at = |p: P3| { + let p = flat(xf.point(p)); + let near: Vec<_> = segs.iter().enumerate().map(|(i, s)| (s.nearest(p, 1e-9), i)).collect(); + let (n, i) = near.iter().min_by(|a, b| a.0.distance_sq.total_cmp(&b.0.distance_sq))?; + let along = |i: usize, t: f64| lengths[i] + segs[i].subsegment(0.0..t).arclen(1e-9); + let tolerance = 1e-6 * (1.0 + p.x.hypot(p.y)); + let mut locations: Vec<_> = + near.iter().filter(|(n, i)| !endpoints_apart(p, segs[*i].eval(n.t))).map(|(n, i)| (*i as f64 + n.t, along(*i, n.t))).collect(); + for (i, s) in segs.iter().enumerate() { + if let PathSeg::Cubic(cubic) = s + && let Some((a, b)) = cubic_crossing(*cubic) + && !endpoints_apart(p, cubic.eval(a)) + { + locations.extend([a, b].map(|t| (i as f64 + t, along(i, t)))); + } + } + // Nearby ends at a segment joint, or at a closed curve's seam, are one location. + locations.sort_by(|a, b| a.0.total_cmp(&b.0)); + locations.dedup_by(|a, b| (a.1 - b.1).abs() <= 4.0 * tolerance); + if ring && locations.len() > 1 && (total - (locations.last()?.1 - locations.first()?.1)).abs() <= 4.0 * tolerance { + locations.pop(); + } + Some((*i as f64 + n.t, locations)) + }; + let mut ambiguous = false; + let part = if closed && ring { + let (_, locations) = at(from)?; + ambiguous = locations.len() > 1; + full + } else { + let bounds = if closed { + let (_, locations) = at(from)?; + if let [a, b] = locations.as_slice() { + Some((a.0, b.0)) + } else { + ambiguous = true; + None + } + } else { + let ((ga, a), (gb, b)) = (at(from)?, at(to)?); + ambiguous = a.len() > 1 || b.len() > 1; + Some((ga, gb)) + }; + if let Some((ga, gb)) = bounds { + let (lo, hi) = if back { (gb, ga) } else { (ga, gb) }; + let pieces = if lo <= hi || !ring { + piece(&segs, lo.min(hi), hi.max(lo)) + } else { + [piece(&segs, lo, segs.len() as f64), piece(&segs, 0.0, hi)].concat() + }; + if pieces.is_empty() { + return None; + } + BezPath::from_path_segments(pieces.into_iter()) + } else { + full + } + }; + Some((if back { part.reverse_subpaths() } else { part }, ambiguous)) +} + +/// The parts of `segs` from `lo` to `hi`, counted in segments (2.5: halfway along the third). +fn piece(segs: &[PathSeg], lo: f64, hi: f64) -> Vec { + let mut out = vec![]; + for (i, s) in segs.iter().enumerate() { + let (t0, t1) = ((lo - i as f64).max(0.0), (hi - i as f64).min(1.0)); + if t1 > t0 { + out.push(s.subsegment(t0..t1)); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cubic_crossings_have_two_distinct_parameters() { + let cubic = kurbo::CubicBez::new((36.0, -18.0), (-28.0, 26.0), (-28.0, -26.0), (36.0, 18.0)); + let (s, t) = cubic_crossing(cubic).unwrap(); + assert!((s - 0.25).abs() < 1e-12 && (t - 0.75).abs() < 1e-12, "{s}, {t}"); + let plain = kurbo::CubicBez::new((0.0, 0.0), (30.0, 50.0), (70.0, -50.0), (100.0, 0.0)); + assert!(cubic_crossing(plain).is_none()); + } + + #[test] + fn deciphering_maps_each_character_back_and_drops_the_caret_space() { + // "Ab@_ 7#" ciphered: A→^ (and a space), b→=, @→_, _→@, 7→h, #→|. + assert_eq!(decipher("^ =_@ h|"), "Ab@_ 7#"); + } +} diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 4e1bed4ae1..0b3532ca87 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -27,7 +27,7 @@ const MAX_NODES: usize = 2_000_000; /// per item of the block looked at for it (art on hidden layers too). const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 }; /// The most path elements an import makes (blocks drawn as art are copied for every placement). -const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 }; +pub(crate) const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 }; /// The most dash lengths an import keeps (every dashed path holds its own copy of its pattern). const MAX_DASH_VALUES: usize = if cfg!(test) { 1_000 } else { 4_000_000 }; /// The most bytes of text, font names and symbol names an import copies into objects (a block's @@ -128,7 +128,7 @@ impl<'d, 'a> Build<'d, 'a> { Self { d, o, - conv: Converter::default(), + conv: Converter::new(d.regions.clone()), doc: Document::new(1.0, 1.0), blocks: HashMap::new(), bounds: HashMap::new(), diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index 9d147b08cf..acca831206 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -1,7 +1,8 @@ //! Entities to drawing items: their geometry in world coordinates (drawing units, y up) and the //! properties they take from their layer or block (resolved when the items become art). -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; +use std::rc::Rc; use kurbo::{BezPath, PathEl}; use vectorcraft_doc::Justify; @@ -9,6 +10,7 @@ use vectorcraft_geom::{Affine, Point, Vec2}; use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath}; +use super::acis; use super::curve::{self, Vertex}; use super::reader::{aci_paper, point}; @@ -174,6 +176,8 @@ pub(crate) struct Converter { pub warnings: Vec, /// Array insert copies made so far, against [`MAX_TOTAL_CELLS`]. cells: i64, + /// The binary solid-modeler data of regions, by handle (DXF 2013 and later). + regions: Rc>>, } const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries"; @@ -182,8 +186,16 @@ const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertic const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each"; const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all"; const FAR_AWAY: &str = "entities with coordinates out of range are left out"; +const REGION_CURVES: &str = "region edges of some curve types come in as straight lines"; +const REGION_BROKEN: &str = "regions whose outlines break off are closed with straight lines"; +const REGION_AMBIGUOUS: &str = "region edges on curves that cross themselves may come in along the wrong part of the curve"; impl Converter { + /// A converter reading regions' binary data from `regions`. + pub fn new(regions: Rc>>) -> Self { + Self { regions, ..Self::default() } + } + fn warn(&mut self, w: &str) { if !self.warnings.iter().any(|x| x == w) { self.warnings.push(w.to_string()); @@ -255,6 +267,7 @@ impl Converter { model::EntityKind::Dimension(d) => { Some(Geom::Insert(InsertItem { block: d.block.as_ref()?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] })) } + _ if e.kind == "REGION" => self.region(e), _ => None, } } @@ -378,6 +391,41 @@ impl Converter { out } + /// A region as a filled path: its solid-modeler data as text in groups 1 (a line each) and 3 + /// (the rest of a long line), or, from DXF 2013 on, binary data kept by handle. + fn region(&mut self, e: &EntityRecord<'_>) -> Option { + let g = e.groups(); + let own = g.subclass("AcDbModelerGeometry"); + let tags = if own.0.is_empty() { g.0 } else { own.0 }; + let mut text = String::new(); + for t in tags { + match t.code { + 1 => { + if !text.is_empty() { + text.push('\n'); + } + text.push_str(t.str_ref().unwrap_or_default()); + } + 3 => text.push_str(t.str_ref().unwrap_or_default()), + _ => {} + } + if text.len() > acis::MAX_BYTES { + return None; + } + } + let outline = if text.trim().is_empty() { acis::from_binary(self.regions.get(&e.record().handle()?)?) } else { acis::from_text(&text) }?; + if outline.approximated { + self.warn(REGION_CURVES); + } + if outline.broken { + self.warn(REGION_BROKEN); + } + if outline.ambiguous { + self.warn(REGION_AMBIGUOUS); + } + Some(Geom::Path { bp: outline.path, fill: true, width: 0.0 }) + } + fn hatch(&mut self, h: &model::Hatch, ocs: Affine) -> Option { let mut bp = BezPath::new(); for l in &h.loops { @@ -601,7 +649,7 @@ fn boundary(path: &HatchPath) -> Option { } /// `seg` continuing `bp`: joined by a line when it starts elsewhere. -fn append(bp: &mut BezPath, seg: &BezPath) { +pub(super) fn append(bp: &mut BezPath, seg: &BezPath) { for el in seg.elements() { match *el { PathEl::MoveTo(p) => { diff --git a/crates/cad/src/import/reader.rs b/crates/cad/src/import/reader.rs index f2ed000809..bfa1293b8d 100644 --- a/crates/cad/src/import/reader.rs +++ b/crates/cad/src/import/reader.rs @@ -1,7 +1,8 @@ //! What the import uses of a drawing, from `craft_dxf::model`: header variables; the layer, //! linetype and text style tables; the blocks; the entities; the layouts. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; +use std::rc::Rc; use craft_dxf::model::{self, EntityRecord}; use vectorcraft_geom::Point; @@ -81,6 +82,9 @@ pub(crate) struct Drawing<'a> { pub layouts: Vec, /// How many sections the file has (none: not a drawing). pub sections: usize, + /// The binary solid-modeler data of the regions, by handle (DXF 2013 and later keep it in + /// the ACDSDATA section). + pub regions: Rc>>, } /// The colour of index `i` on paper: index 7 (white on a CAD screen) is black. @@ -112,6 +116,7 @@ impl<'a> Drawing<'a> { } let block_names = doc.block_names(); d.layouts = layouts(&doc, &block_names); + d.regions = Rc::new(region_data(&doc)); for b in doc.blocks { if b.name.is_empty() { continue; @@ -148,6 +153,69 @@ impl<'a> Drawing<'a> { } } +/// The binary data of each region in the ACDSDATA section: an `ACDSRECORD` names its entity's +/// handle (320), then holds the bytes (310 chunks) after `2 ASM_Data`, their count in 94. +fn region_data(doc: &model::Document<'_>) -> HashMap> { + let records = doc.entities.iter().chain(doc.blocks.iter().flat_map(|b| &b.entities)); + let wanted: HashSet = records.filter(|e| e.kind == "REGION").filter_map(|e| e.record().handle()).collect(); + let mut out = HashMap::new(); + if wanted.is_empty() { + return out; + } + for section in doc.other_sections.iter().filter(|s| s.name.eq_ignore_ascii_case("ACDSDATA")) { + for r in model::records(section.tags).into_iter().filter(|r| r.kind == "ACDSRECORD") { + let Some(handle) = r.tags.iter().find(|t| t.code == 320).and_then(|t| model::parse_handle(&t.str())) else { continue }; + if !wanted.contains(&handle) || out.contains_key(&handle) { + continue; + } + let Some(at) = r.tags.iter().position(|t| t.code == 2 && t.str_ref().is_some_and(|s| s.trim() == "ASM_Data")) else { continue }; + let data = r.tags.get(at + 1..).unwrap_or_default(); + let size = data.iter().find(|t| t.code == 94).and_then(|t| usize::try_from(t.i64()).ok()); + let mut bytes = Vec::new(); + let mut whole = true; + for t in data.iter().filter(|t| t.code == 310) { + whole = hex_bytes(t.str_ref().unwrap_or_default().trim(), &mut bytes); + if !whole || bytes.len() > super::acis::MAX_BYTES { + break; + } + } + if !whole { + continue; + } + if let Some(bytes) = sized_region(bytes, size, super::acis::MAX_BYTES) { + out.insert(handle, bytes); + } + } + } + out +} + +/// A region's `bytes` cut to its declared `size`, or `None` when the record declares more bytes +/// than it holds (the data was cut short or damaged) or the data is longer than `limit`. +pub(super) fn sized_region(mut bytes: Vec, size: Option, limit: usize) -> Option> { + match size { + Some(n) if n <= bytes.len() => bytes.truncate(n), + Some(_) => return None, + None => {} + } + (bytes.len() <= limit).then_some(bytes) +} + +/// Hex digits' bytes, two digits each, onto `out`. False when `hex` has a character that is not +/// a hex digit or an odd number of digits. +pub(super) fn hex_bytes(hex: &str, out: &mut Vec) -> bool { + let digit = |c: u8| (c as char).to_digit(16).and_then(|d| u8::try_from(d).ok()); + let (pairs, rest) = hex.as_bytes().as_chunks::<2>(); + if !rest.is_empty() { + return false; + } + for pair in pairs { + let (Some(hi), Some(lo)) = (digit(pair[0]), digit(pair[1])) else { return false }; + out.push(hi << 4 | lo); + } + true +} + pub(crate) fn point(p: model::Point) -> Point { Point::new(p[0], p[1]) } diff --git a/crates/cad/src/import/tests_region.rs b/crates/cad/src/import/tests_region.rs new file mode 100644 index 0000000000..a44e02c84d --- /dev/null +++ b/crates/cad/src/import/tests_region.rs @@ -0,0 +1,686 @@ +//! Regions: solid-modeler data in text (ciphered or not, lines split over groups 1 and 3) and in +//! binary form (the ACDSDATA section) comes in as one filled path of the region's loops; lines, +//! circles, ellipses and spline edges keep their shape, coedge and edge senses are followed, a +//! body's transform is applied, and damaged data is left out without hanging. + +use kurbo::{BezPath, Shape}; +use vectorcraft_doc::{Document, Node, NodeKind, Unit}; +use vectorcraft_geom::{FillRule, Point, Rect}; + +use super::*; + +/// A curve an edge runs along. +#[derive(Clone)] +enum Curve { + Line, + /// A circle about the z axis (`-z`: clockwise) of this centre and radius. + Circle { + c: [f64; 2], + r: f64, + down: bool, + }, + /// A curve record's text after its first three values. + Raw(String), +} + +/// An edge of a loop, from `a` to `b` as the loop runs it. `flip`: the edge is stored from `b` +/// to `a` and the coedge runs it reversed; `against`: the edge also runs against its curve. +#[derive(Clone)] +struct E { + a: [f64; 2], + b: [f64; 2], + curve: Curve, + flip: bool, + against: bool, +} + +fn line(a: [f64; 2], b: [f64; 2]) -> E { + E { a, b, curve: Curve::Line, flip: false, against: false } +} + +fn circle(c: [f64; 2], r: f64, down: bool) -> E { + let p = [c[0] + r, c[1]]; + E { a: p, b: p, curve: Curve::Circle { c, r, down }, flip: false, against: false } +} + +fn square(lo: f64, hi: f64) -> Vec { + vec![line([lo, lo], [hi, lo]), line([hi, lo], [hi, hi]), line([hi, hi], [lo, hi]), line([lo, hi], [lo, lo])] +} + +/// Text data (version 700) of one face with `loops`, placed by `transform` (12 numbers and a +/// scale) when given. +fn sat(loops: &[Vec], transform: Option<&str>) -> String { + let mut recs: Vec = vec![]; + let xf = if transform.is_some() { "$5" } else { "$-1" }; + recs.push(format!("body $-1 -1 $-1 $1 $-1 {xf}")); + recs.push("lump $-1 -1 $-1 $-1 $2 $0".into()); + recs.push("shell $-1 -1 $-1 $-1 $-1 $3 $-1 $1".into()); + recs.push("face $-1 -1 $-1 $-1 $6 $2 $-1 $4 forward single".into()); + recs.push("plane-surface $-1 -1 $-1 0 0 0 0 0 1 1 0 0 forward_v I I I I".into()); + recs.push(format!("transform $-1 -1 $-1 {} no_rotate no_reflect no_shear", transform.unwrap_or("1 0 0 0 1 0 0 0 1 0 0 0 1"))); + let mut base = 6; + for (l, edges) in loops.iter().enumerate() { + let next_loop = if l + 1 < loops.len() { format!("${}", base + 1 + 7 * edges.len()) } else { "$-1".into() }; + recs.push(format!("loop $-1 -1 $-1 {next_loop} ${} $3", base + 1)); + let n = edges.len(); + for (j, e) in edges.iter().enumerate() { + let at = |k: usize| base + 1 + 7 * k; + let i = at(j); + let (coedge, edge, sv, ev, sp, ep, cv) = (i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6); + let (start, end) = if e.flip { (e.b, e.a) } else { (e.a, e.b) }; + let ev = if start == end { sv } else { ev }; + let sense = |r: bool| if r { "reversed" } else { "forward" }; + recs.push(format!("coedge $-1 -1 $-1 ${} ${} $-1 ${edge} {} ${base} $-1", at((j + 1) % n), at((j + n - 1) % n), sense(e.flip))); + recs.push(format!("edge $-1 -1 $-1 ${sv} 0 ${ev} 1 ${coedge} ${cv} {} @7 unknown", sense(e.against))); + recs.push(format!("vertex $-1 -1 $-1 ${edge} ${sp}")); + recs.push(format!("vertex $-1 -1 $-1 ${edge} ${ep}")); + recs.push(format!("point $-1 -1 $-1 {} {} 0", start[0], start[1])); + recs.push(format!("point $-1 -1 $-1 {} {} 0", end[0], end[1])); + recs.push(match &e.curve { + Curve::Line => format!("straight-curve $-1 -1 $-1 {} {} 0 {} {} 0 I I", start[0], start[1], end[0] - start[0], end[1] - start[1]), + Curve::Circle { c, r, down } => { + format!("ellipse-curve $-1 -1 $-1 {} {} 0 0 0 {} {r} 0 0 1 I I", c[0], c[1], if *down { -1 } else { 1 }) + } + Curve::Raw(s) => s.clone(), + }); + } + base += 1 + 7 * n; + } + let mut s = String::from("700 0 1 0\n9 Synthetic 3 ASM 4 none\n1 9.9999999999999995e-07 1e-10\n"); + for r in recs { + s.push_str(&r); + s.push_str(" #\n"); + } + s.push_str("End-of-ACIS-data\n"); + s +} + +/// DXF's cipher of text data: each printable character mapped, a space after each caret. +fn encipher(s: &str) -> String { + let mut out = String::new(); + for c in s.chars() { + let m = match c { + ' ' | '\n' => c, + '@'..='_' => char::from(159 - c as u8), + c => char::from(c as u8 ^ 0x5F), + }; + out.push(m); + if m == '^' { + out.push(' '); + } + } + out +} + +/// A drawing of `version` with `entities` and, when given, an ACDSDATA section. +fn drawing(version: &str, entities: &[(i32, String)], acds: &[(i32, String)]) -> Vec { + let mut s = format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\n{version}\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n"); + let put = |pairs: &[(i32, String)], s: &mut String| { + for (c, v) in pairs { + s.push_str(&format!("{c:>3}\n{v}\n")); + } + }; + put(entities, &mut s); + s.push_str(" 0\nENDSEC\n"); + if !acds.is_empty() { + s.push_str(" 0\nSECTION\n 2\nACDSDATA\n"); + put(acds, &mut s); + s.push_str(" 0\nENDSEC\n"); + } + s.push_str(" 0\nEOF\n"); + s.into_bytes() +} + +/// A REGION entity holding `lines` of text data (`split`: each line over 40 characters goes on +/// in group 3 from inside a word). +fn region_text(lines: &str, split: bool) -> Vec<(i32, String)> { + let mut e = vec![ + (0, "REGION".to_string()), + (5, "2A".into()), + (8, "0".into()), + (100, "AcDbEntity".into()), + (100, "AcDbModelerGeometry".into()), + (70, "1".into()), + ]; + for l in lines.lines() { + let b = l.as_bytes(); + let cut = (40..b.len()).find(|&i| !b[i - 1].is_ascii_whitespace() && !b[i].is_ascii_whitespace()); + if let Some(at) = cut.filter(|_| split) { + e.push((1, l[..at].to_string())); + e.push((3, l[at..].to_string())); + } else { + e.push((1, l.to_string())); + } + } + e +} + +fn points() -> ImportOptions { + ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() } +} + +/// Every leaf path of the document as one path, in document coordinates. +fn outline(doc: &Document) -> BezPath { + let mut bp = BezPath::new(); + doc.walk(|n: &Node| { + if let NodeKind::Path { path, .. } = &n.kind { + bp.extend(path.to_bezpath()); + } + }); + bp +} + +/// Inside the path by the even-odd rule. +fn filled(bp: &BezPath, p: Point) -> bool { + bp.winding(p) % 2 != 0 +} + +/// The region (drawing `x, y`) is filled at `inside` and not at `outside`. +fn check(doc: &Document, inside: &[[f64; 2]], outside: &[[f64; 2]]) { + let h = doc.artboards[0].rect.height(); + let (bp, at) = (outline(doc), |p: &[f64; 2]| Point::new(p[0], h - p[1])); + for p in inside { + assert!(filled(&bp, at(p)), "{p:?} should be filled"); + } + for p in outside { + assert!(!filled(&bp, at(p)), "{p:?} should be empty"); + } +} + +/// The only top-level object: filled, without a stroke. +fn filled_object(doc: &Document) -> Node { + let [n] = &doc.layers[0].children().unwrap()[..] else { panic!("{:?}", doc.layers[0].children()) }; + assert!(n.appearance.fill().is_some_and(|f| !f.paint.is_none()), "regions are filled"); + assert!(n.appearance.stroke().is_none_or(|s| s.paint.is_none()), "regions have no stroke"); + n.as_ref().clone() +} + +fn square_with_hole() -> Vec> { + vec![square(0.0, 100.0), vec![circle([50.0, 50.0], 20.0, true)]] +} + +#[test] +fn ciphered_text_data_comes_in_as_a_filled_path_with_its_hole() { + let text = encipher(&sat(&square_with_hole(), None)); + let r = import(&drawing("AC1015", ®ion_text(&text, false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let n = filled_object(&r.document); + let NodeKind::Compound { rule, .. } = &n.kind else { panic!("{:?}", n.kind) }; + assert_eq!(*rule, FillRule::EvenOdd); + assert!((n.geometric_bounds().unwrap().area() - 10_000.0).abs() < 1e-6); + check(&r.document, &[[10.0, 10.0], [50.0, 75.0], [90.0, 50.0]], &[[50.0, 50.0], [60.0, 55.0], [110.0, 50.0]]); + // The hole is a circle. + let h = r.document.artboards[0].rect.height(); + let bp = outline(&r.document); + let centre = Point::new(50.0, h - 50.0); + let on_hole: Vec = bp.segments().map(|s| kurbo::ParamCurve::eval(&s, 0.5).distance(centre)).filter(|d| *d < 30.0).collect(); + assert!(!on_hole.is_empty() && on_hole.iter().all(|d| (d - 20.0).abs() < 1e-3), "{on_hole:?}"); +} + +#[test] +fn plain_text_split_over_groups_one_and_three_reads_alike() { + let text = sat(&square_with_hole(), None); + let r = import(&drawing("AC1021", ®ion_text(&text, true), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + filled_object(&r.document); + check(&r.document, &[[10.0, 10.0]], &[[50.0, 50.0]]); + // Before version 700 a record starts with its attribute alone. + let old: String = text.replacen("700 0 1 0", "400 0 1 0", 1).lines().map(|l| format!("{}\n", l.replacen(" $-1 -1 $-1 ", " $-1 ", 1))).collect(); + assert!(old.contains("body $-1 $1 $-1 $-1 #"), "{old}"); + let r = import(&drawing("AC1012", ®ion_text(&old, false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + check(&r.document, &[[10.0, 10.0]], &[[50.0, 50.0]]); +} + +/// Binary data of the same records: tagged values, type names in parts. +fn sab(text: &str) -> Vec { + let mut b = b"ACIS BinaryFile".to_vec(); + for v in [700u32, 0, 1, 0] { + b.extend(v.to_le_bytes()); + } + let string = |b: &mut Vec, tag: u8, s: &str| { + b.push(tag); + b.push(u8::try_from(s.len()).unwrap()); + b.extend(s.as_bytes()); + }; + string(&mut b, 0x07, "Synthetic"); + b.push(0x06); + b.extend(1.0f64.to_le_bytes()); + for line in text.lines().skip(3) { + if line.starts_with("End-of") { + break; + } + let mut words = line.split_whitespace().peekable(); + let kind = words.next().unwrap(); + let parts: Vec<&str> = kind.split('-').collect(); + for (i, p) in parts.iter().enumerate() { + string(&mut b, if i + 1 == parts.len() { 0x0D } else { 0x0E }, p); + } + while let Some(w) = words.next() { + match w { + "#" => {} + "forward" | "forward_v" => b.push(0x0B), + "reversed" | "reversed_v" => b.push(0x0A), + "{" => b.push(0x0F), + "}" => b.push(0x10), + w if w.starts_with('$') => { + b.push(0x0C); + b.extend(w[1..].parse::().unwrap().to_le_bytes()); + } + w if w.starts_with('@') => { + let s = words.next().unwrap(); + string(&mut b, 0x07, s); + } + w => match w.parse::() { + Ok(v) => { + b.push(0x06); + b.extend(v.to_le_bytes()); + } + Err(_) => string(&mut b, 0x07, w), + }, + } + } + b.push(0x11); + } + for p in ["End", "of", "ASM"] { + string(&mut b, 0x0E, p); + } + string(&mut b, 0x0D, "data"); + b +} + +/// An ACDSDATA record holding `bytes` for the entity with handle 2A, in 50-byte chunks. +fn acds(bytes: &[u8]) -> Vec<(i32, String)> { + let mut a = vec![ + (0, "ACDSRECORD".to_string()), + (90, "1".into()), + (2, "AcDbDs::ID".into()), + (280, "10".into()), + (320, "2A".into()), + (2, "ASM_Data".into()), + (280, "15".into()), + (94, bytes.len().to_string()), + ]; + for c in bytes.chunks(50) { + a.push((310, c.iter().map(|b| format!("{b:02X}")).collect())); + } + a +} + +#[test] +fn binary_data_in_the_acdsdata_section_reads_alike() { + let bytes = sab(&sat(&square_with_hole(), None)); + let e = vec![(0, "REGION".to_string()), (5, "2A".into()), (8, "0".into()), (100, "AcDbModelerGeometry".into()), (290, "0".into())]; + // ASM's signature in place of ACIS's, as DXF 2018 may write it. + let asm = [b"ASM BinaryFile4".as_slice(), &bytes[b"ACIS BinaryFile".len()..]].concat(); + for data in [&bytes, &asm] { + let r = import(&drawing("AC1032", &e, &acds(data)), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + filled_object(&r.document); + check(&r.document, &[[10.0, 10.0], [50.0, 75.0]], &[[50.0, 50.0]]); + } + // Without its data the region is left out and listed. + let r = import(&drawing("AC1027", &e, &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings); + // Data shorter than its declared size is left out and listed too. + let mut short = acds(&bytes); + short[7].1 = (bytes.len() + 1).to_string(); + let r = import(&drawing("AC1032", &e, &short), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings); + // A chunk with an odd number of digits or a character that is not a hex digit fails to read. + let mut out = Vec::new(); + assert!(super::reader::hex_bytes("0aFf", &mut out)); + assert_eq!(out, [0x0A, 0xFF]); + for hex in ["0aF", "0aZZ", "0 aF"] { + assert!(!super::reader::hex_bytes(hex, &mut Vec::new()), "{hex}"); + } + // Data longer than the limit is left out, unless its declared size cuts it within the limit. + let sized = |len: usize, size: Option| super::reader::sized_region(vec![7; len], size, 8).map(|b| b.len()); + assert_eq!(sized(10, None), None); + assert_eq!(sized(10, Some(9)), None); + assert_eq!(sized(10, Some(11)), None); + assert_eq!(sized(10, Some(5)), Some(5)); + assert_eq!(sized(8, None), Some(8)); +} + +/// A drawing the export writes (R2000, millimetres) with a region added to its entities. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +fn exported_with_region() -> Vec { + let d = Document::new(200.0, 200.0); + let o = + crate::DxfOptions { version: crate::DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..crate::DxfOptions::default() }; + let dxf = String::from_utf8(crate::export(&d, &o).unwrap().bytes).unwrap(); + let mut region = String::new(); + for (c, v) in region_text(&encipher(&sat(&square_with_hole(), None)), false) { + let v = if c == 5 { "FFF0".to_string() } else { v }; + region.push_str(&format!("{c:>3}\n{v}\n")); + } + let at = dxf.find("ENTITIES\n").unwrap() + "ENTITIES\n".len(); + format!("{}{region}{}", &dxf[..at], &dxf[at..]).into_bytes() +} + +/// The converter writes a region's data as text in a 2004 drawing and as binary data in the +/// ACDSDATA section of a 2013 one; both come in as the DXF does. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn regions_in_dwg_drawings_come_in_from_text_and_binary_data() { + crate::dwg::allow_in_process(); + let dxf = exported_with_region(); + let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), center: false, ..ImportOptions::default() }; + let want = import(&dxf, &o).unwrap(); + assert!(want.warnings.is_empty(), "{:?}", want.warnings); + let want = filled_object(&want.document).geometric_bounds().unwrap(); + for version in ["AC1018", "AC1027"] { + let dwg = craft_dwg::dxf_to_dwg_as(&dxf, version).unwrap(); + let back = craft_dwg::dwg_to_dxf(&dwg).unwrap(); + let binary = String::from_utf8_lossy(&back).contains("ACDSDATA"); + assert_eq!(binary, version == "AC1027", "{version}: the data's form"); + let r = import(&dwg, &o).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("REGION")), "{version}: {:?}", r.warnings); + let got = filled_object(&r.document).geometric_bounds().unwrap(); + assert!((got.area() - want.area()).abs() < 1e-6 && got.origin().distance(want.origin()) < 1e-6, "{version}: {got:?} {want:?}"); + let mm = 72.0 / 25.4; + check_at(&r.document, mm, &[[10.0, 10.0], [50.0, 75.0]], &[[50.0, 50.0]]); + } +} + +/// [`check`] for art at `k` points per drawing unit. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +fn check_at(doc: &Document, k: f64, inside: &[[f64; 2]], outside: &[[f64; 2]]) { + let scale = |ps: &[[f64; 2]]| ps.iter().map(|p| [p[0] * k, p[1] * k]).collect::>(); + check(doc, &scale(inside), &scale(outside)); +} + +#[test] +fn reversed_coedges_and_edges_run_their_curves_backwards() { + // A quarter of a circle from (100, 0) to (0, 100): on a counter-clockwise circle run along + // it, or on a clockwise one run against it, with the edge stored either way round. + for (down, flip, against) in [(false, true, true), (true, false, true), (true, true, false), (false, false, false)] { + let quarter = E { a: [100.0, 0.0], b: [0.0, 100.0], curve: Curve::Circle { c: [0.0, 0.0], r: 100.0, down }, flip, against }; + let flipped_line = E { flip: true, against: true, ..line([0.0, 100.0], [0.0, 0.0]) }; + let quadrant = vec![line([0.0, 0.0], [100.0, 0.0]), quarter, flipped_line]; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[quadrant], None), false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + // A quarter disc, not the three quarters the other way round. + check(&r.document, &[[20.0, 20.0], [10.0, 50.0], [65.0, 65.0]], &[[80.0, 80.0], [-50.0, 50.0], [50.0, -50.0]]); + let b = filled_object(&r.document).geometric_bounds().unwrap(); + assert!((b.width() - 100.0).abs() < 1e-6 && (b.height() - 100.0).abs() < 1e-6, "{down} {flip} {against}: {b:?}"); + } +} + +#[test] +fn a_spline_edge_keeps_only_its_part_of_the_curve() { + // A parabola from (0, 0) through (100, -50) to (200, 0); the edge runs its first half, + // stored from its end and run reversed. + let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 2 open 2 0 2 1 2 0 0 0 100 -100 0 200 0 0 0 } I I".to_string(); + let half = E { a: [0.0, 0.0], b: [100.0, -50.0], curve: Curve::Raw(curve), flip: true, against: true }; + let shape = vec![half, line([100.0, -50.0], [100.0, 50.0]), line([100.0, 50.0], [0.0, 0.0])]; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[shape], None), false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let b = filled_object(&r.document).geometric_bounds().unwrap(); + assert!((b.width() - 100.0).abs() < 1e-6, "only the first half of the curve: {b:?}"); + assert!((b.height() - 100.0).abs() < 1e-6, "down to the curve's midpoint: {b:?}"); + // Below the chord from (0, 0) to (100, -50), above the curve. + check(&r.document, &[[50.0, -30.0], [90.0, 0.0]], &[[50.0, -45.0], [150.0, 0.0]]); +} + +#[test] +fn a_spline_edge_warns_when_an_endpoint_lies_on_separate_parts_of_its_curve() { + // The first and last spans both pass through (0, 0), away from their ends. + let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 open 4 0 2 1 1 2 1 3 2 -100 -100 0 100 100 0 -100 100 0 100 -100 0 } I I"; + for back in [false, true] { + let (a, b) = if back { ([100.0, 100.0], [0.0, 0.0]) } else { ([0.0, 0.0], [100.0, 100.0]) }; + let edge = E { a, b, curve: Curve::Raw(curve.into()), flip: false, against: back }; + let shape = vec![edge, line(b, [100.0, 0.0]), line([100.0, 0.0], a)]; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[shape], None), false), &[]), &points()).unwrap(); + assert_eq!(r.warnings, ["region edges on curves that cross themselves may come in along the wrong part of the curve"]); + assert!(!outline(&r.document).elements().is_empty()); + } +} + +#[test] +fn a_spline_edge_warns_when_an_endpoint_is_at_one_cubic_spans_crossing() { + let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 3 open 2 0 3 1 3 36 -18 0 -28 26 0 -28 -26 0 36 18 0 } I I"; + let edge = E { a: [0.0, 0.0], b: [36.0, 18.0], curve: Curve::Raw(curve.into()), flip: false, against: false }; + let shape = vec![edge, line([36.0, 18.0], [36.0, 0.0]), line([36.0, 0.0], [0.0, 0.0])]; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[shape], None), false), &[]), &points()).unwrap(); + assert_eq!(r.warnings, ["region edges on curves that cross themselves may come in along the wrong part of the curve"]); + assert!(!outline(&r.document).elements().is_empty()); +} + +#[test] +fn a_closed_spline_edge_keeps_the_loop_at_one_cubic_spans_crossing() { + // The curve crosses (0, 0) at 0.25 and 0.75; the loop reaches (-12, 0) at 0.5. + let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 3 open 2 0 3 1 3 36 -18 0 -28 26 0 -28 -26 0 36 18 0 } I I"; + for back in [false, true] { + let edge = E { a: [0.0, 0.0], b: [0.0, 0.0], curve: Curve::Raw(curve.into()), flip: false, against: back }; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[vec![edge]], None), false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + check(&r.document, &[[-6.0, 0.0]], &[[30.0, 0.0]]); + } +} + +#[test] +fn a_closed_spline_ring_warns_only_when_its_vertex_is_at_the_crossing() { + // The first and third spans cross (0, 0) halfway along each; the seam is (-100, -100). + let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 closed 5 0 2 1 1 2 1 3 1 4 2 -100 -100 0 100 100 0 -100 100 0 100 -100 0 -100 -100 0 } I I"; + for a in [[0.0, 0.0], [-100.0, -100.0]] { + for back in [false, true] { + let edge = E { a, b: a, curve: Curve::Raw(curve.into()), flip: false, against: back }; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[vec![edge]], None), false), &[]), &points()).unwrap(); + if a == [0.0, 0.0] { + assert_eq!(r.warnings, ["region edges on curves that cross themselves may come in along the wrong part of the curve"]); + } else { + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + } + check(&r.document, &[[0.0, 50.0], [0.0, -50.0]], &[[75.0, 0.0], [-75.0, 0.0]]); + } + } +} + +#[test] +fn spline_joints_and_a_closed_curves_seam_do_not_warn() { + for (curve, a) in [ + ("intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 open 3 0 2 1 1 2 2 0 0 0 100 0 0 100 100 0 } I I", [100.0, 0.0]), + ( + "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 closed 5 0 2 1 1 2 1 3 1 4 2 0 0 0 100 0 0 100 100 0 0 100 0 0 0 0 } I I", + [0.0, 0.0], + ), + ] { + let edge = E { a, b: [100.0, 100.0], curve: Curve::Raw(curve.into()), flip: false, against: false }; + let shape = vec![edge, line([100.0, 100.0], [0.0, 100.0]), line([0.0, 100.0], a)]; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[shape], None), false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(!outline(&r.document).elements().is_empty()); + } +} + +#[test] +fn a_transform_places_the_body() { + // Twice the size, moved 1000 along x. + let text = sat(&[square(0.0, 10.0)], Some("1 0 0 0 1 0 0 0 1 1000 0 0 2")); + let r = import(&drawing("AC1015", ®ion_text(&text, false), &[]), &points()).unwrap(); + let b = filled_object(&r.document).geometric_bounds().unwrap(); + assert!((b.width() - 20.0).abs() < 1e-9 && (b.height() - 20.0).abs() < 1e-9, "{b:?}"); + let h = r.document.artboards[0].rect.height(); + assert!(Rect::new(b.x0, h - b.y1, b.x1, h - b.y0).contains(Point::new(1010.0, 10.0)), "{b:?}"); +} + +#[test] +fn missing_or_unreadable_body_transforms_leave_the_region_out() { + let text = sat(&[square(0.0, 10.0)], Some("1 0 0 0 1 0 0 0 1 1000 0 0 2")); + for damaged in [ + text.replacen("body $-1 -1 $-1 $1 $-1 $5", "body $-1 -1 $-1 $1 $-1 $99999", 1), + text.replacen("body $-1 -1 $-1 $1 $-1 $5", "body $-1 -1 $-1 $1 $-1 $4", 1), + text.replacen("1 0 0 0 1 0 0 0 1 1000 0 0 2 no_rotate", "1 0 0 0 1 0 0 0 1 1000 0 no_rotate", 1), + text.replacen("1000 0 0 2 no_rotate", "1000 0 0 no_rotate", 1), + text.replacen("1000 0 0 2 no_rotate", "1000 0 0 unreadable no_rotate", 1), + text.replacen("1 0 0 0 1 0 0 0 1 1000", "1 unreadable 0 0 0 1 0 0 0 1 1000", 1), + ] { + assert_ne!(damaged, text); + let r = import(&drawing("AC1015", ®ion_text(&damaged, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings); + assert!(outline(&r.document).elements().is_empty()); + } +} + +#[test] +fn missing_or_unreadable_edge_and_coedge_senses_leave_the_region_out() { + let text = sat(&[square(0.0, 10.0)], None); + for before in ["$8 forward $6", "$13 forward @7 unknown"] { + assert!(text.contains(before), "{text}"); + for sense in ["", "unreadable"] { + let damaged = text.replacen(before, &before.replace("forward", sense), 1); + let r = import(&drawing("AC1015", ®ion_text(&damaged, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{before} {sense}: {:?}", r.warnings); + assert!(outline(&r.document).elements().is_empty()); + } + } +} + +#[test] +fn missing_curve_records_warn_when_edges_come_in_straight() { + let text = sat(&square_with_hole(), None); + let before = "$42 forward @7 unknown"; + assert!(text.contains(before), "{text}"); + let damaged = text.replacen(before, "$99999 forward @7 unknown", 1); + let r = import(&drawing("AC1015", ®ion_text(&damaged, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("straight lines")), "{:?}", r.warnings); + check(&r.document, &[[10.0, 10.0], [50.0, 50.0]], &[[110.0, 50.0]]); +} + +#[test] +fn disconnected_edges_warn_even_when_the_coedge_ring_is_complete() { + let mut edges = square(0.0, 100.0); + edges[1].a[0] += 5.0; + edges[1].b[0] += 5.0; + let mut closing = square(0.0, 100.0); + closing[3].b[0] += 5.0; + for edges in [edges, closing] { + let r = import(&drawing("AC1015", ®ion_text(&sat(&[edges], None), false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("break off")), "{:?}", r.warnings); + check(&r.document, &[[50.0, 50.0]], &[[110.0, 50.0]]); + } +} + +#[test] +fn unknown_curves_come_in_straight_and_damaged_data_is_left_out() { + let mut edges = square(0.0, 100.0); + edges[0].curve = Curve::Raw("helix-curve $-1 -1 $-1 0 0 0".into()); + let r = import(&drawing("AC1015", ®ion_text(&sat(&[edges], None), false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("straight lines")), "{:?}", r.warnings); + check(&r.document, &[[50.0, 50.0]], &[]); + // A ring of coedges whose second points at itself ends there; a body pointing out of range + // and text that isn't data are listed as left out. + let ring = sat(&[square(0.0, 10.0)], None); + assert!(ring.contains("coedge $-1 -1 $-1 $21 $7 $-1")); + let ring = ring.replace("coedge $-1 -1 $-1 $21 $7 $-1", "coedge $-1 -1 $-1 $14 $7 $-1"); + let wild = sat(&[square(0.0, 10.0)], None).replace("body $-1 -1 $-1 $1", "body $-1 -1 $-1 $99999"); + let mut e = region_text(&ring, false); + for text in [wild.as_str(), "not data", "700 0 1 0\n"] { + e.extend(region_text(text, false)); + } + let r = import(&drawing("AC1015", &e, &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("3 REGION")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("break off")), "{:?}", r.warnings); + // The ring's two edges and the line that closes them. + check(&r.document, &[[8.0, 2.0]], &[[2.0, 8.0]]); + // A hole whose ring of coedges is missing is listed, not dropped quietly. + let holed = sat(&[square(0.0, 100.0), square(40.0, 60.0)], None); + assert!(holed.contains("loop $-1 -1 $-1 $-1 $36 $3"), "{holed}"); + let holed = holed.replace("loop $-1 -1 $-1 $-1 $36 $3", "loop $-1 -1 $-1 $-1 $99999 $3"); + let r = import(&drawing("AC1015", ®ion_text(&holed, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("break off")), "{:?}", r.warnings); +} + +#[test] +fn shared_topology_chains_are_walked_within_a_limit() { + // 100 lumps share one chain of 100 shells, each shell one chain of 100 faces: the first face + // a square, the others without loops. That is 1,000,000 faces visited, over the limit of + // records visited, though only 40,000 coedges. + let one = sat(&[square(0.0, 10.0)], None); + let mut recs: Vec = one.lines().skip(3).take_while(|l| !l.starts_with("End-of")).map(str::to_string).collect(); + let (lumps, shells, faces) = (recs.len(), recs.len() + 100, recs.len() + 200); + recs[0] = format!("body $-1 -1 $-1 ${lumps} $-1 $-1 #"); + let next = |i: usize, n: usize, at: usize| if i + 1 < n { format!("${}", at + i + 1) } else { "$-1".into() }; + for i in 0..100 { + recs.push(format!("lump $-1 -1 $-1 {} ${shells} $0 #", next(i, 100, lumps))); + } + for i in 0..100 { + recs.push(format!("shell $-1 -1 $-1 {} $-1 ${faces} $-1 ${lumps} #", next(i, 100, shells))); + } + for i in 0..100 { + let lp = if i == 0 { "$6" } else { "$-1" }; + recs.push(format!("face $-1 -1 $-1 {} {lp} ${shells} $-1 $4 forward single #", next(i, 100, faces))); + } + let text = format!("{}\n{}\nEnd-of-ACIS-data\n", one.lines().take(3).collect::>().join("\n"), recs.join("\n")); + let r = import(&drawing("AC1015", ®ion_text(&text, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings); + // One lump, shell and face of the same records come in. + let small = text.replacen(&format!("lump $-1 -1 $-1 ${} ", lumps + 1), "lump $-1 -1 $-1 $-1 ", 1); + let small = small.replacen(&format!("shell $-1 -1 $-1 ${} ", shells + 1), "shell $-1 -1 $-1 $-1 ", 1); + let small = small.replacen(&format!("face $-1 -1 $-1 ${} ", faces + 1), "face $-1 -1 $-1 $-1 ", 1); + let r = import(&drawing("AC1015", ®ion_text(&small, false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + check(&r.document, &[[5.0, 5.0]], &[[15.0, 5.0]]); +} + +#[test] +fn broken_topology_chains_warn_when_the_next_record_is_missing_or_the_wrong_type() { + let text = sat(&[square(0.0, 100.0), square(40.0, 60.0)], None); + for (before, prefix) in [ + ("lump $-1 -1 $-1 $-1", "lump $-1 -1 $-1"), + ("shell $-1 -1 $-1 $-1", "shell $-1 -1 $-1"), + ("face $-1 -1 $-1 $-1", "face $-1 -1 $-1"), + ("loop $-1 -1 $-1 $35", "loop $-1 -1 $-1"), + ] { + for next in ["$99999", "$4"] { + assert!(text.contains(before), "{before}"); + let broken = text.replacen(before, &format!("{prefix} {next}"), 1); + let r = import(&drawing("AC1015", ®ion_text(&broken, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("break off")), "{before} {next}: {:?}", r.warnings); + check(&r.document, &[[10.0, 10.0]], &[[110.0, 10.0]]); + } + } +} + +#[test] +fn shared_spline_loops_are_left_out_when_their_generated_outline_is_too_large() { + // Many faces share one loop. Its degree-one spline follows a square with many knot spans, + // so generated elements reach their limit well before topology visits do. + let spans = 1024; + let mut curve = format!("intcurve-curve $-1 -1 $-1 forward {{ exactcur 0 nubs 1 closed {} 0 2", spans + 1); + for i in 1..spans { + curve.push_str(&format!(" {i} 1")); + } + curve.push_str(&format!(" {spans} 2")); + for i in 0..=spans { + let t = (i % (spans / 4)) as f64 / (spans / 4) as f64; + let (x, y) = match i / (spans / 4) { + 0 => (t, 0.0), + 1 => (1.0, t), + 2 => (1.0 - t, 1.0), + _ => (0.0, 1.0 - t), + }; + let (x, y) = if i == spans { (0.0, 0.0) } else { (x, y) }; + curve.push_str(&format!(" {x} {y} 0")); + } + curve.push_str(" } I I"); + let edge = E { a: [0.0, 0.0], b: [0.0, 0.0], curve: Curve::Raw(curve), flip: false, against: false }; + let one = sat(&[vec![edge]], None); + let r = import(&drawing("AC1015", ®ion_text(&one, false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + check(&r.document, &[[0.5, 0.5]], &[[1.5, 0.5]]); + let mut recs: Vec = one.lines().skip(3).take_while(|l| !l.starts_with("End-of")).map(str::to_string).collect(); + let faces = recs.len(); + let count = super::build::MAX_ELEMENTS / (spans + 2) + 1; + recs[2] = format!("shell $-1 -1 $-1 $-1 $-1 ${faces} $-1 $1 #"); + for i in 0..count { + let next = if i + 1 < count { format!("${}", faces + i + 1) } else { "$-1".into() }; + recs.push(format!("face $-1 -1 $-1 {next} $6 $2 $-1 $4 forward single #")); + } + let text = format!("{}\n{}\nEnd-of-ACIS-data\n", one.lines().take(3).collect::>().join("\n"), recs.join("\n")); + let r = import(&drawing("AC1015", ®ion_text(&text, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings); + assert!(outline(&r.document).elements().is_empty()); +} diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 39b39fc294..78927ef970 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -227,6 +227,16 @@ impl Node { } } + /// The path whose anchors the anchor tools edit, in document space: a path's, or the path of + /// type on a path outside perspective (Add, Delete and Anchor Point tools, Pen + Alt). + pub fn anchor_path(&self) -> Option> { + match &self.kind { + NodeKind::Path { path, .. } => Some(std::borrow::Cow::Borrowed(path)), + NodeKind::Text(t) if self.extras().perspective.is_none() => t.type_path().map(std::borrow::Cow::Owned), + _ => None, + } + } + pub fn path_data_mut(&mut self) -> Option<&mut PathData> { match &mut self.kind { NodeKind::Path { path, .. } => Some(path), diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index 7c13b8f755..eb882f5e77 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -368,18 +368,29 @@ impl Document { } } -/// Whether any fill or stroke of `n`'s subtree overprints, characters' too. -fn overprints_anywhere(n: &Node) -> bool { +/// Whether any fill or stroke of `n`'s subtree overprints, characters' too, and with `images` an +/// image's color. +fn overprints_anywhere(n: &Node, images: bool) -> bool { n.appearance.items.iter().any(|i| i.overprint()) - || n.extras().colorize_overprint + || (images && n.extras().colorize_overprint) || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke)) - || n.children().is_some_and(|c| c.iter().any(|c| overprints_anywhere(c))) + || n.children().is_some_and(|c| c.iter().any(|c| overprints_anywhere(c, images))) } /// Stop every fill and stroke of `a`'s subtree overprinting (characters' too), copying only the /// nodes on the way to them. pub fn clear_overprints(a: &mut Arc) { - if !overprints_anywhere(a) { + clear(a, true); +} + +/// [`clear_overprints`] for fills, strokes and characters only: the colors of images keep their +/// overprint ([`crate::NodeExtras::colorize_overprint`]). +pub fn clear_paint_overprints(a: &mut Arc) { + clear(a, false); +} + +fn clear(a: &mut Arc, images: bool) { + if !overprints_anywhere(a, images) { return; } let n = Arc::make_mut(a); @@ -392,11 +403,11 @@ pub fn clear_overprints(a: &mut Arc) { } } // Also the flag an image keeps after its color is removed. - if n.extras().colorize_overprint { + if images && n.extras().colorize_overprint { n.extras_mut().colorize_overprint = false; } for c in n.children_mut().into_iter().flatten() { - clear_overprints(c); + clear(c, images); } } diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 5b213f3b08..c4d3cd6bb4 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -487,6 +487,16 @@ impl TextObject { true }) } + /// Replace type on a path's path with `path`, given in document space; the brackets keep their + /// fractions of the path. False, changing nothing, for other type, a degenerate `xf` or a path + /// that would not be finite. + pub fn set_type_path(&mut self, path: &PathData) -> bool { + matches!(self.kind, TextKind::OnPath { .. }) + && self.reshape_local(|frame, to_text| { + *frame = path.transformed(to_text); + true + }) + } /// Edit a copy of the area frame with `f` (given the document → text space map) and keep it /// when `f` succeeds and the result is finite. fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool { diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 586deb604c..138d75ed61 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -18,6 +18,7 @@ pub mod colormgmt; pub mod colortheme; pub mod compositefonts; mod compoundshape; +pub mod conceptvector; pub(crate) mod create; mod css; mod cut; @@ -365,6 +366,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(panelcmds::specs()); v.extend(artboardalign::specs()); v.extend(buildcmds::specs()); + v.extend(conceptvector::specs()); v.extend(shaper::specs()); v.extend(brushsym::specs()); v.extend(patterncmds::specs()); diff --git a/crates/engine/src/cmd/addons/cleanup.rs b/crates/engine/src/cmd/addons/cleanup.rs index 8f4def2dcd..90fc007910 100644 --- a/crates/engine/src/cmd/addons/cleanup.rs +++ b/crates/engine/src/cmd/addons/cleanup.rs @@ -65,7 +65,7 @@ pub fn specs() -> Vec { "Fix All Issues", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents → {scope, total, fixed: {kind: count}}", + "{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents. An error, with nothing fixed, when the fixes would delete the artboard an open Create Font Sheet dialog uses → {scope, total, fixed: {kind: count}}", has_doc, fix ), @@ -262,6 +262,13 @@ fn fix(s: &mut Session, p: &Value) -> Result { } // With nothing to fix, the document and its undo history stay as they are. if total > 0 { + if let Some(guard) = &s.artboard_deletion_guard { + let st = s.doc()?; + let protected = |doc: &Document| doc.artboards.iter().any(|a| a.id == guard.artboard); + if (st.uid, st.reverts) == guard.document && protected(&st.doc) && !protected(&d) { + return Err(EngineError::Other(guard.message.clone())); + } + } sel.prune(&d); s.edit("Fix Issues", |doc, selection| { *doc = d; diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index ef010d7f32..10df5322e1 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -5,8 +5,10 @@ //! (). Release Type on a Path //! splits type on a path into point type holding the same text and the plain path it was set on //! (#5532). The reference app has no command for it, so it goes beyond parity and changes no -//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's. +//! parity score. Create Font Sheet ([`font_sheet`]) sets a line of sample text in every font. Its +//! submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's. +pub mod font_sheet; pub mod numbers; #[cfg(test)] mod tests; @@ -76,6 +78,9 @@ pub fn specs() -> Vec { numbers::make_numbers ), ] + .into_iter() + .chain(font_sheet::specs()) + .collect() } /// Release Type on a Path's command (the id in [`specs`]). diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet.rs b/crates/engine/src/cmd/addons/typetools/font_sheet.rs new file mode 100644 index 0000000000..5f86fe9ea4 --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/font_sheet.rs @@ -0,0 +1,376 @@ +//! Create Font Sheet (`addon.type.fontSheet`; Object › Plug-ins › Type Tools › Create Font +//! Sheet…): a line of sample text set once in each font the font menus list (or in the fonts a +//! filter or a list names), each labeled with its font's name, flowed down columns on the active +//! artboard and on new artboards to its right when it fills, as one group made in one undo step. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind, TextObject, TextRun}; +use vectorcraft_geom::{Affine, Point, Rect, Shape}; +use vectorcraft_text::{FontDb, FontMatch}; + +use super::super::super::create::{new_type_para, new_type_style}; +use super::super::super::panelcmds::artboard_at; +use super::super::super::typecmd::refresh_bounds; +use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; +use crate::{Result, Session}; + +/// The command. +pub const COMMAND: &str = "addon.type.fontSheet"; +/// The sample text when none is given. +pub const DEFAULT_TEXT: &str = "The quick brown fox jumps over the lazy dog"; +/// Most fonts one sheet sets. +pub const MAX_FONTS: usize = 5000; +/// Most characters the sample text has. +pub const MAX_CHARS: usize = 1000; +/// The largest size a label is set at; a smaller sample's label is set at the sample's size. +const LABEL_SIZE: f64 = 9.0; +/// The space between the artboards the sheet adds, as `artboard.new` leaves it. +const ARTBOARD_GAP: f64 = 20.0; +/// The page a document without artboards lays the sheet out on (US Letter). +const LETTER: Rect = Rect { x0: 0.0, y0: 0.0, x1: 612.0, y1: 792.0 }; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.type.fontSheet", + "Create Font Sheet", + ["Object", "Plug-ins", "Type Tools"], + None, + "{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once; an error with any filter, an empty one included), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards), artboard?: n (0-based; the artboard the first page is; default: the active one), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, every line aligned left (right-to-left samples too), flowed down the columns of the active artboard, or artboard `artboard` (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An entry whose font lacks a glyph needed by the sample stays on the sheet, and is listed in `fallback` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], fallback: [entry name…], artboards: [index…] (the artboards added), warning?}", + has_doc, + font_sheet + )] +} + +/// `key` of `p`: `default` when omitted, else a number in `range`. +fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive) -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(default), + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && range.contains(n)) + .ok_or_else(|| bad(COMMAND, format!("`{key}` must be a number {}..{}", range.start(), range.end()))), + } +} + +/// The sample text of `p`: one line, not empty, at most [`MAX_CHARS`] characters. +fn sample_text(p: &Value) -> Result { + let text = match p.get("text") { + None | Some(Value::Null) => return Ok(DEFAULT_TEXT.into()), + Some(Value::String(t)) => t.clone(), + Some(_) => return Err(bad(COMMAND, "`text` must be a string")), + }; + if text.trim().is_empty() { + return Err(bad(COMMAND, "`text` must not be empty")); + } + // The line and paragraph separators break a line too. + if text.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')) { + return Err(bad(COMMAND, "`text` must be one line, without line breaks or other control characters")); + } + if text.chars().count() > MAX_CHARS { + return Err(bad(COMMAND, format!("`text` must be at most {MAX_CHARS} characters"))); + } + Ok(text) +} + +/// The families the sheet sets, in order: those `families` names, else those the font menus of +/// `db` list whose name contains `filter`. +fn families(p: &Value, db: &FontDb) -> Result> { + let filter = match p.get("filter") { + None | Some(Value::Null) => None, + Some(Value::String(f)) => Some(f.trim().to_lowercase()).filter(|f| !f.is_empty()), + Some(_) => return Err(bad(COMMAND, "`filter` must be a string")), + }; + let listed = match p.get("families") { + None | Some(Value::Null) => { + let menu = db.menu_family_list(); + let wanted = |f: &&String| filter.as_ref().is_none_or(|w| f.to_lowercase().contains(w.as_str())); + let found: Vec = menu.iter().filter(wanted).cloned().collect(); + if found.is_empty() { + return Err(bad(COMMAND, "no font family matches `filter`")); + } + return Ok(found); + } + Some(_) if p.get("filter").is_some_and(|f| !f.is_null()) => return Err(bad(COMMAND, "give `families` or `filter`, not both")), + Some(Value::Array(a)) => a, + Some(_) => return Err(bad(COMMAND, "`families` must be a list of font family names")), + }; + if listed.is_empty() { + return Err(bad(COMMAND, "`families` must name at least one family")); + } + let mut out: Vec = Vec::with_capacity(listed.len()); + for f in listed { + let f = f.as_str().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(COMMAND, "`families` must be a list of font family names"))?; + if !db.has_family(f) { + return Err(bad(COMMAND, format!("font family `{f}` is not available"))); + } + // The name as the font menus spell it, looked up as the database compares names. + let name = match db.composite_font(f) { + Some(c) => c.name.clone(), + None => db.canonical(f, "").0, + }; + if out.iter().any(|o| o.to_lowercase() == name.to_lowercase()) { + return Err(bad(COMMAND, format!("`families` names `{name}` twice"))); + } + out.push(name); + } + Ok(out) +} + +/// The index of the artboard the view has active, else the one the document opened on, else the first. +fn active_artboard(st: &crate::DocState) -> usize { + let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id); + st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0) +} + +fn font_sheet(s: &mut Session, p: &Value) -> Result { + font_sheet_in(s, p, FontDb::global()) +} + +/// [`font_sheet`] over the fonts of `db`. +fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { + const C: &str = COMMAND; + let text = sample_text(p)?; + let size = number(p, "size", 12.0, 1.0..=1296.0)?; + let columns = number(p, "columns", 2.0, 1.0..=50.0)?; + if columns.fract() != 0.0 { + return Err(bad(C, "`columns` must be a whole number 1..50")); + } + let columns = columns as usize; + let gap = number(p, "gap", 12.0, 0.0..=1000.0)?; + let margin = number(p, "margin", 36.0, 0.0..=1000.0)?; + let all_styles = switch_or(p, "allStyles", false, C)?; + let labels = switch_or(p, "labels", true, C)?; + let new_artboards = switch_or(p, "newArtboards", true, C)?; + let families = families(p, db)?; + + // Each entry's font: (family, style); no style for the family's Regular or closest style. + let mut fonts: Vec<(String, Option)> = vec![]; + for f in &families { + let styles = if all_styles { db.styles(f) } else { vec![] }; + if styles.is_empty() { + fonts.push((f.clone(), None)); + } else { + fonts.extend(styles.into_iter().map(|st| (f.clone(), Some(st)))); + } + if fonts.len() > MAX_FONTS { + return Err(bad(C, format!("a sheet sets at most {MAX_FONTS} fonts: give `filter` or `families`"))); + } + } + + let label = size.min(LABEL_SIZE); + // The artboard named, else `activeArtboard` (a replay of the journal), else the view's active + // one, which the journal entry then records as `activeArtboard` so a replay uses the same artboard. + let named = artboard_at(&s.doc()?.doc, p, "artboard", C)?; + let active = match named.or(artboard_at(&s.doc()?.doc, p, "activeArtboard", C)?) { + Some(i) => i, + None => { + let st = s.doc()?; + let i = active_artboard(st); + if i < st.doc.artboards.len() { + s.note_journal("activeArtboard", json!(i)); + } + i + } + }; + let st = s.doc()?; + let d = &st.doc; + let template = d.artboards.get(active).cloned(); + let page = template.as_ref().map_or(LETTER, |a| a.rect); + let right = d.artboards.iter().map(|a| a.rect.x1).fold(page.x1, f64::max); + let system_layout = d.setup.system_layout; + let parent = st.target_parent()?; + // An entry's first baseline is at least one line's size below its top, and the entry at least + // this tall; the fonts are only laid out when the page has room for that. + let (least_above, least_height) = (if labels { label } else { size }, if labels { label } else { 0.0 } + size * 1.5); + let (inner_w, inner_h) = (page.width() - 2.0 * margin, page.height() - 2.0 * margin); + let column_w = (inner_w - gap * (columns - 1) as f64) / columns as f64; + let no_room = || bad(C, "the margin, gap and columns leave no room for a font on the artboard"); + if column_w <= 0.0 || inner_h < least_height { + return Err(no_room()); + } + + let label_style = { + let mut style = new_type_style(s, &json!({ "size": label }), C)?; + style.leading = Some(label * 1.2); + style + }; + // Each entry laid out at the origin, and how far its laid-out ink reaches above and below its first baseline. + let mut laid: Vec<(String, TextObject, (f64, f64))> = Vec::with_capacity(fonts.len()); + let mut skipped: Vec = vec![]; + // The entries whose font lacks a glyph needed by the sample. + let mut fallback: Vec = vec![]; + for (family, style) in fonts { + let mut sample = new_type_style(s, &json!({ "size": size, "font": family, "style": style }), C)?; + sample.leading = Some(size * 1.2); + let name = match &style { + Some(st) => format!("{family} {st}"), + None => family.clone(), + }; + // A font that doesn't load is drawn in the fallback font, and a style that doesn't in the + // family's closest style: either is left out. A composite font is left out when a part + // that sets the sample names a font or style that doesn't load. + let composite = db.composite_font(&family).is_some(); + // Layout picks a font for each character as typed, then draws All Caps type, and the + // lowercase letters of Small Caps type, in capitals in that font, so coverage is checked on both. + let caps = sample.all_caps || sample.small_caps.is_some(); + let (loads, covers) = if composite { + // Glyph coverage is checked on the characters layout draws, in the sample's numeral system. + let covers = db.composite_cased_coverage(&family, &[text.as_str()], sample.digits, caps).is_none_or(|c| c.lacking.is_empty()); + (db.composite_coverage(&family, &[text.as_str()]).is_some_and(|c| c.status == FontMatch::Exact), covers) + } else { + let wanted = db.canonical(&family, "").0; + match db.face(&sample.font_family, &sample.font_style) { + Some(face) if face.family.eq_ignore_ascii_case(&wanted) && style.as_ref().is_none_or(|st| face.style.eq_ignore_ascii_case(st)) => { + let drawn = |t: &str| vectorcraft_text::drawn_chars(t, sample.digits).all(|c| face.covers(c)); + let capitals = || text.chars().flat_map(char::to_uppercase).collect::(); + (true, drawn(&text) && (!caps || drawn(&capitals()))) + } + _ => (false, true), + } + }; + if !loads { + skipped.push(name); + continue; + } + if !covers { + fallback.push(name.clone()); + } + let (first, more) = if labels { + (TextRun::new(format!("{name}\n"), label_style.clone()), Some(TextRun::new(text.clone(), sample))) + } else { + (TextRun::new(text.clone(), sample), None) + }; + let t = laid_out(first, more, system_layout); + let extent = ink_extent(&t); + laid.push((name, t, extent)); + } + if laid.is_empty() { + return Err(bad(C, "none of the fonts could be loaded")); + } + + // Each page's layout: each entry's first baseline as far below its top as its ink reaches above + // it, a row as tall as the tallest entry with the gap below it, and the rows that fit inside the margin. + let height = laid.iter().map(|(.., (a, b))| a.max(least_above) + b).fold(least_height, f64::max); + let pitch = height + gap; + if inner_h < height { + return Err(no_room()); + } + let rows = (((inner_h + gap) / pitch).floor() as usize).max(1); + let per_page = rows * columns; + // Where page `k` starts: the active artboard, then to the right of every artboard. + let page_x = |k: usize| if k == 0 { page.x0 } else { right + ARTBOARD_GAP + (k - 1) as f64 * (page.width() + ARTBOARD_GAP) }; + let mut entries: Vec<(String, TextObject)> = Vec::with_capacity(laid.len()); + for (i, (name, mut t, (above, _))) in laid.into_iter().enumerate() { + let (k, j) = (i / per_page, i % per_page); + let (col, row) = (j / rows, j % rows); + let x = page_x(k) + margin + col as f64 * (column_w + gap); + let baseline = page.y0 + margin + row as f64 * pitch + above.max(least_above); + // The layout is in text space, so moving the type keeps it. + t.xf = Affine::translate((x, baseline)); + entries.push((name, t)); + } + let count = entries.len(); + let pages = count.div_ceil(per_page); + let boards: Vec = (1..pages).map(|k| Rect::new(page_x(k), page.y0, page_x(k) + page.width(), page.y1)).collect(); + let template = template.filter(|_| new_artboards); + let (gid, added) = s.edit("Create Font Sheet", |d, sel| { + let mut added = vec![]; + if let Some(template) = template { + for rect in boards { + let mut a = template.clone(); + a.id = d.next_artboard_id(); + a.name = format!("Artboard {}", d.artboards.len() + 1); + a.rect = rect; + a.locked = false; + d.artboards.push(a); + added.push(d.artboards.len() - 1); + } + } + let children: Vec> = entries + .into_iter() + .map(|(name, t)| { + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.name = Some(name); + Arc::new(n) + }) + .collect(); + let gid = d.alloc_id(); + let mut g = Node::new(gid, NodeKind::Group { children, clip: false }); + g.name = Some("Font Sheet".into()); + d.insert(parent, usize::MAX, g)?; + sel.set([gid]); + Ok((gid, added)) + })?; + let mut out = json!({ "id": gid.0, "count": count, "skipped": skipped, "fallback": fallback, "artboards": added }); + let warnings: Vec = skipped_warning(&skipped).into_iter().chain(fallback_warning(&fallback)).collect(); + if !warnings.is_empty() { + out["warning"] = json!(warnings.join("; ")); + } + Ok(out) +} + +/// The warning a sheet with entries whose font lacks a glyph of the sample gives, naming the first few. +fn fallback_warning(fallback: &[String]) -> Option { + const NAMED: usize = 5; + let (first, more) = (fallback.iter().take(NAMED).cloned().collect::>(), fallback.len().saturating_sub(NAMED)); + match (first.is_empty(), more) { + (true, _) => None, + (false, 0) => Some(format!("{} font(s) lack glyphs for the sample: {}", fallback.len(), first.join(", "))), + (false, more) => Some(format!("{} font(s) lack glyphs for the sample: {} and {more} more", fallback.len(), first.join(", "))), + } +} + +/// Point type set in `first` and then `more`, with its first baseline at the origin, laid out. +fn laid_out(first: TextRun, more: Option, system_layout: bool) -> TextObject { + let mut t = TextObject::point(Point::ZERO, "", first.style.clone()); + t.runs = std::iter::once(first).chain(more).collect(); + // Every paragraph is aligned left, right-to-left ones too, so each starts at the column's edge. + t.para = vectorcraft_doc::ParaStyle { justify: vectorcraft_doc::Justify::Left, ..new_type_para() }; + t.system_layout = system_layout; + t.normalize_paras(); + let layout = vectorcraft_text::layout(FontDb::global(), &t); + t.cached_bounds = Some(layout.bounds); + t.cached_baselines = layout.baselines(); + let mut ink = layout.run_ink_bounds.clone(); + for (run, bar) in vectorcraft_text::decorations(&layout, FontDb::global(), &t) { + if let Some(bounds) = ink.get_mut(run) { + let bar = bar.bounding_box(); + *bounds = Some(bounds.map_or(bar, |bounds| bounds.union(bar))); + } + } + t.cached_ink = Some((layout.bounds, ink.iter().copied().flatten().reduce(|a, b| a.union(b)))); + if t.runs.len() == 2 + && let (Some(label), Some(sample)) = (ink[0], ink[1]) + { + let overlap = label.y1 - sample.y0; + if overlap > 0.0 + && let Some(run) = t.runs.get_mut(1) + { + run.style.leading = Some(run.style.leading.unwrap_or(run.style.size * 1.2) + overlap); + refresh_bounds(&mut t); + } + } + t +} + +/// How far the ink of laid-out type `t` reaches above and below its first baseline, underline and +/// strikethrough bars included; none when nothing draws. +fn ink_extent(t: &TextObject) -> (f64, f64) { + t.cached_ink.and_then(|(_, ink)| ink).map_or((0.0, 0.0), |b| ((-b.y0).max(0.0), b.y1.max(0.0))) +} + +/// The warning a sheet that left fonts out gives, naming the first few. +fn skipped_warning(skipped: &[String]) -> Option { + const NAMED: usize = 5; + let (first, more) = (skipped.iter().take(NAMED).cloned().collect::>(), skipped.len().saturating_sub(NAMED)); + match (first.is_empty(), more) { + (true, _) => None, + (false, 0) => Some(format!("{} font(s) could not be loaded and were left out: {}", skipped.len(), first.join(", "))), + (false, more) => Some(format!("{} font(s) could not be loaded and were left out: {} and {more} more", skipped.len(), first.join(", "))), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs new file mode 100644 index 0000000000..143f1dc2b3 --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs @@ -0,0 +1,636 @@ +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeId, NodeKind, TextObject}; +use vectorcraft_text::FontDb; + +use super::{COMMAND, DEFAULT_TEXT, MAX_CHARS}; +use crate::Session; + +/// The bundled families, available on every platform. +const BUNDLED: [&str; 3] = ["Inter", "Source Serif 4", "JetBrains Mono"]; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn group(s: &Session, r: &Value) -> Node { + s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().clone() +} + +/// Each entry of the sheet `g`: its name and its type. +fn entries(g: &Node) -> Vec<(String, TextObject)> { + g.children() + .unwrap() + .iter() + .map(|n| match &n.kind { + NodeKind::Text(t) => (n.name.clone().unwrap_or_default(), (**t).clone()), + _ => panic!("a font sheet holds only type"), + }) + .collect() +} + +/// Where the first baseline of `t` starts. +fn origin(t: &TextObject) -> (f64, f64) { + let [.., x, y] = t.xf.as_coeffs(); + (x, y) +} + +#[test] +fn a_sheet_sets_the_text_in_each_family_labeled_in_columns_in_one_undo_step() { + let mut s = session(); + let undo = steps(&s); + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 2, "size": 12, "gap": 10, "margin": 20, "text": "Hamburgefonstiv"})).unwrap(); + assert_eq!(r["count"], 3); + assert_eq!(r["skipped"], json!([])); + assert_eq!(r["artboards"], json!([]), "three entries fit on the artboard"); + assert_eq!(steps(&s), undo + 1, "one undo step"); + let g = group(&s, &r); + assert_eq!(g.name.as_deref(), Some("Font Sheet")); + assert_eq!(s.doc().unwrap().selection.objects, [g.id], "the sheet is selected"); + let e = entries(&g); + assert_eq!(e.iter().map(|(n, _)| n.as_str()).collect::>(), BUNDLED, "in the order given, each named after its font"); + for ((name, t), family) in e.iter().zip(BUNDLED) { + assert_eq!(t.plain_text(), format!("{name}\nHamburgefonstiv"), "a label line, then the sample"); + let [label, sample] = &t.runs[..] else { panic!("a label run and a sample run: {:?}", t.runs.len()) }; + assert_eq!(sample.style.font_family, family); + assert!((sample.style.size - 12.0).abs() < 1e-9 && (label.style.size - 9.0).abs() < 1e-9, "the label is set at 9 pt"); + assert_eq!(label.style.font_family, "Source Sans 3", "the label is in the normal type font"); + } + // Down the first column, 9 + 18 + 10 pt apart, inside the 20 pt margin, the first baseline one label below the top. + let board = s.doc().unwrap().doc.artboards[0].rect; + let (a, b) = (origin(&e[0].1), origin(&e[1].1)); + assert!((a.0 - board.x0 - 20.0).abs() < 1e-9 && (a.1 - board.y0 - 29.0).abs() < 1e-9, "{a:?}"); + assert!((b.0 - a.0).abs() < 1e-9 && (b.1 - a.1 - 37.0).abs() < 1e-9, "{b:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(g.id).is_none(), "undo removes the sheet"); +} + +#[test] +fn a_full_artboard_continues_on_new_artboards_to_the_right() { + let mut s = session(); + let undo = steps(&s); + // 400 pt tall less 2 × 100 pt of margin: 200 pt, room for two 72 pt entries (9 + 54 + 9). + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100})).unwrap(); + assert_eq!(r["count"], 3); + assert_eq!(r["artboards"], json!([1]), "the third entry goes on a new artboard"); + assert_eq!(steps(&s), undo + 1, "the new artboard is in the same undo step"); + let doc = &s.doc().unwrap().doc; + let (first, added) = (doc.artboards[0].rect, doc.artboards[1].rect); + assert!((added.x0 - first.x1 - 20.0).abs() < 1e-9 && (added.y0 - first.y0).abs() < 1e-9, "{added:?}"); + assert!((added.width() - first.width()).abs() < 1e-9 && (added.height() - first.height()).abs() < 1e-9, "the same size"); + let e = entries(&group(&s, &r)); + assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9, "inset by the margin on the new artboard"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "undo removes the artboard too"); + + // Without new artboards, the page after the first is laid out in the same place with none. + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100, "newArtboards": false})).unwrap(); + assert_eq!(r["artboards"], json!([])); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 1); + let e = entries(&group(&s, &r)); + assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9); +} + +#[test] +fn a_filter_picks_families_and_all_styles_lists_each_style() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"filter": " sOURCE s ", "labels": false})).unwrap(); + let e = entries(&group(&s, &r)); + let names: Vec<&str> = e.iter().map(|(n, _)| n.as_str()).collect(); + assert!(e.len() >= 2 && names.len() == e.len(), "{names:?}"); + assert!(names.contains(&"Source Sans 3") && names.contains(&"Source Serif 4"), "{names:?}"); + assert!(names.iter().all(|n| n.to_lowercase().contains("source s")), "{names:?}"); + assert!(e.iter().all(|(_, t)| t.runs.len() == 1 && t.plain_text() == DEFAULT_TEXT), "no labels: the sample alone"); + + let r = s.execute(COMMAND, &json!({"families": ["Source Sans 3"], "allStyles": true})).unwrap(); + let e = entries(&group(&s, &r)); + let styles: Vec = vectorcraft_text::FontDb::global().styles("Source Sans 3"); + assert!(styles.len() > 1, "{styles:?}"); + assert_eq!(e.len(), styles.len(), "one entry for each style"); + for ((name, t), style) in e.iter().zip(&styles) { + assert_eq!(name, &format!("Source Sans 3 {style}")); + assert_eq!(&t.runs[1].style.font_style, style); + } +} + +/// Columns sit side by side, each `gap` apart and as wide as the room inside the margin allows. +#[test] +fn columns_share_the_room_inside_the_margin() { + let mut s = session(); + // 400 pt less 2 × 50 pt of margin leaves 300 pt: eight 39 pt entries (9 + 18 + 12) fit in a column. + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12})).unwrap(); + let board = s.doc().unwrap().doc.artboards[0].rect; + let e = entries(&group(&s, &r)); + // The first column fills before the second starts, so all three share it. + let xs: Vec = e.iter().map(|(_, t)| origin(t).0).collect(); + assert!(!xs.is_empty(), "the sheet has entries"); + assert!(xs.iter().all(|x| (x - board.x0 - 50.0).abs() < 1e-9), "{xs:?}"); + // One row per column: each entry starts a column, (500 − 2 × 12) / 3 wide plus the gap apart. + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "size": 150})).unwrap(); + let e = entries(&group(&s, &r)); + let step = (500.0 - 24.0) / 3.0 + 12.0; + for (i, (_, t)) in e.iter().enumerate() { + let (x, y) = origin(t); + assert!((x - board.x0 - 50.0 - i as f64 * step).abs() < 1e-9 && (y - board.y0 - 59.0).abs() < 1e-9, "entry {i}: {x}, {y}"); + } + assert_eq!(r["artboards"], json!([])); +} + +/// The journal records the active artboard, so a replay in a new session lays the sheet out on the +/// same one; an action leaves it out, and a named artboard goes ahead of it. +#[test] +fn the_journal_records_the_artboard_the_sheet_was_laid_out_on() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap(); + let second = s.doc().unwrap().doc.artboards[1].clone(); + s.doc_mut().unwrap().active_artboard = Some(second.id); + let start = s.journal.len(); + let params = json!({"families": ["Inter"], "margin": 10}); + let r = s.execute(COMMAND, ¶ms).unwrap(); + let e = entries(&group(&s, &r)); + assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "on the active artboard"); + let (id, recorded) = s.journal.last().unwrap().clone(); + assert_eq!((id.as_str(), &recorded["activeArtboard"]), (COMMAND, &json!(1))); + assert_eq!(s.journal_for_action(start)[0].1.get("activeArtboard"), None, "an action uses the artboard active when it plays"); + + // A replay in a session whose view has no active artboard uses the recorded one. + let mut fresh = session(); + fresh.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap(); + let r = fresh.replay(COMMAND, &recorded).unwrap(); + let e = entries(&group(&fresh, &r)); + assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "the replay lays it out on the recorded artboard"); + // A named artboard goes ahead of the recorded one. + let r = fresh.execute(COMMAND, &json!({"families": ["Inter"], "margin": 10, "artboard": 0, "activeArtboard": 1})).unwrap(); + let e = entries(&group(&fresh, &r)); + let first = fresh.doc().unwrap().doc.artboards[0].rect; + assert!((origin(&e[0].1).0 - first.x0 - 10.0).abs() < 1e-9); + assert!(fresh.execute(COMMAND, &json!({"families": ["Inter"], "artboard": 5})).is_err(), "no such artboard"); +} + +/// A right-to-left sample starts at its column's left edge like any other, so it stays inside its column. +#[test] +fn a_right_to_left_sample_stays_inside_its_column() { + let mut s = session(); + let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}"; + let board = s.doc().unwrap().doc.artboards[0].rect; + // Alone, and under a left-to-right label: each line starts at the column's left edge. + for labels in [false, true] { + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "labels": labels, "text": rtl})).unwrap(); + assert_eq!(r["fallback"], json!(BUNDLED), "no bundled font has Hebrew glyphs, so each entry is named"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}"); + for (name, t) in &entries(&group(&s, &r)) { + let x = origin(t).0; + assert!((x - board.x0 - 50.0).abs() < 1e-9, "{name}: {x}"); + let layout = vectorcraft_text::layout(FontDb::global(), t); + for line in &layout.lines { + let left = x + line.x0; + assert!(left > board.x0 + 50.0 - 1e-6, "{name}, labels {labels}: a line starts at {left}, left of the column's edge"); + } + } + } +} + +#[test] +fn a_variation_selector_does_not_require_a_separate_glyph() { + let mut s = session(); + let face = FontDb::global().face("Inter", "Regular").unwrap(); + assert!(face.covers('A')); + assert!(!face.covers('\u{fe0f}')); + let text = "A\u{fe0f}"; + let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap(); + assert_eq!(r["count"], 1); + assert_eq!(r["skipped"], json!([])); + assert_eq!(r["fallback"], json!([])); + assert!(r.get("warning").is_none(), "{r}"); + let e = entries(&group(&s, &r)); + assert_eq!(e.len(), 1); + assert_eq!(e[0].1.plain_text(), text); +} + +#[test] +fn coverage_uses_the_samples_numeral_system() { + let mut s = session(); + let face = FontDb::global().face("Inter", "Regular").unwrap(); + assert!(face.covers('1')); + assert!(!face.covers('\u{661}')); + for (digits, text, missing) in [("hindi", "1", true), ("arabic", "\u{661}", false)] { + s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": digits}})) + .unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap(); + assert_eq!(r["count"], 1); + assert_eq!(r["skipped"], json!([])); + assert_eq!(r["fallback"], if missing { json!(["Inter"]) } else { json!([]) }, "{digits}: {r}"); + if missing { + assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}"); + } else { + assert!(r.get("warning").is_none(), "{r}"); + } + let e = entries(&group(&s, &r)); + assert_eq!(e.len(), 1); + assert_eq!(e[0].1.plain_text(), text); + assert_eq!(e[0].1.runs[0].style.digits.id(), digits); + } +} + +/// All Caps in the normal character style draws the sample in capitals, so a font with a lowercase +/// letter but not its capital is named in `fallback`, plain and composite fonts alike. +#[test] +fn coverage_checks_the_capitals_all_caps_draws() { + let mut s = session(); + let face = FontDb::global().face("Inter", "Regular").unwrap(); + let lower = (0x80..0x3000u32) + .filter_map(char::from_u32) + .find(|&c| { + let mut up = c.to_uppercase(); + face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u)) + }) + .unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital")); + let font = json!({"name": "CF Sheet Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let text = lower.to_string(); + let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap(); + assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}"); + s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"all_caps": true}})).unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}"); + assert_eq!(r["fallback"], json!(["Inter", "CF Sheet Caps"]), "{lower:?}: {r}"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs")), "{r}"); + let e = entries(&group(&s, &r)); + assert!(e[0].1.runs[0].style.all_caps); + assert_eq!(e[0].1.plain_text(), text, "the sample keeps its own case"); + // Layout picks the font for the character as typed, so one the font lacks still falls back + // when the font has its capitals. + let uncased = (0x80..0x3000u32) + .filter_map(char::from_u32) + .find(|&c| { + let up: String = c.to_uppercase().collect(); + !face.covers(c) && up != c.to_string() && up.chars().all(|u| face.covers(u)) + }) + .unwrap_or_else(|| panic!("Inter has every character whose capitals it has")); + let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": uncased.to_string()})).unwrap(); + assert_eq!(r["fallback"], json!(["Inter"]), "{uncased:?}: {r}"); +} + +/// Small Caps in the normal character style draws lowercase letters as capitals too, so a font with +/// a lowercase letter but not its capital is named in `fallback`, plain and composite fonts alike. +#[test] +fn coverage_checks_the_capitals_small_caps_draws() { + let mut s = session(); + let face = FontDb::global().face("Inter", "Regular").unwrap(); + let lower = (0x80..0x3000u32) + .filter_map(char::from_u32) + .find(|&c| { + let mut up = c.to_uppercase(); + c.is_lowercase() && face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u)) + }) + .unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital")); + let font = json!({"name": "CF Sheet Small Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let text = lower.to_string(); + let families = json!(["Inter", "CF Sheet Small Caps"]); + let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap(); + assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}"); + s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"small_caps": 70}})).unwrap(); + let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}"); + let e = entries(&group(&s, &r)); + assert_eq!(e.len(), 2); + assert!(e[0].1.runs[0].style.small_caps.is_some()); + assert_eq!(r["fallback"], families, "{lower:?}: {r}"); +} + +#[test] +fn bad_params_are_refused_without_a_change() { + let mut s = session(); + let before = steps(&s); + let long = "x".repeat(MAX_CHARS + 1); + for bad in [ + json!({"text": ""}), + json!({"text": " "}), + json!({"text": "two\nlines"}), + json!({"text": "two\u{2028}lines"}), + json!({"text": "two\u{2029}paragraphs"}), + json!({"text": long}), + json!({"text": 5}), + json!({"size": 0.5}), + json!({"size": "12"}), + json!({"columns": 0}), + json!({"columns": 1.5}), + json!({"gap": -1}), + json!({"margin": 2000}), + json!({"margin": 300}), + json!({"columns": 50, "gap": 1000}), + json!({"filter": "no family is called this"}), + json!({"filter": 3}), + json!({"families": []}), + json!({"families": "Inter"}), + json!({"families": ["Inter", "inter"]}), + json!({"families": ["No Such Family Anywhere"]}), + json!({"families": [""]}), + json!({"families": ["Inter"], "filter": "Inter"}), + json!({"families": ["Inter"], "filter": ""}), + json!({"families": ["Inter"], "filter": " "}), + json!({"labels": "yes"}), + json!({"allStyles": 1}), + json!({"newArtboards": "no"}), + ] { + assert!(s.execute(COMMAND, &bad).is_err(), "{bad}"); + } + assert_eq!(steps(&s), before); + let layers = &s.doc().unwrap().doc.layers; + assert!(!layers.is_empty(), "the document keeps its layers"); + assert!(layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "nothing was drawn"); +} + +/// Fonts left out are named in the warning, the first five of them, with a count of the rest. +#[test] +fn fonts_left_out_are_named_in_a_warning() { + let names = |n: usize| (1..=n).map(|i| format!("Font {i}")).collect::>(); + assert_eq!(super::skipped_warning(&[]), None); + assert_eq!(super::skipped_warning(&names(2)).as_deref(), Some("2 font(s) could not be loaded and were left out: Font 1, Font 2")); + assert_eq!( + super::skipped_warning(&names(7)).as_deref(), + Some("7 font(s) could not be loaded and were left out: Font 1, Font 2, Font 3, Font 4, Font 5 and 2 more") + ); + let mut s = session(); + let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap(); + assert!(r.get("warning").is_none(), "nothing left out: no warning"); +} + +/// A family the font menus list whose file no longer reads as a font is left out, as is a style +/// that would be drawn in another style of its family; the rest of the sheet is made. +#[test] +fn fonts_that_do_not_load_are_left_out_and_named() { + use vectorcraft_text::test_fonts::named_copy; + let dir = vectorcraft_testkit::temp_dir("font-sheet-unreadable"); + let file = |family: &str, style: &str| dir.join(format!("{}-{style}.ttf", family.replace(' ', ""))); + for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Regular"), ("Sheet Half", "Bold")] { + let postscript = format!("{}-{style}", family.replace(' ', "")); + std::fs::write(file(family, style), named_copy(false, (family, style, "Version 1.000", &postscript)).unwrap()).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir.clone()]); + // Cataloged while every file reads; then two of them stop reading as fonts. + assert_eq!(db.styles("Sheet Half").len(), 2, "{:?}", db.styles("Sheet Half")); + assert!(db.menu_family_list().iter().any(|f| f == "Sheet Gone")); + for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Bold")] { + std::fs::write(file(family, style), b"not a font").unwrap(); + } + let mut s = session(); + let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone", "Inter"]}), &db).unwrap(); + assert_eq!(r["skipped"], json!(["Sheet Gone"]), "drawn in the fallback font, it is left out: {r}"); + assert_eq!(r["count"], 1); + assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: Sheet Gone"); + assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::>(), ["Inter"]); + let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Half"], "allStyles": true}), &db).unwrap(); + assert_eq!(r["skipped"], json!(["Sheet Half Bold"]), "drawn in its Regular, the Bold is left out: {r}"); + assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::>(), ["Sheet Half Regular"]); + // Nothing that loads: an error, with nothing changed. + let before = steps(&s); + assert!(super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone"]}), &db).is_err()); + assert_eq!(steps(&s), before); +} + +/// Where the ink of `t` starts and ends down the page. +fn ink_rows(t: &TextObject) -> (f64, f64) { + let (_, y) = origin(t); + let b = vectorcraft_text::layout(FontDb::global(), t).ink_bounds().unwrap(); + (y + b.y0, y + b.y1) +} + +/// A composite font whose Roman part sets the sample at four times its size gets rows as tall as +/// its laid-out ink: the first entry stays inside the margin, the second starts below the first, +/// and each sample starts below its own label. +#[test] +fn rows_fit_the_laid_out_ink_of_a_composite_font() { + let mut s = session(); + let big = |name: &str| json!({"name": name, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter", "size": 400}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [big("CF Sheet Big A"), big("CF Sheet Big B")]})).unwrap(); + let p = json!({"families": ["CF Sheet Big A", "CF Sheet Big B"], "columns": 1, "size": 12, "gap": 10, "margin": 20, "text": "Hamburg"}); + let r = s.execute(COMMAND, &p).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}"); + let board = s.doc().unwrap().doc.artboards[0].rect; + let e = entries(&group(&s, &r)); + let ((top0, bottom0), (top1, _)) = (ink_rows(&e[0].1), ink_rows(&e[1].1)); + assert!(top0 >= board.y0 + 20.0 - 1e-6, "the first entry reaches into the margin: {top0}"); + assert!(top1 >= bottom0 - 1e-6, "the second entry overlaps the first: {top1} < {bottom0}"); + for (name, t) in &e { + let mut label = t.clone(); + label.runs.truncate(1); + let mut sample = t.clone(); + sample.runs.remove(0); + let (y0, y1) = (t.cached_baselines[0].0.y, t.cached_baselines[1].0.y); + let label_bottom = y0 + vectorcraft_text::layout(FontDb::global(), &label).ink_bounds().unwrap().y1; + let sample_top = y1 + vectorcraft_text::layout(FontDb::global(), &sample).ink_bounds().unwrap().y0; + assert!(sample_top >= label_bottom - 1e-6, "{name}: the sample reaches into its label: {sample_top} < {label_bottom}"); + } +} + +/// A composite font named in other letter case, accented letters included, is found by its own name. +#[test] +fn a_composite_font_named_in_other_case_is_set() { + let mut s = session(); + let font = json!({"name": "\u{c9}preuve Sheet", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["\u{e9}preuve sheet"], "text": "Hamburg"})).unwrap(); + assert_eq!((r["skipped"].clone(), r["count"].clone()), (json!([]), json!(1)), "{r}"); + assert_eq!(entries(&group(&s, &r))[0].0, "\u{c9}preuve Sheet"); + let twice = s.execute(COMMAND, &json!({"families": ["\u{c9}preuve Sheet", "\u{e9}PREUVE SHEET"]})).unwrap_err().to_string(); + assert!(twice.contains("twice"), "{twice}"); +} + +/// A composite font whose part setting the sample names a font that doesn't load is left out and +/// named, as a family that doesn't load is. +#[test] +fn a_composite_font_with_a_missing_part_is_left_out() { + let mut s = session(); + let font = json!({"name": "CF Sheet Gone", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "No Such Sheet Font"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Gone", "Inter"], "text": "Hamburg"})).unwrap(); + assert_eq!(r["skipped"], json!(["CF Sheet Gone"]), "{r}"); + assert_eq!(r["count"], 1); + assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::>(), ["Inter"]); +} + +#[test] +fn a_composite_font_with_an_unavailable_part_style_is_left_out() { + let mut s = session(); + let font = json!({ + "name": "CF Sheet Missing Style", + "parts": { + "kanji": {"font": "Source Sans 3"}, + "roman": {"font": "Inter", "style": "No Such Sheet Style"} + } + }); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let coverage = FontDb::global().composite_coverage("CF Sheet Missing Style", &["Hamburg"]).unwrap(); + assert_eq!(coverage.status, vectorcraft_text::FontMatch::Style); + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style", "Inter"], "text": "Hamburg"})).unwrap(); + assert_eq!(r["skipped"], json!(["CF Sheet Missing Style"])); + assert_eq!(r["count"], 1); + assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: CF Sheet Missing Style"); + assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::>(), ["Inter"]); + let before = (s.doc().unwrap().doc.clone(), steps(&s)); + assert!(s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style"], "text": "Hamburg"})).is_err()); + assert_eq!(s.doc().unwrap().doc, before.0); + assert_eq!(steps(&s), before.1); +} + +/// A composite font whose parts load but lack a glyph the sample needs stays on the sheet and is +/// named in `fallback`, as a plain font is. +#[test] +fn a_composite_font_lacking_a_sample_glyph_is_named_as_a_fallback() { + let mut s = session(); + let font = json!({"name": "CF Sheet Lacking", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}"; + let coverage = FontDb::global().composite_coverage("CF Sheet Lacking", &[rtl]).unwrap(); + assert_eq!(coverage.status, vectorcraft_text::FontMatch::Exact); + assert!(!coverage.lacking.is_empty()); + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": rtl})).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(1), &json!([])), "{r}"); + assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("CF Sheet Lacking")), "{r}"); + // A variation selector needs no glyph of its own, and digits are checked in the sample's numeral system. + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "A\u{fe0f}"})).unwrap(); + assert_eq!(r["fallback"], json!([]), "{r}"); + s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": "hindi"}})) + .unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "1"})).unwrap(); + assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}"); +} + +#[test] +fn labels_without_overlap_need_no_additional_layouts() { + use vectorcraft_text::test_fonts::{ink_work_on_this_thread, layouts_on_this_thread}; + + let mut counts = vec![]; + for labels in [false, true] { + let mut s = session(); + let before = layouts_on_this_thread(); + let ink_before = ink_work_on_this_thread(); + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "text": "Hamburg", "labels": labels})).unwrap(); + let ink_after = ink_work_on_this_thread(); + counts.push(layouts_on_this_thread() - before); + assert_eq!(r["count"], BUNDLED.len()); + let mut outlines = 0; + for (_, t) in entries(&group(&s, &r)) { + assert!(t.cached_ink.unwrap().1.is_some()); + assert_eq!(t.cached_baselines.len(), if labels { 2 } else { 1 }); + let layout = vectorcraft_text::layout(FontDb::global(), &t); + outlines += layout.glyphs.iter().chain(&layout.ruby).filter(|glyph| !glyph.outline.elements().is_empty()).count() as u64; + assert_eq!(t.cached_ink.unwrap().1, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t)); + } + assert_eq!(ink_after.0 - ink_before.0, outlines, "each glyph outline is measured once"); + assert_eq!(ink_after.1 - ink_before.1, BUNDLED.len() as u64, "decorations are measured once per entry"); + } + assert!(counts[0] > 0); + assert_eq!(counts[1], counts[0], "labels that fit must not cause separate label and sample layouts"); +} + +#[test] +fn reused_font_sheet_ink_includes_decorations_and_handles_blank_runs() { + use vectorcraft_doc::{CharStyle, TextRun}; + + for text in ["Hamburg", " "] { + for labels in [false, true] { + let style = CharStyle { font_family: "Inter".into(), size: 12.0, underline: true, strikethrough: true, ..Default::default() }; + let sample = TextRun::new(text, style.clone()); + let (first, more) = if labels { (TextRun::new("Font\n", style), Some(sample)) } else { (sample, None) }; + let t = super::laid_out(first, more, false); + let layout = vectorcraft_text::layout(FontDb::global(), &t); + let bars = vectorcraft_text::decorations(&layout, FontDb::global(), &t); + assert!(!bars.is_empty(), "the entry includes underline and strikethrough bars"); + let ink = t.cached_ink.unwrap().1; + assert_eq!(ink, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t)); + let ink = ink.unwrap(); + for (_, bar) in bars { + let bounds = vectorcraft_geom::Shape::bounding_box(&bar); + assert!(ink.x0 <= bounds.x0 && ink.y0 <= bounds.y0 && ink.x1 >= bounds.x1 && ink.y1 >= bounds.y1); + } + } + } +} + +#[test] +fn an_artboard_deletion_guard_checks_the_document_and_artboard_ids() { + let mut s = Session::new(); + s.execute("file.new", &json!({"artboards": 3})).unwrap(); + let state = s.doc().unwrap(); + let document = (state.uid, state.reverts); + let artboard = state.doc.artboards[1].id; + s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() }); + s.execute("artboard.delete", &json!({"index": 0})).unwrap(); + let before = (s.doc().unwrap().doc.clone(), steps(&s)); + for params in [json!({"index": 0}), json!({"indices": [1, 0]})] { + let error = s.execute("artboard.delete", ¶ms).unwrap_err(); + assert_eq!(error.to_string(), "The artboard is in use."); + assert_eq!(s.doc().unwrap().doc, before.0); + assert_eq!(steps(&s), before.1); + } + s.execute("file.new", &json!({"artboards": 2})).unwrap(); + s.execute("artboard.delete", &json!({"index": 1})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "another document is not protected"); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + s.doc_mut().unwrap().reverts += 1; + s.execute("artboard.delete", &json!({"index": 0})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "a reverted drawing is not protected"); +} + +/// Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards keep the guarded artboard too. +#[test] +fn an_artboard_deletion_guard_covers_every_command_that_deletes_artboards() { + let mut s = Session::new(); + s.execute("file.new", &json!({"artboards": 3})).unwrap(); + let state = s.doc().unwrap(); + let document = (state.uid, state.reverts); + let artboard = state.doc.artboards[1].id; + s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() }); + let before = (s.doc().unwrap().doc.clone(), steps(&s)); + for (command, params) in [ + ("artboard.cut", json!({"index": 1})), + ("artboard.deleteEmpty", json!({})), + ("addon.cleanup.fix", json!({"kinds": ["emptyArtboards"], "scope": "document"})), + ] { + let error = s.execute(command, ¶ms).unwrap_err(); + assert_eq!(error.to_string(), "The artboard is in use.", "{command}"); + assert_eq!(s.doc().unwrap().doc, before.0, "{command}"); + assert_eq!(steps(&s), before.1, "{command}"); + } + s.execute("artboard.cut", &json!({"index": 2})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2, "another artboard is cut"); +} + +#[test] +fn it_needs_a_document() { + let mut s = Session::new(); + assert!(s.execute(COMMAND, &json!({})).is_err()); +} + +#[test] +fn a_locked_layer_takes_no_sheet() { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); + let before = steps(&s); + assert!(s.execute(COMMAND, &json!({"families": ["Inter"]})).is_err()); + assert_eq!(steps(&s), before); +} + +#[test] +fn a_locked_current_layer_sends_the_sheet_to_the_topmost_editable_layer() { + let mut s = session(); + let editable = s.doc().unwrap().doc.layers[0].id; + let locked = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap(); + let gid = NodeId(r["id"].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + let holds = |layer: NodeId| doc.children(Some(layer)).is_some_and(|c| c.iter().any(|n| n.id == gid)); + assert!(holds(editable), "the sheet goes to the layer that is shown and unlocked"); + assert!(!holds(locked)); +} diff --git a/crates/engine/src/cmd/conceptvector.rs b/crates/engine/src/cmd/conceptvector.rs new file mode 100644 index 0000000000..469c0c1080 --- /dev/null +++ b/crates/engine/src/cmd/conceptvector.rs @@ -0,0 +1,830 @@ +//! Concept to Vector (`conceptVector.*`): vector variations of one selected image, made by a +//! provider ([`crate::concept_vector`]), compared, and inserted beside the image. +//! +//! `conceptVector.generate` asks the named provider for one variation per style and keeps them as a +//! job of this session; it changes nothing in the document. `conceptVector.insert` puts the chosen +//! variations to the right of the image as one undo step. A job is kept until it is canceled, its +//! document closes, or [`KEEP_JOBS`] newer ones replace it; it is never saved. + +use std::collections::VecDeque; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer}; +use vectorcraft_doc::{Appearance, ImageObject, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, Rect}; + +use super::buildcmds::TRACE_NAME; +use super::edit::selected_roots; +use super::pathops::shape_node; +use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_id, cmd, has_doc, text_param}; +use crate::concept_vector::{self as cv, MAX_STYLES, Output, Provider, ProviderError, Request, Variation}; + +/// The most jobs a session keeps; a new one drops the oldest. +pub const KEEP_JOBS: usize = 4; + +/// The gap, in points, between the image and the first inserted variation, and between variations. +pub const GAP: f64 = 24.0; + +/// A job's variations, or that it was canceled. +#[derive(Clone)] +enum Outcome { + Done(Arc>), + Canceled, +} + +/// What `conceptVector.generate` made, and what it was made of. +#[derive(Clone)] +pub(crate) struct Job { + id: u64, + /// The document ([`crate::DocState::uid`]) and the object (an image or an Image Trace object). + doc: u64, + source: NodeId, + image: ImageObject, + bytes: Arc>, + provider: String, + outcome: Outcome, +} + +/// The session's providers and jobs. +pub(crate) struct ConceptState { + pub(crate) registry: cv::Registry, + jobs: VecDeque, + next: u64, +} + +impl Default for ConceptState { + fn default() -> Self { + Self { registry: cv::Registry::default(), jobs: VecDeque::new(), next: 1 } + } +} + +impl Session { + /// The Concept to Vector providers this session calls by id. + pub fn concept_providers(&self) -> &cv::Registry { + &self.concept.registry + } + + /// The providers, to register another ([`cv::Registry::register`]). + pub fn concept_providers_mut(&mut self) -> &mut cv::Registry { + &mut self.concept.registry + } + + /// Job `job`'s variations and the size in pixels of the image they were made of; `None` for a + /// job this session does not keep, or one that was canceled. + pub fn concept_variations(&self, job: u64) -> Option<(&[Variation], (u32, u32))> { + let j = self.concept.jobs.iter().find(|j| j.id == job)?; + match &j.outcome { + Outcome::Done(v) => Some((v.as_slice(), (j.image.width, j.image.height))), + Outcome::Canceled => None, + } + } + + /// The document ([`crate::DocState::uid`]) job `job` was made in; `None` for a job this session + /// does not keep. + pub fn concept_job_doc(&self, job: u64) -> Option { + self.concept.jobs.iter().find(|j| j.id == job).map(|j| j.doc) + } + + /// The jobs, for a batch to put back when a step fails. Job numbers are not reused. + pub(crate) fn concept_jobs_snapshot(&self) -> VecDeque { + self.concept.jobs.clone() + } + + /// Puts back the jobs that [`Self::concept_jobs_snapshot`] took. + pub(crate) fn restore_concept_jobs(&mut self, jobs: VecDeque) { + self.concept.jobs = jobs; + } + + /// Exchanges the jobs with `jobs`: a script works on a copy of them, which becomes the + /// session's only when the script ends without an error. + pub(crate) fn swap_concept_jobs(&mut self, jobs: &mut VecDeque) { + std::mem::swap(&mut self.concept.jobs, jobs); + } + + /// The number the next job gets. + pub(crate) fn next_concept_job(&self) -> u64 { + self.concept.next + } + + /// Takes in what the app did to the jobs while a script ran, `others` being the jobs as the app + /// left them: a job canceled there is canceled here too, and the jobs numbered `from` or higher + /// that this session does not keep (those the app made) are added. Then keeps the + /// [`KEEP_JOBS`] newest of open documents. + pub(crate) fn merge_concept_jobs(&mut self, others: VecDeque, from: u64) { + for j in others { + match self.concept.jobs.iter_mut().find(|k| k.id == j.id) { + Some(k) if matches!(j.outcome, Outcome::Canceled) => k.outcome = Outcome::Canceled, + Some(_) => {} + None if j.id >= from => self.concept.jobs.push_back(j), + None => {} + } + } + self.concept.jobs.make_contiguous().sort_by_key(|j| j.id); + self.prune_concept_jobs(); + while self.concept.jobs.len() > KEEP_JOBS { + self.concept.jobs.pop_front(); + } + } + + /// Drops the jobs of document `doc` (its `uid`), when it closes. + pub(crate) fn forget_concept_jobs(&mut self, doc: u64) { + self.concept.jobs.retain(|j| j.doc != doc); + } + + /// Drops the jobs whose document is closed. + /// In a batch, nothing is dropped until the batch ends without an error. + pub(crate) fn prune_concept_jobs(&mut self) { + if self.batch_stash.is_some() { + return; + } + let open: Vec = self.documents().iter().map(|d| d.uid).collect(); + self.concept.jobs.retain(|j| open.contains(&j.doc)); + } +} + +/// The image `n` shows: its own, or the source image of an Image Trace object that wasn't expanded. +fn shown_image(n: &Node) -> Option<&ImageObject> { + match &shown_image_node(n)?.kind { + NodeKind::Image(i) => Some(i), + _ => None, + } +} + +/// The image object [`shown_image`] reads: `n` itself, or the first member of its Image Trace object. +fn shown_image_node(n: &Node) -> Option<&Node> { + match &n.kind { + NodeKind::Image(_) => Some(n), + NodeKind::Group { clip: false, .. } if n.name.as_deref() == Some(TRACE_NAME) => { + n.children()?.first().map(|i| &**i).filter(|i| matches!(i.kind, NodeKind::Image(_))) + } + _ => None, + } +} + +/// Is `n` a group whose members are made or placed from data it holds (a graph, an Objects on +/// Path, Shaper, dimension, flare or Live Paint group, a compound shape, a plug-in's generated +/// art), so that a member added to it would be placed again, replaced or combined with the others? +fn generated(n: &Node) -> bool { + let e = n.extras(); + e.generated.is_some() + || e.graph.is_some() + || e.objects_on_path.is_some() + || e.shaper.is_some() + || e.dimension.is_some() + || e.flare.is_some() + || e.compound_shape + || vectorcraft_tools::builder::is_live_paint(n) +} + +const NO_SOURCE: &str = "select one image or an unexpanded Image Trace object"; + +const LOCKED: &str = "the image is locked or hidden"; + +/// The object `id` names, else the one selected: an image or an unexpanded Image Trace object, +/// shown and unlocked with every layer and group around it, and not on a locked artboard → it, its +/// image and the image's bytes. +fn source(s: &Session, c: &str, p: &Value) -> Result<(NodeId, ImageObject, Arc>)> { + let id = match p.get("id").filter(|v| !v.is_null()) { + Some(v) => checked_id(s, v, c)?, + None => match selected_roots(s)?.as_slice() { + [one] => *one, + _ => return Err(bad(c, NO_SOURCE)), + }, + }; + let d = &s.doc()?.doc; + let n = d.node(id).ok_or(EngineError::NoNode(id))?; + let image = shown_image(n).ok_or_else(|| bad(c, NO_SOURCE))?; + if !d.is_editable(id) { + return Err(bad(c, LOCKED)); + } + let blob = d.images.get(&image.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", image.key)))?; + Ok((id, image.clone(), Arc::clone(&blob.bytes))) +} + +/// A generation prepared from the session, which runs without it ([`ConceptRun::run`]), on any +/// thread, and is kept as a job with [`ConceptRun::finish`]. +pub struct ConceptRun { + provider: Arc, + /// The provider's id, as it was registered. + provider_id: &'static str, + request: Request, + doc: u64, + source: NodeId, + image: ImageObject, +} + +impl ConceptRun { + /// What `conceptVector.generate` with params `p` makes in the active document, checked as the + /// command checks it. + pub fn prepare(s: &Session, p: &Value) -> Result { + const C: &str = "conceptVector.generate"; + let name = text_param(p, "provider", C)?.ok_or_else(|| bad(C, "missing `provider` (see conceptVector.providers)"))?; + let found = + s.concept.registry.get(name).ok_or_else(|| bad(C, format!("no Concept to Vector provider `{name}` (see conceptVector.providers)")))?; + let (caps, pid, provider) = (&found.capabilities, found.id, Arc::clone(&found.provider)); + let styles_error = || bad(C, format!("`styles` must list 1 to 8 different style ids of `{pid}` (see conceptVector.providers)")); + // The count is checked before any id is copied or scanned for repeats. + let styles: Vec = match p.get("styles") { + Some(Value::Array(a)) if (1..=MAX_STYLES).contains(&a.len()) => { + a.iter().map(|v| v.as_str().map(str::to_string)).collect::>().ok_or_else(styles_error)? + } + _ => return Err(styles_error()), + }; + let known = |id: &String| caps.styles.iter().any(|st| st.id == id); + let unique = styles.iter().enumerate().all(|(i, id)| !styles.get(..i).unwrap_or_default().contains(id)); + if !unique || !styles.iter().all(known) { + return Err(styles_error()); + } + let prompt = text_param(p, "prompt", C)?.map(str::trim).filter(|t| !t.is_empty()).map(str::to_string); + // Results are vector paths, inserted as vector art, whatever else a provider makes. + let output = match text_param(p, "output", C)? { + None | Some("vector") => Output::Vector, + Some(_) => return Err(bad(C, "`output` must be \"vector\"")), + }; + if !caps.image_input { + return Err(bad(C, format!("`{pid}` does not take an image"))); + } + if !caps.vector_output { + return Err(bad(C, format!("`{pid}` does not make vector art"))); + } + if prompt.is_some() && !caps.prompt { + return Err(bad(C, format!("`{pid}` takes no prompt"))); + } + let detail = match p.get("detail") { + None => 50, + Some(v) => v.as_u64().filter(|d| *d <= 100).ok_or_else(|| bad(C, "`detail` must be a whole number from 0 to 100"))? as u8, + }; + let (source, image, bytes) = source(s, C, p)?; + let request = Request { image: bytes, width: image.width, height: image.height, prompt, styles, detail, output }; + Ok(ConceptRun { provider, provider_id: pid, request, doc: s.doc()?.uid, source, image }) + } + + /// The document it was prepared in ([`crate::DocState::uid`]). + pub fn doc(&self) -> u64 { + self.doc + } + + /// The image or Image Trace object it makes variations of. + pub fn source(&self) -> NodeId { + self.source + } + + /// Asks the provider for the variations and checks them ([`cv::check_result`]), telling `steps` + /// how far it has got; it touches no document. A panic in the provider is an error. + pub fn run(&self, steps: cv::Steps) -> std::result::Result, ProviderError> { + let made = crate::guard::catch_panic(|| self.provider.generate(&self.request, steps)).map_err(ProviderError::Internal)??; + cv::check_result(&self.request, &made)?; + Ok(made) + } + + /// How many styles it makes. + pub fn style_count(&self) -> usize { + self.request.styles.len() + } + + /// Does the next part of the run kept in `run`, for a caller with no thread for + /// [`ConceptRun::run`] (the web build), which can run other work, or stop, between the parts + /// → whether every style is made ([`PartRun::made`]). A provider that makes parts + /// ([`cv::Provider::parts`]) does one of its own; the others make one style alone, and the + /// styles made so far are checked together ([`cv::check_result`]) after each one, so the + /// totals stop the run as soon as they are passed. A panic in the provider is an error. + pub fn run_part(&self, run: &mut PartRun, steps: cv::Steps) -> std::result::Result { + let guard = ProviderError::Internal; + if run.parts.is_none() { + run.parts = Some(crate::guard::catch_panic(|| self.provider.parts(&self.request)).map_err(guard)?); + } + if let Some(Some(parts)) = &mut run.parts { + run.done = crate::guard::catch_panic(|| parts.styles_done()).map_err(guard)?; + if !steps(run.done as u64, self.style_count() as u64) { + return Err(ProviderError::Canceled); + } + let Some(made) = crate::guard::catch_panic(|| parts.step()).map_err(guard)?? else { + run.done = crate::guard::catch_panic(|| parts.styles_done()).map_err(guard)?; + return Ok(false); + }; + cv::check_result(&self.request, &made)?; + run.made = made; + return Ok(true); + } + let Some(style) = self.request.styles.get(run.made.len()) else { return Ok(true) }; + let one = Request { styles: vec![style.clone()], ..self.request.clone() }; + let next = crate::guard::catch_panic(|| self.provider.generate(&one, steps)).map_err(guard)??; + cv::check_result(&one, &next)?; + // A style that takes the totals past their limits is dropped, so `run` keeps only the + // styles that passed. + let kept = run.made.len(); + run.made.extend(next); + let so_far = Request { styles: self.request.styles.get(..run.made.len()).unwrap_or_default().to_vec(), ..one }; + if let Err(e) = cv::check_result(&so_far, &run.made) { + run.made.truncate(kept); + return Err(e); + } + Ok(run.made.len() == self.request.styles.len()) + } + + /// Keeps `variations` as a new job of `s` → the job, as `conceptVector.results` gives it; + /// `None`, keeping nothing, when the document it was prepared in has closed. + pub fn finish(self, s: &mut Session, variations: Vec) -> Option { + s.prune_concept_jobs(); + if !s.documents().iter().any(|d| d.uid == self.doc) { + return None; + } + let id = s.concept.next; + s.concept.next += 1; + let job = Job { + id, + doc: self.doc, + source: self.source, + image: self.image, + bytes: self.request.image, + provider: self.provider_id.to_string(), + outcome: Outcome::Done(Arc::new(variations)), + }; + let out = job_json(&s.concept.registry, &job); + s.concept.jobs.push_back(job); + while s.concept.jobs.len() > KEEP_JOBS { + s.concept.jobs.pop_front(); + } + Some(out) + } +} + +/// How far a run made a part at a time ([`ConceptRun::run_part`]) has got. +#[derive(Default)] +pub struct PartRun { + /// The provider's parts, once asked for (`None` inside: it makes one style at a time). + parts: Option>>, + /// The styles the provider's parts had made when last asked, inside the panic guard. + done: usize, + made: Vec, +} + +impl PartRun { + /// The styles made so far. + pub fn styles_done(&self) -> usize { + if self.made.is_empty() { self.done } else { self.made.len() } + } + + /// The variations made: all of them once [`ConceptRun::run_part`] has said so. + pub fn made(self) -> Vec { + self.made + } +} + +/// `e` as the engine's error. +pub fn provider_error(e: ProviderError) -> EngineError { + match e { + ProviderError::Canceled => EngineError::Cancelled, + e => EngineError::Other(e.to_string()), + } +} + +/// The English name of style `style` of provider `provider`, else the id. +fn style_label(registry: &cv::Registry, provider: &str, style: &str) -> String { + let caps = registry.get(provider).map(|p| &p.capabilities); + caps.and_then(|c| c.styles.iter().find(|s| s.id == style).map(|s| s.label.to_string())).unwrap_or_else(|| style.to_string()) +} + +/// Where `style` comes in the styles `provider` lists; after them when it lists no such style. +fn style_rank(registry: &cv::Registry, provider: &str, style: &str) -> usize { + let caps = registry.get(provider).map(|p| &p.capabilities); + caps.and_then(|c| c.styles.iter().position(|s| s.id == style)).unwrap_or(usize::MAX) +} + +/// Where `image`'s pixels lie in the document. +fn image_rect(image: &ImageObject) -> Option { + let r = Rect::new(0.0, 0.0, f64::from(image.width.max(1)), f64::from(image.height.max(1))); + let pts = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| image.xf * kurbo::Point::new(x, y)); + let mut out = Rect::from_points(pts[0], pts[0]); + for q in &pts[1..] { + out = out.union_pt(*q); + } + [out.x0, out.y0, out.x1, out.y1].iter().all(|v| v.is_finite()).then_some(out) +} + +fn job_json(registry: &cv::Registry, j: &Job) -> Value { + let (state, variations) = match &j.outcome { + Outcome::Done(v) => ("done", v.as_slice()), + Outcome::Canceled => ("canceled", &[][..]), + }; + let variations: Vec = variations + .iter() + .map(|v| { + let bounds = v.paths.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)); + json!({ + "style": v.style, + "label": style_label(registry, &j.provider, &v.style), + "paths": v.paths.len(), + "anchors": v.anchors(), + "bounds": bounds.map(|b| [b.x0, b.y0, b.x1, b.y1]), + "warnings": v.warnings, + }) + }) + .collect(); + json!({ "job": j.id, "provider": j.provider, "source": j.source.0, "state": state, "variations": variations }) +} + +/// The `job` param of command `c`. +fn job_param(c: &str, p: &Value) -> Result { + p.get("job").and_then(Value::as_u64).ok_or_else(|| bad(c, "`job` must be a job number from conceptVector.generate")) +} + +/// The error of command `c` for a job the session does not keep. +fn no_job(c: &str, job: u64) -> EngineError { + bad(c, format!("no Concept to Vector job {job}: it was never made, or was dropped (see conceptVector.results)")) +} + +/// The index of job `job` among those `s` keeps. +fn job_index(s: &mut Session, c: &str, job: u64) -> Result { + s.prune_concept_jobs(); + s.concept.jobs.iter().position(|j| j.id == job).ok_or_else(|| no_job(c, job)) +} + +fn providers(s: &mut Session, _: &Value) -> Result { + let list: Vec = s + .concept + .registry + .iter() + .map(|p| { + let c = &p.capabilities; + json!({ + "id": p.id, + "name": p.name, + "available": true, + "offline": c.offline, + "imageInput": c.image_input, + "vectorOutput": c.vector_output, + "prompt": c.prompt, + "rasterOutput": c.raster_output, + "maxStyles": MAX_STYLES, + "styles": c.styles, + }) + }) + .collect(); + let selected = s.concept.registry.iter().next().map(|p| p.id); + Ok(json!({ "providers": list, "selected": selected })) +} + +fn generate(s: &mut Session, p: &Value) -> Result { + let run = ConceptRun::prepare(s, p)?; + // A script's run stops when the script is asked to stop, and keeps no job. + let stop = s.script_in_run.then(|| s.script_interrupt()); + let stopped = || stop.as_ref().is_some_and(|i| i.is_set()); + let made = run.run(&|_, _| !stopped()).map_err(provider_error)?; + if stopped() { + return Err(EngineError::Cancelled); + } + run.finish(s, made).ok_or(EngineError::NoDocument) +} + +fn results(s: &mut Session, p: &Value) -> Result { + const C: &str = "conceptVector.results"; + let job = job_param(C, p)?; + let at = job_index(s, C, job)?; + let j = s.concept.jobs.get(at).ok_or_else(|| no_job(C, job))?; + Ok(job_json(&s.concept.registry, j)) +} + +/// The error of an insert or cancel played from recorded steps: a job lives only in this session, +/// and a job number from another one may name other results. +const REPLAYED: &str = "Concept to Vector jobs are not saved, so a recorded insert or cancel does not play again: generate again"; + +fn cancel(s: &mut Session, p: &Value) -> Result { + const C: &str = "conceptVector.cancel"; + if s.replaying() { + return Err(bad(C, REPLAYED)); + } + let job = job_param(C, p)?; + let at = job_index(s, C, job)?; + if let Some(j) = s.concept.jobs.get_mut(at) { + j.outcome = Outcome::Canceled; + } + Ok(json!({ "job": job, "state": "canceled" })) +} + +/// The appearance of variation path `p`, its widths scaled by `unit` (points per pixel). +fn appearance_of(p: &cv::VectorPath, unit: f64) -> Appearance { + let solid = |c: [u8; 3]| Paint::solid(Color::rgb8(c[0], c[1], c[2])); + let mut items = vec![]; + if let Some(c) = p.fill { + items.push(AppearanceItem::Fill(FillLayer::new(solid(c)))); + } + if let Some((c, w)) = p.stroke { + let cap = if p.square_caps { LineCap::Square } else { LineCap::Round }; + items.push(AppearanceItem::Stroke(StrokeLayer { cap, join: LineJoin::Round, ..StrokeLayer::new(solid(c), w * unit) })); + } + Appearance { items, ..Default::default() } +} + +fn insert(s: &mut Session, p: &Value) -> Result { + const C: &str = "conceptVector.insert"; + if s.replaying() { + return Err(bad(C, REPLAYED)); + } + let job = job_param(C, p)?; + let at = job_index(s, C, job)?; + let list_error = || bad(C, format!("`variations` must list different style ids of job {job}")); + let listed = match p.get("variations") { + Some(Value::Array(a)) if !a.is_empty() => a, + _ => return Err(list_error()), + }; + let stale = || bad(C, format!("job {job} no longer applies: its document, image or image placement changed, so generate again")); + let (doc, source, image, bytes, picked, label_of) = { + let j = s.concept.jobs.get(at).ok_or_else(|| no_job(C, job))?; + let Outcome::Done(all) = &j.outcome else { return Err(bad(C, format!("job {job} has no results to insert: it was canceled"))) }; + // The count is checked before the ids are read or scanned for repeats. + if listed.len() > all.len() { + return Err(list_error()); + } + let chosen: Vec<&str> = listed.iter().map(Value::as_str).collect::>().ok_or_else(list_error)?; + let unique = chosen.iter().enumerate().all(|(i, id)| !chosen.get(..i).unwrap_or_default().contains(id)); + let mut picked: Vec = all.iter().filter(|v| chosen.contains(&v.style.as_str())).cloned().collect(); + if !unique || picked.len() != chosen.len() { + return Err(list_error()); + } + // In the provider's order, whatever order they were listed or generated in. + picked.sort_by_key(|v| style_rank(&s.concept.registry, &j.provider, &v.style)); + let labels: Vec = picked.iter().map(|v| style_label(&s.concept.registry, &j.provider, &v.style)).collect(); + (j.doc, j.source, j.image.clone(), Arc::clone(&j.bytes), picked, labels) + }; + // The same document, the same object showing the same pixels where they were. + let st = s.doc()?; + let now = st.doc.node(source).and_then(shown_image); + let same_pixels = || st.doc.images.get(&image.key).is_some_and(|b| Arc::ptr_eq(&b.bytes, &bytes) || *b.bytes == *bytes); + let current = st.uid == doc && now.is_some_and(|i| i.key == image.key && i.xf == image.xf && i.width == image.width && i.height == image.height); + if !current || !same_pixels() { + return Err(stale()); + } + if !st.doc.is_editable(source) { + return Err(bad(C, LOCKED)); + } + // The results go above the outermost group around the image that clips or masks it, so that + // it hides none of them, and above the outermost envelope, blend, repeat or other live object, + // the outermost group whose members it makes or places ([`generated`]), and the outermost + // group with effects or fills and strokes of its own, so that its content and the place its + // effects measure from stay as they are. A layer that clips or masks its art, or has effects, + // fills or strokes of its own, leaves them nowhere to go. An effect that moves or reshapes + // the image, its own or a group's around it, shows it away from its placement, which the + // results are placed by. + let ancestry = st.doc.ancestry(source).ok_or_else(stale)?; + let moves = |id: &NodeId| st.doc.node(*id).is_some_and(|n| !n.is_layer() && vectorcraft_render::effects::has_geometry(&n.appearance.effects)); + if ancestry.iter().any(moves) { + return Err(bad(C, "the image or a group around it has effects that move or reshape it, so the results would not go beside it")); + } + // A distorted image ([`Node::image_quad`]) is drawn at its corners, not by its transform. + if st.doc.node(source).and_then(shown_image_node).is_some_and(Node::is_distorted_image) { + return Err(bad(C, "the image is distorted, so the results would not go beside it")); + } + let mut anchor = source; + for &id in ancestry.iter().rev().skip(1) { + let n = st.doc.node(id).ok_or_else(stale)?; + let masked = n.extras().mask.as_ref().is_some_and(|m| !m.disabled); + if matches!(n.kind, NodeKind::Layer { clip: true, .. }) { + return Err(bad(C, "the image is on a layer with a clipping mask, which would hide the results")); + } + if n.is_layer() && masked { + return Err(bad(C, "the image is on a layer with an opacity mask, which would hide the results")); + } + let styled = !n.appearance.items.is_empty() || !n.appearance.effects.is_empty(); + if n.is_layer() && !n.appearance.effects.is_empty() { + return Err(bad(C, "the image is on a layer with effects of its own, which would apply to the results")); + } + // A layer's fills and strokes paint over its members, the results included. + if n.is_layer() && !n.appearance.items.is_empty() { + return Err(bad(C, "the image is on a layer with fills or strokes of its own, which would apply to the results")); + } + let live = !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || generated(n); + if !n.is_layer() && (masked || live || styled || matches!(n.kind, NodeKind::Group { clip: true, .. })) { + anchor = id; + } + } + let src = image_rect(&image).ok_or_else(stale)?; + // A variation with no paths adds nothing: it is left out, and with none left nothing changes. + let (picked, label_of): (Vec, Vec) = picked.into_iter().zip(label_of).filter(|(v, _)| !v.paths.is_empty()).unzip(); + if picked.is_empty() { + return Ok(json!({ "ids": [] })); + } + let unit = image.xf.determinant().abs().sqrt(); + // Each chosen variation's box over the image: the image's box and the variation's painted + // bounds, which may reach past it. A square cap's corner lies half the width along the path + // and half across it from the end, so up to √2 times half the width past it on an axis. + let boxes: Vec = picked + .iter() + .map(|v| { + v.paths + .iter() + .filter_map(|vp| { + let reach = if vp.square_caps { std::f64::consts::SQRT_2 } else { 1.0 }; + let half = vp.stroke.map_or(0.0, |(_, w)| w * unit / 2.0 * reach); + vp.path.transformed(image.xf).bounds().map(|b| b.inflate(half, half)) + }) + .fold(src, |a, b| a.union(b)) + }) + .collect(); + // How far each variation's box is moved past the first's: each box starts GAP to the right of + // the one before it (`width + GAP` further right for boxes the image's size). + let mut offsets = Vec::with_capacity(boxes.len()); + let mut next = 0.0; + for (k, b) in boxes.iter().enumerate() { + if let Some(prev) = k.checked_sub(1).and_then(|j| boxes.get(j)) { + next += prev.x1 - b.x0 + GAP; + } + offsets.push(next); + } + // The first box's left edge, which may lie left of the image's where its variation paints there. + let first = boxes.first().map_or(src.x0, |b| b.x0); + // The boxes with the first one's left edge moved to `x0`, the others after it. + let row = |x0: f64| -> Vec { + boxes + .iter() + .zip(&offsets) + .map(|(b, off)| { + let dx = x0 + off - first; + Rect::new(b.x0 + dx, b.y0, b.x1 + dx, b.y1) + }) + .collect() + }; + // The painted bounds of every visible object (the source's too: an Image Trace object's traced + // art and effects can reach past the image), and the image's own box. A layer or group that + // paints nothing of its own is measured by its members (an opacity mask only hides them); one + // that clips, by its members after the clipping path, cut to what it paints. + let mut obstacles: Vec = vec![src]; + // One lookup of the symbols for the whole walk, so each symbol's art is measured once. + let symbols = st.doc.symbol_boxes(); + let mut stack: Vec<(&Arc, Option)> = st.doc.layers.iter().map(|l| (l, None)).collect(); + while let Some((node, within)) = stack.pop() { + if !node.visible { + continue; + } + let cut = |b: Rect| match within { + Some(w) => Some(b.intersect(w)).filter(|i| i.width() > 0.0 && i.height() > 0.0), + None => Some(b), + }; + let painted = || vectorcraft_render::painted_bounds_with(&symbols, node).and_then(cut); + if node.id == source { + obstacles.extend(painted()); + continue; + } + let clips = matches!(node.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }); + let by_members = (node.is_layer() || matches!(node.kind, NodeKind::Group { .. })) + && node.appearance.items.is_empty() + && node.appearance.effects.is_empty(); + if by_members { + // A clipping path paints its fills and strokes when they are set (`Node::clip_paint`), + // its strokes outside the clip too, whether or not it is shown. + if clips && let Some(path) = node.children().into_iter().flatten().next() { + let paint = path.clip_paint(); + for part in [paint.fill, paint.stroke].into_iter().flatten() { + if let Some(b) = vectorcraft_render::painted_bounds_with(&symbols, &part).and_then(cut) { + obstacles.push(b); + } + } + } + let within = if clips { + // Nothing of a clipping group shows outside what it paints. + let Some(shown) = painted() else { continue }; + Some(shown) + } else { + within + }; + stack.extend(node.children().into_iter().flatten().skip(usize::from(clips)).map(|c| (c, within))); + } else if let Some(b) = painted() { + obstacles.push(b); + } + } + let placed = place_row(&row, src.x1 + GAP, &obstacles); + let room = || bad(C, "there is no room for the results to the right of the image"); + let Some(x0) = placed.filter(|x0| x0.is_finite()) else { + return Err(room()); + }; + let right = row(x0).iter().map(|r| r.x1).fold(f64::NEG_INFINITY, f64::max); + if right > crate::MAX_COORD { + return Err(room()); + } + let ids = s.edit("Concept to Vector", |d, sel| { + let mut groups = vec![]; + for ((v, label), off) in picked.into_iter().zip(label_of).zip(&offsets) { + let dx = x0 + off - first; + let xf = Affine::translate((dx, 0.0)) * image.xf; + let mut members = Vec::with_capacity(v.paths.len()); + for vp in &v.paths { + let path = vp.path.transformed(xf); + if path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().any(|c| c.abs() > crate::MAX_COORD)) { + return Err(room()); + } + let mut node = shape_node(d, path, None); + node.appearance = appearance_of(vp, unit).into(); + members.push(Arc::new(node)); + } + let mut g = Node::group(d.alloc_id(), members); + g.name = Some(label); + groups.push(g); + } + let ids: Vec = groups.iter().map(|g| g.id).collect(); + d.insert_beside(vec![(anchor, groups)], false)?; + sel.set(ids.iter().copied()); + Ok(ids) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) +} + +#[cfg(test)] +thread_local! { + /// How many times [`place_row`] has looked at an object on this thread. + pub(crate) static LOOKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Where the left edge of the row's first box goes, from `start` rightward, so that no box meets +/// one of `obstacles`: a box in the way moves GAP past the rightmost object it meets. `row(x0)` +/// gives the boxes with the first one's left edge at `x0`. `None` when the moves run out. +pub(crate) fn place_row(row: &dyn Fn(f64) -> Vec, start: f64, obstacles: &[Rect]) -> Option { + // Each box's objects: those level with it, by their left edges. The row only moves right, so + // each object joins its box's list once, when the box's right edge passes its left edge, and + // stays: of those joined, only the rightmost right edge matters, and the box meets that object + // exactly when the edge is right of the box's left edge. + let lanes: Vec> = row(start) + .iter() + .map(|b| { + let mut lane: Vec = obstacles.iter().filter(|o| o.y0 < b.y1 && b.y0 < o.y1).copied().collect(); + lane.sort_by(|a, b| a.x0.total_cmp(&b.x0)); + lane + }) + .collect(); + let mut joined = vec![0usize; lanes.len()]; + let mut reach = vec![f64::NEG_INFINITY; lanes.len()]; + let mut x0 = start; + // Each move takes a box past every object joined to it, so another move of that box needs a + // new object to join. + for _ in 0..=lanes.iter().map(Vec::len).sum::() { + let mut shift = None; + for ((r, lane), (j, far)) in row(x0).iter().zip(&lanes).zip(joined.iter_mut().zip(reach.iter_mut())) { + while let Some(o) = lane.get(*j).filter(|o| o.x0 < r.x1) { + #[cfg(test)] + LOOKS.with(|n| n.set(n.get() + 1)); + *far = far.max(o.x1); + *j += 1; + } + // The first box in the way, moved past the rightmost object it meets. + if shift.is_none() && *far > r.x0 { + shift = Some(*far + GAP - r.x0); + } + } + match shift { + None => return Some(x0), + Some(by) => x0 += by, + } + } + None +} + +pub fn specs() -> Vec { + vec![ + cmd!( + query "conceptVector.providers", + "Concept to Vector Providers", + [], + None, + "{} → {providers: [{id, name, available, offline, imageInput, vectorOutput, prompt, rasterOutput, maxStyles: 8, styles: [{id, label}]}], selected: the id the panel uses} the providers conceptVector.generate can call by id; the built-in offline.traceStyles makes its styles with Image Trace on this computer (outline, inkLines, flatColor, detailedColor, grayTones), takes no prompt and makes vector art only", + always, + providers + ), + cmd!( + query "conceptVector.generate", + "Generate Concept to Vector Styles", + [], + None, + "{id?: image or unexpanded Image Trace object (default: the one selected object), provider: id (conceptVector.providers; no other provider is used in its place), styles: [style id…] (1 to 8 different ids of that provider), detail?: 0-100 (50: how much of the image's detail each style keeps), prompt?: text (an error for a provider without prompts unless empty), output?: \"vector\" (the only output; any other value is an error)} one variation of the image for each style, kept by this session as a job and not put in the document; a provider that takes no image, makes no vector art or takes no prompt when one is given is refused with that reason; an object that is locked or hidden, itself or by a layer or group around it, or on a locked artboard, is refused → {job, provider, source: id, state: \"done\", variations: [{style, label, paths, anchors, bounds: [x0,y0,x1,y1] in the image's pixels, warnings: [text…]}]}", + has_doc, + generate + ), + cmd!( + query "conceptVector.results", + "Concept to Vector Results", + [], + None, + "{job} a job conceptVector.generate made, as it returned it, or with state \"canceled\" and no variations; the session keeps the 4 newest jobs, until their document closes → {job, provider, source, state, variations}", + has_doc, + results + ), + cmd!( + query "conceptVector.cancel", + "Cancel Concept to Vector Job", + [], + None, + "{job} drop a job's variations, so that it can't be inserted; canceling it again does the same; an error when it plays from recorded steps (an action, a replayed journal or a step of a replayed batch), since jobs are not saved → {job, state: \"canceled\"}", + has_doc, + cancel + ), + cmd!( + "conceptVector.insert", + "Insert Concept to Vector Styles", + [], + None, + "{job, variations: [style id…] (different styles of the job)} put a group of each chosen variation, named after its style and in the provider's order, in a row to the right of the job's image, each the image's size with 24 pt between them, moved further right past other visible art in their way, where a variation reaches past its box too (the next one then starts 24 pt past what it paints); the groups go above the outermost clip group or opacity-masked group around the image, and above the outermost envelope, blend, repeat or other live object, the outermost group whose members it makes or places (a graph, an Objects on Path, Shaper, dimension, flare or Live Paint group, a compound shape) and the outermost group with effects or fills and strokes of its own around it; the image and other art stay as they are; one undo step; a variation with no paths is left out, and when every chosen one has none nothing changes (no undo step, ids []); an error when the job's document is not the active one, the object, its image or its placement changed, the object is now locked or hidden, or it is on a layer with a clipping mask, an opacity mask, or effects, fills or strokes of its own, or it or a group around it has effects that move or reshape it, or its image is distorted (Perspective Distort or Free Distort), and when it plays from recorded steps (an action, a replayed journal or a step of a replayed batch), since jobs are not saved →{ids: the groups, selected}", + has_doc, + insert + ), + ] +} diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 1054ca3ddc..13291b5307 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -33,6 +33,6 @@ mod smooth; pub(super) use anchors::{following_anchors, remove_anchors_of}; pub use commands::specs; -pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt}; +pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt, with_anchor_path}; pub(super) use cut::{components, erase_outline}; pub(super) use freehand::freehand_brushed; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index 8068418edd..a1271a39a9 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -1,4 +1,4 @@ -use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, within_input_bound}; +use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, with_anchor_path, within_input_bound}; use super::{ Anchor, BTreeSet, Beside, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Point, Result, Selection, Session, Value, Vec2, add_look, bad, check_numbers, f64_or, json, number_or, object_param, ok, po, str_param, switch_or, @@ -111,6 +111,24 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result { let ai = usize_req(p, "anchor", C)?; let curvature = switch_or(p, "curvature", false, C)?; let removed = s.edit("Delete Anchor Point", |d, sel| { + if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) { + // Type on a path keeps its path: the anchor goes only while two or more stay. + with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + if ai >= sp.anchors.len() { + return Err(EngineError::Other("no such anchor".into())); + } + if curvature { + vectorcraft_tools::draw2::curvature_remove(sp, ai); + } else { + po::remove_anchors(sp, &[ai]); + } + Ok(()) + })?; + sel.anchors.remove(&id); + sel.segments.remove(&id); + return Ok(false); + } let sp = path_mut(d, id)?.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; if ai >= sp.anchors.len() { return Err(EngineError::Other("no such anchor".into())); @@ -254,23 +272,24 @@ pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "x and y must be finite")); } s.edit("Convert Anchor Point", |d, _| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - if smooth && target.is_none() { - if ai >= sp.anchors.len() { - return Err(EngineError::Other("no such anchor".into())); + with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + if smooth && target.is_none() { + if ai >= sp.anchors.len() { + return Err(EngineError::Other("no such anchor".into())); + } + // Without a handle position the anchor curves as the Curvature tool curves a point; one + // with no direction to take stays as it is. + vectorcraft_tools::draw2::curvature_smooth(sp, ai); + return Ok(()); } - // Without a handle position the anchor curves as the Curvature tool curves a point; one - // with no direction to take stays as it is. - vectorcraft_tools::draw2::curvature_smooth(sp, ai); - return Ok(()); - } - let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - match target { - Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t), - _ => a.retract(), - } - Ok(()) + let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + match target { + Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t), + _ => a.retract(), + } + Ok(()) + }) })?; ok() } @@ -287,13 +306,14 @@ pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result { } let perpendicular = switch_or(p, "perpendicular", false, C)?; s.edit("Reshape", |d, _| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) }; - if !bent { - return Err(EngineError::Other("no such segment".into())); - } - Ok(()) + with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) }; + if !bent { + return Err(EngineError::Other("no such segment".into())); + } + Ok(()) + }) })?; ok() } diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 08404a3092..eda5d19d23 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Delete Anchor Point", [], None, - "{id, subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points)", + "{id (a path, or type on a path), subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points); type on a path keeps two anchors on its path at least", has_doc, remove_anchor ), @@ -75,7 +75,7 @@ pub fn specs() -> Vec { "Convert Anchor Point", [], None, - "{id, subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)", + "{id (a path, or type on a path), subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)", has_doc, convert_anchor ), @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Reshape Segment", [], None, - "{id, subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does", + "{id (a path, or type on a path), subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does", has_doc, reshape_segment ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index f69ac40822..999953eb52 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -308,6 +308,29 @@ pub(super) fn path_mut(d: &mut Document, id: NodeId) -> Result<&mut PathData> { } } +/// Run `f` on the anchors the anchor tools edit on `id` ([`Node::anchor_path`]): a path's, as +/// [`path_mut`] gives them, or type on a path's path in document space. The type keeps the edited +/// path and lays out again; an edit that leaves a subpath with fewer than two anchors, or a path +/// that is not finite or reaches past the canvas, is an error and changes nothing. +pub(in super::super) fn with_anchor_path(d: &mut Document, id: NodeId, f: impl FnOnce(&mut PathData) -> Result) -> Result { + if !matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) { + return f(path_mut(d, id)?); + } + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + let mut path = n.anchor_path().map(std::borrow::Cow::into_owned).ok_or_else(|| EngineError::Other(format!("object {id} is not a path")))?; + let r = f(&mut path)?; + let within = path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD)); + if path.subpaths.is_empty() || path.subpaths.iter().any(|sp| sp.anchors.len() < 2) || !within { + return Err(EngineError::Other(format!("type on a path keeps at least two anchors on its path, within the canvas (object {id})"))); + } + let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::NoNode(id)) }; + if !t.set_type_path(&path) { + return Err(EngineError::Other(format!("the path of object {id} would not be finite"))); + } + crate::cmd::typecmd::refresh_bounds(t); + Ok(r) +} + pub(super) fn path_of(d: &Document, id: NodeId) -> Result<(PathData, FillRule)> { match d.node(id).map(|n| &n.kind) { Some(NodeKind::Path { path, rule, .. }) => Ok((path.clone(), *rule)), diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 9e67ab1916..81c23e9684 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -178,14 +178,14 @@ pub(crate) use export_names::{ artboard_file_names_keeping_dots, default_name, merge, unique_file_names_keeping_dots, with_black_output, write_or_return, }; use export_names::{distinct_names_by, write_encoded}; -pub(crate) use formats::is_own_title; use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable}; pub use formats::{ DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters, export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions, - open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_filters, places_with_importer, plugin_formats, read_extensions, - readable_format, readable_format_for_name, reads_as_dwg, titled_for_export, writable_format, + open_exts, open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_exts, place_filters, places_with_importer, + plugin_formats, read_extensions, readable_format, readable_format_for_name, reads_as_dwg, titled_for_export, writable_format, }; +pub(crate) use formats::{is_own_title, reads}; #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 9beed7e8a2..276886d534 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -785,7 +785,7 @@ fn is_openable(path: &str) -> bool { if ext.is_empty() { return false; } - open_extensions().iter().any(|e| *e == ext) || FORMATS.iter().any(|f| f.read && f.extensions.iter().any(|e| *e == ext)) + open_extensions().iter().any(|e| *e == ext) || FORMATS.iter().any(|f| super::formats::reads(f) && f.extensions.iter().any(|e| *e == ext)) } #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 821c74acb0..a7e19bc0cb 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -14,7 +14,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // The active artboard the app passes, for the steps that act on it. 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). + // (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group, the + // Concept to Vector jobs). // 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() && !s.previewing { @@ -24,6 +25,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { } 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()); let (clipboard_copied, copies) = (s.clipboard_copied, s.copies); + let concept_jobs = s.concept_jobs_snapshot(); // 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(); @@ -42,6 +44,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { Ok(results) => { s.notify_text_tool("batch.end"); s.batch_steps = Some(grouped); + s.prune_concept_jobs(); results } Err(e) => { @@ -59,6 +62,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { (s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved; (s.clipboard_copied, s.copies) = (clipboard_copied, copies); s.pending_paint = None; + s.restore_concept_jobs(concept_jobs); return Err(e); } }; diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 8940407aff..fd46b7b4ca 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -389,7 +389,10 @@ impl RasterOptions { top_down: self.flip_rows.unwrap_or(false), gray: color_model == jpeg::ColorModel::Gray, }, - tga: tga::TgaOptions { depth: self.depth.unwrap_or(24) }, + tga: { + let gray = color_model == jpeg::ColorModel::Gray; + tga::TgaOptions { depth: self.depth.unwrap_or_else(|| tga::TgaOptions::default_depth(gray)), gray } + }, psd: psd::PsdOptions { color_model, layers: self.layers.unwrap_or(true), @@ -413,12 +416,12 @@ fn bmp_layout(s: &str) -> Option { } /// Refuse options `format` can't write together: BMP and Targa depths and layouts, and colour -/// models (BMP is RGB or grey, Targa RGB). +/// models (BMP and Targa are RGB or grey). fn check_options(format: RasterFormat, o: &RasterExportOptions) -> Result<()> { let model = o.jpeg.color_model; let r = match format { RasterFormat::Bmp if model == jpeg::ColorModel::Cmyk => Err("BMP files are RGB or grayscale: colorModel rgb or gray".to_string()), - RasterFormat::Tga if model != jpeg::ColorModel::Rgb => Err("Targa files are RGB: colorModel rgb".to_string()), + RasterFormat::Tga if model == jpeg::ColorModel::Cmyk => Err("Targa files are RGB or grayscale: colorModel rgb or gray".to_string()), RasterFormat::Psd if o.psd.preserve_text && !o.psd.layers => Err("preserveText writes type layers: it needs layers: true".to_string()), RasterFormat::Bmp => o.bmp.check(), RasterFormat::Tga => o.tga.check(), diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 87ae541bf3..ff20e5046a 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -315,14 +315,18 @@ const BMP_OPTIONS: &[FormatOption] = &[ DITHER_AMOUNT, ]; +const TGA_COLOR_MODEL: FormatOption = + FormatOption { name: "colorModel", ty: "string", default: "\"rgb\"", description: "rgb (true color) or gray (grayscale)" }; + const TGA_DEPTH: FormatOption = FormatOption { name: "depth", ty: "integer", default: "24", - description: "bits per pixel: 16 (one-bit alpha), 24 (flattened on white) or 32 (keeps transparency)", + description: "bits per pixel: with rgb 16 (one-bit alpha), 24 (flattened on white) or 32 (keeps transparency); with gray 8 (the default, flattened on white) or 16 (keeps transparency)", }; -const TGA_OPTIONS: &[FormatOption] = &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, TGA_DEPTH]; +const TGA_OPTIONS: &[FormatOption] = + &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, TGA_COLOR_MODEL, TGA_DEPTH]; const PSD_LAYERS: FormatOption = FormatOption { name: "layers", @@ -603,6 +607,7 @@ pub const OPEN_EXTS: &[&str] = &[ "pns", "jpg", "jpeg", + "jpe", "gif", "webp", "tif", @@ -656,14 +661,15 @@ pub const OPEN_EXTS: &[&str] = &[ /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to /// raster editors, so Finder and file managers don't offer a vector app for them, and there is no -/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of -/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS -/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. +/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib`, `.rle` and `.jpe` +/// names of PNG, BMP and JPEG files (File › Open and Place still read them all). On Linux the desktop +/// entry's EPS and JPEG types (shared-mime-info's) also cover `.epsf` and `.jpe`, so file managers +/// offer VectorCraft for them. /// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft` /// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either. pub const UNASSOCIATED_EXTS: &[&str] = &[ - "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt", + "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "jpe", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", + "jpc", "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -708,6 +714,7 @@ pub const PLACE_EXTS: &[&str] = &[ "pns", "jpg", "jpeg", + "jpe", "gif", "webp", "tif", @@ -763,13 +770,14 @@ pub const PLACE_EXTS: &[&str] = &[ "doc", ]; -/// The extensions File › Open and Place read PNG, BMP and Photoshop files by: the format's own, -/// then the other names its files have (`.pns`, `.dib` and `.rle`, `.pdd`). Exports write only -/// the format's own extension. -const READ_ALIASES: &[(&str, &[&str])] = &[("png", &["png", "pns"]), ("bmp", &["bmp", "dib", "rle"]), ("psd", &["psd", "pdd"])]; +/// The extensions File › Open and Place read PNG, JPEG, BMP and Photoshop files by: the format's +/// own, then the other names its files have (`.pns`, `.jpe`, `.dib` and `.rle`, `.pdd`). Exports +/// write only the format's own extensions. +const READ_ALIASES: &[(&str, &[&str])] = + &[("png", &["png", "pns"]), ("jpg", &["jpg", "jpeg", "jpe"]), ("bmp", &["bmp", "dib", "rle"]), ("psd", &["psd", "pdd"])]; -/// The extensions File › Open and Place read format `f` by: its own, and for PNG, BMP and PSD -/// those of [`READ_ALIASES`]. +/// The extensions File › Open and Place read format `f` by: its own, and for PNG, JPEG, BMP and +/// PSD those of [`READ_ALIASES`]. pub fn read_extensions(f: &Format) -> &'static [&'static str] { READ_ALIASES.iter().find(|(id, _)| *id == f.id).map_or(f.extensions, |(_, exts)| *exts) } @@ -777,9 +785,52 @@ pub fn read_extensions(f: &Format) -> &'static [&'static str] { /// The built-in readable format of extension `ext` (any case, leading dot allowed): [`format`]'s /// when it reads, else the one [`READ_ALIASES`] gives it (`.dib` is BMP). Importer plug-ins are /// not looked at ([`importer_formats`]). +/// DWG drawings are readable only in a build with a DWG decoder ([`vectorcraft_cad::dwg::DECODES`]). pub fn readable_format(ext: &str) -> Option<&'static Format> { + readable_format_in(ext, vectorcraft_cad::dwg::DECODES) +} + +/// The built-in format a file of extension `ext` is taken for ([`super::load::detect`]): [`readable_format`]'s, +/// with DWG also in a build without a DWG decoder. +pub(crate) fn recognized_format(ext: &str) -> Option<&'static Format> { + readable_format_in(ext, true) +} + +/// [`readable_format`] in a build that decodes DWG drawings when `dwg`. +fn readable_format_in(ext: &str, dwg: bool) -> Option<&'static Format> { let k = ext.trim_start_matches('.').to_ascii_lowercase(); - builtin(&k).filter(|f| f.read).or_else(|| READ_ALIASES.iter().find(|(_, exts)| exts.contains(&k.as_str())).and_then(|(id, _)| builtin(id))) + builtin(&k) + .filter(|f| reads_in(f, dwg)) + .or_else(|| READ_ALIASES.iter().find(|(_, exts)| exts.contains(&k.as_str())).and_then(|(id, _)| builtin(id))) +} + +/// Whether format `f` reads in this build: DWG drawings only where a DWG decoder is built in. +pub(crate) fn reads(f: &Format) -> bool { + reads_in(f, vectorcraft_cad::dwg::DECODES) +} + +/// Whether format `f` reads in a build that decodes DWG drawings when `dwg`. +fn reads_in(f: &Format, dwg: bool) -> bool { + f.read && (dwg || !reads_as_dwg(f.id)) +} + +/// `exts` less `.dwg`, `.dws` and `.dwt` in a build without a DWG decoder (`dwg` false). +fn listed_in(exts: &[&'static str], dwg: bool) -> Vec<&'static str> { + exts.iter().copied().filter(|e| dwg || !matches!(*e, "dwg" | "dws" | "dwt")).collect() +} + +/// The extensions File › Open reads as a document in this build: [`OPEN_EXTS`], less `.dwg`, `.dws` and `.dwt` where +/// no DWG decoder is built in ([`vectorcraft_cad::dwg::DECODES`]). +pub fn open_exts() -> &'static [&'static str] { + static EXTS: std::sync::LazyLock> = std::sync::LazyLock::new(|| listed_in(OPEN_EXTS, vectorcraft_cad::dwg::DECODES)); + &EXTS +} + +/// The extensions File › Place reads in this build: [`PLACE_EXTS`], less `.dwg` where no DWG +/// decoder is built in ([`vectorcraft_cad::dwg::DECODES`]). +pub fn place_exts() -> &'static [&'static str] { + static EXTS: std::sync::LazyLock> = std::sync::LazyLock::new(|| listed_in(PLACE_EXTS, vectorcraft_cad::dwg::DECODES)); + &EXTS } /// The readable format a file name's extension names ([`readable_format`]). @@ -789,7 +840,12 @@ pub fn readable_format_for_name(name: &str) -> Option<&'static Format> { /// One dialog filter per readable format. fn format_filters() -> impl Iterator { - FORMATS.iter().filter(|f| f.read).map(|f| (f.label, read_extensions(f))) + format_filters_in(vectorcraft_cad::dwg::DECODES) +} + +/// [`format_filters`] in a build that decodes DWG drawings when `dwg`. +fn format_filters_in(dwg: bool) -> impl Iterator { + FORMATS.iter().filter(move |f| reads_in(f, dwg)).map(|f| (f.label, read_extensions(f))) } /// Whether a file named `name` can only be opened, by an importer plug-in: an installed importer lists @@ -798,7 +854,7 @@ fn format_filters() -> impl Iterator bool { let ext = extension(name); !ext.is_empty() - && !PLACE_EXTS.contains(&ext.as_str()) + && !place_exts().contains(&ext.as_str()) && !vectorcraft_plugins::import::for_extension(&ext).is_empty() && !places_with_importer(name) } @@ -810,7 +866,7 @@ pub fn places_with_importer(name: &str) -> bool { let ext = extension(name); !ext.is_empty() && readable_format(&ext).is_none() - && !PLACE_EXTS.contains(&ext.as_str()) + && !place_exts().contains(&ext.as_str()) && !vectorcraft_plugins::import::placing(&ext).is_empty() } @@ -856,7 +912,7 @@ fn importer_open_part() -> ImporterPart { { return part.clone(); } - let mut exts: Vec<&'static str> = OPEN_EXTS.to_vec(); + let mut exts: Vec<&'static str> = open_exts().to_vec(); let mut filters = Vec::new(); for f in importer_formats() { let own: Vec<&'static str> = f.extensions.iter().copied().filter(|e| readable_format(e).is_none() && !opens_as_other(e)).collect(); @@ -871,7 +927,7 @@ fn importer_open_part() -> ImporterPart { let own: &'static [&'static str] = if own.len() == f.extensions.len() { f.extensions } else { Box::leak(own.into_boxed_slice()) }; filters.push((f.label, own)); } - let exts: &'static [&'static str] = if exts.len() == OPEN_EXTS.len() { OPEN_EXTS } else { Box::leak(exts.into_boxed_slice()) }; + let exts: &'static [&'static str] = if exts.len() == open_exts().len() { open_exts() } else { Box::leak(exts.into_boxed_slice()) }; let part = (exts, filters); *made = Some((revision, part.clone())); part @@ -898,7 +954,7 @@ pub fn open_filters() -> impl Iterator impl Iterator { - std::iter::once(("All readable files", OPEN_EXTS)).chain(format_filters()).chain(other_open_filters()) + std::iter::once(("All readable files", open_exts())).chain(format_filters()).chain(other_open_filters()) } /// The open-dialog filters after the document formats: swatch and graphic style libraries, @@ -934,7 +990,7 @@ pub fn library_open_filters( /// File → Place dialog filters: "All placeable files", then one per placeable format, then text, /// RTF and Word (`.docx` and `.doc`). pub fn place_filters() -> impl Iterator { - std::iter::once(("All placeable files", PLACE_EXTS)) + std::iter::once(("All placeable files", place_exts())) .chain(format_filters().filter(|(_, exts)| exts.iter().all(|ext| PLACE_EXTS.contains(ext)))) .chain(std::iter::once(("Text", TEXT_EXTS))) .chain(std::iter::once(("RTF", RTF_EXTS))) @@ -956,12 +1012,16 @@ fn importer_place_part() -> ImporterPart { { return part.clone(); } - let mut exts: Vec<&'static str> = PLACE_EXTS.to_vec(); + let mut exts: Vec<&'static str> = place_exts().to_vec(); let mut filters = Vec::new(); for p in import::installed().into_iter().filter(|p| p.manifest().place) { let m = p.manifest(); - let own: Vec<&'static str> = - m.extensions.iter().filter(|e| readable_format(e).is_none() && !PLACE_EXTS.contains(&e.as_str())).map(|e| registry::intern(e)).collect(); + let own: Vec<&'static str> = m + .extensions + .iter() + .filter(|e| readable_format(e).is_none() && !place_exts().contains(&e.as_str())) + .map(|e| registry::intern(e)) + .collect(); if own.is_empty() { continue; } @@ -973,7 +1033,7 @@ fn importer_place_part() -> ImporterPart { let own: &'static [&'static str] = Box::leak(own.into_boxed_slice()); filters.push((registry::intern(&m.name), own)); } - let exts: &'static [&'static str] = if exts.len() == PLACE_EXTS.len() { PLACE_EXTS } else { Box::leak(exts.into_boxed_slice()) }; + let exts: &'static [&'static str] = if exts.len() == place_exts().len() { place_exts() } else { Box::leak(exts.into_boxed_slice()) }; let part = (exts, filters); *made = Some((revision, part.clone())); part @@ -1138,6 +1198,9 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result { let ids = |pick: fn(&Format) -> bool| all().filter(|f| pick(f)).map(|f| f.id).collect::>(); let listed = |f: &Format| { let mut v = f.to_json(); + if f.read && !reads(f) { + v["read"] = json!(false); + } if let Some(id) = vectorcraft_plugins::export::plugin_id(f.id) { v["plugin"] = json!(id); if vectorcraft_plugins::import::by_format(f.id).is_some_and(|p| p.manifest().place) { @@ -1148,9 +1211,37 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result { }; Ok(json!({ "formats": all().map(listed).collect::>(), - "readable": ids(|f| f.read), + "readable": ids(reads), "writable": ids(|f| f.write), "openExtensions": open_extensions(), "unsupported": UNSUPPORTED.iter().map(Unsupported::to_json).collect::>(), })) } + +#[cfg(test)] +mod dwg_listing_tests { + use super::*; + + #[test] + fn dwg_is_listed_only_in_a_build_that_decodes_it() { + assert_eq!(readable_format_in("dwg", true).map(|f| f.id), Some("dwg")); + assert_eq!(listed_in(OPEN_EXTS, true), OPEN_EXTS); + assert_eq!(listed_in(PLACE_EXTS, true), PLACE_EXTS); + assert!(format_filters_in(true).any(|(_, exts)| exts.contains(&"dwg"))); + // Without a decoder, nothing offers DWG drawings, standards files or templates. + for e in ["dwg", "dws", "dwt"] { + assert!(readable_format_in(e, false).is_none(), ".{e} is not readable"); + assert!(!listed_in(OPEN_EXTS, false).contains(&e), "File › Open does not list .{e}"); + assert!(!listed_in(PLACE_EXTS, false).contains(&e), "File › Place does not list .{e}"); + assert!(format_filters_in(false).all(|(_, exts)| !exts.contains(&e)), "no filter lists .{e}"); + } + assert!(readable_format_in("dxf", false).is_some(), "DXF still is"); + let drawing_exts = OPEN_EXTS.iter().filter(|e| matches!(**e, "dwg" | "dws" | "dwt")).count(); + assert_eq!(listed_in(OPEN_EXTS, false).len(), OPEN_EXTS.len() - drawing_exts, "every other extension stays"); + // This build lists DWG exactly when it decodes it. + let dwg = vectorcraft_cad::dwg::DECODES; + assert_eq!(open_exts().contains(&"dwg"), dwg); + assert_eq!(place_exts().contains(&"dwg"), dwg); + assert_eq!(readable_format("dwg").is_some(), dwg); + } +} diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index c578dece5d..2320bd9650 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -17,6 +17,7 @@ //! layers and artboards (its manifest's `outputKinds`): the artboards it returns replace the one //! around the art of a new document, and File › Place leaves them out. +use std::borrow::Cow; use std::sync::Arc; use serde_json::Value; @@ -61,7 +62,7 @@ pub(super) fn pick(name: &str, bytes: &[u8], p: &Value) -> Result bool { super::readable_format(ext).is_none() && match mode { Mode::Import => !import::for_extension(ext).is_empty(), - Mode::Place => !super::PLACE_EXTS.contains(&ext) && !import::placing(ext).is_empty(), + Mode::Place => !super::place_exts().contains(&ext) && !import::placing(ext).is_empty(), } } @@ -140,7 +141,7 @@ fn check_data_for(p: &Value, mode: Mode, cmd: &str) -> Result<()> { if !explicit { let start: Vec = b64.bytes().filter(|b| !b.is_ascii_whitespace()).take(SNIFF_BYTES / 3 * 4).collect(); let head = std::str::from_utf8(&start).ok().and_then(vectorcraft_format::base64_decode); - if head.is_some_and(|head| detect(name, &head).is_some()) { + if head.is_some_and(|head| detect(name, &head).is_some_and(super::formats::reads)) { return Ok(()); } } @@ -171,7 +172,7 @@ fn read_path_for(path: &str, p: &Value, mode: Mode, cmd: &str) -> Result if head.len() < SNIFF_BYTES { return Ok(head); } - if detect(path, &head).is_some() { + if detect(path, &head).is_some_and(super::formats::reads) { return super::read_file(path); } read_for_importer(path, mode) @@ -202,17 +203,43 @@ fn read_path_for(path: &str, _: &Value, _: Mode, _: &str) -> Result> { /// The file `file.place`'s params `p` name, as [`super::source`] reads it for command `cmd`, except /// that a file an importer would place (one `importer` names, or an extension no built-in format /// reads that an importer which places its files lists) is read, or decoded, only when it is at -/// most [`import::MAX_INPUT_BYTES`] long. -pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result> { +/// most [`import::MAX_INPUT_BYTES`] long. `given`: the bytes of the file `path` names, read already, +/// which are borrowed instead of reading the path again (by the same size rule). +pub(crate) fn place_source<'a, 'b>(p: &'a Value, cmd: &str, given: Option<&'b [u8]>) -> Result> { match str_param(p, "path") { - Some(path) => Ok(Source { name: path, bytes: read_path_for(path, p, Mode::Place, cmd)?, path: Some(path) }), + Some(path) => { + let bytes: Cow<'b, [u8]> = match given { + Some(bytes) => { + // The roots in force now still apply to the path, though it is not read again. + #[cfg(not(target_arch = "wasm32"))] + super::may_read(path)?; + let explicit = named(p, cmd)?.is_some(); + let importer = explicit || importer_reads(&extension(path), Mode::Place); + let built_in = !explicit && detect(path, bytes.get(..SNIFF_BYTES).unwrap_or(bytes)).is_some(); + if importer && !built_in && bytes.len() > import::MAX_INPUT_BYTES { + return Err(too_large(path, Mode::Place)); + } + Cow::Borrowed(bytes) + } + None => Cow::Owned(read_path_for(path, p, Mode::Place, cmd)?), + }; + Ok(PlaceSource { name: path, bytes, path: Some(path) }) + } None => { check_data_for(p, Mode::Place, cmd)?; - super::source(p, cmd) + let Source { name, bytes, path } = super::source(p, cmd)?; + Ok(PlaceSource { name, bytes: Cow::Owned(bytes), path }) } } } +/// The file [`place_source`] gives: as [`Source`], its bytes borrowed when they were given. +pub(crate) struct PlaceSource<'a, 'b> { + pub name: &'a str, + pub bytes: Cow<'b, [u8]>, + pub path: Option<&'a str>, +} + /// What [`read`] gives: the importer's format, the new document, its objects' ids, the artboards /// the importer returned and its warnings. type Read = (&'static Format, Document, Vec, Vec, Vec); diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 38e8b38c8b..d434dcf6ec 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -8,7 +8,7 @@ use vectorcraft_render::effects::pixel::LoadedTexture; use super::super::fileinfo::imported_title; use super::super::{Result, Session, bad, bool_or, clipboard, parse_range, str_param}; use super::pdfimport::LoadOptions; -use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, jxlread, psdread, read_file, readable_format_for_name}; +use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, jxlread, psdread, read_file}; use crate::cmd::links::Resolved; use crate::{EngineError, Prefs}; @@ -93,7 +93,7 @@ pub fn file_name(name: &str) -> String { /// The readable format of a file: from its content (magic bytes) when that tells, else from the /// extension of `name`. pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { - let by_name = readable_format_for_name(name); + let by_name = super::formats::recognized_format(&super::extension(name)); if vectorcraft_affinity::is_affinity(bytes) { return format("affinity"); } @@ -308,10 +308,12 @@ fn reads_editing_copy(opts: &LoadOptions) -> bool { /// 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? +/// trim boxes by default, 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 + reads_editing_copy(opts) + && !opts.explicit_crop_box + && opts.crop == vectorcraft_pdf::CropTo::Crop + && opts.text_as != vectorcraft_pdf::TextAs::Outlines } /// The editor's own copy of its art that `opened` carries, decoded ([`decoded_copy`]), when `opts` @@ -475,8 +477,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result // The file is read and checked once, for the document it carries, its pages, the // editor's copy and its File Info. let opened = vectorcraft_pdf::open_pdf(bytes, opts.password.as_deref()); - // Saved with Preserve Editing: the document it carries, unless some pages are picked. - let editing = (opts.pages.is_none() && opts.native) + // Restore the preserved document when opening all pages at their original size. + let editing = (opts.pages.is_none() && opts.native && !opts.explicit_crop_box) .then(|| opened.as_ref().ok().and_then(|o| o.editing())) .flatten() .map(|e| (e.intact, move || Some(e.data))); @@ -524,7 +526,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result } None => None, }; - let alone = (r.only_text || empty) + let alone = (!opts.explicit_crop_box && (r.only_text || empty)) .then(copy_alone) .flatten() .and_then(|read| read.ok()) diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 005cc4a557..2dd408acdc 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -173,7 +173,13 @@ impl LoadOptions { /// box, a password, without its hidden layers, without the VectorCraft document it carries, its /// pages linked)? Writing it back would lose the rest, so Save doesn't (it asks for a name). pub fn is_partial(&self) -> bool { - self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages + self.pages.is_some() + || self.crop != CropTo::default() + || self.explicit_crop_box + || self.password.is_some() + || !self.layers + || !self.native + || self.link_pages } /// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index ed0034b99e..9c86777182 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -453,14 +453,14 @@ fn open_exts_cover_every_readable_format() { assert!(OPEN_EXTS.contains(e), "OPEN_EXTS lacks .{e} ({})", f.label); } } - for e in OPEN_EXTS { - assert!(readable_format(e).is_some(), ".{e} in OPEN_EXTS is no readable format"); + for e in open_exts() { + assert!(readable_format(e).is_some(), ".{e} in open_exts() is no readable format"); } let filters: Vec<_> = open_filters().collect(); - assert_eq!(filters[0], ("All readable files", OPEN_EXTS)); + assert_eq!(filters[0], ("All readable files", open_exts())); assert_eq!( filters.len(), - 13 + FORMATS.iter().filter(|f| f.read).count(), + 13 + FORMATS.iter().filter(|f| formats::reads(f)).count(), "and swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export presets, composite \ fonts, shortcut sets, scripts, plug-ins" ); @@ -484,7 +484,7 @@ fn library_open_filters_list_library_formats_first() { let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS).collect(); assert_eq!(filters[0], ("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS)); assert!(filters[0].1.contains(&"ase")); - assert_eq!(filters[1], ("All readable files", OPEN_EXTS)); + assert_eq!(filters[1], ("All readable files", open_exts())); let styles: &'static [&'static str] = std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT); for (label, exts) in [("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS), ("Graphic Style Libraries", styles)] { let filters: Vec<_> = library_open_filters(label, exts).collect(); @@ -576,7 +576,7 @@ fn formats_query_lists_readers_writers_and_options() { assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string())); let png = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "png").unwrap(); assert_eq!(png["options"]["scale"]["default"], Value::Null); - assert_eq!(r["openExtensions"].as_array().unwrap().len(), OPEN_EXTS.len()); + assert_eq!(r["openExtensions"].as_array().unwrap().len(), open_exts().len()); } /// The format ids `command`'s params text lists for `format` (`a|b (default)|c (…)`, up to the diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 6e63170f88..3c6343ebea 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -1395,8 +1395,7 @@ fn link_pages_refuses_an_ai_file_saved_without_its_pdf_part() { let _ = std::fs::remove_dir_all(&d); } -/// `document.open` with `linkPages` opens a PDF-compatible `.ai` asked for its crop box on its trim -/// box, as it opens as art, showing its bleed box round the artboard, which is the document's bleed. +/// Linked pages default to the trim box with the bleed and honor an explicit Crop Box. #[test] fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() { let d = std::env::temp_dir().join(format!("vc-ailinkpagestrim-{}", std::process::id())); @@ -1416,6 +1415,13 @@ fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() { let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) }; assert_eq!((p.width, p.height, p.page_box), (192.0, 96.0, vectorcraft_doc::PageBox::Bleed)); assert_eq!(p.xf.translation(), vectorcraft_geom::Vec2::new(-6.0, -8.0), "the trim box on the artboard"); + + s.execute("document.open", &json!({"path": path, "linkPages": true, "cropTo": "crop"})).unwrap(); + let cropped = &s.doc().unwrap().doc; + assert!(cropped.artboards[0].rect.width() > board.width()); + let placed = &cropped.layers[0].children().unwrap()[0]; + let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) }; + assert_eq!(p.page_box, vectorcraft_doc::PageBox::Crop); let _ = std::fs::remove_dir_all(&d); } diff --git a/crates/engine/src/cmd/fileio/tests_jpeg.rs b/crates/engine/src/cmd/fileio/tests_jpeg.rs index 2e3c0d156c..7e27c15cc6 100644 --- a/crates/engine/src/cmd/fileio/tests_jpeg.rs +++ b/crates/engine/src/cmd/fileio/tests_jpeg.rs @@ -1,4 +1,5 @@ -//! JPEG Options: colour model, coding method, scans, profile and image maps. +//! JPEG Options: colour model, coding method, scans, profile and image maps; JPEG files named +//! `.jpe` open and place. use serde_json::{Value, json}; @@ -87,3 +88,28 @@ fn image_maps_list_the_objects_with_a_url() { // One file only: Export for Screens can't add the map. assert!(s.execute("document.exportForScreens", &json!({"formats": [{"format": "jpg", "imageMap": "client"}]})).is_err()); } + +/// JPEG files named `.jpe` open and place as JPEG, in any case; the dialogs and a drop on the +/// window take them by their extension, the desktop packaging doesn't associate them, and exports +/// still write `.jpg`. +#[test] +fn jpe_files_open_and_place() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let jpg = b64(&s.execute("document.export", &json!({"format": "jpg"})).unwrap()); + let data = vectorcraft_format::base64_encode(&jpg); + for name in ["art.jpe", "ART.JPE"] { + assert_eq!(readable_format_for_name(name).map(|f| f.id), Some("jpg"), "{name}"); + let r = s.execute("document.open", &json!({"name": name, "dataBase64": data})).unwrap(); + assert_eq!((&r["format"], &r["warnings"]), (&json!("jpg"), &json!([])), "{name}: {r}"); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + let r = s.execute("file.place", &json!({"name": name, "dataBase64": data})).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("jpg"), Some(1)), "{name}: {r}"); + } + assert!(OPEN_EXTS.contains(&"jpe") && PLACE_EXTS.contains(&"jpe") && UNASSOCIATED_EXTS.contains(&"jpe")); + let jpeg = ("JPEG", &["jpg", "jpeg", "jpe"][..]); + assert!(open_filters().any(|f| f == jpeg) && place_filters().any(|f| f == jpeg)); + assert!(!export_extensions().contains(&"jpe")); + assert!(format_for_name("x.jpe").is_none() && writable_format(None, Some("x.jpe")).is_err()); + assert!(s.execute("document.export", &json!({"path": "x.jpe"})).is_err()); +} diff --git a/crates/engine/src/cmd/fileio/tests_tiffbmp.rs b/crates/engine/src/cmd/fileio/tests_tiffbmp.rs index 74df5216aa..9a00ad28e0 100644 --- a/crates/engine/src/cmd/fileio/tests_tiffbmp.rs +++ b/crates/engine/src/cmd/fileio/tests_tiffbmp.rs @@ -138,8 +138,38 @@ fn targa_depth_reaches_the_file() { } let tga = export(&mut s, json!({"format": "tga"})); assert_eq!(tga[16], 24, "24 bits by default"); - for bad in [json!({"depth": 8}), json!({"colorModel": "gray"})] { - assert!(s.execute("document.export", &merge(json!({"format": "tga"}), bad.clone())).is_err(), "{bad}"); + for bad in [ + json!({"depth": 8}), + json!({"colorModel": "cmyk"}), + json!({"colorModel": "lab"}), + json!({"colorModel": "gray", "depth": 24}), + json!({"colorModel": "gray", "depth": 32}), + ] { + let e = s.execute("document.export", &merge(json!({"format": "tga"}), bad.clone())).unwrap_err(); + assert!(matches!(e, EngineError::BadParams { .. }), "{bad}: {e}"); + } +} + +#[test] +fn targa_color_model_gray_writes_grayscale() { + let mut s = session(); + let gray = export(&mut s, json!({"format": "tga", "colorModel": "gray"})); + assert_eq!((gray[2], gray[16], gray[17]), (3, 8, 0), "grayscale, 8 bits by default, no alpha"); + let img = image::load_from_memory_with_format(&gray, image::ImageFormat::Tga).unwrap().to_rgba8(); + assert_eq!(img.dimensions(), (60, 40)); + assert_eq!(img.get_pixel(5, 5).0, [255; 4], "flattened on white"); + let black = img.get_pixel(40, 20).0; + assert!(black[0] == black[1] && black[1] == black[2] && black[0] < 80, "{black:?}"); + + let alpha = export(&mut s, json!({"format": "tga", "colorModel": "gray", "depth": 16})); + assert_eq!((alpha[2], alpha[16], alpha[17]), (3, 16, 8), "grayscale with an 8-bit alpha"); + let img = image::load_from_memory_with_format(&alpha, image::ImageFormat::Tga).unwrap().to_rgba8(); + assert_eq!(img.get_pixel(5, 5).0[3], 0, "transparent where nothing is drawn"); + assert_eq!(img.get_pixel(40, 20).0[3], 255); + + for file in [gray, alpha] { + let r = s.execute("document.open", &json!({"name": "back.tga", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap(); + assert_eq!(r["format"], "tga"); } } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index a2dd7f83a6..4975d3ec48 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -147,7 +147,7 @@ pub fn specs() -> Vec { "Delete Artboard", ["Window", "Artboards"], None, - "{index | indices: [index…]} delete artboards (with their guides) in one step; one is always left, and a locked one is an error", + "{index | indices: [index…]} delete artboards (with their guides) in one step; one is always left, and a locked one, or the one an open Create Font Sheet dialog uses, is an error", has_doc, artboard_delete ), @@ -156,7 +156,7 @@ pub fn specs() -> Vec { "Delete Empty Artboards", ["Window", "Artboards"], None, - "{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go) → {deleted: [index…]} (the indices before deleting)", + "{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go); an error, with nothing deleted, when one of them is the artboard an open Create Font Sheet dialog uses → {deleted: [index…]} (the indices before deleting)", has_empty_artboards, artboard_delete_empty ), @@ -1225,11 +1225,25 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result { fn artboard_delete(s: &mut Session, p: &Value) -> Result { let indices = super::panelcmds::artboard_indices(&s.doc()?.doc, p, "artboard.delete")?; + refuse_guarded(s, &indices)?; super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?; s.edit("Delete Artboard", |d, sel| remove_artboards(d, sel, &indices))?; ok() } +/// The session's artboard deletion guard's message when deleting artboards `indices` of the +/// active document would delete the artboard it protects. +pub(crate) fn refuse_guarded(s: &Session, indices: &[usize]) -> Result<()> { + let Some(guard) = &s.artboard_deletion_guard else { return Ok(()) }; + let state = s.doc()?; + if (state.uid, state.reverts) == guard.document + && indices.iter().any(|&index| state.doc.artboards.get(index).is_some_and(|a| a.id == guard.artboard)) + { + return Err(EngineError::Other(guard.message.clone())); + } + Ok(()) +} + /// Delete artboards `indices` (sorted, each once) of `d` with their guides; at least one must be /// left. The other artboards keep their order, no later artboard takes a deleted one's id, and /// `sel` forgets the deleted guides. One walk over the artboards and one over the ruler guides, @@ -1306,6 +1320,7 @@ fn artboard_delete_empty(s: &mut Session, _: &Value) -> Result { if indices.is_empty() { return Err(EngineError::Other("no empty artboards to delete".into())); } + refuse_guarded(s, &indices)?; s.edit("Delete Empty Artboards", |d, sel| remove_artboards(d, sel, &indices))?; Ok(json!({ "deleted": indices })) } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 3851aeefac..92171a0b71 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -3061,6 +3061,22 @@ fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::R if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) } } +/// `path` with `.ext` added when it has no extension: the file Unembed writes for a `path` given. +fn with_unembed_extension(path: &str, ext: &str) -> String { + if fileio::extension(path).is_empty() { format!("{path}.{ext}") } else { path.to_string() } +} + +/// The file `links.unembed {id, path}` writes embedded image `id` of the active document to: `path` +/// with the extension of the format the image is stored in added when `path` has none. `None` when +/// `id` is not an embedded image there. +pub fn unembed_path(s: &Session, id: u64, path: &str) -> Option { + let st = s.doc().ok()?; + let doc = with_brush_art(&st.doc); + let im = image_of(&doc, NodeId(id)).filter(|im| im.link.is_none())?; + let blob = st.doc.images.get(&im.key)?; + Some(with_unembed_extension(path, stored_extension(blob))) +} + fn unembed(s: &mut Session, p: &Value) -> Result { const C: &str = "links.unembed"; let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); @@ -3097,7 +3113,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result { let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned()); return Ok(json!({ "name": format!("{stem}.{ext}"), "dataBase64": vectorcraft_format::base64_encode(&bytes) })); }; - let path = absolute_path(&if fileio::extension(path).is_empty() { format!("{path}.{ext}") } else { path.to_string() }); + let path = absolute_path(&with_unembed_extension(path, &ext)); // Read before writing: pixels that can't be read leave no file behind. let img = linked_image(&bytes, Some(&path))?; write_file(&path, &bytes)?; diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 0f604d81f1..4adf91a9c8 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -38,7 +38,7 @@ pub fn specs() -> Vec { "Cut Artboard", [], None, - "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}", + "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, a locked one, or the one an open Create Font Sheet dialog uses; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}", has_doc, |s, p| { boards_and_art_noted(s, p, "artboard.cut")?; @@ -366,6 +366,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result Vec { "Move Direction Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle", + "{id (a path, or type on a path), subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle", has_doc, set_handle ), @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Move Anchor Point", [], None, - "{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again", + "{id (a path, or type on a path), subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again", has_doc, move_anchor ), @@ -149,7 +149,7 @@ pub fn specs() -> Vec { "Add Anchor Point", [], None, - "{id, subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected", + "{id (a path, or type on a path), subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected; type on a path is left selected whole, with no direct-selected anchors (with selectAnchor, or when it wasn't selected, it becomes the selection)", has_doc, insert_anchor ), @@ -719,39 +719,42 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Reshape", |d, _| { - let path = path_mut(d, id)?; - let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - let old_point = a.p; - let old_handle = if out { a.h_out } else { a.h_in }; - if let Some(to) = at { - a.translate(to - a.p); - } - let handle = if out { a.h_out } else { a.h_in }; - let kind_changes = independent && a.kind != AnchorKind::Corner; - // Ordinary decimal moves can round `at - old_point` differently from the handle's - // translation. Within that calculation's roundoff, place the selected point exactly - // without realigning the other stored Smooth handle. Real edits still use set_handle. - let translation_roundoff = at.is_some_and(|to| { - let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| { - let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0); - (actual - requested).abs() <= 4.0 * f64::EPSILON * scale - }; - to != old_point && matches(handle.x, pos.x, old_point.x, old_handle.x, to.x) && matches(handle.y, pos.y, old_point.y, old_handle.y, to.y) - }); - if !kind_changes && (handle == pos || translation_roundoff) { - if out { - a.h_out = pos; - } else { - a.h_in = pos; + super::draw2::with_anchor_path(d, id, |path| { + let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + let old_point = a.p; + let old_handle = if out { a.h_out } else { a.h_in }; + if let Some(to) = at { + a.translate(to - a.p); } - } else { - a.set_handle(out, pos, independent); - } - if symmetric { - let opposite = a.p - (pos - a.p); - if out { a.h_in = opposite } else { a.h_out = opposite } - } - Ok(()) + let handle = if out { a.h_out } else { a.h_in }; + let kind_changes = independent && a.kind != AnchorKind::Corner; + // Ordinary decimal moves can round `at - old_point` differently from the handle's + // translation. Within that calculation's roundoff, place the selected point exactly + // without realigning the other stored Smooth handle. Real edits still use set_handle. + let translation_roundoff = at.is_some_and(|to| { + let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| { + let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0); + (actual - requested).abs() <= 4.0 * f64::EPSILON * scale + }; + to != old_point + && matches(handle.x, pos.x, old_point.x, old_handle.x, to.x) + && matches(handle.y, pos.y, old_point.y, old_handle.y, to.y) + }); + if !kind_changes && (handle == pos || translation_roundoff) { + if out { + a.h_out = pos; + } else { + a.h_in = pos; + } + } else { + a.set_handle(out, pos, independent); + } + if symmetric { + let opposite = a.p - (pos - a.p); + if out { a.h_in = opposite } else { a.h_out = opposite } + } + Ok(()) + }) })?; ok() } @@ -852,22 +855,26 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out if s.script_running() { return Err(EngineError::Busy); } - let unchanged = s.doc()?.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)).is_some_and(|sp| { - sp.anchors.get(ai).is_some_and(|a| { - let mut linked = *a; - linked.link_handle(out, pos, sp.has_segment(ai, !out)); - linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos)) + let unchanged = s.doc()?.doc.node(id).and_then(Node::anchor_path).is_some_and(|pd| { + pd.subpaths.get(si).is_some_and(|sp| { + sp.anchors.get(ai).is_some_and(|a| { + let mut linked = *a; + linked.link_handle(out, pos, sp.has_segment(ai, !out)); + linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos)) + }) }) }); if unchanged { return ok(); } s.edit("Reshape", |d, _| { - let sp = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - let pull_out = sp.has_segment(ai, !out); - let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - a.link_handle(out, pos, pull_out); - Ok(()) + super::draw2::with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + let pull_out = sp.has_segment(ai, !out); + let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + a.link_handle(out, pos, pull_out); + Ok(()) + }) })?; ok() } @@ -958,6 +965,13 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Move", |d, sel| { + if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) { + return super::draw2::with_anchor_path(d, id, |path| { + let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + *a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p)); + Ok(()) + }); + } let old = d.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).map(|a| a.p); let before = corner_sources(d, id); let moved = BTreeSet::from([(si, ai)]); @@ -975,24 +989,25 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result { ok() } -/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path that has it. -/// Busy while a script runs, as [`Session::edit`] is. +/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path, or type +/// on a path ([`Node::anchor_path`], in document space), that has it. Busy while a script runs, as +/// [`Session::edit`] is. fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result> { if s.script_running() { return Err(EngineError::Busy); } let d = &s.doc()?.doc; - Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).copied()) + Ok(d.node(id).and_then(Node::anchor_path).and_then(|path| path.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)).copied())) } -/// Whether anchor `ai` of subpath `si` of path `id` has a segment on its outgoing (`out`) or -/// incoming side; false when the path, subpath or anchor is not there. +/// Whether anchor `ai` of subpath `si` of path `id` (or of type on a path's path) has a segment on +/// its outgoing (`out`) or incoming side; false when the path, subpath or anchor is not there. fn has_segment(s: &Session, id: NodeId, si: usize, ai: usize, out: bool) -> Result { if s.script_running() { return Err(EngineError::Busy); } let d = &s.doc()?.doc; - Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out))) + Ok(d.node(id).and_then(Node::anchor_path).is_some_and(|path| path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, out)))) } fn set_anchors(s: &mut Session, p: &Value) -> Result { @@ -1089,45 +1104,82 @@ fn reverse(s: &mut Session, p: &Value) -> Result { None => path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect(), } }; - let changed = super::overprint::edit_counted(s, "Reverse Path Direction", |d| { - // A compound path's own strokes run along its members' subpaths in order, so they turn - // with them, read before any member turns. - let compounds: BTreeSet = ids.iter().map(|id| compound_or_self(d, *id)).filter(|c| ids.binary_search(c).is_err()).collect(); - for c in compounds { - let Some(NodeKind::Compound { children, .. }) = d.node(c).map(|n| &n.kind) else { continue }; - let flip: Vec = children - .iter() - .filter_map(|m| m.path_data().map(|pd| if ids.binary_search(&m.id).is_ok() { flip_of(pd) } else { vec![false; pd.subpaths.len()] })) - .flatten() - .collect(); - if flip.contains(&true) - && let Some(n) = d.node_mut(c) - { - vectorcraft_doc::blend::reverse_stroke_records(n, &flip); + let mut d = (*s.doc()?.doc).clone(); + // A compound path's own strokes run along its members' subpaths in order, so they turn + // with them, read before any member turns. + let compounds: BTreeSet = ids.iter().map(|id| compound_or_self(&d, *id)).filter(|c| ids.binary_search(c).is_err()).collect(); + for c in compounds { + let Some(NodeKind::Compound { children, .. }) = d.node(c).map(|n| &n.kind) else { continue }; + let flip: Vec = children + .iter() + .filter_map(|m| m.path_data().map(|pd| if ids.binary_search(&m.id).is_ok() { flip_of(pd) } else { vec![false; pd.subpaths.len()] })) + .flatten() + .collect(); + if flip.contains(&true) + && let Some(n) = d.node_mut(c) + { + vectorcraft_doc::blend::reverse_stroke_records(n, &flip); + } + } + let mut turned = Vec::new(); + for id in &ids { + let path = path_mut(&mut d, *id)?; + let flip = flip_of(path); + if !flip.contains(&true) { + continue; + } + // The stroke's width profile and pen recordings turn with the path, read before it turns. + if let Some(n) = d.node_mut(*id) { + vectorcraft_doc::blend::reverse_stroke_records(n, &flip); + } + let path = path_mut(&mut d, *id)?; + for (sp, f) in path.subpaths.iter_mut().zip(&flip) { + if *f { + sp.reverse(); } } - let mut changed = 0; - for id in &ids { - let path = path_mut(d, *id)?; - let flip = flip_of(path); - if !flip.contains(&true) { - continue; - } - // The stroke's width profile and pen recordings turn with the path, read before it turns. - if let Some(n) = d.node_mut(*id) { - vectorcraft_doc::blend::reverse_stroke_records(n, &flip); - } - let path = path_mut(d, *id)?; - for (sp, f) in path.subpaths.iter_mut().zip(flip) { - if f { - sp.reverse(); + turned.push((*id, flip)); + } + if !turned.is_empty() { + s.edit("Reverse Path Direction", |doc, sel| { + *doc = d; + for (id, flip) in &turned { + if let Some(path) = doc.node(*id).and_then(Node::path_data) { + reverse_selected_anchors(sel, *id, path, flip); } } - changed += 1; - } - Ok(changed) - })?; - Ok(json!({ "changed": changed })) + Ok(()) + })?; + } + Ok(json!({ "changed": turned.len() })) +} + +/// Point the selected anchors, selected segments and key anchor of `sel` on path `id` at the same +/// points after the subpaths of `path` marked in `flip` were reversed ([`SubPath::reverse`]). In a +/// reversed subpath of `n` anchors, anchor `i` becomes anchor `n - 1 - i` and segment `j` becomes +/// segment `n - 2 - j`; a closed subpath's closing segment (`n - 1`) stays its closing segment. +fn reverse_selected_anchors(sel: &mut Selection, id: NodeId, path: &PathData, flip: &[bool]) { + let reversed = |si: usize| path.subpaths.get(si).filter(|_| flip.get(si) == Some(&true)).map(|sp| (sp.anchors.len(), sp.closed)); + let anchor = |(si, ai): AnchorRef| match reversed(si) { + Some((n, _)) if ai < n => (si, n - 1 - ai), + _ => (si, ai), + }; + let segment = |(si, j): SegmentRef| match reversed(si) { + Some((n, true)) if j < n => (si, (2 * n - 2 - j) % n), + Some((n, false)) if j < n.saturating_sub(1) => (si, n - 2 - j), + _ => (si, j), + }; + if let Some(set) = sel.anchors.get_mut(&id) { + *set = set.iter().map(|r| anchor(*r)).collect(); + } + if let Some(set) = sel.segments.get_mut(&id) { + *set = set.iter().map(|r| segment(*r)).collect(); + } + if let Some((key, r)) = sel.key_anchor + && key == id + { + sel.key_anchor = Some((id, anchor(r))); + } } /// First and last anchor points of a subpath. @@ -2409,8 +2461,9 @@ fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f shares } -/// After an anchor is added at `(si, added)` of path `id`, number the direct-selected anchors and -/// selected segments after it on that subpath one higher, so the selection keeps the same points. +/// After an anchor is added at `(si, added)` of path `id`, number the direct-selected anchors, +/// selected segments and key anchor after it on that subpath one higher, so the selection keeps +/// the same points. /// A selected segment that the new anchor splits stays selected as its two halves, and the new /// anchor joins its ends in the anchors that move with it. fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usize) { @@ -2419,6 +2472,14 @@ fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usiz // renumbering saturates instead of overflowing. *set = set.iter().map(|&(s, a)| if s == si && a >= added { (s, a.saturating_add(1)) } else { (s, a) }).collect(); } + // The key anchor moves along with the anchors after the new one. + if let Some((key, (s, a))) = sel.key_anchor + && key == id + && s == si + && a >= added + { + sel.key_anchor = Some((id, (s, a.saturating_add(1)))); + } let split = added.checked_sub(1); if sel.segments.get(&id).is_some_and(|set| split.is_some_and(|g| set.contains(&(si, g)))) { sel.anchors.entry(id).or_default().insert((si, added)); @@ -2564,12 +2625,27 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result { let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0); let select_anchor = switch_or(p, "selectAnchor", false, "path.insertAnchor")?; let idx = s.edit("Add Anchor Point", |d, sel| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - if seg >= sp.segment_count() { - return Err(EngineError::Other("no such segment".into())); + let idx = super::draw2::with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + if seg >= sp.segment_count() { + return Err(EngineError::Other("no such segment".into())); + } + Ok(sp.insert_anchor(seg, t)) + })?; + // Type on a path is selected whole and keeps no direct-selected anchors, as `path.removeAnchor` + // leaves it: the arrow keys and `path.moveAnchors` move anchors of paths only. + if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) { + if select_anchor || !sel.contains(id) { + sel.clear(); + } + sel.anchors.remove(&id); + sel.segments.remove(&id); + if sel.key_anchor.is_some_and(|(k, _)| k == id) { + sel.key_anchor = None; + } + sel.add(id); + return Ok(idx); } - let idx = sp.insert_anchor(seg, t); renumber_after_insert(sel, id, si, idx); // A path that wasn't selected becomes the selection, its new anchor direct-selected, so // the point added shows and can be edited at once (#4237). `selectAnchor` does the same diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 621ee4fb07..6755da719d 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -183,13 +183,13 @@ pub(crate) fn pt_per_px(ppi: Option<(f64, f64)>) -> (f64, f64) { /// [`load_sliced`] without the slices. fn load(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result { - load_into(p, cmd, board, link_pdf, &mut vec![]) + load_into(p, cmd, board, link_pdf, None, &mut vec![]) } /// [`load_into`], with the slices of a PSD or PSB file that `importSlices` brings in. -fn load_sliced(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result<(Loaded, Slices)> { +fn load_sliced(p: &Value, cmd: &str, board: Option, link_pdf: bool, given: Option<&[u8]>) -> Result<(Loaded, Slices)> { let mut slices = vec![]; - let l = load_into(p, cmd, board, link_pdf, &mut slices)?; + let l = load_into(p, cmd, board, link_pdf, given, &mut slices)?; Ok((l, slices)) } @@ -197,9 +197,10 @@ fn load_sliced(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Res /// (unless the params name their own box). A PDF/.ai page or an EPS file read from a path is placed /// linked with Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB /// file's slices go to `slices`. A file an importer plug-in places (the one `importer` names, or one -/// no built-in format reads) is read by it ([`plugin_art`]). -fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_out: &mut Slices) -> Result { - let src = fileio::importer::place_source(p, cmd)?; +/// no built-in format reads) is read by it ([`plugin_art`]). `given`: the bytes of the file `p`'s +/// `path` names, read already ([`PlaceJob::with_bytes`]). +fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, given: Option<&[u8]>, slices_out: &mut Slices) -> Result { + let src = fileio::importer::place_source(p, cmd, given)?; let name = fileio::file_name(src.name); if let Some(plugin) = fileio::importer::named_for_place(src.name, p, cmd)? { return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd); @@ -238,11 +239,14 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o } return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None }); } - let Some(format) = fileio::detect(src.name, &src.bytes) else { - return match fileio::importer::for_place(src.name) { - Some(plugin) => plugin_art(name, src.name, &src.bytes, &plugin, p, cmd), - None => Err(bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)"))), - }; + let format = fileio::detect(src.name, &src.bytes); + if format.is_none_or(|f| !fileio::reads(f)) + && let Some(plugin) = fileio::importer::for_place(src.name) + { + return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd); + } + let Some(format) = format else { + return Err(bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)"))); }; let page = match p.get("page") { None => 1, @@ -760,8 +764,13 @@ pub struct PlaceJob { /// The object Replace swaps as it was when Place started. replaced: Option, target: Option, + /// The bytes of the file `path` names, read already ([`PlaceJob::with_bytes`]). + bytes: Option, } +/// The bytes of a file read already, shared with whoever read them ([`PlaceJob::with_bytes`]). +pub type GivenBytes = Arc + Send + Sync>; + /// A file [`PlaceJob::read`] read, which [`Session::place_read`] places. pub struct PlaceRead { job: PlaceJob, @@ -775,6 +784,14 @@ impl PlaceJob { str_param(&self.params, "path").or_else(|| str_param(&self.params, "name")).map(fileio::file_name).unwrap_or_else(|| "Untitled".into()) } + /// The job placing `bytes` as the file its `path` names, which [`PlaceJob::read`] then does not + /// read again: the placed object's link and the journaled params keep the path. Without a + /// `path` the bytes are not used. + pub fn with_bytes(mut self, bytes: GivenBytes) -> Self { + self.bytes = Some(bytes); + self + } + /// Read and decode the file, as `file.place` does, without the session. The pixels of a PNG, /// JPEG, GIF or WebP file are decoded here to check that they can be read (an error when they /// can't), a linked image's preview is made from that decode, and the decoded pixels are kept in @@ -782,7 +799,7 @@ impl PlaceJob { /// ([`super::links::readable_and_kept`]). pub fn read(self) -> Result { crate::cancel::check()?; - let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true)?; + let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true, self.bytes.as_deref().map(AsRef::as_ref))?; let linked = loaded.link.is_some() && bool_or(&self.params, "link", true); match &mut loaded.art { Art::Image(img, _) => { @@ -941,12 +958,12 @@ fn prepare(s: &Session, p: &Value) -> Result { (true, _) => return Err(bad(PLACE, "replace: select the one object to replace")), }; let replaced = old.and_then(|id| st.doc.node(id)).cloned(); - Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at) }) + Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at), bytes: None }) } /// Place the file `read` holds in the active document. fn apply(s: &mut Session, read: PlaceRead) -> Result { - let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded, slices: read_slices } = read; + let PlaceRead { job: PlaceJob { params, old, target: read_for, bytes, .. }, mut loaded, slices: read_slices } = read; let p = ¶ms; let template = bool_or(p, "template", false); let at = at_param(p)?; @@ -957,10 +974,11 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { None => None, }; // The artboard under `at` as it is now, as a replay of the journal finds it: a DXF drawing laid - // out on the artboard it was read for is read again when that artboard changed meanwhile. + // out on the artboard it was read for is read again when that artboard changed meanwhile, from + // the same bytes when the job was given them. let target = board_at(&st.doc, at); if loaded.board.is_some() && target != read_for { - loaded = load(p, PLACE, target, true)?; + loaded = load_into(p, PLACE, target, true, bytes.as_deref().map(AsRef::as_ref), &mut vec![])?; } // Type reflows rather than scales: its frame takes the size it is placed at. let is_text = matches!(loaded.art, Art::Text(_)); @@ -1347,7 +1365,7 @@ pub fn read_info(p: &Value) -> Result { check_switches(p, &["link"], "file.place.info")?; check_numbers(p, &["thumbnail"], "file.place.info")?; // A PDF/.ai page linked or not has the same size and art. - let (mut l, slices) = load_sliced(p, "file.place.info", None, false)?; + let (mut l, slices) = load_sliced(p, "file.place.info", None, false, None)?; let natural = l.natural; let mut out = json!({ "name": l.name, diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index fb9d2df26b..0bc243be41 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -895,6 +895,7 @@ pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[ (&["Object"], "Perspective"), (&["Object"], "Live Paint"), (&["Object"], "Image Trace"), + (&["Object"], "Concept to Vector…"), (&["Object"], "Text Wrap"), (&["Object"], "Clipping Mask"), (&["Object"], "Compound Path"), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 988c64a83e..fa90cccf8e 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -762,13 +762,20 @@ pub(super) const ALLOWED: &[&str] = &[ /// Commands a plug-in may not call although no rule refuses them, in order: they change the /// preferences, a tool's options, a drag's state or the font names the whole app knows, list the /// fonts installed on the system as `text.fontList` does, run plug-ins again, read a file and -/// report where it is on disk, or edit text once per match with no limit on the matches in one call. +/// report where it is on disk, edit text once per match with no limit on the matches in one call, +/// or hand an image to a Concept to Vector provider and its results. pub(super) const DENIED: &[&str] = &[ "addon.cleanup.splitText", "addon.pathtools.movePointsTogether", "addon.pen.nextSegment", + "addon.type.fontSheet", "addon.type.numbers", "color.contrast", + "conceptVector.cancel", + "conceptVector.generate", + "conceptVector.insert", + "conceptVector.providers", + "conceptVector.results", "effect.refreshDeferred", "graphicStyle.setOptions", "object.blend.createSpine", diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index e3bbe41d23..72bc9aec80 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -39,7 +39,7 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 39] = [ +const REPLAY_ONLY: [(&str, &str); 40] = [ ("edit.copy", "artboard"), ("edit.cut", "artboard"), ("file.new", "created"), @@ -70,6 +70,7 @@ const REPLAY_ONLY: [(&str, &str); 39] = [ ("artboard.distribute", "activeArtboard"), ("artboard.distributeSpacing", "selectedArtboards"), ("artboard.distributeSpacing", "activeArtboard"), + ("addon.type.fontSheet", "activeArtboard"), ("addon.document.floodFillArtboards", "activeArtboard"), ("edit.copy", "selectedArtboards"), ("edit.copy", "art"), diff --git a/crates/engine/src/concept_vector.rs b/crates/engine/src/concept_vector.rs new file mode 100644 index 0000000000..da5ae76304 --- /dev/null +++ b/crates/engine/src/concept_vector.rs @@ -0,0 +1,269 @@ +//! Concept to Vector providers: what makes vector variations of a selected image. +//! +//! A provider ([`Provider`]) takes one image's encoded pixels and up to [`MAX_STYLES`] of its own +//! style ids ([`Request`]), and returns one [`Variation`] per style, in the order asked, as paths +//! in the image's pixel space with explicit paints. It sees nothing else of the session or the +//! document. The session keeps the providers in a [`Registry`] and calls one only by its id: an +//! unknown or incapable provider is an error, never a substitute. +//! +//! The host checks every result again ([`check_result`]) before it keeps it, whatever provider +//! made it: the number and order of the variations, finite coordinates and widths within bounds, +//! and the totals [`MAX_ANCHORS`] and [`MAX_PATHS`] across all styles. +//! +//! The one built-in provider ([`offline::ID`]) makes its styles with Image Trace, on this +//! computer: it takes no prompt and makes vector art only. + +pub mod offline; +#[cfg(test)] +mod tests; + +use std::sync::Arc; + +use vectorcraft_geom::{PathData, Point}; + +/// The most styles one request may ask for. +pub const MAX_STYLES: usize = 8; + +/// The most anchor points all the variations of one request may hold together. +pub const MAX_ANCHORS: usize = 1_000_000; + +/// The most paths all the variations of one request may hold together, each subpath of a compound +/// path counted as one. +pub const MAX_PATHS: usize = 250_000; + +/// The most warnings a variation may carry, and the most characters in each. +pub const MAX_WARNINGS: usize = 16; +const MAX_WARNING_CHARS: usize = 500; + +/// One of a provider's styles: its stable id and its English name. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +pub struct Style { + pub id: &'static str, + pub label: &'static str, +} + +/// What a provider takes and makes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Capabilities { + /// It takes an image as its input. + pub image_input: bool, + /// It makes editable vector paths. + pub vector_output: bool, + /// It takes a text prompt. + pub prompt: bool, + /// It makes raster images. + pub raster_output: bool, + /// It runs on this computer without a network. + pub offline: bool, + /// Its styles, in the order it lists them. + pub styles: Vec