Merge main into fix/swatches-browser-selection-set

This commit is contained in:
dotCooCoo committed 2026-12-05 04:35:09 -08:00
commit daed599cb4
208 files changed
+12640 -715

No files matched your search

+1
View File
@@ -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.
+2 -2
View File
@@ -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
+4
View File
@@ -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;
+144 -1
View File
@@ -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<dyn FnMut()>;
#[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<super::Viewports<HWND>> = 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<H>(Mutex<HashMap<egui::ViewportId, Option<H>>>);
impl<H> Default for Viewports<H> {
fn default() -> Self {
Self(Mutex::new(HashMap::new()))
}
}
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
impl<H> Viewports<H> {
/// 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<H>) {
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<egui::ViewportId, Option<H>>> {
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<u32>, viewports: &[egui::ViewportId]) -> Vec<Option<u32>> {
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() {
+3
View File
@@ -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";
+5 -1
View File
@@ -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<Imported, String> {
mod tests;
#[cfg(test)]
mod tests_dwg;
#[cfg(test)]
mod tests_region;
+779
View File
@@ -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
//! (<https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-644BF0F0-FD79-4C5E-AD5A-0053FCC5A5A4>); which
//! DXF versions hold text and which binary data is in <https://ezdxf.mozman.at/docs/acis.html>.
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<f64>, Vec<P3>, Option<Vec<f64>>);
/// 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<Tok>,
}
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<bool> {
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<f64> {
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<Rec>,
/// Record number by index, when the records carry their own.
at: HashMap<i64, usize>,
}
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<Outline> {
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<Outline> {
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::<i64>().ok()) {
return Tok::Ptr(p);
}
match w.parse::<f64>() {
Ok(v) if v.is_finite() => Tok::Num(v),
_ => Tok::Word(w.to_string()),
}
}
}
}
/// Does this line start a record (`[-<index>] <type> $<attribute> …`)?
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::<u64>().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<Model> {
let version = text.split_whitespace().next()?.parse::<f64>().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<Tok> = vec![];
let (mut kind, mut index): (Option<String>, Option<i64>) = (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: `@<n>`, a space, then n bytes.
if let Some(n) = word.strip_prefix('@').and_then(|n| n.parse::<usize>().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::<i64>().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<u8> {
self.take(1).map(|s| s[0])
}
fn i16(&mut self) -> Option<f64> {
self.take(2).map(|s| f64::from(i16::from_le_bytes([s[0], s[1]])))
}
fn u16(&mut self) -> Option<usize> {
self.take(2).map(|s| usize::from(u16::from_le_bytes([s[0], s[1]])))
}
fn i32(&mut self) -> Option<i32> {
self.take(4).map(|s| i32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
fn u32(&mut self) -> Option<u32> {
self.take(4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
fn f64(&mut self) -> Option<f64> {
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<String> {
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<Model> {
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<String>, Option<String>, Vec<Tok>) = (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<Xf> {
let n: Vec<f64> = 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<P3> {
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<Outline> {
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::<Vec<_>>()[..]
&& !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<P3> {
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<BezPath> {
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<Spline> {
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<f64> = 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<Point> = 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<PathSeg> = 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<PathSeg> {
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#");
}
}
+2 -2
View File
@@ -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(),
+50 -2
View File
@@ -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<String>,
/// 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<HashMap<u64, Vec<u8>>>,
}
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<HashMap<u64, Vec<u8>>>) -> 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<Geom> {
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<Geom> {
let mut bp = BezPath::new();
for l in &h.loops {
@@ -601,7 +649,7 @@ fn boundary(path: &HatchPath) -> Option<BezPath> {
}
/// `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) => {
+69 -1
View File
@@ -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<LayoutDef>,
/// 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<HashMap<u64, Vec<u8>>>,
}
/// 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<u64, Vec<u8>> {
let records = doc.entities.iter().chain(doc.blocks.iter().flat_map(|b| &b.entities));
let wanted: HashSet<u64> = 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<u8>, size: Option<usize>, limit: usize) -> Option<Vec<u8>> {
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<u8>) -> 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])
}
+686
View File
@@ -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<E> {
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<E>], transform: Option<&str>) -> String {
let mut recs: Vec<String> = 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<u8> {
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<E>> {
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", &region_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<f64> = 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", &region_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", &region_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<u8> {
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<u8>, 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::<i32>().unwrap().to_le_bytes());
}
w if w.starts_with('@') => {
let s = words.next().unwrap();
string(&mut b, 0x07, s);
}
w => match w.parse::<f64>() {
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<usize>| 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<u8> {
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::<Vec<_>>();
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", &region_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", &region_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", &region_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", &region_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", &region_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", &region_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", &region_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", &region_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", &region_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", &region_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", &region_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", &region_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", &region_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", &region_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<String> = 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::<Vec<_>>().join("\n"), recs.join("\n"));
let r = import(&drawing("AC1015", &region_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", &region_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", &region_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", &region_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<String> = 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::<Vec<_>>().join("\n"), recs.join("\n"));
let r = import(&drawing("AC1015", &region_text(&text, false), &[]), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings);
assert!(outline(&r.document).elements().is_empty());
}
+10
View File
@@ -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<std::borrow::Cow<'_, PathData>> {
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),
+18 -7
View File
@@ -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<Node>) {
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<Node>) {
clear(a, false);
}
fn clear(a: &mut Arc<Node>, 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<Node>) {
}
}
// 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);
}
}
+10
View File
@@ -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 {
+2
View File
@@ -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());
+8 -1
View File
@@ -65,7 +65,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Value> {
}
// 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;
+6 -1
View File
@@ -5,8 +5,10 @@
//! (<https://helpx.adobe.com/illustrator/using/formatting-type.html>). 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<CommandSpec> {
numbers::make_numbers
),
]
.into_iter()
.chain(font_sheet::specs())
.collect()
}
/// Release Type on a Path's command (the id in [`specs`]).
@@ -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<CommandSpec> {
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<f64>) -> Result<f64> {
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<String> {
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<Vec<String>> {
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<String> = 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<String> = 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<Value> {
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<Value> {
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<String>)> = 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<String> = vec![];
// The entries whose font lacks a glyph needed by the sample.
let mut fallback: Vec<String> = 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::<String>();
(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<Rect> = (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<Arc<Node>> = 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<String> = 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<String> {
const NAMED: usize = 5;
let (first, more) = (fallback.iter().take(NAMED).cloned().collect::<Vec<_>>(), 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<TextRun>, 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<String> {
const NAMED: usize = 5;
let (first, more) = (skipped.iter().take(NAMED).cloned().collect::<Vec<_>>(), 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;
@@ -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::<Vec<_>>(), 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<String> = 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<f64> = 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, &params).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::<Vec<_>>();
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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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", &params).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, &params).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));
}
+830
View File
@@ -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<Vec<Variation>>),
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<Vec<u8>>,
provider: String,
outcome: Outcome,
}
/// The session's providers and jobs.
pub(crate) struct ConceptState {
pub(crate) registry: cv::Registry,
jobs: VecDeque<Job>,
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<u64> {
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<Job> {
self.concept.jobs.clone()
}
/// Puts back the jobs that [`Self::concept_jobs_snapshot`] took.
pub(crate) fn restore_concept_jobs(&mut self, jobs: VecDeque<Job>) {
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<Job>) {
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<Job>, 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<u64> = 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<Vec<u8>>)> {
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<dyn Provider>,
/// 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<ConceptRun> {
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<String> = 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::<Option<_>>().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<Vec<Variation>, 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<bool, ProviderError> {
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<Variation>) -> Option<Value> {
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<Option<Box<dyn cv::Parts>>>,
/// The styles the provider's parts had made when last asked, inside the panic guard.
done: usize,
made: Vec<Variation>,
}
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<Variation> {
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<Rect> {
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<Value> = 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<u64> {
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<usize> {
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<Value> {
let list: Vec<Value> = 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<Value> {
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<Value> {
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<Value> {
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<Value> {
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::<Option<_>>().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<Variation> = 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<String> = 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<Variation>, Vec<String>) = 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<Rect> = 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<Rect> {
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<Rect> = 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<Node>, Option<Rect>)> = 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<NodeId> = 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::<Vec<_>>() }))
}
#[cfg(test)]
thread_local! {
/// How many times [`place_row`] has looked at an object on this thread.
pub(crate) static LOOKS: std::cell::Cell<usize> = 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<Rect>, start: f64, obstacles: &[Rect]) -> Option<f64> {
// 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<Vec<Rect>> = row(start)
.iter()
.map(|b| {
let mut lane: Vec<Rect> = 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::<usize>() {
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<CommandSpec> {
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
),
]
}
+1 -1
View File
@@ -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;
+44 -24
View File
@@ -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<Value> {
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<Value> {
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<Value> {
}
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()
}
+3 -3
View File
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<CommandSpec> {
"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<CommandSpec> {
"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
),
+23
View File
@@ -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<R>(d: &mut Document, id: NodeId, f: impl FnOnce(&mut PathData) -> Result<R>) -> Result<R> {
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)),
+3 -3
View File
@@ -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;
+1 -1
View File
@@ -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)]
+5 -1
View File
@@ -14,7 +14,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
// 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<Value> {
}
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<Value> {
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<Value> {
(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);
}
};
+6 -3
View File
@@ -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<bool> {
}
/// 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(),
+117 -26
View File
@@ -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<Vec<&'static str>> = 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<Vec<&'static str>> = 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<Item = (&'static str, &'static [&'static str])> {
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<Item = (&'static str, &'static [&'static str])> {
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<Item = (&'static str, &'static [&'static st
pub fn opens_with_importer(name: &str) -> 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<Item = (&'static str, &'static [&'static
/// open dialogs whose files the built-in readers read (New from Template, Load Styles, a document
/// picked for its swatches, symbols, brushes or graphic styles).
pub fn builtin_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
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<Item = (&'static str, &'static [&'static str])> {
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<Value> {
let ids = |pick: fn(&Format) -> bool| all().filter(|f| pick(f)).map(|f| f.id).collect::<Vec<_>>();
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<Value> {
};
Ok(json!({
"formats": all().map(listed).collect::<Vec<_>>(),
"readable": ids(|f| f.read),
"readable": ids(reads),
"writable": ids(|f| f.write),
"openExtensions": open_extensions(),
"unsupported": UNSUPPORTED.iter().map(Unsupported::to_json).collect::<Vec<_>>(),
}))
}
#[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);
}
}
+35 -8
View File
@@ -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<Option<Arc<Plu
check_extension(C, plugin.manifest(), name)?;
return Ok(Some(plugin));
}
if detect(name, bytes).is_some() {
if detect(name, bytes).is_some_and(super::formats::reads) {
return Ok(None);
}
Ok(import::for_extension(&extension(name)).into_iter().next())
@@ -97,7 +98,7 @@ fn importer_reads(ext: &str, mode: Mode) -> 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<u8> = 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<Vec<u8>
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<Vec<u8>> {
/// 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<Source<'a>> {
/// 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<PlaceSource<'a, 'b>> {
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<NodeId>, Vec<import::OutArtboard>, Vec<String>);
+10 -8
View File
@@ -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<Loaded>
// 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<Loaded>
}
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())
+7 -1
View File
@@ -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
+6 -6
View File
@@ -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
@@ -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);
}
+27 -1
View File
@@ -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());
}
+32 -2
View File
@@ -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");
}
}
+17 -2
View File
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<CommandSpec> {
"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<Value> {
fn artboard_delete(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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 }))
}
+17 -1
View File
@@ -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<String> {
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<Value> {
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<Value> {
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)?;
+2 -1
View File
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Val
return Err(EngineError::Other("a document needs at least one artboard".into()));
}
if cut {
super::layer::refuse_guarded(s, &indices)?;
refuse_locked(&st.doc, &indices)?;
}
let art = st.doc.paint_order(arts.into_iter().flat_map(|(_, a)| a));
+169 -93
View File
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<CommandSpec> {
"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<CommandSpec> {
"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<Value> {
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<Value> {
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<Value> {
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<Option<Anchor>> {
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<bool> {
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<Value> {
@@ -1089,45 +1104,82 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
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<NodeId> = 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<bool> = 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<NodeId> = 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<bool> = 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<Value> {
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
+35 -17
View File
@@ -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<Rect>, link_pdf: bool) -> Result<Loaded> {
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<Rect>, link_pdf: bool) -> Result<(Loaded, Slices)> {
fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, 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<Rect>, 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<Rect>, link_pdf: bool, slices_out: &mut Slices) -> Result<Loaded> {
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<Rect>, link_pdf: bool, given: Option<&[u8]>, slices_out: &mut Slices) -> Result<Loaded> {
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<Rect>, 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<Node>,
target: Option<Rect>,
/// The bytes of the file `path` names, read already ([`PlaceJob::with_bytes`]).
bytes: Option<GivenBytes>,
}
/// The bytes of a file read already, shared with whoever read them ([`PlaceJob::with_bytes`]).
pub type GivenBytes = Arc<dyn AsRef<[u8]> + 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<PlaceRead> {
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<PlaceJob> {
(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<Value> {
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 = &params;
let template = bool_or(p, "template", false);
let at = at_param(p)?;
@@ -957,10 +974,11 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
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<Value> {
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,
+1
View File
@@ -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"),
@@ -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",
+2 -1
View File
@@ -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"),
+269
View File
@@ -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<Style>,
}
/// The kind of result a request asks for. `conceptVector.generate` asks only for
/// [`Output::Vector`]: a [`Variation`] holds vector paths.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Output {
Vector,
Raster,
}
/// One request: the encoded pixels of an image, and how to make its variations.
#[derive(Clone, Debug)]
pub struct Request {
/// The image's encoded bytes (PNG, JPEG, WebP or GIF), as the document holds them.
pub image: Arc<Vec<u8>>,
/// The image's size in pixels: the space the variations' paths are in.
pub width: u32,
pub height: u32,
/// The prompt, trimmed; `None` when there is none.
pub prompt: Option<String>,
/// The provider's style ids, 1 to [`MAX_STYLES`] of them, each once.
pub styles: Vec<String>,
/// How much of the image's detail to keep, 0 (least) to 100 (most).
pub detail: u8,
pub output: Output,
}
/// One path of a variation, in the image's pixel space (`(0, 0)` top left, `(width, height)` bottom
/// right).
#[derive(Clone, Debug, PartialEq)]
pub struct VectorPath {
pub path: PathData,
/// The fill color (sRGB), if it is filled.
pub fill: Option<[u8; 3]>,
/// The stroke color (sRGB) and width in pixels, if it is stroked.
pub stroke: Option<([u8; 3], f64)>,
/// Stroked: the stroke's ends are square (cut straight half the width past the path's end);
/// otherwise round.
pub square_caps: bool,
}
/// The variation a provider made for one style.
#[derive(Clone, Debug, PartialEq)]
pub struct Variation {
/// The style id it was made for.
pub style: String,
/// Its paths, bottom-most first.
pub paths: Vec<VectorPath>,
/// Notes for the person who asked (a scaled-down image, nothing traced).
pub warnings: Vec<String>,
}
impl Variation {
/// Its anchor points, every path counted.
pub fn anchors(&self) -> usize {
self.paths.iter().map(|p| p.path.anchor_count()).sum()
}
}
/// Why a provider made nothing.
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
pub enum ProviderError {
/// The image or the request cannot be used.
#[error("{0}")]
InvalidInput(String),
/// The provider does not do what the request asks.
#[error("{0}")]
Unsupported(String),
/// The provider cannot run now.
#[error("{0}")]
Unavailable(String),
/// The caller stopped it.
#[error("cancelled; nothing was changed")]
Canceled,
/// The results would pass a limit.
#[error("the results would have more than {0} anchor points: lower Detail or choose fewer styles")]
ResourceLimit(usize),
/// The provider's results do not match the request, or are out of bounds.
#[error("the provider's results do not match the request or are malformed")]
InvalidResult,
/// The provider stopped on a fault of its own.
#[error("the provider stopped with an internal error: {0}")]
Internal(String),
}
/// How far a provider has got: `steps(done, total)`; it stops with [`ProviderError::Canceled`]
/// once this answers `false`.
pub type Steps<'a> = &'a (dyn Fn(u64, u64) -> bool + Sync);
/// Something that makes vector variations of an image.
pub trait Provider: Send + Sync {
/// Its stable id, such as `offline.traceStyles`.
fn id(&self) -> &'static str;
/// Its English name.
fn name(&self) -> &'static str;
fn capabilities(&self) -> Capabilities;
/// One variation for each of `request.styles`, in that order. A style's variation depends only
/// on the image, the prompt, the detail and that style, not on the other styles asked for: a
/// caller with no thread to wait on asks for one style at a time when [`Provider::parts`] gives
/// `None` (`ConceptRun::run_part`, which the web build uses).
fn generate(&self, request: &Request, steps: Steps) -> Result<Vec<Variation>, ProviderError>;
/// What [`Provider::generate`] makes, made a part at a time ([`Parts`]), for a caller with no
/// thread to wait on; `None` (the default) when it makes no parts smaller than one style.
fn parts(&self, _request: &Request) -> Option<Box<dyn Parts>> {
None
}
}
/// A request's variations made a part at a time: each call of [`Parts::step`] does a part and
/// returns, so that the caller can run other work, or stop, between parts.
pub trait Parts: Send {
/// Does the next part → the variations once the last part is done, `None` before it.
fn step(&mut self) -> Result<Option<Vec<Variation>>, ProviderError>;
/// The styles made so far.
fn styles_done(&self) -> usize;
}
/// The providers a session can call, by id.
#[derive(Clone)]
pub struct Registry {
providers: Vec<Registered>,
}
/// A provider in a [`Registry`], with the id, name and capabilities it gave when it was
/// registered.
#[derive(Clone)]
pub struct Registered {
pub id: &'static str,
pub name: &'static str,
pub capabilities: Capabilities,
pub provider: Arc<dyn Provider>,
}
impl Default for Registry {
/// The built-in provider only.
fn default() -> Self {
let p = offline::TraceStyles;
Self { providers: vec![Registered { id: p.id(), name: p.name(), capabilities: p.capabilities(), provider: Arc::new(p) }] }
}
}
impl Registry {
/// A registry with no provider.
pub fn empty() -> Self {
Self { providers: vec![] }
}
/// Add `provider`, reading its id, name and capabilities once; an error when one with its id
/// is registered already, or when the provider panics while giving them.
pub fn register(&mut self, provider: Arc<dyn Provider>) -> Result<(), String> {
let (id, name, capabilities) = crate::guard::catch_panic(|| (provider.id(), provider.name(), provider.capabilities()))
.map_err(|e| ProviderError::Internal(e).to_string())?;
if self.get(id).is_some() {
return Err(format!("a provider with the id `{id}` is registered already"));
}
self.providers.push(Registered { id, name, capabilities, provider });
Ok(())
}
/// The provider `id` (exactly so spelled).
pub fn get(&self, id: &str) -> Option<&Registered> {
self.providers.iter().find(|p| p.id == id)
}
/// The providers in the order they were registered.
pub fn iter(&self) -> impl Iterator<Item = &Registered> {
self.providers.iter()
}
}
/// Whether `p` is a finite point within `limit` of the image's pixel space.
fn within(p: Point, limit: f64, size: (f64, f64)) -> bool {
p.x.is_finite() && p.y.is_finite() && p.x >= -limit && p.y >= -limit && p.x <= size.0 + limit && p.y <= size.1 + limit
}
/// Checks the variations a provider returned for `request`: one per style in the order asked, at
/// most [`MAX_PATHS`] paths (each subpath of a compound path counted as one) and [`MAX_ANCHORS`]
/// anchors together, each path with a fill or a stroke and with subpaths that each have an anchor,
/// every anchor and handle finite and within one image side of the image, every
/// stroke width finite, over 0 and at most the image's larger side, and at most [`MAX_WARNINGS`]
/// warnings of at most 500 characters on each variation.
pub fn check_result(request: &Request, variations: &[Variation]) -> Result<(), ProviderError> {
if variations.len() != request.styles.len() || variations.iter().zip(&request.styles).any(|(v, s)| v.style != *s) {
return Err(ProviderError::InvalidResult);
}
let size = (f64::from(request.width.max(1)), f64::from(request.height.max(1)));
let side = size.0.max(size.1);
let (mut paths, mut anchors) = (0usize, 0usize);
for v in variations {
// Each subpath of a compound path becomes an object of its own when it is inserted.
paths = v.paths.iter().fold(paths, |n, p| n.saturating_add(p.path.subpaths.len().max(1)));
anchors += v.anchors();
if anchors > MAX_ANCHORS {
return Err(ProviderError::ResourceLimit(MAX_ANCHORS));
}
if paths > MAX_PATHS || v.warnings.len() > MAX_WARNINGS || v.warnings.iter().any(|w| w.chars().count() > MAX_WARNING_CHARS) {
return Err(ProviderError::InvalidResult);
}
for p in &v.paths {
let width_ok = p.stroke.is_none_or(|(_, w)| w.is_finite() && w > 0.0 && w <= side);
let painted = p.fill.is_some() || p.stroke.is_some();
let points_ok = p.path.anchors().all(|(_, _, a)| [a.p, a.h_in, a.h_out].into_iter().all(|q| within(q, side, size)));
let no_empty_subpath = !p.path.subpaths.is_empty() && p.path.subpaths.iter().all(|sp| !sp.anchors.is_empty());
if !width_ok || !painted || !no_empty_subpath || !points_ok {
return Err(ProviderError::InvalidResult);
}
}
}
Ok(())
}
+440
View File
@@ -0,0 +1,440 @@
//! The built-in provider: Concept to Vector styles made with Image Trace on this computer.
//!
//! Each style is a fixed set of Image Trace settings of VectorCraft's own, and Detail (0 to 100)
//! moves its Paths, Noise and color count within that style's range. The image is decoded once and
//! traced once per style; an image over [`MAX_PIXELS`] is scaled down first, aspect kept, and
//! each variation says so. The paths are mapped back to the image's own pixel size.
use std::sync::Arc;
use vectorcraft_geom::kurbo::common::solve_cubic;
use vectorcraft_geom::{Affine, Anchor, CubicBez, ParamCurve, PathData, Point, SubPath};
use vectorcraft_trace as tr;
use super::{Capabilities, MAX_ANCHORS, MAX_PATHS, Output, Parts, ProviderError, Request, Steps, Style, Variation, VectorPath};
/// The built-in provider's id.
pub const ID: &str = "offline.traceStyles";
/// The most pixels the built-in provider traces an image at (16 megapixels).
pub const MAX_PIXELS: u64 = 16 << 20;
/// The built-in provider's styles, in the order it lists them.
pub const STYLES: [Style; 5] = [
Style { id: "outline", label: "Outline" },
Style { id: "inkLines", label: "Ink Lines" },
Style { id: "flatColor", label: "Flat Color" },
Style { id: "detailedColor", label: "Detailed Color" },
Style { id: "grayTones", label: "Gray Tones" },
];
/// Concept to Vector styles made with Image Trace ([`ID`]).
pub struct TraceStyles;
/// `lo` at Detail 0 to `hi` at Detail 100.
fn between(lo: f64, hi: f64, t: f64) -> f64 {
lo + (hi - lo) * t
}
/// The trace settings of style `id` at Detail `detail` (0 to 100); `None` for an id that isn't one
/// of [`STYLES`].
pub fn style_params(id: &str, detail: u8) -> Option<tr::TraceParams> {
let t = f64::from(detail.min(100)) / 100.0;
let noise = |lo: f64, hi: f64| between(hi, lo, t).round().max(1.0) as u32;
let count = |lo: f64, hi: f64| between(lo, hi, t).round() as u32;
let base = tr::TraceParams { shapes: false, gradients: false, auto_grouping: false, ..tr::TraceParams::default() };
Some(match id {
// Black stroked lines only: thin lines as center lines, wider areas as outlines.
"outline" => {
tr::TraceParams { fills: false, strokes: true, ignore_white: true, paths: between(50.0, 90.0, t), noise: noise(4.0, 40.0), ..base }
}
// Black filled ink on no background, the straight runs straightened.
"inkLines" => tr::TraceParams {
ignore_white: true,
snap_curves_to_lines: true,
paths: between(50.0, 95.0, t),
corners: 80.0,
noise: noise(4.0, 30.0),
..base
},
// A few flat colors, abutting.
"flatColor" => tr::TraceParams {
mode: tr::Mode::Color,
colors: count(3.0, 8.0),
paths: between(40.0, 80.0, t),
corners: 60.0,
noise: noise(8.0, 40.0),
snap_curves_to_lines: true,
..base
},
// Many colors, stacked so no hairline gaps show.
"detailedColor" => tr::TraceParams {
mode: tr::Mode::Color,
colors: count(12.0, 32.0),
paths: between(70.0, 95.0, t),
corners: 40.0,
noise: noise(2.0, 12.0),
method: tr::Method::Overlapping,
..base
},
// Grays, stacked.
"grayTones" => tr::TraceParams {
mode: tr::Mode::Grayscale,
colors: count(4.0, 12.0),
paths: between(55.0, 90.0, t),
corners: 50.0,
noise: noise(4.0, 20.0),
method: tr::Method::Overlapping,
..base
},
_ => return None,
})
}
/// `img` box-filtered down to at most [`MAX_PIXELS`], aspect kept; `img` itself when it fits.
fn fit(img: tr::Raster) -> tr::Raster {
fit_within(img, MAX_PIXELS)
}
/// `img` box-filtered down to at most `max` pixels (at least 1), aspect kept as far as a side of
/// at least one pixel allows; `img` itself when it fits.
pub(super) fn fit_within(img: tr::Raster, max: u64) -> tr::Raster {
let (w, h) = (u64::from(img.width), u64::from(img.height));
let max = max.max(1);
if w * h <= max || w == 0 || h == 0 {
return img;
}
let k = (max as f64 / (w * h) as f64).sqrt();
// A side that rounds down to one pixel leaves the other side the whole budget, no more.
let nh = ((h as f64 * k).floor() as u64).clamp(1, h.min(max));
let nw = ((w as f64 * k).floor() as u64).clamp(1, w.min(max / nh)) as u32;
let nh = nh as u32;
let mut rgba = Vec::with_capacity(nw as usize * nh as usize * 4);
for y in 0..nh {
let (y0, y1) = (u64::from(y) * h / u64::from(nh), (u64::from(y + 1) * h / u64::from(nh)).max(u64::from(y) * h / u64::from(nh) + 1));
for x in 0..nw {
let (x0, x1) = (u64::from(x) * w / u64::from(nw), (u64::from(x + 1) * w / u64::from(nw)).max(u64::from(x) * w / u64::from(nw) + 1));
// Each pixel's color is weighted by its alpha. A box with nothing opaque in it is clear black.
let mut sum = [0u64; 4];
for sy in y0..y1.min(h) {
for sx in x0..x1.min(w) {
let [r, g, b, a] = img.pixel(sx as u32, sy as u32).map(u64::from);
sum = [sum[0] + r * a, sum[1] + g * a, sum[2] + b * a, sum[3] + a];
}
}
let n = ((y1.min(h) - y0) * (x1.min(w) - x0)).max(1);
let alpha = sum[3];
let color = |s: u64| s.checked_div(alpha).map_or(0, |c| c.min(255) as u8);
rgba.extend([color(sum[0]), color(sum[1]), color(sum[2]), (alpha / n) as u8]);
}
}
tr::Raster { width: nw, height: nh, rgba }
}
impl super::Provider for TraceStyles {
fn id(&self) -> &'static str {
ID
}
fn name(&self) -> &'static str {
"Offline Image Trace Styles"
}
fn capabilities(&self) -> Capabilities {
Capabilities { image_input: true, vector_output: true, prompt: false, raster_output: false, offline: true, styles: STYLES.to_vec() }
}
fn generate(&self, request: &Request, steps: Steps) -> Result<Vec<Variation>, ProviderError> {
let params = checked(request)?;
let total = params.len() as u64;
if !steps(0, total) {
return Err(ProviderError::Canceled);
}
let image = Decoded::new(request)?;
let mut left = MAX_ANCHORS;
let mut out = Vec::with_capacity(params.len());
for (i, (style, p)) in request.styles.iter().zip(&params).enumerate() {
let go_on = |_: u64, _: u64| steps(i as u64, total);
let res = tr::trace_watched(&image.raster, p, left, &go_on).map_err(trace_error)?;
left = left.saturating_sub(res.anchor_count());
out.push(image.variation(style, p, res));
}
if !steps(total, total) {
return Err(ProviderError::Canceled);
}
Ok(with_seams(out))
}
/// The image decoded in the first part; then for each style, its color layers found in one
/// part and each layer traced in a part of its own ([`tr::TraceSteps`]), or all of them in
/// one part where the style stacks them (Overlapping with Fills).
fn parts(&self, request: &Request) -> Option<Box<dyn Parts>> {
Some(Box::new(TraceParts { request: request.clone(), image: None, trace: None, left: MAX_ANCHORS, out: vec![], ended: false }))
}
}
/// The trace settings of each of `request`'s styles; an error for a prompt, an output other than
/// vector art, or a style that isn't one of [`STYLES`]. The host refuses these first; a direct
/// caller gets the same answer.
fn checked(request: &Request) -> Result<Vec<tr::TraceParams>, ProviderError> {
let pid = ID;
if request.prompt.is_some() || request.output != Output::Vector {
return Err(ProviderError::Unsupported(format!("`{pid}` takes no prompt and makes vector art only")));
}
request
.styles
.iter()
.map(|s| style_params(s, request.detail))
.collect::<Option<_>>()
.ok_or_else(|| ProviderError::InvalidInput(format!("`styles` must list 1 to 8 different style ids of `{pid}` (see conceptVector.providers)")))
}
fn trace_error(e: tr::TraceError) -> ProviderError {
match e {
tr::TraceError::Cancelled => ProviderError::Canceled,
tr::TraceError::TooComplex { .. } => ProviderError::ResourceLimit(MAX_ANCHORS),
e => ProviderError::InvalidInput(e.to_string()),
}
}
/// A request's image decoded for tracing, with what maps its traced paths back.
struct Decoded {
raster: Arc<tr::Raster>,
/// The decoded raster's pixels → the image's own pixel space.
back: Affine,
unit: f64,
warnings: Vec<String>,
}
impl Decoded {
/// `request`'s image decoded, scaled down to at most [`MAX_PIXELS`].
fn new(request: &Request) -> Result<Self, ProviderError> {
let raster = fit(tr::Raster::decode_to_fit(&request.image).map_err(|e| ProviderError::InvalidInput(e.to_string()))?);
let mut warnings = vec![];
let (iw, ih) = (request.width.max(1), request.height.max(1));
if u64::from(raster.width) * u64::from(raster.height) < u64::from(iw) * u64::from(ih) {
warnings.push(format!("The image was traced at {} × {} pixels, scaled down from {iw} × {ih}.", raster.width, raster.height));
}
let back = Affine::scale_non_uniform(f64::from(iw) / f64::from(raster.width.max(1)), f64::from(ih) / f64::from(raster.height.max(1)));
let unit = back.determinant().abs().sqrt();
Ok(Self { raster: Arc::new(raster), back, unit, warnings })
}
/// The variation of `style` that the trace `res` of this image, made with `params`, makes, and
/// the seam fills of an Abutting trace with fills ([`tr::seam_fills`]) trimmed inside the
/// image ([`within_image`]) and outlined in raster pixels before mapping them back, for
/// [`with_seams`] to lay under its paths.
fn variation(&self, style: &str, params: &tr::TraceParams, res: tr::TraceResult) -> Made {
let size = (self.raster.width, self.raster.height);
let seams = tr::seam_fills(&res.paths, params, size).map_or_else(Vec::new, |s| {
s.strokes
.into_iter()
.map(|tp| {
let mut tp = within_image(tp, size);
if let Some(width) = tp.stroke.take() {
tp.path = vectorcraft_pathops::outline_stroke(
&tp.path,
width,
vectorcraft_pathops::Cap::Butt,
vectorcraft_pathops::Join::Round,
4.0,
);
}
tp
})
.filter(|tp| !tp.path.subpaths.is_empty())
.map(|tp| self.vector_path(tp))
.collect()
});
let paths = res.paths.into_iter().map(|tp| self.vector_path(tp)).collect();
Made { variation: Variation { style: style.to_string(), paths, warnings: self.warnings.clone() }, seams }
}
/// Traced path `tp` in the image's own pixels.
fn vector_path(&self, tp: tr::TracedPath) -> VectorPath {
let path = tp.path.transformed(self.back);
match tp.stroke {
Some(w) => VectorPath { path, fill: None, stroke: Some((tp.color, w * self.unit)), square_caps: tp.square_caps },
None => VectorPath { path, fill: Some(tp.color), stroke: None, square_caps: false },
}
}
}
/// A variation made, and the outlined seam fills to lay under its paths.
pub(super) struct Made {
pub(super) variation: Variation,
pub(super) seams: Vec<VectorPath>,
}
/// [`with_seams_within`] [`MAX_ANCHORS`] and [`MAX_PATHS`].
fn with_seams(made: Vec<Made>) -> Vec<Variation> {
with_seams_within(made, MAX_ANCHORS, MAX_PATHS)
}
/// The variations `made`, each with its seam fills under its paths, in order, while they fit in
/// the `max_anchors` anchors and `max_paths` paths (each subpath counted as one) left once every
/// variation is counted: the traced paths of every style come first, and a style whose seam fills
/// do not fit goes without them.
pub(super) fn with_seams_within(made: Vec<Made>, max_anchors: usize, max_paths: usize) -> Vec<Variation> {
let subpaths = |paths: &[VectorPath]| paths.iter().map(|p| p.path.subpaths.len().max(1)).sum::<usize>();
let mut anchors = made.iter().map(|m| m.variation.anchors()).sum::<usize>();
let mut paths = made.iter().map(|m| subpaths(&m.variation.paths)).sum::<usize>();
made.into_iter()
.map(|Made { mut variation, seams }| {
let (more_anchors, more_paths) = (seams.iter().map(|p| p.path.anchor_count()).sum::<usize>(), subpaths(&seams));
if !seams.is_empty() && anchors.saturating_add(more_anchors) <= max_anchors && paths.saturating_add(more_paths) <= max_paths {
anchors += more_anchors;
paths += more_paths;
variation.paths.splice(0..0, seams);
}
variation
})
.collect()
}
/// Seam stroke `tp` of a `size` raster trimmed to half its width inside the raster's border,
/// so that its outline with butt caps and round joins stays inside the image. The pieces left form
/// open runs; a closed subpath left whole stays closed.
fn within_image(mut tp: tr::TracedPath, size: (u32, u32)) -> tr::TracedPath {
let half = tp.stroke.unwrap_or_default() / 2.0;
let (w, h) = (f64::from(size.0), f64::from(size.1));
let mut runs: Vec<SubPath> = vec![];
if !half.is_finite() || half < 0.0 || half * 2.0 > w || half * 2.0 > h {
tp.path = PathData::new(runs);
return tp;
}
let inside = |p: Point| p.x >= half && p.y >= half && p.x <= w - half && p.y <= h - half;
let clamp = |p: Point| Point::new(p.x.clamp(half, w - half), p.y.clamp(half, h - half));
for sp in &tp.path.subpaths {
let count = sp.segment_count();
let mut pieces = vec![];
for k in 0..count {
let c = sp.segment(k);
let mut cuts = vec![0.0, 1.0];
if ![c.p0, c.p1, c.p2, c.p3].into_iter().all(inside) {
for (p0, p1, p2, p3, side) in [
(c.p0.x, c.p1.x, c.p2.x, c.p3.x, half),
(c.p0.x, c.p1.x, c.p2.x, c.p3.x, w - half),
(c.p0.y, c.p1.y, c.p2.y, c.p3.y, half),
(c.p0.y, c.p1.y, c.p2.y, c.p3.y, h - half),
] {
// Intersections with the sides' supporting lines also cover corner crossings.
cuts.extend(
solve_cubic(p0 - side, 3.0 * (p1 - p0), 3.0 * (p0 - 2.0 * p1 + p2), p3 - p0 + 3.0 * (p1 - p2))
.into_iter()
.filter(|&t| t > 0.0 && t < 1.0),
);
}
cuts.sort_by(f64::total_cmp);
cuts.dedup();
}
for pair in cuts.windows(2) {
let (t0, t1) = (pair[0], pair[1]);
pieces.push((k, t0, t1, inside(c.eval(t0 + (t1 - t0) / 2.0))));
}
}
if pieces.iter().all(|&(_, _, _, kept)| kept) {
if count > 0 {
runs.push(sp.clone());
}
continue;
}
// Start after a piece left out, so that a run across a closed subpath's first anchor
// stays one run.
let start = if sp.closed { pieces.iter().position(|&(_, _, _, kept)| !kept).map_or(0, |k| k + 1) } else { 0 };
let mut run: Vec<Anchor> = vec![];
for j in 0..pieces.len() {
let (k, t0, t1, kept) = pieces[(start + j) % pieces.len()];
if kept {
let (Some(&a), Some(&b)) = (sp.anchors.get(k), sp.anchors.get((k + 1) % sp.anchors.len())) else { continue };
let c = sp.segment(k);
let mut c = if t0 == 0.0 && t1 == 1.0 { c } else { c.subsegment(t0..t1) };
// Remove roundoff at the cut endpoints without constraining the curve's handles.
c.p0 = clamp(c.p0);
c.p3 = clamp(c.p3);
if sp.segment_is_line(k) {
c = CubicBez::new(c.p0, c.p0, c.p3, c.p3);
}
if let Some(last) = run.last_mut() {
last.h_out = c.p1;
} else {
let a = if t0 == 0.0 { a } else { Anchor::corner(c.p0) };
run.push(Anchor { p: c.p0, h_in: c.p0, h_out: c.p1, ..a });
}
let b = if t1 == 1.0 { b } else { Anchor::corner(c.p3) };
run.push(Anchor { p: c.p3, h_in: c.p2, h_out: c.p3, ..b });
} else if !run.is_empty() {
runs.push(open_run(std::mem::take(&mut run)));
}
}
if !run.is_empty() {
runs.push(open_run(run));
}
}
tp.path = PathData::new(runs);
tp
}
/// An open run of anchors: the last one has no handle out.
fn open_run(mut run: Vec<Anchor>) -> SubPath {
if let Some(last) = run.last_mut() {
last.h_out = last.p;
}
SubPath::new(run, false)
}
/// [`TraceStyles`]' variations made a part at a time.
struct TraceParts {
request: Request,
image: Option<Decoded>,
/// The trace of the style after those in `out`, once started.
trace: Option<tr::TraceSteps>,
/// The anchor points the styles not made yet may have.
left: usize,
out: Vec<Made>,
/// The variations or an error have been given.
ended: bool,
}
impl Parts for TraceParts {
/// After the variations or an error, each call gives `None`.
fn step(&mut self) -> Result<Option<Vec<Variation>>, ProviderError> {
if self.ended {
return Ok(None);
}
let part = self.next_part();
self.ended = !matches!(part, Ok(None));
part
}
fn styles_done(&self) -> usize {
self.out.len()
}
}
impl TraceParts {
fn next_part(&mut self) -> Result<Option<Vec<Variation>>, ProviderError> {
let Some(image) = &self.image else {
checked(&self.request)?;
self.image = Some(Decoded::new(&self.request)?);
return Ok(None);
};
let Some(style) = self.request.styles.get(self.out.len()) else { return Ok(Some(with_seams(std::mem::take(&mut self.out)))) };
let trace = match &mut self.trace {
Some(t) => t,
None => {
let params = style_params(style, self.request.detail).ok_or(ProviderError::InvalidResult)?;
self.trace.insert(tr::TraceSteps::new(Arc::clone(&image.raster), params, self.left))
}
};
let Some(res) = trace.step().map_err(trace_error)? else { return Ok(None) };
self.trace = None;
let params = style_params(style, self.request.detail).ok_or(ProviderError::InvalidResult)?;
self.left = self.left.saturating_sub(res.anchor_count());
self.out.push(image.variation(style, &params, res));
if self.out.len() < self.request.styles.len() {
return Ok(None);
}
Ok(Some(with_seams(std::mem::take(&mut self.out))))
}
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -118,7 +118,7 @@ pub struct DocState {
/// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not
/// change it, and a batch that fails puts it back with the document.
pub reverts: u64,
/// Advances when Undo or Redo restores an older document snapshot. The same node ID can name different objects
/// Advances when Undo, Redo or a canceled undo group restores an older document snapshot. The same node ID can name different objects
/// across that boundary.
pub history_restores: u64,
/// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared,
+8
View File
@@ -19,6 +19,10 @@ pub struct Interaction {
/// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an
/// interaction runs its commands inside it.
pub(crate) tool: bool,
/// A dialog's live preview began it: a command from outside the dialog runs as a step of its
/// own under it, as it does under a drag, so the next preview, OK and Cancel keep its edit
/// (a `file.*` command still runs inside it).
pub dialog: bool,
/// A tool began or joined this interaction through `Action::Begin`.
pub(crate) tool_joined: bool,
/// A replaced or canceled preview restores these new-art paints from before the interaction.
@@ -100,6 +104,10 @@ pub(crate) struct HeldInteraction {
/// The new-art paints when the command began: a change the command makes to them stays when
/// the interaction's next preview or a cancel puts back the paints it began with.
pub(crate) paint: vectorcraft_tools::PaintDefaults,
/// The command's own selection steps went into the journal before it ran.
pub(crate) journaled: bool,
/// The command returned an error.
pub(crate) refused: bool,
}
/// The per-document state an interaction puts back when it is canceled, besides the document and
+11
View File
@@ -8,6 +8,7 @@
#![doc(test(attr(forbid(unsafe_code))))]
pub mod cmd;
pub mod concept_vector;
pub mod file_access;
pub mod guard;
pub mod inspect;
@@ -58,6 +59,12 @@ pub use vectorcraft_tools as tools;
pub use vectorcraft_doc::MAX_COORD;
const _: () = assert!(vectorcraft_doc::MAX_DEPTH == 32, "TOO_DEEP (and its catalog rows) names the cap");
pub struct ArtboardDeletionGuard {
pub document: (u64, u64),
pub artboard: u32,
pub message: String,
}
/// The maximum number of newest swatch renames a session keeps until they are taken.
pub(crate) const MAX_SWATCH_RENAMES: usize = 64;
@@ -67,6 +74,7 @@ pub struct Session {
pub prefs: Prefs,
/// Whether Caps Lock is on, as the desktop host reports it; never saved with the preferences.
pub caps_lock: bool,
pub artboard_deletion_guard: Option<ArtboardDeletionGuard>,
/// Fill/stroke for new art (the toolbar proxy).
pub paint: PaintDefaults,
/// Which proxy is in front (true = Fill, false = Stroke) — the X key toggles.
@@ -352,6 +360,9 @@ pub struct Session {
/// What a [`cmd::TraceRun`] traced, until the next `imageTrace.make` or
/// `imageTrace.makeAndExpand` takes it ([`cmd::Traced::hand_in`]).
pub(crate) trace_hand_off: Option<cmd::Traced>,
/// The Concept to Vector providers and the jobs made with them ([`cmd::conceptvector`]); not
/// saved.
pub(crate) concept: cmd::conceptvector::ConceptState,
/// The installed fonts a [`cmd::RetypeSearch`] found, until the next `type.retype` or
/// `type.retypeFonts` takes it ([`cmd::RetypeFound::hand_in`]).
pub(crate) retype_hand_off: Option<cmd::RetypeFound>,
+14 -2
View File
@@ -98,6 +98,10 @@ pub struct ScriptDialog {
/// `showColorPicker`: the run's active document is in CMYK when the picker opens, so the app
/// gives an RGB pick back as CMYK. False for the other dialogs.
pub cmyk_document: bool,
/// `showColorPicker`: the RGB and CMYK profiles the run's active document is assigned (`None`:
/// none) when the picker opens, which the app converts the pick through. `(None, None)` for the
/// other dialogs.
pub profiles: (Option<String>, Option<String>),
}
/// The answer to a [`ScriptDialog`].
@@ -705,7 +709,10 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
if preset.len() > MAX_PROMPT_BYTES {
return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB")));
}
wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false })
wait_or_answer(
host,
ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false, profiles: (None, None) },
)
}
/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK,
@@ -713,7 +720,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
pub(super) fn show_color_picker(host: &Host, color: Color) -> Result<Data, HostError> {
// During a slice the session holds the run's working copy, whose active document may be one
// the script made; between slices the app sees the documents as they were before the run.
let cmyk_document = host.session.borrow().active().is_some_and(|s| s.doc.color_mode == crate::doc::ColorMode::Cmyk);
let (cmyk_document, profiles) = host
.session
.borrow()
.active()
.map_or((false, (None, None)), |s| (s.doc.color_mode == crate::doc::ColorMode::Cmyk, crate::cmd::colormgmt::doc_profiles(&s.doc)));
let dialog = ScriptDialog {
kind: DialogKind::ColorPicker,
message: String::new(),
@@ -723,6 +734,7 @@ pub(super) fn show_color_picker(host: &Host, color: Color) -> Result<Data, HostE
preset: String::new(),
color: Some(color),
cmyk_document,
profiles,
};
wait_or_answer(host, dialog)
}
+1 -1
View File
@@ -123,7 +123,7 @@ pub(super) use colors::of_color as color_data;
#[cfg(test)]
pub(crate) use paths::index_builds;
#[cfg(test)]
pub(crate) use paths::{PATH_LIST_BUILDS, POINT_LOOKS};
pub(crate) use paths::{PATH_LIST_BUILDS, POINT_LOOKS, REMOVE_ALL_VISITS};
pub(super) use resources::{Kind as ResourceKind, gone as resources_gone, held as holds_resources};
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
+108 -7
View File
@@ -707,13 +707,19 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
}
}
#[cfg(test)]
thread_local! {
/// How many objects [`items_remove_all`] walked on this thread, for the tests.
pub(crate) static REMOVE_ALL_VISITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or
/// locked path, one in a hidden or locked layer or group, or one on a locked artboard stops it
/// before anything is deleted, as `PageItems.removeAll()` does. A compound path's
/// `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its last path does.
/// It also throws and deletes nothing when it would delete the clipping path of a group or layer
/// that keeps other objects, or leave a compound path or group that clips one with no visible path
/// or visible type that lays out glyphs to clip by.
/// that keeps other objects, or leave a compound path or group that clips one with no visible path,
/// image, placed document or visible type that lays out glyphs to clip by.
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
let (doc, c) = items_scope(h, a)?;
let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| {
@@ -727,9 +733,42 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
let refused: Vec<u64> = ids.iter().filter(|i| !editable(d, **i)).map(|i| i.0).take(20).collect();
let locks = d.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
let mut next: Vec<_> = d.layers.iter().collect();
// The document's list is checked against every object. A layer's or group's list is checked
// against the container's subtree, or, when the container lies in the clipping path of a
// clipping group above it, against the subtree of the highest such clipping path and the
// group it clips; no other outline holds its paths. An empty list is not walked.
let mut next: Vec<&Arc<crate::doc::Node>> = Vec::new();
let mut nodes = Vec::new();
if !ids.is_empty() {
match c.and_then(|c| d.index_path(c)) {
None => next.extend(d.layers.iter()),
Some(at) => {
// A damaged file can give two objects one id; a path that the id finds outside
// the container would be deleted in place of the container's own.
if let Some(id) = ids.iter().find(|i| d.index_path(**i).is_none_or(|p| p.len() != at.len() + 1 || !p.starts_with(&at))) {
return Err(HostError::Error(format!("cannot delete PathItem {}: its id also names another object", id.0)));
}
let mut line: Vec<&Arc<crate::doc::Node>> = Vec::with_capacity(at.len());
let mut kids = d.layers.as_slice();
for &i in &at {
let Some(n) = kids.get(i) else { break };
line.push(n);
kids = n.children().map_or(&[][..], Vec::as_slice);
}
// A clipping path is its group's first child, found by place, not by id.
let clip = (1..line.len()).find(|&k| line[k - 1].clips() && at[k] == 0);
if let Some(k) = clip {
#[cfg(test)]
REMOVE_ALL_VISITS.with(|v| v.set(v.get() + 1));
nodes.push(line[k - 1]);
}
next.extend(line.get(clip.unwrap_or(line.len().saturating_sub(1))).copied());
}
}
}
while let Some(n) = next.pop() {
#[cfg(test)]
REMOVE_ALL_VISITS.with(|v| v.set(v.get() + 1));
nodes.push(n);
next.extend(n.children().into_iter().flatten());
}
@@ -768,12 +807,15 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
{
going.insert(n.id);
}
// A clip outline takes in visible paths and the glyphs of visible type, as
// `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no
// outline. A list marker is a glyph too, so whitespace-only type is laid out as well.
// A clip outline takes in visible paths, the frames of visible images and placed
// documents that enclose an area, and the glyphs of visible type, as `push_clip_shapes` does; type that lays
// out no glyphs (blank, or overset) gives no outline. A list marker is a glyph too, so
// whitespace-only type is laid out as well.
let shape = n.visible
&& match &n.kind {
NodeKind::Path { .. } => true,
// A frame collapsed to a line or a point encloses nothing to clip by.
NodeKind::Image(_) | NodeKind::PlacedDocument(_) => n.clip_shapes(None).iter().any(|(frame, _)| encloses(frame)),
NodeKind::Text(t) => {
in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty()
}
@@ -785,10 +827,18 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
if n.visible && ((shape && !going.contains(&n.id)) || inner) {
geometry.insert(n.id);
}
// The live geometry effects of what stays in the clipping path reshape the region it
// clips by, as the renderer draws it; deleting paths that lets an effect shrink the
// region to nothing leaves no outline. A region that was empty before is left as it is.
// The region is the area the outline fills under its fill rule, so outlines that run
// opposite ways over the same area under nonzero fill nothing.
let reshaped_empty = |m: &vectorcraft_doc::Node| {
vectorcraft_render::effects::reshaped_clip_outline(m).is_some_and(|o| !o.is_some_and(|(bp, rule)| fills(&bp, rule)))
};
if n.clips()
&& let Some(mask) = kids.first()
&& affected.contains(&mask.id)
&& !geometry.contains(&mask.id)
&& (!geometry.contains(&mask.id) || (reshaped_empty(&without(mask, &going, &affected)) && !reshaped_empty(mask)))
&& kids.iter().skip(1).any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
&& masks.len() < 20
{
@@ -819,6 +869,57 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// Whether a subpath of `outline` encloses an area. Each subpath's area is measured from its first
/// point, so its position does not change the result, and an area within roundoff of its own
/// bounding box's is counted as none.
fn encloses(outline: &kurbo::BezPath) -> bool {
let mut subpaths: Vec<kurbo::BezPath> = Vec::new();
for el in outline.elements() {
if matches!(el, kurbo::PathEl::MoveTo(_)) || subpaths.is_empty() {
subpaths.push(kurbo::BezPath::new());
}
if let Some(last) = subpaths.last_mut() {
last.push(*el);
}
}
subpaths.into_iter().any(|mut sub| {
let Some(start) = sub.elements().iter().find_map(|e| e.end_point()) else { return false };
sub.apply_affine(kurbo::Affine::translate(-start.to_vec2()));
let area = kurbo::Shape::area(&sub).abs();
area > 0.0 && area > 64.0 * f64::EPSILON * kurbo::Shape::bounding_box(&sub).area()
})
}
/// Whether `outline` fills an area under `rule`: a subpath encloses an area ([`encloses`]) and the
/// outline with its overlaps resolved, thin strips included, has an area. An outline the path
/// operations refuse is judged by [`encloses`] alone.
fn fills(outline: &kurbo::BezPath, rule: vectorcraft_geom::FillRule) -> bool {
if !encloses(outline) {
return false;
}
match vectorcraft_pathops::try_area(&vectorcraft_geom::PathData::from_bezpath(outline), rule) {
Ok(area) => area > 0.0,
Err(_) => true,
}
}
/// `n` without the members in `going`, at every depth. Only the members in `affected` (those that
/// hold a member in `going`) are copied; the others are shared.
fn without(
n: &vectorcraft_doc::Node,
going: &std::collections::HashSet<NodeId>,
affected: &std::collections::HashSet<NodeId>,
) -> vectorcraft_doc::Node {
let mut m = n.clone();
if let Some(kids) = m.children_mut() {
kids.retain(|k| !going.contains(&k.id));
for k in kids.iter_mut().filter(|k| affected.contains(&k.id)) {
*k = Arc::new(without(k, going, affected));
}
}
m
}
/// The id in the JSON result of a command that made an object, read exactly, as the text creators
/// read it.
fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
@@ -281,6 +281,7 @@ fn set_warning(h: &Host, on: bool) -> Answer {
preset: String::new(),
color: None,
cmyk_document: false,
profiles: (None, None),
};
if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) {
return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into()));
+12
View File
@@ -501,6 +501,9 @@ struct World {
pending_paint: Option<crate::Paint>,
choices: Choices,
journal: Journal,
/// The Concept to Vector jobs, and the number of the first job made after the run started.
concept_jobs: std::collections::VecDeque<cmd::conceptvector::Job>,
concept_from: u64,
/// The preferences when the run started.
start_prefs: crate::Prefs,
/// The Caps Lock state when the run started.
@@ -631,6 +634,8 @@ impl World {
pending_paint: s.pending_paint.clone(),
choices: Choices::of(s),
journal: Journal::default(),
concept_jobs: s.concept_jobs_snapshot(),
concept_from: s.next_concept_job(),
start_prefs: s.prefs.clone(),
start_caps_lock: s.caps_lock,
}
@@ -655,6 +660,7 @@ impl World {
swap(&mut self.pending_paint, &mut s.pending_paint);
self.choices.swap(s);
swap(&mut self.journal, &mut s.journal);
s.swap_concept_jobs(&mut self.concept_jobs);
}
}
@@ -696,6 +702,7 @@ pub(crate) struct Savepoint {
pending_paint: Option<crate::Paint>,
choices: Choices,
journal: usize,
concept_jobs: std::collections::VecDeque<cmd::conceptvector::Job>,
/// The plug-in events queued before the command ([`Session::plugin_events_mark`]).
plugin_events: u64,
}
@@ -732,6 +739,7 @@ impl Savepoint {
pending_paint: s.pending_paint.clone(),
choices: Choices::of(s),
journal: s.journal.len(),
concept_jobs: s.concept_jobs_snapshot(),
plugin_events: s.plugin_events_mark(),
}
}
@@ -787,6 +795,7 @@ impl Savepoint {
s.pending_paint = self.pending_paint;
self.choices.put(s);
s.journal.truncate(self.journal);
s.restore_concept_jobs(self.concept_jobs);
// The documents the command opened are closed again: plug-ins are not told of them.
s.forget_plugin_opens_since(self.plugin_events);
s.sync_front_profiles();
@@ -2842,6 +2851,9 @@ impl Session {
for st in start.iter().filter(|b| !job.start_uids.contains(&b.uid)) {
self.docs.push(st.clone());
}
// So do the Concept to Vector jobs the app made while the run went on.
let others = std::mem::take(&mut job.world.concept_jobs);
self.merge_concept_jobs(others, job.world.concept_from);
// A document the script closed is gone now, with its recovery copy.
for b in start.iter().filter(|b| job.start_uids.contains(&b.uid) && !self.docs.iter().any(|d| d.uid == b.uid)) {
cmd::recovery::forget_closed(self, b);
+6
View File
@@ -51,6 +51,7 @@ impl Session {
active: None,
prefs: Prefs::default(),
caps_lock: false,
artboard_deletion_guard: None,
paint: PaintDefaults::default(),
fill_active: true,
clipboard: Clipboard::default(),
@@ -149,6 +150,7 @@ impl Session {
place_queue_loads: 0,
image_hand_off: None,
trace_hand_off: None,
concept: Default::default(),
retype_hand_off: None,
place_cursor_requests: false,
package_hand_off: None,
@@ -567,6 +569,10 @@ impl Session {
// Closed (saved or discarded): nothing left to recover.
let uid = self.docs[index].uid;
cmd::recovery::forget(self, uid);
// In a batch, the jobs are dropped when the batch ends without an error.
if self.batch_stash.is_none() {
self.forget_concept_jobs(uid);
}
let old = self.docs.remove(index);
if let Some(stash) = &mut self.batch_stash {
stash.push(old);
+106 -16
View File
@@ -343,19 +343,26 @@ impl Session {
/// it updates Recent Colors and converts or remaps the new-art paints at once, as it does with
/// no drag in progress.
///
/// The interaction stays as it is, and the command runs inside it, for an interaction a dialog
/// or a panel began (it builds its preview from commands), for typing in progress
/// A dialog's live preview ([`crate::Interaction::dialog`]) is set aside the same way, except
/// for a command that acts on the drawing on show ([`reads_preview`]). Outside commands use
/// the shown selection with objects absent from the base document removed, and without a path
/// whose selected anchors the preview renumbered. A selection of only preview objects becomes
/// empty. The journal records that selection before the command, and records the dialog's
/// own selection again when the command is refused. The interaction stays as it is, and the command runs
/// inside it, for an interaction a panel or
/// another dialog began (it builds its preview from commands), for typing in progress
/// ([`Session::edit`] keeps it as a step of its own), for the Quick Pen (an edit made outside
/// it ends the path it draws), and for a copy made with `object.transform` during a drag that
/// copies (it copies the document as the drag's move left it). A command that settles,
/// commits or cancels the interaction, or that hands the active tool actions to apply, gets it
/// back first ([`Session::put_back_interaction`]), as it found it.
pub(crate) fn outside_interaction(&mut self, id: &str, params: &Value, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
if cmd::typing_in_progress(self) || self.tool_id() == vectorcraft_tools::quickpen::ID {
let dialog = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.dialog);
if cmd::typing_in_progress(self) || (!dialog && self.tool_id() == vectorcraft_tools::quickpen::ID) {
return f(self);
}
let Some(st) = self.active_mut() else { return f(self) };
let Some(it) = st.interaction.as_ref().filter(|it| it.tool) else { return f(self) };
let Some(it) = st.interaction.as_ref().filter(|it| it.tool || (it.dialog && !reads_preview(id))) else { return f(self) };
// A drag that copies: its latest preview, applied or held back by Real-time Drawing off, copies.
let copying = it.preview.as_ref().is_some_and(|(c, p)| c == "object.transform" && p.get("copy").and_then(Value::as_bool) == Some(true));
if copying && id == "object.transform" && params.get("copy").and_then(Value::as_bool) == Some(true) {
@@ -367,36 +374,57 @@ impl Session {
let shown = previewed.then(|| (st.doc.clone(), st.selection.clone()));
if previewed {
st.doc = interaction.doc.clone();
st.selection.clone_from(&interaction.selection);
if let Some((shown_doc, _)) = shown.as_ref().filter(|_| interaction.dialog) {
shown_base_selection(&mut st.selection, shown_doc, &st.doc);
} else {
st.selection.clone_from(&interaction.selection);
}
st.revision += 1;
cmd::globaledit::follow_history(st);
}
// The journal holds the dialog's base selection, so the command replays on the one it acts on.
let reselect = (interaction.dialog && st.selection != *interaction.selection)
.then(|| selection_steps(&st.selection, &interaction.selection, &st.doc, st.active_layer, &st.highlighted_rows()));
let (uid, state) = (st.uid, crate::interaction::ViewState::of(st));
let paint = self.paint.clone();
self.held_interaction = Some(crate::HeldInteraction { uid, interaction, shown, state, paint });
let journaled = reselect.is_some();
if let Some(steps) = reselect {
let (from, grouped) = (self.journal.len(), self.undo_group_docs());
for step in steps {
self.journal.push(step);
}
self.journal_in_undo_groups(Some(uid), &grouped, from);
}
self.held_interaction = Some(crate::HeldInteraction { uid, interaction, shown, state, paint, journaled, refused: false });
if previewed {
self.sync_front_profiles();
}
let r = f(self);
if let Some(held) = self.held_interaction.as_mut().filter(|_| r.is_err()) {
held.refused = true;
}
self.put_back_interaction();
r
}
/// Put back the interaction [`Session::outside_interaction`] set aside. When the command left
/// the document and the selection as it found them, the preview on show before it is on show
/// again. Otherwise the interaction starts from the document the command left and from its
/// own selection, without the objects the command removed, hid or locked, and the preview that Real-time
/// Drawing showed is applied to it again. The warning or the error of that preview goes to
/// again. Otherwise a tool drag starts from the document the command left and from its own
/// selection, without the objects the command removed, hid or locked. The preview that
/// Real-time Drawing showed is applied to it again. The warning or the error of that preview goes to
/// the command's result ([`Session::note_settled_warning`]); a preview that fails leaves the
/// interaction with nothing to commit. An interaction whose document the command closed ends,
/// and so does one with anchors or segments selected on a path the command changed in more
/// than a move. A document
/// the command left an interaction of its own on keeps that one.
/// than a move. A document the command left an interaction of its own on keeps that one.
/// A dialog adopts the command's selection and paints and reruns its preview on its next pass.
pub(crate) fn put_back_interaction(&mut self) {
let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint }) = self.held_interaction.take() else { return };
let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint, journaled, refused }) = self.held_interaction.take() else {
return;
};
// A selection command loaded the paints of the selection it made into the fill and stroke
// proxies. The drag goes on with its own selection, so they show its paints again.
if self.paint != paint
if !it.dialog
&& self.paint != paint
&& let Some(st) = self.active_mut().filter(|d| d.uid == uid && d.interaction.is_none())
{
let own = drag_selection(&it.selection, &st.doc);
@@ -450,7 +478,19 @@ impl Session {
// isolation stays when the interaction is canceled.
state.rebase(crate::interaction::ViewState::of(st), &mut it);
let previewed = shown.is_some();
if Arc::ptr_eq(&st.doc, &it.doc) && st.selection == *it.selection {
// A refused command leaves the selection it was given: a dialog's is the one on show without
// preview objects. A command that ran (Deselect) and left that selection keeps it.
let given = match shown.as_ref().filter(|_| it.dialog && refused) {
Some((shown_doc, selection)) => {
let mut given = selection.clone();
shown_base_selection(&mut given, shown_doc, &it.doc);
given
}
None => (*it.selection).clone(),
};
if Arc::ptr_eq(&st.doc, &it.doc) && st.selection == given {
// The journal goes back to the dialog's base selection, as the preview on show again holds it.
let back = (journaled && active).then(|| selection_steps(&it.selection, &given, &st.doc, st.active_layer, &st.highlighted_rows()));
if let Some((doc, selection)) = shown {
st.doc = doc;
st.selection = selection;
@@ -458,6 +498,13 @@ impl Session {
cmd::globaledit::follow_history(st);
}
st.interaction = Some(it);
if let Some(steps) = back {
let (from, grouped) = (self.journal.len(), self.undo_group_docs());
for step in steps {
self.journal.push(step);
}
self.journal_in_undo_groups(Some(uid), &grouped, from);
}
if previewed {
self.sync_front_profiles();
}
@@ -472,8 +519,17 @@ impl Session {
}
let began = std::mem::replace(&mut it.doc, st.doc.clone());
// The drag acts on the objects it began with: a selection the command made (a paste, a
// duplicate, Select All) does not change what the drag moves.
it.selection = Arc::new(drag_selection(&it.selection, &st.doc));
// duplicate, Select All) does not change what the drag moves. A dialog's preview acts on
// the selection the command left, and its dialog previews again on its next pass, from the
// values it shows then, so nothing is applied here.
if it.dialog {
if st.selection != *it.selection {
it.selection = Arc::new(st.selection.clone());
}
it.preview = None;
} else {
it.selection = Arc::new(drag_selection(&it.selection, &st.doc));
}
// The journal holds the selection the command left. The drag's own selection is journaled
// after it, so the drag and the commands after it replay on the objects they act on.
let reselect = (active && st.selection != *it.selection)
@@ -569,6 +625,7 @@ impl Session {
revision: st.revision,
preview: None,
tool: false,
dialog: false,
tool_joined: false,
paint,
used_defaults_only: false,
@@ -944,6 +1001,39 @@ fn take_changed_paints(
}
}
/// Whether command `id` acts on the drawing as a dialog's preview shows it (a copy, a save, a
/// revert), so it runs inside that preview rather than as a step of its own.
fn reads_preview(id: &str) -> bool {
id == "edit.copy" || (id.starts_with("file.") && id != "file.documentColorMode")
}
/// The selection on show in a dialog's preview `shown`, as a command from outside the dialog acts
/// on it in the base document `base`: without the objects the preview made, and without a path
/// whose selected anchors or segments are numbered in a shape the preview changed in more than a
/// move (Set Corners recut it), since those numbers can name other points in `base`.
fn shown_base_selection(selection: &mut Selection, shown: &Document, base: &Document) {
selection.prune(base);
let recut: Vec<_> = selection
.anchors
.keys()
.chain(selection.segments.keys())
.copied()
.filter(|&id| {
let path = |d: &Document| d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.clone());
match (path(shown), path(base)) {
(Some(now), Some(was)) => !moved_whole(&was, &now),
(now, was) => now.is_some() != was.is_some(),
}
})
.collect();
for id in recut {
selection.objects.retain(|o| *o != id);
selection.anchors.remove(&id);
selection.segments.remove(&id);
}
selection.prune(base);
}
/// The selection a drag began with, without the objects that a command run during it removed,
/// hid or locked in `doc`.
fn drag_selection(began: &Selection, doc: &Document) -> Selection {
+4
View File
@@ -123,6 +123,7 @@ impl Session {
st.sync_new_art();
cmd::globaledit::follow_history(st);
st.drop_stale_variables_highlight();
st.history_restores += 1;
st.revision += 1;
// The journal drops only the canceled groups' own entries and keeps the ones made in other documents meanwhile.
journal.extend(g.journal);
@@ -280,6 +281,9 @@ impl Session {
st.drop_stale_variables_highlight();
deselect_hidden(&menu, &st.doc, &mut st.selection);
st.history.recost_last(&st.doc);
if !Arc::ptr_eq(&undone, &st.doc) {
st.history_restores += 1;
}
st.revision += 1;
if colors_changed {
self.paint = scope.paint;
+100
View File
@@ -180,6 +180,106 @@ fn reverse_path_direction_on_and_off_set_the_winding() {
assert!(s.execute("path.reverse", &json!({})).is_err(), "nothing to reverse");
}
/// Points of what is direct-selected on one path, rounded to whole points.
#[derive(Debug, PartialEq)]
struct Picked {
/// The selected anchors' points, sorted.
anchors: Vec<(i64, i64)>,
/// The end points of the selected segments, each pair and the list sorted.
segments: Vec<[(i64, i64); 2]>,
/// The key anchor's point, when the key anchor is on the path.
key: Option<(i64, i64)>,
}
/// What is direct-selected on path `id`, as points.
fn picked_points(s: &Session, id: NodeId) -> Picked {
let st = s.doc().unwrap();
let sp = &st.doc.node(id).unwrap().path_data().unwrap().subpaths;
let at = |(si, ai): (usize, usize)| {
let p = sp[si].anchors[ai].p;
(p.x.round() as i64, p.y.round() as i64)
};
let mut anchors: Vec<_> = st.selection.anchors.get(&id).into_iter().flatten().map(|r| at(*r)).collect();
anchors.sort_unstable();
let mut segments: Vec<_> = st
.selection
.segments
.get(&id)
.into_iter()
.flatten()
.map(|&(si, j)| {
let mut ends = [at((si, j)), at((si, (j + 1) % sp[si].anchors.len()))];
ends.sort_unstable();
ends
})
.collect();
segments.sort_unstable();
let key = st.selection.key_anchor.filter(|(k, _)| *k == id).map(|(_, r)| at(r));
Picked { anchors, segments, key }
}
#[test]
fn reverse_path_direction_keeps_the_same_anchors_and_segments_direct_selected() {
let mut s = session();
let path = |s: &mut Session, anchors: Value, closed: bool| {
NodeId(run(s, "path.create", json!({"anchors": anchors, "closed": closed}))["id"].as_u64().unwrap())
};
let open = path(&mut s, json!([{"x": 0, "y": 50}, {"x": 40, "y": 50}, {"x": 100, "y": 50}]), false);
let closed = path(&mut s, json!([{"x": 10, "y": 10}, {"x": 90, "y": 10}, {"x": 90, "y": 90}, {"x": 10, "y": 90}]), true);
run(&mut s, "select.anchorsMany", json!({"items": [{"id": open.0, "anchors": [[0, 0]]}, {"id": closed.0, "anchors": [[0, 1], [0, 2]]}]}));
run(&mut s, "select.key", json!({"id": closed.0, "anchor": [0, 1]}));
let before = [picked_points(&s, open), picked_points(&s, closed)];
assert_eq!(before[0].anchors, [(0, 50)]);
assert_eq!((before[1].anchors.clone(), before[1].key), (vec![(90, 10), (90, 90)], Some((90, 10))));
assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 2);
let first = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[0].p;
assert_eq!((first(&s, open).x, first(&s, closed).y), (100.0, 90.0), "both paths turned");
assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "the same points stay direct-selected after Reverse Path Direction");
// Undo turns the paths back with the selection they had.
run(&mut s, "edit.undo", json!({}));
assert_eq!(first(&s, open).x, 0.0);
assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "undo");
// Selected segments, the closing segment of a closed path included, stay the same segments.
run(&mut s, "select.segments", json!({"id": closed.0, "segments": [[0, 0], [0, 3]], "mode": "set"}));
run(&mut s, "select.segments", json!({"id": open.0, "segments": [[0, 0]], "mode": "add"}));
let before = [picked_points(&s, open), picked_points(&s, closed)];
assert_eq!(before[0].segments, [[(0, 50), (40, 50)]]);
assert_eq!(before[1].segments, [[(10, 10), (10, 90)], [(10, 10), (90, 10)]]);
assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 2);
assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "the same segments stay selected after Reverse Path Direction");
}
#[test]
fn reverse_path_direction_of_one_subpath_leaves_the_others_selection_as_it_is() {
let mut s = session();
let id = NodeId(run(&mut s, "path.create", json!({"d": "M0 0 L40 0 L100 0 M0 200 L40 200 L100 200"}))["id"].as_u64().unwrap());
run(&mut s, "select.anchorsMany", json!({"items": [{"id": id.0, "anchors": [[0, 0], [1, 0]]}]}));
run(&mut s, "select.key", json!({"id": id.0, "anchor": [0, 0]}));
let before = picked_points(&s, id);
assert_eq!((before.anchors.clone(), before.key), (vec![(0, 0), (0, 200)], Some((0, 0))));
assert_eq!(run(&mut s, "path.reverse", json!({"subpath": 1}))["changed"], 1);
let first = |s: &Session, si: usize| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[si].anchors[0].p;
assert_eq!((first(&s, 0).x, first(&s, 1).x), (0.0, 100.0), "only the second subpath turned");
assert_eq!(picked_points(&s, id), before, "the same points stay direct-selected on both subpaths");
}
#[test]
fn add_anchor_point_keeps_the_key_anchor_on_its_point() {
let mut s = session();
let anchors = json!([{"x": 10, "y": 10}, {"x": 90, "y": 10}, {"x": 90, "y": 90}, {"x": 10, "y": 90}]);
let id = NodeId(run(&mut s, "path.create", json!({"anchors": anchors, "closed": true}))["id"].as_u64().unwrap());
run(&mut s, "select.anchorsMany", json!({"items": [{"id": id.0, "anchors": [[0, 1], [0, 2]]}]}));
run(&mut s, "select.key", json!({"id": id.0, "anchor": [0, 2]}));
let before = picked_points(&s, id);
assert_eq!((before.anchors.clone(), before.key), (vec![(90, 10), (90, 90)], Some((90, 90))));
run(&mut s, "path.insertAnchor", json!({"id": id.0, "segment": 0}));
assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.len(), 5);
assert_eq!(picked_points(&s, id), before, "the key anchor and the selected anchors stay on their points after Add Anchor Point");
run(&mut s, "edit.undo", json!({}));
assert_eq!(picked_points(&s, id), before, "undo");
}
#[test]
fn reverse_path_direction_turns_the_width_profile_and_pen_records_with_the_path() {
use vectorcraft_doc::{AngleProfile, PressureProfile, WidthProfile};
+26
View File
@@ -175,6 +175,32 @@ fn an_undo_group_lets_no_other_documents_steps_go_until_it_ends() {
assert!(history_bytes(&s) <= s.history_budget);
}
/// A canceled undo group, and a canceled undo scope that joined one, put back an older snapshot:
/// both advance the document's history restores, as Undo does, and a kept one does not.
#[test]
fn canceled_undo_groups_and_scopes_count_as_history_restores() {
let mut s = session_with_rects(2);
let restores = |s: &Session| s.docs[0].history_restores;
s.begin_undo_group();
moves(&mut s, 2);
s.end_undo_group(false);
assert_eq!(restores(&s), 0, "a kept group restores nothing");
s.begin_undo_group();
moves(&mut s, 2);
s.end_undo_group(true);
assert_eq!(restores(&s), 1, "a canceled group");
s.begin_undo_group();
moves(&mut s, 1);
let scope = s.begin_undo_scope().unwrap();
moves(&mut s, 2);
s.end_undo_scope(scope, true);
assert_eq!(restores(&s), 2, "a canceled scope that joined the open group");
let scope = s.begin_undo_scope().unwrap();
s.end_undo_scope(scope, true);
assert_eq!(restores(&s), 2, "a canceled scope that made no edit puts back the same snapshot");
s.end_undo_group(false);
}
#[test]
fn steps_kept_outside_a_command_keep_to_the_shared_budget() {
let mut s = session_with_rects(50);
+28 -1
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, NodeKind};
use vectorcraft_geom::{FillRule, PathData, Rect};
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
use crate::*;
@@ -211,6 +211,33 @@ fn exclude_makes_compound() {
assert!((area_of(&s, r[0]) - 15000.0).abs() < 1.0);
}
#[test]
fn divide_over_work_budget_preserves_art_and_selection() {
let mut s = session();
let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let line = s.execute("shape.line", &json!({"x1": -10, "y1": -10, "x2": 110, "y2": 110})).unwrap();
let cutter = NodeId(line["id"].as_u64().unwrap());
// The existing pathops work-budget fixture uses 1,500 overlapping lines.
// Put them in one open path so the setup only makes two document objects.
let line = SubPath::polyline(&[Point::new(-10.0, -10.0), Point::new(110.0, 110.0)], false);
s.edit("complex cutter", |d, _| {
let NodeKind::Path { path, .. } = &mut d.node_mut(cutter).unwrap().kind else { panic!("expected a path") };
*path = PathData::new(vec![line; 1_500]);
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [square.0, cutter.0]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let selection = s.doc().unwrap().selection.clone();
let undo = s.doc().unwrap().history.undo.len();
let error = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
assert!(error.contains("too many segments or pieces"), "{error}");
let state = s.doc().unwrap();
assert!(std::sync::Arc::ptr_eq(&state.doc, &before), "the original document must be restored");
assert_eq!(state.selection, selection);
assert_eq!(state.history.undo.len(), undo);
}
#[test]
fn divide_produces_group_of_faces() {
let mut s = session();
+135
View File
@@ -519,3 +519,138 @@ fn type_on_a_path_made_with_the_type_tool_has_brackets_at_once() {
assert!(ink(&s, id).y0 > 299.0, "{tool}: below the path");
}
}
/// Press and release `tool` at `p`.
fn click(s: &mut Session, tool: &str, p: Point) {
let v = ViewInfo::default();
s.select_tool(tool, v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, p.x, p.y), v).unwrap();
}
assert!(!s.in_interaction());
}
/// Type along "M100 300 L300 300 L500 300" turned a quarter turn, so a document-space edit isn't
/// the path's own, and selected; with its path in document space.
fn turned_path_type(s: &mut Session) -> NodeId {
let id = path_type(s, "M100 300 L300 300 L500 300", [100.0, 310.0], "Reshaped type");
s.execute("object.transform", &json!({"ids": [id.0], "matrix": [0, 1, -1, 0, 600, 0]})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
id
}
fn type_path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData {
text(s, id).type_path().unwrap()
}
fn close(a: Point, b: Point) -> bool {
near(a.x, b.x) && near(a.y, b.y)
}
/// #10862: the Anchor Point tool drags handles out of an anchor of selected type on a path's path,
/// in document space through the type's transform, as one undo step, and the type reflows.
#[test]
fn anchor_point_tool_pulls_handles_out_of_type_on_a_path() {
let mut s = session();
let id = turned_path_type(&mut s);
let middle = type_path(&s, id).subpaths[0].anchors[1].p;
let (glyphs, n) = (origins(&s, id), undo_len(&s));
let to = middle + vectorcraft_geom::Vec2::new(40.0, 0.0);
drag(&mut s, "anchorPoint", middle, to, Mods::default());
let a = type_path(&s, id).subpaths[0].anchors[1];
assert!(close(a.p, middle) && close(a.h_out, to) && close(a.h_in, middle - (to - middle)), "{a:?}");
assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth);
assert_ne!(origins(&s, id), glyphs, "the type reflows along the curved path");
assert_eq!(undo_len(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(!type_path(&s, id).subpaths[0].anchors[1].has_out());
}
/// #10862: the rest of the Anchor Point tool's gestures on type on a path's path: a click makes a
/// smooth anchor a corner, a handle drag moves that handle alone, Shift at the press moves the
/// anchor, and a segment drag bends the segment.
#[test]
fn anchor_point_tool_reshapes_type_on_a_path() {
let mut s = session();
let id = turned_path_type(&mut s);
let [first, middle, last] = [0, 1, 2].map(|i| type_path(&s, id).subpaths[0].anchors[i].p);
let up = vectorcraft_geom::Vec2::new(40.0, 0.0);
drag(&mut s, "anchorPoint", middle, middle + up, Mods::default());
// A handle end, dragged, moves alone and makes the anchor a corner.
let handle = middle + vectorcraft_geom::Vec2::new(40.0, 30.0);
drag(&mut s, "anchorPoint", middle + up, handle, Mods::default());
let a = type_path(&s, id).subpaths[0].anchors[1];
assert!(close(a.h_out, handle) && close(a.h_in, middle - up) && a.kind == vectorcraft_geom::AnchorKind::Corner, "{a:?}");
// A click on the anchor takes its handles back.
click(&mut s, "anchorPoint", middle);
let a = type_path(&s, id).subpaths[0].anchors[1];
assert!(!a.has_in() && !a.has_out(), "{a:?}");
// Shift at the press moves the anchor.
let shift = Mods { shift: true, ..Mods::default() };
drag(&mut s, "anchorPoint", middle, middle + up, shift);
assert!(close(type_path(&s, id).subpaths[0].anchors[1].p, middle + up));
// A drag on the first segment bends it; its anchors stay.
let on_segment = first.midpoint(middle + up);
drag(&mut s, "anchorPoint", on_segment, on_segment + vectorcraft_geom::Vec2::new(0.0, 30.0), Mods::default());
let sp = &type_path(&s, id).subpaths[0];
assert!(close(sp.anchors[0].p, first) && close(sp.anchors[2].p, last));
assert!(sp.anchors[0].has_out() && sp.anchors[1].has_in(), "the segment curves: {sp:?}");
}
/// #10862: the Add and Delete Anchor Point tools add an anchor to type on a path's path and delete
/// one, and Pen + Alt pulls handles out of one; Delete leaves the path two anchors at least, and
/// Scissors does not cut the type.
#[test]
fn add_delete_and_pen_alt_edit_type_on_a_path() {
let mut s = session();
let id = turned_path_type(&mut s);
let [first, middle] = [0, 1].map(|i| type_path(&s, id).subpaths[0].anchors[i].p);
let quarter = first.midpoint(middle);
click(&mut s, "addAnchor", quarter);
let sp = type_path(&s, id).subpaths[0].clone();
assert_eq!(sp.anchors.len(), 4);
assert!(close(sp.anchors[1].p, quarter), "{sp:?}");
let alt = Mods { alt: true, ..Mods::default() };
let to = quarter + vectorcraft_geom::Vec2::new(0.0, 25.0);
drag(&mut s, "pen", quarter, to, alt);
let a = type_path(&s, id).subpaths[0].anchors[1];
assert!(close(a.p, quarter) && close(a.h_out, to) && a.kind == vectorcraft_geom::AnchorKind::Smooth, "{a:?}");
// The Pen's Auto Add/Delete adds an anchor on a segment and deletes it again.
let last = type_path(&s, id).subpaths[0].anchors[3].p;
let three_quarters = middle.midpoint(last);
click(&mut s, "pen", three_quarters);
assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 5);
click(&mut s, "pen", three_quarters);
assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 4);
click(&mut s, "deleteAnchor", quarter);
click(&mut s, "deleteAnchor", middle);
assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 2);
let n = undo_len(&s);
let r = s.execute("path.removeAnchor", &json!({"id": id.0, "anchor": 0}));
assert!(r.is_err(), "type on a path keeps two anchors: {r:?}");
assert_eq!((type_path(&s, id).subpaths[0].anchors.len(), undo_len(&s)), (2, n));
let end = type_path(&s, id).subpaths[0].anchors[1].p;
click(&mut s, "scissors", first.midpoint(end));
assert!(matches!(text(&s, id).kind, TextKind::OnPath { .. }));
assert_eq!(undo_len(&s), n, "Scissors leaves the type whole");
}
/// #10862: `path.insertAnchor` on type on a path, unselected or with `selectAnchor`, leaves the type
/// selected whole with no direct-selected anchors, so `path.moveAnchors` (the arrow keys) moves
/// the type instead of failing on an anchor that is not a path's.
#[test]
fn an_anchor_added_to_type_on_a_path_leaves_it_selected_whole() {
let mut s = session();
let id = turned_path_type(&mut s);
for select_anchor in [false, true] {
if !select_anchor {
s.execute("select.set", &json!({"ids": []})).unwrap();
}
s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 0, "t": 0.5, "selectAnchor": select_anchor})).unwrap();
let sel = &s.doc().unwrap().selection;
assert!(sel.contains(id) && sel.partial(id).is_none() && !sel.anchors.contains_key(&id), "selectAnchor {select_anchor}");
let before = type_path(&s, id).subpaths[0].anchors[0].p;
s.execute("path.moveAnchors", &json!({"dx": 10, "dy": 0})).unwrap();
assert!(close(type_path(&s, id).subpaths[0].anchors[0].p, before + vectorcraft_geom::Vec2::new(10.0, 0.0)));
}
}
@@ -179,6 +179,7 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() {
preset: String::new(),
color: None,
cmyk_document: false,
profiles: (None, None),
};
assert_eq!(s.script_dialog(), Some(want));
assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused");
+146
View File
@@ -4095,6 +4095,55 @@ const CAUGHT_PATHS_REMOVE_ALL: &str = "var p = app.activeDocument.pathItems, m =
try { p.removeAll(); } catch (e) { m = e.message; }\
vc.log(m); vc.log(p.length);";
/// A group's `pathItems.removeAll()` walks the group, not the document: emptying a group of two
/// paths beside 500 other paths looks at a handful of objects, and an empty group's looks at none.
#[test]
fn group_path_items_remove_all_walks_only_the_group() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
for i in 0..500 {
rect(&mut s, f64::from(i % 25) * 10.0, f64::from(i / 25) * 10.0, 5.0, 5.0);
}
s.execute("select.none", &json!({})).unwrap();
let start = crate::script::dom::REMOVE_ALL_VISITS.with(|n| n.get());
let out = log(
&mut s,
"var g = app.activeDocument.groupItems[0]; g.pathItems.removeAll(); g.pathItems.removeAll();\
vc.log(g.pathItems.length); vc.log(app.activeDocument.pathItems.length);",
);
let visits = crate::script::dom::REMOVE_ALL_VISITS.with(|n| n.get()) - start;
assert_eq!(out, vec![json!(0), json!(500)]);
assert!(visits <= 3, "{visits} objects walked to empty a group of two paths");
}
/// In a damaged document where a path outside a group has the same id as a path in it, the
/// group's `pathItems.removeAll()` throws and deletes nothing, instead of deleting the outside path.
#[test]
fn group_path_items_remove_all_refuses_an_id_found_outside_the_group() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
s.execute("object.arrange.sendToBack", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc);
d.node_mut(c).unwrap().id = a;
d.drop_lookup_cache();
// The first object in tree order with the id is the one outside the group.
assert_eq!(d.index_path(a).map(|p| p.len()), Some(2));
let n = d.layers[0].children().map_or(0, Vec::len);
let out = log(
&mut s,
"var d = app.activeDocument, m = ''; try { d.groupItems[0].pathItems.removeAll(); } catch (e) { m = e.message; }\
vc.log(m); vc.log(d.groupItems[0].pathItems.length);",
);
assert_eq!(out, vec![json!(format!("cannot delete PathItem {}: its id also names another object", a.0)), json!(2)]);
let d = &s.active().unwrap().doc;
assert_eq!(d.layers[0].children().map_or(0, Vec::len), n, "the path outside the group is kept");
}
/// The document's `pathItems.removeAll()` refuses to delete the path that clips a group while the
/// group keeps other art, and deletes nothing, as the scoped collections do.
#[test]
@@ -4420,6 +4469,103 @@ fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empt
assert_eq!(undo_steps(&s), steps);
}
/// An image's frame clips as a clipping path does, so a clipping group whose clipping path keeps
/// an image still has an outline after its paths are deleted.
#[test]
fn document_path_items_remove_all_keeps_a_clipping_group_whose_clipping_path_keeps_an_image() {
for frame in [Frame::Square, Frame::Line, Frame::Far, Frame::Inset, Frame::Mirrored, Frame::Strip] {
remove_all_beside_an_image(frame);
}
}
/// The image frame of [`remove_all_beside_an_image`].
#[derive(Clone, Copy, PartialEq)]
enum Frame {
/// 40 pt square.
Square,
/// Collapsed to a line.
Line,
/// 1/64 pt square 3,500,000 pt from the origin.
Far,
/// 40 pt square with a live Offset Path of -30 pt, which leaves nothing.
Inset,
/// 40 pt square with a live Transform effect that adds one copy reflected about its center:
/// the two outlines run opposite ways over the same area and fill nothing under nonzero.
Mirrored,
/// 40 pt square with a live Transform effect that scales it to 0.004 pt high, which still
/// clips to a thin strip.
Strip,
}
/// A clipping group whose clipping path is a group of one path and an image with `frame`, then the
/// document's `pathItems.removeAll()`.
fn remove_all_beside_an_image(frame: Frame) {
let flat = matches!(frame, Frame::Line | Frame::Inset | Frame::Mirrored);
let (mut s, a, b) = doc();
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let image = s
.edit("Place", |d, _| {
let id = d.alloc_id();
let im = vectorcraft_doc::ImageObject {
key: "pic".into(),
width: 4,
height: 4,
xf: match frame {
Frame::Square | Frame::Inset | Frame::Mirrored | Frame::Strip => kurbo::Affine::scale(10.0),
Frame::Line => kurbo::Affine::scale_non_uniform(10.0, 0.0),
Frame::Far => kurbo::Affine::translate((3_500_000.0, 3_500_000.0)) * kurbo::Affine::scale(1.0 / 256.0),
},
link: None,
placement: Default::default(),
pixels: None,
};
d.insert(Some(mask), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?;
Ok(id)
})
.unwrap();
if frame == Frame::Inset {
s.execute("effect.apply", &json!({"effect": "path.offsetPath", "params": {"offset": -30}, "ids": [image.0], "item": null})).unwrap();
}
if frame == Frame::Mirrored {
s.execute(
"effect.apply",
&json!({"effect": "distort.transform", "params": {"reflectX": true, "copies": 1, "reference": 4}, "ids": [image.0], "item": null}),
)
.unwrap();
}
if frame == Frame::Strip {
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleV": 0.01}, "ids": [image.0], "item": null})).unwrap();
}
s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap();
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("Clip", |d, _| {
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
children.sort_by_key(|c| c.id != mask);
*clip = true;
}
Ok(())
})
.unwrap();
let before = s.active().unwrap().doc.clone();
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
if flat {
assert_eq!(
out[0],
json!(format!("cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", mask.0))
);
assert_eq!(s.active().unwrap().doc, before);
return;
}
assert_eq!(out, [json!(""), json!(0)]);
let d = &s.active().unwrap().doc;
assert!(d.node(a).is_none() && d.node(b).is_none());
assert!(d.node(outer).unwrap().clips());
assert_eq!(d.parent_of(image), Some(mask));
assert!(d.node(t).is_some());
}
#[test]
fn document_path_items_remove_all_keeps_empty_groups_but_removes_empty_compounds() {
for compound in [false, true] {
@@ -106,6 +106,7 @@ fn yes_to_the_confirm_turns_the_warning_off() {
preset: String::new(),
color: None,
cmyk_document: false,
profiles: (None, None),
};
assert_eq!(s.script_dialog(), Some(want));
assert!(s.script_dialog_turns_warning_off());
+1 -1
View File
@@ -19,7 +19,7 @@ fn folder(name: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
std::fs::canonicalize(&base).unwrap()
crate::cmd::findfiles::plain(std::fs::canonicalize(&base).unwrap())
}
fn write(path: &Path, bytes: &[u8]) {
+1 -1
View File
@@ -57,7 +57,7 @@ impl AsRef<Path> for Folder {
/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path.
fn folder(name: &str) -> Folder {
let guard = vectorcraft_testkit::TempDir::new(&format!("script-xmp-{name}"));
let base = std::fs::canonicalize(&*guard).unwrap();
let base = crate::cmd::findfiles::plain(std::fs::canonicalize(&*guard).unwrap());
std::fs::create_dir_all(base.join("main")).unwrap();
Folder { _guard: guard, path: base }
}
+1 -1
View File
@@ -1160,7 +1160,7 @@ fn place_reads_what_open_reads_and_text_files() {
assert_eq!(PLACE_EXTS, [OPEN_EXTS, TEXT_EXTS, RTF_EXTS, DOCX_EXTS, DOC_EXTS].concat());
let filters: Vec<_> = cmd::fileio::place_filters().collect();
let word: (&str, &[&str]) = ("Word", &["docx", "doc"]);
assert_eq!((filters.first(), filters.last()), (Some(&("All placeable files", PLACE_EXTS)), Some(&word)));
assert_eq!((filters.first(), filters.last()), (Some(&("All placeable files", cmd::fileio::place_exts())), Some(&word)));
assert_eq!(filters.get(filters.len() - 3..), Some(&[("Text", TEXT_EXTS), ("RTF", RTF_EXTS), word][..]));
assert!(
!cmd::fileio::open_filters().any(|(_, exts)| ["txt", "rtf", "docx", "doc"].iter().any(|e| exts.contains(e))),
+129 -3
View File
@@ -3711,12 +3711,20 @@ fn arb_dxf_entity() -> impl Strategy<Value = Vec<(i32, String)>> {
"ATTRIB",
"DIMENSION",
"VIEWPORT",
"REGION",
]);
let code = prop::sample::select(vec![
2, 6, 7, 8, 10, 11, 12, 13, 20, 21, 22, 23, 40, 41, 42, 43, 44, 45, 48, 50, 51, 60, 62, 66, 67, 70, 71, 72, 73, 74, 75, 76, 90, 91, 92, 93,
94, 95, 96, 97, 210, 220, 230, 370, 420, 440, 450,
1, 2, 3, 6, 7, 8, 10, 11, 12, 13, 20, 21, 22, 23, 40, 41, 42, 43, 44, 45, 48, 50, 51, 60, 62, 66, 67, 70, 71, 72, 73, 74, 75, 76, 90, 91, 92,
93, 94, 95, 96, 97, 210, 220, 230, 370, 420, 440, 450,
]);
let value = prop_oneof![arb_num(), Just("B".to_string()), Just("*U1".to_string()), Just(r"{\fA;x}\P%%c^".to_string())];
let value = prop_oneof![
arb_num(),
Just("B".to_string()),
Just("*U1".to_string()),
Just(r"{\fA;x}\P%%c^".to_string()),
Just("700 0 1 0".to_string()),
Just("body $-1 -1 $-1 $0 $-1 $-1 #".to_string()),
];
(kind, prop::collection::vec((code, value), 0..24)).prop_map(|(k, g)| std::iter::once((0, k.to_string())).chain(g).collect())
}
@@ -3730,6 +3738,107 @@ fn hostile_dxf(block: &[Vec<(i32, String)>], body: &[Vec<(i32, String)>]) -> Vec
dxf_text(&all).into_bytes()
}
/// A region's solid-modeler text data: one face whose loop is two lines and a quarter circle,
/// (0, 0) to (100, 0), round to (0, 100) and back.
const REGION_SAT: &str = "700 0 1 0
4 Fuzz 3 ASM 4 none
1 9.9999999999999995e-07 1e-10
body $-1 -1 $-1 $1 $-1 $-1 #
lump $-1 -1 $-1 $-1 $2 $0 #
shell $-1 -1 $-1 $-1 $-1 $3 $-1 $1 #
face $-1 -1 $-1 $-1 $4 $2 $-1 $-1 forward single #
loop $-1 -1 $-1 $-1 $5 $3 #
coedge $-1 -1 $-1 $6 $7 $-1 $8 forward $4 $-1 #
coedge $-1 -1 $-1 $7 $5 $-1 $9 forward $4 $-1 #
coedge $-1 -1 $-1 $5 $6 $-1 $10 forward $4 $-1 #
edge $-1 -1 $-1 $11 0 $12 1 $5 $-1 forward @7 unknown #
edge $-1 -1 $-1 $12 0 $13 1 $6 $17 forward @7 unknown #
edge $-1 -1 $-1 $13 0 $11 1 $7 $-1 forward @7 unknown #
vertex $-1 -1 $-1 $8 $14 #
vertex $-1 -1 $-1 $9 $15 #
vertex $-1 -1 $-1 $10 $16 #
point $-1 -1 $-1 0 0 0 #
point $-1 -1 $-1 100 0 0 #
point $-1 -1 $-1 0 100 0 #
ellipse-curve $-1 -1 $-1 0 0 0 0 0 1 100 0 0 1 I I #
End-of-ACIS-data
";
/// [`REGION_SAT`]'s records as binary data: tagged values, type names in parts.
fn region_sab() -> Vec<u8> {
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<u8>, tag: u8, s: &str| {
b.push(tag);
b.push(u8::try_from(s.len()).unwrap_or(0));
b.extend(s.as_bytes());
};
for line in REGION_SAT.lines().skip(3).take_while(|l| !l.starts_with("End-of")) {
let mut words = line.split_whitespace();
let parts: Vec<&str> = words.next().unwrap_or_default().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" => b.push(0x0B),
"reversed" => b.push(0x0A),
w if w.starts_with('$') => {
b.push(0x0C);
b.extend(w[1..].parse::<i32>().unwrap_or(-1).to_le_bytes());
}
w if w.starts_with('@') => string(&mut b, 0x07, words.next().unwrap_or_default()),
w => match w.parse::<f64>() {
Ok(v) => {
b.push(0x06);
b.extend(v.to_le_bytes());
}
Err(_) => string(&mut b, 0x07, w),
},
}
}
b.push(0x11);
}
b
}
/// A drawing with one REGION: `text` as its data in groups 1 (DXF 2000), or `binary` in the
/// ACDSDATA section (DXF 2013).
fn region_dxf(text: &str, binary: Option<&[u8]>) -> Vec<u8> {
let version = if binary.is_some() { "AC1027" } else { "AC1015" };
let mut p: Vec<(i32, String)> =
[(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, version), (0, "ENDSEC"), (0, "SECTION"), (2, "ENTITIES"), (0, "REGION"), (5, "2A")]
.iter()
.map(|(c, v)| (*c, v.to_string()))
.collect();
p.extend([(8, "0".to_string()), (100, "AcDbEntity".into()), (100, "AcDbModelerGeometry".into()), (70, "1".into())]);
p.extend(text.lines().map(|l| (1, l.to_string())));
p.push((0, "ENDSEC".into()));
if let Some(bytes) = binary {
p.extend([(0, "SECTION"), (2, "ACDSDATA"), (0, "ACDSRECORD"), (320, "2A"), (2, "ASM_Data")].iter().map(|(c, v)| (*c, v.to_string())));
p.push((94, bytes.len().to_string()));
p.extend(bytes.chunks(127).map(|c| (310, c.iter().map(|b| format!("{b:02X}")).collect())));
p.push((0, "ENDSEC".into()));
}
p.push((0, "EOF".into()));
dxf_text(&p).into_bytes()
}
#[test]
fn region_seeds_open_as_a_filled_path() {
let o = vectorcraft_cad::ImportOptions::default();
for bytes in [region_dxf(REGION_SAT, None), region_dxf("", Some(&region_sab()))] {
let r = vectorcraft_cad::import(&bytes, &o).expect("opens");
assert!(!r.warnings.iter().any(|w| w.contains("REGION")), "{:?}", r.warnings);
let mut paths = 0;
r.document.walk(|n: &vectorcraft_doc::Node| paths += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. })));
assert_eq!(paths, 1);
}
}
/// Import with every option at once, and place it; whatever comes back must render and export.
fn survive_dxf(what: &str, bytes: &[u8], fit: bool) -> Result<(), TestCaseError> {
let o = vectorcraft_cad::ImportOptions { fit, center: !fit, merge_layers: fit, ..Default::default() };
@@ -3783,6 +3892,23 @@ proptest! {
bytes.truncate(cut.max(8));
survive_dxf("mutated dxf", &bytes, cut % 2 == 0)?;
}
#[test]
fn dxf_mutated_regions_never_panic(
binary in any::<bool>(),
cut in 0usize..2_000,
edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec![b'0', b'1', b'9', b'-', b'.', b'e', b'$', b'#', b' ', b'@', 0xFF, 0x0C])), 0..12),
) {
let mut data = if binary { region_sab() } else { REGION_SAT.as_bytes().to_vec() };
for &(at, b) in &edits {
let n = data.len();
// Text stays ASCII, as group values are.
data[at % n] = if binary || (b' '..0x80).contains(&b) { b } else { b' ' };
}
data.truncate(cut.max(8));
let bytes = if binary { region_dxf("", Some(&data)) } else { region_dxf(&String::from_utf8_lossy(&data), None) };
survive_dxf("mutated region", &bytes, cut % 2 == 0)?;
}
}
// ---------- Windows metafiles: opened, placed and pasted ----------
+185 -36
View File
@@ -279,11 +279,35 @@ enum FrameKind {
/// Point type: the matrix carries the layout (its anchor at the origin of its lines) onto the
/// canvas.
Point([f64; 6]),
/// Area type flowed inside a path: its cubic segments on the canvas, four points each, and the
/// Area Type Options the frame keeps.
Area(Vec<[f64; 8]>, AreaFrame),
/// Type on a path, from `start` to `end` (segment index and the place in that segment).
OnPath { segments: Vec<[f64; 8]>, start: f64, end: f64, options: PathFrame },
/// Area type flowed inside a path: its cubic segments on the canvas, four points each, the Area
/// Type Options the frame keeps, and the frame's matrix (the segments are already on the
/// canvas; the matrix turns and scales the lines inside them).
Area(Vec<[f64; 8]>, AreaFrame, [f64; 6]),
/// Type on a path, from `start` to `end` (segment index and the place in that segment), its
/// segments on the canvas, and the frame's matrix.
OnPath { segments: Vec<[f64; 8]>, start: f64, end: f64, options: PathFrame, matrix: [f64; 6] },
}
/// The matrix of a frame that keeps none: its frame and layout are already on the canvas.
const NO_MATRIX: [f64; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
/// Segment `s` (four points) carried onto the canvas by the frame matrix `m`.
fn on_canvas(m: &[f64; 6], s: &[f64; 8]) -> [f64; 8] {
let [a, b, c, d, e, f] = *m;
let mut out = *s;
for [x, y] in out.as_chunks_mut::<2>().0 {
(*x, *y) = (a * *x + c * *y + e, b * *x + d * *y + f);
}
out
}
/// The scale of the frame matrix `m` and its turn (the matrix without its scale or its move), or
/// `None` for a matrix that mirrors, has no size or isn't finite.
fn turn_of(m: &[f64; 6]) -> Option<(f64, Affine)> {
let [a, b, c, d, ..] = *m;
let det = a * d - b * c;
let scale = det.abs().sqrt();
(scale.is_finite() && scale > 1e-6 && det > 0.0).then(|| (scale, Affine::new([a / scale, b / scale, c / scale, d / scale, 0.0, 0.0])))
}
/// The Type on a Path Options a frame of type on a path keeps at key 11. Each stays at its default
@@ -732,19 +756,21 @@ impl Texts {
fn frame(&self, i: usize) -> Option<FrameKind> {
let f = self.frames.get(i)?.get("0")?;
let carries = f.get("2")?;
// Key 2, the frame's matrix: it carries the frame's segments and its layout onto the canvas.
// Type that is neither turned nor scaled has none (Illustrator 24 leaves it out): its frame
// and layout are already where they go on the canvas.
let matrix: [f64; 6] = match carries.get("2") {
None => NO_MATRIX,
Some(m) => m.nums()?.try_into().ok()?,
};
let segments = || -> Option<Vec<[f64; 8]>> {
let n = f.get("1")?.get("0")?.nums()?;
let (chunks, rest) = n.as_chunks::<8>();
(rest.is_empty() && !chunks.is_empty() && chunks.len() <= MAX_SEGMENTS).then(|| chunks.to_vec())
(rest.is_empty() && !chunks.is_empty() && chunks.len() <= MAX_SEGMENTS).then(|| chunks.iter().map(|s| on_canvas(&matrix, s)).collect())
};
match carries.get("0").and_then(Val::num).unwrap_or(0.0) as i64 {
// Point type that is neither turned nor scaled has no matrix (Illustrator 24 leaves it out):
// its layout is already where it goes on the canvas.
0 => Some(FrameKind::Point(match carries.get("2") {
None => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
Some(m) => m.nums()?.try_into().ok()?,
})),
1 => Some(FrameKind::Area(segments()?, AreaFrame::read(carries))),
0 => Some(FrameKind::Point(matrix)),
1 => Some(FrameKind::Area(segments()?, AreaFrame::read(carries), matrix)),
2 => {
let range = carries.get("6").and_then(Val::nums).unwrap_or_default();
let segments = segments()?;
@@ -760,7 +786,7 @@ impl Texts {
let start = finite(range.first()).unwrap_or(0.0).clamp(0.0, n);
(start, finite(range.get(1)).unwrap_or(n).clamp(start, n))
};
Some(FrameKind::OnPath { segments, start, end, options: PathFrame::read(carries) })
Some(FrameKind::OnPath { segments, start, end, options: PathFrame::read(carries), matrix })
}
_ => None,
}
@@ -1219,11 +1245,11 @@ impl Story {
frame == 0 && matches!(self.frames.first(), Some(FrameKind::Point(_))) && self.is_blank()
}
/// The point frame's matrix (the first frame's, when it is one), else the identity.
/// The first frame's matrix, which carries its layout onto the canvas, else the identity.
fn matrix(&self) -> [f64; 6] {
match self.frames.first() {
Some(FrameKind::Point(m)) => *m,
_ => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
Some(FrameKind::Point(m) | FrameKind::Area(_, _, m) | FrameKind::OnPath { matrix: m, .. }) => *m,
None => NO_MATRIX,
}
}
@@ -1256,7 +1282,7 @@ impl Story {
let size = self.runs.iter().map(|(_, s)| s.size).fold(0.0, f64::max) * art_scale(to_doc);
let bounds = |segments: &[[f64; 8]]| path_of(segments, template, to_doc).bounds();
let r = match self.frames.first()? {
FrameKind::Area(s, _) => bounds(s)?,
FrameKind::Area(s, ..) => bounds(s)?,
FrameKind::OnPath { segments, .. } => bounds(segments)?.inflate(size * 1.5, size * 1.5),
FrameKind::Point(m) => {
let longest = self.text.split(['\r', '\x03']).map(|l| l.chars().count()).max().unwrap_or(0) as f64;
@@ -1312,23 +1338,34 @@ impl Story {
let threaded = frame > 0;
let (scale, xf, kind) = match kind {
FrameKind::Point(m) => {
let [a, b, c, d, ..] = *m;
let scale = (a * d - b * c).abs().sqrt();
if !(scale.is_finite() && scale > 1e-6 && a * d - b * c > 0.0) || threaded {
return None;
}
let (scale, turn) = turn_of(m).filter(|_| !threaded)?;
let (x, y) = self.place(template);
let at = to_doc * Point::new(x, y);
(scale, Affine::new([a / scale, b / scale, c / scale, d / scale, at.x, at.y]), TextKind::Point)
(scale, Affine::translate(at.to_vec2()) * turn, TextKind::Point)
}
FrameKind::Area(s, _) => (1.0, Affine::IDENTITY, TextKind::Area { frame: path_of(s, template, to_doc) }),
FrameKind::OnPath { segments, start, end, options } => {
// Turned area type keeps its turn: its lines run along the turned frame, which is kept
// in the text's own space (the frame on the canvas turned back).
FrameKind::Area(s, _, m) => {
let (scale, turn) = turn_of(m)?;
(scale, turn, TextKind::Area { frame: path_of(s, template, to_doc).transformed(turn.inverse()) })
}
// The glyphs follow the path's tangent and grow by one scale: a frame matrix that also
// stretches or slants them isn't made from the text document (the page draws that type).
FrameKind::OnPath { segments, start, end, options, matrix } => {
let (scale, _) = turn_of(matrix).filter(|(_, turn)| {
let [a, b, c, d, ..] = turn.as_coeffs();
(a - d).abs() < 1e-6 && (b + c).abs() < 1e-6
})?;
let n = segments.len() as f64;
// A closed path keeps its end bracket wherever it is (the same place as the start: a
// full turn, see `TextKind::path_span`); an open one's end at its end is none, unless
// a flip makes it the place the type starts.
let end = (closed(segments) || options.flip || *end < n - 0.02).then(|| length_fraction(segments, *end));
(1.0, Affine::IDENTITY, TextKind::OnPath { path: path_of(segments, template, to_doc), start: length_fraction(segments, *start), end })
(
scale,
Affine::IDENTITY,
TextKind::OnPath { path: path_of(segments, template, to_doc), start: length_fraction(segments, *start), end },
)
}
};
// A `\x03` ends a line inside its paragraph: a forced line break (U+2028), which the
@@ -1389,7 +1426,7 @@ impl Story {
}
// Each frame of a thread keeps its own options.
match self.frames.get(frame) {
Some(FrameKind::Area(_, options)) => options.apply(&mut t.area, scale),
Some(FrameKind::Area(_, options, _)) => options.apply(&mut t.area, scale),
Some(FrameKind::OnPath { options, .. }) => {
t.path_effect = options.effect;
t.path_align = options.align;
@@ -1450,7 +1487,7 @@ impl Story {
pub(super) fn place_first_line(&self, node: &mut Node, frame: usize, template: (f64, f64), to_doc: Affine) -> bool {
// Closer than this (points of the document) and the line is where the file has it.
const SAME: f64 = 0.5;
if matches!(self.frames.get(frame), Some(FrameKind::Area(_, AreaFrame { first_baseline: Some(_), .. }))) {
if matches!(self.frames.get(frame), Some(FrameKind::Area(_, AreaFrame { first_baseline: Some(_), .. }, _))) {
return false;
}
let NodeKind::Text(t) = &mut node.kind else { return false };
@@ -1458,7 +1495,8 @@ impl Story {
return false;
}
let Some((_, (x, y))) = self.line_starts(template).into_iter().next() else { return false };
let at = to_doc * Point::new(x, y);
// In the text's own space, where its lines are laid out (turned area type's is turned).
let at = t.xf.inverse() * (to_doc * Point::new(x, y));
let db = vectorcraft_text::FontDb::global();
// A frame too short for the line lays nothing out: as the line needs it (see `fit_first_line`).
let mut probe = TextObject::clone(t);
@@ -2229,7 +2267,7 @@ mod tests {
for frame in [
FrameKind::Point([0.0, 1.0, -1.0, 0.0, 30.0, 40.0]),
FrameKind::Point([2.0, 0.0, 0.0, 2.0, -7.0, 3.0]),
FrameKind::Area(area_segments(), AreaFrame::default()),
FrameKind::Area(area_segments(), AreaFrame::default(), NO_MATRIX),
] {
let mut st = story("type", &[0.0], &Para::default());
st.frames = vec![frame.clone()];
@@ -2987,12 +3025,12 @@ mod tests {
let mut s = story("one\rtwo\rthree\r", &[0.0, 15.6, 31.2], &Para::default());
// A point-type frame (the helper's) isn't fitted.
assert!(!s.fit_last_lines(&mut t));
s.frames = vec![FrameKind::Area(vec![], AreaFrame::default())];
s.frames = vec![FrameKind::Area(vec![], AreaFrame::default(), NO_MATRIX)];
assert!(s.fit_last_lines(&mut t));
assert_eq!(vectorcraft_text::layout(db, &t).lines.len(), 3);
// A story threaded through two frames: its lines are the first frame's alone.
let mut t = area(third.baseline - 20.0 + third.descent / 2.0);
s.frames.push(FrameKind::Area(vec![], AreaFrame::default()));
s.frames.push(FrameKind::Area(vec![], AreaFrame::default(), NO_MATRIX));
assert!(!s.fit_last_lines(&mut t));
}
@@ -3017,7 +3055,7 @@ mod tests {
(placed, l.lines.first().map(|l| l.baseline), t.area.first_baseline)
};
let mut s = story("Heading\r", &[], &Para::default());
s.frames = vec![FrameKind::Area(frame, AreaFrame::default())];
s.frames = vec![FrameKind::Area(frame, AreaFrame::default(), NO_MATRIX)];
// Where this lays the line out on its own: the file agrees, and nothing changes.
s.lines = vec![(10.0, 20.0)];
let (_, Some(own), _) = first(&s) else { panic!("a line") };
@@ -3030,6 +3068,32 @@ mod tests {
assert!(at.is_some_and(|y| (y - (own - 3.0)).abs() < 1e-6), "{at:?} for {}", own - 3.0);
}
#[test]
fn turned_area_type_s_first_line_is_compared_in_its_own_space() {
// GUARDS: the file's first line was compared with the layout where it is on the page, not
// in the turned type's own space: turned area type whose line is where the file has it got
// a fixed first baseline it doesn't keep.
let (template, to_doc) = ((CANVAS_CENTRE, -CANVAS_CENTRE), Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]));
let first = |s: &Story| {
let mut node = s.node(NodeId(0), 0, template, to_doc).unwrap();
let placed = s.place_first_line(&mut node, 0, template, to_doc);
let NodeKind::Text(t) = node.kind else { panic!("area type") };
let l = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
(placed, l.lines.first().map(|l| l.baseline), t.area.first_baseline)
};
let mut s = story("Heading\r", &[], &Para::default());
// A quarter turn round the canvas's origin: the frame's own space is the text document's.
s.frames = vec![area_frame("/2 [ 0 1 -1 0 0 0 ]")];
s.lines = vec![(10.0, 20.0)];
let (_, Some(own), _) = first(&s) else { panic!("a line") };
s.lines = vec![(10.0, own)];
assert_eq!(first(&s), (false, Some(own), vectorcraft_doc::FirstBaseline::Ascent));
s.lines = vec![(10.0, own - 3.0)];
let (placed, at, fb) = first(&s);
assert!(placed && fb == vectorcraft_doc::FirstBaseline::Fixed, "{fb:?}");
assert!(at.is_some_and(|y| (y - (own - 3.0)).abs() < 1e-6), "{at:?} for {}", own - 3.0);
}
/// A text document's area frame, the rectangle 10, 20 to 210, 120 of the canvas, whose frame
/// data has `options` besides its kind, written by hand.
fn area_frame(options: &str) -> FrameKind {
@@ -3065,6 +3129,91 @@ mod tests {
t.area
}
/// The text object a story in the area frame [`area_frame`] makes with `options` comes in as,
/// or `None`.
fn area_type(options: &str) -> Option<TextObject> {
let mut s = story("Some area type\r", &[], &Para::default());
s.frames = vec![area_frame(options)];
let to_doc = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]);
match s.node(NodeId(0), 0, (CANVAS_CENTRE, -CANVAS_CENTRE), to_doc)?.kind {
NodeKind::Text(t) => Some(*t),
_ => None,
}
}
/// Width and height of the area frame of `t`, in its own space.
fn own_frame_size(t: &TextObject) -> (f64, f64) {
let vectorcraft_doc::TextKind::Area { frame } = &t.kind else { panic!("area type") };
let r = frame.bounds().unwrap();
(r.width(), r.height())
}
#[test]
fn turned_area_type_comes_in_turned_with_its_lines_along_its_frame() {
// GUARDS: area type's frame matrix was left out: a frame turned a quarter came in unturned,
// its lines across the page where the file runs them down it.
let plain = area_type("").unwrap();
let turned = area_type("/2 [ 0 1 -1 0 300 0 ]").unwrap();
let (w, h) = own_frame_size(&plain);
assert!(w > h, "{w} by {h}");
// On the page the frame stands on its end ...
let page = turned.bounds().unwrap();
assert!((page.width() - h).abs() < 1e-6 && (page.height() - w).abs() < 1e-6, "{page:?}");
// ... and in the text's own space, where its lines run, it is as wide as the unturned one.
let (tw, th) = own_frame_size(&turned);
assert!((tw - w).abs() < 1e-6 && (th - h).abs() < 1e-6, "{tw} by {th}");
let along = turned.xf * Point::new(1.0, 0.0) - turned.xf * Point::ZERO;
assert!(along.x.abs() < 1e-9 && (along.y.abs() - 1.0).abs() < 1e-9, "{along:?}");
// A turn alone leaves the type's size as it is.
assert_eq!(turned.runs[0].style.size, plain.runs[0].style.size);
}
#[test]
fn a_scaled_area_frame_scales_its_type_and_a_mirrored_one_isnt_made() {
// GUARDS: area type's frame matrix was left out: a frame scaled up came in at its unscaled
// size, and a mirrored one unmirrored.
let plain = area_type("").unwrap();
let double = area_type("/2 [ 2 0 0 2 0 0 ]").unwrap();
assert_eq!(double.runs[0].style.size, plain.runs[0].style.size * 2.0);
let ((w, h), (dw, dh)) = (own_frame_size(&plain), own_frame_size(&double));
assert!((dw - 2.0 * w).abs() < 1e-6 && (dh - 2.0 * h).abs() < 1e-6, "{dw} by {dh}");
// Mirrored type isn't made from the text document, as point type isn't.
assert!(area_type("/2 [ -1 0 0 1 0 0 ]").is_none());
}
#[test]
fn type_on_a_turned_path_runs_along_the_path_where_the_canvas_has_it() {
// GUARDS: type on a path's frame matrix was left out: the path of a frame turned a quarter
// came in unturned.
let open = [[0.0, 0.0, 30.0, 0.0, 70.0, 0.0, 100.0, 0.0], [100.0, 0.0, 130.0, 0.0, 170.0, 0.0, 200.0, 0.0]];
let path = |options: &str| {
let (t, _) = on_path("type", on_path_frame_with(&open, [0.0, 2.0], options).unwrap());
let vectorcraft_doc::TextKind::OnPath { path, .. } = &t.kind else { panic!("type on a path") };
path.bounds().unwrap()
};
let plain = path("");
assert!(plain.width() > 100.0 && plain.height() < 1e-6, "{plain:?}");
let turned = path("/2 [ 0 1 -1 0 0 0 ]");
assert!(turned.width() < 1e-6 && (turned.height() - plain.width()).abs() < 1e-6, "{turned:?}");
}
#[test]
fn type_on_a_stretched_path_is_left_to_the_page() {
// GUARDS: a frame matrix that stretched the path four times and the type not at all came
// in with glyphs twice as wide and twice as tall.
let open = [[0.0, 0.0, 30.0, 0.0, 70.0, 0.0, 100.0, 0.0], [100.0, 0.0, 130.0, 0.0, 170.0, 0.0, 200.0, 0.0]];
let made = |options: &str| {
let mut st = story("type", &[0.0], &Para::default());
st.frames = vec![on_path_frame_with(&open, [0.0, 2.0], options).unwrap()];
st.node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY)
};
assert!(made("/2 [ 4 0 0 1 0 0 ]").is_none());
assert!(made("/2 [ 1 0.5 0 1 0 0 ]").is_none());
// A uniform scale and a turn are still made.
assert!(made("/2 [ 2 0 0 2 0 0 ]").is_some());
assert!(made("/2 [ 0 2 -2 0 0 0 ]").is_some());
}
#[test]
fn area_frame_options_are_read() {
// GUARDS: area type came in with one row, one column and the 18 pt gutter whatever its frame kept.
@@ -3152,7 +3301,7 @@ mod tests {
#[test]
fn area_frame_without_options_comes_in_as_before() {
assert_eq!(area_of(vec![area_frame("")], 0, 1.0), vectorcraft_doc::AreaOptions::default());
assert_eq!(area_frame(""), FrameKind::Area(area_segments(), AreaFrame::default()));
assert_eq!(area_frame(""), FrameKind::Area(area_segments(), AreaFrame::default(), NO_MATRIX));
}
/// The segments [`area_frame`] writes.
@@ -3199,7 +3348,7 @@ mod tests {
(placed, l.baselines().first().map(|b| b.0.x), t.area.first_baseline)
};
let mut s = story("§§\r", &[], &Para::default());
s.frames = vec![FrameKind::Area(frame, AreaFrame::default())];
s.frames = vec![FrameKind::Area(frame, AreaFrame::default(), NO_MATRIX)];
s.vertical = true;
s.anchor = (210.0, 20.0);
s.lines = vec![(0.0, 0.0)];
+24 -1
View File
@@ -38,7 +38,9 @@ fn frame_text_from_art(info: &SlotInfo, node: &mut Node, region: &mut Option<Rec
let size = text.runs.iter().map(|r| r.style.size).fold(0.0, f64::max);
match &mut text.kind {
TextKind::Area { frame } => {
*frame = path.clone();
// The object's path is on the page; turned area type keeps its frame in its own
// (turned) space.
*frame = path.transformed(text.xf.inverse());
*region = path.bounds();
}
TextKind::OnPath { path: on, .. } => {
@@ -738,4 +740,25 @@ mod tests {
assert_eq!(has_made_words(&present, &content, &spelled, &mut few), Some(true));
assert!(one_word_everywhere - few.0 < one_word_everywhere / 2, "{} searches", one_word_everywhere - few.0);
}
/// The object's own path frames turned area type where the path is on the page: the frame is
/// kept in the type's turned space.
#[test]
fn an_object_s_path_frames_turned_area_type_where_the_path_is() {
// GUARDS: the path replaced the frame as it is on the page, and the type's turn then turned
// it a second time.
let mut node = text(1, "Turned");
let NodeKind::Text(t) = &mut node.kind else { panic!("type") };
t.xf = Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]);
t.kind = TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)) };
let on_page = vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 20.0, 150.0, 220.0));
let info = SlotInfo { story: Some(0), frame: 0, shown: true, art_path: Some(on_page.clone()), look: None, group: None };
let mut region = None;
frame_text_from_art(&info, &mut node, &mut region);
let NodeKind::Text(t) = &node.kind else { panic!("type") };
let (drawn, want) = (t.bounds().unwrap(), on_page.bounds().unwrap());
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
assert!(near(drawn.x0, want.x0) && near(drawn.y0, want.y0) && near(drawn.x1, want.x1) && near(drawn.y1, want.y1), "{drawn:?} {want:?}");
assert_eq!(region, Some(want));
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
//! [`Backend`].
use serde_json::{Map, Value, json};
use vectorcraft_engine::cmd::fileio::{ARTBOARD_PARAMS, FORMATS, OPEN_EXTS, SAVE_FORMATS, format, writable_format};
use vectorcraft_engine::cmd::fileio::{ARTBOARD_PARAMS, FORMATS, SAVE_FORMATS, format, open_exts, writable_format};
use crate::backend::Backend;
+2 -2
View File
@@ -1,6 +1,6 @@
use super::dispatch::{BRIEF, MAX_SIDE_WINDOW, MENU_FILTER, TRACE_VIEWS};
use super::handlers::MAX_DIALOG_FIELDS;
use super::{FORMATS, OPEN_EXTS, SAVE_FORMATS, Value, format, json};
use super::{FORMATS, SAVE_FORMATS, Value, format, json, open_exts};
// ---------- schemas ----------
@@ -365,7 +365,7 @@ pub fn tool_definitions() -> Vec<Value> {
"Open file",
&format!(
"Open a file as a new, active document: .{} (see run_command document.formats). Templates (.ait, native templates) open as a new untitled document. The reply's `warnings` say what didn't come in as it was (an EPS shown as its preview image says why its PostScript couldn't be read). A file of an extension no built-in format reads opens with the installed importer plug-in that lists it; `importer` names the importer to use (File › Open With), also for an extension a built-in format reads, and `params` gives that importer's parameters.",
OPEN_EXTS.join(", .")
open_exts().join(", .")
),
obj(
json!({
+21 -3
View File
@@ -720,7 +720,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"window.taskBar.actions",
"Bar Actions",
"",
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"conceptToVector\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
),
(
"window.taskBar.resetActions",
@@ -1038,6 +1038,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library; an error with `group`)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)",
),
(
"ui.conceptVector",
"Concept to Vector…",
"",
"{} open the Concept to Vector panel for the selected image or unexpanded Image Trace object; an error when the selection is not one such object, unlocked and shown (engine: conceptVector.generate / conceptVector.insert)",
),
(
"ui.conceptVector.generate",
"Generate Concept to Vector Styles",
"",
"{} make the styles ticked in the Concept to Vector panel of the selected image or unexpanded Image Trace object, with the panel's Detail (the panel's Generate; engine: conceptVector.generate), and show them in the panel; off the UI thread in the app unless VECTORCRAFT_SYNC_OPEN is set, one part a frame on the web; a run going is canceled first, and the new one starts once its thread has ended → {running: true} while they are made, else {running: false, job}",
),
(
"ui.conceptVector.cancel",
"Cancel Concept to Vector",
"",
"{} stop the styles the Concept to Vector panel is making off the UI thread (the panel's Cancel; on the web, before the next part): nothing is kept or shown → {canceled: 0 or 1}",
),
(
"ui.recolorUndo",
"Undo Changes",
@@ -1555,7 +1573,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.menuDialog",
"Menu Dialog",
"",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.fontSheet|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
),
(
"ui.widthPointEdit",
@@ -1780,7 +1798,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.placementOptionsDialog",
"Placement Options…",
"",
"{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo or Redo there (reopen the dialog)",
"{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo, a Redo or a canceled edit that put back an earlier state there (reopen the dialog)",
),
(
"ui.relinkDialog",
+29 -2
View File
@@ -4,7 +4,8 @@
//! - A filled or stroked path becomes a path with a fill and a stroke (caps, joins, miter limit
//! and dashes from the pen). Opaque solid strokes with round caps and round joins drawn one after
//! another, each starting where the last one ended, with the same pen and clip, join into one
//! path. Other strokes stay apart, each with its own caps and its own dashes.
//! path. Other strokes stay apart, each with its own caps and its own dashes. A path that is
//! only filled comes in with every figure closed.
//! - A path filled with a pattern or hatched brush is filled with the average color of the
//! brush's tile.
//! - A bitmap becomes an image (its pixels as PNG) placed where the picture draws it, turned or
@@ -309,11 +310,14 @@ impl Mapper {
st
}
/// A path node painted with `fill` and `stroke`; None when neither shows.
/// A path node painted with `fill` and `stroke`; None when neither shows. A path that is only
/// filled has every figure closed, as a fill closes it: a figure a file fills without closing
/// it (FILLPATH without CLOSEFIGURE) comes in as a closed path.
fn path_node(&self, bp: BezPath, fill: Option<[u8; 4]>, stroke: Option<([u8; 4], f32, &LineStyle)>, even_odd: bool) -> Option<Node> {
if bp.elements().is_empty() {
return None;
}
let bp = if stroke.is_none() { closed_figures(&bp) } else { bp };
let mut items = vec![];
if let Some(c) = fill.filter(|c| c[3] > 0) {
let mut f = FillLayer::new(color(c));
@@ -793,6 +797,29 @@ impl Mapper {
}
}
/// `bp` with every figure that has a segment and no close closed.
fn closed_figures(bp: &BezPath) -> BezPath {
let mut out = BezPath::new();
let mut open = false;
for el in bp.elements() {
match el {
PathEl::MoveTo(_) => {
if open {
out.close_path();
}
open = false;
}
PathEl::ClosePath => open = false,
PathEl::LineTo(_) | PathEl::QuadTo(..) | PathEl::CurveTo(..) => open = true,
}
out.push(*el);
}
if open {
out.close_path();
}
out
}
/// Where a line `lead + span` long (along the baseline) starts from the reference point, as
/// `align` puts it, and `lead` on from there: where its first character starts.
fn aligned(lead: f64, span: f64, align: &HAlign) -> f64 {
+48
View File
@@ -1560,3 +1560,51 @@ fn emf_without_a_frame_is_read_at_its_device_resolution() {
let p = paths(&back.document);
assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(10.0 * mm, 5.0 * mm, 20.0 * mm, 7.5 * mm), 0.01), "{:?}", p[0].geometric_bounds());
}
/// Whether each subpath of each path in `bytes` is closed, in order.
fn closed_subpaths(bytes: &[u8]) -> Vec<Vec<bool>> {
paths(&import(bytes).unwrap().document)
.iter()
.map(|n| match &n.kind {
NodeKind::Path { path, .. } => path.subpaths.iter().map(|s| s.closed).collect(),
_ => panic!("a path"),
})
.collect()
}
#[test]
fn filled_ellipses_and_filled_path_figures_come_in_closed() {
// A green brush in slot 1, selected; a null pen.
let brush = vec![(39, le(&[1, 0, 0x00_ff_00, 0])), (37, le(&[1])), (37, le(&[0x8000_0008u32 as i32]))];
// EMR_ELLIPSE.
let ellipse = [brush.clone(), vec![(42, le(&[1000, 1000, 2000, 1500]))]].concat();
assert_eq!(closed_subpaths(&hand_emf(5000, 3000, &ellipse)), vec![vec![true]]);
// EmfPlusFillEllipse with an inline green color, in a dual file.
let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]);
let fill = [le(&[0xFF00_FF00u32 as i32]), le_f32(&[1000.0, 1000.0, 1000.0, 500.0])].concat();
let comment = emf_plus(&[(0x4001, 1, header), (0x400E, 0x8000, fill), (0x4002, 0, vec![])]);
assert_eq!(closed_subpaths(&hand_emf(5000, 3000, &[(70, comment)])), vec![vec![true]]);
// BEGINPATH, two figures of MOVETOEX and POLYBEZIERTO16 (half an ellipse each) without
// CLOSEFIGURE, ENDPATH, then `paint`.
let bracket = |paint: u32, pen: bool| {
let mut r = brush.clone();
if pen {
r.push((37, le(&[0x8000_0007u32 as i32])));
}
r.push((59, vec![]));
for x in [1000, 3000] {
let half: [i16; 12] = [x + 1000, 1500, x + 200, 1500, x, 1400, x, 1250, x, 1100, x + 200, 1000];
r.push((27, le(&[i32::from(x) + 1000, 1250])));
let mut body = le(&[0, 0, 0, 0, 6]);
body.extend(half.iter().flat_map(|v| v.to_le_bytes()));
r.push((88, body));
}
r.push((60, vec![]));
r.push((paint, le(&[0, 0, 0, 0])));
closed_subpaths(&hand_emf(5000, 3000, &r))
};
// FILLPATH: a fill closes every open figure.
assert_eq!(bracket(62, false), vec![vec![true, true]]);
// STROKEPATH: a stroke leaves them open.
assert_eq!(bracket(64, true), vec![vec![false, false]]);
}
+30 -8
View File
@@ -83,6 +83,7 @@ impl<'p> Builder<'p> {
cmyk_keys: HashSet::new(),
intent_cmyk: None,
separation_paints: HashMap::new(),
fill_overprint: (false, 0),
opaque: HashSet::new(),
warnings: vec![],
fonts: HashMap::new(),
@@ -155,6 +156,7 @@ impl<'p> Builder<'p> {
self.stack = vec![Frame::new(FrameKind::Root)];
self.root_groups.clear();
self.blend = BlendMode::Normal;
self.fill_overprint = (false, 0);
self.glyphs = None;
self.type3_run = None;
self.text = None;
@@ -182,6 +184,21 @@ impl<'p> Builder<'p> {
self.scan.overprints && self.scan.paints.get(self.paint_at - 1).copied().unwrap_or(false)
}
/// Whether the image the interpreter draws now, colorized by `paint`, overprints: its fill
/// overprint, as the interpreter reported it for this image. Off in a nested reading, as for
/// paths. A process color (one without a swatch) overprinting in mode 0 is reported as paths
/// are ([`OVERPRINT_ZERO_MODE`]).
pub(super) fn image_overprint(&mut self, paint: &Paint) -> bool {
let (on, mode) = self.fill_overprint;
if !on || self.nested > 0 {
return false;
}
if mode == 0 && matches!(paint, Paint::Solid { swatch: None, .. }) {
self.warn(OVERPRINT_ZERO_MODE);
}
true
}
/// What the interpreter draws now, as the page's walk counts it: the path whose turn comes
/// next, or the `text` before it. `None` in a nested reading, which the walk doesn't follow.
pub(super) fn walked(&self, text: bool) -> Option<Walked> {
@@ -207,9 +224,10 @@ impl<'p> Builder<'p> {
pub(super) fn end_page(&mut self) -> Vec<(Option<usize>, Vec<Arc<Node>>)> {
let mut children = self.close_frames();
// The interpreter drew another number of paths than the file was read to paint: which
// of them overprint can't be trusted.
// of them overprint can't be trusted. An image's overprint comes from the interpreter
// itself, so it stays.
if self.scan.overprints && self.paint_at != self.scan.paints.len() {
children.iter_mut().for_each(vectorcraft_doc::overprint::clear_overprints);
children.iter_mut().for_each(vectorcraft_doc::overprint::clear_paint_overprints);
self.warn(OVERPRINT_UNREAD);
}
let groups = std::mem::take(&mut self.root_groups);
@@ -1114,7 +1132,8 @@ impl<'p> Builder<'p> {
}
/// An image of key `key` (its blob made by `make` the first time), placed by `xf`, with opacity
/// mask `mask` and the solid paint that colorizes it (`colorize`, for a grayscale image).
/// mask `mask` and the solid paint that colorizes it (`colorize`, for a grayscale image), which
/// overprints when the interpreter says the image does ([`Self::image_overprint`]).
pub(super) fn add_image_masked(
&mut self,
key: u128,
@@ -1123,6 +1142,7 @@ impl<'p> Builder<'p> {
mask: Option<OpacityMask>,
colorize: Option<Paint>,
) {
let overprint = colorize.as_ref().is_some_and(|p| self.image_overprint(p));
let (k, w, h) = if let Some(v) = self.image_keys.get(&key).cloned() {
v
} else {
@@ -1143,6 +1163,7 @@ impl<'p> Builder<'p> {
);
n.extras_mut().mask = mask.map(Box::new);
n.extras_mut().colorize = colorize.map(Box::new);
n.extras_mut().colorize_overprint = overprint;
self.push_node(n);
}
@@ -1616,14 +1637,15 @@ fn visual_glyph_text(text: String) -> String {
order.iter().filter_map(|&i| chars.get(i)).collect()
}
/// Whether a visible fill or stroke among `children` overprints, characters' too, directly or
/// through children that don't isolate. In an isolated group an overprinting object is drawn on
/// the group's empty backdrop, so it covers the inks of the art below the group that it does not
/// paint; without isolation it leaves them.
/// Whether a visible fill or stroke among `children` overprints, characters' and colorized
/// images' too, directly or through children that don't isolate. In an isolated group an
/// overprinting object is drawn on the group's empty backdrop, so it covers the inks of the art
/// below the group that it does not paint; without isolation it leaves them.
fn children_overprint(children: &[Arc<Node>]) -> bool {
children.iter().any(|c| {
c.visible
&& (c.appearance.items.iter().any(|i| i.visible() && i.overprint())
&& (c.colorize_overprints()
|| c.appearance.items.iter().any(|i| i.visible() && i.overprint())
|| matches!(&c.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|| (!c.isolate && c.children().is_some_and(|ch| children_overprint(ch))))
})
+4
View File
@@ -31,6 +31,10 @@ impl<'a> Device<'a> for Builder<'_> {
}
}
fn set_overprint(&mut self, fill: bool, _stroke: bool, mode: u8) {
self.fill_overprint = (fill, mode);
}
fn draw_path(&mut self, path: &BezPath, transform: Affine, paint: &craft::pdf::interpret::Paint<'a>, draw_mode: &PathDrawMode) {
self.flush_glyphs();
self.flush_type3();
+3
View File
@@ -144,6 +144,9 @@ pub(super) struct Builder<'p> {
/// Images in a Separation space, by key: the paint of their ink, or `None` when they open in
/// RGB (an ink that can't be told, tints that can't be read).
pub(super) separation_paints: HashMap<u128, Option<Paint>>,
/// The fill overprint (`/op`) and overprint mode (`/OPM`) the interpreter reported last. It
/// reports them before each image it draws, and an image paints with the fill's overprint.
pub(super) fill_overprint: (bool, u8),
/// Mask keys of CMYK images whose mask turned out to hide nothing.
pub(super) opaque: HashSet<u128>,
pub(super) warnings: Vec<String>,
+115
View File
@@ -134,3 +134,118 @@ fn hidden_optional_content_and_pattern_cells_dont_shift_the_count() {
assert!(about_overprint(&r).is_empty(), "layers {layers}: {:?}", r.warnings);
}
}
/// A 2 × 1 image in the spot ink `Spot1` (a Separation space): it opens colorized by the ink.
const SPOT_IMAGE: &str = "<< /Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace [/Separation /Spot1 /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 0 0] /N 1 >>] /BitsPerComponent 8 /Filter /ASCIIHexDecode /Length 5 >>\nstream\nFF00>\nendstream";
/// An 8 × 1 image mask: it opens colorized by the color that paints it.
const MASK: &str = "<< /Type /XObject /Subtype /Image /Width 8 /Height 1 /ImageMask true /BitsPerComponent 1 /Filter /ASCIIHexDecode /Length 3 >>\nstream\nC3>\nendstream";
/// A page drawing `image` as `/Im1` with `content`, then the `extra` objects after it.
fn open_image(content: &str, image: &str, extra: &[&str]) -> ImportReport {
let mut objects = vec![image];
objects.extend_from_slice(extra);
open(content, &format!("{SPOT} /XObject << /Im1 {} 0 R /X0 {} 0 R >>", first_extra(1), first_extra(1) + 1), &objects)
}
/// Each colorized image in paint order: whether its color overprints.
fn image_overprints(d: &Document) -> Vec<bool> {
let mut out = vec![];
d.walk(|n: &Node| {
if matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.is_some() {
out.push(n.colorize_overprints());
}
});
out
}
/// One placement of `/Im1`, `i` steps down the page.
fn draw(i: u32) -> String {
format!("q 80 0 0 10 10 {} cm /Im1 Do Q", 10 + 20 * i)
}
#[test]
fn a_spot_image_overprints_as_its_fill_does() {
// `/op` is the fill's; `/OP` alone is both; a stroke's `/OP` beside `/op false` is not the image's.
let content = format!("/On gs {} /Off gs {} /Stroke gs {} /Both gs {}", draw(0), draw(1), draw(2), draw(3));
let r = open_image(&content, SPOT_IMAGE, &[]);
assert_eq!(image_overprints(&r.document), [true, false, false, true], "{:?}", r.warnings);
assert!(about_overprint(&r).is_empty(), "{:?}", r.warnings);
// Written with its overprint and read again, each keeps it.
let back = import_with_report(&export(&r.document, &PdfOptions::uncompressed()).unwrap(), &ImportOptions::default()).unwrap();
assert_eq!(image_overprints(&back.document), [true, false, false, true], "{:?}", back.warnings);
}
#[test]
fn an_image_mask_overprints_as_its_fill_does() {
let r = open_image(&format!("/CS0 cs 1 scn /On gs {} /Off gs {}", draw(0), draw(1)), MASK, &[]);
assert_eq!(image_overprints(&r.document), [true, false], "{:?}", r.warnings);
assert!(about_overprint(&r).is_empty(), "{:?}", r.warnings);
// Overprint mode 0 changes nothing for a spot color; a process color's zero tints would knock out.
let r = open_image(&format!("/Zero gs /CS0 cs 1 scn {}", draw(0)), MASK, &[]);
assert_eq!(image_overprints(&r.document), [true]);
assert!(about_overprint(&r).is_empty(), "{:?}", r.warnings);
let r = open_image(&format!("/Zero gs 0 0 0 1 k {}", draw(0)), MASK, &[]);
assert_eq!(image_overprints(&r.document), [true]);
assert_eq!(about_overprint(&r).len(), 1, "{:?}", r.warnings);
assert!(about_overprint(&r)[0].contains("/OPM 0"));
}
#[test]
fn an_image_in_a_form_overprints_as_the_form_sets_it() {
// The page's state, then the form's own.
let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 400 400]", &format!("{} /Off gs {}", draw(0), draw(1)));
let r = open_image("/On gs /X0 Do", SPOT_IMAGE, &[&form]);
assert_eq!(image_overprints(&r.document), [true, false], "{:?}", r.warnings);
}
#[test]
fn an_isolated_form_holding_only_an_overprinting_image_stays_isolated() {
let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 400 400] /Group << /S /Transparency /I true >>", &draw(0));
let r = open_image("/On gs /X0 Do", SPOT_IMAGE, &[&form]);
let mut groups = vec![];
r.document.walk(|n: &Node| {
if matches!(n.kind, NodeKind::Group { .. }) {
groups.push(n.isolate);
}
});
assert_eq!(image_overprints(&r.document), [true]);
assert!(groups.contains(&true), "{groups:?}");
}
#[test]
fn an_image_in_a_pattern_cell_knocks_out_as_the_cells_paths_do() {
let (x, cell) = (first_extra(1), first_extra(1) + 1);
let cell_stream = stream(
&format!(
"/Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << {ON} /XObject << /Im1 {x} 0 R >> >>"
),
"/On gs 0 0 1 rg 0 0 5 5 re f q 10 0 0 10 0 0 cm /Im1 Do Q",
);
let r = open("/On gs /Pattern cs /P0 scn 0 0 100 100 re f", &format!("/Pattern << /P0 {cell} 0 R >>"), &[SPOT_IMAGE, &cell_stream]);
let mut art = vec![];
for p in r.document.patterns.iter() {
for a in &p.art {
a.walk(&mut |n: &Node| {
if matches!(n.kind, NodeKind::Image(_)) {
art.push(n.colorize_overprints());
}
});
}
}
assert_eq!(art, [false], "{:?}", r.warnings);
}
#[test]
fn an_image_keeps_its_overprint_on_a_page_whose_paths_cant_be_counted() {
// The paths' overprint is dropped (see above); the image's comes from the interpreter.
let content = format!("0 0 1 rg /Sh0 sh /On gs 10 10 50 50 re f {}", draw(4));
let page = PdfPage {
resources: format!("{ON} /Shading << /Sh0 << /ShadingType 99 >> >> /XObject << /Im1 {} 0 R >>", first_extra(1)),
..PdfPage::new(400.0, 400.0, &content)
};
let r = import_with_report(&pdf_with(&[page], &[SPOT_IMAGE], None), &ImportOptions::default()).unwrap();
assert_eq!(overprints(&r.document), [(Some(false), None)]);
assert_eq!(image_overprints(&r.document), [true]);
assert_eq!(about_overprint(&r).len(), 1, "{:?}", r.warnings);
}
+30 -4
View File
@@ -1,4 +1,4 @@
//! Targa export: depths, alpha and the footer.
//! Targa export: depths, grayscale, alpha and the footer.
use super::on_white;
use super::tests_bmp::{art, decode, u16_at};
@@ -9,7 +9,7 @@ fn targa_depths_alpha_and_footer() {
let (w, h) = (7, 3);
let px = art(w, h);
for (depth, alpha_bits) in [(16, 1), (24, 0), (32, 8)] {
let file = tga::encode(&px, w, h, &TgaOptions { depth }).unwrap();
let file = tga::encode(&px, w, h, &TgaOptions { depth, gray: false }).unwrap();
assert_eq!((file[2], file[16], file[17]), (2, depth, alpha_bits), "true colour, the depth byte, alpha bits");
assert_eq!((u16_at(&file, 12), u16_at(&file, 14)), (7, 3));
assert_eq!(file.len(), 18 + (w * h) as usize * usize::from(depth / 8) + 26);
@@ -18,13 +18,39 @@ fn targa_depths_alpha_and_footer() {
assert_eq!(img.dimensions(), (w, h));
let want = on_white(px[(2 * w as usize + 3) * 4..][..4].try_into().unwrap());
let got = img.get_pixel(3, 2).0;
assert!(got[..3].iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 8), "depth {depth}: {got:?} vs {want:?}");
for c in 0..3 {
assert!(got[c].abs_diff(want[c]) <= 8, "depth {depth}, channel {c}: {got:?} vs {want:?}");
}
match depth {
32 => assert_eq!((img.get_pixel(0, 0).0[3], img.get_pixel(1, 0).0[3]), (0, 128), "8-bit alpha"),
24 => assert_eq!(img.get_pixel(0, 0).0, [255; 4], "flattened on white"),
_ => {}
}
}
assert!(tga::encode(&px, w, h, &TgaOptions { depth: 8 }).is_err());
assert!(tga::encode(&px, w, h, &TgaOptions { depth: 8, gray: false }).is_err());
assert!(tga::encode(&px, 70_000, 1, &TgaOptions::default()).is_err(), "too wide");
}
/// Grayscale Targa files are image type 3: 8 bits flattened on white, or 16 with an 8-bit alpha.
#[test]
fn targa_grayscale_writes_lightness() {
let (w, h) = (7, 3);
let px = art(w, h);
for (depth, alpha_bits) in [(8, 0), (16, 8)] {
let file = tga::encode(&px, w, h, &TgaOptions { depth, gray: true }).unwrap();
assert_eq!((file[2], file[16], file[17]), (3, depth, alpha_bits), "grayscale, the depth byte, alpha bits");
assert_eq!(file.len(), 18 + (w * h) as usize * usize::from(depth / 8) + 26);
let img = decode(&file, craft_image_codecs::Format::Tga);
assert_eq!(img.dimensions(), (w, h));
// (0, 2) is opaque red 230, 40, 30: Rec. 601 lightness 96, the same in every channel.
let [r, g, b, a] = img.get_pixel(0, 2).0;
assert!(r == g && g == b && r.abs_diff(96) <= 1 && a == 255, "depth {depth}: {:?}", [r, g, b, a]);
match depth {
8 => assert_eq!(img.get_pixel(0, 0).0, [255; 4], "flattened on white"),
_ => assert_eq!((img.get_pixel(0, 0).0[3], img.get_pixel(1, 0).0[3]), (0, 128), "8-bit alpha"),
}
}
for depth in [24, 32] {
assert!(tga::encode(&px, w, h, &TgaOptions { depth, gray: true }).is_err(), "{depth} bits gray");
}
}
+39 -15
View File
@@ -1,33 +1,55 @@
//! Targa export: uncompressed true colour at 16 bits per pixel (5-5-5 and a one-bit alpha), 24 or
//! 32 (8-bit alpha), rows bottom-up, with the version 2 footer.
//! 32 (8-bit alpha), or uncompressed grayscale at 8 bits or 16 (8-bit alpha), rows bottom-up, with
//! the version 2 footer.
use super::on_white;
use super::quantize::luma;
/// Bits per pixel a Targa export can have.
/// Bits per pixel a true-colour Targa export can have.
pub const DEPTHS: [u8; 3] = [16, 24, 32];
/// Bits per pixel a grayscale Targa export can have.
pub const GRAY_DEPTHS: [u8; 2] = [8, 16];
/// The Targa options of a raster export.
#[derive(Clone, Debug, PartialEq)]
pub struct TgaOptions {
/// Bits per pixel ([`DEPTHS`]).
/// Bits per pixel ([`DEPTHS`], or [`GRAY_DEPTHS`] when `gray`).
pub depth: u8,
/// Grayscale (image type 3) instead of true colour (image type 2).
pub gray: bool,
}
impl Default for TgaOptions {
fn default() -> Self {
Self { depth: 24 }
Self { depth: Self::default_depth(false), gray: false }
}
}
impl TgaOptions {
/// The depth a colour model starts with: 24 bits for true colour, 8 for grayscale.
pub fn default_depth(gray: bool) -> u8 {
if gray { 8 } else { 24 }
}
/// The depths the colour model can be written at.
pub fn depths(gray: bool) -> &'static [u8] {
if gray { &GRAY_DEPTHS } else { &DEPTHS }
}
/// Why these options can't be written, if they can't.
pub fn check(&self) -> Result<(), String> {
if DEPTHS.contains(&self.depth) { Ok(()) } else { Err(format!("Targa depth {}: 16, 24 or 32 bits per pixel", self.depth)) }
match (self.gray, Self::depths(self.gray).contains(&self.depth)) {
(_, true) => Ok(()),
(false, false) => Err(format!("Targa depth {}: 16, 24 or 32 bits per pixel", self.depth)),
(true, false) => Err(format!("grayscale Targa depth {}: 8 or 16 bits per pixel", self.depth)),
}
}
}
/// Straight-alpha RGBA pixels as a Targa file. 24 bits blend partly transparent pixels over white;
/// at 16 bits a pixel is opaque from half opacity up, else transparent.
/// Straight-alpha RGBA pixels as a Targa file. 24 bits and 8-bit grayscale blend partly
/// transparent pixels over white; at 16 bits true colour a pixel is opaque from half opacity up,
/// else transparent.
pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result<Vec<u8>, String> {
o.check()?;
let (Ok(w16), Ok(h16)) = (u16::try_from(width), u16::try_from(height)) else {
@@ -40,21 +62,23 @@ pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result<Ve
}
let px = rgba.as_chunks::<4>().0;
let mut out = Vec::with_capacity((w * h).saturating_mul(usize::from(o.depth / 8)).saturating_add(18 + 26));
// No image id or colour map, uncompressed true colour, origin (0, 0).
out.extend([0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
// No image id or colour map, uncompressed true colour (2) or grayscale (3), origin (0, 0).
out.extend([0, 0, if o.gray { 3 } else { 2 }, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
out.extend(w16.to_le_bytes());
out.extend(h16.to_le_bytes());
// Bits per pixel, then the alpha bits (rows bottom-up, left to right).
let alpha_bits = match o.depth {
16 => 1,
32 => 8,
let alpha_bits = match (o.gray, o.depth) {
(false, 16) => 1,
(true, 16) | (false, 32) => 8,
_ => 0,
};
out.extend([o.depth, alpha_bits]);
for row in px.chunks(w).rev() {
for p in row {
match o.depth {
16 => {
match (o.gray, o.depth) {
(true, 8) => out.push(luma(on_white(p))),
(true, _) => out.extend([luma([p[0], p[1], p[2]]), p[3]]),
(false, 16) => {
let v = if p[3] >= 128 {
let [r, g, b] = [p[0], p[1], p[2]].map(|c| u16::from(c >> 3));
0x8000 | r << 10 | g << 5 | b
@@ -63,7 +87,7 @@ pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result<Ve
};
out.extend(v.to_le_bytes());
}
24 => {
(false, 24) => {
let [r, g, b] = on_white(p);
out.extend([b, g, r]);
}
+31 -2
View File
@@ -12,7 +12,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
use unicode_segmentation::UnicodeSegmentation;
use vectorcraft_doc::text::CompositeClasses;
use vectorcraft_doc::{CharClass, CompositeClass, CompositeFont, CompositePart, TextObject, TextRun};
use vectorcraft_doc::{CharClass, CompositeClass, CompositeFont, CompositePart, Digits, TextObject, TextRun};
use super::face::FALLBACK_FAMILY;
use super::{Arc, FontDb, FontFace, FontMatch};
@@ -242,6 +242,24 @@ impl FontDb {
/// match, and the characters (neither whitespace nor control characters, sorted, each once)
/// that their part's face lacks. `None` when `name` is no composite font.
pub fn composite_coverage(&self, name: &str, texts: &[&str]) -> Option<CompositeCoverage> {
self.coverage_of(name, texts, None)
}
/// [`FontDb::composite_coverage`] of the characters layout draws in numeral system `digits`:
/// each grapheme cluster's part is chosen by its own first character, and the part's face is
/// checked for the cluster's drawn characters ([`crate::drawn_chars`]).
pub fn composite_drawn_coverage(&self, name: &str, texts: &[&str], digits: Digits) -> Option<CompositeCoverage> {
self.coverage_of(name, texts, Some((digits, false)))
}
/// [`FontDb::composite_drawn_coverage`] of type set in All Caps when `all_caps` is on: each
/// cluster's part is still chosen by its own first character, and the part's face is also
/// checked for the capitals layout draws.
pub fn composite_cased_coverage(&self, name: &str, texts: &[&str], digits: Digits, all_caps: bool) -> Option<CompositeCoverage> {
self.coverage_of(name, texts, Some((digits, all_caps)))
}
fn coverage_of(&self, name: &str, texts: &[&str], digits: Option<(Digits, bool)>) -> Option<CompositeCoverage> {
let f = self.composite_font(name)?;
let rank = |m: FontMatch| match m {
FontMatch::Exact => 0,
@@ -272,7 +290,18 @@ impl FontDb {
if worst.as_ref().is_none_or(|(w, _)| rank(m) > rank(*w)) {
worst = Some((m, found.as_ref().map(|(face, _)| face.clone())));
}
lacking.extend(g.chars().filter(|c| !c.is_whitespace() && !c.is_control() && !found.as_ref().is_some_and(|(face, _)| face.covers(*c))));
match digits {
Some((d, caps)) => {
let missing = |c: &char| !found.as_ref().is_some_and(|(face, _)| face.covers(*c));
lacking.extend(crate::drawn_chars(g, d).filter(missing));
if caps {
let upper: String = g.chars().flat_map(char::to_uppercase).collect();
lacking.extend(crate::drawn_chars(&upper, d).filter(missing));
}
}
None => lacking
.extend(g.chars().filter(|c| !c.is_whitespace() && !c.is_control() && !found.as_ref().is_some_and(|(face, _)| face.covers(*c)))),
}
}
lacking.sort_unstable();
lacking.dedup();
+11 -1
View File
@@ -99,6 +99,8 @@ pub fn fit_source_lines(db: &FontDb, t: &mut TextObject, lines: usize) -> bool {
/// own underline and strikeout metrics through the glyph's transform (so the size, baseline shift
/// and scaling follow) → (run, bar in text space). Type on a path and vertical type have none yet.
pub fn decorations(layout: &TextLayout, db: &FontDb, t: &TextObject) -> Vec<(usize, BezPath)> {
#[cfg(any(test, feature = "test-fonts"))]
crate::test_fonts::count_decorations();
let mut out = vec![];
if layout.on_path || layout.vertical {
return out;
@@ -449,6 +451,14 @@ fn layout_once(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout
let original = |run: &mut usize| *run = from.get(*run).copied().unwrap_or(*run);
l.glyphs.iter_mut().chain(l.ruby.iter_mut()).for_each(|g| original(&mut g.run));
l.inlines.iter_mut().for_each(|i| original(&mut i.run));
let mut ink: Vec<Option<Rect>> = vec![None; t.runs.len()];
for (mut run, bounds) in std::mem::take(&mut l.run_ink_bounds).into_iter().enumerate() {
original(&mut run);
if let (Some(ink), Some(bounds)) = (ink.get_mut(run), bounds) {
*ink = Some(ink.map_or(bounds, |ink| ink.union(bounds)));
}
}
l.run_ink_bounds = ink;
l
}
@@ -572,6 +582,6 @@ fn layout_runs(db: &FontDb, t: &TextObject, opts: &LayoutOptions, set: Option<&T
cx.out.line_xf = line_xf;
}
keep_lone_ligature_carets(&mut cx.out.glyphs);
finish_bounds(&mut cx.out);
finish_bounds(&mut cx.out, t.runs.len());
cx.out
}
+10 -2
View File
@@ -402,9 +402,17 @@ pub(super) fn stands_upright(g: &SGlyph) -> bool {
!needs_vertical_form || g.gid != g.face.glyph_for(g.ch)
}
pub(super) fn finish_bounds(out: &mut TextLayout) {
pub(super) fn finish_bounds(out: &mut TextLayout, runs: usize) {
let xf = out.line_xf;
let mut b: Option<Rect> = out.ink_bounds();
let mut ink: Vec<Option<Rect>> = vec![None; runs];
let mut b: Option<Rect> = None;
out.for_each_ink(|run, bounds| {
b = Some(b.map_or(bounds, |b| b.union(bounds)));
if let Some(ink) = ink.get_mut(run) {
*ink = Some(ink.map_or(bounds, |ink| ink.union(bounds)));
}
});
out.run_ink_bounds = ink;
let mut add = |r: Rect| b = Some(b.map_or(r, |b| b.union(r)));
if !out.on_path {
for l in &out.lines {
+30 -8
View File
@@ -60,7 +60,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader};
pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout};
use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2};
pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled};
pub use shape::{aki_space, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale};
pub use shape::{aki_space, drawn_chars, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale};
pub use vectorcraft_doc::TextObject;
pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign};
@@ -388,6 +388,9 @@ pub struct TextLayout {
pub lines: Vec<LineInfo>,
/// Ink/advance bounds in text space.
pub bounds: Rect,
/// Ink bounds per text run when layout completed, excluding decorations. These bounds do
/// not update when glyph geometry changes; [`Self::ink_bounds`] measures the current geometry.
pub run_ink_bounds: Vec<Option<Rect>>,
/// True if area text did not fit its frame (the red overflow "+" marker), or on-path text ran
/// past the end of the path.
pub overflow: bool,
@@ -422,6 +425,7 @@ impl Default for TextLayout {
ruby: Vec::new(),
lines: Vec::new(),
bounds: Rect::ZERO,
run_ink_bounds: Vec::new(),
overflow: false,
on_path: false,
frames: Vec::new(),
@@ -477,16 +481,34 @@ impl TextLayout {
/// inline graphics included, without the lines' em boxes that [`Self::bounds`] also covers.
/// What Align to Glyph Bounds aligns. `None` when nothing draws (only spaces, or no text).
pub fn ink_bounds(&self) -> Option<Rect> {
let outlined = |g: &PositionedGlyph| (!g.outline.elements().is_empty()).then(|| g.outline.bounding_box());
let glyphs = self.glyphs.iter().flat_map(|g| {
let mut bounds: Option<Rect> = None;
self.for_each_ink(|_, ink| bounds = Some(bounds.map_or(ink, |bounds| bounds.union(ink))));
bounds
}
fn for_each_ink(&self, mut add: impl FnMut(usize, Rect)) {
let outlined = |g: &PositionedGlyph| {
(!g.outline.elements().is_empty()).then(|| {
#[cfg(any(test, feature = "test-fonts"))]
test_fonts::count_ink_outline();
g.outline.bounding_box()
})
};
for g in &self.glyphs {
let image = g.placed_image().map(|(image, xf)| xf.transform_rect_bbox(image.rect()));
let colour = g.colour.as_ref().and_then(|c| c.geometric_bounds()).map(|b| g.xf.transform_rect_bbox(b));
[outlined(g), image, colour]
});
for ink in [outlined(g), image, colour].into_iter().flatten() {
add(g.run, ink);
}
}
// Ruby is covered by its line's ascent, but its ink can overhang sideways past the line.
let ruby = self.ruby.iter().map(outlined);
let inlines = self.inlines.iter().map(|i| Some(i.bounds));
glyphs.chain(ruby).chain(inlines).flatten().reduce(|a, b| a.union(b))
for g in &self.ruby {
if let Some(ink) = outlined(g) {
add(g.run, ink);
}
}
for inline in &self.inlines {
add(inline.run, inline.bounds);
}
}
/// The box of [`Self::ink_bounds`]' ink with text space mapped by `m`: the glyph and ruby
/// outlines are mapped point by point, so a rotated or sheared `m` gives the outlines' own
+3 -3
View File
@@ -1382,11 +1382,11 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
&& ligatures_suppressed_by(*tracking) == ligatures_suppressed_by(b.tracking)
}
/// The characters of a grapheme cluster that need a glyph of their own, in the numeral system
/// The characters of the text that need a glyph of their own, in the numeral system
/// `digits`: not what the layout handles itself (tab, line and paragraph breaks), joiners or
/// variation selectors.
fn drawn_chars(cluster: &str, digits: Digits) -> impl Iterator<Item = char> + '_ {
craft::font_catalog::drawable_characters(cluster, move |c| digits.map(c))
pub fn drawn_chars(text: &str, digits: Digits) -> impl Iterator<Item = char> + '_ {
craft::font_catalog::drawable_characters(text, move |c| digits.map(c))
}
/// Does the face with charmap `map` have a glyph for `c` (any face does when it has no charmap)?
+14
View File
@@ -29,6 +29,20 @@ pub(crate) fn keeps_shape_plans() -> bool {
std::thread_local! {
/// How many layouts this thread has started ([`layouts_on_this_thread`]).
static LAYOUTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
static INK_OUTLINES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
static DECORATIONS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
pub(crate) fn count_ink_outline() {
INK_OUTLINES.with(|n| n.set(n.get() + 1));
}
pub(crate) fn count_decorations() {
DECORATIONS.with(|n| n.set(n.get() + 1));
}
pub fn ink_work_on_this_thread() -> (u64, u64) {
(INK_OUTLINES.with(std::cell::Cell::get), DECORATIONS.with(std::cell::Cell::get))
}
pub(crate) fn count_layout() {
+17
View File
@@ -834,6 +834,23 @@ fn type_path_handles(cx: &ToolContext) -> Vec<Overlay> {
out
}
/// The anchors and direction handles of selected, editable type on a path's path, for the tools
/// that edit them besides Direct Selection (the Anchor Point, Add and Delete Anchor Point tools and
/// the Pen, #10862): the canvas draws only a path's own.
pub(crate) fn type_path_overlays(cx: &ToolContext) -> Vec<Overlay> {
let editable = cx.doc.editable();
let mut out = vec![];
for &id in &cx.selection.objects {
let Some(path) = cx.doc.node(id).filter(|n| is_path_type(n) && editable(id)).and_then(editable_path) else { continue };
let color = cx.doc.layer_color(id);
out.extend(path.anchors().map(|(_, _, a)| Overlay::Anchor { p: a.p, color, filled: false, size: 5.0 }));
}
if !out.is_empty() {
out.extend(type_path_handles(cx));
}
out
}
/// The end of a shown direction handle ([`handle_anchors`]) nearest to `p` within `tol`, and
/// nearer to it than the handle's anchor (a short handle leaves its anchor to be picked): (path,
/// subpath, anchor, is_out).
+52 -7
View File
@@ -377,7 +377,18 @@ pub(crate) fn walk_pickable<'a>(cx: &ToolContext<'a>, mut f: impl FnMut(&'a vect
/// Editable path nodes, selected ones first, then the rest top-most first ([`walk_pickable`]).
pub(crate) fn candidate_paths(cx: &ToolContext) -> Vec<NodeId> {
let mut v: Vec<NodeId> = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(|n| n.path_data().is_some())).collect();
candidates(cx, false)
}
/// [`candidate_paths`], with selected type on a path outside perspective among the selected ones:
/// the objects whose anchors the Add, Delete and Anchor Point tools edit (#10862).
pub(crate) fn anchor_owners(cx: &ToolContext) -> Vec<NodeId> {
candidates(cx, true)
}
fn candidates(cx: &ToolContext, path_type: bool) -> Vec<NodeId> {
let picks = |n: &vectorcraft_doc::Node| n.path_data().is_some() || (path_type && crate::select::is_path_type(n));
let mut v: Vec<NodeId> = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(picks)).collect();
let mut rest = vec![];
walk_pickable(cx, |n| {
if let NodeKind::Path { guide: false, .. } = &n.kind {
@@ -407,9 +418,28 @@ pub(crate) fn editable_paths<'a>(cx: &'a ToolContext) -> impl Iterator<Item = No
.filter(move |&id| editable(id) && cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })))
}
/// [`editable_paths`] with selected type on a path outside perspective: the objects the Pen's Auto
/// Add/Delete adds anchors to and deletes them from (#10862).
pub(crate) fn editable_anchor_owners<'a>(cx: &'a ToolContext) -> impl Iterator<Item = NodeId> + 'a {
let editable = cx.doc.editable();
cx.selection.objects.iter().copied().filter(move |&id| {
editable(id) && cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. }) || crate::select::is_path_type(n))
})
}
/// The paths whose anchors show with the Pen: the selected ones, and those inside selected groups
/// and compound paths (not guides, nor locked or hidden ones). Pen + Alt converts their anchors.
/// and compound paths (not guides, nor locked or hidden ones).
pub(crate) fn shown_paths(cx: &ToolContext) -> Vec<NodeId> {
shown(cx, false)
}
/// [`shown_paths`] with selected type on a path outside perspective, as the Anchor Point tool the
/// Pen lends takes it ([`anchor_owners`]): the objects whose anchors Pen + Alt converts (#10862).
pub(crate) fn shown_anchor_owners(cx: &ToolContext) -> Vec<NodeId> {
shown(cx, true)
}
fn shown(cx: &ToolContext, path_type: bool) -> Vec<NodeId> {
fn inside(n: &vectorcraft_doc::Node, v: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Path { guide: false, .. } => v.push(n.id),
@@ -424,7 +454,11 @@ pub(crate) fn shown_paths(cx: &ToolContext) -> Vec<NodeId> {
}
let mut v = vec![];
for n in cx.selection.objects.iter().filter_map(|id| cx.doc.node(*id)) {
inside(n, &mut v);
if path_type && crate::select::is_path_type(n) {
v.push(n.id);
} else {
inside(n, &mut v);
}
}
let editable = cx.doc.editable();
v.retain(|id| editable(*id));
@@ -436,11 +470,17 @@ pub(crate) fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId
anchor_in(cx, candidate_paths(cx), p, tol)
}
/// Nearest anchor within `tol` on the first of `ids` that has one: (path, subpath, anchor).
/// [`hit_anchor`] on the [`anchor_owners`], selected type on a path's path included.
pub(crate) fn hit_owner_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize)> {
anchor_in(cx, anchor_owners(cx), p, tol)
}
/// Nearest anchor within `tol` on the first of `ids` that has one: (path, subpath, anchor). Type on
/// a path among `ids` offers its path's anchors ([`vectorcraft_doc::Node::anchor_path`]).
pub(crate) fn anchor_in(cx: &ToolContext, ids: impl IntoIterator<Item = NodeId>, p: Point, tol: f64) -> Option<(NodeId, usize, usize)> {
let mut best: Option<((NodeId, usize, usize), f64)> = None;
for id in ids {
let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue };
let Some(pd) = cx.doc.node(id).and_then(|n| n.anchor_path()) else { continue };
for (si, ai, a) in pd.anchors() {
let d = a.p.distance(p);
if d <= tol && best.is_none_or(|b| d < b.1 - 1e-9) {
@@ -459,11 +499,16 @@ pub(crate) fn hit_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeI
segment_in(cx, candidate_paths(cx), p, tol)
}
/// [`hit_segment`] on the [`anchor_owners`], selected type on a path's path included.
pub(crate) fn hit_owner_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, f64)> {
segment_in(cx, anchor_owners(cx), p, tol)
}
/// Nearest point within `tol` on a segment of the first of `ids` that passes there: (path,
/// subpath, segment, t).
/// subpath, segment, t). Type on a path among `ids` offers its path's segments.
pub(crate) fn segment_in(cx: &ToolContext, ids: impl IntoIterator<Item = NodeId>, p: Point, tol: f64) -> Option<(NodeId, usize, usize, f64)> {
for id in ids {
let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue };
let Some(pd) = cx.doc.node(id).and_then(|n| n.anchor_path()) else { continue };
if let Some((si, seg, t, _, d)) = pd.nearest(p)
&& d <= tol
{
+21 -16
View File
@@ -14,12 +14,14 @@
//! follow the same conversions (#2544).
//! Scissors: hover and click snap as the Pen does; click a path to split it there (Alt = add,
//! as the Add Anchor Point tool does).
//! Add, Delete and Anchor Point edit the path of selected type on a path outside perspective as
//! they edit a path's (#10862); Delete leaves it two anchors at least, and Scissors does not cut it.
use serde_json::json;
use vectorcraft_doc::NodeId;
use vectorcraft_geom::{ParamCurve, Point};
use super::{FEEDBACK, hit_anchor, hit_segment, insert_anchor, remove_anchor};
use super::{FEEDBACK, hit_anchor, hit_owner_anchor, hit_owner_segment, hit_segment, insert_anchor, remove_anchor};
use crate::direct::hit_handle;
use crate::guides::{DrawSnap, HandleSnap};
use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
@@ -276,14 +278,14 @@ impl AnchorTool {
}
fn anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option<Point> {
cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
cx.doc.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
}
/// Where anchor `ai` is in the document a preview edits: the document as the interaction
/// began, since each preview runs on that, otherwise the document `cx` shows.
fn began_anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option<Point> {
let d = cx.interaction_doc.unwrap_or(cx.doc);
d.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
d.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
}
/// Where a blend's spine point `ai` is in the spine a spine edit changes: the spine pinned
@@ -342,9 +344,9 @@ impl AnchorTool {
let (point, tol) = (cx.point_tol(), cx.pick_tol());
let mut target = if let Some((id, si, ai, out)) = hit_handle(cx, p, point) {
State::Handle { id, si, ai, out, start: p, began: false }
} else if let Some((id, si, ai)) = hit_anchor(cx, p, point) {
} else if let Some((id, si, ai)) = hit_owner_anchor(cx, p, point) {
State::Convert { id, si, ai, start: p, began: false }
} else if let Some((id, si, seg, t)) = hit_segment(cx, p, tol) {
} else if let Some((id, si, seg, t)) = hit_owner_segment(cx, p, tol) {
State::Reshape { id, si, seg, t, start: p, began: false, spine: false }
} else {
State::Idle
@@ -402,12 +404,10 @@ impl AnchorTool {
/// instead of converting it. Any other press is kept.
fn moving(cx: &ToolContext, st: State) -> State {
match st {
State::Convert { id, si, ai, start, .. } => {
match cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) {
Some(from) => State::Move { id, si, ai, from, start, began: false },
None => st,
}
}
State::Convert { id, si, ai, start, .. } => match Self::anchor_pos(cx, id, si, ai) {
Some(from) => State::Move { id, si, ai, from, start, began: false },
None => st,
},
State::SpineConvert { id, ai, start, .. } => {
match crate::direct::spines(cx)
.into_iter()
@@ -471,11 +471,11 @@ impl AnchorTool {
}
fn add(cx: &ToolContext, p: Point) -> Vec<Action> {
hit_segment(cx, p, cx.pick_tol()).map(insert_anchor).into_iter().collect()
hit_owner_segment(cx, p, cx.pick_tol()).map(insert_anchor).into_iter().collect()
}
fn delete(cx: &ToolContext, p: Point) -> Vec<Action> {
hit_anchor(cx, p, cx.point_tol()).map(remove_anchor).into_iter().collect()
hit_owner_anchor(cx, p, cx.point_tol()).map(remove_anchor).into_iter().collect()
}
}
@@ -708,8 +708,8 @@ impl Tool for AnchorTool {
let has_handles = cx
.doc
.node(id)
.and_then(|n| n.path_data())
.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai))
.and_then(|n| n.anchor_path())
.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).copied())
.is_some_and(|a| a.has_in() || a.has_out());
if has_handles {
vec![Action::Exec("path.convertAnchor".into(), json!({"id": id.0, "subpath": si, "anchor": ai, "to": "corner"}))]
@@ -743,7 +743,8 @@ impl Tool for AnchorTool {
)]
}
State::Handle { id, si, ai, out, began: false, .. } => {
let Some(a) = cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) else {
let Some(a) = cx.doc.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).copied())
else {
return vec![];
};
vec![Action::Exec(
@@ -780,6 +781,10 @@ impl Tool for AnchorTool {
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut out = if self.id == "anchorPoint" { Self::spine_overlays(cx) } else { vec![] };
if self.id != "scissors" {
// These tools edit selected type on a path's path, whose anchors the canvas leaves out.
out.extend(crate::direct::type_path_overlays(cx));
}
if matches!(self.state, State::Handle { .. }) {
out.extend(self.guides.iter().cloned());
}
+56
View File
@@ -672,6 +672,62 @@ fn anchor_tools_leave_out_shaper_sources_and_art_outside_isolation() {
assert_eq!(picked(Some(rect), "deleteAnchor", 100.0, 100.0), Some(rect));
}
/// #10862: selected type on a path's path takes the Anchor Point, Add and Delete Anchor Point tools
/// as a path does; Scissors leaves it alone, and type that is not selected is not picked.
#[test]
fn anchor_tools_edit_selected_type_on_a_path() {
let (d, text) = doc_with_path_type();
let p = paint();
let mut s = Selection::default();
s.add(text);
let names = |a: &[Action]| -> Vec<(String, u64)> {
a.iter()
.filter_map(|x| match x {
Action::Preview(c, v) | Action::Exec(c, v) => Some((c.clone(), v["id"].as_u64()?)),
_ => None,
})
.collect()
};
let gesture = |sel: &Selection, tool: &str, from: (f64, f64), to: (f64, f64)| {
let cx = cx(&d, sel, &p);
let mut t = AnchorTool::new(tool);
let mut out = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, from.0, from.1));
if from != to {
out.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1)));
}
out.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.0, to.1)));
names(&out)
};
let convert = gesture(&s, "anchorPoint", (400.0, 300.0), (420.0, 260.0));
assert!(convert.contains(&("path.convertAnchor".into(), text.0)), "{convert:?}");
assert_eq!(gesture(&s, "addAnchor", (250.0, 300.0), (250.0, 300.0)), vec![("path.insertAnchor".to_string(), text.0)]);
assert_eq!(gesture(&s, "deleteAnchor", (400.0, 300.0), (400.0, 300.0)), vec![("path.removeAnchor".to_string(), text.0)]);
assert!(gesture(&s, "scissors", (250.0, 300.0), (250.0, 300.0)).is_empty(), "Scissors does not cut type");
let none = Selection::default();
assert!(gesture(&none, "anchorPoint", (400.0, 300.0), (420.0, 260.0)).is_empty(), "type that is not selected");
}
/// #10862: the anchors of selected type on a path's path show with the tools that edit them (the
/// canvas draws only a path's own), not with Scissors, and not when the type is not selected.
#[test]
fn anchor_tools_show_the_anchors_of_selected_type_on_a_path() {
let (d, text) = doc_with_path_type();
let p = paint();
let mut s = Selection::default();
s.add(text);
let anchors =
|o: Vec<Overlay>| -> Vec<Point> { o.into_iter().filter_map(|o| if let Overlay::Anchor { p, .. } = o { Some(p) } else { None }).collect() };
let ends = [Point::new(100.0, 300.0), Point::new(400.0, 300.0)];
let selected = cx(&d, &s, &p);
for tool in ["anchorPoint", "addAnchor", "deleteAnchor"] {
assert_eq!(anchors(AnchorTool::new(tool).overlays(&selected)), ends, "{tool}");
}
assert_eq!(anchors(crate::pen::PenTool::default().overlays(&selected)), ends, "pen");
assert!(anchors(AnchorTool::new("scissors").overlays(&selected)).is_empty());
let none = Selection::default();
assert!(anchors(AnchorTool::new("anchorPoint").overlays(&cx(&d, &none, &p))).is_empty());
}
#[test]
fn anchor_point_drag_pulls_handles_click_converts() {
let (d, id) = doc_with_rect();
+1 -1
View File
@@ -171,7 +171,7 @@ mod tests {
(TYPE, &["editing"]),
(&["puppetWarp"], &["pins", "selected"]),
// With nothing queued, `current` (0) is no file's index either.
(&["place"], &["count", "current", "sourceIndex", "name", "width", "height", "names"]),
(&["place"], &["count", "total", "current", "sourceIndex", "name", "width", "height", "names"]),
];
let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k));
// Tools that `create` makes and the catalog doesn't list.
+14 -12
View File
@@ -36,7 +36,7 @@ use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{Anchor, BezPath, Point, Vec2};
use crate::direct::hit_handle;
use crate::draw2::{AnchorTool, editable_paths, shown_paths};
use crate::draw2::{AnchorTool, editable_anchor_owners, shown_anchor_owners, shown_paths};
use crate::guides::{DrawSnap, Leave};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
@@ -225,21 +225,21 @@ fn pick_endpoint(first: Option<Point>, last: Point, p: Point, tol: f64, tie: End
(None, None) => None,
}
}
/// Alt held over a handle end, an anchor or a segment of a selected path: the Anchor Point tool's
/// gesture, within its tolerance.
/// Alt held over a handle end, an anchor or a segment of a selected path, or of selected type on a
/// path's path: the Anchor Point tool's gesture, within its tolerance.
fn alt_converts(cx: &ToolContext, p: Point, m: Mods) -> bool {
let point = cx.point_tol();
m.alt
&& (hit_handle(cx, p, point).is_some()
|| crate::draw2::anchor_in(cx, crate::draw2::shown_paths(cx), p, point).is_some()
|| crate::draw2::segment_in(cx, crate::draw2::shown_paths(cx), p, cx.pick_tol()).is_some())
|| crate::draw2::anchor_in(cx, shown_anchor_owners(cx), p, point).is_some()
|| crate::draw2::segment_in(cx, shown_anchor_owners(cx), p, cx.pick_tol()).is_some())
}
/// The cursor where [`alt_converts`]: Alt lends the Anchor Point tool, so its caret over a handle
/// end or an anchor, the Reshape Segment cursor over a segment.
fn alt_cursor(cx: &ToolContext, p: Point) -> Cursor {
let point = cx.point_tol();
if hit_handle(cx, p, point).is_some() || crate::draw2::anchor_in(cx, crate::draw2::shown_paths(cx), p, point).is_some() {
if hit_handle(cx, p, point).is_some() || crate::draw2::anchor_in(cx, shown_anchor_owners(cx), p, point).is_some() {
Cursor::AnchorPoint
} else {
Cursor::ReshapeSegment
@@ -526,7 +526,8 @@ impl Tool for PenTool {
if let Some(t) = &self.convert {
return t.overlays(cx);
}
let mut o = vec![];
// Pen + Alt and Auto Add/Delete edit selected type on a path's path, so its anchors show.
let mut o = crate::direct::type_path_overlays(cx);
// The rubber band preference hides only the preview segment; Measurement Labels decides the readout.
if self.drag.is_none()
&& self.handle.is_none()
@@ -752,15 +753,16 @@ pub(crate) fn continue_from(cx: &ToolContext, id: NodeId, si: usize, at_first: b
out
}
/// Auto Add/Delete: what a click at `p` does to a selected path. On one of its anchors it deletes
/// it; else, where one of its segments passes within `tol`, it adds an anchor. None when the
/// preference turns it off, Shift is held, or no selected path is there.
/// Auto Add/Delete: what a click at `p` does to a selected path, or to selected type on a path's
/// path. On one of its anchors it deletes it; else, where one of its segments passes within `tol`,
/// it adds an anchor. None when the preference turns it off, Shift is held, or no selected path is
/// there.
fn auto_add_delete(cx: &ToolContext, p: Point, m: Mods, tol: f64) -> Option<Action> {
if !cx.auto_add_delete || m.shift {
return None;
}
let anchor = crate::draw2::anchor_in(cx, editable_paths(cx), p, tol).map(crate::draw2::remove_anchor);
anchor.or_else(|| crate::draw2::segment_in(cx, editable_paths(cx), p, tol).map(crate::draw2::insert_anchor))
let anchor = crate::draw2::anchor_in(cx, editable_anchor_owners(cx), p, tol).map(crate::draw2::remove_anchor);
anchor.or_else(|| crate::draw2::segment_in(cx, editable_anchor_owners(cx), p, tol).map(crate::draw2::insert_anchor))
}
/// A click on a selected blend's spine: delete the point under `p` when no key object sits on it
+32 -1
View File
@@ -32,6 +32,8 @@ struct Entry {
#[derive(Default)]
pub struct PlaceTool {
entries: Vec<Entry>,
/// How many files the last load held, before any was placed or discarded.
total: usize,
current: usize,
/// The tool to return to when the last file is placed or discarded.
prev: Option<String>,
@@ -67,6 +69,7 @@ impl PlaceTool {
}
if self.entries.is_empty() {
self.current = 0;
self.total = 0;
return vec![Action::SwitchTool(self.prev.clone().unwrap_or_else(|| "selection".into()))];
}
self.current %= self.entries.len();
@@ -153,11 +156,13 @@ impl Tool for PlaceTool {
Cursor::Crosshair
}
/// `{count, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data).
/// `{count, total, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data);
/// `total` is how many files the load held.
fn options(&self) -> Value {
let e = self.entry();
json!({
"count": self.entries.len(),
"total": self.total,
"current": self.current,
"sourceIndex": e.map(|e| e.source_index),
"name": e.map(|e| &e.name),
@@ -187,6 +192,7 @@ impl Tool for PlaceTool {
})
})
.collect();
self.total = entries.len();
self.entries = entries;
self.current = 0;
self.drag = None;
@@ -233,6 +239,7 @@ impl Tool for PlaceTool {
/// Switching tools discards what the cursor holds.
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
self.entries.clear();
self.total = 0;
self.drag = None;
vec![]
}
@@ -399,6 +406,30 @@ mod tests {
assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("pen".into())]);
}
#[test]
fn the_total_is_the_size_of_the_load_until_the_cursor_empties() {
let (d, _) = doc_with_rect();
let (s, p) = (Default::default(), paint());
let c = cx(&d, &s, &p);
let counts = |t: &PlaceTool| (t.options()["count"].clone(), t.options()["total"].clone());
let mut t = loaded(3);
assert_eq!(counts(&t), (json!(3), json!(3)));
t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0));
t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0));
assert_eq!(counts(&t), (json!(2), json!(3)), "a placed file leaves the total");
t.key(&c, ToolKey::Escape, Mods::default());
assert_eq!(counts(&t), (json!(1), json!(3)), "a discarded file leaves the total");
// A new load replaces the total, and an empty cursor has none.
let mut t = loaded(3);
t.set_option("queue", &json!({"entries": [{"params": {"path": "g.png"}, "name": "g.png", "width": 4.0, "height": 2.0}]}));
assert_eq!(counts(&t), (json!(1), json!(1)));
t.key(&c, ToolKey::Escape, Mods::default());
assert_eq!(counts(&t), (json!(0), json!(0)));
let mut t = loaded(2);
t.deactivate(&c);
assert_eq!(counts(&t), (json!(0), json!(0)));
}
#[test]
fn source_indices_survive_removal_in_cursor_requests() {
let (d, _) = doc_with_rect();
+1 -1
View File
@@ -88,7 +88,7 @@ use layers::parallel_map_at_most;
#[cfg(test)]
pub(crate) use layers::shift_probe;
pub use params::{Method, Mode, PRESET_NAMES, Palette, TraceParams, enhanced_preset, preset, presets};
pub use pipeline::{TraceResult, TracedPath, trace, trace_watched, trace_within};
pub use pipeline::{TraceResult, TraceSteps, TracedPath, trace, trace_watched, trace_within};
#[cfg(test)]
use pipeline::{clear_background, label_extents};
#[cfg(test)]
+259 -75
View File
@@ -1,3 +1,4 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use super::layers::{Layers, parallel_map_at_most};
@@ -177,21 +178,255 @@ pub fn trace_watched(
max_anchors: usize,
steps: &(dyn Fn(u64, u64) -> bool + Sync),
) -> Result<TraceResult, TraceError> {
let (w, h) = (img.width as usize, img.height as usize);
if w == 0 || h == 0 || w.checked_mul(h).and_then(|n| n.checked_mul(4)) != Some(img.rgba.len()) {
if !traceable(img) {
return Ok(TraceResult::default());
}
let mut out = trace_paths(img, params, max_anchors, steps)?;
let out = trace_paths(img, params, max_anchors, steps)?;
Ok(grouped(out, img, params))
}
/// Whether `img` has pixels, as many as its size says.
fn traceable(img: &Raster) -> bool {
let (w, h) = (img.width as usize, img.height as usize);
w > 0 && h > 0 && w.checked_mul(h).and_then(|n| n.checked_mul(4)) == Some(img.rgba.len())
}
/// `out` with Auto Grouping's parents (see [`TraceResult::parents`]) when `params` asks for them.
fn grouped(mut out: TraceResult, img: &Raster, params: &TraceParams) -> TraceResult {
if params.auto_grouping {
// Abutting areas cannot overlap; stacked layers, Logo's shapes and stroked lines can.
let stacked = params.method == Method::Overlapping || params.mode == Mode::Logo || params.strokes;
out.parents = group::parents(&out.paths, img.width as usize, img.height as usize, stacked);
}
Ok(out)
out
}
fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<TraceResult, TraceError> {
let (w, h) = (img.width as usize, img.height as usize);
/// How far a trace has got: see [`trace_watched`].
type Steps<'s> = &'s (dyn Fn(u64, u64) -> bool + Sync);
fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: Steps) -> Result<TraceResult, TraceError> {
let p = match prepare(Source::Borrowed(img), params, max_anchors, steps)? {
Begun::Done(out) => return Ok(out),
Begun::Layers(p) => p,
};
if p.stacks() {
let paths = p.job(0).stacked(&p.layers, p.largest(), steps)?;
return Ok((*p).finish_stacked(paths));
}
let traced = {
let job = p.job(0);
// A layer takes about ten bytes a pixel of its box while it is traced (its mask, the labels
// of its components, the stack that fills them, its edges): as many layers at a time as fit
// in half a gigabyte, so that a large image is not traced at the cost of gigabytes.
let at_a_time = ((512 << 20) / (p.largest() * 10)).max(1);
let total = p.layers.len() as u64;
if !steps(0, total) {
return Err(TraceError::Cancelled);
}
// Once stopped, the layers not started yet are skipped.
let (done, stopped) = (AtomicU64::new(0), AtomicBool::new(false));
let traced = parallel_map_at_most(at_a_time, &p.layers, |&(r, ci)| {
if stopped.load(Ordering::Relaxed) {
return None;
}
let paths = job.layer(r, ci);
if !steps(done.fetch_add(1, Ordering::Relaxed) + 1, total) {
stopped.store(true, Ordering::Relaxed);
}
paths
});
if stopped.load(Ordering::Relaxed) {
return Err(TraceError::Cancelled);
}
traced
};
(*p).finish(traced)
}
/// The image a trace works from: borrowed for the length of one call, or shared, for a trace
/// made a part at a time ([`TraceSteps`]).
enum Source<'a> {
Borrowed(&'a Raster),
Shared(Arc<Raster>),
}
impl std::ops::Deref for Source<'_> {
type Target = Raster;
fn deref(&self) -> &Raster {
match self {
Source::Borrowed(img) => img,
Source::Shared(img) => img,
}
}
}
/// A trace with its color layers found and ordered, none of them traced yet.
struct Prepared<'a> {
src: Source<'a>,
/// A copy with a JPEG's block edges (see `deblock`) or a photo's noise (see `smooth`) smoothed
/// away, traced in its place.
smoothed: Option<Raster>,
params: TraceParams,
q: Quantized,
/// Ignore Color, background only: `q.labels` with the background [`TRANSPARENT`].
cleared: Option<Vec<u16>>,
rank: Vec<usize>,
left_out: Vec<bool>,
boxes: Vec<Option<PixelBox>>,
gradients: Vec<Option<TracedGradient>>,
bw_tones: [f64; 2],
/// The layers to trace, bottom first: `(rank, palette entry)`.
layers: Vec<(usize, usize)>,
keep_unmatched: Vec<String>,
keep_ignored: bool,
max_anchors: usize,
}
/// What preparing a trace gives: the whole result (Logo mode), or its layers to trace.
enum Begun<'a> {
Done(TraceResult),
Layers(Box<Prepared<'a>>),
}
impl Prepared<'_> {
/// What tracing one of the layers needs, with `anchors` anchor points made so far.
fn job(&self, anchors: usize) -> Layers<'_> {
Layers {
q: &self.q,
traced: self.cleared.as_deref().unwrap_or(&self.q.labels),
rank: &self.rank,
params: &self.params,
img: self.smoothed.as_ref().unwrap_or(&*self.src),
left_out: self.left_out.clone(),
boxes: self.boxes.clone(),
gradients: &self.gradients,
bw_tones: self.bw_tones,
style: self.params.outline_style(),
w: self.src.width as usize,
h: self.src.height as usize,
anchors: AtomicUsize::new(anchors),
max_anchors: self.max_anchors,
}
}
/// Whether the layers are traced together: Overlapping with Fills fills each shape whole and
/// traces what it encloses again above it (see `Layers::stacked`). Lines (Create Strokes) and
/// outlines (no Fills) are traced a layer at a time.
fn stacks(&self) -> bool {
self.params.method == Method::Overlapping && self.params.fills && !self.params.strokes
}
/// The pixel count of the largest layer's box (at least 1).
fn largest(&self) -> usize {
self.boxes.iter().flatten().map(|b| (b.2 - b.0) * (b.3 - b.1)).max().unwrap_or(1).max(1)
}
/// The result of `paths`, the layers traced together ([`Prepared::stacks`]).
fn finish_stacked(self, paths: Vec<TracedPath>) -> TraceResult {
let mut out = TraceResult { paths, keep_unmatched: self.keep_unmatched, keep_ignored: self.keep_ignored, ..TraceResult::default() };
// The colors used, bottom layer first.
for &(_, ci) in &self.layers {
if let Some(&color) = self.q.palette.get(ci)
&& !out.palette.contains(&color)
&& out.paths.iter().any(|p| p.color == color)
{
out.palette.push(color);
}
}
out
}
/// The result of `traced`, the paths of each of [`Prepared::layers`] in order (`None` for a
/// layer that passed the anchor maximum).
fn finish(self, traced: Vec<Option<Vec<TracedPath>>>) -> Result<TraceResult, TraceError> {
let mut out = TraceResult { keep_unmatched: self.keep_unmatched, keep_ignored: self.keep_ignored, ..TraceResult::default() };
for (paths, &(_, ci)) in traced.into_iter().zip(&self.layers) {
let paths = paths.ok_or(TraceError::TooComplex { max: self.max_anchors })?;
// A layer with no paths adds no color to the palette.
if paths.is_empty() {
continue;
}
out.paths.extend(paths);
let color = self.q.palette[ci];
if !out.palette.contains(&color) {
out.palette.push(color);
}
}
Ok(out)
}
}
/// A trace made a part at a time, for a caller with no thread to trace on that must let other
/// work run between the parts (the web build). The first [`TraceSteps::step`] finds the color
/// layers and each later one traces one layer, bottom first, one at a time (Overlapping with
/// Fills, without Create Strokes, traces all of them in the second step, as its layers are traced
/// together); the result is the one [`trace_within`] gives.
pub struct TraceSteps {
img: Arc<Raster>,
params: TraceParams,
max_anchors: usize,
state: StepState,
}
enum StepState {
Start,
/// The layers found, the paths of those traced so far, and their anchor points.
Layers(Box<Prepared<'static>>, Vec<Option<Vec<TracedPath>>>, usize),
Finished,
}
impl TraceSteps {
/// A trace of `img` with `params` that gives up with [`TraceError::TooComplex`] once the paths
/// have more than `max_anchors` anchor points; nothing is done until [`TraceSteps::step`].
pub fn new(img: Arc<Raster>, params: TraceParams, max_anchors: usize) -> Self {
Self { img, params, max_anchors, state: StepState::Start }
}
/// Does the next part → the result once the last part is done, `None` before it. After the
/// result or an error, each call gives `None`.
pub fn step(&mut self) -> Result<Option<TraceResult>, TraceError> {
let (prepared, mut traced, anchors) = match std::mem::replace(&mut self.state, StepState::Finished) {
StepState::Finished => return Ok(None),
StepState::Start => {
if !traceable(&self.img) {
return Ok(Some(TraceResult::default()));
}
match prepare(Source::Shared(Arc::clone(&self.img)), &self.params, self.max_anchors, &|_, _| true)? {
Begun::Done(out) => return Ok(Some(grouped(out, &self.img, &self.params))),
Begun::Layers(p) if p.layers.is_empty() => return (*p).finish(vec![]).map(|out| Some(grouped(out, &self.img, &self.params))),
Begun::Layers(p) => {
let traced = Vec::with_capacity(p.layers.len());
self.state = StepState::Layers(p, traced, 0);
return Ok(None);
}
}
}
StepState::Layers(p, traced, anchors) => (p, traced, anchors),
};
if prepared.stacks() {
let paths = prepared.job(0).stacked(&prepared.layers, prepared.largest(), &|_, _| true)?;
return Ok(Some(grouped((*prepared).finish_stacked(paths), &self.img, &self.params)));
}
// With every layer traced already the result is finished below.
let mut anchors = anchors;
if let Some(&(r, ci)) = prepared.layers.get(traced.len()) {
let job = prepared.job(anchors);
let paths = job.layer(r, ci);
anchors = job.anchors.load(Ordering::Relaxed);
traced.push(Some(paths.ok_or(TraceError::TooComplex { max: self.max_anchors })?));
}
if traced.len() < prepared.layers.len() {
self.state = StepState::Layers(prepared, traced, anchors);
return Ok(None);
}
(*prepared).finish(traced).map(|out| Some(grouped(out, &self.img, &self.params)))
}
}
/// Finds the color layers of `src` traced with `params` and the order they stack in, telling
/// `steps(0, 0)` after each stage; Logo mode traces the whole image at once.
fn prepare<'a>(src: Source<'a>, params: &TraceParams, max_anchors: usize, steps: Steps) -> Result<Begun<'a>, TraceError> {
let (w, h) = (src.width as usize, src.height as usize);
// The colors Keep Colors traces (checked in every mode).
let listed = params
.keep_colors
@@ -202,7 +437,7 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
let go_on = || if steps(0, 0) { Ok(()) } else { Err(TraceError::Cancelled) };
if params.mode == Mode::Logo {
go_on()?;
return logo::trace_logo(img, params, max_anchors);
return logo::trace_logo(&src, params, max_anchors).map(Begun::Done);
}
// The colour Ignore Color leaves out, if not white.
let ignore = match &params.ignore_color {
@@ -218,12 +453,12 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
// A photo is traced from a copy with its noise smoothed away (see `smooth`); the deblocked copy is
// dropped once it is smoothed.
let photo = |img: &Raster| params.mode != Mode::BlackAndWhite && quantize::continuous_tone(img);
let prepared = match deblock::deblocked(img, strength) {
let smoothed = match deblock::deblocked(&src, strength) {
Some(deblocked) if photo(&deblocked) => Some(smooth::smoothed(&deblocked)),
Some(deblocked) => Some(deblocked),
None => photo(img).then(|| smooth::smoothed(img)),
None => photo(&src).then(|| smooth::smoothed(&src)),
};
let img = prepared.as_ref().unwrap_or(img);
let img = smoothed.as_ref().unwrap_or(&*src);
go_on()?;
// Gradients are found first and kept out of the palette: no colour is spent on bands of them.
// Grayscale finds them in the image's grays (as its flat colours are), so their stops are gray.
@@ -337,75 +572,24 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
.collect();
// Every layer is left out although a listed color matches one: Ignore Color left those out.
let keep_ignored = !listed.is_empty() && layers.is_empty() && order.iter().any(|&ci| is_kept(q.palette[ci], &listed));
let job = Layers {
q: &q,
traced: cleared.as_deref().unwrap_or(&q.labels),
rank: &rank,
let tones = bw_tones(img, &q);
let params = params.clone();
Ok(Begun::Layers(Box::new(Prepared {
src,
smoothed,
params,
img,
q,
cleared,
rank,
left_out,
boxes,
gradients: &gradients,
bw_tones: bw_tones(img, &q),
style: params.outline_style(),
w,
h,
anchors: AtomicUsize::new(0),
gradients,
bw_tones: tones,
layers,
keep_unmatched,
keep_ignored,
max_anchors,
};
let mut out = TraceResult { keep_unmatched, keep_ignored, ..TraceResult::default() };
// A layer takes about ten bytes a pixel of its box while it is traced (its mask, the labels
// of its components, the stack that fills them, its edges): as many layers at a time as fit
// in half a gigabyte, so that a large image is not traced at the cost of gigabytes.
let largest = job.boxes.iter().flatten().map(|b| (b.2 - b.0) * (b.3 - b.1)).max().unwrap_or(1).max(1);
let at_a_time = ((512 << 20) / (largest * 10)).max(1);
// Overlapping with Fills: each shape is filled whole, and what it encloses is traced again above it (see
// `Layers::stacked`). Lines (Create Strokes) and outlines (no Fills) are stacked as they always were.
if params.method == Method::Overlapping && params.fills && !params.strokes {
out.paths = job.stacked(&layers, largest, steps)?;
// The colors used, bottom layer first.
for &(_, ci) in &layers {
if let Some(&color) = q.palette.get(ci)
&& !out.palette.contains(&color)
&& out.paths.iter().any(|p| p.color == color)
{
out.palette.push(color);
}
}
return Ok(out);
}
let total = layers.len() as u64;
if !steps(0, total) {
return Err(TraceError::Cancelled);
}
// Once stopped, the layers not started yet are skipped.
let (done, stopped) = (AtomicU64::new(0), AtomicBool::new(false));
let traced = parallel_map_at_most(at_a_time, &layers, |&(r, ci)| {
if stopped.load(Ordering::Relaxed) {
return None;
}
let paths = job.layer(r, ci);
if !steps(done.fetch_add(1, Ordering::Relaxed) + 1, total) {
stopped.store(true, Ordering::Relaxed);
}
paths
});
if stopped.load(Ordering::Relaxed) {
return Err(TraceError::Cancelled);
}
for (paths, &(_, ci)) in traced.into_iter().zip(&layers) {
let paths = paths.ok_or(TraceError::TooComplex { max: max_anchors })?;
// A layer with no paths adds no color to the palette.
if paths.is_empty() {
continue;
}
out.paths.extend(paths);
let color = q.palette[ci];
if !out.palette.contains(&color) {
out.palette.push(color);
}
}
Ok(out)
})))
}
/// The luminance of white and of black in a Black and White quantisation: what its lightest
+46
View File
@@ -1086,6 +1086,52 @@ fn a_watched_trace_counts_its_layers_and_stops_when_told() {
assert!(matches!(trace_watched(&img, &p, usize::MAX, &|done, _| done == 0), Err(TraceError::Cancelled)));
}
/// A trace made a part at a time finds its layers in the first part and traces one layer a part
/// after it (all of them in the second part for Overlapping with Fills, which stacks them), and
/// gives what one call gives, Auto Grouping, Logo mode and the anchor budget included.
#[test]
fn a_trace_made_a_part_at_a_time_matches_one_made_at_once() {
fn parts(img: &Raster, p: &TraceParams, max: usize) -> (usize, Result<TraceResult, TraceError>) {
let mut s = TraceSteps::new(std::sync::Arc::new(img.clone()), p.clone(), max);
let mut n = 0;
loop {
n += 1;
assert!(n < 1000, "the parts never end");
match s.step() {
Ok(None) => {}
Ok(Some(r)) => return (n, Ok(r)),
Err(e) => return (n, Err(e)),
}
}
}
let img = stripes(120, 8);
let overlapping =
TraceParams { mode: Mode::Color, colors: 16, noise: 1, method: Method::Overlapping, auto_grouping: true, ..TraceParams::default() };
// Overlapping with Fills traces its layers together: one part finds them, the next traces them.
for (p, layered) in [
(TraceParams { mode: Mode::Color, colors: 16, noise: 1, ..TraceParams::default() }, true),
(TraceParams { strokes: true, ..overlapping.clone() }, true),
(overlapping, false),
] {
let at_once = trace_within(&img, &p, usize::MAX).unwrap();
let (n, made) = parts(&img, &p, usize::MAX);
assert_eq!(made.unwrap(), at_once, "{p:?}");
assert!(at_once.palette.len() > 1, "{} colors", at_once.palette.len());
assert!(if layered { n > 2 } else { n == 2 }, "{n} parts for {} colors, {p:?}", at_once.palette.len());
}
let logo = TraceParams { mode: Mode::Logo, ..TraceParams::default() };
let round = disc(64, 32.0, 32.0, 20.0);
let (n, made) = parts(&round, &logo, usize::MAX);
assert_eq!((n, made.unwrap()), (1, trace_within(&round, &logo, usize::MAX).unwrap()), "Logo mode is one part");
let p = TraceParams { mode: Mode::Color, colors: 16, noise: 1, ..TraceParams::default() };
let anchors = trace(&img, &p).anchor_count();
assert!(matches!(parts(&img, &p, anchors / 2).1, Err(TraceError::TooComplex { max }) if max == anchors / 2));
assert_eq!(parts(&img, &p, anchors).1.unwrap(), trace(&img, &p));
let mut done = TraceSteps::new(std::sync::Arc::new(Raster::from_fn(0, 0, |_, _| WHITE)), p, usize::MAX);
assert_eq!(done.step().unwrap(), Some(TraceResult::default()), "an empty image");
assert_eq!(done.step().unwrap(), None, "nothing after the result");
}
/// Layers traced in parallel come out in the same order every time: bottom (largest) first.
#[test]
fn parallel_layers_keep_their_order() {
+10 -10
View File
@@ -89,16 +89,16 @@ pub fn menu() -> Vec<Node> {
]
}
static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None };
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None };
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None };
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None };
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None };
static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None };
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None };
static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None };
static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None };
static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None, pin_opening_artboard: false };
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None, pin_opening_artboard: false };
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None, pin_opening_artboard: false };
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None, pin_opening_artboard: false };
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None, pin_opening_artboard: false };
static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None, pin_opening_artboard: false };
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None, pin_opening_artboard: false };
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None, pin_opening_artboard: false };
static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None, pin_opening_artboard: false };
static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None, pin_opening_artboard: false };
/// The dialog over `rows`, titled by the heading of `command`.
fn dialog<'a>(command: &str, rows: Vec<Param>) -> ParamDialog<'a> {
@@ -298,6 +298,28 @@ fn add_artboard_guides_does_not_replace_a_deleted_artboard_with_its_neighbor() {
}
}
#[test]
fn add_artboard_guides_preview_keeps_an_artboard_deleted_while_it_shows() {
let (mut app, _, _) = app();
app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
app.view_mut().unwrap().artboard = 0;
click(&mut app, "Add Artboard Guides…");
let id = host::dialog_id(&app);
host::set(&app, id, "preview", json!(true));
host::frame(&mut app);
assert_eq!(artboard_guides(&app).len(), 1);
app.run("artboard.delete", json!({"index": 0})).unwrap();
assert!(artboard_guides(&app).is_empty(), "the remaining artboard gets no guide");
host::frame(&mut app);
assert_eq!(app.session.doc().unwrap().doc.artboards.len(), 1);
assert!(artboard_guides(&app).is_empty());
assert!(host::confirm(&app, id));
host::frame(&mut app);
assert_eq!(app.session.doc().unwrap().doc.artboards.len(), 1);
assert!(artboard_guides(&app).is_empty());
assert_eq!(app.ui.status, "The artboard no longer exists.");
}
#[test]
fn artboard_guides_menu_dialog_is_available_without_a_selection() {
let (mut app, _, _) = app();
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff. Show more