mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 19:51:26 -05:00
Merge main into feat/color-palette-strip
# Conflicts: # crates/ui-egui/src/panels/swatches.rs
This commit is contained in:
Generated
+1
@@ -8792,6 +8792,7 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-geom 0.25.1",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
@@ -140,7 +140,8 @@ mod platform {
|
||||
let (rect, monitor, work) = ((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom));
|
||||
// The taskbars are looked up (a few `FindWindowEx` calls) only while the window covers its
|
||||
// whole monitor, which it no longer does once trimmed.
|
||||
let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work).or_else(|| {
|
||||
let frame = super::frame_limit(hwnd.GetDpiForWindow());
|
||||
let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work, frame).or_else(|| {
|
||||
super::covers(rect, monitor).then(|| super::short_of_autohide_taskbars(rect, monitor, work, &taskbar_edges(monitor))).flatten()
|
||||
}) else {
|
||||
return;
|
||||
@@ -238,21 +239,29 @@ impl<H> Viewports<H> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
const FRAME: i32 = 32;
|
||||
/// How far, in physical pixels at 96 DPI (100 %), a parked maximize reaches past a monitor or
|
||||
/// work-area edge at most: the resize border is about 8 px at 100 %. Past that, a maximized
|
||||
/// window's rect is not parked but being dragged or snapped, and is left alone.
|
||||
const FRAME_AT_96_DPI: i32 = 32;
|
||||
|
||||
/// [`FRAME_AT_96_DPI`] for a window at `dpi`, which the resize border grows with; never less than
|
||||
/// at 96 DPI, so an unknown DPI (0) counts as 100 %.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
fn frame_limit(dpi: u32) -> i32 {
|
||||
let scaled = i64::from(FRAME_AT_96_DPI) * i64::from(dpi) / 96;
|
||||
i32::try_from(scaled).unwrap_or(i32::MAX).max(FRAME_AT_96_DPI)
|
||||
}
|
||||
|
||||
/// The rect to move a maximize to so it stays inside the work area on every edge, plus the resize
|
||||
/// border it was parked with, or `None` when it already does or `rect` (`left, top, right,
|
||||
/// bottom`, desktop coordinates) is not parked at its maximize place. `monitor` is the monitor's
|
||||
/// full rect and `work` its work area (the monitor less the taskbar) in the same coordinates. The
|
||||
/// border is read from the edges that have no taskbar, and every edge must sit that far outside
|
||||
/// either the monitor (where Windows puts a caption-less maximize) or the work area (where the
|
||||
/// guard puts it), so a rect it already moved is left alone. Platform-neutral so it is tested
|
||||
/// everywhere.
|
||||
/// full rect and `work` its work area (the monitor less the taskbar) in the same coordinates;
|
||||
/// `frame` is the largest border a parked maximize has ([`frame_limit`]). The border is read from
|
||||
/// the edges that have no taskbar, and every edge must sit that far outside either the monitor
|
||||
/// (where Windows puts a caption-less maximize) or the work area (where the guard puts it), so a
|
||||
/// rect it already moved is left alone. Platform-neutral so it is tested everywhere.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> {
|
||||
fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32), frame: i32) -> Option<(i32, i32, i32, i32)> {
|
||||
let (l, t, r, b) = rect;
|
||||
let (ml, mt, mr, mb) = monitor;
|
||||
let (wl, wt, wr, wb) = work;
|
||||
@@ -269,7 +278,7 @@ fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work:
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|n| (0..=FRAME).contains(n))
|
||||
.filter(|n| (0..=frame).contains(n))
|
||||
.min()?;
|
||||
let parked = |monitor: Option<i32>, work: Option<i32>| monitor == Some(border) || work == Some(border);
|
||||
if !parked(ml.checked_sub(l), wl.checked_sub(l))
|
||||
@@ -304,9 +313,11 @@ fn covers(rect: Rect, monitor: Rect) -> bool {
|
||||
}
|
||||
|
||||
/// The edge of `monitor` that a taskbar with the rect `taskbar` sits on: the edge nearest the
|
||||
/// taskbar's center, or `None` when the taskbar does not overlap the monitor. An auto-hidden
|
||||
/// taskbar is parked mostly past its edge with a sliver left on the monitor, so its center can lie
|
||||
/// outside the monitor.
|
||||
/// taskbar's center, or `None` when the taskbar is not this monitor's. A shown taskbar lies wholly
|
||||
/// on its monitor. An auto-hidden taskbar is parked mostly past its edge with a sliver left on the
|
||||
/// monitor, so its center can lie outside the monitor; the part past the edge can lie on a
|
||||
/// neighboring monitor, which a taskbar that is neither wholly on the monitor nor mostly off it
|
||||
/// belongs to.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option<Edge> {
|
||||
let (tl, tt, tr, tb) = (i64::from(taskbar.0), i64::from(taskbar.1), i64::from(taskbar.2), i64::from(taskbar.3));
|
||||
@@ -314,6 +325,12 @@ fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option<Edge> {
|
||||
if tl >= tr || tt >= tb || ml >= mr || mt >= mb || tr <= ml || tl >= mr || tb <= mt || tt >= mb {
|
||||
return None;
|
||||
}
|
||||
let inside = tl >= ml && tt >= mt && tr <= mr && tb <= mb;
|
||||
let area = |l: i64, t: i64, r: i64, b: i64| i128::from(r - l) * i128::from(b - t);
|
||||
let on_monitor = area(tl.max(ml), tt.max(mt), tr.min(mr), tb.min(mb));
|
||||
if !inside && on_monitor * 2 >= area(tl, tt, tr, tb) {
|
||||
return None;
|
||||
}
|
||||
// The center and the distances are doubled, so nothing is rounded.
|
||||
let (cx, cy) = (tl + tr, tt + tb);
|
||||
[(Edge::Left, cx - 2 * ml), (Edge::Top, cy - 2 * mt), (Edge::Right, 2 * mr - cx), (Edge::Bottom, 2 * mb - cy)]
|
||||
@@ -346,7 +363,12 @@ fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: &
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Edge, Viewports, clamped_rect, short_of_autohide_taskbars, taskbar_edge};
|
||||
use super::{Edge, Viewports, frame_limit, short_of_autohide_taskbars, taskbar_edge};
|
||||
|
||||
/// [`super::clamped_rect`] for a window at 96 DPI (100 %).
|
||||
fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> {
|
||||
super::clamped_rect(rect, monitor, work, frame_limit(96))
|
||||
}
|
||||
|
||||
fn viewport(name: &str) -> egui::ViewportId {
|
||||
egui::ViewportId::from_hash_of(name)
|
||||
@@ -453,6 +475,22 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_frame_limit_grows_with_the_monitor_dpi() {
|
||||
// At 500 % (480 DPI) the resize border is about 40 px, past the limit at 100 %.
|
||||
let (monitor, work) = ((0, 0, 3840, 2160), (0, 0, 3840, 2000));
|
||||
let rect = (-40, -40, 3880, 2200);
|
||||
assert_eq!(clamped_rect(rect, monitor, work), None, "100 %");
|
||||
let Some(clamped) = super::clamped_rect(rect, monitor, work, frame_limit(480)) else {
|
||||
panic!("500 %: the maximized frame is not clamped");
|
||||
};
|
||||
assert_eq!((clamped.0, clamped.1, clamped.2), (rect.0, rect.1, rect.2), "500 %: only the bottom edge moves");
|
||||
assert_eq!(clamped.3 - work.3, monitor.1 - rect.1, "500 %: the bottom border hangs below the work area as the top one above the monitor");
|
||||
assert_eq!(super::clamped_rect((-8, -8, 1928 + 40, 1088), (0, 0, 1920, 1080), (0, 0, 1920, 1046), frame_limit(96)), None, "past the limit");
|
||||
assert_eq!(frame_limit(0), frame_limit(96), "an unknown DPI counts as 100 %");
|
||||
assert!(frame_limit(u32::MAX) > frame_limit(480), "no overflow");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_maximize_without_a_reserved_taskbar_is_left_alone() {
|
||||
let monitor = (0, 0, 1920, 1080);
|
||||
@@ -503,6 +541,12 @@ mod tests {
|
||||
assert_eq!(taskbar_edge((-60, 0, 2, 1080), monitor), Some(Edge::Left));
|
||||
assert_eq!(taskbar_edge((1918, 0, 1980, 1080), monitor), Some(Edge::Right));
|
||||
assert_eq!(taskbar_edge((1920, 1032, 3840, 1080), monitor), None, "other monitor");
|
||||
// With monitors stacked, the part of the upper monitor's auto-hidden taskbar parked past its
|
||||
// bottom edge lies on the monitor below, which it does not belong to.
|
||||
let below = (0, 1080, 1920, 2160);
|
||||
assert_eq!(taskbar_edge((0, 1078, 1920, 1126), below), None, "neighbor's auto-hidden taskbar");
|
||||
assert_eq!(taskbar_edge((0, 2158, 1920, 2206), below), Some(Edge::Bottom), "its own auto-hidden taskbar");
|
||||
assert_eq!(taskbar_edge((0, 1080, 1920, 1128), below), Some(Edge::Top), "its own shown top taskbar");
|
||||
assert!(taskbar_edge((i32::MIN, i32::MIN, i32::MAX, i32::MAX), monitor).is_some(), "no overflow");
|
||||
}
|
||||
}
|
||||
|
||||
+113
-2
@@ -62,9 +62,72 @@ pub fn use_own_worker_for(limit: std::time::Duration) {
|
||||
/// The largest DXF rendition kept for the next read of the same drawing (128 MiB).
|
||||
const MAX_KEPT: usize = 128 << 20;
|
||||
|
||||
/// Is `bytes` a DWG drawing (an `AC10nn` version code first)?
|
||||
/// Is `bytes` a DWG drawing (an `AC10nn` or `AD10nn` version code first)?
|
||||
pub fn is_dwg(bytes: &[u8]) -> bool {
|
||||
craft_dwg::is_dwg(bytes)
|
||||
craft_dwg::is_dwg(bytes) || craft_dwg::is_dwg(&ac_code(bytes))
|
||||
}
|
||||
|
||||
/// The first six bytes of `bytes`, with an `AD10` start read as `AC10`.
|
||||
fn ac_code(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut head = bytes.get(..bytes.len().min(7)).unwrap_or(bytes).to_vec();
|
||||
if head.starts_with(b"AD10") {
|
||||
head[1] = b'C';
|
||||
}
|
||||
head
|
||||
}
|
||||
|
||||
/// The version codes of DWG drawings and the name of each version, oldest first
|
||||
/// (<https://en.wikipedia.org/wiki/.dwg#Version_history>).
|
||||
const VERSIONS: [(&str, &str); 21] = [
|
||||
("MC0.0", "R1.0"),
|
||||
("AC1.2", "R1.2"),
|
||||
("AC1.40", "R1.40"),
|
||||
("AC1.50", "R2.05"),
|
||||
("AC2.10", "R2.10"),
|
||||
("AC2.21", "R2.21"),
|
||||
("AC2.22", "R2.22"),
|
||||
("AC1001", "R2.22"),
|
||||
("AC1002", "R2.50"),
|
||||
("AC1003", "R2.60"),
|
||||
("AC1004", "R9"),
|
||||
("AC1006", "R10"),
|
||||
("AC1009", "R11/12"),
|
||||
("AC1012", "R13"),
|
||||
("AC1014", "R14"),
|
||||
("AC1015", "2000"),
|
||||
("AC1018", "2004"),
|
||||
("AC1021", "2007"),
|
||||
("AC1024", "2010"),
|
||||
("AC1027", "2013"),
|
||||
("AC1032", "2018"),
|
||||
];
|
||||
|
||||
/// The version codes the DWG reader reads, each also with `AD` in place of `AC` except `AC1006`.
|
||||
const READS: [&str; 10] = ["AC1006", "AC1009", "AC1012", "AC1014", "AC1015", "AC1018", "AC1021", "AC1024", "AC1027", "AC1032"];
|
||||
|
||||
/// Why `bytes` can't be read when they start with a DWG version code that the DWG reader does
|
||||
/// not read: the message names the version and says to save the drawing as DXF or as a DWG
|
||||
/// version that is read. `None` for any other bytes, a DWG drawing of a version that is read
|
||||
/// included.
|
||||
pub fn unreadable(bytes: &[u8]) -> Option<String> {
|
||||
let head = ac_code(bytes);
|
||||
let numbered = head.starts_with(b"AC10");
|
||||
if !numbered && ![&b"MC0."[..], b"AC1.", b"AC2."].iter().any(|m| head.starts_with(m)) {
|
||||
return None;
|
||||
}
|
||||
if numbered && READS.iter().any(|c| head.starts_with(c.as_bytes())) && !bytes.starts_with(b"AD1006") {
|
||||
return None;
|
||||
}
|
||||
let named = match VERSIONS.iter().find(|(c, _)| head.starts_with(c.as_bytes())) {
|
||||
Some((code, name)) => format!("DWG {name} ({})", if bytes.starts_with(b"AD") { code.replacen("AC", "AD", 1) } else { code.to_string() }),
|
||||
None => {
|
||||
let shown: String = bytes.iter().take(6).take_while(|b| b.is_ascii_graphic()).map(|&b| char::from(b)).collect();
|
||||
format!("DWG version {shown}")
|
||||
}
|
||||
};
|
||||
Some(format!(
|
||||
"this drawing is {named}, a DWG version VectorCraft can't read: save it from the CAD app as a DXF, or as a DWG from R10 to 2018, and open that"
|
||||
))
|
||||
}
|
||||
|
||||
/// A DWG drawing as DXF bytes, and what the conversion left out.
|
||||
@@ -173,6 +236,9 @@ pub fn hold(bytes: &[u8]) -> Result<Held, String> {
|
||||
}
|
||||
|
||||
fn convert(bytes: &[u8]) -> Result<Converted, String> {
|
||||
if let Some(why) = unreadable(bytes) {
|
||||
return Err(why);
|
||||
}
|
||||
let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(|e| worded(&e))?;
|
||||
Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() })
|
||||
}
|
||||
@@ -278,4 +344,49 @@ mod tests {
|
||||
let n = worded("DWG: 2 objects of types this bridge can't preserve were left out (X × 2); saving over the original file would lose them");
|
||||
assert_eq!(n, "DWG: 2 objects of types VectorCraft can't read were left out (X × 2)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_version_the_reader_skips_is_named_with_what_to_save_it_as() {
|
||||
let named = [
|
||||
(&b"AC1001\x00\x00\x00\x00"[..], "DWG R2.22 (AC1001)"),
|
||||
(b"AD1006\x00\x00\x00\x00", "DWG R10 (AD1006)"),
|
||||
(b"AD1004\x00\x00\x00\x00", "DWG R9 (AD1004)"),
|
||||
(b"AC1.50\x00\x00\x00\x00", "DWG R2.05 (AC1.50)"),
|
||||
(b"AC1.2\x00\x00\x00\x00", "DWG R1.2 (AC1.2)"),
|
||||
(b"MC0.0\x00\x00\x00\x00", "DWG R1.0 (MC0.0)"),
|
||||
(b"AC1033\x00\x00\x00\x00", "DWG version AC1033"),
|
||||
(b"AC1010\x00\x00\x00\x00", "DWG version AC1010"),
|
||||
(b"AC10\x00\x00\x00\x00", "DWG version AC10"),
|
||||
];
|
||||
for (bytes, name) in named {
|
||||
let why = unreadable(bytes).unwrap_or_default();
|
||||
assert!(why.starts_with(&format!("this drawing is {name},")), "{name}: {why}");
|
||||
assert!(why.contains("as a DXF, or as a DWG from R10 to 2018"), "{why}");
|
||||
}
|
||||
for read in [
|
||||
&b"AC1006\x00\x00"[..],
|
||||
b"AC1009\x00\x00",
|
||||
b"AD1009\x00\x00",
|
||||
b"AC1018\x00\x00",
|
||||
b"AC1032\x00\x00",
|
||||
b"AD1015\x00\x00",
|
||||
b"0\nSECTION\n",
|
||||
b"AC",
|
||||
b"",
|
||||
] {
|
||||
assert_eq!(unreadable(read), None, "{:?}", String::from_utf8_lossy(read));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ad_version_code_is_a_dwg_drawing() {
|
||||
assert!(is_dwg(b"AD1018\x00\x00") && is_dwg(b"AC1018\x00\x00"));
|
||||
assert!(!is_dwg(b"AD10\x00\x00\x00") && !is_dwg(b"AD1018") && !is_dwg(b"0\nSECTION\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_version_the_reader_skips_is_refused_before_converting() {
|
||||
let e = hold(b"AC1004\x00\x00\x00\x00").unwrap_err();
|
||||
assert!(e.starts_with("this drawing is DWG R9 (AC1004),"), "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
//! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred
|
||||
//! 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, 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),
|
||||
//! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid and
|
||||
//! gradient hatches, pattern hatches' lines, solids and regions become paths; text and multiline
|
||||
//! text point type; named blocks symbols
|
||||
//! (anonymous ones, such as dimensions, groups of their art); raster images linked images of the
|
||||
//! files they name, clipped by their clip boundaries. 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.
|
||||
//!
|
||||
@@ -15,6 +17,7 @@
|
||||
//! blocks and layouts.
|
||||
//! - `entity`: entities to items (geometry and properties).
|
||||
//! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths.
|
||||
//! - `hatch`: pattern hatches' lines and gradient hatches' fills.
|
||||
//! - `text`: text values to plain text.
|
||||
//! - `acis`: a region's solid-modeler data as its outline.
|
||||
//! - `build`: items to the document.
|
||||
@@ -23,6 +26,7 @@ mod acis;
|
||||
mod build;
|
||||
mod curve;
|
||||
mod entity;
|
||||
mod hatch;
|
||||
mod reader;
|
||||
mod text;
|
||||
|
||||
@@ -108,15 +112,18 @@ pub fn is_dxf(bytes: &[u8]) -> bool {
|
||||
/// The tags of a DXF file, or of a DWG file converted to DXF ([`crate::dwg`]), and what the read
|
||||
/// left out: where the file is damaged, and what the DWG conversion couldn't read.
|
||||
fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Vec<String>), String> {
|
||||
if let Some(why) = crate::dwg::unreadable(bytes) {
|
||||
return Err(why);
|
||||
}
|
||||
if crate::dwg::is_dwg(bytes) {
|
||||
let converted = crate::dwg::to_dxf(bytes)?;
|
||||
let (tags, mut notes) = dxf_tags(&converted.dxf)?;
|
||||
notes.extend(converted.notes.iter().cloned());
|
||||
return Ok((tags, notes));
|
||||
}
|
||||
// R1.x and R2.x drawings (MC0.0, AC1.2 to AC2.10), and an AC10 header with no version number.
|
||||
if [&b"AC10"[..], b"AC1.", b"AC2.", b"MC0."].iter().any(|magic| bytes.starts_with(magic)) {
|
||||
return Err("this DWG drawing's version can't be read: save it from the CAD app as a DXF and open that".into());
|
||||
// A DWG version code with nothing after it.
|
||||
if [&b"AC10"[..], b"AD10"].iter().any(|magic| bytes.starts_with(magic)) {
|
||||
return Err("DWG: the file is cut short".into());
|
||||
}
|
||||
dxf_tags(bytes)
|
||||
}
|
||||
@@ -240,4 +247,6 @@ mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_dwg;
|
||||
#[cfg(test)]
|
||||
mod tests_image;
|
||||
#[cfg(test)]
|
||||
mod tests_region;
|
||||
|
||||
+578
-27
@@ -7,13 +7,17 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::BezPath;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Dash, Document, LAYER_COLORS, LayerColor, LineCap, Node, NodeKind, Symbol, TextObject};
|
||||
use kurbo::{BezPath, PathEl};
|
||||
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, CharStyle, Dash, Document, ImageBlob, ImageObject, LAYER_COLORS, LayerColor, LineCap, LinkInfo, Node, NodeKind,
|
||||
Symbol, TextObject,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect};
|
||||
|
||||
use super::ImportOptions;
|
||||
use super::entity::{Alpha, Col, Converter, Geom, InsertItem, Item, Lw, Props, Span, TextItem};
|
||||
use super::entity::{Alpha, Col, Converter, Geom, ImageItem, InsertItem, Item, Lw, Props, Shade, Span, TextItem};
|
||||
use super::hatch::{Grad, Second};
|
||||
use super::reader::{Drawing, LayoutDef};
|
||||
use crate::{CAP_HEIGHT, MAX_NEST};
|
||||
|
||||
@@ -22,7 +26,7 @@ const PT_PER_MM: f64 = 72.0 / 25.4;
|
||||
/// The stroke weight of lineweight 0 (CAD apps draw it one device pixel wide), in points.
|
||||
const THINNEST: f64 = 0.25;
|
||||
/// The most objects an import makes.
|
||||
const MAX_NODES: usize = 2_000_000;
|
||||
const MAX_NODES: usize = if cfg!(test) { 100_000 } else { 2_000_000 };
|
||||
/// The most block work an import does, whatever it produces: one per insert copy drawn, and one
|
||||
/// 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 };
|
||||
@@ -38,6 +42,9 @@ const MAX_TEXT_BYTES: usize = if cfg!(test) { 64 << 10 } else { 64 << 20 };
|
||||
const MAX_FAMILY_BYTES: usize = 256;
|
||||
/// How far from the origin art may lie (points): the canvas.
|
||||
pub(crate) const MAX_EXTENT: f64 = 4.0e6;
|
||||
/// How far from a symbol's origin its image clip points may lie (points): as far as an insert at
|
||||
/// the smallest scale it accepts (1e-12) still brings back onto the canvas.
|
||||
const MAX_SYMBOL_EXTENT: f64 = MAX_EXTENT * 1e12;
|
||||
|
||||
const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are left out";
|
||||
const XREFS: &str = "blocks referencing other drawings (external references) are left out";
|
||||
@@ -46,6 +53,27 @@ const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points:
|
||||
const TOO_MUCH_BLOCK_WORK: &str = "the drawing's blocks take too much work to place: the rest are left out";
|
||||
const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid";
|
||||
const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out";
|
||||
const NO_IMAGE_FILE: &str = "images that name no image file are left out";
|
||||
const FAR_CLIPS: &str = "images whose clip boundaries reach out of range are left out";
|
||||
const IMAGE_SIZE: &str = "images with no size in pixels, or more than 1,048,576 pixels a side, are left out";
|
||||
/// The most pixels an image may have a side.
|
||||
const MAX_IMAGE_SIDE: f64 = 1_048_576.0;
|
||||
/// The key of the image data of the images showing the file at a path: the placeholder, until
|
||||
/// the file is read.
|
||||
const IMAGE_KEY: &str = "dxf-image-";
|
||||
|
||||
/// How a path paints.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Look<'g> {
|
||||
/// Stroked at its width or lineweight, in its linetype.
|
||||
Line,
|
||||
/// Filled with its color.
|
||||
Fill,
|
||||
/// Filled with a gradient hatch's gradient.
|
||||
Gradient(&'g Grad),
|
||||
/// Pattern hatch lines: stroked without the linetype; `dots` take round caps.
|
||||
Pattern { dots: bool },
|
||||
}
|
||||
|
||||
/// What a block's art takes from the insert that places it: its colour, lineweight, linetype
|
||||
/// and opacity where the art says "by block", and its layer for art on layer 0.
|
||||
@@ -58,6 +86,35 @@ struct Inherit {
|
||||
layer: Option<String>,
|
||||
}
|
||||
|
||||
/// Objects, path elements, dash lengths and text bytes taken from the import's limits.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct Cost {
|
||||
nodes: usize,
|
||||
elements: usize,
|
||||
dash_values: usize,
|
||||
text_bytes: usize,
|
||||
}
|
||||
|
||||
impl Cost {
|
||||
fn minus(self, o: Cost) -> Cost {
|
||||
Cost {
|
||||
nodes: self.nodes.saturating_sub(o.nodes),
|
||||
elements: self.elements.saturating_sub(o.elements),
|
||||
dash_values: self.dash_values.saturating_sub(o.dash_values),
|
||||
text_bytes: self.text_bytes.saturating_sub(o.text_bytes),
|
||||
}
|
||||
}
|
||||
|
||||
fn plus(self, o: Cost) -> Cost {
|
||||
Cost {
|
||||
nodes: self.nodes.saturating_add(o.nodes),
|
||||
elements: self.elements.saturating_add(o.elements),
|
||||
dash_values: self.dash_values.saturating_add(o.dash_values),
|
||||
text_bytes: self.text_bytes.saturating_add(o.text_bytes),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Build<'d, 'a> {
|
||||
d: &'d Drawing<'a>,
|
||||
o: &'d ImportOptions,
|
||||
@@ -74,6 +131,21 @@ pub(crate) struct Build<'d, 'a> {
|
||||
next_suffix: HashMap<String, usize>,
|
||||
/// Blocks being drawn, outermost first.
|
||||
stack: Vec<String>,
|
||||
/// How many symbols' art is being drawn: above 0, art is in a symbol's own space.
|
||||
in_symbol: u32,
|
||||
/// The box of the image clip points in the symbol being drawn, in its own space, and of each
|
||||
/// symbol made (none: its art has no clips).
|
||||
clip_reach: Option<Rect>,
|
||||
symbol_reach: HashMap<String, Rect>,
|
||||
/// What each symbol's own art took from the limits (not the symbols made while drawing it),
|
||||
/// how many instances place each symbol, and what the symbols made inside the one being
|
||||
/// drawn took.
|
||||
symbol_cost: HashMap<String, Cost>,
|
||||
uses: HashMap<String, usize>,
|
||||
nested: Cost,
|
||||
/// Each symbol's place in the document's symbols, and the symbols whose art was taken out.
|
||||
symbol_slot: HashMap<String, usize>,
|
||||
empty: HashSet<String>,
|
||||
/// Document space per drawing unit, and its symbols' (no translation).
|
||||
map: Affine,
|
||||
symbol_map: Affine,
|
||||
@@ -137,6 +209,14 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
symbol_names: HashSet::new(),
|
||||
next_suffix: HashMap::new(),
|
||||
stack: vec![],
|
||||
in_symbol: 0,
|
||||
clip_reach: None,
|
||||
symbol_reach: HashMap::new(),
|
||||
symbol_cost: HashMap::new(),
|
||||
uses: HashMap::new(),
|
||||
symbol_slot: HashMap::new(),
|
||||
empty: HashSet::new(),
|
||||
nested: Cost::default(),
|
||||
map: Affine::IDENTITY,
|
||||
symbol_map: Affine::IDENTITY,
|
||||
lw_scale: 1.0,
|
||||
@@ -169,6 +249,72 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the import has taken from its limits so far.
|
||||
fn cost(&self) -> Cost {
|
||||
Cost { nodes: self.nodes, elements: self.elements, dash_values: self.dash_values, text_bytes: self.text_bytes }
|
||||
}
|
||||
|
||||
fn set_cost(&mut self, c: Cost) {
|
||||
self.nodes = c.nodes;
|
||||
self.elements = c.elements;
|
||||
self.dash_values = c.dash_values;
|
||||
self.text_bytes = c.text_bytes;
|
||||
}
|
||||
|
||||
/// Take symbol `name`'s art out when no instance places it, giving back its share of the limits
|
||||
/// and its art's instances of other symbols (and in turn those that no instance places any
|
||||
/// more); the art, when it was taken. The symbol stays empty until [`Self::restore`] puts the
|
||||
/// art back or [`Self::symbol`] draws it again, and is dropped at the end if still empty.
|
||||
fn take_unused(&mut self, name: &str) -> Option<Arc<Node>> {
|
||||
let first = self.take_art(name)?;
|
||||
// A worklist, not recursion: chains of symbols can be long.
|
||||
let mut todo = placed_symbols(&first);
|
||||
while let Some(s) = todo.pop() {
|
||||
if let Some(n) = self.uses.get_mut(&s) {
|
||||
*n = n.saturating_sub(1);
|
||||
}
|
||||
if let Some(art) = self.take_art(&s) {
|
||||
todo.extend(placed_symbols(&art));
|
||||
}
|
||||
}
|
||||
Some(first)
|
||||
}
|
||||
|
||||
/// Symbol `name`'s art, taken out with its share of the limits when no instance places it.
|
||||
fn take_art(&mut self, name: &str) -> Option<Arc<Node>> {
|
||||
if self.uses.get(name).is_some_and(|n| *n > 0) || self.empty.contains(name) {
|
||||
return None;
|
||||
}
|
||||
let i = *self.symbol_slot.get(name)?;
|
||||
let id = self.doc.alloc_id();
|
||||
let art = std::mem::replace(&mut self.doc.symbols.get_mut(i)?.art, Arc::new(Node::group(id, vec![])));
|
||||
self.set_cost(self.cost().minus(self.symbol_cost.get(name).copied().unwrap_or_default()));
|
||||
self.empty.insert(name.to_string());
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// Put `art`, taken from symbol `name` by [`Self::take_unused`], back, charging its share of
|
||||
/// the limits again; false (nothing changed) when that share no longer fits.
|
||||
fn restore(&mut self, name: &str, art: Arc<Node>) -> bool {
|
||||
let t = self.cost().plus(self.symbol_cost.get(name).copied().unwrap_or_default());
|
||||
let inner = placed_symbols(&art);
|
||||
// Its instances of symbols that are empty now need those drawn again.
|
||||
let fits = t.nodes < MAX_NODES && t.elements <= MAX_ELEMENTS && t.dash_values <= MAX_DASH_VALUES && t.text_bytes <= MAX_TEXT_BYTES;
|
||||
if !fits || inner.iter().any(|s| self.empty.contains(s)) {
|
||||
return false;
|
||||
}
|
||||
let Some(slot) = self.symbol_slot.get(name).and_then(|i| self.doc.symbols.get_mut(*i)) else {
|
||||
return false;
|
||||
};
|
||||
slot.art = art;
|
||||
self.set_cost(t);
|
||||
self.empty.remove(name);
|
||||
for s in inner {
|
||||
*self.uses.entry(s).or_default() += 1;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Import `layout`; `natural` and `ratio` are points per drawing unit in the drawing's own
|
||||
/// unit and at the scale asked for (fitting computes its own).
|
||||
pub fn run(mut self, layout: &LayoutDef, natural: f64, ratio: f64) -> Result<(Document, Vec<String>), String> {
|
||||
@@ -183,6 +329,7 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
if !layers.is_empty() {
|
||||
doc.layers = layers;
|
||||
}
|
||||
drop_unplaced_symbols(&mut doc);
|
||||
if let Some(a) = doc.artboards.first_mut() {
|
||||
a.rect = Rect::from_origin_size(Point::ZERO, size);
|
||||
}
|
||||
@@ -291,7 +438,7 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
/// An item's bounds in world coordinates (type: an estimate from its height and length).
|
||||
fn item_bounds(&mut self, it: &Item, depth: u32) -> Option<Rect> {
|
||||
match &it.geom {
|
||||
Geom::Path { bp, .. } => super::curve::bounds(bp),
|
||||
Geom::Path { bp, .. } | Geom::Shaded { bp, .. } => super::curve::bounds(bp),
|
||||
Geom::Text(t) => {
|
||||
let lines = t.text.lines().count().max(1) as f64;
|
||||
let longest = t.text.lines().map(|l| l.chars().count()).max().unwrap_or(0) as f64;
|
||||
@@ -314,6 +461,14 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
let attribs: Vec<Option<Rect>> = ins.attribs.iter().map(|a| self.item_bounds(a, depth)).collect();
|
||||
cells.map(Some).chain(attribs).fold(None, vectorcraft_geom::union_opt)
|
||||
}
|
||||
Geom::Image(im) => {
|
||||
self.image_file(im)?;
|
||||
let (w, h) = self.image_size(im)?;
|
||||
let place = im.placement(h);
|
||||
let whole = place.transform_rect_bbox(Rect::new(0.0, 0.0, w, h));
|
||||
let clip = im.clip.as_ref().and_then(|c| c.iter().map(|p| place * *p).map(|p| Rect::from_points(p, p)).reduce(|a, b| a.union(b)));
|
||||
Some(clip.map_or(whole, |c| c.intersect(whole)))
|
||||
}
|
||||
}
|
||||
.filter(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()))
|
||||
}
|
||||
@@ -331,8 +486,17 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
for it in items.iter() {
|
||||
let p = &it.props;
|
||||
let on_zero = p.layer == "0";
|
||||
s |= p.color == Col::ByBlock || p.lineweight == Lw::ByBlock || p.linetype == "BYBLOCK" || p.alpha == Alpha::ByBlock;
|
||||
s |= on_zero && (p.color == Col::ByLayer || p.lineweight == Lw::ByLayer || p.linetype == "BYLAYER");
|
||||
// Fills draw no stroke, and pattern lines carry their own dashes.
|
||||
let filled = matches!(&it.geom, Geom::Path { fill: true, .. } | Geom::Shaded { shade: Shade::Gradient(_), .. });
|
||||
let stroked = !filled;
|
||||
let in_linetype = !filled && !matches!(&it.geom, Geom::Shaded { shade: Shade::Pattern { .. }, .. });
|
||||
s |= p.color == Col::ByBlock || p.alpha == Alpha::ByBlock;
|
||||
s |= (stroked && p.lineweight == Lw::ByBlock) || (in_linetype && p.linetype == "BYBLOCK");
|
||||
s |= on_zero && (p.color == Col::ByLayer || (stroked && p.lineweight == Lw::ByLayer) || (in_linetype && p.linetype == "BYLAYER"));
|
||||
if let Geom::Shaded { shade: Shade::Gradient(g), .. } = &it.geom {
|
||||
let inherited = |c| c == Col::ByBlock || (on_zero && c == Col::ByLayer);
|
||||
s |= inherited(g.first) || matches!(g.second, Second::Col(c) if inherited(c));
|
||||
}
|
||||
if let Geom::Insert(ins) = &it.geom {
|
||||
s |= !ins.attribs.is_empty() || self.is_sensitive(&ins.block, depth + 1);
|
||||
}
|
||||
@@ -391,6 +555,23 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gradient `g` as paint, placed by `map`; its colors resolved as the hatch's own would be.
|
||||
fn gradient(&self, g: &Grad, p: &Props, map: Affine, inh: &Inherit) -> Paint {
|
||||
let rgb = |c: Col| self.rgb(&Props { color: c, ..p.clone() }, inh);
|
||||
let first = rgb(g.first);
|
||||
let second = match g.second {
|
||||
Second::Col(c) => rgb(c),
|
||||
Second::Tint(t) => Grad::tinted(first, t),
|
||||
};
|
||||
let stops = g.stops.iter().map(|(at, two)| GradientStop::new(*at, rgb_color(if *two { second } else { first }))).collect();
|
||||
let mut geom = g.geom;
|
||||
geom.transform(map, g.kind);
|
||||
let mut paint = GradientPaint::new(Gradient::new(g.kind, stops));
|
||||
paint.angle = geom.angle_deg();
|
||||
paint.geom = Some(geom);
|
||||
Paint::Gradient(Box::new(paint))
|
||||
}
|
||||
|
||||
/// What a block placed by an insert with `p` inherits.
|
||||
fn inherit(&self, p: &Props, inh: &Inherit) -> Inherit {
|
||||
Inherit {
|
||||
@@ -479,16 +660,75 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
return None;
|
||||
}
|
||||
let mut node = match &it.geom {
|
||||
Geom::Path { bp, fill, width } => self.path(bp, *fill, *width, &it.props, map, inh)?,
|
||||
Geom::Path { bp, fill, width } => self.path(bp, if *fill { Look::Fill } else { Look::Line }, *width, &it.props, map, inh)?,
|
||||
Geom::Shaded { bp, shade: Shade::Gradient(g) } => self.path(bp, Look::Gradient(g), 0.0, &it.props, map, inh)?,
|
||||
Geom::Shaded { bp, shade: Shade::Pattern { dots } } => self.pattern(bp, *dots, &it.props, map, inh)?,
|
||||
Geom::Text(t) => self.text(t, &it.props, map, inh)?,
|
||||
Geom::Insert(ins) => return self.insert(ins, &it.props, map, inh, depth),
|
||||
Geom::Image(im) => self.image(im, map)?,
|
||||
};
|
||||
node.opacity = self.opacity(&it.props, inh);
|
||||
self.nodes += 1;
|
||||
Some(node)
|
||||
}
|
||||
|
||||
fn path(&mut self, bp: &BezPath, fill: bool, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> {
|
||||
/// Pattern hatch lines (`bp`, a move and a line per piece). With `dots`, the pieces of no
|
||||
/// length go on a path of their own with round caps, grouped with the dashes, which keep
|
||||
/// butt caps and their lengths.
|
||||
fn pattern(&mut self, bp: &BezPath, dots: bool, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> {
|
||||
if !dots {
|
||||
return self.path(bp, Look::Pattern { dots: false }, 0.0, p, map, inh);
|
||||
}
|
||||
let (mut dashes, mut points) = (BezPath::new(), BezPath::new());
|
||||
let (mut dash_count, mut dot_count) = (0usize, 0usize);
|
||||
let mut from = None;
|
||||
for el in bp.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(a) => from = Some(a),
|
||||
PathEl::LineTo(b) => {
|
||||
if let Some(a) = from {
|
||||
let (out, count) = if a == b { (&mut points, &mut dot_count) } else { (&mut dashes, &mut dash_count) };
|
||||
out.move_to(a);
|
||||
out.line_to(b);
|
||||
*count += 1;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if dashes.elements().is_empty() {
|
||||
return self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh);
|
||||
}
|
||||
if points.elements().is_empty() {
|
||||
return self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh);
|
||||
}
|
||||
// Every object the split makes: the group (`item` counts it), the two paths, and each
|
||||
// piece of a path with more than one (`path` counts those).
|
||||
let loops = |count: usize| if count > 1 { count } else { 0 };
|
||||
if loops(dash_count).saturating_add(loops(dot_count)).saturating_add(3) > MAX_NODES.saturating_sub(self.nodes) {
|
||||
self.warn(TOO_MANY);
|
||||
return None;
|
||||
}
|
||||
if dashes.elements().len().saturating_add(points.elements().len()) > MAX_ELEMENTS.saturating_sub(self.elements) {
|
||||
self.warn(TOO_MANY_POINTS);
|
||||
return None;
|
||||
}
|
||||
// A split that loses either path is left out whole, and charges nothing.
|
||||
let (nodes, elements) = (self.nodes, self.elements);
|
||||
let lines = self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh);
|
||||
let dots = lines.as_ref().and_then(|_| self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh));
|
||||
let (Some(lines), Some(dots)) = (lines, dots) else {
|
||||
(self.nodes, self.elements) = (nodes, elements);
|
||||
return None;
|
||||
};
|
||||
self.nodes += 2;
|
||||
Some(Node::group(self.doc.alloc_id(), vec![Arc::new(lines), Arc::new(dots)]))
|
||||
}
|
||||
|
||||
/// A path painted as `look` says; `width`: a line's width in drawing units (0: the
|
||||
/// lineweight).
|
||||
fn path(&mut self, bp: &BezPath, look: Look<'_>, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> {
|
||||
let fill = matches!(look, Look::Fill | Look::Gradient(_));
|
||||
let n = bp.elements().len();
|
||||
if self.elements.saturating_add(n) > MAX_ELEMENTS {
|
||||
self.warn(TOO_MANY_POINTS);
|
||||
@@ -498,7 +738,14 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
let mut bp = bp.clone();
|
||||
bp.apply_affine(map);
|
||||
super::curve::bounds(&bp)?;
|
||||
let paint = Paint::solid(rgb_color(self.rgb(p, inh)));
|
||||
let paint = match look {
|
||||
Look::Gradient(g) => self.gradient(g, p, map, inh),
|
||||
_ => Paint::solid(rgb_color(self.rgb(p, inh))),
|
||||
};
|
||||
let pattern = match look {
|
||||
Look::Pattern { dots } => Some(dots),
|
||||
_ => None,
|
||||
};
|
||||
let scale = map.determinant().abs().sqrt();
|
||||
let path = PathData::from_bezpath(&bp);
|
||||
// A compound path's loops each keep a copy of its appearance, beside its own.
|
||||
@@ -515,7 +762,14 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
f64::from(lw) / 100.0 * PT_PER_MM * self.lw_scale
|
||||
};
|
||||
let mut ap = Appearance::basic(Paint::None, paint, w);
|
||||
if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
|
||||
// Pattern lines carry their own dashes; dots of no length show with round caps.
|
||||
if let Some(dots) = pattern {
|
||||
if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
|
||||
&& dots
|
||||
{
|
||||
s.cap = LineCap::Round;
|
||||
}
|
||||
} else if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
|
||||
&& let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale)
|
||||
{
|
||||
match dash.pattern.len().checked_mul(copies).and_then(|v| self.dash_values.checked_add(v)).filter(|n| *n <= MAX_DASH_VALUES) {
|
||||
@@ -590,6 +844,92 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
Some(Node::new(self.doc.alloc_id(), NodeKind::Text(Box::new(obj))))
|
||||
}
|
||||
|
||||
/// The non-empty, trimmed file path that image `im`'s IMAGEDEF names.
|
||||
fn image_file(&self, im: &ImageItem) -> Option<String> {
|
||||
im.def.and_then(|h| self.d.images.get(&h)).map(|f| f.path.trim().to_string()).filter(|p| !p.is_empty())
|
||||
}
|
||||
|
||||
/// The size in pixels of image `im`: its own, else its file's as its IMAGEDEF gives it.
|
||||
fn image_size(&self, im: &ImageItem) -> Option<(f64, f64)> {
|
||||
let def = im.def.and_then(|h| self.d.images.get(&h)).map_or([0.0; 2], |f| f.size);
|
||||
let size = if im.size.iter().all(|v| *v >= 1.0) { im.size } else { def };
|
||||
let [w, h] = size.map(f64::round);
|
||||
[w, h].iter().all(|v| (1.0..=MAX_IMAGE_SIDE).contains(v)).then_some((w, h))
|
||||
}
|
||||
|
||||
/// A raster image, linked to the file its IMAGEDEF names (the path as the drawing stores it,
|
||||
/// found from the drawing's folder when the document opens): until the file is read it shows
|
||||
/// a placeholder over its pixels. A clip boundary makes it a clip group.
|
||||
fn image(&mut self, im: &ImageItem, map: Affine) -> Option<Node> {
|
||||
let Some(path) = self.image_file(im) else {
|
||||
self.warn(NO_IMAGE_FILE);
|
||||
return None;
|
||||
};
|
||||
let Some((w, h)) = self.image_size(im) else {
|
||||
self.warn(IMAGE_SIZE);
|
||||
return None;
|
||||
};
|
||||
let xf = map * im.placement(h);
|
||||
if !(xf.as_coeffs().iter().all(|v| v.is_finite()) && xf.determinant() != 0.0) {
|
||||
return None;
|
||||
}
|
||||
// The clip boundary, unless it shows the whole image. Its path and the image are objects of
|
||||
// their own (`item` counts the group), and its points and the close are path elements: both
|
||||
// are checked against the limits before the points are read.
|
||||
let clip = im.clip.as_ref().filter(|c| !covers(c, w, h));
|
||||
let elements = clip.map_or(0, |c| c.len().saturating_add(1));
|
||||
if clip.is_some() && self.nodes.saturating_add(2) >= MAX_NODES {
|
||||
self.warn(TOO_MANY);
|
||||
return None;
|
||||
}
|
||||
if self.elements.saturating_add(elements) > MAX_ELEMENTS {
|
||||
self.warn(TOO_MANY_POINTS);
|
||||
return None;
|
||||
}
|
||||
// In document space, or in a symbol's own space, where each instance places it.
|
||||
let clip: Option<Vec<Point>> = clip.map(|c| c.iter().map(|p| xf * *p).collect());
|
||||
let local = self.in_symbol > 0;
|
||||
let limit = if local { MAX_SYMBOL_EXTENT } else { MAX_EXTENT };
|
||||
let fits = |p: &Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= limit && p.y.abs() <= limit;
|
||||
if clip.as_ref().is_some_and(|c| !c.iter().all(fits)) {
|
||||
self.warn(FAR_CLIPS);
|
||||
return None;
|
||||
}
|
||||
// Each image keeps its own copy of the path.
|
||||
if !self.charge_text(path.len()) {
|
||||
return None;
|
||||
}
|
||||
let key = format!("{IMAGE_KEY}{}", vectorcraft_doc::links::hash_bytes(path.as_bytes()));
|
||||
if !self.doc.images.contains_key(&key) {
|
||||
let bytes = Arc::new(vectorcraft_doc::links::missing_placeholder()?);
|
||||
let blob = ImageBlob {
|
||||
mime: vectorcraft_doc::links::PROXY_MIME.into(),
|
||||
bytes: bytes.clone(),
|
||||
proxy: Some(bytes),
|
||||
file_font: Default::default(),
|
||||
};
|
||||
self.doc.images.insert(key.clone(), blob);
|
||||
}
|
||||
let (w_px, h_px) = (w as u32, h as u32);
|
||||
let image = ImageObject { key, width: w_px, height: h_px, xf, link: Some(LinkInfo::new(path)), placement: Default::default(), pixels: None };
|
||||
let image = Node::new(self.doc.alloc_id(), NodeKind::Image(Box::new(image)));
|
||||
let Some(clip) = clip else { return Some(image) };
|
||||
// A symbol's clips are checked where each of its instances places them.
|
||||
if local && let Some(b) = clip.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) {
|
||||
self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b)));
|
||||
}
|
||||
self.nodes += 2;
|
||||
self.elements += elements;
|
||||
let mut bp = BezPath::new();
|
||||
for (i, p) in clip.iter().enumerate() {
|
||||
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
|
||||
}
|
||||
bp.close_path();
|
||||
let path = PathData::from_bezpath(&bp);
|
||||
let clip = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: true, guide: false });
|
||||
Some(Node::new(self.doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true }))
|
||||
}
|
||||
|
||||
/// An insert: a symbol instance per copy (anonymous blocks: a group of their art), grouped
|
||||
/// with its attributes.
|
||||
fn insert(&mut self, ins: &InsertItem, p: &Props, map: Affine, inh: &Inherit, depth: u32) -> Option<Node> {
|
||||
@@ -597,11 +937,53 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
let base = self.d.blocks.get(&ins.block).map_or(Point::ZERO, |b| b.base);
|
||||
let unbase = Affine::translate(-base.to_vec2());
|
||||
let anonymous = ins.block.starts_with('*');
|
||||
let symbol = if anonymous { None } else { self.symbol(&ins.block, &child, depth) };
|
||||
// An empty symbol is drawn again only for a cell that places an instance of it.
|
||||
let symbol = if anonymous { None } else { self.symbol(&ins.block, &child, depth, false) };
|
||||
// The symbol's art when this insert took it out.
|
||||
let mut taken = None;
|
||||
let mut parts = vec![];
|
||||
for cell in &ins.cells {
|
||||
let node = match &symbol {
|
||||
Some(name) => {
|
||||
let xf = map * *cell * self.symbol_map.inverse();
|
||||
// Its image clips where this instance places them: inside another symbol, their
|
||||
// box joins that symbol's; else, when it may leave the canvas, this placement
|
||||
// draws the block's art, which checks each clip where it lands.
|
||||
let reach_of = |b: &Self| b.symbol_reach.get(name).map(|r| placed_reach(xf, *r));
|
||||
let leaves =
|
||||
|r: Option<Rect>| r.is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_EXTENT));
|
||||
let mut reach = reach_of(self);
|
||||
// An empty symbol is drawn again (or its taken art put back) unless this placement
|
||||
// draws the art anyway; the art drawn again may reach further.
|
||||
if self.empty.contains(name) && (self.in_symbol > 0 || !leaves(reach)) {
|
||||
if self.nodes >= MAX_NODES {
|
||||
self.warn(TOO_MANY);
|
||||
break;
|
||||
}
|
||||
let back = taken.take().is_some_and(|art| self.restore(name, art));
|
||||
if !back && self.symbol(&ins.block, &child, depth, true).is_none() {
|
||||
continue;
|
||||
}
|
||||
reach = reach_of(self);
|
||||
}
|
||||
// Joins the enclosing symbol's box once the instance is kept.
|
||||
let inside = reach.filter(|_| self.in_symbol > 0);
|
||||
if inside.is_none() && leaves(reach) {
|
||||
// This placement draws the art instead of the symbol. The art of a symbol
|
||||
// no instance places yet is taken out, so that it isn't kept and charged
|
||||
// as well; an instance in a later cell puts it back.
|
||||
if taken.is_none() {
|
||||
taken = self.take_unused(name);
|
||||
}
|
||||
if self.nodes >= MAX_NODES {
|
||||
self.warn(TOO_MANY);
|
||||
break;
|
||||
}
|
||||
parts.extend(self.art(&ins.block, map * *cell * unbase, &child, depth));
|
||||
continue;
|
||||
}
|
||||
// Checked here, after the art drawn in its place: that art gets back the
|
||||
// share of an unused symbol.
|
||||
if self.nodes >= MAX_NODES {
|
||||
self.warn(TOO_MANY);
|
||||
break;
|
||||
@@ -609,7 +991,10 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
if !self.charge_text(name.len()) {
|
||||
break;
|
||||
}
|
||||
let xf = map * *cell * self.symbol_map.inverse();
|
||||
if let Some(b) = inside {
|
||||
self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b)));
|
||||
}
|
||||
*self.uses.entry(name.clone()).or_default() += 1;
|
||||
self.nodes += 1;
|
||||
Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf }))
|
||||
}
|
||||
@@ -664,30 +1049,124 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The symbol for block `name` placed with `inh` (made once per look).
|
||||
fn symbol(&mut self, name: &str, inh: &Inherit, depth: u32) -> Option<String> {
|
||||
/// The symbol for block `name` placed with `inh` (made once per look). One whose art was
|
||||
/// taken out is drawn again when `draw` is set, and else returned empty.
|
||||
fn symbol(&mut self, name: &str, inh: &Inherit, depth: u32, draw: bool) -> Option<String> {
|
||||
let inh = if self.is_sensitive(name, depth) { inh.clone() } else { Inherit::default() };
|
||||
let key = (name.to_string(), inh);
|
||||
if let Some(s) = self.symbols.get(&key) {
|
||||
return s.clone();
|
||||
}
|
||||
let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base);
|
||||
let map = self.symbol_map * Affine::translate(-base.to_vec2());
|
||||
let art = self.art(name, map, &key.1, depth);
|
||||
let made = art.and_then(|art| {
|
||||
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str());
|
||||
// The symbol keeps its name: text, as its instances' copies of it are.
|
||||
if !self.charge_text(label.len()) {
|
||||
return None;
|
||||
let s = s.clone()?;
|
||||
if !draw || !self.empty.contains(&s) {
|
||||
return Some(s);
|
||||
}
|
||||
let (art, reach, cost) = self.symbol_art(name, &key.1, depth);
|
||||
let slot = self.symbol_slot.get(&s).and_then(|i| self.doc.symbols.get_mut(*i));
|
||||
return match (art, slot) {
|
||||
(Some(art), Some(slot)) => {
|
||||
slot.art = Arc::new(art);
|
||||
self.symbol_cost.insert(s.clone(), cost);
|
||||
match reach {
|
||||
Some(b) => self.symbol_reach.insert(s.clone(), b),
|
||||
None => self.symbol_reach.remove(&s),
|
||||
};
|
||||
self.empty.remove(&s);
|
||||
Some(s)
|
||||
}
|
||||
// Nothing of it fits now: what it took goes back, and it stays empty.
|
||||
_ => {
|
||||
self.set_cost(self.cost().minus(cost));
|
||||
self.nested = self.nested.minus(cost);
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
let (art, reach, cost) = self.symbol_art(name, &key.1, depth);
|
||||
let made = art.map(|art| {
|
||||
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str());
|
||||
let symbol = unique(label, &mut self.next_suffix, &self.symbol_names);
|
||||
self.symbol_names.insert(symbol.clone());
|
||||
if let Some(b) = reach {
|
||||
self.symbol_reach.insert(symbol.clone(), b);
|
||||
}
|
||||
self.symbol_slot.insert(symbol.clone(), self.doc.symbols.len());
|
||||
self.symbol_cost.insert(symbol.clone(), cost);
|
||||
self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) });
|
||||
Some(symbol)
|
||||
symbol
|
||||
});
|
||||
self.symbols.insert(key, made.clone());
|
||||
made
|
||||
}
|
||||
|
||||
/// The art of the symbol for block `name` placed with `inh`, the box of its image clips, and
|
||||
/// what it took from the limits itself (not the symbols made while drawing it, which other
|
||||
/// instances may use).
|
||||
fn symbol_art(&mut self, name: &str, inh: &Inherit, depth: u32) -> (Option<Node>, Option<Rect>, Cost) {
|
||||
let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base);
|
||||
let map = self.symbol_map * Affine::translate(-base.to_vec2());
|
||||
let outer = self.clip_reach.take();
|
||||
let before = self.cost();
|
||||
let outer_nested = std::mem::take(&mut self.nested);
|
||||
self.in_symbol += 1;
|
||||
let art = self.art(name, map, inh, depth);
|
||||
self.in_symbol -= 1;
|
||||
let reach = std::mem::replace(&mut self.clip_reach, outer);
|
||||
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()).len();
|
||||
// The symbol keeps its name: text, as its instances' copies of it are.
|
||||
let art = art.filter(|_| self.charge_text(label));
|
||||
let total = self.cost().minus(before);
|
||||
let own = total.minus(self.nested);
|
||||
self.nested = outer_nested.plus(total);
|
||||
(art, reach, own)
|
||||
}
|
||||
}
|
||||
|
||||
/// The box of `r` placed by `xf`. A box that is not finite, or whose placed corners are not (an
|
||||
/// overflow, which a union or a bounding box would drop as NaN), is the whole plane, so every
|
||||
/// placement of it is out of range.
|
||||
pub(crate) fn placed_reach(xf: Affine, r: Rect) -> Rect {
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|p| xf * p);
|
||||
match corners.iter().all(|p| p.x.is_finite() && p.y.is_finite()) {
|
||||
true => corners.iter().fold(Rect::from_points(corners[0], corners[0]), |b, p| b.union_pt(*p)),
|
||||
false => Rect::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY),
|
||||
}
|
||||
}
|
||||
|
||||
/// The symbol of each instance in `art`, once per instance.
|
||||
fn placed_symbols(art: &Node) -> Vec<String> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |n: &Node| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
out.push(symbol.clone());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Every symbol of `doc` that no instance on its layers places, directly or through other
|
||||
/// symbols, removed.
|
||||
fn drop_unplaced_symbols(doc: &mut Document) {
|
||||
let index: HashMap<&str, usize> = doc.symbols.iter().enumerate().map(|(i, s)| (s.name.as_str(), i)).collect();
|
||||
let mut placed = vec![false; doc.symbols.len()];
|
||||
let mut todo: Vec<usize> = vec![];
|
||||
// Each symbol is queued once, however many instances place it.
|
||||
let note = |n: &Node, placed: &mut Vec<bool>, todo: &mut Vec<usize>| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
|
||||
&& let Some(&i) = index.get(symbol.as_str())
|
||||
&& let Some(seen) = placed.get_mut(i)
|
||||
&& !*seen
|
||||
{
|
||||
*seen = true;
|
||||
todo.push(i);
|
||||
}
|
||||
};
|
||||
doc.walk(|n| note(n, &mut placed, &mut todo));
|
||||
while let Some(i) = todo.pop() {
|
||||
if let Some(s) = doc.symbols.get(i) {
|
||||
s.art.walk(&mut |n: &Node| note(n, &mut placed, &mut todo));
|
||||
}
|
||||
}
|
||||
let mut keep = placed.into_iter();
|
||||
doc.symbols.retain(|_| keep.next().unwrap_or(false));
|
||||
}
|
||||
|
||||
/// Fit text stretched or squeezed across, aligned text scaled as a whole, to run its span
|
||||
@@ -704,6 +1183,22 @@ fn fill_span(obj: &mut TextObject, span: Span, s: f64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does clip boundary `clip` (pixel space) show the whole `w` × `h` image: is it a rectangle
|
||||
/// square to the image that holds it?
|
||||
fn covers(clip: &[Point], w: f64, h: f64) -> bool {
|
||||
if clip.len() != 4 || clip.iter().enumerate().any(|(i, p)| clip[..i].contains(p)) {
|
||||
return false;
|
||||
}
|
||||
let Some(b) = clip.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { return false };
|
||||
let corner = |p: &Point| (p.x == b.x0 || p.x == b.x1) && (p.y == b.y0 || p.y == b.y1);
|
||||
// Each point a distinct corner, and each edge along one side: the four corners in order around.
|
||||
let side = |i: usize| {
|
||||
let (p, q) = (clip[i], clip[(i + 1) % clip.len()]);
|
||||
(p.x == q.x) != (p.y == q.y)
|
||||
};
|
||||
clip.len() == 4 && clip.iter().all(corner) && (0..4).all(side) && b.x0 <= 0.0 && b.y0 <= 0.0 && b.x1 >= w && b.y1 >= h
|
||||
}
|
||||
|
||||
fn rgb_color([r, g, b]: [u8; 3]) -> Color {
|
||||
Color::rgb8(r, g, b)
|
||||
}
|
||||
@@ -735,3 +1230,59 @@ fn unique(base: &str, next: &mut HashMap<String, usize>, taken: &HashSet<String>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EMPTY: &[u8] = b" 0\nSECTION\n 2\nENTITIES\n 0\nENDSEC\n 0\nEOF\n";
|
||||
|
||||
fn props() -> Props {
|
||||
Props {
|
||||
layer: "0".into(),
|
||||
color: Col::Rgb([0, 0, 0]),
|
||||
lineweight: Lw::Default,
|
||||
linetype: "CONTINUOUS".into(),
|
||||
ltscale: 1.0,
|
||||
alpha: Alpha::Opacity(1.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Two dashes and two dots: the group, its two paths and four pieces, in 8 path elements.
|
||||
fn mixed() -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
for (a, b) in [((0.0, 0.0), (1.0, 0.0)), ((0.0, 1.0), (1.0, 1.0)), ((2.0, 0.0), (2.0, 0.0)), ((2.0, 1.0), (2.0, 1.0))] {
|
||||
bp.move_to(a);
|
||||
bp.line_to(b);
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_patterns_fit_every_object_and_point_or_charge_nothing() {
|
||||
let (tags, _) = super::super::tags(EMPTY).unwrap();
|
||||
let d = Drawing::read(craft_dxf::model::Document::read(&tags));
|
||||
let o = ImportOptions::default();
|
||||
let (p, inh) = (props(), Inherit::default());
|
||||
// Seven objects with six slots free: refused; with seven: drawn, the group left to `item`.
|
||||
let mut b = Build::new(&d, &o);
|
||||
b.nodes = MAX_NODES - 6;
|
||||
assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_none());
|
||||
assert_eq!(b.nodes, MAX_NODES - 6);
|
||||
b.nodes = MAX_NODES - 7;
|
||||
assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_some());
|
||||
assert_eq!(b.nodes, MAX_NODES - 1);
|
||||
// Eight points with seven left: refused without charging them, so a 4-point path that
|
||||
// follows still fits.
|
||||
let mut b = Build::new(&d, &o);
|
||||
b.elements = MAX_ELEMENTS - 7;
|
||||
assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_none());
|
||||
assert_eq!(b.elements, MAX_ELEMENTS - 7);
|
||||
let mut line = BezPath::new();
|
||||
line.move_to((0.0, 0.0));
|
||||
line.line_to((1.0, 0.0));
|
||||
line.line_to((1.0, 1.0));
|
||||
line.line_to((0.0, 1.0));
|
||||
assert!(b.path(&line, Look::Line, 0.0, &p, Affine::IDENTITY, &inh).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
+249
-16
@@ -4,7 +4,7 @@
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::rc::Rc;
|
||||
|
||||
use kurbo::{BezPath, PathEl};
|
||||
use kurbo::{BezPath, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Shape};
|
||||
use vectorcraft_doc::Justify;
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
@@ -12,6 +12,7 @@ use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath};
|
||||
|
||||
use super::acis;
|
||||
use super::curve::{self, Vertex};
|
||||
use super::hatch::{self, Grad, NoPattern};
|
||||
use super::reader::{aci_paper, point};
|
||||
|
||||
/// How far below the baseline the lowest descender reaches, as a fraction of the cap height.
|
||||
@@ -22,6 +23,10 @@ const LINE_SPACING: f64 = 5.0 / 3.0;
|
||||
const MAX_CELLS: i64 = 10_000;
|
||||
/// The most copies all the array inserts of a file make together.
|
||||
const MAX_TOTAL_CELLS: i64 = 2_000_000;
|
||||
/// The most winding steps for island nesting: loops times boundary elements times samples.
|
||||
const MAX_ISLAND_WORK: usize = if cfg!(test) { 1_000 } else { 10_000_000 };
|
||||
/// The most segment midpoints sampled just inside each loop for island nesting.
|
||||
const MAX_ISLAND_SAMPLES: usize = 16;
|
||||
/// Art farther than this from the origin (drawing units) is damaged data, left out.
|
||||
const MAX_COORD: f64 = 1e12;
|
||||
/// How far fit and aligned text may be squeezed or stretched to span their two points: at width
|
||||
@@ -148,6 +153,31 @@ pub(crate) struct InsertItem {
|
||||
pub attribs: Vec<Item>,
|
||||
}
|
||||
|
||||
/// A raster image: the file its IMAGEDEF names, shown on a parallelogram.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ImageItem {
|
||||
/// The handle of its IMAGEDEF.
|
||||
pub def: Option<u64>,
|
||||
/// The lower-left corner, and one pixel along the width and up the height (world
|
||||
/// coordinates, drawing units).
|
||||
pub insert: Point,
|
||||
pub u: Vec2,
|
||||
pub v: Vec2,
|
||||
/// Its size in pixels (0: its IMAGEDEF's).
|
||||
pub size: [f64; 2],
|
||||
/// The clip boundary in pixel space ([`ImageItem::placement`]); `None`: the whole image.
|
||||
pub clip: Option<Vec<Point>>,
|
||||
}
|
||||
|
||||
impl ImageItem {
|
||||
/// Pixel space (the top-left corner at the origin, x right, y down, one unit a pixel) to world
|
||||
/// coordinates, for an image `height` pixels high.
|
||||
pub fn placement(&self, height: f64) -> Affine {
|
||||
let top = self.insert + self.v * height;
|
||||
Affine::new([self.u.x, self.u.y, -self.v.x, -self.v.y, top.x, top.y])
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Geom {
|
||||
/// A path in world coordinates; `fill`: a filled area (hatch, solid), else a line of
|
||||
@@ -157,8 +187,24 @@ pub(crate) enum Geom {
|
||||
fill: bool,
|
||||
width: f64,
|
||||
},
|
||||
/// A hatch filled with a gradient, or a pattern hatch's lines (`bp`, world coordinates).
|
||||
Shaded {
|
||||
bp: BezPath,
|
||||
shade: Shade,
|
||||
},
|
||||
Text(TextItem),
|
||||
Insert(InsertItem),
|
||||
Image(ImageItem),
|
||||
}
|
||||
|
||||
/// How a [`Geom::Shaded`] path paints.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Shade {
|
||||
/// The area filled with a gradient.
|
||||
Gradient(Box<Grad>),
|
||||
/// Pattern lines, stroked at the lineweight without a linetype; `dots`: some pieces have no
|
||||
/// length and need round caps to show.
|
||||
Pattern { dots: bool },
|
||||
}
|
||||
|
||||
/// An entity as art: its geometry and its properties.
|
||||
@@ -176,16 +222,26 @@ pub(crate) struct Converter {
|
||||
pub warnings: Vec<String>,
|
||||
/// Array insert copies made so far, against [`MAX_TOTAL_CELLS`].
|
||||
cells: i64,
|
||||
/// The pattern budget shared by entity sections and blocks.
|
||||
patterns: hatch::Budget,
|
||||
/// 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";
|
||||
const GRADIENT_HATCH: &str = "gradient hatches are filled with their first colour";
|
||||
const PATTERN_HATCH: &str = "pattern hatches without usable pattern lines come in as their boundaries";
|
||||
const DENSE_PATTERN: &str =
|
||||
"pattern hatches of more than 20,000 dashes, 200,000 boundary edges or 20,000,000 clipping steps come in as their boundaries";
|
||||
const MANY_PATTERNS: &str = "the drawing's pattern hatches have more than 2,000,000 dashes in all: the rest come in as their boundaries";
|
||||
const MUCH_PATTERN_WORK: &str = "the drawing's pattern hatches take too much work to clip: the rest come in as their boundaries";
|
||||
const MUCH_ISLAND_WORK: &str = "hatches with too many boundary points to sort into islands are filled as if every loop were a boundary";
|
||||
const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertices are missing are left out";
|
||||
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 FLAT_IMAGES: &str = "images with no width or height are left out";
|
||||
const IMAGE_ADJUSTMENTS: &str = "the brightness, contrast and fade of images are left out";
|
||||
const OPAQUE_IMAGES: &str = "images set to show opaque keep their file's transparency";
|
||||
const INVERTED_CLIPS: &str = "inverted image clips are left out: those images show whole";
|
||||
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";
|
||||
@@ -215,7 +271,7 @@ impl Converter {
|
||||
if !m.common.visible {
|
||||
continue;
|
||||
}
|
||||
match self.geom(e, &m) {
|
||||
match self.geom(e, &m).map(usable_paint) {
|
||||
Some(geom) if !in_range(&geom) => self.warn(FAR_AWAY),
|
||||
Some(geom) => out.push(Item { props: Props::read(&m.common), geom }),
|
||||
None if is_known(e.kind) => {}
|
||||
@@ -259,7 +315,7 @@ impl Converter {
|
||||
face(&mut bp, &corners);
|
||||
(!bp.elements().is_empty()).then_some(bp).and_then(path)
|
||||
}
|
||||
model::EntityKind::Hatch(h) => self.hatch(h, ocs),
|
||||
model::EntityKind::Hatch(h) => self.hatch(h, ocs, Props::read(&m.common).color),
|
||||
model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text),
|
||||
model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text),
|
||||
model::EntityKind::Insert(ins) => self.insert(ins, &e.followers, ocs),
|
||||
@@ -267,11 +323,39 @@ impl Converter {
|
||||
model::EntityKind::Dimension(d) => {
|
||||
Some(Geom::Insert(InsertItem { block: d.block.as_ref()?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] }))
|
||||
}
|
||||
// Group 70 without its Show Image bit: a hidden image (an IMAGE without group 70 shows).
|
||||
model::EntityKind::Image(_) if g.i(70).is_some_and(|flags| flags & 1 == 0) => None,
|
||||
model::EntityKind::Image(im) => self.image(im, g.i(70).is_some()),
|
||||
_ if e.kind == "REGION" => self.region(e),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// An IMAGE (its points are in world coordinates).
|
||||
fn image(&mut self, im: &model::Image, has_display: bool) -> Option<Geom> {
|
||||
let (u, v) = (point(im.u).to_vec2(), point(im.v).to_vec2());
|
||||
let area = u.cross(v);
|
||||
if !(area.is_finite() && area != 0.0) {
|
||||
self.warn(FLAT_IMAGES);
|
||||
return None;
|
||||
}
|
||||
if (im.brightness, im.contrast, im.fade) != (50, 50, 0) {
|
||||
self.warn(IMAGE_ADJUSTMENTS);
|
||||
}
|
||||
if has_display && im.display & 8 == 0 {
|
||||
self.warn(OPAQUE_IMAGES);
|
||||
}
|
||||
let clip = if !im.clipping || (has_display && im.display & 4 == 0) {
|
||||
None
|
||||
} else if im.clip_inverted {
|
||||
self.warn(INVERTED_CLIPS);
|
||||
None
|
||||
} else {
|
||||
image_clip(im)
|
||||
};
|
||||
Some(Geom::Image(ImageItem { def: im.image_def, insert: point(im.insert), u, v, size: im.size, clip }))
|
||||
}
|
||||
|
||||
fn polyline(&mut self, p: &model::Polyline, g: &Groups<'_>, ocs: Affine) -> Option<Geom> {
|
||||
// Meshes are in world coordinates, seen from above.
|
||||
if p.is_polyface() || p.is_mesh() {
|
||||
@@ -426,27 +510,153 @@ impl Converter {
|
||||
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();
|
||||
/// A hatch's art; `own`: its color, which a gradient without color records takes.
|
||||
fn hatch(&mut self, h: &model::Hatch, ocs: Affine, own: Col) -> Option<Geom> {
|
||||
let mut loops = Vec::new();
|
||||
for l in &h.loops {
|
||||
let Some(path) = boundary(&l.path) else { break };
|
||||
bp.extend(path);
|
||||
loops.push(path);
|
||||
}
|
||||
let mut max_depth = match h.style {
|
||||
1 => Some(1),
|
||||
2 => Some(0),
|
||||
_ => None,
|
||||
};
|
||||
if max_depth.is_some() {
|
||||
let elements = loops.iter().fold(0usize, |total, path| total.saturating_add(path.elements().len()));
|
||||
// Count each loop's samples against every loop, including its own containment checks.
|
||||
if loops.len().saturating_mul(elements).saturating_mul(MAX_ISLAND_SAMPLES) > MAX_ISLAND_WORK {
|
||||
self.warn(MUCH_ISLAND_WORK);
|
||||
max_depth = None;
|
||||
}
|
||||
}
|
||||
let nesting: Vec<_> = if max_depth.is_some() {
|
||||
loops
|
||||
.iter()
|
||||
.map(|path| {
|
||||
let bounds = path.bounding_box();
|
||||
// Center each loop independently so distant loops do not erase small geometry.
|
||||
let center = bounds.center();
|
||||
let local = transformed(path.clone(), Affine::translate(-center.to_vec2()));
|
||||
let area = local.area();
|
||||
// Area divided by perimeter measures thickness independently of the loop's rotation.
|
||||
let perimeter = local.perimeter(bounds.width().max(bounds.height()) * 1e-3);
|
||||
let inset = if perimeter > 0.0 { area.abs() / perimeter * 1e-3 * area.signum() } else { 0.0 };
|
||||
let step = local.segments().count().div_ceil(MAX_ISLAND_SAMPLES).max(1);
|
||||
let mut samples: Vec<_> = local
|
||||
.segments()
|
||||
.step_by(step)
|
||||
.filter_map(|segment| {
|
||||
let tangent = match segment {
|
||||
PathSeg::Line(line) => line.deriv().eval(0.5),
|
||||
PathSeg::Quad(quad) => quad.deriv().eval(0.5),
|
||||
PathSeg::Cubic(cubic) => cubic.deriv().eval(0.5),
|
||||
}
|
||||
.to_vec2();
|
||||
let tangent = if tangent.hypot() > 0.0 { tangent } else { segment.end() - segment.start() };
|
||||
let length = tangent.hypot();
|
||||
if length == 0.0 {
|
||||
return None;
|
||||
}
|
||||
// Positive area puts the interior to the left of the tangent in y-up coordinates.
|
||||
Some(segment.eval(0.5) + Vec2::new(-tangent.y, tangent.x) * (inset / length))
|
||||
})
|
||||
.take(MAX_ISLAND_SAMPLES)
|
||||
.filter(|sample| local.winding(*sample) != 0)
|
||||
.collect();
|
||||
if samples.is_empty()
|
||||
&& let Some(PathEl::MoveTo(first)) = local.elements().first()
|
||||
{
|
||||
samples.push(*first);
|
||||
}
|
||||
(bounds, center, local, area.abs(), samples)
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let mut bp = BezPath::new();
|
||||
for (i, path) in loops.iter().enumerate() {
|
||||
if let Some(limit) = max_depth {
|
||||
let (bounds, center, _, area, samples) = &nesting[i];
|
||||
// Require geometric containment and a majority of samples so a shared
|
||||
// edge or a single vertex on the boundary does not decide nesting.
|
||||
let depth = nesting
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(j, _)| {
|
||||
let (other_bounds, other_center, other, other_area, _) = &nesting[*j];
|
||||
let offset = *center - *other_center;
|
||||
*j != i
|
||||
&& area < other_area
|
||||
&& bounds.x0 >= other_bounds.x0
|
||||
&& bounds.y0 >= other_bounds.y0
|
||||
&& bounds.x1 <= other_bounds.x1
|
||||
&& bounds.y1 <= other_bounds.y1
|
||||
&& samples.iter().filter(|p| other.winding(**p + offset) != 0).count() > samples.len() / 2
|
||||
})
|
||||
.count();
|
||||
if depth > limit {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
bp.extend(path.iter());
|
||||
}
|
||||
if bp.elements().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let bp = transformed(bp, ocs);
|
||||
if h.gradient.is_some() {
|
||||
self.warn(GRADIENT_HATCH);
|
||||
} else if !h.solid {
|
||||
self.warn(PATTERN_HATCH);
|
||||
return Some(Geom::Path { bp, fill: false, width: 0.0 });
|
||||
if let Some(g) = &h.gradient {
|
||||
let shade = hatch::gradient(g, &bp, ocs, own).map(|g| Shade::Gradient(Box::new(g)));
|
||||
let bp = transformed(bp, ocs);
|
||||
return Some(match shade {
|
||||
Some(shade) => Geom::Shaded { bp, shade },
|
||||
None => Geom::Path { bp, fill: true, width: 0.0 },
|
||||
});
|
||||
}
|
||||
if h.solid {
|
||||
return Some(Geom::Path { bp: transformed(bp, ocs), fill: true, width: 0.0 });
|
||||
}
|
||||
// The pattern lines are in the hatch's plane, as its boundary is.
|
||||
let doubled;
|
||||
let lines = if h.pattern_type == 0 && h.double && h.pattern_lines.len() == 1 {
|
||||
doubled = hatch::doubled(&h.pattern_lines);
|
||||
&doubled
|
||||
} else {
|
||||
&h.pattern_lines
|
||||
};
|
||||
match hatch::pattern(lines, &bp, &mut self.patterns) {
|
||||
Ok((lines, _)) if lines.elements().is_empty() => None,
|
||||
Ok((lines, dots)) => Some(Geom::Shaded { bp: transformed(lines, ocs), shade: Shade::Pattern { dots } }),
|
||||
Err(why) => {
|
||||
self.warn(match why {
|
||||
NoPattern::Undefined => PATTERN_HATCH,
|
||||
NoPattern::TooDense => DENSE_PATTERN,
|
||||
NoPattern::DrawingPieces => MANY_PATTERNS,
|
||||
NoPattern::DrawingWork => MUCH_PATTERN_WORK,
|
||||
});
|
||||
Some(Geom::Path { bp: transformed(bp, ocs), fill: false, width: 0.0 })
|
||||
}
|
||||
}
|
||||
Some(Geom::Path { bp, fill: true, width: 0.0 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the geometry within [`MAX_COORD`] of the origin?
|
||||
/// A gradient hatch whose gradient cannot be placed (numbers out of range) as a solid fill.
|
||||
fn usable_paint(g: Geom) -> Geom {
|
||||
match g {
|
||||
Geom::Shaded { bp, shade: Shade::Gradient(grad) } => {
|
||||
let geom = &grad.geom;
|
||||
let finite = |p: Point| p.x.is_finite() && p.y.is_finite();
|
||||
if finite(geom.start) && finite(geom.end) && geom.aspect.is_finite() && geom.focal.is_none_or(finite) {
|
||||
Geom::Shaded { bp, shade: Shade::Gradient(grad) }
|
||||
} else {
|
||||
Geom::Path { bp, fill: true, width: 0.0 }
|
||||
}
|
||||
}
|
||||
g => g,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the geometry within [`MAX_COORD`] of the origin? A gradient's handles may lie beyond it.
|
||||
fn in_range(g: &Geom) -> bool {
|
||||
let near = |p: Point| p.x.abs() <= MAX_COORD && p.y.abs() <= MAX_COORD;
|
||||
let origin = |m: &Affine| near(m.translation().to_point());
|
||||
@@ -454,8 +664,30 @@ fn in_range(g: &Geom) -> bool {
|
||||
Geom::Path { bp, width, .. } => {
|
||||
curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))) && *width <= MAX_COORD
|
||||
}
|
||||
Geom::Shaded { bp, .. } => curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))),
|
||||
Geom::Text(t) => origin(&t.xf) && t.height <= MAX_COORD,
|
||||
Geom::Insert(i) => i.cells.iter().all(|m| origin(m) && m.as_coeffs().iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)),
|
||||
Geom::Image(i) => {
|
||||
let [w, h] = i.size;
|
||||
let far = i.insert + i.u * w + i.v * h;
|
||||
near(i.insert) && near(far) && [i.u.x, i.u.y, i.v.x, i.v.y, w, h].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The clip boundary of IMAGE `im` in pixel space ([`ImageItem::placement`]): two opposite corners
|
||||
/// of a rectangle, or a polygon of three points or more. The boundary's points are pixel centres
|
||||
/// counted from the top-left pixel, so the image's own corners are at (−0.5, −0.5) and
|
||||
/// (width − 0.5, height − 0.5). `None` when it has too few points.
|
||||
fn image_clip(im: &model::Image) -> Option<Vec<Point>> {
|
||||
let pts: Vec<Point> = im.clip.iter().map(|[x, y]| Point::new(x + 0.5, y + 0.5)).collect();
|
||||
match pts.as_slice() {
|
||||
[a, b] if im.clip_type == 1 => {
|
||||
let (x0, x1, y0, y1) = (a.x.min(b.x), a.x.max(b.x), a.y.min(b.y), a.y.max(b.y));
|
||||
Some(vec![Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)])
|
||||
}
|
||||
p if p.len() >= 3 => Some(p.to_vec()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -479,6 +711,7 @@ fn is_known(kind: &str) -> bool {
|
||||
| "MTEXT"
|
||||
| "INSERT"
|
||||
| "DIMENSION"
|
||||
| "IMAGE"
|
||||
| "ATTDEF"
|
||||
| "SEQEND"
|
||||
| "VERTEX"
|
||||
|
||||
@@ -0,0 +1,847 @@
|
||||
//! Hatch fills other than solid: a pattern hatch's line families clipped to its boundary and cut
|
||||
//! into their dashes, and a gradient hatch's colors and placement. Both work in the hatch's own
|
||||
//! plane (its object coordinate system), where the boundary and the pattern lines are given.
|
||||
|
||||
use kurbo::{BezPath, PathEl};
|
||||
use vectorcraft_color::{GradientGeom, GradientKind};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use craft_dxf::model::{self, PatternLine};
|
||||
|
||||
use super::entity::Col;
|
||||
use super::reader::aci_paper;
|
||||
|
||||
/// The most dashes and dots one pattern hatch draws.
|
||||
pub(crate) const MAX_PIECES: usize = 20_000;
|
||||
/// The most boundary edges a pattern hatch is clipped against, once its curves are flattened.
|
||||
const MAX_EDGES: usize = 200_000;
|
||||
/// The most work one pattern hatch does: each pattern line drawn costs one step per boundary
|
||||
/// edge, and each dash, gap or dot looked at one more.
|
||||
const MAX_WORK: usize = 20_000_000;
|
||||
/// The most dashes and dots all pattern hatches draw together.
|
||||
pub(crate) const MAX_TOTAL_PIECES: usize = if cfg!(test) { 1_000 } else { 2_000_000 };
|
||||
/// The most clipping and dash steps all pattern hatches take together.
|
||||
pub(crate) const MAX_TOTAL_WORK: usize = if cfg!(test) { 200_000 } else { 200_000_000 };
|
||||
/// How far flattened boundary curves may stray, as a fraction of their loop's larger side.
|
||||
const FLATNESS: f64 = 1e-4;
|
||||
/// Spans, line spacings and dash periods shorter than this many units of the last place of their
|
||||
/// coordinates count as none.
|
||||
const LOCAL_TINY: f64 = 64.0 * f64::EPSILON;
|
||||
|
||||
/// Why a pattern hatch is not drawn as its pattern.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum NoPattern {
|
||||
/// The hatch holds no pattern lines.
|
||||
Undefined,
|
||||
/// Drawing it would take more than [`MAX_PIECES`] pieces, [`MAX_EDGES`] boundary edges or
|
||||
/// [`MAX_WORK`] steps.
|
||||
TooDense,
|
||||
/// The drawing reaches its total piece limit.
|
||||
DrawingPieces,
|
||||
/// The drawing reaches its total work limit.
|
||||
DrawingWork,
|
||||
}
|
||||
|
||||
/// The remaining pattern budget; discarded patterns also use it.
|
||||
pub(crate) struct Budget {
|
||||
pieces: usize,
|
||||
work: usize,
|
||||
stopped: Option<NoPattern>,
|
||||
}
|
||||
|
||||
impl Default for Budget {
|
||||
fn default() -> Self {
|
||||
Self { pieces: MAX_TOTAL_PIECES, work: MAX_TOTAL_WORK, stopped: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
fn piece(&mut self, pieces: &mut usize) -> Result<(), NoPattern> {
|
||||
if *pieces >= MAX_PIECES {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
if self.pieces == 0 {
|
||||
self.stopped = Some(NoPattern::DrawingPieces);
|
||||
return Err(NoPattern::DrawingPieces);
|
||||
}
|
||||
*pieces += 1;
|
||||
self.pieces -= 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn work(&mut self, work: &mut usize, steps: usize) -> Result<(), NoPattern> {
|
||||
if steps > MAX_WORK - *work {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
if steps > self.work {
|
||||
self.stopped = Some(NoPattern::DrawingWork);
|
||||
return Err(NoPattern::DrawingWork);
|
||||
}
|
||||
*work += steps;
|
||||
self.work -= steps;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a perpendicular family when the pattern holds only one family.
|
||||
pub(crate) fn doubled(lines: &[PatternLine]) -> Vec<PatternLine> {
|
||||
let mut out = lines.to_vec();
|
||||
if let [line] = lines {
|
||||
out.push(PatternLine { angle: line.angle + 90.0, base: line.base, offset: [-line.offset[1], line.offset[0]], dashes: line.dashes.clone() });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A pattern hatch's lines inside `boundary` (closed loops; even-odd, as solid hatches fill):
|
||||
/// each family's lines, cut into dashes and dots that start from the line's own base point.
|
||||
/// `Ok` holds the pieces (empty when no line crosses the area) and whether any of them is a dot.
|
||||
pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Budget) -> Result<(BezPath, bool), NoPattern> {
|
||||
if lines.is_empty() {
|
||||
return Err(NoPattern::Undefined);
|
||||
}
|
||||
let exhausted = if budget.pieces == 0 {
|
||||
Some(NoPattern::DrawingPieces)
|
||||
} else if budget.work == 0 {
|
||||
Some(NoPattern::DrawingWork)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(why) = budget.stopped.or(exhausted) {
|
||||
budget.stopped = Some(why);
|
||||
return Err(why);
|
||||
}
|
||||
let mut out = BezPath::new();
|
||||
let Some(b) = super::curve::bounds(boundary) else { return Ok((out, false)) };
|
||||
let size = b.width().max(b.height());
|
||||
if !(size > 0.0 && size.is_finite()) {
|
||||
return Ok((out, false));
|
||||
}
|
||||
let edges = edges(boundary)?;
|
||||
if edges.is_empty() {
|
||||
return Ok((out, false));
|
||||
}
|
||||
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)];
|
||||
let center = b.center();
|
||||
// The precision of the boundary's coordinates: spacings and periods below it draw nothing apart.
|
||||
let tiny = LOCAL_TINY * center.to_vec2().hypot().max(size);
|
||||
let (mut work, mut pieces, mut dots, mut usable) = (0usize, 0usize, false, false);
|
||||
for l in lines {
|
||||
let a = l.angle.to_radians();
|
||||
let d = Vec2::new(a.cos(), a.sin());
|
||||
let n = Vec2::new(-d.y, d.x);
|
||||
let base = Point::new(l.base[0], l.base[1]);
|
||||
let offset = Vec2::new(l.offset[0], l.offset[1]);
|
||||
let step = offset.dot(n);
|
||||
// A family with numbers out of range is damaged: the others still draw.
|
||||
if ![a, base.x, base.y, offset.x, offset.y].iter().all(|v| v.is_finite()) || l.dashes.iter().any(|v| !v.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
usable = true;
|
||||
// Lines no distance apart, or closer than the coordinates can tell apart, fill the area
|
||||
// past what can be drawn.
|
||||
if step.abs() <= tiny {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
let period: f64 = l.dashes.iter().map(|v| v.abs()).sum();
|
||||
if !l.dashes.is_empty() && period <= tiny {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
// The same family from the line nearest the boundary's center, a whole number of offsets
|
||||
// away. The base and the center are each measured from the line through the origin
|
||||
// first, so a base far away keeps the fraction of the center's position.
|
||||
let (bn, cn) = (base.to_vec2().dot(n), center.to_vec2().dot(n));
|
||||
let (to_origin, to_center) = (-(bn / step).round(), (cn / step).round());
|
||||
let across = (bn + to_origin * step) + (to_center * step - cn);
|
||||
let last = -(across / step).round();
|
||||
let across = across + last * step;
|
||||
// Where the dashes start on that line, from its point nearest the center. Each line is
|
||||
// measured from its own point nearest the center, so its spans stay near the boundary
|
||||
// however long the dash period is. Each term is reduced to within half a period before
|
||||
// the terms are added, so a distant base or a large offset count keeps its remainder.
|
||||
let od = offset.dot(d);
|
||||
let along = if l.dashes.is_empty() {
|
||||
0.0
|
||||
} else {
|
||||
let ([o, oe], [c, ce]) = (product_parts(to_origin, od), product_parts(to_center + last, od));
|
||||
sum_rem(&[base.to_vec2().dot(d), -center.to_vec2().dot(d), o, oe, c, ce], period)
|
||||
};
|
||||
if !(across.is_finite() && along.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
// The dash start nearest a line's point nearest the center, as a signed distance.
|
||||
let phase = |k: f64| {
|
||||
let [p, e] = product_parts(k, od);
|
||||
sum_rem(&[along, p, e], period)
|
||||
};
|
||||
let base = center + n * across;
|
||||
// The lines crossing the boundary's box: base + k * step along the normal for whole k.
|
||||
let h = corners.map(|c| (c - base).dot(n) / step);
|
||||
let lo = h.iter().copied().fold(f64::INFINITY, f64::min).ceil();
|
||||
let hi = h.iter().copied().fold(f64::NEG_INFINITY, f64::max).floor();
|
||||
if hi < lo {
|
||||
continue;
|
||||
}
|
||||
let count = hi - lo + 1.0;
|
||||
if count * (edges.len() as f64) + work as f64 > MAX_WORK as f64 {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
let mut t = Vec::new();
|
||||
for k in (lo as i64)..=(hi as i64) {
|
||||
budget.work(&mut work, edges.len())?;
|
||||
let q = base + n * (step * k as f64);
|
||||
crossings(&edges, q, d, n, &mut t);
|
||||
for &[ta, tb] in t.as_chunks::<2>().0 {
|
||||
// Spans of no length at the precision of their own coordinates are dropped.
|
||||
if tb - ta <= LOCAL_TINY * (q.to_vec2().hypot() + ta.abs().max(tb.abs())) {
|
||||
continue;
|
||||
}
|
||||
let mut emit = |s0: f64, s1: f64, budget: &mut Budget| -> Result<(), NoPattern> {
|
||||
budget.piece(&mut pieces)?;
|
||||
out.move_to(q + d * s0);
|
||||
out.line_to(q + d * s1);
|
||||
Ok(())
|
||||
};
|
||||
if l.dashes.is_empty() {
|
||||
emit(ta, tb, budget)?;
|
||||
continue;
|
||||
}
|
||||
// The dashes run from the line's dash start, element by element, from the period
|
||||
// the span starts in.
|
||||
let start = phase(k as f64);
|
||||
let mut at = start + ((ta - start) / period).floor() * period;
|
||||
// Periods too short to move along the span, or more dashes than one hatch may
|
||||
// look at, are refused before any of them is looked at.
|
||||
let steps = ((tb - at) / period + 2.0) * l.dashes.len() as f64;
|
||||
if period <= LOCAL_TINY * at.abs().max(tb.abs()) || steps + work as f64 > MAX_WORK as f64 {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
// An element from `s` to `e`: a dash when `v` is positive, a dot when it is zero.
|
||||
let mut element = |s: f64, e: f64, v: f64, budget: &mut Budget| -> Result<(), NoPattern> {
|
||||
budget.work(&mut work, 1)?;
|
||||
if v > 0.0 {
|
||||
let (s0, s1) = (s.max(ta), e.min(tb));
|
||||
if s1 > s0 {
|
||||
emit(s0, s1, budget)?;
|
||||
}
|
||||
} else if v == 0.0 && s >= ta {
|
||||
emit(s, s, budget)?;
|
||||
dots = true;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
// When that period starts on the span's start, or past it, the elements that end
|
||||
// the period before are measured back from its end, so a dot there is kept and a
|
||||
// long period does not move them. Each element's start and end are the distances
|
||||
// summed back from that end, so a long element does not move its known end.
|
||||
if at >= ta {
|
||||
let (mut back, mut first) = (vec![0.0], l.dashes.len());
|
||||
while first > 0 && at - back[back.len() - 1] >= ta {
|
||||
first -= 1;
|
||||
back.push(back[back.len() - 1] + l.dashes[first].abs());
|
||||
}
|
||||
for (i, v) in l.dashes[first..].iter().enumerate() {
|
||||
let rest = back.len() - 1 - i;
|
||||
element(at - back[rest], at - back[rest - 1], *v, budget)?;
|
||||
}
|
||||
}
|
||||
'span: loop {
|
||||
for v in &l.dashes {
|
||||
if at > tb {
|
||||
break 'span;
|
||||
}
|
||||
element(at, at + v.abs(), *v, budget)?;
|
||||
at += v.abs();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !usable {
|
||||
return Err(NoPattern::Undefined);
|
||||
}
|
||||
Ok((out, dots))
|
||||
}
|
||||
|
||||
/// `x` less the whole number of periods nearest it, within half a period of zero. Both steps
|
||||
/// are exact: the remainder of a division, then one period added or taken away.
|
||||
fn near_rem(x: f64, period: f64) -> f64 {
|
||||
let r = x % period;
|
||||
if r > period / 2.0 {
|
||||
r - period
|
||||
} else if r < -period / 2.0 {
|
||||
r + period
|
||||
} else {
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// `a * b` as the rounded product and its rounding error, which add up to it exactly.
|
||||
fn product_parts(a: f64, b: f64) -> [f64; 2] {
|
||||
let p = a * b;
|
||||
[p, a.mul_add(b, -p)]
|
||||
}
|
||||
|
||||
/// The sum of `terms` reduced as [`near_rem`] does. Each term is reduced first, so a large term
|
||||
/// keeps its remainder, and the reduced terms are added with their rounding errors kept apart, so
|
||||
/// a small term is kept when larger ones cancel.
|
||||
fn sum_rem(terms: &[f64], period: f64) -> f64 {
|
||||
let (mut hi, mut lo) = (0.0, 0.0);
|
||||
for &t in terms {
|
||||
let t = near_rem(t, period);
|
||||
let s = hi + t;
|
||||
let v = s - hi;
|
||||
lo += (hi - (s - v)) + (t - v);
|
||||
hi = s;
|
||||
}
|
||||
near_rem(near_rem(hi, period) + near_rem(lo, period), period)
|
||||
}
|
||||
|
||||
/// The boundary's edges as straight segments, each loop closed and its curves flattened to
|
||||
/// within [`FLATNESS`] of the loop's own size. Loops of no size are left out.
|
||||
fn edges(boundary: &BezPath) -> Result<Vec<(Point, Point)>, NoPattern> {
|
||||
let mut loops: Vec<BezPath> = Vec::new();
|
||||
for el in boundary.elements() {
|
||||
if matches!(el, PathEl::MoveTo(_)) {
|
||||
loops.push(BezPath::new());
|
||||
}
|
||||
if let Some(l) = loops.last_mut() {
|
||||
l.push(*el);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut over = false;
|
||||
let mut push = |a: Point, b: Point, out: &mut Vec<(Point, Point)>| {
|
||||
if out.len() >= MAX_EDGES {
|
||||
over = true;
|
||||
} else if a != b {
|
||||
out.push((a, b));
|
||||
}
|
||||
};
|
||||
for lp in &loops {
|
||||
let Some(b) = super::curve::bounds(lp) else { continue };
|
||||
let tolerance = b.width().max(b.height()) * FLATNESS;
|
||||
if !(tolerance > 0.0 && tolerance.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let (mut start, mut last) = (None::<Point>, None::<Point>);
|
||||
kurbo::flatten(lp.iter(), tolerance, |el| match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
start = Some(p);
|
||||
last = Some(p);
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
if let Some(l) = last {
|
||||
push(l, p, &mut out);
|
||||
}
|
||||
last = Some(p);
|
||||
}
|
||||
PathEl::ClosePath => {
|
||||
if let (Some(s), Some(l)) = (start, last) {
|
||||
push(l, s, &mut out);
|
||||
}
|
||||
last = start;
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
if let (Some(s), Some(l)) = (start, last) {
|
||||
push(l, s, &mut out);
|
||||
}
|
||||
}
|
||||
if over { Err(NoPattern::TooDense) } else { Ok(out) }
|
||||
}
|
||||
|
||||
/// Where the line through `q` along `d` (unit; `n` its normal) crosses the edges, as distances
|
||||
/// from `q` along `d`, sorted into `t`. A vertex on the line counts once, for the edge that leaves
|
||||
/// the side the previous one came from.
|
||||
fn crossings(edges: &[(Point, Point)], q: Point, d: Vec2, n: Vec2, t: &mut Vec<f64>) {
|
||||
t.clear();
|
||||
for (p0, p1) in edges {
|
||||
let (h0, h1) = ((*p0 - q).dot(n), (*p1 - q).dot(n));
|
||||
if (h0 > 0.0) != (h1 > 0.0) {
|
||||
let p = p0.lerp(*p1, h0 / (h0 - h1));
|
||||
t.push((p - q).dot(d));
|
||||
}
|
||||
}
|
||||
t.sort_by(f64::total_cmp);
|
||||
}
|
||||
|
||||
/// The second color of a gradient: a color of its own, or for a one-color gradient the first
|
||||
/// one shaded toward black (tint 0) or tinted toward white (tint 1); 0.5 keeps it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum Second {
|
||||
Col(Col),
|
||||
Tint(f64),
|
||||
}
|
||||
|
||||
/// A gradient hatch's fill, placed in world coordinates (drawing units, y up).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Grad {
|
||||
pub kind: GradientKind,
|
||||
/// Linear: where the first stop sits and the last; radial: the center, a point on the outer
|
||||
/// ellipse and its aspect (a circle in the hatch's plane, an ellipse when the plane is seen
|
||||
/// at a slant).
|
||||
pub geom: GradientGeom,
|
||||
pub first: Col,
|
||||
pub second: Second,
|
||||
/// Each stop's position and whether it takes the second color (else the first).
|
||||
pub stops: Vec<(f32, bool)>,
|
||||
}
|
||||
|
||||
impl Grad {
|
||||
/// `first` shaded or tinted by `tint` (see [`Second::Tint`]).
|
||||
pub fn tinted([r, g, b]: [u8; 3], tint: f64) -> [u8; 3] {
|
||||
let t = if tint.is_finite() { tint.clamp(0.0, 1.0) } else { 0.5 };
|
||||
let mix = |c: u8| {
|
||||
let c = f64::from(c);
|
||||
let v = if t < 0.5 { c * t * 2.0 } else { c + (255.0 - c) * (t - 0.5) * 2.0 };
|
||||
v.round().clamp(0.0, 255.0) as u8
|
||||
};
|
||||
[mix(r), mix(g), mix(b)]
|
||||
}
|
||||
}
|
||||
|
||||
fn col(c: model::Color) -> Col {
|
||||
match c {
|
||||
model::Color::Rgb(rgb) => Col::Rgb(rgb),
|
||||
model::Color::Index(i) => Col::Rgb(aci_paper(i)),
|
||||
model::Color::ByBlock => Col::ByBlock,
|
||||
model::Color::ByLayer => Col::ByLayer,
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill of gradient `g` over `boundary` (in the hatch's plane; `ocs` takes it to world
|
||||
/// coordinates), `own` standing in for colors the gradient lacks. The gradient runs at its angle
|
||||
/// across the boundary's extent in that direction. VectorCraft draws the named gradients this way:
|
||||
/// `LINEAR` the first color to the second; `CYLINDER` the second color in the middle of the first;
|
||||
/// `SPHERICAL` a circle from the second color at the center to the first; `HEMISPHERICAL` the same
|
||||
/// circle centered on the bottom edge; `CURVED` the second color at the bottom to the first at the
|
||||
/// top; each `INV` name the two colors the other way round; any other name as `LINEAR`. The shift
|
||||
/// moves the center up and left by up to a quarter of the extent.
|
||||
pub(crate) fn gradient(g: &model::Gradient, boundary: &BezPath, ocs: Affine, own: Col) -> Option<Grad> {
|
||||
let angle = if g.angle.is_finite() { g.angle } else { 0.0 };
|
||||
let mut frame = boundary.clone();
|
||||
frame.apply_affine(Affine::rotate(-angle));
|
||||
let r = super::curve::bounds(&frame)?;
|
||||
let (w, h) = (r.width(), r.height());
|
||||
let shift = if g.shift.is_finite() { g.shift.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let c = r.center() + Vec2::new(-w, h) * (shift / 4.0);
|
||||
// How far the shift moves the center left and up.
|
||||
let (dx, dy) = (c.x - r.center().x, c.y - r.center().y);
|
||||
let name = g.name.trim().to_uppercase();
|
||||
let (inverse, name) = match name.strip_prefix("INV") {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, name.as_str()),
|
||||
};
|
||||
let swap = |stops: &[(f32, bool)]| stops.iter().map(|(o, s)| (*o, *s != inverse)).collect::<Vec<_>>();
|
||||
let (kind, start, end, stops) = match name {
|
||||
"CYLINDER" => {
|
||||
(GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (0.5, true), (1.0, false)]))
|
||||
}
|
||||
"SPHERICAL" => (GradientKind::Radial, c, c + Vec2::new(w.max(h) / 2.0, 0.0), swap(&[(0.0, true), (1.0, false)])),
|
||||
"HEMISPHERICAL" => {
|
||||
let center = Point::new(c.x, r.y0 + dy);
|
||||
(GradientKind::Radial, center, center + Vec2::new((w / 2.0).max(h), 0.0), swap(&[(0.0, true), (1.0, false)]))
|
||||
}
|
||||
"CURVED" => (GradientKind::Linear, Point::new(c.x, r.y0 + dy), Point::new(c.x, r.y1 + dy), swap(&[(0.0, true), (1.0, false)])),
|
||||
_ => (GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (1.0, true)])),
|
||||
};
|
||||
let mut geom = GradientGeom { start, end, aspect: 1.0, focal: None };
|
||||
geom.transform(ocs * Affine::rotate(angle), kind);
|
||||
let first = g.colors.first().map_or(own, |c| col(*c));
|
||||
let second = if g.single { Second::Tint(g.tint) } else { Second::Col(g.colors.get(1).map_or(first, |c| col(*c))) };
|
||||
Some(Grad { kind, geom, first, second, stops })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pattern(lines: &[PatternLine], boundary: &BezPath) -> Result<(BezPath, bool), NoPattern> {
|
||||
let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None };
|
||||
super::pattern(lines, boundary, &mut budget)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_budgets_charge_discarded_patterns_and_stop_later_hatches() {
|
||||
let lines = [line(0.0, [0.0, 1.0], &[])];
|
||||
let boundary = square(10.0);
|
||||
let mut budget = Budget { pieces: 3, work: 100, stopped: None };
|
||||
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingPieces));
|
||||
assert_eq!(budget.pieces, 0);
|
||||
assert!(budget.work < 100);
|
||||
let work = budget.work;
|
||||
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingPieces));
|
||||
assert_eq!(budget.work, work, "later hatches do no clipping");
|
||||
|
||||
let mut budget = Budget { pieces: 100, work: 9, stopped: None };
|
||||
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingWork));
|
||||
assert_eq!(budget.work, 1, "two lines cost four edges each");
|
||||
let pieces = budget.pieces;
|
||||
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingWork));
|
||||
assert_eq!((budget.work, budget.pieces), (1, pieces));
|
||||
|
||||
let gaps = [line(0.0, [0.0, 1.0], &[-0.01])];
|
||||
let mut budget = Budget { pieces: 100, work: 20, stopped: None };
|
||||
assert_eq!(super::pattern(&gaps, &boundary, &mut budget), Err(NoPattern::DrawingWork));
|
||||
assert_eq!((budget.work, budget.pieces), (0, 100), "gaps cost work without drawing pieces");
|
||||
}
|
||||
|
||||
fn square(side: f64) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.line_to((side, 0.0));
|
||||
bp.line_to((side, side));
|
||||
bp.line_to((0.0, side));
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
|
||||
fn line(angle: f64, offset: [f64; 2], dashes: &[f64]) -> PatternLine {
|
||||
PatternLine { angle, base: [0.0, 0.0], offset, dashes: dashes.to_vec() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doubling_adds_a_perpendicular_family_only_when_one_is_present() {
|
||||
let mut level = line(0.0, [3.0, 10.0], &[4.0, -2.0]);
|
||||
level.base = [2.0, 5.0];
|
||||
let lines = doubled(&[level.clone()]);
|
||||
let [first, second] = &lines[..] else { panic!("two families") };
|
||||
assert_eq!((first.angle, first.base, first.offset, &first.dashes), (level.angle, level.base, level.offset, &level.dashes));
|
||||
assert_eq!(second.angle, level.angle + 90.0);
|
||||
assert_eq!(second.offset, [-level.offset[1], level.offset[0]]);
|
||||
assert_eq!((second.base, &second.dashes), (level.base, &level.dashes));
|
||||
let kept = doubled(&lines);
|
||||
assert_eq!(kept.len(), lines.len());
|
||||
for (a, b) in kept.iter().zip(&lines) {
|
||||
assert_eq!((a.angle, a.base, a.offset, &a.dashes), (b.angle, b.base, b.offset, &b.dashes));
|
||||
}
|
||||
}
|
||||
|
||||
/// The pieces as (start, end) pairs.
|
||||
fn pieces(bp: &BezPath) -> Vec<(Point, Point)> {
|
||||
let mut out = vec![];
|
||||
let mut from = Point::ZERO;
|
||||
for el in bp.elements() {
|
||||
match el {
|
||||
PathEl::MoveTo(p) => from = *p,
|
||||
PathEl::LineTo(p) => out.push((from, *p)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_lines_stop_at_the_boundary_and_skip_holes() {
|
||||
// Horizontal lines 10 apart, through y 5, 15 … 95, across a 100 square with a 20 square
|
||||
// hole in the middle.
|
||||
let mut boundary = square(100.0);
|
||||
let mut hole = square(20.0);
|
||||
hole.apply_affine(Affine::translate((40.0, 40.0)));
|
||||
boundary.extend(hole);
|
||||
let l = PatternLine { angle: 0.0, base: [0.0, 5.0], offset: [0.0, 10.0], dashes: vec![] };
|
||||
let (bp, dots) = pattern(&[l], &boundary).unwrap();
|
||||
assert!(!dots);
|
||||
let p = pieces(&bp);
|
||||
// Ten lines, the two through the hole (y 45 and 55) each cut in two.
|
||||
assert_eq!(p.len(), 12, "{p:?}");
|
||||
for (a, b) in &p {
|
||||
assert!((a.y - b.y).abs() < 1e-9 && a.x >= -1e-9 && b.x <= 100.0 + 1e-9);
|
||||
}
|
||||
let middle: Vec<_> = p.iter().filter(|(a, _)| (a.y - 45.0).abs() < 1e-9).collect();
|
||||
assert_eq!(middle.len(), 2);
|
||||
assert!(middle.iter().all(|(a, b)| b.x <= 40.0 + 1e-9 || a.x >= 60.0 - 1e-9), "{middle:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashes_start_at_each_lines_base_point() {
|
||||
// Dash 3, gap 2, a dot, gap 5: period 10 from x = 0, lines staggered by 5 along them.
|
||||
let l = PatternLine { angle: 0.0, base: [0.0, 0.0], offset: [5.0, 50.0], dashes: vec![3.0, -2.0, 0.0, -5.0] };
|
||||
let (bp, dots) = pattern(&[l], &square(100.0)).unwrap();
|
||||
assert!(dots);
|
||||
let p = pieces(&bp);
|
||||
let row = |y: f64| p.iter().filter(|(a, _)| (a.y - y).abs() < 1e-9).map(|(a, b)| (a.x, b.x)).collect::<Vec<_>>();
|
||||
let first = row(50.0);
|
||||
assert!(first.len() > 4, "{first:?}");
|
||||
// The pattern at y 50 starts at x 5, so the period before it puts a dot on the boundary.
|
||||
assert_eq!(&first[..4], &[(0.0, 0.0), (5.0, 8.0), (10.0, 10.0), (15.0, 18.0)]);
|
||||
assert!(first.iter().all(|(a, b)| *a >= 0.0 && *b <= 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dash_across_the_boundary_is_cut_there() {
|
||||
let (bp, _) = pattern(&[line(0.0, [0.0, 7.0], &[30.0, -10.0])], &square(50.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert!(p.iter().any(|(a, b)| (a.x - 0.0).abs() < 1e-9 && (b.x - 30.0).abs() < 1e-9));
|
||||
// The second dash, 40 to 70, crosses the boundary at 50 and stops there.
|
||||
assert!(p.iter().any(|(a, b)| (a.x - 40.0).abs() < 1e-9 && (b.x - 50.0).abs() < 1e-9), "{p:?}");
|
||||
assert!(p.iter().all(|(_, b)| b.x <= 50.0 + 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_spans_far_apart_keep_their_pieces_and_curves() {
|
||||
// Two strips 1 wide and 100 tall, 10 billion units apart: each level line keeps its
|
||||
// one-unit spans.
|
||||
let strip = |x: f64| {
|
||||
let mut s = square(1.0);
|
||||
s.apply_affine(Affine::translate((x, 0.0)) * Affine::scale_non_uniform(1.0, 100.0));
|
||||
s
|
||||
};
|
||||
let mut boundary = strip(0.0);
|
||||
boundary.extend(strip(1e10));
|
||||
let l = PatternLine { angle: 0.0, base: [0.0, 25.0], offset: [0.0, 50.0], dashes: vec![] };
|
||||
let (bp, _) = pattern(std::slice::from_ref(&l), &boundary).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert_eq!(p.len(), 4, "{p:?}");
|
||||
assert!(p.iter().all(|(a, b)| ((b.x - a.x) - 1.0).abs() < 1e-3), "{p:?}");
|
||||
// Unit circles as far apart keep their round outlines: the line through y 0.5 spans
|
||||
// 2 * sqrt(0.75) of each.
|
||||
let circle = |x: f64| kurbo::Shape::to_path(&kurbo::Circle::new((x, 0.0), 1.0), 0.1);
|
||||
let mut boundary = circle(0.0);
|
||||
boundary.extend(circle(1e10));
|
||||
let l = PatternLine { angle: 0.0, base: [0.0, 0.5], offset: [0.0, 100.0], dashes: vec![] };
|
||||
let (bp, _) = pattern(&[l], &boundary).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert_eq!(p.len(), 2, "{p:?}");
|
||||
let chord = 2.0 * 0.75f64.sqrt();
|
||||
assert!(p.iter().all(|(a, b)| ((b.x - a.x).abs() - chord).abs() < chord * 1e-2), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_lines_across_squares_far_apart_are_drawn() {
|
||||
// Two unit squares 10 billion units apart, lines 0.5 apart: two lines cross each square.
|
||||
let mut boundary = square(1.0);
|
||||
let mut far = square(1.0);
|
||||
far.apply_affine(Affine::translate((1e10, 0.0)));
|
||||
boundary.extend(far);
|
||||
let (bp, _) = pattern(&[line(0.0, [0.0, 0.5], &[])], &boundary).unwrap();
|
||||
assert_eq!(pieces(&bp).len(), 4, "{:?}", pieces(&bp));
|
||||
// Dashes 0.25 long with 0.25 gaps: two per line in each square.
|
||||
let (bp, _) = pattern(&[line(0.0, [0.0, 0.5], &[0.25, -0.25])], &boundary).unwrap();
|
||||
assert_eq!(pieces(&bp).len(), 8, "{:?}", pieces(&bp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn families_based_far_away_draw_the_same_lines() {
|
||||
// Lines one apart from a base 1e19 up are the lines one apart from the origin.
|
||||
let mut far = line(0.0, [0.0, 1.0], &[]);
|
||||
far.base = [0.0, 1e19];
|
||||
let (bp, _) = pattern(&[far], &square(100.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert_eq!(p.len(), 100, "{p:?}");
|
||||
assert!(p.iter().all(|(a, b)| a.y == b.y && a.y.fract() == 0.0 && (0.0..100.0).contains(&a.y)), "{p:?}");
|
||||
// A staggered family based 100 lines away keeps each line's dash phase.
|
||||
let mut near = line(0.0, [5.0, 10.0], &[3.0, -7.0]);
|
||||
near.base = [-497.0, 0.0];
|
||||
let mut away = near.clone();
|
||||
away.base = [3.0, 1000.0];
|
||||
let sorted = |l: PatternLine| {
|
||||
let mut p = pieces(&pattern(&[l], &square(100.0)).unwrap().0);
|
||||
p.sort_by(|a, b| (a.0.y, a.0.x).partial_cmp(&(b.0.y, b.0.x)).unwrap_or(std::cmp::Ordering::Equal));
|
||||
p
|
||||
};
|
||||
let (a, b) = (sorted(near), sorted(away));
|
||||
assert_eq!(a.len(), b.len());
|
||||
assert!(!a.is_empty());
|
||||
assert!(a.iter().zip(&b).all(|(x, y)| x.0.distance(y.0) < 1e-9 && x.1.distance(y.1) < 1e-9), "{a:?} {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn families_based_far_away_keep_lines_off_a_fractional_center() {
|
||||
// A 3 square centered on y 1.5: lines one apart from a base 1e19 up run at whole y, not
|
||||
// through the center.
|
||||
let mut far = line(0.0, [0.0, 1.0], &[]);
|
||||
far.base = [0.0, 1e19];
|
||||
let (bp, _) = pattern(&[far], &square(3.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert!(p.len() >= 2, "{p:?}");
|
||||
assert!(p.iter().all(|(a, b)| a.y == b.y && a.y.fract() == 0.0), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_periods_far_longer_than_the_boundary_still_draw() {
|
||||
// Dashes 1e16 long from x 0, and from x -7.5e15: each row of the 100 square lies in a
|
||||
// dash, so every row is drawn across the square.
|
||||
for x in [0.0, -7.5e15] {
|
||||
let mut l = line(0.0, [0.0, 10.0], &[1e16, -1e16]);
|
||||
l.base = [x, 0.0];
|
||||
let (bp, _) = pattern(&[l], &square(100.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
let rows: Vec<_> = p.iter().filter(|(a, _)| a.y > 0.0 && a.y < 100.0).collect();
|
||||
assert_eq!(rows.len(), 9, "base x {x}: {p:?}");
|
||||
assert!(rows.iter().all(|(a, b)| a.x.abs() < 1e-9 && (b.x - 100.0).abs() < 1e-9), "base x {x}: {p:?}");
|
||||
}
|
||||
// From x 5e15 the square lies in a gap: nothing is drawn.
|
||||
let mut l = line(0.0, [0.0, 10.0], &[1e16, -1e16]);
|
||||
l.base = [5e15, 0.0];
|
||||
let (bp, _) = pattern(&[l], &square(100.0)).unwrap();
|
||||
assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_offset_counts_that_cancel_keep_the_dash_start() {
|
||||
// A 100 square 2^40 up, its family based on the row through its middle with offsets
|
||||
// 2^30 along: the row's dashes start at x 0, so it draws 0 to 30.
|
||||
let b = 2f64.powi(40);
|
||||
let mut boundary = square(100.0);
|
||||
boundary.apply_affine(Affine::translate((0.0, b)));
|
||||
let mut l = line(0.0, [2f64.powi(30), 1024.0], &[30.0, -70.0]);
|
||||
l.base = [0.0, b + 50.0];
|
||||
let p = pieces(&pattern(&[l], &boundary).unwrap().0);
|
||||
let row: Vec<_> = p.iter().filter(|(a, _)| a.y == b + 50.0).map(|(a, e)| (a.x, e.x)).collect();
|
||||
assert_eq!(row.len(), 1, "{p:?}");
|
||||
assert!((row[0].0 - 0.0).abs() < 1e-9 && (row[0].1 - 30.0).abs() < 1e-9, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_phase_terms_that_cancel_keep_a_small_one() {
|
||||
// Based and offset by 2^54 along and 10 up: the line one offset back runs along the
|
||||
// bottom of the unit square with its dash 16 long from x 0, so it covers 0 to 1.
|
||||
let big = 2f64.powi(54);
|
||||
let mut l = line(0.0, [big, 10.0], &[16.0, -(2f64.powi(57) - 16.0)]);
|
||||
l.base = [big, 10.0];
|
||||
let p = pieces(&pattern(&[l], &square(1.0)).unwrap().0);
|
||||
let row: Vec<_> = p.iter().filter(|(a, _)| a.y == 0.0).map(|(a, e)| (a.x, e.x)).collect();
|
||||
assert_eq!(row, [(0.0, 1.0)], "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_dash_before_the_boundary_ends_where_its_gap_starts() {
|
||||
// A gap 1e16 long from x 0, after a dash 1e16 long that ends at x 0: the unit square
|
||||
// lies in the gap, so nothing is drawn.
|
||||
let mut l = line(0.0, [0.0, 10.0], &[-1e16, 1e16]);
|
||||
l.base = [0.0, 0.5];
|
||||
let (bp, _) = pattern(&[l], &square(1.0)).unwrap();
|
||||
assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distant_bases_keep_their_dash_remainder() {
|
||||
// Dash 1, gap 5 from x 1e19, which is 4 more than a whole number of periods of 6: the
|
||||
// dashes run 4 to 5, 10 to 11 … 94 to 95 in squares centered on a whole and a half x.
|
||||
for side in [96.0, 98.0] {
|
||||
let mut l = line(0.0, [0.0, 10.0], &[1.0, -5.0]);
|
||||
l.base = [1e19, 0.0];
|
||||
let p = pieces(&pattern(&[l], &square(side)).unwrap().0);
|
||||
let row: Vec<_> = p.iter().filter(|(a, _)| a.y == 50.0).map(|(a, e)| (a.x, e.x)).collect();
|
||||
assert_eq!(row.len(), 16, "side {side}: {row:?}");
|
||||
assert!(
|
||||
row.iter().enumerate().all(|(i, (a, e))| (a - (4.0 + 6.0 * i as f64)).abs() < 1e-9 && (e - a - 1.0).abs() < 1e-9),
|
||||
"side {side}: {row:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dot_on_the_start_of_a_span_is_kept() {
|
||||
// A gap of 5 then a dot, from x 0: dots at 0, 5 and 10 on the line along the bottom.
|
||||
let (bp, dots) = pattern(&[line(0.0, [0.0, 20.0], &[-5.0, 0.0])], &square(10.0)).unwrap();
|
||||
assert!(dots);
|
||||
let xs: Vec<f64> = pieces(&bp).iter().filter(|(a, _)| a.y == 0.0).map(|(a, _)| a.x).collect();
|
||||
assert_eq!(xs, [0.0, 5.0, 10.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slanted_lines_fill_a_square_evenly() {
|
||||
// 45 degree lines 1 apart across the square's diagonal of 14.1: each piece runs from one
|
||||
// side of the square to another.
|
||||
let offset = [-(0.5f64.sqrt()), 0.5f64.sqrt()];
|
||||
let (bp, _) = pattern(&[line(45.0, offset, &[])], &square(10.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert!((14..=15).contains(&p.len()), "{} lines", p.len());
|
||||
let on_edge = |q: Point| [q.x, q.y].iter().any(|v| v.abs() < 1e-6 || (v - 10.0).abs() < 1e-6);
|
||||
assert!(p.iter().all(|(a, b)| on_edge(*a) && on_edge(*b)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_dense_patterns_and_missing_ones_are_reported() {
|
||||
assert_eq!(pattern(&[], &square(10.0)), Err(NoPattern::Undefined));
|
||||
// Lines 0.001 apart across a 1,000 square: a million lines.
|
||||
assert_eq!(pattern(&[line(0.0, [0.0, 0.001], &[])], &square(1000.0)), Err(NoPattern::TooDense));
|
||||
// Few lines, but dashes far shorter than the square: more pieces than allowed.
|
||||
assert_eq!(pattern(&[line(0.0, [0.0, 10.0], &[0.01, -0.01])], &square(1000.0)), Err(NoPattern::TooDense));
|
||||
// A tiny nonempty dash period is too dense; only an empty list draws continuous lines.
|
||||
// It is refused once the first line is clipped, before any of its dashes is looked at.
|
||||
let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None };
|
||||
assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-12])], &square(10.0), &mut budget), Err(NoPattern::TooDense));
|
||||
assert_eq!(budget.work, usize::MAX - 4, "one line clipped against four edges, no dashes looked at");
|
||||
// A period below the coordinates' precision is refused before any line is clipped.
|
||||
let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None };
|
||||
assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-15])], &square(10.0), &mut budget), Err(NoPattern::TooDense));
|
||||
assert_eq!(budget.work, usize::MAX, "no work done");
|
||||
let (bp, _) = pattern(&[line(0.0, [0.0, 1.0], &[])], &square(10.0)).unwrap();
|
||||
assert!(!pieces(&bp).is_empty());
|
||||
// Lines on top of each other, or as good as, are as dense as can be.
|
||||
assert_eq!(pattern(&[line(0.0, [5.0, 0.0], &[])], &square(10.0)), Err(NoPattern::TooDense));
|
||||
assert_eq!(pattern(&[line(0.0, [0.0, 1e-7], &[])], &square(1000.0)), Err(NoPattern::TooDense));
|
||||
// Only damaged families: no pattern to draw.
|
||||
assert_eq!(pattern(&[line(f64::NAN, [0.0, 1.0], &[])], &square(10.0)), Err(NoPattern::Undefined));
|
||||
}
|
||||
|
||||
fn grad(name: &str, angle: f64, shift: f64) -> model::Gradient {
|
||||
model::Gradient {
|
||||
name: name.into(),
|
||||
angle,
|
||||
shift,
|
||||
single: false,
|
||||
tint: 0.0,
|
||||
colors: vec![model::Color::Index(1), model::Color::Rgb([0, 0, 255])],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradients_run_across_the_boundary_at_their_angle() {
|
||||
let box_ = {
|
||||
let mut b = square(100.0);
|
||||
b.apply_affine(Affine::scale_non_uniform(2.0, 1.0));
|
||||
b
|
||||
};
|
||||
let g = gradient(&grad("LINEAR", 0.0, 0.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!((g.kind, g.geom.start, g.geom.end), (GradientKind::Linear, Point::new(0.0, 50.0), Point::new(200.0, 50.0)));
|
||||
assert_eq!((g.first, g.second), (Col::Rgb(aci_paper(1)), Second::Col(Col::Rgb([0, 0, 255]))));
|
||||
assert_eq!(g.stops, [(0.0, false), (1.0, true)]);
|
||||
// At a quarter turn it runs bottom to top.
|
||||
let g = gradient(&grad("LINEAR", std::f64::consts::FRAC_PI_2, 0.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert!(g.geom.start.distance(Point::new(100.0, 0.0)) < 1e-9 && g.geom.end.distance(Point::new(100.0, 100.0)) < 1e-9, "{g:?}");
|
||||
// Shifted, the center moves up and left: a sphere's center and a cylinder's middle.
|
||||
let g = gradient(&grad("SPHERICAL", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!((g.kind, g.geom.start), (GradientKind::Radial, Point::new(50.0, 75.0)));
|
||||
assert_eq!(g.stops, [(0.0, true), (1.0, false)], "the second color in the center");
|
||||
let g = gradient(&grad("CYLINDER", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!(g.geom.start.midpoint(g.geom.end), Point::new(50.0, 75.0));
|
||||
// A curved gradient runs bottom to top, so the shift moves it up.
|
||||
for name in ["CURVED", "INVCURVED"] {
|
||||
let g = gradient(&grad(name, 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!((g.geom.start, g.geom.end), (Point::new(50.0, 25.0), Point::new(50.0, 125.0)), "{name}");
|
||||
}
|
||||
// A plane stretched twice as wide stretches the circle into an ellipse with it.
|
||||
let g = gradient(&grad("SPHERICAL", 0.0, 0.0), &square(10.0), Affine::scale_non_uniform(2.0, 1.0), Col::ByLayer).unwrap();
|
||||
assert!((g.geom.aspect - 0.5).abs() < 1e-9 && g.geom.end.distance(Point::new(20.0, 5.0)) < 1e-9, "{:?}", g.geom);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_gradients_swap_their_colors() {
|
||||
for (name, inv) in
|
||||
[("CYLINDER", "INVCYLINDER"), ("SPHERICAL", "INVSPHERICAL"), ("HEMISPHERICAL", "INVHEMISPHERICAL"), ("CURVED", "INVCURVED")]
|
||||
{
|
||||
let a = gradient(&grad(name, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
let b = gradient(&grad(inv, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!((a.kind, a.geom), (b.kind, b.geom), "{name}");
|
||||
let count = if name == "CYLINDER" { 3 } else { 2 };
|
||||
assert_eq!((a.stops.len(), b.stops.len()), (count, count), "{name}");
|
||||
assert!(a.stops.iter().zip(&b.stops).all(|(x, y)| x.0 == y.0 && x.1 != y.1), "{name}: {:?} {:?}", a.stops, b.stops);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_color_gradients_shade_or_tint_their_color() {
|
||||
assert_eq!(Grad::tinted([200, 100, 0], 0.0), [0, 0, 0]);
|
||||
assert_eq!(Grad::tinted([200, 100, 0], 0.5), [200, 100, 0]);
|
||||
assert_eq!(Grad::tinted([200, 100, 0], 1.0), [255, 255, 255]);
|
||||
assert_eq!(Grad::tinted([200, 100, 0], 0.25), [100, 50, 0]);
|
||||
let mut g = grad("LINEAR", 0.0, 0.0);
|
||||
(g.single, g.tint, g.colors) = (true, 0.75, vec![]);
|
||||
let g = gradient(&g, &square(10.0), Affine::IDENTITY, Col::ByBlock).unwrap();
|
||||
assert_eq!((g.first, g.second), (Col::ByBlock, Second::Tint(0.75)), "no color record: the hatch's own color");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! 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.
|
||||
//! linetype and text style tables; the blocks; the entities; the layouts; the image files.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
@@ -50,6 +50,15 @@ pub(crate) struct BlockDef<'a> {
|
||||
pub xref: bool,
|
||||
}
|
||||
|
||||
/// A raster image file that IMAGE entities show (an IMAGEDEF object).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ImageFile {
|
||||
/// The file's path as the drawing stores it (absolute, or relative to the drawing).
|
||||
pub path: String,
|
||||
/// Its size in pixels (0 when not given).
|
||||
pub size: [f64; 2],
|
||||
}
|
||||
|
||||
/// A layout: model space, or a paper layout with the block holding its art.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct LayoutDef {
|
||||
@@ -80,6 +89,8 @@ pub(crate) struct Drawing<'a> {
|
||||
pub entities: Vec<EntityRecord<'a>>,
|
||||
/// Model space first, then the paper layouts in tab order.
|
||||
pub layouts: Vec<LayoutDef>,
|
||||
/// The image files by the handle of their IMAGEDEF.
|
||||
pub images: HashMap<u64, ImageFile>,
|
||||
/// 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
|
||||
@@ -116,6 +127,11 @@ impl<'a> Drawing<'a> {
|
||||
}
|
||||
let block_names = doc.block_names();
|
||||
d.layouts = layouts(&doc, &block_names);
|
||||
for def in doc.objects_of("IMAGEDEF").map(model::objects::ImageDef::read) {
|
||||
if let Some(h) = def.handle {
|
||||
d.images.entry(h).or_insert(ImageFile { path: def.file, size: def.size });
|
||||
}
|
||||
}
|
||||
d.regions = Rc::new(region_data(&doc));
|
||||
for b in doc.blocks {
|
||||
if b.name.is_empty() {
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::ParamCurve;
|
||||
use kurbo::{ParamCurve, Shape};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Justify, Node, NodeKind, TextObject, Unit};
|
||||
use vectorcraft_doc::{Appearance, Document, Justify, LineCap, Node, NodeKind, TextObject, Unit};
|
||||
use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes};
|
||||
|
||||
use super::*;
|
||||
@@ -505,6 +505,593 @@ fn solid_hatches_fill_and_pattern_hatches_outline() {
|
||||
assert!(square.appearance.fill().is_some_and(|f| !f.paint.is_none()));
|
||||
}
|
||||
|
||||
/// [`hatch`]'s square with a round hole, as a pattern hatch of level lines 10 apart through
|
||||
/// y 5, 15 … 95, in linetype `linetype`, with `dashes` (79 and 49 groups).
|
||||
fn pattern_hatch(linetype: &'static str, dashes: &[(i32, &'static str)]) -> Vec<(i32, &'static str)> {
|
||||
let mut e = hatch("0");
|
||||
e.insert(1, (6, linetype));
|
||||
let seeds = e.iter().position(|p| *p == (98, "0")).unwrap();
|
||||
let mut lines = vec![(78, "1"), (53, "0"), (43, "0"), (44, "5"), (45, "0"), (46, "10")];
|
||||
lines.extend_from_slice(if dashes.is_empty() { &[(79, "0")] } else { dashes });
|
||||
e.splice(seeds..seeds, lines);
|
||||
e
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignore_islands_hatches_fill_and_pattern_through_the_hole() {
|
||||
let mut e = hatch("1");
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "ignore islands leaves only the outer square");
|
||||
assert!(path.subpaths[0].closed);
|
||||
assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none()));
|
||||
let box_area = bounds(area).area();
|
||||
assert!((path.to_bezpath().area().abs() - box_area).abs() < box_area * 1e-9, "the whole square is filled");
|
||||
|
||||
let mut e = pattern_hatch("CONTINUOUS", &[]);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) };
|
||||
assert_eq!(children.len(), 10, "the ten level lines are not cut by the hole");
|
||||
let width = bounds(lines).width();
|
||||
assert!(children.iter().all(|c| (bounds(c).width() - width).abs() < width * 1e-9), "each line spans the square");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_island_styles_select_nested_boundary_levels() {
|
||||
let mut e = hatch("1");
|
||||
let count = e.iter().position(|p| p.0 == 91).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
e[count] = (91, "3");
|
||||
let mut loops = Vec::new();
|
||||
// Innermost first so nesting depends on geometry, not boundary order or flags.
|
||||
for (lo, hi) in [("40", "60"), ("0", "100"), ("20", "80")] {
|
||||
loops.extend([
|
||||
(92, "2"),
|
||||
(72, "0"),
|
||||
(73, "1"),
|
||||
(93, "4"),
|
||||
(10, lo),
|
||||
(20, lo),
|
||||
(10, hi),
|
||||
(20, lo),
|
||||
(10, hi),
|
||||
(20, hi),
|
||||
(10, lo),
|
||||
(20, hi),
|
||||
(97, "0"),
|
||||
]);
|
||||
}
|
||||
e.splice(count + 1..end, loops);
|
||||
// The sides of the squares each style keeps: normal and unknown styles all three, outer the
|
||||
// outermost and middle ones, ignore the outermost alone.
|
||||
for (style, expected) in [("0", &[20.0, 60.0, 100.0][..]), ("1", &[60.0, 100.0]), ("2", &[100.0]), ("3", &[20.0, 60.0, 100.0])] {
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style);
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "style {style}: {:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let mut sides: Vec<f64> = match &area.kind {
|
||||
NodeKind::Compound { children, rule } => {
|
||||
assert_eq!(*rule, FillRule::EvenOdd);
|
||||
children.iter().map(|c| bounds(c).width().round()).collect()
|
||||
}
|
||||
_ => {
|
||||
assert_eq!(area.path_data().unwrap().subpaths.len(), 1);
|
||||
vec![bounds(area).width().round()]
|
||||
}
|
||||
};
|
||||
sides.sort_by(f64::total_cmp);
|
||||
assert_eq!(sides, expected, "boundary loops for island style {style}");
|
||||
assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_small_island_far_from_origin() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
for (lo, hi) in [("100000000", "100000001"), ("100000000.2", "100000000.8")] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
// Centered, so the art far from the drawing's origin lands on the canvas.
|
||||
let r = open(&entities(&e), &ImportOptions { center: true, ..points() });
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the small island far from the origin is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_small_island_with_distant_outer_loop() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
*e.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "3");
|
||||
let mut loops = Vec::new();
|
||||
for (lo, hi) in [("0", "1"), ("0.2", "0.8"), ("100000000", "100000001")] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
// Fitted to the artboard: the drawing spans more than the canvas holds at 1:1.
|
||||
let r = open(&entities(&e), &ImportOptions { fit: true, ..points() });
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &area.kind else { panic!("both outer boundary loops must remain") };
|
||||
assert_eq!(children.len(), 2, "the island is removed and both outer squares remain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_tiny_island_with_distant_outer_loop() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
*e.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "3");
|
||||
let mut loops = Vec::new();
|
||||
for (lo, hi) in [("0", "0.000001"), ("0.0000002", "0.0000008"), ("100000000000", "100000000001")] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
// Fitted to the artboard: the drawing spans more than the canvas holds at 1:1.
|
||||
let r = open(&entities(&e), &ImportOptions { fit: true, ..points() });
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &area.kind else { panic!("both outer boundary loops must remain") };
|
||||
assert_eq!(children.len(), 2, "the tiny island is removed and both outer squares remain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_keeps_squares_sharing_an_edge() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
// The first vertex lies on the second square's left edge.
|
||||
for vertices in [[("10", "0"), ("10", "10"), ("0", "10"), ("0", "0")], [("10", "0"), ("20", "0"), ("20", "10"), ("10", "10")]] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &area.kind else { panic!("both boundary loops must remain") };
|
||||
assert_eq!(children.len(), 2, "adjacent squares are both boundaries");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_square_touching_outer_boundary_at_a_vertex() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
// The island's first vertex touches the outer square's right edge, where
|
||||
// winding is zero. Its other vertices and all segment midpoints are inside.
|
||||
for vertices in [[("100", "50"), ("75", "75"), ("50", "50"), ("75", "25")], [("0", "0"), ("100", "0"), ("100", "100"), ("0", "100")]] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the touching island is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_square_sharing_two_outer_edges() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
for vertices in [[("50", "50"), ("100", "50"), ("100", "100"), ("50", "100")], [("0", "0"), ("100", "0"), ("100", "100"), ("0", "100")]] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the island sharing two outer edges is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_thin_island() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
for vertices in [
|
||||
[("0", "0"), ("100", "0"), ("100", "0.00001"), ("0", "0.00001")],
|
||||
[("10", "0.000002"), ("90", "0.000002"), ("90", "0.000008"), ("10", "0.000008")],
|
||||
] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the thin island is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_rotated_thin_island() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
// These are the previous test's corners turned 45 degrees about the origin.
|
||||
for vertices in [
|
||||
[("0", "0"), ("70.7106781187", "70.7106781187"), ("70.7106710476", "70.7106851897"), ("-0.00000707106781187", "0.00000707106781187")],
|
||||
[
|
||||
("7.07106639765", "7.07106922608"),
|
||||
("63.6396088926", "63.6396117210"),
|
||||
("63.6396046499", "63.6396159636"),
|
||||
("7.07106215421", "7.07107346952"),
|
||||
],
|
||||
] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the rotated thin island is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_island_work_limit_keeps_all_loops_and_warns_only_for_island_styles() {
|
||||
let mut e = hatch("1");
|
||||
let count = e.iter().position(|p| p.0 == 91).unwrap();
|
||||
let hole = e.iter().position(|p| *p == (92, "0")).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
e[count] = (91, "16");
|
||||
// Keep the outer square and add 15 inner squares. With at least five path elements
|
||||
// per square, 16 loops require at least 1,280 steps, over the test-time limit.
|
||||
// Without the fallback, ignore style removes the inner squares.
|
||||
let inner = [
|
||||
(92, "2"),
|
||||
(72, "0"),
|
||||
(73, "1"),
|
||||
(93, "4"),
|
||||
(10, "20"),
|
||||
(20, "20"),
|
||||
(10, "80"),
|
||||
(20, "20"),
|
||||
(10, "80"),
|
||||
(20, "80"),
|
||||
(10, "20"),
|
||||
(20, "80"),
|
||||
(97, "0"),
|
||||
];
|
||||
e.splice(hole..end, inner.repeat(15));
|
||||
for style in ["2", "0"] {
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style);
|
||||
let r = open(&entities(&e), &points());
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let count = match &area.kind {
|
||||
NodeKind::Compound { children, .. } => children.len(),
|
||||
_ => area.path_data().unwrap().subpaths.len(),
|
||||
};
|
||||
assert_eq!(count, 16, "every boundary loop is kept for style {style}");
|
||||
if style == "2" {
|
||||
assert_eq!(r.warnings, ["hatches with too many boundary points to sort into islands are filled as if every loop were a boundary"]);
|
||||
} else {
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_hatches_draw_their_lines_inside_the_boundary() {
|
||||
// A dashed linetype on the hatch: its pattern lines stay solid, as the pattern defines them.
|
||||
let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")];
|
||||
let r = open(&drawing(&[], &tables, &[], &pattern_hatch("DASHED", &[])), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) };
|
||||
// Ten lines; the four that cross the hole (y 35 to 65) are cut in two.
|
||||
assert_eq!(children.len(), 14);
|
||||
assert_eq!(stroke_rgb(lines), [255, 0, 0, 255]);
|
||||
assert!(lines.appearance.fill().is_none_or(|f| f.paint.is_none()), "the lines are not filled");
|
||||
assert!(lines.appearance.stroke().is_some_and(|s| s.dash.is_none()), "no linetype dashes on pattern lines");
|
||||
let h = height(&r.document);
|
||||
for c in children {
|
||||
let pts = path_points(c);
|
||||
let (a, b) = (pts[0], *pts.last().unwrap());
|
||||
let y = h - a.y;
|
||||
assert!((a.y - b.y).abs() < 1e-9 && (y - 5.0).rem_euclid(10.0) < 1e-9, "level lines through y 5, 15 …: {a:?} {b:?}");
|
||||
assert!(a.x.min(b.x) >= -1e-9 && a.x.max(b.x) <= 100.0 + 1e-9, "inside the square: {a:?} {b:?}");
|
||||
let mid = Point::new((a.x + b.x) / 2.0, y);
|
||||
assert!(mid.distance(Point::new(50.0, 50.0)) > 20.0, "outside the hole: {a:?} {b:?}");
|
||||
}
|
||||
assert!(lines.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round));
|
||||
// A pattern of dots (no length) shows them with round caps.
|
||||
let r = open(&entities(&pattern_hatch("CONTINUOUS", &[(79, "2"), (49, "0"), (49, "-5")])), &points());
|
||||
let [dots] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round), "{:?}", r.warnings);
|
||||
// Dashes and dots together: the dots take round caps on a path of their own, and the dashes
|
||||
// keep butt caps, so they do not grow into their gaps.
|
||||
let mixed = [(79, "4"), (49, "3"), (49, "-2"), (49, "0"), (49, "-5")];
|
||||
let r = open(&entities(&pattern_hatch("CONTINUOUS", &mixed)), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [hatch_art] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let [dashes, dots] = &hatch_art.children().unwrap()[..] else { panic!("dashes and dots: {:?}", hatch_art.kind) };
|
||||
assert!(dashes.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round));
|
||||
assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round));
|
||||
let length = |n: &Node| {
|
||||
let pts = path_points(n);
|
||||
pts[0].distance(*pts.last().unwrap())
|
||||
};
|
||||
let pieces = |n: &Node| match &n.kind {
|
||||
NodeKind::Compound { children, .. } => children.iter().map(|c| (**c).clone()).collect(),
|
||||
_ => vec![n.clone()],
|
||||
};
|
||||
assert!(pieces(dashes).iter().all(|c| length(c) > 1e-9), "no dots among the dashes");
|
||||
assert!(pieces(dots).iter().all(|c| length(c) < 1e-9), "only dots");
|
||||
// Without its pattern lines a pattern hatch still comes in as its boundary, with a note.
|
||||
let r = open(&entities(&hatch("0")), &points());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("without usable pattern lines")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_defined_double_hatches_draw_level_and_vertical_lines() {
|
||||
for double in ["1", "0"] {
|
||||
let mut e = pattern_hatch("CONTINUOUS", &[]);
|
||||
let kind = e.iter().position(|p| *p == (76, "1")).unwrap();
|
||||
e[kind] = (76, "0");
|
||||
e.insert(kind + 1, (77, double));
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) };
|
||||
let (mut level, mut vertical) = (0, 0);
|
||||
for c in children {
|
||||
let pts = path_points(c);
|
||||
let (a, b) = (pts[0], *pts.last().unwrap());
|
||||
if (a.y - b.y).abs() < 1e-9 && (a.x - b.x).abs() > 1e-9 {
|
||||
level += 1;
|
||||
} else if (a.x - b.x).abs() < 1e-9 && (a.y - b.y).abs() > 1e-9 {
|
||||
vertical += 1;
|
||||
} else {
|
||||
panic!("level or vertical piece: {a:?} {b:?}");
|
||||
}
|
||||
}
|
||||
assert!(level > 0, "level pieces with double = {double}");
|
||||
assert_eq!(vertical > 0, double == "1", "vertical pieces with double = {double}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_hatches_share_the_drawings_budget() {
|
||||
// Keep the fixture's square alone so every fallback is one closed path.
|
||||
let mut hatch = pattern_hatch("CONTINUOUS", &[]);
|
||||
let hole = hatch.iter().position(|p| *p == (92, "0")).unwrap();
|
||||
let end = hatch.iter().position(|p| p.0 == 75).unwrap();
|
||||
hatch.drain(hole..end);
|
||||
*hatch.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "1");
|
||||
let limit = super::hatch::MAX_TOTAL_PIECES;
|
||||
let count = limit / 10 + 5;
|
||||
let e = hatch.repeat(count);
|
||||
let r = open(&entities(&e), &points());
|
||||
assert_eq!(r.warnings.len(), 1, "{:?}", r.warnings);
|
||||
assert!(r.warnings[0].contains("2,000,000 dashes in all"), "{:?}", r.warnings);
|
||||
let art = r.document.layers[0].children().unwrap();
|
||||
assert_eq!(art.len(), count, "each hatch keeps its place");
|
||||
let mut pieces = 0;
|
||||
let mut boundaries = 0;
|
||||
for n in art {
|
||||
if let NodeKind::Compound { children, .. } = &n.kind {
|
||||
assert_eq!(boundaries, 0, "all hatches after exhaustion keep their boundaries");
|
||||
pieces += children.len();
|
||||
assert!(children.iter().all(|c| c.path_data().is_some_and(|p| p.subpaths.iter().all(|s| !s.closed))));
|
||||
} else {
|
||||
let path = n.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
assert!(path.subpaths[0].closed);
|
||||
boundaries += 1;
|
||||
}
|
||||
}
|
||||
assert!(pieces > 0 && pieces <= limit, "{pieces} pieces against {limit}");
|
||||
assert!(boundaries >= 5, "hatches past the budget keep their boundaries");
|
||||
}
|
||||
|
||||
/// [`hatch`]'s square with a round hole, filled with gradient `name` at `angle` (radians) from
|
||||
/// a true color (red) to color 5 (blue), or from red alone with `tint`.
|
||||
fn gradient_hatch(name: &'static str, angle: &'static str, tint: Option<&'static str>) -> Vec<(i32, &'static str)> {
|
||||
let mut e = hatch("1");
|
||||
e.extend([(450, "1"), (451, "0"), (452, if tint.is_some() { "1" } else { "0" }), (453, "2"), (460, angle), (461, "0")]);
|
||||
e.extend([(462, tint.unwrap_or("0")), (463, "0"), (63, "1"), (421, "16711680"), (463, "1"), (63, "5"), (470, name)]);
|
||||
e
|
||||
}
|
||||
|
||||
fn gradient_of(n: &Node) -> vectorcraft_color::GradientPaint {
|
||||
match n.appearance.fill().map(|f| &f.paint) {
|
||||
Some(Paint::Gradient(g)) => (**g).clone(),
|
||||
other => panic!("not a gradient: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_hatches_keep_their_gradient() {
|
||||
let r = open(&entities(&gradient_hatch("LINEAR", "0", None)), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let g = gradient_of(area);
|
||||
let colors: Vec<[u8; 4]> = g.gradient.stops.iter().map(|s| s.color.to_rgba8(1.0)).collect();
|
||||
assert_eq!(g.gradient.kind, vectorcraft_color::GradientKind::Linear);
|
||||
assert_eq!(colors, [[255, 0, 0, 255], [0, 0, 255, 255]], "the true color, then color 5");
|
||||
// Level, across the square from left to right through its middle.
|
||||
let (h, geom) = (height(&r.document), g.geom.unwrap());
|
||||
assert!(geom.start.distance(Point::new(0.0, h - 50.0)) < 1e-9 && geom.end.distance(Point::new(100.0, h - 50.0)) < 1e-9, "{geom:?}");
|
||||
// A quarter turn runs it up the square: from the bottom (larger y in the document) to the top.
|
||||
let r = open(&entities(&gradient_hatch("LINEAR", "1.5707963267948966", None)), &points());
|
||||
let geom = gradient_of(&r.document.layers[0].children().unwrap()[0]).geom.unwrap();
|
||||
assert!(geom.start.distance(Point::new(50.0, h)) < 1e-6 && geom.end.distance(Point::new(50.0, h - 100.0)) < 1e-6, "{geom:?}");
|
||||
// A one-color sphere tinted to white: white in the center, red at the edge.
|
||||
let r = open(&entities(&gradient_hatch("SPHERICAL", "0", Some("1"))), &points());
|
||||
let g = gradient_of(&r.document.layers[0].children().unwrap()[0]);
|
||||
let colors: Vec<[u8; 4]> = g.gradient.stops.iter().map(|s| s.color.to_rgba8(1.0)).collect();
|
||||
assert_eq!((g.gradient.kind, colors), (vectorcraft_color::GradientKind::Radial, vec![[255; 4], [255, 0, 0, 255]]));
|
||||
assert!(g.geom.unwrap().start.distance(Point::new(50.0, h - 50.0)) < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_gradient_stops_keep_the_inserts_color() {
|
||||
for (color, layer) in [("0", "Doors"), ("256", "0")] {
|
||||
for (second, tint) in [(false, None), (true, None), (false, Some("1"))] {
|
||||
let mut hatch = gradient_hatch("LINEAR", "0", tint);
|
||||
// The hatch's explicit color and other properties do not need insert inheritance.
|
||||
hatch.splice(1..1, [(8, layer), (6, "CONTINUOUS"), (370, "25")]);
|
||||
hatch.retain(|p| p.0 != 421);
|
||||
let stop = hatch.iter_mut().filter(|p| p.0 == 63).nth(usize::from(second)).unwrap();
|
||||
*stop = (63, color);
|
||||
let inserts = [(0, "INSERT"), (8, "Doors"), (2, "Door"), (62, "3"), (10, "0"), (20, "0")];
|
||||
let r = open(&with_door(&hatch, &inserts), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [symbol] = &r.document.symbols[..] else { panic!("one symbol") };
|
||||
let g = gradient_of(&symbol.art);
|
||||
let stop = &g.gradient.stops[usize::from(second)];
|
||||
let expected = if color == "0" { [0, 255, 0, 255] } else { [0, 0, 255, 255] };
|
||||
assert_eq!(stop.color.to_rgba8(1.0), expected, "color {color}, second {second}, tint {tint:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_hatches_far_out_keep_their_fill() {
|
||||
// A sphere hatch on a strip 10 wide ending 1e12 out: its circle reaches past 1e12, and the
|
||||
// strip still comes in, centered on the artboard.
|
||||
let mut e = vec![(0, "HATCH"), (62, "1"), (10, "0"), (20, "0"), (30, "0"), (2, "SOLID"), (70, "1"), (71, "0"), (91, "1")];
|
||||
e.extend([(92, "3"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in [("999999999990", "0"), ("1000000000000", "0"), ("1000000000000", "100"), ("999999999990", "100")] {
|
||||
e.extend([(10, x), (20, y)]);
|
||||
}
|
||||
e.extend([(97, "0"), (75, "0"), (76, "1"), (98, "0")]);
|
||||
e.extend([(450, "1"), (451, "0"), (452, "0"), (453, "2"), (460, "0"), (461, "0")]);
|
||||
e.extend([(462, "0"), (463, "0"), (63, "1"), (463, "1"), (63, "5"), (470, "SPHERICAL")]);
|
||||
let r = open(&entities(&e), &ImportOptions { center: true, ..points() });
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
assert_eq!(gradient_of(area).gradient.kind, vectorcraft_color::GradientKind::Radial);
|
||||
assert_eq!(bounds(area).width().round(), 10.0);
|
||||
}
|
||||
|
||||
/// [`with_door`] with a dashed linetype `DASHED` in the drawing.
|
||||
fn with_dashed_door(block_art: &[(i32, &'static str)], inserts: &[(i32, &'static str)]) -> Vec<u8> {
|
||||
let mut blocks = vec![(0, "BLOCK"), (8, "0"), (2, "Door"), (70, "0"), (10, "5"), (20, "5"), (3, "Door")];
|
||||
blocks.extend_from_slice(block_art);
|
||||
blocks.push((0, "ENDBLK"));
|
||||
let tables = [
|
||||
(0, "TABLE"),
|
||||
(2, "LTYPE"),
|
||||
(0, "LTYPE"),
|
||||
(2, "DASHED"),
|
||||
(73, "2"),
|
||||
(40, "15"),
|
||||
(49, "10"),
|
||||
(49, "-5"),
|
||||
(0, "ENDTAB"),
|
||||
(0, "TABLE"),
|
||||
(2, "LAYER"),
|
||||
(0, "LAYER"),
|
||||
(2, "Doors"),
|
||||
(70, "0"),
|
||||
(62, "5"),
|
||||
(6, "CONTINUOUS"),
|
||||
(0, "ENDTAB"),
|
||||
];
|
||||
drawing(&[], &tables, &blocks, inserts)
|
||||
}
|
||||
|
||||
/// Whether `n` or any object inside it has a dashed stroke.
|
||||
fn dashed(n: &Node) -> bool {
|
||||
n.appearance.stroke().is_some_and(|s| s.dash.is_some()) || n.children().is_some_and(|c| c.iter().any(|c| dashed(c)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_pattern_hatches_ignore_the_inserts_linetype() {
|
||||
let inserts = [(0, "INSERT"), (2, "Door"), (62, "1"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (62, "3"), (10, "200"), (20, "0")];
|
||||
// Pattern lines draw without a linetype: inserts of other colors share one symbol.
|
||||
let mut lines = pattern_hatch("BYBLOCK", &[]);
|
||||
lines.splice(1..1, [(8, "Doors"), (370, "25")]);
|
||||
let r = open(&with_door(&lines, &inserts), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
assert_eq!(r.document.symbols.len(), 1);
|
||||
// A pattern hatch drawn as its boundary strokes it in the insert's linetype.
|
||||
let mut boundary = hatch("0");
|
||||
boundary.splice(1..1, [(8, "Doors"), (370, "25"), (6, "BYBLOCK")]);
|
||||
let r = open(&with_door(&boundary, &inserts), &points());
|
||||
assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings);
|
||||
|
||||
// Inserts of one color, one dashed and one continuous.
|
||||
let inserts =
|
||||
[(0, "INSERT"), (2, "Door"), (6, "DASHED"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (6, "CONTINUOUS"), (10, "200"), (20, "0")];
|
||||
let r = open(&with_dashed_door(&lines, &inserts), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [symbol] = &r.document.symbols[..] else { panic!("one symbol for both linetypes") };
|
||||
assert!(!dashed(&symbol.art), "pattern lines carry no linetype dashes");
|
||||
// The boundary drawn for each insert takes that insert's linetype.
|
||||
let r = open(&with_dashed_door(&boundary, &inserts), &points());
|
||||
assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings);
|
||||
let looks: Vec<bool> = leaves(&r.document)
|
||||
.iter()
|
||||
.map(|n| {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { panic!("{:?}", n.kind) };
|
||||
dashed(&r.document.symbols.iter().find(|s| s.name == *symbol).unwrap().art)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(looks, [true, false], "the dashed insert's boundary is dashed, the continuous one's is not");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_declaring_many_absent_source_handles_parses_quickly() {
|
||||
let base = hatch("1");
|
||||
|
||||
@@ -77,9 +77,24 @@ fn a_damaged_dwg_is_an_error_that_names_dwg() {
|
||||
let e = import(&cut, &ImportOptions::default()).unwrap_err();
|
||||
assert!(e.contains("DWG"), "{e}");
|
||||
assert!(info(&cut).is_err());
|
||||
// An R1.x or R2.x drawing is refused without reading it.
|
||||
for old in [&b"AC1.50\x00\x00\x00\x00"[..], b"AC2.10\x00\x00\x00\x00", b"MC0.0\x00\x00\x00\x00"] {
|
||||
// A drawing of a version the DWG reader skips is refused by its version, without reading it.
|
||||
for (old, name) in [
|
||||
(&b"AC1.50\x00\x00\x00\x00"[..], "DWG R2.05 (AC1.50)"),
|
||||
(b"MC0.0\x00\x00\x00\x00", "DWG R1.0 (MC0.0)"),
|
||||
(b"AC1004\x00\x00\x00\x00", "DWG R9 (AC1004)"),
|
||||
] {
|
||||
let e = import(old, &ImportOptions::default()).unwrap_err();
|
||||
assert!(e.contains("version can't be read") && e.contains("DXF"), "{e}");
|
||||
assert!(e.starts_with(&format!("this drawing is {name},")) && e.contains("DXF"), "{e}");
|
||||
assert_eq!(info(old).unwrap_err(), e);
|
||||
}
|
||||
assert_eq!(import(b"AC1018", &ImportOptions::default()).unwrap_err(), "DWG: the file is cut short");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_drawing_with_an_ad_version_code_comes_in_as_its_ac_one_does() {
|
||||
let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() };
|
||||
let ac = dwg();
|
||||
let mut ad = ac.clone();
|
||||
ad[1] = b'D';
|
||||
assert_eq!(art(&import(&ad, &o).unwrap().document), art(&import(&ac, &o).unwrap().document));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,620 @@
|
||||
//! Raster images: an IMAGE comes in as an image linked to the file its IMAGEDEF names, placed as
|
||||
//! its corner and pixel vectors say and clipped by its clip boundary; images the export wrote come
|
||||
//! back where they were.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind, Unit};
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
|
||||
use super::*;
|
||||
use crate::{DxfOptions, DxfVersion};
|
||||
|
||||
/// A DXF file of `entities` and `objects` (each a run of pairs).
|
||||
fn drawing(entities: &[(i32, &str)], objects: &[(i32, &str)]) -> Vec<u8> {
|
||||
with_blocks(&[], entities, objects)
|
||||
}
|
||||
|
||||
/// A DXF file of `blocks`, `entities` and `objects` (each a run of pairs).
|
||||
fn with_blocks(blocks: &[(i32, &str)], entities: &[(i32, &str)], objects: &[(i32, &str)]) -> Vec<u8> {
|
||||
let mut p: Vec<(i32, &str)> = vec![(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, "AC1015"), (0, "ENDSEC")];
|
||||
p.extend([(0, "SECTION"), (2, "BLOCKS")]);
|
||||
p.extend_from_slice(blocks);
|
||||
p.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "ENTITIES")]);
|
||||
p.extend_from_slice(entities);
|
||||
p.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS")]);
|
||||
p.extend_from_slice(objects);
|
||||
p.extend([(0, "ENDSEC"), (0, "EOF")]);
|
||||
p.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect::<String>().into_bytes()
|
||||
}
|
||||
|
||||
/// An IMAGEDEF with handle `handle` naming `file`, 30 × 10 pixels.
|
||||
fn def<'a>(handle: &'a str, file: &'a str) -> Vec<(i32, &'a str)> {
|
||||
vec![(0, "IMAGEDEF"), (5, handle), (100, "AcDbRasterImageDef"), (1, file), (10, "30"), (20, "10")]
|
||||
}
|
||||
|
||||
/// An IMAGE of IMAGEDEF `def` with its lower-left corner at (10, 20) and 2-unit pixels, `size`
|
||||
/// pixels (none given: `None`), followed by `more` groups.
|
||||
fn image<'a>(def: &'a str, size: Option<(&'a str, &'a str)>, more: &[(i32, &'a str)]) -> Vec<(i32, &'a str)> {
|
||||
let mut e = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10"), (20, "20"), (11, "2"), (21, "0"), (12, "0"), (22, "2")];
|
||||
if let Some((w, h)) = size {
|
||||
e.extend([(13, w), (23, h)]);
|
||||
}
|
||||
e.push((340, def));
|
||||
e.extend_from_slice(more);
|
||||
e
|
||||
}
|
||||
|
||||
/// Points at 1:1, not centred: drawing (x, y) lands at document (x, artboard height − y).
|
||||
fn points() -> ImportOptions {
|
||||
ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() }
|
||||
}
|
||||
|
||||
fn nodes(doc: &Document) -> Vec<Node> {
|
||||
let mut out = vec![];
|
||||
doc.walk(|n| out.push(n.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
fn images(doc: &Document) -> Vec<ImageObject> {
|
||||
nodes(doc)
|
||||
.into_iter()
|
||||
.filter_map(|n| match n.kind {
|
||||
NodeKind::Image(im) => Some(*im),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where image `im`'s pixel corner `(x, y)` lands.
|
||||
fn at(im: &ImageObject, x: f64, y: f64) -> Point {
|
||||
im.xf * Point::new(x, y)
|
||||
}
|
||||
|
||||
fn near(a: Point, b: Point) -> bool {
|
||||
a.distance(b) < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_comes_in_linked_to_its_file_with_its_top_left_pixel_at_the_top_left() {
|
||||
let bytes = drawing(&image("1F", Some(("30", "10")), &[]), &def("1F", r"photos\scan.png"));
|
||||
let r = import(&bytes, &points()).unwrap();
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings);
|
||||
let doc = &r.document;
|
||||
assert_eq!(doc.layers.iter().filter_map(|l| l.name.as_deref()).collect::<Vec<_>>(), ["Photos"]);
|
||||
let ims = images(doc);
|
||||
assert_eq!(ims.len(), 1);
|
||||
let im = &ims[0];
|
||||
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(r"photos\scan.png"));
|
||||
assert_eq!((im.width, im.height), (30, 10));
|
||||
// The drawing's 60 × 20 units from (10, 20): y up there, y down here.
|
||||
let h = doc.artboards[0].rect.height();
|
||||
assert!(near(at(im, 0.0, 0.0), Point::new(10.0, h - 40.0)), "{:?}", at(im, 0.0, 0.0));
|
||||
assert!(near(at(im, 30.0, 10.0), Point::new(70.0, h - 20.0)), "{:?}", at(im, 30.0, 10.0));
|
||||
// Until its file is read it shows the placeholder.
|
||||
assert!(doc.images.get(&im.key).is_some_and(ImageBlob::is_proxy));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_without_its_own_size_takes_its_file_s_and_two_images_of_one_file_share_its_data() {
|
||||
let mut e = image("1F", None, &[]);
|
||||
e.extend(image("1F", Some(("30", "10")), &[]));
|
||||
let doc = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap().document;
|
||||
let ims = images(&doc);
|
||||
assert_eq!(ims.iter().map(|im| (im.width, im.height)).collect::<Vec<_>>(), [(30, 10), (30, 10)]);
|
||||
assert_eq!(ims[0].key, ims[1].key);
|
||||
assert_eq!(doc.images.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_boundary_clips_the_image_and_the_whole_image_s_boundary_does_not() {
|
||||
// Pixels 5 to 14 across and 2 to 6 down: a 20 × 10 unit window.
|
||||
let part = image("1F", Some(("30", "10")), &[(280, "1"), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")]);
|
||||
let r = import(&drawing(&part, &def("1F", "scan.png")), &points()).unwrap();
|
||||
let all = nodes(&r.document);
|
||||
let group = all.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })).expect("a clip group");
|
||||
let children = group.children().unwrap();
|
||||
assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }));
|
||||
assert!(matches!(children[1].kind, NodeKind::Image(_)));
|
||||
let h = r.document.artboards[0].rect.height();
|
||||
let clip = children[0].geometric_bounds().unwrap();
|
||||
// x 10 + 2·5 to 10 + 2·15; y down from the image's top (20 + 2·10) 2·2 to 2·7.
|
||||
let want = Rect::new(20.0, h - 40.0 + 4.0, 40.0, h - 40.0 + 14.0);
|
||||
assert!([(clip.x0, want.x0), (clip.y0, want.y0), (clip.x1, want.x1), (clip.y1, want.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-9), "{clip:?}");
|
||||
// The default boundary, the whole image, makes no group; clipping off ignores a boundary.
|
||||
let whole = image("1F", Some(("30", "10")), &[(280, "1"), (71, "1"), (91, "2"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "9.5")]);
|
||||
let off = image("1F", Some(("30", "10")), &[(280, "0"), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")]);
|
||||
for e in [whole, off] {
|
||||
let doc = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap().document;
|
||||
assert!(!nodes(&doc).iter().any(|n| matches!(n.kind, NodeKind::Group { .. })), "no clip group");
|
||||
assert_eq!(images(&doc).len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_boundary_with_a_repeated_corner_still_clips_the_image() {
|
||||
let boundary = image(
|
||||
"1F",
|
||||
Some(("30", "10")),
|
||||
&[
|
||||
(280, "1"),
|
||||
(71, "2"),
|
||||
(91, "4"),
|
||||
(14, "-0.5"),
|
||||
(24, "-0.5"),
|
||||
(14, "29.5"),
|
||||
(24, "-0.5"),
|
||||
(14, "-0.5"),
|
||||
(24, "-0.5"),
|
||||
(14, "-0.5"),
|
||||
(24, "9.5"),
|
||||
],
|
||||
);
|
||||
let doc = import(&drawing(&boundary, &def("1F", "scan.png")), &points()).unwrap().document;
|
||||
let all = nodes(&doc);
|
||||
let group = all.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })).expect("a clip group");
|
||||
let children = group.children().unwrap();
|
||||
assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }));
|
||||
assert!(matches!(children[1].kind, NodeKind::Image(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_display_flags_control_clipping_only_when_present() {
|
||||
for (display, clipping, clipped) in [(None, "1", true), (Some("9"), "1", false), (Some("13"), "1", true), (Some("13"), "0", false)] {
|
||||
let mut boundary = vec![(280, clipping), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")];
|
||||
if let Some(flags) = display {
|
||||
boundary.push((70, flags));
|
||||
}
|
||||
let e = image("1F", Some(("30", "10")), &boundary);
|
||||
let r = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert_eq!(images(&r.document).len(), 1);
|
||||
assert_eq!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })), clipped, "{display:?}, {clipping}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_requested_opaque_warn_once_and_other_images_do_not() {
|
||||
for (display, opaque) in [(None, false), (Some("9"), false), (Some("1"), true), (Some("5"), true)] {
|
||||
let flags: Vec<_> = display.map(|flags| (70, flags)).into_iter().collect();
|
||||
let mut e = image("1F", Some(("30", "10")), &flags);
|
||||
e.extend(image("1F", Some(("30", "10")), &flags));
|
||||
let r = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert_eq!(images(&r.document).len(), 2);
|
||||
let warnings: Vec<_> = r.warnings.iter().filter(|w| w.contains("opaque") && w.contains("transparency")).collect();
|
||||
assert_eq!(warnings.len(), usize::from(opaque), "{display:?}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polygon_clip_keeps_its_points_and_an_inverted_clip_shows_the_whole_image_with_a_warning() {
|
||||
let tri = image(
|
||||
"1F",
|
||||
Some(("30", "10")),
|
||||
&[(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")],
|
||||
);
|
||||
let doc = import(&drawing(&tri, &def("1F", "scan.png")), &points()).unwrap().document;
|
||||
let clip = nodes(&doc).into_iter().find(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. })).expect("a clip path");
|
||||
let NodeKind::Path { path, .. } = &clip.kind else { panic!("not a path") };
|
||||
let im = &images(&doc)[0];
|
||||
let mut corners: Vec<Point> = path.to_bezpath().elements().iter().filter_map(|el| el.end_point()).collect();
|
||||
// The path may draw its closing edge as a line back to the start.
|
||||
if corners.len() > 1 && corners.first() == corners.last() {
|
||||
corners.pop();
|
||||
}
|
||||
assert_eq!(corners.len(), 3, "{corners:?}");
|
||||
for (c, (x, y)) in corners.iter().zip([(0.0, 0.0), (30.0, 0.0), (0.0, 10.0)]) {
|
||||
assert!(near(*c, at(im, x, y)), "{c:?}");
|
||||
}
|
||||
// The same triangle closed by repeating its first point still clips: three corners of the
|
||||
// image's box and a repeat are not the box.
|
||||
let closed = image(
|
||||
"1F",
|
||||
Some(("30", "10")),
|
||||
&[
|
||||
(280, "1"),
|
||||
(71, "2"),
|
||||
(91, "4"),
|
||||
(14, "-0.5"),
|
||||
(24, "-0.5"),
|
||||
(14, "29.5"),
|
||||
(24, "-0.5"),
|
||||
(14, "29.5"),
|
||||
(24, "9.5"),
|
||||
(14, "-0.5"),
|
||||
(24, "-0.5"),
|
||||
],
|
||||
);
|
||||
let doc = import(&drawing(&closed, &def("1F", "scan.png")), &points()).unwrap().document;
|
||||
assert!(nodes(&doc).iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })), "a clip group");
|
||||
// A clip point far out of range leaves the image out.
|
||||
let far = image(
|
||||
"1F",
|
||||
Some(("30", "10")),
|
||||
&[(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "1e308"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")],
|
||||
);
|
||||
let r = import(&drawing(&far, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(images(&r.document).is_empty());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
let mut inverted = tri.clone();
|
||||
inverted.push((290, "1"));
|
||||
let r = import(&drawing(&inverted, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(!nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Group { .. })));
|
||||
assert!(r.warnings.iter().any(|w| w.contains("inverted image clips")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_without_usable_file_references_do_not_expand_the_artboard() {
|
||||
for objects in [def("1F", "scan.png"), def("2A", " ")] {
|
||||
let mut far = image("2A", Some(("30", "10")), &[]);
|
||||
for (code, value) in &mut far {
|
||||
if *code == 10 || *code == 20 {
|
||||
*value = "100000";
|
||||
}
|
||||
}
|
||||
let mut entities = vec![(0, "LINE"), (10, "0"), (20, "0"), (11, "100"), (21, "50")];
|
||||
entities.extend(far);
|
||||
let r = import(&drawing(&entities, &objects), &points()).unwrap();
|
||||
assert!(images(&r.document).is_empty());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("name no image file")), "{:?}", r.warnings);
|
||||
assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
let board = r.document.artboards[0].rect;
|
||||
assert!(board.width() < 1000.0 && board.height() < 1000.0, "{board:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Entities, objects, and the warning they give.
|
||||
type Case<'a> = (Vec<(i32, &'a str)>, Vec<(i32, &'a str)>, &'a str);
|
||||
|
||||
#[test]
|
||||
fn images_that_name_no_file_or_have_no_size_or_area_are_left_out_with_warnings() {
|
||||
let cases: [Case; 4] = [
|
||||
(image("2A", Some(("30", "10")), &[]), def("1F", "scan.png"), "name no image file"),
|
||||
(image("1F", Some(("30", "10")), &[]), def("1F", " "), "name no image file"),
|
||||
(image("1F", Some(("0", "10")), &[]), vec![(0, "IMAGEDEF"), (5, "1F"), (1, "scan.png")], "no size in pixels"),
|
||||
(
|
||||
vec![(0, "IMAGE"), (10, "10"), (20, "20"), (11, "2"), (21, "0"), (12, "4"), (22, "0"), (13, "30"), (23, "10"), (340, "1F")],
|
||||
def("1F", "scan.png"),
|
||||
"no width or height",
|
||||
),
|
||||
];
|
||||
for (e, o, why) in cases {
|
||||
let r = import(&drawing(&e, &o), &points()).unwrap();
|
||||
assert!(images(&r.document).is_empty(), "{why}");
|
||||
assert!(r.warnings.iter().any(|w| w.contains(why)), "{why}: {:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("of these types")), "an IMAGE is not an unknown entity: {:?}", r.warnings);
|
||||
}
|
||||
// Brightness, contrast and fade are noted.
|
||||
let faded = image("1F", Some(("30", "10")), &[(283, "40")]);
|
||||
let r = import(&drawing(&faded, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert_eq!(images(&r.document).len(), 1);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("fade")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_whose_show_image_flag_is_off_is_hidden() {
|
||||
let o = def("1F", "scan.png");
|
||||
for (flags, shown) in [("3", 1), ("1", 1), ("2", 0), ("0", 0)] {
|
||||
let r = import(&drawing(&image("1F", Some(("30", "10")), &[(70, flags)]), &o), &points()).unwrap();
|
||||
assert_eq!(images(&r.document).len(), shown, "group 70 = {flags}");
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("of these types")), "{:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clipped_image_far_out_in_a_named_block_comes_in_when_its_insert_places_it_on_the_canvas() {
|
||||
// The block's image sits 10,000,000 units out, and the insert moves it back next to the origin.
|
||||
let tri = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")];
|
||||
let mut far = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10000010"), (20, "20")];
|
||||
far.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]);
|
||||
let head = far.len();
|
||||
far.extend_from_slice(&tri);
|
||||
let block_of = |image: &[(i32, &'static str)]| {
|
||||
let mut block = vec![(0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")];
|
||||
block.extend_from_slice(image);
|
||||
block.push((0, "ENDBLK"));
|
||||
block
|
||||
};
|
||||
let insert = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-10000000"), (20, "0")];
|
||||
let r = import(&with_blocks(&block_of(&far), &insert, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
let art = &r.document.symbols.first().expect("a symbol").art;
|
||||
assert!(matches!(art.kind, NodeKind::Group { clip: true, .. }), "{:?}", art.kind);
|
||||
// A clip point far from its own image in the block still leaves the image out.
|
||||
let mut farther = far[..head].to_vec();
|
||||
farther.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "1e308"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]);
|
||||
let r = import(&with_blocks(&block_of(&farther), &insert, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
// A wide image whose corner is far out, cropped to a part near the origin, comes in too.
|
||||
let mut wide = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "-5000000"), (20, "0")];
|
||||
wide.extend([(11, "1000"), (21, "0"), (12, "0"), (22, "1000"), (13, "10000"), (23, "10"), (340, "1F")]);
|
||||
wide.extend([(280, "1"), (71, "2"), (91, "3"), (14, "5200"), (24, "0"), (14, "5400"), (24, "0"), (14, "5200"), (24, "5")]);
|
||||
let at_origin = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")];
|
||||
let r = import(&with_blocks(&block_of(&wide), &at_origin, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
assert!(r.document.symbols.first().is_some_and(|s| matches!(s.art.kind, NodeKind::Group { clip: true, .. })));
|
||||
// A block's image near the origin whose clip reaches out of range where the insert places it
|
||||
// is left out with that warning, and the block's other art stays.
|
||||
let mut reaching = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10"), (20, "20")];
|
||||
reaching.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]);
|
||||
reaching.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]);
|
||||
reaching.extend([(0, "LINE"), (8, "Photos"), (10, "0"), (20, "0"), (11, "50"), (21, "50")]);
|
||||
let r = import(&with_blocks(&block_of(&reaching), &at_origin, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
let placed = nodes(&r.document);
|
||||
assert!(!placed.iter().any(|n| matches!(n.kind, NodeKind::SymbolInstance { .. } | NodeKind::Image(_))));
|
||||
assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the block's line");
|
||||
// The block's symbol has no instance left, so it is not kept with the image it holds.
|
||||
assert!(r.document.symbols.is_empty(), "{:?}", r.document.symbols.iter().map(|s| &s.name).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_that_only_placements_drawn_as_art_use_is_not_charged_twice() {
|
||||
// Block B holds a 600,000-point polyline and an image whose clip reaches out of range where an
|
||||
// insert at the origin places it, so that insert draws B's art instead of an instance.
|
||||
let mut owned: Vec<(i32, String)> = vec![(0, "BLOCK".into()), (2, "B".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())];
|
||||
owned.extend([(0, "IMAGE".into()), (8, "Photos".into()), (100, "AcDbRasterImage".into()), (10, "10".into()), (20, "20".into())]);
|
||||
owned.extend([(11, "2".into()), (21, "0".into()), (12, "0".into()), (22, "2".into()), (13, "30".into()), (23, "10".into())]);
|
||||
owned.extend([(340, "1F".into()), (280, "1".into()), (71, "2".into()), (91, "3".into()), (14, "-0.5".into()), (24, "-0.5".into())]);
|
||||
owned.extend([(14, "2000010".into()), (24, "-0.5".into()), (14, "-0.5".into()), (24, "9.5".into())]);
|
||||
owned.extend([(0, "LWPOLYLINE".into()), (8, "Photos".into()), (90, "600000".into()), (70, "0".into())]);
|
||||
for i in 0..600_000 {
|
||||
owned.extend([(10, format!("{}", i % 100)), (20, format!("{}", i / 100))]);
|
||||
}
|
||||
owned.push((0, "ENDBLK".into()));
|
||||
let block: Vec<(i32, &str)> = owned.iter().map(|(c, v)| (*c, v.as_str())).collect();
|
||||
let at_origin = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")];
|
||||
let r = import(&with_blocks(&block, &at_origin, &def("1F", "scan.png")), &points()).unwrap();
|
||||
// 1,200,000 points if the unused symbol stayed charged: past the tests' limit of 1,000,000.
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings);
|
||||
assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the block's polyline");
|
||||
assert!(r.document.symbols.is_empty());
|
||||
// A second insert that places B in range makes the symbol again, which is charged again: its
|
||||
// polyline no longer fits, and the first insert's stays.
|
||||
let both = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0"), (0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-2000000"), (20, "0")];
|
||||
let r = import(&with_blocks(&block, &both, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings);
|
||||
let placed = nodes(&r.document);
|
||||
assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the first insert's polyline");
|
||||
assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })), "the second insert's instance");
|
||||
assert_eq!(r.document.symbols.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_that_only_a_removed_symbol_placed_is_removed_with_it() {
|
||||
// Block B holds a 600,000-point polyline and an image whose clip reaches out of range where the
|
||||
// drawing's insert of block A, which places B, puts it. That insert draws A's art and removes
|
||||
// A's symbol; B's symbol, which only A's art placed, goes too, so drawing B's art fits.
|
||||
let mut owned: Vec<(i32, String)> = vec![(0, "BLOCK".into()), (2, "B".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())];
|
||||
owned.extend([(0, "LWPOLYLINE".into()), (8, "Photos".into()), (90, "600000".into()), (70, "0".into())]);
|
||||
for i in 0..600_000 {
|
||||
owned.extend([(10, format!("{}", i % 100)), (20, format!("{}", i / 100))]);
|
||||
}
|
||||
owned.extend([(0, "IMAGE".into()), (8, "Photos".into()), (100, "AcDbRasterImage".into()), (10, "10".into()), (20, "20".into())]);
|
||||
owned.extend([(11, "2".into()), (21, "0".into()), (12, "0".into()), (22, "2".into()), (13, "30".into()), (23, "10".into())]);
|
||||
owned.extend([(340, "1F".into()), (280, "1".into()), (71, "2".into()), (91, "3".into()), (14, "-0.5".into()), (24, "-0.5".into())]);
|
||||
owned.extend([(14, "2000010".into()), (24, "-0.5".into()), (14, "-0.5".into()), (24, "9.5".into()), (0, "ENDBLK".into())]);
|
||||
owned.extend([(0, "BLOCK".into()), (2, "A".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())]);
|
||||
owned.extend([(0, "INSERT".into()), (8, "Photos".into()), (2, "B".into()), (10, "0".into()), (20, "0".into()), (0, "ENDBLK".into())]);
|
||||
let blocks: Vec<(i32, &str)> = owned.iter().map(|(c, v)| (*c, v.as_str())).collect();
|
||||
let insert = [(0, "INSERT"), (8, "Photos"), (2, "A"), (10, "0"), (20, "0")];
|
||||
let r = import(&with_blocks(&blocks, &insert, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings);
|
||||
assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "B's polyline");
|
||||
assert!(r.document.symbols.is_empty());
|
||||
}
|
||||
|
||||
/// Block B holds an image clipped by a triangle with a corner at (`far`, −0.5) in pixel space, and
|
||||
/// block A places B by `inner` beside an image of its own clipped near it; the drawing places A
|
||||
/// at the origin scaled by `outer`.
|
||||
fn nested(far: &'static str, inner: &[(i32, &'static str)], outer: &'static str) -> Vec<u8> {
|
||||
let clipped = |x: &'static str, corner: &'static str| {
|
||||
let mut e = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, x), (20, "20")];
|
||||
e.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]);
|
||||
e.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, corner), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]);
|
||||
e
|
||||
};
|
||||
let mut blocks = vec![(0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")];
|
||||
blocks.extend(clipped("10", far));
|
||||
blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "A"), (70, "0"), (10, "0"), (20, "0")]);
|
||||
blocks.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]);
|
||||
blocks.extend_from_slice(inner);
|
||||
blocks.extend(clipped("100", "29.5"));
|
||||
blocks.push((0, "ENDBLK"));
|
||||
let insert = [(0, "INSERT"), (8, "Photos"), (2, "A"), (10, "0"), (20, "0"), (41, outer), (42, outer)];
|
||||
with_blocks(&blocks, &insert, &def("1F", "scan.png"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_s_clip_point_beyond_any_usable_range_leaves_its_image_out_even_where_inserts_scale_it_back() {
|
||||
// B's clip corner is 2e19 units out in its own space, and two inserts at the smallest scale
|
||||
// would bring it back next to the origin.
|
||||
let r = import(&nested("1e19", &[(41, "1e-12"), (42, "1e-12")], "1e-12"), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
let mut held = 0;
|
||||
for s in &r.document.symbols {
|
||||
s.art.walk(&mut |n: &Node| held += usize::from(matches!(n.kind, NodeKind::Image(_))));
|
||||
}
|
||||
assert_eq!(held + images(&r.document).len(), 1, "A's own image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_reach_placed_by_an_overflowing_transform_is_unbounded() {
|
||||
use super::build::placed_reach;
|
||||
let out = |b: Rect| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite());
|
||||
// Across, the terms of every corner overflow with opposite signs to NaN, which a union with
|
||||
// another symbol's reach would drop; the reach is unbounded instead.
|
||||
let h = 1e300;
|
||||
let xf = Affine::new([h, 1.0, -h, 1.0, 0.0, 0.0]);
|
||||
let r = Rect::new(1e10, 1e10, 2e10, 2e10);
|
||||
let near = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
let whole = placed_reach(xf, r);
|
||||
assert!(out(whole.union(near)), "{whole:?}");
|
||||
// An unbounded reach stays unbounded wherever it is placed.
|
||||
assert!(out(placed_reach(Affine::scale(1e-12), whole).union(near)));
|
||||
assert!(out(placed_reach(Affine::IDENTITY, whole).union(near)));
|
||||
// A placement that stays finite is the box of the placed corners.
|
||||
let b = placed_reach(Affine::new([0.0, 1.0, -1.0, 0.0, 5.0, 0.0]), near);
|
||||
assert_eq!((b.x0, b.y0, b.x1, b.y1), (-5.0, 0.0, 5.0, 10.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clip_paths_count_against_the_path_point_limit() {
|
||||
// A 1,000-point clip in an anonymous block placed 1,100 times: 1,001,000 path elements, past
|
||||
// the tests' limit of 1,000,000.
|
||||
let mut clip: Vec<(i32, String)> = vec![(280, "1".into()), (71, "2".into()), (91, "1000".into())];
|
||||
for i in 0..1000 {
|
||||
let a = f64::from(i) * std::f64::consts::TAU / 1000.0;
|
||||
clip.extend([(14, format!("{}", 14.5 + 10.0 * a.cos())), (24, format!("{}", 4.5 + 4.0 * a.sin()))]);
|
||||
}
|
||||
let clip: Vec<(i32, &str)> = clip.iter().map(|(c, v)| (*c, v.as_str())).collect();
|
||||
let mut block = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
|
||||
block.extend(image("1F", Some(("30", "10")), &clip));
|
||||
block.push((0, "ENDBLK"));
|
||||
let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "1100"), (44, "100")];
|
||||
let r = import(&with_blocks(&block, &insert, &def("1F", "scan.png")), &points()).unwrap();
|
||||
let clips = nodes(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. })).count();
|
||||
assert!((900..1000).contains(&clips), "{clips} clip paths");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_insert_drawn_as_art_gets_back_its_unused_symbol_s_objects_at_the_object_limit() {
|
||||
// Block B holds a line and an image whose clip reaches out of range where B's insert places
|
||||
// it: 4 objects as a symbol. 99,996 lines before it leave exactly room for that symbol under
|
||||
// the tests' limit of 100,000 objects, so its insert draws B's art in the room the unused
|
||||
// symbol gives back.
|
||||
let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
|
||||
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]);
|
||||
blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]);
|
||||
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]);
|
||||
let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")];
|
||||
blocks.extend(image("1F", Some(("30", "10")), &reaching));
|
||||
blocks.push((0, "ENDBLK"));
|
||||
// An insert makes at most 10,000 copies: nine of 100 × 100 and one of 84 × 119.
|
||||
let mut entities = vec![];
|
||||
for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("84", "119")]) {
|
||||
entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]);
|
||||
}
|
||||
entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]);
|
||||
let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings);
|
||||
let lines = nodes(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })).count();
|
||||
assert_eq!(lines, 99_997, "the lines and B's line");
|
||||
assert!(r.document.symbols.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_drawn_as_art_past_the_object_limit_stop_without_looking_at_the_block() {
|
||||
// Block B: 200 lines and an image whose clip reaches out of range unless its copy sits left of
|
||||
// the origin. 99,796 lines, B's symbol and the first copy's instance fill the tests' limit of
|
||||
// 100,000 objects; the next 9,999 copies would each look at B's 201 items, past the tests'
|
||||
// block-work limit of 1,000,000.
|
||||
let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
|
||||
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]);
|
||||
blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]);
|
||||
for _ in 0..200 {
|
||||
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]);
|
||||
}
|
||||
let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")];
|
||||
blocks.extend(image("1F", Some(("30", "10")), &reaching));
|
||||
blocks.push((0, "ENDBLK"));
|
||||
let mut entities = vec![];
|
||||
for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("79", "124")]) {
|
||||
entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]);
|
||||
}
|
||||
entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-35"), (20, "0"), (70, "10000"), (44, "10")]);
|
||||
let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_of_a_symbol_taken_out_at_the_object_limit_are_not_drawn_again() {
|
||||
// Block B: an image whose clip reaches out of range only for the first copy, and 200 lines.
|
||||
// 99,800 lines and the first copy, drawn as art in the room its unused symbol gives back,
|
||||
// fill the tests' limit of 100,000 objects; each of the next 9,999 copies would draw the
|
||||
// symbol again from B's 201 items, past the tests' block-work limit of 1,000,000.
|
||||
let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
|
||||
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]);
|
||||
blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]);
|
||||
let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")];
|
||||
blocks.extend(image("1F", Some(("30", "10")), &reaching));
|
||||
for _ in 0..200 {
|
||||
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]);
|
||||
}
|
||||
blocks.push((0, "ENDBLK"));
|
||||
let mut entities = vec![];
|
||||
for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("98", "100")]) {
|
||||
entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]);
|
||||
}
|
||||
entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-25"), (20, "0"), (70, "10000"), (44, "-10")]);
|
||||
let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// A document with a 4 × 2 pixel image, 5 pt pixels, its top-left corner at (10, 20).
|
||||
fn image_doc() -> Document {
|
||||
let png = craft_image_codecs::encode(
|
||||
&craft_image_codecs::Image::from_raw(
|
||||
4,
|
||||
2,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[0u8, 0, 255, 255].repeat(8),
|
||||
)
|
||||
.unwrap(),
|
||||
craft_image_codecs::Format::Png,
|
||||
&craft_image_codecs::EncodeOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut d = Document::new(200.0, 100.0);
|
||||
let layer = d.add_layer(Some("Photos"));
|
||||
let im = ImageObject {
|
||||
key: "raster-1".into(),
|
||||
width: 4,
|
||||
height: 2,
|
||||
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() });
|
||||
d
|
||||
}
|
||||
|
||||
/// Import `bytes`, written from [`image_doc`], and check its one image: linked to `name`, the file
|
||||
/// the export wrote, and the size and way up it had.
|
||||
fn written_and_read(bytes: &[u8], name: &str) {
|
||||
let doc = import(bytes, &points()).unwrap().document;
|
||||
let ims = images(&doc);
|
||||
assert_eq!(ims.len(), 1, "{:?}", nodes(&doc).iter().map(|n| &n.kind).collect::<Vec<_>>());
|
||||
let im = &ims[0];
|
||||
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(name));
|
||||
assert_eq!((im.width, im.height), (4, 2));
|
||||
// 20 × 10 pt with the top-left pixel at the top-left, as it was.
|
||||
let (tl, br) = (at(im, 0.0, 0.0), at(im, 4.0, 2.0));
|
||||
assert!((br.x - tl.x - 20.0).abs() < 1e-6 && (br.y - tl.y - 10.0).abs() < 1e-6, "{tl:?} {br:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_the_export_wrote_comes_back_linked_to_the_file_it_wrote() {
|
||||
let d = image_doc();
|
||||
let out = crate::export(&d, &DxfOptions { region: d.artboards[0].rect, unit: Unit::Points, ..DxfOptions::default() }).unwrap();
|
||||
assert_eq!(out.images.len(), 1);
|
||||
written_and_read(&out.bytes, &out.images[0].name);
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn an_image_in_a_dwg_drawing_comes_in_as_in_its_dxf() {
|
||||
let d = image_doc();
|
||||
let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Points, ..DxfOptions::default() };
|
||||
let out = crate::export(&d, &o).unwrap();
|
||||
crate::dwg::allow_in_process();
|
||||
let dwg = craft_dwg::dxf_to_dwg_as(&out.bytes, "AC1018").unwrap();
|
||||
written_and_read(&dwg, &out.images[0].name);
|
||||
}
|
||||
@@ -15,6 +15,8 @@ spine-count = []
|
||||
symbol-read-count = []
|
||||
# `vectorcraft_doc::locked_artboard_measures` for other crates' tests (dev-dependencies only).
|
||||
locked-artboard-count = []
|
||||
# `vectorcraft_doc::swatches::swatch_scans` for other crates' tests (dev-dependencies only).
|
||||
swatch-scans = []
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-geom = { workspace = true }
|
||||
@@ -39,3 +41,6 @@ flate2 = { workspace = true }
|
||||
zune-jpeg = { workspace = true }
|
||||
jpeg-encoder = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
# The counter vectorcraft-ui-egui's tests turn on, also when this crate is tested without
|
||||
# vectorcraft-ui-egui (`cargo xtask ci shard`).
|
||||
vectorcraft-doc = { path = ".", features = ["swatch-scans"] }
|
||||
|
||||
@@ -119,7 +119,7 @@ pub use node::Knockout;
|
||||
pub use node::Scaling;
|
||||
pub use node::changed_nodes;
|
||||
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
|
||||
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS, attribute_copies};
|
||||
pub use orient::OrientedBox;
|
||||
pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType};
|
||||
pub use perspective::PerspectiveAttachment;
|
||||
|
||||
@@ -25,7 +25,9 @@ mod opacity;
|
||||
mod ops;
|
||||
mod wire;
|
||||
|
||||
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
pub use attributes::{
|
||||
ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS, attribute_copies,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use changed::COUNTERPART_LOOKUPS;
|
||||
pub use changed::changed_nodes;
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::live_shape::LiveShape;
|
||||
use super::{Deserialize, Node, Serialize};
|
||||
|
||||
/// Window → Attributes: an object's settings that don't change how it prints.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ObjectAttributes {
|
||||
/// Show Center / Don't Show Center (`None`: the object kind's default, [`Node::shows_center`]).
|
||||
@@ -45,6 +45,34 @@ pub struct ObjectAttributes {
|
||||
pub tags: Vec<ObjectTag>,
|
||||
}
|
||||
|
||||
impl Clone for ObjectAttributes {
|
||||
fn clone(&self) -> Self {
|
||||
ATTRIBUTE_COPIES.set(ATTRIBUTE_COPIES.get().saturating_add(1));
|
||||
Self {
|
||||
show_center: self.show_center,
|
||||
image_map: self.image_map,
|
||||
url: self.url.clone(),
|
||||
note: self.note.clone(),
|
||||
data: self.data.clone(),
|
||||
events: self.events.clone(),
|
||||
classes: self.classes.clone(),
|
||||
foreign: self.foreign.clone(),
|
||||
tags: self.tags.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// [`attribute_copies`] of this thread.
|
||||
static ATTRIBUTE_COPIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many times an object's [`ObjectAttributes`] have been copied on this thread. Tags can hold
|
||||
/// up to [`MAX_TAGS`] values of [`MAX_TAG_TEXT`] bytes each, so each copy can cost megabytes.
|
||||
pub fn attribute_copies() -> u64 {
|
||||
ATTRIBUTE_COPIES.get()
|
||||
}
|
||||
|
||||
/// The most tags one object has.
|
||||
pub const MAX_TAGS: usize = 64;
|
||||
|
||||
|
||||
@@ -16,6 +16,23 @@ use vectorcraft_color::{Color, Paint, Swatch, tint_percent};
|
||||
|
||||
use crate::{AppearanceItem, Document, Node, NodeId, NodeKind};
|
||||
|
||||
#[cfg(any(test, feature = "swatch-scans"))]
|
||||
thread_local! {
|
||||
/// How many swatches and color groups [`Document::swatch`] and [`Document::swatch_name_taken`] have compared by
|
||||
/// name on this thread.
|
||||
static SWATCH_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many swatches and color groups [`Document::swatch`] and [`Document::swatch_name_taken`] have compared by
|
||||
/// name on this thread, for other crates' tests that count how much work their lookups by name do (the
|
||||
/// `swatch-scans` feature, dev-dependencies only). A lookup compares the swatches up to the one it finds, or all of
|
||||
/// them for a name the document does not hold.
|
||||
#[cfg(any(test, feature = "swatch-scans"))]
|
||||
#[doc(hidden)]
|
||||
pub fn swatch_scans() -> usize {
|
||||
SWATCH_SCANS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Every swatch: the ungrouped ones first, then each colour group's in order.
|
||||
pub fn swatches_iter(&self) -> impl Iterator<Item = &Swatch> {
|
||||
@@ -27,7 +44,12 @@ impl Document {
|
||||
/// Swatch `name`, the built-in Registration swatch ([`vectorcraft_color::swatch::registration`])
|
||||
/// included.
|
||||
pub fn swatch(&self, name: &str) -> Option<&Swatch> {
|
||||
self.swatches_iter().find(|s| s.name == name).or_else(|| (name == REGISTRATION).then(vectorcraft_color::swatch::registration))
|
||||
let found = self.swatches_iter().find(|s| {
|
||||
#[cfg(any(test, feature = "swatch-scans"))]
|
||||
SWATCH_SCANS.with(|c| c.set(c.get() + 1));
|
||||
s.name == name
|
||||
});
|
||||
found.or_else(|| (name == REGISTRATION).then(vectorcraft_color::swatch::registration))
|
||||
}
|
||||
pub fn swatch_mut(&mut self, name: &str) -> Option<&mut Swatch> {
|
||||
self.swatches_iter_mut().find(|s| s.name == name)
|
||||
@@ -74,7 +96,12 @@ impl Document {
|
||||
}
|
||||
/// Is `name` used by a swatch or a colour group (they share one namespace)?
|
||||
pub fn swatch_name_taken(&self, name: &str) -> bool {
|
||||
self.swatch(name).is_some() || self.swatch_groups.iter().any(|g| g.name == name)
|
||||
self.swatch(name).is_some()
|
||||
|| self.swatch_groups.iter().any(|g| {
|
||||
#[cfg(any(test, feature = "swatch-scans"))]
|
||||
SWATCH_SCANS.with(|c| c.set(c.get() + 1));
|
||||
g.name == name
|
||||
})
|
||||
}
|
||||
/// `base`, or the first of "base 2", "base 3"… no swatch or colour group uses.
|
||||
pub fn free_swatch_name(&self, base: &str) -> String {
|
||||
|
||||
@@ -17,6 +17,11 @@ bundled-fonts = ["vectorcraft-text/bundled-fonts"]
|
||||
# feature still recognizes the files and refuses them with a message. The apps list it beside
|
||||
# `bundled-fonts`.
|
||||
heif = ["dep:heic-rs", "dep:rayon"]
|
||||
# Binary CGM files open and place. Off until the craft-metafile CGM reader (craft-libs#5410) merges
|
||||
# and the workspace pins it; the build fails with this feature on before then. Without it, `.cgm`
|
||||
# is not listed as readable or placeable anywhere. Turning it on also needs `cgm` in
|
||||
# `UNASSOCIATED_EXTS` (`src/cmd/fileio/formats.rs`).
|
||||
cgm = ["vectorcraft-metafile/cgm"]
|
||||
|
||||
[dependencies]
|
||||
craft-codepage = { workspace = true }
|
||||
|
||||
@@ -16,6 +16,10 @@ mod shapes;
|
||||
mod typetools;
|
||||
mod units;
|
||||
|
||||
pub(crate) use color::screen_marks::{
|
||||
LAYER_NAME as SCREEN_MARKS_LAYER, adopt_layer as adopt_screen_marks_layer, copied_owners as screen_marks_copied, layer_id as screen_marks_layer,
|
||||
managed_owners as screen_marks_owners, owned_by as screen_marks_of, release as release_screen_marks, retag as retag_screen_marks,
|
||||
};
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
@@ -4,15 +4,17 @@
|
||||
//! objects that use spot colours, carry a live colour adjustment, or are images of a colour model,
|
||||
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest
|
||||
//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend
|
||||
//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply
|
||||
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and Randomize Fill Colors
|
||||
//! ([`random_fill`]) gives each filled path its own color at random. Its panel and its submenu,
|
||||
//! Object › Plug-ins › Color Effects, are the UI's.
|
||||
//! ([`legend`]) draws labelled chips of the document's swatches, Create Screen Print Marks
|
||||
//! ([`screen_marks`]) draws registration targets and ink and file lines on the artboard, Apply
|
||||
//! Fill to Stroke and Apply Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and
|
||||
//! Randomize Fill Colors ([`random_fill`]) gives each filled path its own color at random. Its
|
||||
//! panel and its submenu, Object › Plug-ins › Color Effects, are the UI's.
|
||||
|
||||
pub mod legend;
|
||||
mod nearest;
|
||||
mod print_fixes;
|
||||
mod random_fill;
|
||||
pub mod screen_marks;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -106,6 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
.into_iter()
|
||||
.chain(legend::specs())
|
||||
.chain(screen_marks::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,515 @@
|
||||
//! Create Screen Print Marks (`addon.color.screenMarks`; Object › Plug-ins › Color Effects ›
|
||||
//! Create Screen Print Marks…): registration targets at chosen corners and side centers of an
|
||||
//! artboard, in [Registration] or a spot ink, with optional lines that list the document's spot
|
||||
//! inks (each name in its own ink) and give the file name with the date and time. The marks are
|
||||
//! document art, one group per artboard on a locked "Screen Print Marks" layer at the bottom of the
|
||||
//! stack, so they print and export with the rest. Running it again replaces that artboard's marks,
|
||||
//! in one undo step, and makes none when the marks would come out the same.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Document, LAYER_COLORS, LayerColor, MAX_COORD, Node, NodeId, NodeKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
|
||||
use super::super::super::{CommandSpec, bad, clock_date, cmd, date_param, has_doc, index_opt, switch_or, text_param};
|
||||
use crate::{DocState, Result, Session};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.color.screenMarks",
|
||||
"Create Screen Print Marks",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{positions?: [topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight…] (each at most once; default: [top, bottom, left, right]; [] draws no targets), size?: target width in pt 4..1000 (36), weight?: stroke weight in pt 0.1..20 (1), inset?: pt from the artboard's edge to the target's outer edge -1000..1000 (18; below 0 the targets sit outside the artboard), ink?: \"[Registration]\" (default) or a spot swatch's name (the targets and the file line), inks?: false (a line naming the document's spot inks, each name in its own ink; tints and [Registration] left out), info?: false (a line with the file name, or the title of a document never saved, and the date and time in UTC), time?: Unix seconds (default: now; null, or no clock as on the web: no date), textSize?: pt 4..72 (9), textPlace?: \"top\"|\"bottom\" (default), textAlign?: \"left\" (default)|\"right\" (the lines start past a target ticked in that corner, and move in past the top or bottom target they would cross; they stay where they are when moving would cross another target or leave the artboard), artboard?: index (default: the active artboard), activeArtboard?: index (the active artboard the journal records for a replay; used when artboard is left out; omitted from recorded actions), allArtboards?: false; null is refused except for time} draw registration targets (a circle half the target's width with a cross through it, stroked) inside each artboard, and the lines asked for, as one group per artboard on the layer \"Screen Print Marks\", which is made locked at the bottom of the stack when there is none; running it again replaces that artboard's group. Another artboard's group lying on a copied artboard goes with its own artboard. One undo step, none when the marks come out the same; the selection is kept → {changed, layer, ids: [group id…], inks: [spot ink name…]}",
|
||||
has_doc,
|
||||
screen_marks
|
||||
)]
|
||||
}
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.color.screenMarks";
|
||||
|
||||
/// Where a target can go, in the order the command draws them.
|
||||
pub const POSITIONS: [&str; 8] = ["topLeft", "top", "topRight", "left", "right", "bottomLeft", "bottom", "bottomRight"];
|
||||
/// The targets drawn when `positions` is left out.
|
||||
pub const DEFAULT_POSITIONS: [&str; 4] = ["top", "bottom", "left", "right"];
|
||||
/// The name of the layer the marks go on, and of each artboard's group.
|
||||
pub const LAYER_NAME: &str = "Screen Print Marks";
|
||||
/// The object data key that marks the layer (`layer`) and each artboard's group (the artboard's id).
|
||||
pub const KEY: &str = "vc-screen-print-marks";
|
||||
/// Most spot inks one line names.
|
||||
const MAX_INKS: usize = 256;
|
||||
|
||||
fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>) -> Result<f64> {
|
||||
match p.get(key) {
|
||||
None => 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()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// One of `options` for `key`, else `default`.
|
||||
fn choice(p: &Value, key: &str, options: [&'static str; 2], default: &'static str) -> Result<&'static str> {
|
||||
match text_param(p, key, COMMAND)? {
|
||||
None => Ok(default),
|
||||
Some(v) => options.into_iter().find(|o| *o == v).ok_or_else(|| bad(COMMAND, format!("`{key}` must be {} or {}", options[0], options[1]))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The target positions `p` asks for, in [`POSITIONS`] order.
|
||||
fn positions(p: &Value) -> Result<Vec<&'static str>> {
|
||||
let asked: Vec<&str> = match p.get("positions") {
|
||||
None => return Ok(POSITIONS.into_iter().filter(|w| DEFAULT_POSITIONS.contains(w)).collect()),
|
||||
Some(Value::Array(a)) => {
|
||||
a.iter().map(|v| v.as_str().ok_or_else(|| bad(COMMAND, "`positions` must be a list of position names"))).collect::<Result<_>>()?
|
||||
}
|
||||
Some(_) => return Err(bad(COMMAND, "`positions` must be a list of position names")),
|
||||
};
|
||||
for (i, w) in asked.iter().enumerate() {
|
||||
if !POSITIONS.contains(w) {
|
||||
return Err(bad(COMMAND, format!("`{w}` is not a position: give {}", POSITIONS.join(", "))));
|
||||
}
|
||||
if asked[..i].contains(w) {
|
||||
return Err(bad(COMMAND, format!("`positions` names `{w}` twice")));
|
||||
}
|
||||
}
|
||||
Ok(POSITIONS.into_iter().filter(|w| asked.contains(w)).collect())
|
||||
}
|
||||
|
||||
/// The paint of ink `name`: [Registration], or a spot swatch linked to it.
|
||||
fn ink_paint(doc: &Document, name: &str) -> Result<Paint> {
|
||||
if name == REGISTRATION {
|
||||
return Ok(Paint::registration());
|
||||
}
|
||||
let w = doc.swatch(name).ok_or_else(|| bad(COMMAND, format!("no swatch named `{name}`")))?;
|
||||
if !w.spot || w.tint_of().is_some() || w.paint.color().is_none() {
|
||||
return Err(bad(COMMAND, format!("`{name}` is not a spot color swatch: give [Registration] or a spot swatch")));
|
||||
}
|
||||
super::super::super::paint::swatch_solid(doc, name, None).map_err(|e| bad(COMMAND, e))
|
||||
}
|
||||
|
||||
/// The document's spot inks in panel order, each with the paint that links to it: spot color
|
||||
/// swatches that are not tints, [Registration] left out.
|
||||
fn spot_inks(doc: &Document) -> Vec<(String, Paint)> {
|
||||
doc.swatches_iter()
|
||||
.filter(|w| w.spot && w.name != REGISTRATION && w.tint_of().is_none() && w.paint.color().is_some())
|
||||
.map(|w| (w.name.clone(), super::super::super::paint::swatch_solid(doc, &w.name, None).unwrap_or_else(|_| w.paint.clone())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The index of the view's active artboard: when the document no longer has it, the one the
|
||||
/// document opened on, else the first.
|
||||
fn active_artboard(st: &DocState) -> Option<usize> {
|
||||
let d = &st.doc;
|
||||
let at = |id: Option<u32>| id.and_then(|id| d.artboards.iter().position(|a| a.id == id));
|
||||
at(st.active_artboard).or_else(|| at(d.opened_artboard)).or((!d.artboards.is_empty()).then_some(0))
|
||||
}
|
||||
|
||||
/// The settings every artboard's marks are drawn with.
|
||||
struct Marks {
|
||||
positions: Vec<&'static str>,
|
||||
size: f64,
|
||||
weight: f64,
|
||||
inset: f64,
|
||||
ink: Paint,
|
||||
/// The lines of type, top to bottom: each a list of (text, fill) runs.
|
||||
lines: Vec<Vec<(String, Paint)>>,
|
||||
style: CharStyle,
|
||||
system_layout: bool,
|
||||
top: bool,
|
||||
left: bool,
|
||||
}
|
||||
|
||||
impl Marks {
|
||||
/// The center of the target at `position` on artboard `r`.
|
||||
fn center(&self, r: Rect, position: &str) -> Point {
|
||||
let near = self.inset + self.size / 2.0;
|
||||
let x = if position.ends_with("Left") || position == "left" {
|
||||
r.x0 + near
|
||||
} else if position.ends_with("Right") || position == "right" {
|
||||
r.x1 - near
|
||||
} else {
|
||||
r.center().x
|
||||
};
|
||||
let y = if position.starts_with("top") {
|
||||
r.y0 + near
|
||||
} else if position.starts_with("bottom") {
|
||||
r.y1 - near
|
||||
} else {
|
||||
r.center().y
|
||||
};
|
||||
Point::new(x, y)
|
||||
}
|
||||
|
||||
/// The target at `c`: a circle half the target's width and a cross the target's width, stroked.
|
||||
fn target(&self, c: Point, alloc: &mut dyn FnMut() -> NodeId) -> Node {
|
||||
let ap = Appearance::basic(Paint::None, self.ink.clone(), self.weight);
|
||||
let (half, ring) = (self.size / 2.0, self.size / 4.0);
|
||||
let paths = [
|
||||
shapes::ellipse(Rect::new(c.x - ring, c.y - ring, c.x + ring, c.y + ring)),
|
||||
shapes::line(Point::new(c.x - half, c.y), Point::new(c.x + half, c.y)),
|
||||
shapes::line(Point::new(c.x, c.y - half), Point::new(c.x, c.y + half)),
|
||||
];
|
||||
let children = paths.into_iter().map(|path| Arc::new(Node::path(alloc(), path, ap.clone()))).collect();
|
||||
let mut g = Node::group(alloc(), children);
|
||||
g.name = Some("Registration Target".into());
|
||||
g
|
||||
}
|
||||
|
||||
/// A point type line of `runs` placed with its box's top-left (or top-right) corner at `at`, or
|
||||
/// its bottom corner there when `from_bottom`, with its box.
|
||||
fn line(&self, runs: &[(String, Paint)], at: Point, from_bottom: bool) -> (TextObject, Rect) {
|
||||
let runs: Vec<TextRun> = runs
|
||||
.iter()
|
||||
.map(|(text, fill)| {
|
||||
let mut style = self.style.clone();
|
||||
style.fill = fill.clone();
|
||||
style.stroke = Paint::None;
|
||||
TextRun::new(text.clone(), style)
|
||||
})
|
||||
.collect();
|
||||
let mut t = TextObject::point(Point::ZERO, "", self.style.clone());
|
||||
t.runs = runs;
|
||||
t.para = super::super::super::create::new_type_para();
|
||||
t.system_layout = self.system_layout;
|
||||
super::super::super::typecmd::refresh_bounds(&mut t);
|
||||
let b = t.cached_bounds.unwrap_or(Rect::new(0.0, -self.style.size * 0.8, 0.0, self.style.size * 0.2));
|
||||
let dx = if self.left { at.x - b.x0 } else { at.x - b.x1 };
|
||||
let dy = if from_bottom { at.y - b.y1 } else { at.y - b.y0 };
|
||||
t.xf = Affine::translate((dx, dy));
|
||||
(t, Rect::new(b.x0 + dx, b.y0 + dy, b.x1 + dx, b.y1 + dy))
|
||||
}
|
||||
|
||||
/// The lines placed in a column from `y`, at `x`: down from `y` at the top, up
|
||||
/// from it at the bottom. Each with its box.
|
||||
fn column(&self, x: f64, mut y: f64) -> Vec<(TextObject, Rect)> {
|
||||
let gap = self.style.size * 0.25;
|
||||
let mut placed = Vec::with_capacity(self.lines.len());
|
||||
if self.top {
|
||||
for runs in &self.lines {
|
||||
let (t, b) = self.line(runs, Point::new(x, y), false);
|
||||
y += b.height() + gap;
|
||||
placed.push((t, b));
|
||||
}
|
||||
} else {
|
||||
for runs in self.lines.iter().rev() {
|
||||
let (t, b) = self.line(runs, Point::new(x, y), true);
|
||||
y -= b.height() + gap;
|
||||
placed.insert(0, (t, b));
|
||||
}
|
||||
}
|
||||
placed
|
||||
}
|
||||
|
||||
/// The marks of artboard `r` (id `board`) as one group, with ids from `alloc` (the group's last).
|
||||
fn group(&self, r: Rect, board: u32, alloc: &mut dyn FnMut() -> NodeId) -> Node {
|
||||
let mut children: Vec<Arc<Node>> = self.positions.iter().map(|w| Arc::new(self.target(self.center(r, w), alloc))).collect();
|
||||
if !self.lines.is_empty() {
|
||||
// The lines start past a target in the corner they start from.
|
||||
let corner = match (self.top, self.left) {
|
||||
(true, true) => "topLeft",
|
||||
(true, false) => "topRight",
|
||||
(false, true) => "bottomLeft",
|
||||
(false, false) => "bottomRight",
|
||||
};
|
||||
let skip = if self.positions.contains(&corner) { self.size + self.style.size } else { 0.0 };
|
||||
let x = if self.left { r.x0 + self.inset + skip } else { r.x1 - self.inset - skip };
|
||||
let (edge, sign) = if self.top { (r.y0, 1.0) } else { (r.y1, -1.0) };
|
||||
let mut placed = self.column(x, edge + sign * self.inset);
|
||||
// Lines that would cross the center target on their side move in past it, unless they
|
||||
// would then cross another target or leave the artboard.
|
||||
let side = if self.top { "top" } else { "bottom" };
|
||||
// A target's paint: its two bars and the box of its ring, each with half the stroke weight.
|
||||
let (half, ring, w2) = (self.size / 2.0, self.size / 4.0 + self.weight / 2.0, self.weight / 2.0);
|
||||
let crosses = |placed: &[(TextObject, Rect)], w: &str| {
|
||||
let c = self.center(r, w);
|
||||
let paint = [
|
||||
Rect::new(c.x - half - w2, c.y - w2, c.x + half + w2, c.y + w2),
|
||||
Rect::new(c.x - w2, c.y - half - w2, c.x + w2, c.y + half + w2),
|
||||
Rect::new(c.x - ring, c.y - ring, c.x + ring, c.y + ring),
|
||||
];
|
||||
placed.iter().any(|(_, b)| paint.iter().any(|p| b.x0 < p.x1 && b.x1 > p.x0 && b.y0 < p.y1 && b.y1 > p.y0))
|
||||
};
|
||||
if self.positions.contains(&side) && crosses(&placed, side) {
|
||||
let moved = self.column(x, edge + sign * (self.inset + self.size + self.weight / 2.0 + self.style.size * 0.25));
|
||||
if moved.iter().all(|(_, b)| b.y0 >= r.y0 && b.y1 <= r.y1) && !self.positions.iter().any(|w| crosses(&moved, w)) {
|
||||
placed = moved;
|
||||
}
|
||||
}
|
||||
children.extend(placed.into_iter().map(|(t, _)| Arc::new(Node::new(alloc(), NodeKind::Text(Box::new(t))))));
|
||||
}
|
||||
let mut g = Node::group(alloc(), children);
|
||||
g.name = Some(LAYER_NAME.into());
|
||||
g.edit_attrs(|a| a.data.push((KEY.into(), board.to_string())));
|
||||
g
|
||||
}
|
||||
}
|
||||
|
||||
/// The marks layer: the top-level layer whose data says so.
|
||||
fn marks_layer(doc: &Document) -> Option<&Arc<Node>> {
|
||||
doc.layers.iter().find(|l| tag(l) == Some("layer"))
|
||||
}
|
||||
|
||||
/// What `n`'s data holds under [`KEY`].
|
||||
fn tag(n: &Node) -> Option<&str> {
|
||||
n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// The id of the artboard marks group `n` belongs to, from its data.
|
||||
fn owner(n: &Node) -> Option<u32> {
|
||||
tag(n)?.parse().ok()
|
||||
}
|
||||
|
||||
/// Each marks group on the marks layer of `d`, with the id of the artboard it belongs to.
|
||||
pub(crate) fn managed_owners(d: &Document) -> std::collections::HashMap<NodeId, u32> {
|
||||
marks_layer(d).and_then(|l| l.children()).into_iter().flatten().filter_map(|k| Some((k.id, owner(k)?))).collect()
|
||||
}
|
||||
|
||||
/// The id of the marks layer of `d`, when it has one.
|
||||
pub(crate) fn layer_id(d: &Document) -> Option<NodeId> {
|
||||
marks_layer(d).map(|l| l.id)
|
||||
}
|
||||
|
||||
/// Is `n` the marks group of one of the artboards with ids `boards`?
|
||||
pub(crate) fn owned_by(n: &Node, boards: &[u32]) -> bool {
|
||||
owner(n).is_some_and(|o| boards.contains(&o))
|
||||
}
|
||||
|
||||
/// Each marks group on the marks layer of `d` that goes with an artboard copy, in paint order,
|
||||
/// with the id of the artboard it belongs to. Locked and hidden ones, and all of them while the
|
||||
/// marks layer is locked or hidden, only with `locked_and_hidden`.
|
||||
pub(crate) fn copied_owners(d: &Document, locked_and_hidden: bool) -> Vec<(NodeId, u32)> {
|
||||
let layer = marks_layer(d).filter(|l| l.rides_with_artboard(locked_and_hidden));
|
||||
let kids = layer.and_then(|l| l.children()).into_iter().flatten();
|
||||
kids.filter(|k| k.rides_with_artboard(locked_and_hidden)).filter_map(|k| Some((k.id, owner(k)?))).collect()
|
||||
}
|
||||
|
||||
/// Make copy `n` of an artboard's marks group belong to the artboard copied with it: its data
|
||||
/// names artboard `from`, and from now on names `to`. Duplicate Artboards, Alt-drag and paste call
|
||||
/// it on each copy they make. → whether `n` was such a group.
|
||||
pub(crate) fn retag(n: &mut Node, from: u32, to: u32) -> bool {
|
||||
if owner(n) != Some(from) {
|
||||
return false;
|
||||
}
|
||||
let (from, to) = (from.to_string(), to.to_string());
|
||||
n.edit_attrs(|a| {
|
||||
for (k, v) in a.data.iter_mut() {
|
||||
if k == KEY && *v == from {
|
||||
v.clone_from(&to);
|
||||
}
|
||||
}
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// Make the marks groups of the deleted artboards with ids `gone` ordinary art: a file opened
|
||||
/// again can give a new artboard one of those ids, and its marks are drawn afresh.
|
||||
pub(crate) fn release(d: &mut Document, gone: &std::collections::HashSet<u32>) {
|
||||
// Groups moved off the marks layer keep their tag and count too.
|
||||
let mut groups: Vec<NodeId> = vec![];
|
||||
for l in &d.layers {
|
||||
l.walk(&mut |n: &Node| {
|
||||
if owner(n).is_some_and(|o| gone.contains(&o)) {
|
||||
groups.push(n.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
for id in groups {
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
n.edit_attrs(|a| a.data.retain(|(k, _)| k != KEY));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make top-level layer `layer`, which a paste made for a marks group it copied with an artboard,
|
||||
/// the marks layer, when the document has none.
|
||||
pub(crate) fn adopt_layer(d: &mut Document, layer: NodeId) {
|
||||
if marks_layer(d).is_some() || !d.layers.iter().any(|l| l.id == layer) {
|
||||
return;
|
||||
}
|
||||
if let Some(l) = d.node_mut(layer) {
|
||||
l.edit_attrs(|a| a.data.push((KEY.into(), "layer".into())));
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` with every object's id 0: marks drawn again compare equal to marks drawn the same way.
|
||||
fn without_ids(n: &Node) -> Node {
|
||||
let mut n = n.clone();
|
||||
n.id = NodeId(0);
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
*c = Arc::new(without_ids(c));
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn screen_marks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let positions = positions(p)?;
|
||||
let size = number(p, "size", 36.0, 4.0..=1000.0)?;
|
||||
let weight = number(p, "weight", 1.0, 0.1..=20.0)?;
|
||||
let inset = number(p, "inset", 18.0, -1000.0..=1000.0)?;
|
||||
let text_size = number(p, "textSize", 9.0, 4.0..=72.0)?;
|
||||
let top = choice(p, "textPlace", ["top", "bottom"], "bottom")? == "top";
|
||||
let left = choice(p, "textAlign", ["left", "right"], "left")? == "left";
|
||||
let want_inks = switch_or(p, "inks", false, C)?;
|
||||
let want_info = switch_or(p, "info", false, C)?;
|
||||
let all = switch_or(p, "allArtboards", false, C)?;
|
||||
let given_time = date_param(p, "time", C)?;
|
||||
let ink_name = text_param(p, "ink", C)?.unwrap_or(REGISTRATION).to_string();
|
||||
// Defaults are for values left out; only `time` takes null (no date).
|
||||
if let Some((key, _)) = p.as_object().and_then(|o| o.iter().find(|(k, v)| v.is_null() && *k != "time")) {
|
||||
return Err(bad(C, format!("`{key}` must not be null: leave it out for the default")));
|
||||
}
|
||||
let artboard = index_opt(p, "artboard", C)?;
|
||||
if all && artboard.is_some() {
|
||||
return Err(bad(C, "give `artboard` or `allArtboards`, not both"));
|
||||
}
|
||||
// The active artboard, noted in the journal (`activeArtboard`) so a replay marks the same one;
|
||||
// recorded actions leave it out and use the active artboard when played.
|
||||
let recorded = index_opt(p, "activeArtboard", C)?;
|
||||
let artboard = match artboard {
|
||||
None if !all => {
|
||||
let i = match recorded {
|
||||
Some(i) => Some(i),
|
||||
None => active_artboard(s.doc()?),
|
||||
};
|
||||
if let Some(i) = i {
|
||||
s.note_journal("activeArtboard", json!(i));
|
||||
}
|
||||
i
|
||||
}
|
||||
given => given,
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let doc = &st.doc;
|
||||
if doc.artboards.is_empty() {
|
||||
return Err(bad(C, "the document has no artboards"));
|
||||
}
|
||||
let boards: Vec<(Rect, u32)> = if all {
|
||||
doc.artboards.iter().map(|a| (a.rect, a.id)).collect()
|
||||
} else {
|
||||
let i = artboard.unwrap_or(0);
|
||||
let a = doc.artboards.get(i).ok_or_else(|| bad(C, format!("there is no artboard {i}")))?;
|
||||
vec![(a.rect, a.id)]
|
||||
};
|
||||
let ink = ink_paint(doc, &ink_name)?;
|
||||
let inks = if want_inks { spot_inks(doc) } else { vec![] };
|
||||
if inks.len() > MAX_INKS {
|
||||
return Err(bad(C, format!("a line names at most {MAX_INKS} spot inks")));
|
||||
}
|
||||
let file = st
|
||||
.path
|
||||
.as_deref()
|
||||
.and_then(|path| std::path::Path::new(path).file_name())
|
||||
.map(|f| f.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| doc.title.clone());
|
||||
let system_layout = doc.setup.system_layout;
|
||||
if positions.is_empty() && inks.is_empty() && !want_info {
|
||||
let why = if want_inks { "the document has no spot inks" } else { "give `positions`, `inks` or `info`" };
|
||||
return Err(bad(C, format!("nothing to draw: {why}")));
|
||||
}
|
||||
let mut lines: Vec<Vec<(String, Paint)>> = vec![];
|
||||
if !inks.is_empty() {
|
||||
let last = inks.len() - 1;
|
||||
lines.push(
|
||||
inks.iter().enumerate().map(|(i, (name, paint))| (if i < last { format!("{name} ") } else { name.clone() }, paint.clone())).collect(),
|
||||
);
|
||||
}
|
||||
if want_info {
|
||||
let date = clock_date(s, "time", given_time).map(|t| {
|
||||
let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t);
|
||||
format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02} UTC")
|
||||
});
|
||||
let text = match date {
|
||||
Some(date) => format!("{file} {date}"),
|
||||
None => file,
|
||||
};
|
||||
lines.push(vec![(text, ink.clone())]);
|
||||
}
|
||||
let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size }), C)?;
|
||||
let marks = Marks { positions, size, weight, inset, ink, lines, style, system_layout, top, left };
|
||||
let names: Vec<String> = inks.into_iter().map(|(name, _)| name).collect();
|
||||
|
||||
// The marks as they would come out, to tell whether anything changes.
|
||||
let st = s.doc()?;
|
||||
let layer = marks_layer(&st.doc).map(|l| (l.id, l.children().cloned().unwrap_or_default()));
|
||||
let drawn: Vec<Node> = boards.iter().map(|(r, board)| marks.group(*r, *board, &mut || NodeId(0))).collect();
|
||||
// Only the stroked targets reach past their paths, by half the target weight. The lines of type
|
||||
// have no stroke; their glyphs' ink, underline and strikethrough bars included, is checked as well.
|
||||
let past = |b: Rect, reach: f64| [b.x0 - reach, b.y0 - reach, b.x1 + reach, b.y1 + reach].iter().any(|v| !v.is_finite() || v.abs() > MAX_COORD);
|
||||
let beyond = |n: &Node| match &n.kind {
|
||||
NodeKind::Text(t) => {
|
||||
n.geometric_bounds().is_some_and(|b| past(b, 0.0)) || t.ink().flatten().is_some_and(|ink| past(t.xf.transform_rect_bbox(ink), 0.0))
|
||||
}
|
||||
_ => n.geometric_bounds().is_some_and(|b| past(b, marks.weight / 2.0)),
|
||||
};
|
||||
if drawn.iter().any(|g| g.children().is_some_and(|kids| kids.iter().any(|k| beyond(k)))) {
|
||||
return Err(bad(C, format!("the marks would reach past the edge of the canvas (±{MAX_COORD} pt)")));
|
||||
}
|
||||
// Each existing group under the artboard it belongs to, worked out once.
|
||||
let mut owned: std::collections::HashMap<u32, Vec<&Arc<Node>>> = std::collections::HashMap::new();
|
||||
for k in layer.iter().flat_map(|(_, kids)| kids) {
|
||||
if let Some(board) = owner(k) {
|
||||
owned.entry(board).or_default().push(k);
|
||||
}
|
||||
}
|
||||
if let Some((layer, _)) = &layer {
|
||||
let same = boards
|
||||
.iter()
|
||||
.zip(&drawn)
|
||||
.all(|((_, board), new)| matches!(owned.get(board).map(Vec::as_slice), Some([one]) if without_ids(one) == without_ids(new)));
|
||||
if same {
|
||||
let ids: Vec<u64> = boards.iter().filter_map(|(_, board)| owned.get(board).and_then(|g| g.first()).map(|g| g.id.0)).collect();
|
||||
return Ok(json!({ "changed": false, "layer": layer.0, "ids": ids, "inks": names }));
|
||||
}
|
||||
}
|
||||
let owned: std::collections::HashMap<u32, Vec<NodeId>> = owned.into_iter().map(|(b, g)| (b, g.into_iter().map(|k| k.id).collect())).collect();
|
||||
let (layer, ids) = s.edit("Create Screen Print Marks", |d, sel| {
|
||||
let layer = match marks_layer(d).map(|l| l.id) {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
let id = d.alloc_id();
|
||||
let color = LayerColor::Preset((d.layers.len() % LAYER_COLORS.len()) as u8);
|
||||
let mut l = Node::layer(id, LAYER_NAME, color);
|
||||
l.locked = true;
|
||||
l.edit_attrs(|a| a.data.push((KEY.into(), "layer".into())));
|
||||
d.insert(None, 0, l)?;
|
||||
id
|
||||
}
|
||||
};
|
||||
let mut ids = Vec::with_capacity(boards.len());
|
||||
for (r, board) in &boards {
|
||||
let kids = d.children(Some(layer)).cloned().unwrap_or_default();
|
||||
let old: Vec<NodeId> = owned.get(board).cloned().unwrap_or_default();
|
||||
let at = kids.iter().position(|k| old.first() == Some(&k.id)).unwrap_or(usize::MAX);
|
||||
// Only what the selection holds of the marks leaves it; the rest of the selection stays as it is.
|
||||
let mut held = vec![];
|
||||
for k in kids.iter().filter(|k| old.contains(&k.id)) {
|
||||
k.walk(&mut |n: &Node| {
|
||||
if sel.objects.contains(&n.id) || sel.anchors.contains_key(&n.id) || sel.segments.contains_key(&n.id) {
|
||||
held.push(n.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
if !held.is_empty() {
|
||||
sel.remove_all(held);
|
||||
}
|
||||
d.remove_many(&old)?;
|
||||
let g = marks.group(*r, *board, &mut || d.alloc_id());
|
||||
ids.push(g.id.0);
|
||||
d.insert(Some(layer), at, g)?;
|
||||
}
|
||||
Ok((layer, ids))
|
||||
})?;
|
||||
Ok(json!({ "changed": true, "layer": layer.0, "ids": ids, "inks": names }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,935 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::{COMMAND, LAYER_NAME};
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, p: Value) -> Value {
|
||||
s.execute(COMMAND, &p).unwrap()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: u64) -> Node {
|
||||
s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone()
|
||||
}
|
||||
|
||||
/// The targets of group `g`: each one's three paths.
|
||||
fn targets(g: &Node) -> Vec<Vec<Node>> {
|
||||
g.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|n| n.name.as_deref() == Some("Registration Target"))
|
||||
.map(|t| t.children().unwrap().iter().map(|p| (**p).clone()).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The type lines of group `g`, top to bottom as stored.
|
||||
fn lines(g: &Node) -> Vec<vectorcraft_doc::TextObject> {
|
||||
g.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => Some((**t).clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn bounds(n: &Node) -> Rect {
|
||||
n.geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-6
|
||||
}
|
||||
|
||||
/// The swatch solid paint `p` links to.
|
||||
fn swatch_of(p: &Paint) -> Option<String> {
|
||||
match p {
|
||||
Paint::Solid { swatch, .. } => swatch.clone(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_targets_go_on_a_locked_bottom_layer_in_registration_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let art = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
let r = run(&mut s, json!({}));
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert_eq!(undo_len(&s), undo + 1, "one undo step");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(art)], "the selection is kept");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let layer = &doc.layers[0];
|
||||
assert_eq!(layer.id.0, r["layer"].as_u64().unwrap(), "the marks layer is at the bottom of the stack");
|
||||
assert_eq!(layer.name.as_deref(), Some(LAYER_NAME));
|
||||
assert!(layer.locked && layer.visible, "the marks layer is locked");
|
||||
assert_eq!(doc.layers.len(), 2);
|
||||
let ids = r["ids"].as_array().unwrap();
|
||||
assert_eq!(ids.len(), 1, "one group for the active artboard");
|
||||
let g = node(&s, ids[0].as_u64().unwrap());
|
||||
assert_eq!(super::tag(&g), Some(doc.artboards[0].id.to_string().as_str()));
|
||||
let t = targets(&g);
|
||||
assert_eq!(t.len(), 4, "top, bottom, left and right by default");
|
||||
assert!(lines(&g).is_empty(), "no type lines unless asked for");
|
||||
for paths in &t {
|
||||
assert_eq!(paths.len(), 3, "a ring and two cross lines");
|
||||
for p in paths {
|
||||
assert!(p.appearance.stroke_paint().is_registration(), "stroked in [Registration]");
|
||||
assert!(p.appearance.fill_paint().is_none());
|
||||
assert!(close(p.appearance.stroke_width(), 1.0));
|
||||
}
|
||||
}
|
||||
// The top target: its 36 pt box 18 pt in from the top edge, centered across.
|
||||
let top = &t[0];
|
||||
let ring = bounds(&top[0]);
|
||||
assert!(close(ring.width(), 18.0) && close(ring.center().x, 300.0) && close(ring.center().y, 36.0), "{ring:?}");
|
||||
let across = bounds(&top[1]);
|
||||
assert!(close(across.x0, 282.0) && close(across.x1, 318.0), "{across:?}");
|
||||
let down = bounds(&top[2]);
|
||||
assert!(close(down.y0, 18.0) && close(down.y1, 54.0), "{down:?}");
|
||||
// Left, right and bottom.
|
||||
let centers: Vec<_> = t.iter().map(|p| bounds(&p[0]).center()).collect();
|
||||
assert!(close(centers[1].x, 36.0) && close(centers[1].y, 200.0), "left: {:?}", centers[1]);
|
||||
assert!(close(centers[2].x, 564.0) && close(centers[2].y, 200.0), "right: {:?}", centers[2]);
|
||||
assert!(close(centers[3].x, 300.0) && close(centers[3].y, 364.0), "bottom: {:?}", centers[3]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers.len(), 1, "undo removes the layer and its marks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positions_size_weight_inset_and_a_spot_ink_shape_the_targets() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
|
||||
let p = json!({"positions": ["bottomRight", "topLeft"], "size": 20, "weight": 0.5, "inset": -30, "ink": "Plate Red"});
|
||||
let r = run(&mut s, p);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let t = targets(&g);
|
||||
assert_eq!(t.len(), 2);
|
||||
// Drawn in POSITIONS order: top left first. A negative inset puts the targets outside.
|
||||
let tl = bounds(&t[0][0]).center();
|
||||
let br = bounds(&t[1][0]).center();
|
||||
assert!(close(tl.x, -20.0) && close(tl.y, -20.0), "{tl:?}");
|
||||
assert!(close(br.x, 620.0) && close(br.y, 420.0), "{br:?}");
|
||||
assert!(close(bounds(&t[0][0]).width(), 10.0), "the ring is half the target's width");
|
||||
assert!(close(bounds(&t[0][1]).width(), 20.0));
|
||||
for p in t.iter().flatten() {
|
||||
assert_eq!(swatch_of(&p.appearance.stroke_paint()).as_deref(), Some("Plate Red"), "the stroke links to the spot swatch");
|
||||
assert!(close(p.appearance.stroke_width(), 0.5));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_run_replaces_the_marks_and_an_unchanged_run_adds_no_undo_step() {
|
||||
let mut s = session();
|
||||
let first = run(&mut s, json!({"size": 30}));
|
||||
let layer = first["layer"].clone();
|
||||
let undo = undo_len(&s);
|
||||
let again = run(&mut s, json!({"size": 30}));
|
||||
assert_eq!(again["changed"], json!(false));
|
||||
assert_eq!(again["ids"], first["ids"], "the same group stays");
|
||||
assert_eq!(undo_len(&s), undo, "nothing changed: no undo step");
|
||||
let r = run(&mut s, json!({"size": 40, "positions": ["top"]}));
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert_eq!(r["layer"], layer, "the same layer is reused");
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.layers.len(), 2, "no second marks layer");
|
||||
let kids = doc.layers[0].children().unwrap();
|
||||
assert_eq!(kids.len(), 1, "the earlier marks are replaced");
|
||||
let t = targets(&kids[0]);
|
||||
assert_eq!(t.len(), 1);
|
||||
assert!(close(bounds(&t[0][1]).width(), 40.0));
|
||||
assert!(doc.node(NodeId(first["ids"][0].as_u64().unwrap())).is_none(), "the earlier group is gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widening_an_artboard_without_changing_the_marks_adds_no_undo_step() {
|
||||
let mut s = session();
|
||||
let p = json!({"positions": ["topLeft"]});
|
||||
let first = run(&mut s, p.clone());
|
||||
let before = node(&s, first["ids"][0].as_u64().unwrap());
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "width": 800})).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
let again = run(&mut s, p);
|
||||
assert_eq!(again["changed"], json!(false));
|
||||
assert_eq!(again["ids"], first["ids"], "the same group stays");
|
||||
assert!(node(&s, again["ids"][0].as_u64().unwrap()) == before, "the existing group stays unchanged");
|
||||
assert_eq!(undo_len(&s), undo, "unchanged marks add no undo step after a resize");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_the_marks_keeps_a_selected_slice_selected() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("object.slice.make", &json!({})).unwrap();
|
||||
s.execute("select.object.slices", &json!({})).unwrap();
|
||||
let before = s.doc().unwrap().selection.clone();
|
||||
assert!(!before.slices.is_empty());
|
||||
let r = run(&mut s, json!({"size": 50}));
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert!(s.doc().unwrap().selection == before, "the selection is kept as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_past_the_canvas_edge_are_refused() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 3999000, "y": 0, "width": 900, "height": 100})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let err = s.execute(COMMAND, &json!({"artboard": 1, "positions": ["right"], "inset": -1000})).unwrap_err().to_string();
|
||||
assert!(err.contains("edge of the canvas"), "{err}");
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
run(&mut s, json!({"artboard": 1, "positions": ["right"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_target_weight_does_not_pad_lines_of_type_at_the_canvas_edge() {
|
||||
let mut s = session();
|
||||
// The artboard ends 10 pt inside the canvas edge.
|
||||
s.execute("artboard.new", &json!({"x": 3999090, "y": 0, "width": 900, "height": 100})).unwrap();
|
||||
let p = json!({"artboard": 1, "positions": [], "info": true, "textAlign": "right", "inset": 0, "weight": 20});
|
||||
let r = run(&mut s, p);
|
||||
assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_reaches_past_its_paths_by_half_its_weight_at_the_canvas_edge() {
|
||||
let mut s = session();
|
||||
// The artboard ends at the canvas edge.
|
||||
s.execute("artboard.new", &json!({"x": 3999100, "y": 0, "width": 900, "height": 100})).unwrap();
|
||||
// The cross ends 15 pt inside the edge, and its 20 pt stroke reaches 10 pt past that.
|
||||
let r = run(&mut s, json!({"artboard": 1, "positions": ["right"], "size": 36, "weight": 20, "inset": 15}));
|
||||
assert_eq!(targets(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1);
|
||||
// 5 pt inside the edge, the stroke reaches 5 pt past it.
|
||||
let err = s.execute(COMMAND, &json!({"artboard": 1, "positions": ["right"], "size": 36, "weight": 20, "inset": 5})).unwrap_err().to_string();
|
||||
assert!(err.contains("edge of the canvas"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_artboard_gets_its_group_and_one_artboard_rerun_keeps_the_others() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 800, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
let r = run(&mut s, json!({"allArtboards": true, "positions": ["top"]}));
|
||||
assert_eq!(r["ids"].as_array().unwrap().len(), 2);
|
||||
let second = node(&s, r["ids"][1].as_u64().unwrap());
|
||||
let c = bounds(&targets(&second)[0][0]).center();
|
||||
assert!(close(c.x, 900.0) && close(c.y, 36.0), "the second artboard's own target: {c:?}");
|
||||
let only = run(&mut s, json!({"artboard": 1, "positions": ["bottom"]}));
|
||||
assert_eq!(only["ids"].as_array().unwrap().len(), 1);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let kids = doc.layers[0].children().unwrap();
|
||||
assert_eq!(kids.len(), 2, "the first artboard's marks stay");
|
||||
assert!(kids.iter().any(|k| k.id.0 == r["ids"][0].as_u64().unwrap()));
|
||||
let c = bounds(&targets(&node(&s, only["ids"][0].as_u64().unwrap()))[0][0]).center();
|
||||
assert!(close(c.x, 900.0) && close(c.y, 64.0), "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ink_line_names_each_spot_ink_in_its_own_ink_and_the_file_line_gives_name_and_time() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Plate Blue", "color": "#1122cc", "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Process", "color": "#22cc11"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"colors": [{"swatch": "Plate Red", "tint": 50}]})).unwrap();
|
||||
// A tint swatch marked spot, as a file can hold one, is still a tint of its ink.
|
||||
let st = s.doc_mut().unwrap();
|
||||
let mut tints = 0;
|
||||
for w in std::sync::Arc::make_mut(&mut st.doc).swatches_iter_mut().filter(|w| w.tint_of().is_some()) {
|
||||
w.spot = true;
|
||||
tints += 1;
|
||||
}
|
||||
assert_eq!(tints, 1);
|
||||
let title = s.doc().unwrap().doc.title.clone();
|
||||
// 2026-03-04 05:06 UTC.
|
||||
let r = run(&mut s, json!({"positions": [], "inks": true, "info": true, "time": 1772600760}));
|
||||
assert_eq!(r["inks"], json!(["Plate Red", "Plate Blue"]), "spot inks only: process, tints and [Registration] left out");
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(targets(&g).is_empty());
|
||||
let l = lines(&g);
|
||||
assert_eq!(l.len(), 2);
|
||||
let names: Vec<_> = l[0].runs.iter().map(|run| (run.text.trim().to_string(), swatch_of(&run.style.fill))).collect();
|
||||
assert_eq!(names, [("Plate Red".into(), Some("Plate Red".into())), ("Plate Blue".into(), Some("Plate Blue".into()))]);
|
||||
assert_eq!(l[1].plain_text(), format!("{title} 2026-03-04 05:06 UTC"));
|
||||
assert!(l[1].runs[0].style.fill.is_registration(), "the file line prints on every plate");
|
||||
assert!(l.iter().all(|t| close(t.runs[0].style.size, 9.0)));
|
||||
// At the bottom left by default: the file line is the lower one, both 18 pt in.
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let kids = g.children().unwrap();
|
||||
let texts: Vec<_> = kids.iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).collect();
|
||||
assert!(texts[0].y1 <= texts[1].y0 + 1e-6, "the ink line sits above the file line");
|
||||
assert!((texts[1].y1 - 382.0).abs() < 0.5 && (texts[0].x0 - 18.0).abs() < 0.5, "{texts:?}");
|
||||
// No date without a time.
|
||||
let r = run(&mut s, json!({"positions": [], "info": true, "time": null}));
|
||||
assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap()))[0].plain_text(), title);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_at_the_top_right_start_past_a_corner_target() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
|
||||
let p = json!({"positions": ["topRight"], "inks": true, "textPlace": "top", "textAlign": "right", "textSize": 12});
|
||||
let r = run(&mut s, p);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap();
|
||||
let target = bounds(&targets(&g)[0][1]);
|
||||
// 600 - 18 (inset) - 36 (target) - 12 (a gap of the type size).
|
||||
assert!((text.x1 - 534.0).abs() < 0.5, "{text:?}");
|
||||
assert!(text.x1 < target.x0, "the line clears the corner target");
|
||||
assert!((text.y0 - 18.0).abs() < 0.5, "{text:?}");
|
||||
assert!(close(lines(&g)[0].runs[0].style.size, 12.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_move_up_past_a_bottom_center_target_they_would_cross() {
|
||||
let mut s = session();
|
||||
let p = json!({"positions": ["bottom"], "info": true, "time": 1772600760, "textSize": 72});
|
||||
let r = run(&mut s, p);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap();
|
||||
let target = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!(text.x0 < target.x1 && text.x1 > target.x0, "the line is long enough to reach the target: {text:?} {target:?}");
|
||||
assert!(text.y1 <= target.y0, "the line sits above the bottom target: {text:?} {target:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_do_not_move_above_a_short_artboard_to_clear_a_bottom_target() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "width": 100, "height": 56})).unwrap();
|
||||
let p = json!({"positions": [], "info": true, "time": 1772600760});
|
||||
let original = run(&mut s, p.clone());
|
||||
let original_bounds = bounds(&node(&s, original["ids"][0].as_u64().unwrap()));
|
||||
let mut with_target = p;
|
||||
with_target["positions"] = json!(["bottom"]);
|
||||
let r = run(&mut s, with_target);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| bounds(n)).unwrap();
|
||||
let target = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!(text.x0 < target.x1 && text.x1 > target.x0, "the file line reaches the bottom target: {text:?} {target:?}");
|
||||
assert!(text.y0 >= 0.0 && text.y1 <= 56.0, "the line stays vertically inside the artboard: {text:?}");
|
||||
assert_eq!(text, original_bounds, "the line keeps its original placement when shifting would leave the artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_do_not_move_onto_the_opposite_target_on_a_short_artboard() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 110})).unwrap();
|
||||
let p = json!({"artboard": 1, "positions": ["top", "bottom"], "info": true, "time": 1772600760, "textSize": 24});
|
||||
let r = run(&mut s, p);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap();
|
||||
let top = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!(text.x1 <= top.x0 || text.y0 >= top.y1, "the line stays off the top target: {text:?} {top:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_with_a_duplicated_artboard_belong_to_the_copy() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
assert_eq!(kids(&s), 2, "the duplicate carries a copy of the marks");
|
||||
let copy = run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
assert_eq!(kids(&s), 2, "marking the duplicate replaces the copy");
|
||||
let source = run(&mut s, json!({}));
|
||||
assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged");
|
||||
assert_eq!(kids(&s), 2);
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(copy["ids"][0].as_u64().unwrap())).is_some(), "the duplicate's marks stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_with_a_pasted_artboard_belong_to_the_pasted_one() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |k| k.len())).sum::<usize>();
|
||||
let before = kids(&s);
|
||||
run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
assert_eq!(kids(&s), before, "marking the pasted artboard replaces the pasted copy");
|
||||
let source = run(&mut s, json!({}));
|
||||
assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_with_an_artboard_paste_back_into_their_locked_layer() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let marks = |s: &Session| s.doc().unwrap().doc.node(layer).map(|l| (l.locked, l.children().map_or(0, |k| k.len())));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(marks(&s), Some((true, 2)), "the pasted marks go into the marks layer, which stays locked");
|
||||
run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
assert_eq!(marks(&s), Some((true, 2)), "marking the pasted artboard replaces the pasted copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_from_an_unnamed_marks_layer_paste_back_into_it() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
let st = s.doc_mut().unwrap();
|
||||
std::sync::Arc::make_mut(&mut st.doc).node_mut(layer).unwrap().name = None;
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let marks = |s: &Session| s.doc().unwrap().doc.node(layer).map(|l| (l.locked, l.children().map_or(0, |k| k.len())));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(marks(&s), Some((true, 2)), "the pasted marks go into the unnamed marks layer, which stays locked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_pasted_into_another_document_go_into_its_marks_layer_not_a_layer_of_the_same_name() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({}));
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
let plain = NodeId(s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let kids = |s: &Session, l: NodeId| s.doc().unwrap().doc.node(l).map(|l| (l.locked, l.children().map_or(0, |k| k.len())));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(kids(&s, layer), Some((true, 2)), "the pasted marks go into the locked marks layer");
|
||||
assert_eq!(kids(&s, plain), Some((false, 0)), "the ordinary layer of the same name stays empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_pasted_without_a_marks_layer_make_one_and_skip_a_layer_of_the_same_name() {
|
||||
for props in [json!({}), json!({"visible": false}), json!({"locked": true})] {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let plain = s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].clone();
|
||||
let mut set = props.clone();
|
||||
set["id"] = plain.clone();
|
||||
s.execute("layer.setProps", &set).unwrap();
|
||||
let plain = NodeId(plain.as_u64().unwrap());
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.artboards.len(), 2, "{props}");
|
||||
assert_eq!(doc.node(plain).and_then(|l| l.children().map(|k| k.len())), Some(0), "the ordinary layer stays empty: {props}");
|
||||
let made: Vec<_> = doc.layers.iter().filter(|l| l.id != plain && l.name.as_deref() == Some(LAYER_NAME)).collect();
|
||||
assert_eq!(made.len(), 1, "a marks layer is made: {props}");
|
||||
assert_eq!(made[0].children().map_or(0, |k| k.len()), 1, "the pasted marks go into it: {props}");
|
||||
let made = made[0].id.0;
|
||||
let r = run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
assert_eq!(r["layer"], json!(made), "the command uses the made layer: {props}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_and_art_from_a_layer_of_the_same_name_paste_into_separate_layers() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "name": "Renamed Marks"})).unwrap();
|
||||
s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
for paste in 1..=2 {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let marks = super::layer_id(doc).expect("a marks layer is made");
|
||||
let named: Vec<_> = doc.layers.iter().filter(|l| l.name.as_deref() == Some(LAYER_NAME)).collect();
|
||||
assert_eq!(named.len(), 2, "the marks layer and the ordinary layer are separate: paste {paste}");
|
||||
for l in named {
|
||||
let items = l.children().unwrap().len();
|
||||
assert_eq!(items, paste, "each paste adds one item to each layer: paste {paste}, marks {}", l.id == marks);
|
||||
}
|
||||
let ordinary = doc.layers.iter().find(|l| l.name.as_deref() == Some(LAYER_NAME) && l.id != marks).unwrap();
|
||||
assert_eq!(ordinary.children().unwrap().len(), paste, "the ordinary layer holds one rectangle per paste: paste {paste}");
|
||||
assert!(
|
||||
ordinary.children().unwrap().iter().all(|k| k.children().is_none()),
|
||||
"only the rectangle goes into the ordinary layer: paste {paste}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_pasted_again_skips_a_marks_layer_above_its_ordinary_layer() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let ordinary = NodeId(s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].as_u64().unwrap());
|
||||
for paste in 1..=2 {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let marks = super::layer_id(doc).expect("a marks layer is made");
|
||||
assert_ne!(marks, ordinary);
|
||||
let kids = |l: NodeId| doc.node(l).unwrap().children().unwrap().iter().map(|k| k.children().is_none()).collect::<Vec<_>>();
|
||||
assert_eq!(kids(ordinary), vec![true; paste], "the rectangles go into the ordinary layer: paste {paste}");
|
||||
assert_eq!(kids(marks), vec![false; paste], "only marks go into the marks layer: paste {paste}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_lying_off_an_artboard_go_with_its_copy_made_by_moving_it() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
let b = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
assert!(b.x0 >= 600.0, "the marks lie wholly off the artboard: {b:?}");
|
||||
let p = json!({"index": 0, "dy": 500, "copy": true, "moveArt": true, "lockedAndHidden": true});
|
||||
s.execute("artboard.move", &p).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(kids(&s), 2, "the copy carries a copy of the marks");
|
||||
run(&mut s, json!({"artboard": 1, "positions": ["right"], "inset": -200, "size": 30}));
|
||||
assert_eq!(kids(&s), 2, "marking the copy replaces the copied marks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_art_copied_with_an_artboard_does_not_paste_into_a_locked_layer() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
let other = s.doc().unwrap().doc.layers[1].id.0;
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": other, "locked": true})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let err = s.execute("edit.paste", &json!({})).unwrap_err().to_string();
|
||||
assert!(err.contains("locked or hidden"), "{err}");
|
||||
assert!(s.doc().unwrap().doc == before, "nothing is pasted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_pasted_after_their_layer_was_deleted_are_found_again() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("layer.delete", &json!({"ids": [r["layer"]]})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let layers: Vec<_> = doc.layers.iter().filter(|l| l.name.as_deref() == Some(LAYER_NAME)).collect();
|
||||
assert_eq!(layers.len(), 1, "one marks layer");
|
||||
assert_eq!(layers[0].children().unwrap().len(), 1, "marking the pasted artboard replaces the pasted copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_artboards_marks_lying_on_a_copied_artboard_stay_with_their_own() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let b = bounds(&g);
|
||||
assert!(b.x0 >= 700.0 && b.x1 <= 1300.0, "the marks lie wholly on the second artboard: {b:?}");
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
s.execute("artboard.duplicate", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(kids(&s), 1, "duplicating the second artboard leaves the first one's marks out");
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
let copied = s.execute("artboard.copy", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(copied["copied"], json!(0), "copying the second artboard leaves the first one's marks out");
|
||||
let again = run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
assert_eq!(again["changed"], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicating_overlapping_artboards_copies_marks_lying_on_both_once() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
run(&mut s, json!({"artboard": 1, "positions": ["left"]}));
|
||||
s.execute("artboard.duplicate", &json!({"indices": [0, 1], "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the second artboard's copy carries its marks");
|
||||
let copy = run(&mut s, json!({"artboard": 3, "positions": ["left"], "size": 30}));
|
||||
assert_eq!(copy["changed"], json!(true));
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "marking that copy replaces the copied marks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_lying_on_another_copied_artboard_go_with_their_own_artboards_copy() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let p = json!({"positions": ["right"], "inset": -200});
|
||||
run(&mut s, p.clone());
|
||||
s.execute("artboard.duplicate", &json!({"indices": [0, 1], "art": true, "lockedAndHidden": true})).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
assert_eq!(kids(&s), 2, "the first artboard's copy carries its marks");
|
||||
run(&mut s, json!({"artboard": 2, "positions": ["right"], "inset": -200, "size": 30}));
|
||||
assert_eq!(kids(&s), 2, "marking the first artboard's copy replaces the copied marks");
|
||||
assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged");
|
||||
}
|
||||
|
||||
/// `target` (`index` or `indices`) with the parameters each artboard copy command takes: an
|
||||
/// Alt-drag for `artboard.move`, and the artboards' art for the others.
|
||||
fn copy_params(command: &str, target: Value) -> Value {
|
||||
let mut p = match command {
|
||||
"artboard.move" => json!({"moveArt": true, "copy": true, "dy": 500, "lockedAndHidden": true}),
|
||||
_ => json!({"art": true, "lockedAndHidden": true}),
|
||||
};
|
||||
if let (Some(p), Some(t)) = (p.as_object_mut(), target.as_object()) {
|
||||
p.extend(t.clone());
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_artboard_copies_keep_one_marks_group_per_owner() {
|
||||
for command in ["artboard.duplicate", "artboard.move", "artboard.copy"] {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let first = run(&mut s, json!({"artboard": 0, "positions": ["right"]}));
|
||||
let second = run(&mut s, json!({"artboard": 1, "positions": ["left"]}));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let originals = [node(&s, first["ids"][0].as_u64().unwrap()), node(&s, second["ids"][0].as_u64().unwrap())];
|
||||
let p = copy_params(command, json!({"indices": [0, 1]}));
|
||||
s.execute(command, &p).unwrap();
|
||||
if command == "artboard.copy" {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let groups = d.layers[0].children().unwrap();
|
||||
assert_eq!(groups.len(), 4, "{command}");
|
||||
for (source, original) in originals.iter().enumerate() {
|
||||
assert!(d.node(original.id).unwrap() == original, "{command}");
|
||||
let copied_board = &d.artboards[source + 2];
|
||||
let copies: Vec<_> = groups.iter().filter(|g| super::owner(g) == Some(copied_board.id)).collect();
|
||||
assert_eq!(copies.len(), 1, "{command}: owner {source}");
|
||||
let offset = copied_board.rect.origin() - d.artboards[source].rect.origin();
|
||||
assert_eq!(bounds(copies[0]), bounds(original) + offset, "{command}: owner {source}");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before, "{command}: one undo restores both artboards and marks");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_board_marks_follow_artboard_copies_and_cuts_by_owner() {
|
||||
for command in ["artboard.duplicate", "artboard.move", "artboard.copy", "artboard.cut"] {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}));
|
||||
let original = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let other = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}));
|
||||
let foreign = node(&s, other["ids"][0].as_u64().unwrap());
|
||||
assert!(bounds(&original).y1 < 0.0);
|
||||
assert!(s.doc().unwrap().doc.artboards[0].rect.contains_rect(bounds(&foreign)));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let p = copy_params(command, json!({"index": 0}));
|
||||
let reply = s.execute(command, &p).unwrap();
|
||||
if command == "artboard.cut" {
|
||||
assert_eq!(reply["copied"], json!(1));
|
||||
assert!(s.doc().unwrap().doc.node(original.id).is_none());
|
||||
}
|
||||
if matches!(command, "artboard.copy" | "artboard.cut") {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let copied_board = d.artboards.last().unwrap();
|
||||
let copies: Vec<_> = d.layers[0].children().unwrap().iter().filter(|g| super::owner(g) == Some(copied_board.id)).collect();
|
||||
assert_eq!(copies.len(), 1, "{command}");
|
||||
assert!(d.node(foreign.id).unwrap() == &foreign, "{command}: another artboard's marks stay unchanged");
|
||||
let offset = copied_board.rect.origin() - before.artboards[0].rect.origin();
|
||||
assert_eq!(bounds(copies[0]), bounds(&original) + offset, "{command}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
if command == "artboard.cut" {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert!(s.doc().unwrap().doc == before, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_artboard_uses_marks_ownership_instead_of_containment() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let outside = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}));
|
||||
let other = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}));
|
||||
let own = node(&s, outside["ids"][0].as_u64().unwrap());
|
||||
let foreign = node(&s, other["ids"][0].as_u64().unwrap());
|
||||
assert!(bounds(&own).y1 < 0.0);
|
||||
assert!(s.doc().unwrap().doc.artboards[0].rect.contains_rect(bounds(&foreign)));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
for (move_art, all) in [(false, true), (true, false)] {
|
||||
s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": move_art, "lockedAndHidden": all})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own);
|
||||
assert!(node(&s, foreign.id.0) == foreign);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
}
|
||||
s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": true})).unwrap();
|
||||
let start = bounds(&own);
|
||||
let moved = bounds(&node(&s, own.id.0));
|
||||
let expected = (start.x0, start.y0 + 500.0, start.x1, start.y1 + 500.0);
|
||||
assert_eq!((moved.x0, moved.y0, moved.x1, moved.y1), expected, "the marks move 500 pt down with their artboard");
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
assert_eq!(board.y0, before.artboards[0].rect.y0 + 500.0, "the artboard itself moved");
|
||||
assert!(moved.y1 < board.y0, "the top marks stay above their moved artboard");
|
||||
assert!(node(&s, foreign.id.0) == foreign);
|
||||
assert_eq!(super::owner(&node(&s, own.id.0)), super::owner(&own));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_lying_on_another_artboard_go_with_their_own_artboards_copy_alone() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let p = json!({"positions": ["right"], "inset": -200});
|
||||
run(&mut s, p.clone());
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap();
|
||||
assert_eq!(kids(&s), 1, "the locked marks stay without lockedAndHidden");
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(kids(&s), 2, "the first artboard's copy carries its marks lying on the second artboard");
|
||||
run(&mut s, json!({"artboard": 3, "positions": ["right"], "inset": -200, "size": 30}));
|
||||
assert_eq!(kids(&s), 2, "marking the copy replaces the copied marks");
|
||||
assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marks_group_moved_off_the_marks_layer_is_copied_like_other_art() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
let other = s.doc().unwrap().doc.layers[1].id.0;
|
||||
s.execute("layer.move", &json!({"ids": [r["ids"][0]], "target": other})).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[1].children().unwrap().len();
|
||||
let before = kids(&s);
|
||||
s.execute("artboard.duplicate", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(kids(&s), before + 1, "the duplicate carries a copy of the moved group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_of_a_deleted_artboard_are_copied_like_other_art() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
s.execute("artboard.delete", &json!({"indices": [0]})).unwrap();
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the duplicate carries a copy of the marks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_with_a_duplicated_artboard_stay_with_the_copy_after_a_resize() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "width": 500})).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
let source = run(&mut s, json!({}));
|
||||
assert_eq!(source["changed"], json!(false), "the copy's marks are not the source's");
|
||||
assert_eq!(kids(&s), 2);
|
||||
run(&mut s, json!({"artboard": 1}));
|
||||
assert_eq!(kids(&s), 2, "marking the resized duplicate replaces the copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrinking_an_artboard_keeps_its_marks_when_a_new_artboard_covers_more_of_the_stored_rectangle() {
|
||||
let mut s = session();
|
||||
let original = run(&mut s, json!({}));
|
||||
let id = original["ids"][0].as_u64().unwrap();
|
||||
let before = node(&s, id);
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "width": 100})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 120, "y": 0, "width": 480, "height": 400})).unwrap();
|
||||
run(&mut s, json!({"artboard": 1}));
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(id)).is_some(), "marking the new artboard keeps the original group");
|
||||
assert!(node(&s, id) == before, "the original group's art and metadata stay unchanged");
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
|
||||
run(&mut s, json!({"artboard": 0}));
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(id)).is_none(), "marking the resized source replaces its old group");
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_that_reach_onto_the_next_artboard_stay_with_their_own() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 620, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"allArtboards": true, "positions": ["right"], "inset": -60}));
|
||||
let ids = r["ids"].as_array().unwrap();
|
||||
assert_eq!(ids.len(), 2);
|
||||
for id in ids {
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some(), "group {id} is kept");
|
||||
}
|
||||
let again = run(&mut s, json!({"allArtboards": true, "positions": ["right"], "inset": -60}));
|
||||
assert_eq!(again["changed"], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_and_leave_the_document_unchanged() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Process", "color": "#22cc11"})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = undo_len(&s);
|
||||
for bad in [
|
||||
json!({"positions": ["middle"]}),
|
||||
json!({"positions": ["top", "top"]}),
|
||||
json!({"positions": "top"}),
|
||||
json!({"positions": [1]}),
|
||||
json!({"size": 2}),
|
||||
json!({"size": "36"}),
|
||||
json!({"weight": 0}),
|
||||
json!({"inset": 5000}),
|
||||
json!({"textSize": 100}),
|
||||
json!({"textPlace": "middle"}),
|
||||
json!({"textAlign": 1}),
|
||||
json!({"ink": "Nope"}),
|
||||
json!({"ink": "Process"}),
|
||||
json!({"ink": 3}),
|
||||
json!({"inks": "yes"}),
|
||||
json!({"info": 1}),
|
||||
json!({"time": "today", "info": true}),
|
||||
json!({"artboard": 5}),
|
||||
json!({"artboard": -1}),
|
||||
json!({"artboard": 0, "allArtboards": true}),
|
||||
json!({"positions": null}),
|
||||
json!({"artboard": null}),
|
||||
json!({"size": null}),
|
||||
json!({"positions": [], "inks": false, "info": false}),
|
||||
json!({"positions": [], "inks": true}),
|
||||
] {
|
||||
assert!(s.execute(COMMAND, &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
// An ink line with no spot inks draws the targets and no line.
|
||||
let r = run(&mut s, json!({"inks": true}));
|
||||
assert_eq!(r["inks"], json!([]));
|
||||
assert!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_of_a_deleted_artboard_belong_to_no_artboard_that_later_takes_its_id() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 1, "positions": ["right"]}));
|
||||
let gone = s.doc().unwrap().doc.artboards[1].id;
|
||||
s.execute("artboard.delete", &json!({"indices": [1]})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).is_some(), "the marks stay as art");
|
||||
// A reopened file does not remember the deleted id, so a new artboard can take it.
|
||||
assert!(!super::managed_owners(&s.doc().unwrap().doc).values().any(|o| *o == gone), "no marks group names the deleted artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_moved_off_the_marks_layer_forget_their_deleted_artboard() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 1, "positions": ["right"]}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
let other = s.doc().unwrap().doc.layers[1].id.0;
|
||||
s.execute("layer.move", &json!({"ids": [r["ids"][0]], "target": other})).unwrap();
|
||||
s.execute("artboard.delete", &json!({"indices": [1]})).unwrap();
|
||||
assert_eq!(super::owner(&node(&s, r["ids"][0].as_u64().unwrap())), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_artboard_leaves_its_marks_lying_on_another_locked_artboard() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200}));
|
||||
let own = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
|
||||
s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": false})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own, "Move Artboard leaves them on the locked artboard");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "y": 500, "moveArt": true, "lockedAndHidden": false})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own, "a new position leaves them on the locked artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_artboard_scaled_in_the_same_call_leaves_a_moving_artboards_marks_to_it() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200}));
|
||||
let start = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
let edits = json!([{"index": 1, "width": 1200}, {"index": 0, "y": 500}]);
|
||||
s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": true})).unwrap();
|
||||
let moved = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
assert_eq!((moved.x0, moved.y0, moved.width()), (start.x0, start.y0 + 500.0, start.width()), "the marks move with their own artboard, unscaled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_on_an_artboard_unlocked_in_the_same_call_stay_when_their_own_artboard_moves() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200}));
|
||||
let own = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
|
||||
let edits = json!([{"index": 0, "y": 500}, {"index": 1, "locked": false, "y": 500}]);
|
||||
s.execute("artboard.setProps", &json!({"artboards": edits, "moveArt": true, "lockedAndHidden": false})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own, "the marks lay on a locked artboard when the call began");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let edits = json!([{"index": 0, "y": 500}, {"index": 1, "locked": false, "width": 1200}]);
|
||||
s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": false})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own, "the artboard scaled in the same call leaves them too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marks_group_of_a_missing_artboard_goes_with_the_first_listed_artboard() {
|
||||
let mut s = session();
|
||||
for _ in 0..2 {
|
||||
s.execute("artboard.new", &json!({"x": 0, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
}
|
||||
let r = run(&mut s, json!({"artboard": 2, "positions": ["top"]}));
|
||||
// A file saved before deleting an artboard cleared its marks' tag.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.remove(2);
|
||||
let start = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
let edits = json!([{"index": 0, "width": 1200}, {"index": 1, "y": 500}]);
|
||||
s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": true})).unwrap();
|
||||
let now = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
assert!(close(now.width(), start.width() * 2.0), "it scales with the first artboard listed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_artboard_by_its_position_takes_its_own_marks_and_leaves_others() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let own = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}))["ids"][0].as_u64().unwrap();
|
||||
let foreign = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}))["ids"][0].as_u64().unwrap();
|
||||
let (own, foreign) = (node(&s, own), node(&s, foreign));
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "y": 500, "moveArt": true, "lockedAndHidden": true})).unwrap();
|
||||
let start = bounds(&own);
|
||||
let moved = bounds(&node(&s, own.id.0));
|
||||
assert_eq!((moved.x0, moved.y0), (start.x0, start.y0 + 500.0), "the marks lying above the artboard move with it");
|
||||
assert!(node(&s, foreign.id.0) == foreign, "another artboard's marks lying on it stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_drawn_on_the_active_artboard_record_it_for_a_replay() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let second = s.doc().unwrap().doc.artboards[1].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(second);
|
||||
let start = s.journal.len();
|
||||
run(&mut s, json!({"positions": ["right"]}));
|
||||
let (cmd, recorded) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(cmd, COMMAND);
|
||||
assert_eq!(recorded["activeArtboard"], json!(1), "the journal names the artboard the marks went on");
|
||||
// A replay on another active artboard marks the recorded one.
|
||||
let first = s.doc().unwrap().doc.artboards[0].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(first);
|
||||
let replayed = run(&mut s, recorded);
|
||||
assert_eq!(replayed["changed"], json!(false), "the second artboard's marks are drawn again the same");
|
||||
// A recorded action leaves it out and marks the artboard active when it plays.
|
||||
let action = s.journal_for_action(start);
|
||||
assert_eq!(action.len(), 2, "the action holds the first run and the replay");
|
||||
assert!(action.iter().all(|(_, p)| p.get("activeArtboard").is_none()));
|
||||
}
|
||||
@@ -1118,7 +1118,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
let id = s.edit(label, |d, sel| {
|
||||
let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
let mut src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
let mut image = if is_trace_group(&src) {
|
||||
src.children()
|
||||
.and_then(|c| c.first())
|
||||
@@ -1225,17 +1225,23 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
|
||||
// Tracing again keeps the tracing's own object settings: opacity, blend mode, its
|
||||
// appearance items, visibility and lock.
|
||||
if !expand && is_trace_group(&src) {
|
||||
g.visible = src.visible;
|
||||
g.locked = src.locked;
|
||||
g.opacity = src.opacity;
|
||||
g.blend = src.blend;
|
||||
g.isolate = src.isolate;
|
||||
g.knockout = src.knockout;
|
||||
g.knockout_shape = src.knockout_shape;
|
||||
g.appearance = src.appearance.clone();
|
||||
// Tracing again keeps the tracing's note, tags and URL, including when expanding.
|
||||
// Without expansion, it also keeps the tracing's other object settings.
|
||||
if is_trace_group(&src) {
|
||||
// The attributes move from `src`, this edit's own copy of the tracing, without another copy.
|
||||
if src.extras().attrs.is_some() {
|
||||
g.extras_mut().attrs = src.extras_mut().attrs.take();
|
||||
}
|
||||
if !expand {
|
||||
g.visible = src.visible;
|
||||
g.locked = src.locked;
|
||||
g.opacity = src.opacity;
|
||||
g.blend = src.blend;
|
||||
g.isolate = src.isolate;
|
||||
g.knockout = src.knockout;
|
||||
g.knockout_shape = src.knockout_shape;
|
||||
g.appearance = src.appearance.clone();
|
||||
}
|
||||
}
|
||||
if !expand {
|
||||
// Tracing again keeps the object's view unless another is asked for, and the Split
|
||||
|
||||
@@ -26,7 +26,9 @@ pub use perspective::perspective_click;
|
||||
use perspective::{
|
||||
attach, edit_text, grid_set, grid_show, persp_draw, persp_move, persp_nudge, persp_transform, plane_match, plane_move, plane_set, release,
|
||||
};
|
||||
pub(crate) use perspective::{finish_edit_text, grid_kept, grid_of, perspective_rewrite, silent, store_grid, transform_again};
|
||||
pub(crate) use perspective::{
|
||||
finish_edit_text, grid_kept, grid_of, only_grid_view_changed, perspective_rewrite, silent, store_grid, transform_again,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
|
||||
@@ -24,6 +24,37 @@ pub(crate) fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool {
|
||||
serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v))
|
||||
}
|
||||
|
||||
/// Whether `now` differs from `before` only in the view state of its perspective grid (whether it
|
||||
/// shows, the active plane, the point Automatic Plane Positioning holds and the view options), the
|
||||
/// changes [`silent`] makes without an undo step.
|
||||
pub(crate) fn only_grid_view_changed(now: &Document, before: &Document) -> bool {
|
||||
let (a, b) = (now.unknown.get(persp::DOC_KEY), before.unknown.get(persp::DOC_KEY));
|
||||
if a == b {
|
||||
return false;
|
||||
}
|
||||
let (mut g, mut was) = (PerspectiveGrid::current(now), PerspectiveGrid::current(before));
|
||||
g.visible = was.visible;
|
||||
g.plane = was.plane;
|
||||
g.inferred = was.inferred;
|
||||
g.locked = was.locked;
|
||||
g.lock_station = was.lock_station;
|
||||
g.snap = was.snap;
|
||||
g.rulers = was.rulers;
|
||||
g.attached.clear();
|
||||
was.attached.clear();
|
||||
if serde_json::to_value(&g).ok() != serde_json::to_value(&was).ok() {
|
||||
return false;
|
||||
}
|
||||
let mut rest = now.clone();
|
||||
let mut normalized_before = before.clone();
|
||||
PerspectiveGrid::current(before).store(&mut normalized_before);
|
||||
match normalized_before.unknown.get(persp::DOC_KEY) {
|
||||
Some(v) => rest.unknown.insert(persp::DOC_KEY.to_string(), v.clone()),
|
||||
None => rest.unknown.remove(persp::DOC_KEY),
|
||||
};
|
||||
rest == normalized_before
|
||||
}
|
||||
|
||||
/// Change view state of the grid without an undo step.
|
||||
pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> Result<PerspectiveGrid> {
|
||||
let st = s.doc_mut()?;
|
||||
|
||||
+107
-25
@@ -189,7 +189,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste",
|
||||
["Edit"],
|
||||
Some("Cmd+V"),
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own, also for a pie in the art of a symbol, pattern, brush or graph design the paste brings) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own, also for a pie in the art of a symbol, pattern, brush or graph design the paste brings) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted, except the Screen Print Marks layer for the marks copied with their artboard). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Offset)
|
||||
),
|
||||
@@ -1363,17 +1363,15 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.edit("Clear", |d, sel| {
|
||||
let clipped = clipped_ancestors(d, ids.iter().copied());
|
||||
let parents: Vec<_> = if keep_empty {
|
||||
Vec::new()
|
||||
} else {
|
||||
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect()
|
||||
};
|
||||
let emptied = if keep_empty { Vec::new() } else { emptied_compounds(d, &ids) };
|
||||
// A compound path inside another emptied one leaves with it.
|
||||
let outer: Vec<NodeId> = emptied
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|p| !d.ancestry(*p).unwrap_or_default().iter().rev().skip(1).any(|a| emptied.binary_search(a).is_ok()))
|
||||
.collect();
|
||||
d.remove_many(&ids)?;
|
||||
for p in parents {
|
||||
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
|
||||
d.remove(p)?;
|
||||
}
|
||||
}
|
||||
d.remove_many(&outer)?;
|
||||
if with_guides {
|
||||
let gone = sel.guides.clone();
|
||||
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
@@ -1390,6 +1388,27 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The compound paths that deleting the objects `ids` together leaves with no members, sorted by
|
||||
/// id: a compound path counts when each of its members is deleted or is such a compound path, so
|
||||
/// a compound path holding only an emptied inner one is emptied too.
|
||||
fn emptied_compounds(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut gone: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut emptied = BTreeSet::new();
|
||||
loop {
|
||||
let parents: BTreeSet<NodeId> = gone.iter().filter_map(|i| d.parent_of(*i)).filter(|p| !gone.contains(p)).collect();
|
||||
let found: BTreeSet<NodeId> = parents
|
||||
.into_iter()
|
||||
.filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))
|
||||
.filter(|p| d.children(Some(*p)).is_some_and(|k| k.iter().all(|n| gone.contains(&n.id))))
|
||||
.collect();
|
||||
if found.is_empty() {
|
||||
return emptied.into_iter().collect();
|
||||
}
|
||||
gone.extend(found.iter().copied());
|
||||
emptied.extend(found);
|
||||
}
|
||||
}
|
||||
|
||||
/// Does Clear remove direct-selected anchors without opening their paths (`keepJoined` param, else
|
||||
/// General › Delete Removes Anchor Points and Keeps Paths Joined)? Noted in the journal, so a
|
||||
/// replay removes them the same way whatever the preference is at the time. A saved step without `keepJoined`
|
||||
@@ -1638,9 +1657,16 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
&& inside.is_none()
|
||||
&& (st.doc.paste_remembers_layers || boards.is_some())
|
||||
&& parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer));
|
||||
// Screen print marks copied with an artboard that is pasted once go back into the marks layer,
|
||||
// locked or hidden as it is.
|
||||
let pasted_once: Vec<u32> = match boards {
|
||||
Some((all, _)) => all.iter().map(|a| a.id).filter(|id| all.iter().filter(|a| a.id == *id).count() == 1).collect(),
|
||||
None => vec![],
|
||||
};
|
||||
let marks: Vec<bool> = clip.nodes.iter().map(|n| super::addons::screen_marks_of(n, &pasted_once)).collect();
|
||||
// Each object's remembered layer, found before anything is pasted: a hidden or locked one
|
||||
// refuses the whole paste.
|
||||
let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, same_doc)? } else { vec![] };
|
||||
let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, &marks, same_doc)? } else { vec![] };
|
||||
// Front/back: relative to the selection (top-most / bottom-most selected object); with
|
||||
// nothing selected, the top / bottom of the current layer. Art other than paths goes beside
|
||||
// the compound path that holds the selected object, not into it.
|
||||
@@ -1681,13 +1707,22 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
let mut imported = clip.import_into(d, choices, same_doc)?;
|
||||
// Draw Inside: the clip group of the object drawn into, made on the first paste.
|
||||
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
|
||||
let artboards: Vec<usize> = boards
|
||||
let made_boards: Vec<(u32, usize)> = boards
|
||||
.into_iter()
|
||||
.flat_map(|(all, dv)| all.iter().map(move |a| (a, dv)))
|
||||
.map(|(a, dv)| super::panelcmds::push_artboard_copy(d, a, a.rect + dv))
|
||||
.map(|(a, dv)| (a.id, super::panelcmds::push_artboard_copy(d, a, a.rect + dv)))
|
||||
.collect();
|
||||
let artboards: Vec<usize> = made_boards.iter().map(|(_, i)| *i).collect();
|
||||
// Screen print marks copied with an artboard pasted once belong to the pasted artboard.
|
||||
let board_ids: Vec<(u32, u32)> = made_boards
|
||||
.iter()
|
||||
.filter(|(src, _)| made_boards.iter().filter(|(s, _)| s == src).count() == 1)
|
||||
.filter_map(|(src, i)| d.artboards.get(*i).map(|a| (*src, a.id)))
|
||||
.collect();
|
||||
// The layers made for remembered layers the document lacks, by parent and name.
|
||||
let mut made = HashMap::new();
|
||||
// The marks layer made for screen print marks, kept apart from ordinary layers of its name.
|
||||
let mut made_marks: HashMap<(Option<NodeId>, String), NodeId> = HashMap::new();
|
||||
// Objects pasted into each parent so far (keeps their order in front and back pastes).
|
||||
let mut placed: BTreeMap<Option<NodeId>, usize> = BTreeMap::new();
|
||||
let mut new_ids = vec![];
|
||||
@@ -1702,6 +1737,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
// A pasted symbol set packs from the density recorded for it at Copy.
|
||||
d.carry_set_densities(n, &c, &clip.set_densities);
|
||||
imported.apply(&mut c, d);
|
||||
let marks = board_ids.iter().any(|(from, to)| super::addons::retag_screen_marks(&mut c, *from, *to));
|
||||
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
|
||||
if xf != Affine::IDENTITY {
|
||||
// A cross-document drag carries the graphic's appearance with it,
|
||||
@@ -1710,7 +1746,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
}
|
||||
let layer = match remembered.get(k) {
|
||||
Some(Some(Remembered::Layer(l))) => Some(*l),
|
||||
Some(Some(Remembered::Make { parent, names })) => make_layers(d, &mut made, *parent, names)?,
|
||||
Some(Some(Remembered::Make { parent, names })) => make_remembered(d, &mut made, &mut made_marks, marks, *parent, names)?,
|
||||
_ => None,
|
||||
};
|
||||
// In a clip group or a clipping layer the bottom child is the clipping path: art pasted
|
||||
@@ -1850,18 +1886,27 @@ enum Remembered {
|
||||
Make { parent: Option<NodeId>, names: Vec<String> },
|
||||
}
|
||||
|
||||
/// [`remembered_layer`] for each object's source layer, worked out once for each layer.
|
||||
fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], same_doc: bool) -> Result<Vec<Option<Remembered>>> {
|
||||
let mut found: HashMap<&SourceLayer, Remembered> = HashMap::new();
|
||||
/// [`remembered_layer`] for each object's source layer, worked out once for each layer. The objects
|
||||
/// `marks` marks are screen print marks groups, which may go back into the marks layer while it
|
||||
/// is locked or hidden.
|
||||
fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], marks: &[bool], same_doc: bool) -> Result<Vec<Option<Remembered>>> {
|
||||
let mut found: HashMap<(&SourceLayer, bool), Remembered> = HashMap::new();
|
||||
sources
|
||||
.iter()
|
||||
.map(|src| {
|
||||
.enumerate()
|
||||
.map(|(k, src)| {
|
||||
// A marks group goes into the marks layer even when the layer it was copied from has
|
||||
// no name.
|
||||
if marks.get(k).copied().unwrap_or(false) && src.is_none() {
|
||||
return Ok(Some(marks_layer_target(d)));
|
||||
}
|
||||
let Some(src) = src else { return Ok(None) };
|
||||
if let Some(r) = found.get(src) {
|
||||
let key = (src, marks.get(k).copied().unwrap_or(false));
|
||||
if let Some(r) = found.get(&key) {
|
||||
return Ok(Some(r.clone()));
|
||||
}
|
||||
let r = remembered_layer(d, src, same_doc)?;
|
||||
found.insert(src, r.clone());
|
||||
let r = remembered_layer(d, src, key.1, same_doc)?;
|
||||
found.insert(key, r.clone());
|
||||
Ok(Some(r))
|
||||
})
|
||||
.collect()
|
||||
@@ -1872,8 +1917,15 @@ fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], same_doc: bo
|
||||
/// it still where they were (by id) are kept. Below them, and in another document from the top,
|
||||
/// each name is matched among the layers inside the one above (the topmost of the same name whose
|
||||
/// layers match the most names, a shown and unlocked one first). The names left unmatched are
|
||||
/// made. A matched layer that is hidden or locked, or inside one that is, is an error.
|
||||
fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result<Remembered> {
|
||||
/// made. A matched layer that is hidden or locked, or inside one that is, is an error. A screen
|
||||
/// print marks group (`marks`) goes into the document's marks layer, locked or hidden as it is,
|
||||
/// or into a new top-level marks layer when the document has none.
|
||||
fn remembered_layer(d: &Document, src: &SourceLayer, marks: bool, same_doc: bool) -> Result<Remembered> {
|
||||
// A marks group goes into the document's marks layer, never into an ordinary layer of the
|
||||
// same name.
|
||||
if marks {
|
||||
return Ok(marks_layer_target(d));
|
||||
}
|
||||
let held = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_layer() && n.name.as_ref() == src.names.last());
|
||||
let kept = if same_doc && src.ids.last().is_some_and(held) {
|
||||
src.ids.len()
|
||||
@@ -1898,6 +1950,15 @@ fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result<R
|
||||
})
|
||||
}
|
||||
|
||||
/// Where a screen print marks group goes: the document's marks layer, locked or hidden as it is,
|
||||
/// or a new top-level marks layer when the document has none.
|
||||
fn marks_layer_target(d: &Document) -> Remembered {
|
||||
match super::addons::screen_marks_layer(d) {
|
||||
Some(l) => Remembered::Layer(l),
|
||||
None => Remembered::Make { parent: None, names: vec![super::addons::SCREEN_MARKS_LAYER.to_string()] },
|
||||
}
|
||||
}
|
||||
|
||||
/// The deepest chain of layers inside `parent` (none: the top level) named `names` one inside the
|
||||
/// other: its last layer (`parent` when none matches), how many names it matched and whether all
|
||||
/// its layers are shown and unlocked. Of chains as deep, the topmost shown and unlocked one wins.
|
||||
@@ -1908,7 +1969,9 @@ fn named_chain(d: &Document, parent: Option<NodeId>, names: &[String]) -> (Optio
|
||||
None => Some(&d.layers),
|
||||
Some(p) => d.node(p).and_then(Node::children),
|
||||
};
|
||||
for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())) {
|
||||
// Ordinary art never goes into the screen print marks layer by its name.
|
||||
let marks_layer = parent.is_none().then(|| super::addons::screen_marks_layer(d)).flatten();
|
||||
for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str()) && Some(l.id) != marks_layer) {
|
||||
let (end, n, open) = named_chain(d, Some(l.id), rest);
|
||||
let chain = (end, n + 1, open && l.visible && !l.locked);
|
||||
if (chain.1, chain.2) > (best.1, best.2) {
|
||||
@@ -1918,6 +1981,25 @@ fn named_chain(d: &Document, parent: Option<NodeId>, names: &[String]) -> (Optio
|
||||
best
|
||||
}
|
||||
|
||||
/// Makes the layers of a `Remembered::Make` for one pasted object. The marks layer for a screen
|
||||
/// print marks group (`marks`) is made apart from ordinary layers of its name (`made_marks`) and
|
||||
/// becomes the marks layer, so Create Screen Print Marks finds the copy there.
|
||||
fn make_remembered(
|
||||
d: &mut Document,
|
||||
made: &mut HashMap<(Option<NodeId>, String), NodeId>,
|
||||
made_marks: &mut HashMap<(Option<NodeId>, String), NodeId>,
|
||||
marks: bool,
|
||||
parent: Option<NodeId>,
|
||||
names: &[String],
|
||||
) -> Result<Option<NodeId>> {
|
||||
let is_marks = marks && parent.is_none() && matches!(names, [n] if n == super::addons::SCREEN_MARKS_LAYER);
|
||||
let last = make_layers(d, if is_marks { made_marks } else { made }, parent, names)?;
|
||||
if let (true, Some(l)) = (is_marks, last) {
|
||||
super::addons::adopt_screen_marks_layer(d, l);
|
||||
}
|
||||
Ok(last)
|
||||
}
|
||||
|
||||
/// Layers `names`, each inside the one before, the first under `parent` (none: on top); `made`
|
||||
/// keeps the ones a paste has made, by parent and name, so they are made once. The last one, or
|
||||
/// none when `names` is empty.
|
||||
|
||||
@@ -400,3 +400,59 @@ fn selected_roots_are_found_once_for_each_document_and_selection() {
|
||||
selected_roots(&s).unwrap();
|
||||
assert_eq!(roots_found() - before, 2, "an edit finds the roots once again");
|
||||
}
|
||||
|
||||
/// Clear removes a compound path whose members are cleared paths and a compound path the clear
|
||||
/// empties, whichever order the ids come in, and the tracing guard's set counts both as deleted.
|
||||
#[test]
|
||||
fn clear_removes_a_compound_path_emptied_through_an_emptied_inner_one() {
|
||||
for reversed in [false, true] {
|
||||
let mut s = new_doc();
|
||||
let outer_paths = [(); 2].map(|()| rect(&mut s));
|
||||
let (outer, outer_members) = compound(&mut s, &outer_paths);
|
||||
let inner_paths = [(); 2].map(|()| rect(&mut s));
|
||||
let (inner, inner_members) = compound(&mut s, &inner_paths);
|
||||
s.edit("Nest", |d, _| {
|
||||
let taken = d.remove_many(&[inner])?;
|
||||
d.insert(Some(outer), 1, (*taken[0]).clone())?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let mut ids: Vec<NodeId> = outer_members.iter().chain(&inner_members).copied().collect();
|
||||
if reversed {
|
||||
ids.reverse();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.parent_of(inner), Some(outer), "the inner compound path is a member of the outer one");
|
||||
let want: Vec<NodeId> = BTreeSet::from([outer, inner]).into_iter().collect();
|
||||
assert_eq!(emptied_compounds(d, &ids), want, "reversed: {reversed}");
|
||||
run(&mut s, "edit.clear", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(inner).is_none(), "the emptied inner compound path goes (reversed: {reversed})");
|
||||
assert!(d.node(outer).is_none(), "the outer compound path it leaves empty goes too (reversed: {reversed})");
|
||||
}
|
||||
}
|
||||
|
||||
/// With a direct-selected anchor of another path in the selection, Clear still removes the outer
|
||||
/// compound path that an emptied inner one leaves empty.
|
||||
#[test]
|
||||
fn clear_with_direct_anchors_removes_a_compound_path_emptied_through_an_emptied_inner_one() {
|
||||
let mut s = new_doc();
|
||||
let outer_paths = [(); 2].map(|()| rect(&mut s));
|
||||
let (outer, outer_members) = compound(&mut s, &outer_paths);
|
||||
let inner_paths = [(); 2].map(|()| rect(&mut s));
|
||||
let (inner, inner_members) = compound(&mut s, &inner_paths);
|
||||
let other = rect(&mut s);
|
||||
s.edit("Nest", |d, _| {
|
||||
let taken = d.remove_many(&[inner])?;
|
||||
d.insert(Some(outer), 1, (*taken[0]).clone())?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let whole: Vec<NodeId> = outer_members.iter().chain(&inner_members).copied().collect();
|
||||
select_direct(&mut s, &whole, &[(other, two_anchors())]);
|
||||
run(&mut s, "edit.clear", json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(inner).is_none(), "the emptied inner compound path goes");
|
||||
assert!(d.node(outer).is_none(), "the outer compound path it leaves empty goes too");
|
||||
assert!(d.node(other).is_some(), "the path with anchors picked keeps its other sides");
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
//! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PageMaker).
|
||||
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
|
||||
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
|
||||
//! - `metafile`: EMF and WMF export, open and place; PICT open and place.
|
||||
//! - `metafile`: EMF and WMF export, open and place; PICT and CGM open and place.
|
||||
//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with
|
||||
//! 32-bit coordinates, open and place.
|
||||
//! - `cmx`: `.cmx` export (a page for each chosen artboard, a layer for each layer with art on it).
|
||||
@@ -246,6 +246,9 @@ mod tests_svgimport;
|
||||
#[cfg(test)]
|
||||
mod tests_eps;
|
||||
|
||||
// The CGM reader waits on craft-libs#5410 (the `cgm` feature).
|
||||
#[cfg(all(test, feature = "cgm"))]
|
||||
mod tests_cgm;
|
||||
#[cfg(test)]
|
||||
mod tests_dwgimport;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -283,20 +283,6 @@ pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB";
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
thread_local! {
|
||||
/// The paths [`read_file`] has read on this thread, in order.
|
||||
pub(crate) static FILES_READ: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn regular_write_target(path: &str) -> Result<()> {
|
||||
if std::fs::metadata(path).is_ok_and(|m| !m.is_file()) {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static READ_LIMIT: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
@@ -314,6 +300,12 @@ pub(crate) fn with_read_limit<T>(max: usize, f: impl FnOnce() -> T) -> T {
|
||||
f()
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
thread_local! {
|
||||
/// The paths [`read_file`] has read on this thread, in order.
|
||||
pub(crate) static FILES_READ: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
|
||||
@@ -76,6 +76,16 @@ pub(super) fn import(bytes: &[u8], o: &ImportOptions) -> Result<(Document, Vec<S
|
||||
Ok((r.document, r.warnings))
|
||||
}
|
||||
|
||||
/// A note for each linked image of a DXF or DWG drawing whose file is missing (the `missing` rows
|
||||
/// of [`crate::cmd::links::resolve`]): it shows a placeholder.
|
||||
pub(crate) fn missing_image_notes(missing: &[Value]) -> Vec<String> {
|
||||
missing
|
||||
.iter()
|
||||
.filter_map(|row| row["name"].as_str())
|
||||
.map(|name| format!("linked image '{name}' wasn't found: a placeholder keeps its place until it is relinked"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
const INFO: &str = "document.dxfInfo";
|
||||
|
||||
fn dxf_info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -135,6 +135,27 @@ pub(super) fn add_note(notes: &mut Vec<Note>, note: Note) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `\` separates folders in a path: on Windows and on the web, where paths may come from
|
||||
/// Windows. On other platforms `\` is a character of a file name.
|
||||
const BACKSLASH_SEPARATES: bool = cfg!(any(windows, target_arch = "wasm32"));
|
||||
|
||||
/// The length of `path`'s folder part, its last separator included.
|
||||
fn dir_len(path: &str, backslash: bool) -> usize {
|
||||
let at = if backslash { path.rfind(['/', '\\']) } else { path.rfind('/') };
|
||||
at.map_or(0, |i| i + 1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod dir_tests {
|
||||
#[test]
|
||||
fn a_backslash_is_part_of_a_file_name_where_it_does_not_separate_folders() {
|
||||
assert_eq!(super::dir_len("out/a\\b.svg", false), 4, "the file a\\b.svg is in out/");
|
||||
assert_eq!(super::dir_len("a\\b.svg", false), 0);
|
||||
assert_eq!(super::dir_len("out\\a\\b.svg", true), 6);
|
||||
assert_eq!(super::dir_len("b.svg", true), 0);
|
||||
}
|
||||
}
|
||||
|
||||
impl Encoded {
|
||||
pub(super) fn one(bytes: Vec<u8>) -> Self {
|
||||
Self { files: vec![(None, bytes)], ..Self::default() }
|
||||
@@ -180,7 +201,7 @@ impl Encoded {
|
||||
/// under their own names, then the image maps as `{image stem}.html` or `.map`.
|
||||
pub fn named<'a>(&'a self, doc: &Document, path: &str) -> Vec<(String, Cow<'a, [u8]>)> {
|
||||
// Siblings keep the path's own separators (this runs on every platform and on the web).
|
||||
let dir = &path[..path.rfind(['/', '\\']).map_or(0, |i| i + 1)];
|
||||
let dir = &path[..dir_len(path, BACKSLASH_SEPARATES)];
|
||||
let sibling = |name: &str| format!("{dir}{name}");
|
||||
let mut out: Vec<(String, Cow<[u8]>)> = match self.files.as_slice() {
|
||||
[(_, bytes)] => vec![(path.to_string(), Cow::Borrowed(bytes.as_slice()))],
|
||||
|
||||
@@ -577,6 +577,10 @@ pub const FORMATS: &[Format] = &[
|
||||
Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS },
|
||||
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
|
||||
reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false),
|
||||
// Binary Computer Graphics Metafiles, read by `vectorcraft_metafile::import_cgm` into paths,
|
||||
// type and images. Behind the `cgm` feature until craft-libs#5410 merges.
|
||||
#[cfg(feature = "cgm")]
|
||||
reader("cgm", "CGM", &["cgm"], "image/cgm", false),
|
||||
// Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size
|
||||
// composite, the layers combined, or the preview with a note. Exports don't write them.
|
||||
reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true),
|
||||
@@ -640,6 +644,8 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"pct",
|
||||
"pic",
|
||||
"pict",
|
||||
#[cfg(feature = "cgm")]
|
||||
"cgm",
|
||||
"plt",
|
||||
"hpgl",
|
||||
"hgl",
|
||||
@@ -666,7 +672,8 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
/// 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.
|
||||
/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either. CGM files are added here
|
||||
/// when the `cgm` feature is turned on (craft-libs#5410).
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &[
|
||||
"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",
|
||||
@@ -747,6 +754,8 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"pct",
|
||||
"pic",
|
||||
"pict",
|
||||
#[cfg(feature = "cgm")]
|
||||
"cgm",
|
||||
"plt",
|
||||
"hpgl",
|
||||
"hgl",
|
||||
|
||||
@@ -134,6 +134,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
if let Some(kind) = vectorcraft_metafile::sniff(bytes) {
|
||||
return format(kind.id());
|
||||
}
|
||||
if vectorcraft_metafile::is_cgm(bytes) {
|
||||
return format("cgm");
|
||||
}
|
||||
if psdread::is_psd(bytes) {
|
||||
return format(if psdread::is_psb(bytes) { "psb" } else { "psd" });
|
||||
}
|
||||
@@ -581,6 +584,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
let (doc, warnings) = super::metafile::import_pict(bytes)?;
|
||||
(doc, warnings, false)
|
||||
}
|
||||
"cgm" => {
|
||||
let (doc, warnings) = super::metafile::import_cgm(bytes)?;
|
||||
(doc, warnings, false)
|
||||
}
|
||||
"hpgl" => {
|
||||
let i = vectorcraft_cad::hpgl::import(bytes).map_err(err)?;
|
||||
(i.document, i.warnings, false)
|
||||
@@ -920,6 +927,9 @@ impl ReadFile {
|
||||
let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return };
|
||||
let base = crate::cmd::links::LinkBase::file(self.path.as_deref());
|
||||
self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps);
|
||||
if matches!(self.loaded.format.id, "dxf" | "dwg") {
|
||||
self.loaded.warnings.extend(super::dxfimport::missing_image_notes(&self.links.missing));
|
||||
}
|
||||
for note in Session::refresh_text_bounds(&mut self.loaded.doc) {
|
||||
if !self.loaded.warnings.contains(¬e) {
|
||||
self.loaded.warnings.push(note);
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! `document.export {format: emf|wmf}` and Export As (one picture of an artboard, or one per
|
||||
//! artboard with Use Artboards; raster effects as images, rendered at the document's raster
|
||||
//! effects resolution), `document.open` and File → Place (one artboard, the picture's frame).
|
||||
//! QuickDraw pictures (PICT) open and place the same way; they are never written.
|
||||
//! QuickDraw pictures (PICT) and binary Computer Graphics Metafiles (CGM) open and place the same
|
||||
//! way; they are never written.
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::Document;
|
||||
@@ -78,3 +79,9 @@ pub(super) fn import_pict(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
let p = vectorcraft_metafile::import_pict(bytes).map_err(super::err)?;
|
||||
Ok((p.document, p.warnings))
|
||||
}
|
||||
|
||||
/// A binary CGM's first picture as a document, and the import's warnings.
|
||||
pub(super) fn import_cgm(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
let p = vectorcraft_metafile::import_cgm(bytes).map_err(super::err)?;
|
||||
Ok((p.document, p.warnings))
|
||||
}
|
||||
|
||||
@@ -1086,17 +1086,15 @@ impl SaveJob {
|
||||
return Ok(stopped);
|
||||
}
|
||||
// Every path is checked against the file access in force, and as a write target, before
|
||||
// the first file is written. A refused file is not handed to `write`, so a writer that does
|
||||
// not check the file access writes none of the files; the error is the file access's own
|
||||
// refusal, as the writers that check it give.
|
||||
// the first file is written. A refused file, or a folder at a file's path, is not handed to
|
||||
// `write`, so a writer that does not check the file access writes none of the files; the
|
||||
// error is the file access's own refusal, as the writers that check it give.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if files.len() > 1 {
|
||||
let named = |e, p: &str| if self.redact_paths { super::access::naming_in_error(e, p) } else { e };
|
||||
for (p, _) in &files {
|
||||
super::may_write(p).map_err(|e| named(e, p))?;
|
||||
}
|
||||
for (p, _) in &files {
|
||||
super::access::regular_write_target(p).map_err(|e| named(e, p))?;
|
||||
if let Some(refused) = files.iter().find_map(|(p, _)| {
|
||||
super::access::may_write_file(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e })
|
||||
}) {
|
||||
return Err(refused);
|
||||
}
|
||||
super::export_names::distinct_write_targets(files.iter().map(|(p, _)| p.as_str()))?;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Binary CGM files through the commands: `document.open` by extension or by content, File › Place
|
||||
//! as one group clipped to the picture's frame, the dialogs' filters and the format list, and
|
||||
//! files that aren't binary CGM, or a CGM export, refused with a message.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::NodeKind;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn b64(bytes: &[u8]) -> String {
|
||||
vectorcraft_format::base64_encode(bytes)
|
||||
}
|
||||
|
||||
/// One element, padded to an even length.
|
||||
fn el(class: u16, id: u16, data: &[u8]) -> Vec<u8> {
|
||||
let mut b = ((class << 12) | (id << 5) | data.len() as u16).to_be_bytes().to_vec();
|
||||
b.extend(data);
|
||||
if data.len() % 2 == 1 {
|
||||
b.push(0);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn words(v: &[i16]) -> Vec<u8> {
|
||||
v.iter().flat_map(|x| x.to_be_bytes()).collect()
|
||||
}
|
||||
|
||||
/// A binary CGM whose picture is 1000 × 500 units at 0.2 mm a unit (200 × 100 mm): a solid
|
||||
/// rectangle and a line.
|
||||
fn picture() -> Vec<u8> {
|
||||
let mut b = el(0, 1, b"\x04logo");
|
||||
b.extend(el(1, 1, &words(&[1])));
|
||||
b.extend(el(0, 3, b"\x01p"));
|
||||
b.extend(el(2, 1, &[words(&[1]), 0.2f32.to_be_bytes().to_vec()].concat()));
|
||||
b.extend(el(2, 6, &words(&[0, 0, 1000, 500])));
|
||||
b.extend(el(0, 4, &[]));
|
||||
b.extend(el(5, 22, &words(&[1])));
|
||||
b.extend(el(4, 11, &words(&[100, 100, 400, 300])));
|
||||
b.extend(el(4, 1, &words(&[0, 450, 1000, 450])));
|
||||
b.extend(el(0, 5, &[]));
|
||||
b.extend(el(0, 2, &[]));
|
||||
b
|
||||
}
|
||||
|
||||
const MM: f64 = 72.0 / 25.4;
|
||||
|
||||
#[test]
|
||||
fn document_open_reads_a_picture() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"name": "part.cgm", "dataBase64": b64(&picture())})).unwrap();
|
||||
assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("cgm"), Some("part.cgm")), "{r}");
|
||||
assert_eq!(r["warnings"], json!([]));
|
||||
let st = s.doc().unwrap();
|
||||
let size = st.doc.artboards[0].rect.size();
|
||||
assert!((size.width - 200.0 * MM).abs() < 1e-3 && (size.height - 100.0 * MM).abs() < 1e-3, "{size:?}");
|
||||
let mut paths = vec![];
|
||||
st.doc.walk(|n| {
|
||||
if let NodeKind::Path { .. } = n.kind {
|
||||
paths.push(n.clone());
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 2);
|
||||
let b = paths[0].geometric_bounds().unwrap();
|
||||
assert!((b.x0 - 20.0 * MM).abs() < 1e-3 && (b.width() - 60.0 * MM).abs() < 1e-3, "{b:?}");
|
||||
assert!(st.path.is_none(), "opened as artwork: Save asks for a name");
|
||||
|
||||
// A CGM opens by its content under a name no format reads.
|
||||
for name in ["part.CGM", "part.bin", "part"] {
|
||||
let r = Session::new().execute("document.open", &json!({"name": name, "dataBase64": b64(&picture())})).unwrap();
|
||||
assert_eq!(r["format"].as_str(), Some("cgm"), "{name}: {r}");
|
||||
}
|
||||
assert_eq!(detect("part.dat", &picture()).map(|f| f.id), Some("cgm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_place_places_a_picture_as_one_clipped_group() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let p = json!({"name": "part.cgm", "dataBase64": b64(&picture()), "at": [400, 400]});
|
||||
let info = s.execute("file.place.info", &p).unwrap();
|
||||
assert_eq!(info["format"], "cgm", "{info}");
|
||||
assert!((info["width"].as_f64().unwrap() - 200.0 * MM).abs() < 1e-3, "{info}");
|
||||
let r = s.execute("file.place", &p).unwrap();
|
||||
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("cgm"), Some(1)), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let group = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
|
||||
assert_eq!(group.name.as_deref(), Some("part.cgm"));
|
||||
let NodeKind::Group { clip: true, .. } = &group.kind else { panic!("a clipping group, got {:?}", group.kind) };
|
||||
let b = group.geometric_bounds().unwrap();
|
||||
assert!((b.width() - 200.0 * MM).abs() < 1e-3 && (b.height() - 100.0 * MM).abs() < 1e-3, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_are_not_cgm_are_refused() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let e = s.execute("document.open", &json!({"name": "old.cgm", "dataBase64": b64(&[0; 64])})).expect_err("refused");
|
||||
assert!(e.to_string().contains("not a CGM file"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), (100.0, 50.0).into());
|
||||
assert!(s.execute("file.place", &json!({"name": "old.cgm", "dataBase64": b64(&[0; 64])})).is_err());
|
||||
let e = s.execute("document.open", &json!({"name": "text.cgm", "dataBase64": b64(b"BEGMF 'x';")})).expect_err("refused");
|
||||
assert!(e.to_string().contains("only binary CGM files"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": "cgm"})).expect_err("refused").to_string();
|
||||
assert!(e.contains("CGM files can be opened but not written"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dialogs_and_the_format_list_name_cgm() {
|
||||
assert!(OPEN_EXTS.contains(&"cgm") && PLACE_EXTS.contains(&"cgm") && UNASSOCIATED_EXTS.contains(&"cgm"));
|
||||
assert_eq!(format_for_name("a.cgm").map(|f| f.id), Some("cgm"));
|
||||
let filter = ("CGM", &["cgm"][..]);
|
||||
assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter));
|
||||
let r = Session::new().execute("document.formats", &json!({})).unwrap();
|
||||
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "cgm").unwrap().clone();
|
||||
assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)), "{f}");
|
||||
assert_eq!(f["mime"], "image/cgm");
|
||||
assert!(writable_format(None, Some("x/part.cgm")).is_err());
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! DXF through the commands: `document.open` with the DXF options, `document.dxfInfo`,
|
||||
//! File → Place of a drawing (fitted, centred or at its origin), the format table, binary files,
|
||||
//! and a drawing `document.export` wrote opened again.
|
||||
//! a drawing `document.export` wrote opened again, and the image files a drawing links to.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
@@ -268,3 +268,102 @@ fn a_drawing_export_writes_opens_again() {
|
||||
let union = all.iter().copied().reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!((union.width() - 350.0).abs() < 2.0 && (union.y1 - h + 200.0).abs() < 2.0, "{union:?} on {h}");
|
||||
}
|
||||
|
||||
/// A folder of a drawing linking `img\photo.png`, a 30 × 20 pixel PNG beside it, and `gone.png`,
|
||||
/// which isn't there (removed when dropped).
|
||||
struct Linked(std::path::PathBuf);
|
||||
|
||||
impl Linked {
|
||||
fn new(tag: &str) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-dxfimage-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("img")).unwrap();
|
||||
let img = craft_image_codecs::Image::from_raw(
|
||||
30,
|
||||
20,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[230u8, 20, 20, 255].repeat(600),
|
||||
)
|
||||
.unwrap();
|
||||
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
|
||||
std::fs::write(dir.join("img").join("photo.png"), png).unwrap();
|
||||
let image = |def: &'static str, x: &'static str| {
|
||||
vec![(0, "IMAGE"), (8, "0"), (10, x), (20, "0"), (11, "1"), (21, "0"), (12, "0"), (22, "1"), (13, "30"), (23, "20"), (340, def)]
|
||||
};
|
||||
let mut pairs: Vec<(i32, &str)> = vec![(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, "AC1015"), (0, "ENDSEC")];
|
||||
pairs.extend([(0, "SECTION"), (2, "ENTITIES")]);
|
||||
pairs.extend(image("1F", "0"));
|
||||
pairs.extend(image("2A", "100"));
|
||||
pairs.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS")]);
|
||||
pairs.extend([(0, "IMAGEDEF"), (5, "1F"), (1, r"img\photo.png"), (10, "30"), (20, "20")]);
|
||||
pairs.extend([(0, "IMAGEDEF"), (5, "2A"), (1, "gone.png"), (10, "30"), (20, "20")]);
|
||||
pairs.extend([(0, "ENDSEC"), (0, "EOF")]);
|
||||
let text: String = pairs.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect();
|
||||
std::fs::write(dir.join("plan.dxf"), text).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
|
||||
fn drawing(&self) -> String {
|
||||
self.0.join("plan.dxf").to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Linked {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The images of the active document: each one's link's file name, size, and whether its pixels
|
||||
/// are its file's (not the placeholder).
|
||||
fn images(s: &Session) -> Vec<(String, (u32, u32), bool)> {
|
||||
let st = s.doc().unwrap();
|
||||
let mut out = vec![];
|
||||
st.doc.visit_images(|_, im| {
|
||||
let read = st.doc.images.get(&im.key).is_some_and(|b| !b.is_proxy());
|
||||
out.push((im.link.as_ref().map(|l| l.name().to_string()).unwrap_or_default(), (im.width, im.height), read));
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_drawing_reads_its_images_from_its_folder_and_warns_of_missing_ones() {
|
||||
let dir = Linked::new("open");
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"path": dir.drawing()})).unwrap();
|
||||
assert_eq!(images(&s), [("photo.png".to_string(), (30, 20), true), ("gone.png".to_string(), (30, 20), false)]);
|
||||
let missing = r["missingLinks"].as_array().unwrap();
|
||||
assert_eq!(missing.iter().map(|m| m["name"].as_str()).collect::<Vec<_>>(), [Some("gone.png")], "{r}");
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert!(warnings.iter().any(|w| w.contains("'gone.png' wasn't found")), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("photo.png")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_a_drawing_reads_its_images_from_its_folder_and_warns_of_missing_ones() {
|
||||
let dir = Linked::new("place");
|
||||
let mut s = page();
|
||||
let r = s.execute("file.place", &json!({"path": dir.drawing(), "dxf": {"unit": "pt", "scale": 1}})).unwrap();
|
||||
assert_eq!(images(&s), [("photo.png".to_string(), (30, 20), true), ("gone.png".to_string(), (30, 20), false)]);
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert!(warnings.iter().any(|w| w.contains("'gone.png' wasn't found")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_a_drawing_keeps_missing_links_anchored_to_its_folder() {
|
||||
let source = Linked::new("place-missing-source");
|
||||
let destination = Linked::new("place-missing-destination");
|
||||
let mut s = page();
|
||||
s.doc_mut().unwrap().path = Some(destination.0.join("art.vectorcraft").to_string_lossy().into_owned());
|
||||
s.execute("file.place", &json!({"path": source.drawing(), "dxf": {"unit": "pt", "scale": 1}})).unwrap();
|
||||
let mut missing = vec![];
|
||||
s.doc().unwrap().doc.visit_images(|_, im| {
|
||||
if let Some(link) = im.link.as_ref().filter(|link| link.name() == "gone.png") {
|
||||
missing.push(std::path::PathBuf::from(&link.path));
|
||||
}
|
||||
});
|
||||
assert_eq!(missing, [source.0.join("gone.png")]);
|
||||
assert!(missing[0].is_absolute());
|
||||
assert!(!missing[0].starts_with(&destination.0));
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Layer Options…",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step, and none when every row already has every option given",
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|true (50)|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step, and none when every row already has every option given",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Artboard Options…",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on. Supported artboard exports and printing include it by default. This includes raster exports with `selectedOnly: true` when the output area is an artboard. Set `includeArtboardFill: false` on the export or print command to omit it. Exports cropped to selection bounds, artwork bounds, or an explicit raster region leave it out, as do formats that do not support artboard fills) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes",
|
||||
"{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on. Supported artboard exports and printing include it by default. This includes raster exports with `selectedOnly: true` when the output area is an artboard. Set `includeArtboardFill: false` on the export or print command to omit it. Exports cropped to selection bounds, artwork bounds, or an explicit raster region leave it out, as do formats that do not support artboard fills) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard, and the artboard's own screen print marks group wherever it lies, while another artboard's group lying on it stays with its own), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes",
|
||||
has_doc,
|
||||
artboard_set
|
||||
),
|
||||
@@ -1273,6 +1273,7 @@ pub(crate) fn remove_artboards(d: &mut Document, sel: &mut vectorcraft_doc::Sele
|
||||
for &id in &gone {
|
||||
d.retire_artboard_id(id);
|
||||
}
|
||||
super::addons::release_screen_marks(d, &gone);
|
||||
d.retain_guides(sel, |g| !g.artboard.is_some_and(|a| gone.contains(&a)));
|
||||
count_artboard_pass();
|
||||
Ok(())
|
||||
@@ -1417,7 +1418,6 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let delta = now.origin() - was.origin();
|
||||
let moving = !resized && bool_or(p, "moveArt", false) && delta != vectorcraft_geom::Vec2::ZERO;
|
||||
let transform = fit.or_else(|| moving.then(|| Affine::translate(delta)));
|
||||
let art = if transform.is_some() { d.art_moving_with(index, all).into_iter().filter(|id| taken.insert(*id)).collect() } else { vec![] };
|
||||
edits.push(ArtboardEdit {
|
||||
index,
|
||||
now,
|
||||
@@ -1433,9 +1433,29 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
resized,
|
||||
fit,
|
||||
transform,
|
||||
art,
|
||||
art: vec![],
|
||||
});
|
||||
}
|
||||
// The artboards that move take their own screen print marks groups wherever they lie, and not
|
||||
// another artboard's lying on them, as Move Artboard does. An artboard that scales in the same
|
||||
// call leaves a moving artboard's marks lying on it to their own artboard.
|
||||
// One pass for all of them, in the order listed.
|
||||
let movers: Vec<usize> = edits.iter().filter(|e| e.transform.is_some() && e.fit.is_none()).map(|e| e.index).collect();
|
||||
let mut found = super::panelcmds::artboards_art(s, &movers, true, all, true)?.into_iter();
|
||||
let moved: Vec<Option<Vec<NodeId>>> =
|
||||
edits.iter().map(|e| (e.transform.is_some() && e.fit.is_none()).then(|| found.next().map(|(_, a)| a).unwrap_or_default())).collect();
|
||||
// Every group that belongs to a moving artboard, taken by it or left where it is; a group whose
|
||||
// artboard was deleted is ordinary art.
|
||||
let boards: HashSet<u32> = movers.iter().filter_map(|i| d.artboards.get(*i).map(|a| a.id)).collect();
|
||||
let reserved: HashSet<NodeId> = super::addons::screen_marks_owners(d).into_iter().filter(|(_, o)| boards.contains(o)).map(|(id, _)| id).collect();
|
||||
for (e, own) in edits.iter_mut().zip(moved) {
|
||||
let art = match own {
|
||||
Some(art) => art,
|
||||
None if e.fit.is_some() => d.art_moving_with(e.index, all).into_iter().filter(|id| !reserved.contains(id)).collect(),
|
||||
None => vec![],
|
||||
};
|
||||
e.art = art.into_iter().filter(|id| taken.insert(*id)).collect();
|
||||
}
|
||||
// Nothing to change: no undo step.
|
||||
if !edits.iter().any(|e| d.artboards.get(e.index).is_none_or(|a| e.changes(a))) {
|
||||
return if scale_art { Ok(json!({ "scaled": [] })) } else { ok() };
|
||||
|
||||
@@ -2050,6 +2050,36 @@ fn set_found_paths(d: &mut Document, base: LinkBase) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Sets each relative link path of `d`, a document read from `base`, whose file is not found to
|
||||
/// that path under `base`'s folder, so the link still looks for its file there once the art is
|
||||
/// placed into a document in another folder.
|
||||
pub(crate) fn anchor_missing_relative(d: &mut Document, base: LinkBase) {
|
||||
if base.doc.is_none() {
|
||||
return;
|
||||
}
|
||||
editing_brush_art(d, |d| {
|
||||
let mut anchored: BTreeMap<String, String> = BTreeMap::new();
|
||||
let mut look = |l: &LinkInfo| {
|
||||
if Path::new(&l.path).is_relative()
|
||||
&& !anchored.contains_key(&l.path)
|
||||
&& locate(l, base).is_none()
|
||||
&& let Ok(path) = fileio::document_path(&l.path, base.doc)
|
||||
{
|
||||
anchored.insert(l.path.clone(), path);
|
||||
}
|
||||
};
|
||||
d.visit_images(|_, im| im.link.iter().for_each(&mut look));
|
||||
d.visit_placed(|_, p| look(&p.link));
|
||||
if !anchored.is_empty() {
|
||||
d.update_links(|l| {
|
||||
if let Some(path) = anchored.get(&l.path) {
|
||||
l.path = path.clone();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// `d`, a document saved at `doc_path`, as a reply to the caller asking now may show it: without
|
||||
/// read roots in force, `d` itself; with them, a copy in which each link [`path_shown`] does not
|
||||
/// allow names its file alone, without its relative path or the size and date kept of its file,
|
||||
|
||||
@@ -901,7 +901,7 @@ fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result<DocSettings> {
|
||||
|
||||
impl Session {
|
||||
/// New Document's starting settings: Letter in Preferences ▸ Units ▸ General.
|
||||
fn default_settings(&self) -> DocSettings {
|
||||
pub(crate) fn default_settings(&self) -> DocSettings {
|
||||
DocSettings { units: self.default_units(), ..DocSettings::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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, 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}",
|
||||
"{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). With art, screen print marks go with their recorded owner artboard even outside its bounds, subject to 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")?;
|
||||
@@ -306,16 +306,74 @@ pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, all: bool, moving:
|
||||
})
|
||||
}
|
||||
|
||||
/// `arts` (artboard indices with their art) with each artboard's screen print marks group in its
|
||||
/// own artboard's entry: another artboard's group lying on one of them goes with its own artboard
|
||||
/// when that one is among `arts`, and is left out when it is not. Only the groups on the marks
|
||||
/// layer count; a group whose artboard was deleted stays where it is.
|
||||
/// `held(i, id)` says group `id` stays put for artboard `i`.
|
||||
pub(crate) fn marks_with_owners(
|
||||
d: &vectorcraft_doc::Document,
|
||||
arts: Vec<(usize, Vec<NodeId>)>,
|
||||
held: impl Fn(usize, NodeId) -> bool,
|
||||
) -> Vec<(usize, Vec<NodeId>)> {
|
||||
let owners = super::addons::screen_marks_owners(d);
|
||||
if owners.is_empty() {
|
||||
return arts;
|
||||
}
|
||||
let board = |i: usize| d.artboards.get(i).map(|a| a.id);
|
||||
let owner = |id: NodeId| owners.get(&id).copied().filter(|o| d.artboards.iter().any(|a| a.id == *o));
|
||||
let mut moved: Vec<(u32, NodeId)> = vec![];
|
||||
let mut arts: Vec<(usize, Vec<NodeId>)> = arts
|
||||
.into_iter()
|
||||
.map(|(i, art)| {
|
||||
let art = art
|
||||
.into_iter()
|
||||
.filter(|id| match owner(*id) {
|
||||
Some(o) if Some(o) != board(i) => {
|
||||
moved.push((o, *id));
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
})
|
||||
.collect();
|
||||
(i, art)
|
||||
})
|
||||
.collect();
|
||||
for (o, id) in moved {
|
||||
if let Some((i, art)) = arts.iter_mut().find(|(i, _)| board(*i) == Some(o))
|
||||
&& !held(*i, id)
|
||||
{
|
||||
art.push(id);
|
||||
}
|
||||
}
|
||||
arts
|
||||
}
|
||||
|
||||
/// Each of `indices` with the art that goes with it when `art` ([`artboard_art`]), an object
|
||||
/// counted once, with the first of them it is on (artboards can overlap).
|
||||
/// counted once, with the first of them it is on (artboards can overlap). With `art`, each
|
||||
/// artboard takes its own eligible screen print marks group, wherever the group lies.
|
||||
pub(crate) fn artboards_art(s: &Session, indices: &[usize], art: bool, all: bool, moving: bool) -> Result<Vec<(usize, Vec<NodeId>)>> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut arts = vec![];
|
||||
for &i in indices {
|
||||
let art = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
let art: Vec<NodeId> = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
arts.push((i, art));
|
||||
}
|
||||
Ok(arts)
|
||||
let d = &s.doc()?.doc;
|
||||
// A move or a cut leaves a group lying on an artboard locked other than its own, as it leaves
|
||||
// other art there, unless locked and hidden art goes too.
|
||||
let held = |i: usize, id: NodeId| moving && !all && d.node(id).is_some_and(|n| d.locked_artboards_except(i).holds(n));
|
||||
if art {
|
||||
for (id, o) in super::addons::screen_marks_copied(d, all) {
|
||||
if let Some((i, own)) = arts.iter_mut().find(|(i, _)| d.artboards.get(*i).is_some_and(|a| a.id == o))
|
||||
&& !held(*i, id)
|
||||
&& seen.insert(id)
|
||||
{
|
||||
own.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(marks_with_owners(d, arts, held))
|
||||
}
|
||||
|
||||
/// How far a copy of `rect` moves to sit right of the last artboard (Duplicate Artboards, Paste).
|
||||
@@ -399,7 +457,12 @@ pub(crate) fn copy_artboard(d: &mut vectorcraft_doc::Document, i: usize, dv: Vec
|
||||
if let Some(id) = d.artboards.get(index).map(|a| a.id) {
|
||||
d.copy_artboard_guides(src.id, id, dv);
|
||||
}
|
||||
let to = d.artboards.get(index).map(|a| a.id);
|
||||
let copies = super::edit::copy_above(d, art, |_, _, c| {
|
||||
// A copy of the artboard's screen print marks belongs to the copy.
|
||||
if let Some(to) = to {
|
||||
let _ = super::addons::retag_screen_marks(c, src.id, to);
|
||||
}
|
||||
c.transform(Affine::translate(dv), sc);
|
||||
super::object::keep_pixel_aligned(c, sc);
|
||||
})?;
|
||||
|
||||
@@ -2212,9 +2212,13 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo
|
||||
}
|
||||
}
|
||||
emptied.finish(d)?;
|
||||
for p in compounds {
|
||||
// A compound path left empty by an inner one that went is checked again after it.
|
||||
let mut compounds = compounds;
|
||||
while let Some(p) = compounds.pop_first() {
|
||||
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
|
||||
let up = d.parent_of(p).filter(|u| matches!(d.node(*u).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
d.remove(p)?;
|
||||
compounds.extend(up);
|
||||
}
|
||||
}
|
||||
super::edit::release_empty_clips(d, clipped);
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! [`fileio::psd_slices`]).
|
||||
//! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options
|
||||
//! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`).
|
||||
//! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or
|
||||
//! - An EMF, WMF, PICT or CGM picture becomes one group, clipped to its frame (`crop: "crop"`) or
|
||||
//! bounded by its art (`crop: "bounding"`).
|
||||
//! - An EPS file (or a PostScript .ai) becomes one group, clipped to its bounding box or bounded by
|
||||
//! its art: the document an EPS file of ours carries, else what its PostScript draws, else its
|
||||
@@ -377,7 +377,11 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given: O
|
||||
));
|
||||
}
|
||||
// Linked images show their files, found from its folder.
|
||||
super::links::resolve(&mut l.doc, super::links::LinkBase::file(src.path), false, false);
|
||||
let links = super::links::resolve(&mut l.doc, super::links::LinkBase::file(src.path), false, false);
|
||||
if matches!(format.id, "dxf" | "dwg") {
|
||||
l.warnings.extend(fileio::dxfimport::missing_image_notes(&links.missing));
|
||||
super::links::anchor_missing_relative(&mut l.doc, super::links::LinkBase::file(src.path));
|
||||
}
|
||||
(l.doc, l.warnings)
|
||||
};
|
||||
doc.drop_edit_modes();
|
||||
|
||||
@@ -35,6 +35,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.color.filter",
|
||||
"addon.color.nearestSwatch",
|
||||
"addon.color.randomFill",
|
||||
"addon.color.screenMarks",
|
||||
"addon.color.select",
|
||||
"addon.color.strokeToFill",
|
||||
"addon.color.swatchLegend",
|
||||
|
||||
@@ -80,10 +80,11 @@ fn drop_guides(nodes: &mut Vec<Arc<Node>>) {
|
||||
}
|
||||
|
||||
/// The resolution Print as Bitmap renders `doc` at with `set` (ppi): `advanced.bitmapResolution`,
|
||||
/// or the document's raster effects resolution when that is 0.
|
||||
/// or the document's raster effects resolution when that is 0 (72 ppi when the stored value isn't a
|
||||
/// number).
|
||||
fn bitmap_ppi(doc: &Document, set: &PrintSettings) -> f64 {
|
||||
let asked = set.advanced.bitmap_resolution;
|
||||
if asked > 0.0 { asked } else { doc.raster_effects_ppi }
|
||||
if asked > 0.0 { asked } else { doc.raster_ppi() }
|
||||
}
|
||||
|
||||
/// The pixels per document point Print as Bitmap renders `area` at so that it prints at `ppi` on
|
||||
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [index…], dx, dy, moveArt?: bool, copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard)} move artboards (and the art fully inside them; locked and hidden art, and art also on another locked artboard, only with lockedAndHidden), several in one step (an error when one is locked); `copy` (Alt-drag) leaves them and moves copies, which start unlocked → {index (the first), indices: the artboards moved or the copies, moved: the art moved or the copies}",
|
||||
"{index | indices: [index…], dx, dy, moveArt?: bool, copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard)} move artboards (and the art fully inside them; locked and hidden art, and art also on another locked artboard, only with lockedAndHidden), several in one step (an error when one is locked); `copy` (Alt-drag) leaves them and moves copies, which start unlocked. With moveArt, screen print marks go with their recorded owner artboard even outside its bounds, subject to lockedAndHidden → {index (the first), indices: the artboards moved or the copies, moved: the art moved or the copies}",
|
||||
has_doc,
|
||||
artboard_move
|
||||
),
|
||||
@@ -685,13 +685,8 @@ fn artboard_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !copy {
|
||||
super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?;
|
||||
}
|
||||
// Each artboard's art, an object counted once (artboards can overlap).
|
||||
let mut arts: Vec<(usize, Vec<NodeId>)> = vec![];
|
||||
for &i in &indices {
|
||||
let art = super::panelcmds::artboard_art(s, i, move_art, locked_art, !copy)?;
|
||||
let art = art.into_iter().filter(|id| !arts.iter().any(|(_, a)| a.contains(id))).collect();
|
||||
arts.push((i, art));
|
||||
}
|
||||
// Each artboard takes its art once and its own eligible screen print marks group.
|
||||
let arts = super::panelcmds::artboards_art(s, &indices, move_art, locked_art, !copy)?;
|
||||
let ids: Vec<NodeId> = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect();
|
||||
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() };
|
||||
let (index, moved) = s.edit(if copy { "Duplicate Artboard" } else { "Move Artboard" }, |d, _| {
|
||||
|
||||
@@ -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); 40] = [
|
||||
const REPLAY_ONLY: [(&str, &str); 41] = [
|
||||
("edit.copy", "artboard"),
|
||||
("edit.cut", "artboard"),
|
||||
("file.new", "created"),
|
||||
@@ -72,6 +72,7 @@ const REPLAY_ONLY: [(&str, &str); 40] = [
|
||||
("artboard.distributeSpacing", "activeArtboard"),
|
||||
("addon.type.fontSheet", "activeArtboard"),
|
||||
("addon.document.floodFillArtboards", "activeArtboard"),
|
||||
("addon.color.screenMarks", "activeArtboard"),
|
||||
("edit.copy", "selectedArtboards"),
|
||||
("edit.copy", "art"),
|
||||
("edit.cut", "selectedArtboards"),
|
||||
|
||||
@@ -258,8 +258,9 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
|
||||
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
|
||||
// passed over.
|
||||
// A document whose active artboard the script chose uses that choice, not the one the run
|
||||
// started with, nor the Artboard tool's selection from the start of the run.
|
||||
// A document whose active artboard the script chose, or whose artboards the script added or
|
||||
// removed, uses its active artboard by id, not the index the run started with, nor the
|
||||
// Artboard tool's selection from the start of the run.
|
||||
let chosen = h.session.borrow().active().and_then(|st| {
|
||||
h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?;
|
||||
Some((st.uid, super::dom::active_artboard(st)))
|
||||
|
||||
@@ -106,6 +106,7 @@ mod images;
|
||||
pub(super) mod layers;
|
||||
mod matrix;
|
||||
mod paths;
|
||||
mod perspective;
|
||||
pub mod preferences;
|
||||
mod print;
|
||||
mod raster_capture;
|
||||
@@ -274,7 +275,8 @@ pub(super) struct State {
|
||||
layer_lists: RefCell<Vec<layers::LayerList>>,
|
||||
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
|
||||
pub(super) active_artboards: RefCell<Vec<u64>>,
|
||||
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it.
|
||||
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose its active
|
||||
/// artboard, or the script last added or removed one of its artboards.
|
||||
pub(super) chosen_artboards: RefCell<Vec<(u64, u64)>>,
|
||||
/// Each open document's uid and the index of its active artboard when the run started.
|
||||
pub(super) boards_at_start: Vec<(u64, usize)>,
|
||||
@@ -1749,19 +1751,27 @@ fn docs_add_document_no_ui(h: &Host, a: &[Data]) -> Answer {
|
||||
/// left out. The settings stay with the run, which hands the script an object of the
|
||||
/// `DocumentPreset` class.
|
||||
fn new_preset(h: &Host) -> Answer {
|
||||
let item = |k: &str, v: Data| (k.to_string(), v);
|
||||
add_preset(
|
||||
h,
|
||||
vec![
|
||||
item("artboardLayout", text("DocumentArtboardLayout.GridByRow")),
|
||||
item("artboardRowsOrCols", num(1.0)),
|
||||
item("artboardSpacing", num(20.0)),
|
||||
item("height", num(792.0)),
|
||||
item("numArtboards", num(1.0)),
|
||||
item("width", num(612.0)),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// A new `DocumentPreset` of the run with the settings `fields`, which `new DocumentPreset()` and
|
||||
/// `app.getPresetSettings` both make.
|
||||
fn add_preset(h: &Host, fields: Vec<(String, Data)>) -> Answer {
|
||||
let mut presets = h.dom.presets.borrow_mut();
|
||||
if presets.len() >= MAX_PRESETS {
|
||||
return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets")));
|
||||
}
|
||||
let item = |k: &str, v: Data| (k.to_string(), v);
|
||||
let fields = vec![
|
||||
item("artboardLayout", text("DocumentArtboardLayout.GridByRow")),
|
||||
item("artboardRowsOrCols", num(1.0)),
|
||||
item("artboardSpacing", num(20.0)),
|
||||
item("height", num(792.0)),
|
||||
item("numArtboards", num(1.0)),
|
||||
item("width", num(612.0)),
|
||||
];
|
||||
hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| held_bytes(v)).sum())?;
|
||||
presets.push(fields);
|
||||
Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)]))
|
||||
@@ -3487,6 +3497,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}"))))));
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
for (name, members) in perspective::enums() {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
|
||||
realm.define_host_object("BlendModes", blend_modes)?;
|
||||
variables::define_enums(realm)?;
|
||||
@@ -3523,6 +3537,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(perspective::application_members(l));
|
||||
application.extend(preferences::app_members());
|
||||
application.extend(matrix::app_members(l));
|
||||
application.extend(clipboard::app_members(l));
|
||||
@@ -3609,6 +3624,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(layers::document_members(l));
|
||||
document.extend(perspective::document_members(l));
|
||||
document.extend(variables::document_members(l));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(print::document_members(l));
|
||||
|
||||
@@ -1401,7 +1401,10 @@ fn board_set_safe_areas(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn board_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let (b, i) = this_board(h, a)?;
|
||||
let active = active_board_id(h, b.doc);
|
||||
on_doc(h, b.doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?;
|
||||
keep_active_board(h, b.doc.uid, active);
|
||||
follow_active_board(h, b.doc.uid);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -1513,6 +1516,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer {
|
||||
if len >= max {
|
||||
return Err(HostError::Range(format!("a document has at most {max} artboards")));
|
||||
}
|
||||
let active = active_board_id(h, doc);
|
||||
let id = super::atomically(h, |h| {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
let (_, made) = command_value(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?;
|
||||
@@ -1529,6 +1533,8 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer {
|
||||
st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into()))
|
||||
})
|
||||
})?;
|
||||
keep_active_board(h, doc.uid, active);
|
||||
follow_active_board(h, doc.uid);
|
||||
Ok(board_ref(h, doc.uid, id))
|
||||
}
|
||||
|
||||
@@ -1550,10 +1556,58 @@ fn boards_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = boards_doc(h, a)?;
|
||||
let len = with_doc(h, doc, |_, st| st.doc.artboards.len());
|
||||
let i = board_index_arg(arg(a, 1), len, "index")?;
|
||||
let active = active_board_id(h, doc);
|
||||
on_doc(h, doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?;
|
||||
keep_active_board(h, doc.uid, active);
|
||||
follow_active_board(h, doc.uid);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The id and index of the artboard that is active in `doc` now, chosen or only the fallback.
|
||||
fn active_board_id(h: &Host, doc: Doc) -> Option<(u32, usize)> {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let i = active_artboard(st);
|
||||
st.doc.artboards.get(i).map(|ab| (ab.id, i))
|
||||
})
|
||||
}
|
||||
|
||||
/// Keeps artboard `id` active in document `uid` by its id when it is still there, as
|
||||
/// `setActiveArtboardIndex` does, so an artboard added or removed before it moves its index
|
||||
/// instead of making another artboard the active one.
|
||||
/// A stored id of an artboard that is gone is replaced as well. In a document made during the run,
|
||||
/// the index the artboard had before the change is recorded for the run's report, as the first
|
||||
/// `setActiveArtboardIndex` records it.
|
||||
fn keep_active_board(h: &Host, uid: u64, active: Option<(u32, usize)>) {
|
||||
let Some((id, index)) = active else { return };
|
||||
{
|
||||
let mut s = h.session.borrow_mut();
|
||||
let Some(st) = s.document_mut(uid) else { return };
|
||||
if !st.doc.artboards.iter().any(|ab| ab.id == id) {
|
||||
return;
|
||||
}
|
||||
st.active_artboard = Some(id);
|
||||
}
|
||||
if !h.dom.boards_at_start.iter().any(|(u, _)| *u == uid) {
|
||||
let mut made = h.dom.boards_chosen_in_new.borrow_mut();
|
||||
if !made.iter().any(|(u, _)| *u == uid) {
|
||||
made.push((uid, index));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// After the script adds or removes an artboard in document `uid`, the steps `app.doScript` plays
|
||||
/// act on the document's active artboard by id, at the index the run's report gives it, as after
|
||||
/// `setActiveArtboardIndex`, until the document is reverted.
|
||||
fn follow_active_board(h: &Host, uid: u64) {
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
let mut chosen = h.dom.chosen_artboards.borrow_mut();
|
||||
if let Some((_, generation)) = chosen.iter_mut().find(|(u, _)| *u == uid) {
|
||||
*generation = reverts;
|
||||
} else {
|
||||
chosen.push((uid, reverts));
|
||||
}
|
||||
}
|
||||
|
||||
fn boards_active(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = boards_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| active_artboard(st)) as u64)))
|
||||
@@ -1572,15 +1626,7 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer {
|
||||
let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
|
||||
st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id);
|
||||
}
|
||||
{
|
||||
let mut chosen = h.dom.chosen_artboards.borrow_mut();
|
||||
let reverts = with_doc(h, doc, |_, st| st.reverts);
|
||||
if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) {
|
||||
*generation = reverts;
|
||||
} else {
|
||||
chosen.push((doc.uid, reverts));
|
||||
}
|
||||
}
|
||||
follow_active_board(h, doc.uid);
|
||||
// A document made during the run has no index from the start of the run, so the first choice
|
||||
// records one; an artboard inserted before it later still puts it in the report.
|
||||
if !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid) {
|
||||
|
||||
@@ -719,7 +719,8 @@ thread_local! {
|
||||
/// `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,
|
||||
/// image, placed document or visible type that lays out glyphs to clip by.
|
||||
/// image, placed document or visible type that lays out glyphs to clip by, or leave an image first
|
||||
/// in an ordinary group named as a tracing.
|
||||
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| {
|
||||
@@ -798,13 +799,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let mut masks = Vec::new();
|
||||
for n in nodes.into_iter().rev() {
|
||||
let kids = n.children().map_or(&[][..], Vec::as_slice);
|
||||
// Without `keepEmpty`, clear removes compound paths emptied of direct members, but keeps
|
||||
// empty groups. A compound path's own `pathItems.removeAll()` keeps it, empty.
|
||||
if c.is_none()
|
||||
&& matches!(n.kind, NodeKind::Compound { .. })
|
||||
&& !kids.is_empty()
|
||||
&& kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id))
|
||||
{
|
||||
// Without `keepEmpty`, clear removes compound paths whose members all go, emptied inner
|
||||
// compound paths included (`emptied_compounds`), but keeps empty groups. A compound
|
||||
// path's own `pathItems.removeAll()` keeps it, empty.
|
||||
if c.is_none() && matches!(n.kind, NodeKind::Compound { .. }) && !kids.is_empty() && kids.iter().all(|k| going.contains(&k.id)) {
|
||||
going.insert(n.id);
|
||||
}
|
||||
// A clip outline takes in visible paths, the frames of visible images and placed
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
//! The perspective grid of a document and the New Document settings of a startup preset in the
|
||||
//! script object model, as the help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>
|
||||
//! and <https://ai-scripting.docsforadobe.dev/jsobjref/Application/> list them, with the values of
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/>.
|
||||
//!
|
||||
//! `showPerspectiveGrid`, `hidePerspectiveGrid` and `setActivePlane` change view state with
|
||||
//! `perspective.grid.show` and `perspective.plane.set`: no undo step, and a failed run puts them
|
||||
//! back with the document. `selectPerspectivePreset` runs `perspective.grid.preset`, which shows
|
||||
//! the grid and makes one undo step when the grid's geometry changes. As the Document page
|
||||
//! describes, `showPerspectiveGrid` and `setActivePlane` give `true` on success, and
|
||||
//! `hidePerspectiveGrid` gives `true` when it hides a grid and `false` when the grid was already
|
||||
//! hidden.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `selectPerspectivePreset(gridType, presetName)` throws when no built-in or saved preset has
|
||||
//! that name (in any case), and when the preset's grid is not of `gridType`; nothing changes then.
|
||||
//! - A one-point grid takes only the left and the floor plane as its active plane, as the archived
|
||||
//! scripting guide says
|
||||
//! (<https://web.archive.org/web/20170622004549/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/AI_ScriptGd.pdf>).
|
||||
//! `INVALIDGRIDPLANETYPE` makes no plane active.
|
||||
//! - `showPerspectiveGrid` and `setActivePlane` also give `true` when nothing changed.
|
||||
//! - `getPresetSettings(preset)` takes the names `documents.addDocument` takes, and gives a new
|
||||
//! `DocumentPreset` with the settings a new document from that preset starts with, which
|
||||
//! `addDocument` takes back unchanged. Settings it cannot take are left out: units other than
|
||||
//! the six `RulerUnits` values, a PPI other than 72, 150 or 300, the artboard count and layout
|
||||
//! of more than 100 artboards, and the layout of a grid by column that no row count lays out the
|
||||
//! same. Changing the result changes nothing else. Each result counts toward the run's limit
|
||||
//! of `DocumentPreset` objects, as `new DocumentPreset()` does.
|
||||
//! - `startupPresetsList` is an array of the startup preset names, each of which
|
||||
//! `documents.addDocument` and `getPresetSettings` take: `Print` first, then the other New
|
||||
//! Document profiles, then `Basic CMYK` and `Basic RGB`. Each read gives a new
|
||||
//! array; a script that changes that array does not change the list a later read gives.
|
||||
//! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset
|
||||
//! files are not available yet.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostError};
|
||||
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
|
||||
|
||||
use super::{
|
||||
Answer, Described, MAX_TEXT_BYTES, arg, get, later, method, named, num, on_doc, returns, startup_preset, text, this_doc, typed, with_doc,
|
||||
};
|
||||
use crate::script::{Host, Link};
|
||||
|
||||
type Result<T> = std::result::Result<T, HostError>;
|
||||
|
||||
/// The `PerspectiveGridType` values, with the grid kind (`perspective.grid.set`'s `kind`) of each.
|
||||
const GRID_TYPES: &[(&str, Option<u8>)] = &[
|
||||
("OnePointPerspectiveGridType", Some(1)),
|
||||
("TwoPointPerspectiveGridType", Some(2)),
|
||||
("ThreePointPerspectiveGridType", Some(3)),
|
||||
("InvalidPerspectiveGridType", None),
|
||||
];
|
||||
|
||||
/// The `PerspectiveGridPlaneType` values, with the plane of each.
|
||||
const PLANE_TYPES: &[(&str, Plane)] = &[
|
||||
("GRIDLEFTPLANETYPE", Plane::Left),
|
||||
("GRIDRIGHTPLANETYPE", Plane::Right),
|
||||
("GRIDFLOORPLANETYPE", Plane::Ground),
|
||||
("INVALIDGRIDPLANETYPE", Plane::None),
|
||||
];
|
||||
|
||||
/// The enumerations this module adds, as `dom::install` defines them.
|
||||
pub(super) fn enums() -> Vec<(&'static str, Vec<&'static str>)> {
|
||||
vec![
|
||||
("PerspectiveGridType", GRID_TYPES.iter().map(|(n, _)| *n).collect()),
|
||||
("PerspectiveGridPlaneType", PLANE_TYPES.iter().map(|(n, _)| *n).collect()),
|
||||
]
|
||||
}
|
||||
|
||||
/// The kind a `PerspectiveGridType` value names (`None`: `InvalidPerspectiveGridType`).
|
||||
fn grid_type(d: &Data) -> Result<Option<u8>> {
|
||||
let found = match d {
|
||||
Data::String(s) => s.strip_prefix("PerspectiveGridType.").and_then(|m| GRID_TYPES.iter().find(|(n, _)| *n == m)),
|
||||
_ => None,
|
||||
};
|
||||
found.map(|(_, k)| *k).ok_or_else(|| HostError::Type("gridType must be a PerspectiveGridType value".into()))
|
||||
}
|
||||
|
||||
/// The plane a `PerspectiveGridPlaneType` value names.
|
||||
fn plane_type(d: &Data) -> Result<Plane> {
|
||||
let found = match d {
|
||||
Data::String(s) => s.strip_prefix("PerspectiveGridPlaneType.").and_then(|m| PLANE_TYPES.iter().find(|(n, _)| *n == m)),
|
||||
_ => None,
|
||||
};
|
||||
found.map(|(_, p)| *p).ok_or_else(|| HostError::Type("gridPlane must be a PerspectiveGridPlaneType value".into()))
|
||||
}
|
||||
|
||||
/// The document `this` names and its perspective grid, without the objects attached to it.
|
||||
fn grid(h: &Host, a: &[Data]) -> Result<(super::Doc, PerspectiveGrid)> {
|
||||
let doc = this_doc(h, a)?;
|
||||
Ok((doc, with_doc(h, doc, |_, st| PerspectiveGrid::current(&st.doc))))
|
||||
}
|
||||
|
||||
/// `showPerspectiveGrid()`: shows the document's grid (its default one when none was defined).
|
||||
fn show_grid(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, g) = grid(h, a)?;
|
||||
if !g.visible {
|
||||
on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.show", &json!({"visible": true})))?;
|
||||
}
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `hidePerspectiveGrid()`: hides the document's grid. → whether a grid was hidden.
|
||||
fn hide_grid(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, g) = grid(h, a)?;
|
||||
if !g.visible {
|
||||
return Ok(Data::Bool(false));
|
||||
}
|
||||
on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.show", &json!({"visible": false})))?;
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `getPerspectiveActivePlane()`: the grid's active plane, shown or hidden.
|
||||
fn active_plane(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, g) = grid(h, a)?;
|
||||
let name = PLANE_TYPES.iter().find(|(_, p)| *p == g.plane).map_or("INVALIDGRIDPLANETYPE", |(n, _)| *n);
|
||||
Ok(text(format!("PerspectiveGridPlaneType.{name}")))
|
||||
}
|
||||
|
||||
/// `setActivePlane(gridPlane)`: makes `gridPlane` the grid's active plane.
|
||||
fn set_active_plane(h: &Host, a: &[Data]) -> Answer {
|
||||
let plane = plane_type(arg(a, 1))?;
|
||||
let (doc, g) = grid(h, a)?;
|
||||
if g.kind == 1 && plane == Plane::Right {
|
||||
return Err(HostError::Range("a one-point grid has no right plane to make active".into()));
|
||||
}
|
||||
if g.plane != plane {
|
||||
on_doc(h, doc.uid, false, |h| super::command(h, "perspective.plane.set", &json!({"plane": plane.id()})))?;
|
||||
}
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `selectPerspectivePreset(gridType, presetName)`: resets the grid to the preset `presetName`,
|
||||
/// which must be a grid of `gridType`.
|
||||
fn select_preset(h: &Host, a: &[Data]) -> Answer {
|
||||
let kind = grid_type(arg(a, 1))?.ok_or_else(|| HostError::Range("InvalidPerspectiveGridType has no presets".into()))?;
|
||||
let Data::String(name) = arg(a, 2) else { return Err(HostError::Type("presetName must be a string".into())) };
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the preset's name is too long".into()));
|
||||
}
|
||||
let doc = this_doc(h, a)?;
|
||||
let preset = h.session.borrow().perspective_preset(name);
|
||||
let preset = preset.ok_or_else(|| HostError::Error(format!("no perspective grid preset called {name}")))?;
|
||||
if preset.kind != kind {
|
||||
return Err(HostError::Error(format!("the preset {} is not a grid of that type", preset.name)));
|
||||
}
|
||||
on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.preset", &json!({"name": preset.name})))?;
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// The `RulerUnits` value of `u`, for the units `documents.addDocument` takes (`None`: other units,
|
||||
/// which a preset given back to `addDocument` keeps by leaving `units` out).
|
||||
fn units(u: crate::doc::Unit) -> Option<&'static str> {
|
||||
use crate::doc::Unit;
|
||||
Some(match u {
|
||||
Unit::Points => "RulerUnits.Points",
|
||||
Unit::Picas => "RulerUnits.Picas",
|
||||
Unit::Inches => "RulerUnits.Inches",
|
||||
Unit::Millimeters => "RulerUnits.Millimeters",
|
||||
Unit::Centimeters => "RulerUnits.Centimeters",
|
||||
Unit::Pixels => "RulerUnits.Pixels",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `artboardRowsOrCols` as `addDocument` reads it: the rows of a grid filled by column and the
|
||||
/// columns of the other layouts. `None`: a grid by column whose artboards no row count places the
|
||||
/// same.
|
||||
fn rows_or_cols(d: &crate::cmd::newdoc::DocSettings) -> Option<usize> {
|
||||
use crate::cmd::newdoc::ArtboardLayout;
|
||||
let n = d.artboards.max(1) as usize;
|
||||
if d.layout != ArtboardLayout::GridByColumn {
|
||||
return Some(d.grid_columns().max(1));
|
||||
}
|
||||
if d.rows > 0 {
|
||||
return Some((d.rows as usize).min(n));
|
||||
}
|
||||
let rows = n.div_ceil(d.grid_columns().max(1));
|
||||
let by_rows = crate::cmd::newdoc::DocSettings { rows: u32::try_from(rows).ok()?, ..d.clone() };
|
||||
(by_rows.boards() == d.boards()).then_some(rows)
|
||||
}
|
||||
|
||||
/// `app.getPresetSettings(preset)`: a new `DocumentPreset` with the settings a document from the
|
||||
/// startup preset `preset` starts with.
|
||||
fn preset_settings(h: &Host, a: &[Data]) -> Answer {
|
||||
use crate::cmd::newdoc::{ArtboardLayout, PreviewMode};
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("getPresetSettings needs a startup preset's name".into())) };
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the startup preset's name is too long".into()));
|
||||
}
|
||||
let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?;
|
||||
// The settings `documents.addDocument` starts from: the first built-in preset of the profile's
|
||||
// category, which a saved preset of the same name does not replace, else New Document's
|
||||
// starting settings.
|
||||
let d = {
|
||||
let s = h.session.borrow();
|
||||
let first = profile.and_then(|n| crate::cmd::newdoc::category(&s, n)?.into_iter().next());
|
||||
first.unwrap_or_else(|| s.default_settings())
|
||||
};
|
||||
let cmyk = mode.map_or(d.color_mode == crate::doc::ColorMode::Cmyk, |m| m == "cmyk");
|
||||
let layout = match (d.layout, d.right_to_left) {
|
||||
(ArtboardLayout::GridByRow, false) => "GridByRow",
|
||||
(ArtboardLayout::GridByColumn, false) => "GridByCol",
|
||||
(ArtboardLayout::Row, false) => "Row",
|
||||
(ArtboardLayout::Column, _) => "Column",
|
||||
(ArtboardLayout::GridByRow, true) => "RLGridByRow",
|
||||
(ArtboardLayout::GridByColumn, true) => "RLGridByCol",
|
||||
(ArtboardLayout::Row, true) => "RLRow",
|
||||
};
|
||||
let preview = match d.preview_mode {
|
||||
PreviewMode::Default => Some("DefaultPreview"),
|
||||
PreviewMode::Pixel => None,
|
||||
PreviewMode::Overprint => Some("OverprintPreview"),
|
||||
};
|
||||
let item = |k: &str, v: Data| (k.to_string(), v);
|
||||
let mut out = vec![
|
||||
item("artboardLayout", text(format!("DocumentArtboardLayout.{layout}"))),
|
||||
item("artboardSpacing", num(d.spacing)),
|
||||
item("colorMode", text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })),
|
||||
item("height", num(d.height)),
|
||||
item("width", num(d.width)),
|
||||
];
|
||||
if let Some(preview) = preview {
|
||||
out.push(item("previewMode", text(format!("DocumentPreviewMode.{preview}"))));
|
||||
}
|
||||
// The artboard count and `artboardRowsOrCols` are left out when `addDocument` cannot take them
|
||||
// back exactly (more than `MAX_ARTBOARDS`, or a grid by column set by its columns that no row
|
||||
// count lays out the same), so `addDocument` with the same preset keeps the preset's own.
|
||||
if f64::from(d.artboards.max(1)) <= super::MAX_ARTBOARDS {
|
||||
out.push(item("numArtboards", num(f64::from(d.artboards.max(1)))));
|
||||
if let Some(n) = rows_or_cols(&d) {
|
||||
out.push(item("artboardRowsOrCols", num(super::float(n as u64))));
|
||||
}
|
||||
}
|
||||
if let Some(u) = units(d.units) {
|
||||
out.push(item("units", text(u)));
|
||||
}
|
||||
let resolutions = [(72.0, "ScreenResolution"), (150.0, "MediumResolution"), (300.0, "HighResolution")];
|
||||
if let Some((_, r)) = resolutions.iter().find(|(ppi, _)| (d.raster_effects_ppi - ppi).abs() < 1e-9) {
|
||||
out.push(item("rasterResolution", text(format!("DocumentRasterResolution.{r}"))));
|
||||
}
|
||||
super::add_preset(h, out)
|
||||
}
|
||||
|
||||
/// The startup presets in the order `app.startupPresetsList` gives them: `Print` first, then the
|
||||
/// other New Document profiles, then the presets that give a document of one color mode.
|
||||
const STARTUP_PRESETS: [&str; 9] = ["Print", "Web", "Mobile", "Film & Video", "Art & Illustration", "Branding", "Social", "Basic CMYK", "Basic RGB"];
|
||||
|
||||
/// `app.startupPresetsList`: the names of the startup presets, as a new array.
|
||||
fn startup_presets(_: &Host, _: &[Data]) -> Answer {
|
||||
Ok(Data::Array(STARTUP_PRESETS.into_iter().map(text).collect()))
|
||||
}
|
||||
|
||||
/// The members this module adds to `Document`'s.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
let mut m = named(vec![
|
||||
("showPerspectiveGrid", method(l, show_grid), returns("boolean", &[])),
|
||||
("hidePerspectiveGrid", method(l, hide_grid), returns("boolean", &[])),
|
||||
("getPerspectiveActivePlane", method(l, active_plane), returns("PerspectiveGridPlaneType", &[])),
|
||||
("setActivePlane", method(l, set_active_plane), returns("boolean", &[("gridPlane", "PerspectiveGridPlaneType")])),
|
||||
("selectPerspectivePreset", method(l, select_preset), returns("boolean", &[("gridType", "PerspectiveGridType"), ("presetName", "string")])),
|
||||
]);
|
||||
m.extend(["exportPerspectiveGridPreset", "importPerspectiveGridPreset"].into_iter().map(|n| later(l, "Document", n)));
|
||||
m
|
||||
}
|
||||
|
||||
/// The members this module adds to `Application`'s.
|
||||
pub(super) fn application_members(l: &Link) -> Vec<Described> {
|
||||
let mut m = named(vec![
|
||||
("getPresetSettings", method(l, preset_settings), returns("DocumentPreset", &[("preset", "string")])),
|
||||
("startupPresetsList", get(l, startup_presets), typed("Array")),
|
||||
]);
|
||||
let missing = ["saveWorkspace", "switchWorkspace", "deleteWorkspace", "resetWorkspace", "loadColorSettings", "showPresets"];
|
||||
m.extend(missing.into_iter().map(|n| later(l, "Application", n)));
|
||||
m
|
||||
}
|
||||
@@ -1033,7 +1033,7 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer {
|
||||
/// each assigned name against the list it must come from, and puts the checked names into the
|
||||
/// job: a print or flattener preset by its name (any case), an RGB or CMYK color profile by its
|
||||
/// name (any case) and a paper by its id or label. An empty name, or one with a path separator or
|
||||
/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name`.
|
||||
/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name` and no profile in the base settings.
|
||||
fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> {
|
||||
let (count, saved_ignore, saved_fit, saved_tiled, mut base_profile) = with_doc(h, doc, |_, st| {
|
||||
let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str);
|
||||
|
||||
@@ -47,10 +47,12 @@ fn owner_of(h: &Host, d: &Data) -> std::result::Result<Owner, HostError> {
|
||||
}
|
||||
|
||||
/// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must
|
||||
/// still be in its document.
|
||||
/// still be in its document. A tracing the run traced again is followed to the object that
|
||||
/// replaced it, which keeps its tags, as its `PluginItem` is.
|
||||
fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result<Item, HostError> {
|
||||
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let id = super::tracing::follow(h, doc.uid, id);
|
||||
let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some()));
|
||||
if !alive {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
@@ -111,7 +113,8 @@ fn doc_of_owner(owner: Owner) -> Doc {
|
||||
}
|
||||
|
||||
fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data {
|
||||
let [high, low] = id_parts(id);
|
||||
// A tracing traced again keeps the id of the first object of its chain, as its `PluginItem` does.
|
||||
let [high, low] = id_parts(super::tracing::origin(h, doc.uid, id));
|
||||
let [tag_high, tag_low] = id_parts(NodeId(tag));
|
||||
host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low])
|
||||
}
|
||||
@@ -119,7 +122,7 @@ fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data {
|
||||
/// `PageItem.tags`.
|
||||
pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = item_of(h, arg(a, 0))?;
|
||||
let [high, low] = id_parts(item.id);
|
||||
let [high, low] = id_parts(super::tracing::origin(h, item.doc.uid, item.id));
|
||||
Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low]))
|
||||
}
|
||||
|
||||
|
||||
@@ -1539,7 +1539,8 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `removeAll()`: deletes every type object the collection lists in one command; a hidden or
|
||||
/// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does.
|
||||
/// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does, and
|
||||
/// so does an image the deletion would leave first in an ordinary group named as a tracing.
|
||||
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, c) = frames_scope(h, a)?;
|
||||
let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| {
|
||||
@@ -1563,7 +1564,7 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
// A clip group named as a tracing, released with an image left first, would become one.
|
||||
// A group named as a tracing, cleared or released with an image left first, would become one.
|
||||
if tracing {
|
||||
return Err(HostError::Error(super::NOT_A_TRACING.into()));
|
||||
}
|
||||
|
||||
@@ -2835,7 +2835,12 @@ impl Session {
|
||||
changed_names.push(st.title());
|
||||
continue;
|
||||
};
|
||||
let changed = !st.same_content(&b.doc);
|
||||
// The perspective grid's view state changes without an undo step, as it does outside a
|
||||
// run, when no command in the run recorded an undo step of its own on the working copy.
|
||||
// The working copy starts with no undo steps (`World::working`), so any step it holds now
|
||||
// was recorded in the run.
|
||||
let recorded = !st.history.undo.is_empty();
|
||||
let changed = !st.same_content(&b.doc) && (recorded || !cmd::distortcmds::only_grid_view_changed(&st.doc, &b.doc));
|
||||
st.history = std::mem::take(&mut b.history);
|
||||
st.recovery.clone_from(&b.recovery);
|
||||
if changed {
|
||||
|
||||
@@ -188,6 +188,7 @@ mod script_dom;
|
||||
mod script_dom_defaults;
|
||||
mod script_dom_images;
|
||||
mod script_dom_paths;
|
||||
mod script_dom_perspective;
|
||||
mod script_dom_prefs;
|
||||
mod script_dom_resources;
|
||||
mod script_dom_tracing;
|
||||
|
||||
@@ -152,6 +152,31 @@ fn print_as_bitmap_prints_all_of_a_long_artboard() {
|
||||
assert!(b.x0 <= 0.0 && b.x1 >= 9000.0, "the image covers the artboard: {b:?}");
|
||||
}
|
||||
|
||||
/// A raster effects resolution that isn't a number prints at the resolution the document reads it
|
||||
/// as (72 ppi), not as an empty page.
|
||||
#[test]
|
||||
fn print_as_bitmap_of_a_resolution_that_is_not_a_number_prints_at_72_ppi() {
|
||||
let (s, _) = session();
|
||||
let saved = s.prefs.flattener_presets.clone();
|
||||
let set = settings(json!({"advanced": {"printAsBitmap": true}}));
|
||||
let widths = |ppi: f64| {
|
||||
let mut d = doc(&s).clone();
|
||||
d.raster_effects_ppi = ppi;
|
||||
let bitmap = crate::cmd::printadvanced::prepare("file.print", &d, &set, &saved, false).unwrap().unwrap();
|
||||
let mut widths = vec![];
|
||||
bitmap.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
widths.push(im.width);
|
||||
}
|
||||
});
|
||||
widths
|
||||
};
|
||||
let at_72 = widths(72.0);
|
||||
assert_eq!(at_72.len(), 1, "{at_72:?}");
|
||||
assert_eq!(widths(f64::NAN), at_72);
|
||||
assert!(widths(144.0)[0] > at_72[0], "the resolution decides the image's size");
|
||||
}
|
||||
|
||||
/// The images `file.print` prints with `settings`: their pixel sizes and their places on the page
|
||||
/// in the print-ready PDF (read back), their pixel sizes in the PostScript file (its image
|
||||
/// dictionaries, each size once), and the warnings of both.
|
||||
|
||||
@@ -338,6 +338,45 @@ fn steps_discard_the_chosen_artboard_after_revert() {
|
||||
assert_ne!(now[2], was[2], "playback uses the run's original index after revert");
|
||||
}
|
||||
|
||||
/// An artboard the script removes or inserts moves the active artboard's index; its played steps act
|
||||
/// on the active artboard at the index `getActiveArtboardIndex()` gives, as the run's report does,
|
||||
/// also after an undo puts the artboards back. The artboard that was active stays active, also when
|
||||
/// none was chosen before the run.
|
||||
#[test]
|
||||
fn steps_follow_the_active_artboard_after_the_script_removes_or_inserts_one_before_it() {
|
||||
let setup = |active: Option<usize>| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
if let Some(i) = active {
|
||||
make_active(&mut s, i);
|
||||
}
|
||||
(s, id)
|
||||
};
|
||||
let actions = set(&[("Align", vec![json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}})])]);
|
||||
let cases = [
|
||||
(Some(1), "A.remove(0);"),
|
||||
(Some(1), "A[0].remove();"),
|
||||
(Some(1), "A.insert([2000, 500, 2100, 400], 0);"),
|
||||
(Some(1), "A.insert([2000, 500, 2100, 400], 2);"),
|
||||
(Some(1), "A.remove(0); app.undo();"),
|
||||
(None, "A.insert([2000, 500, 2100, 400], 0);"),
|
||||
];
|
||||
for (active, edit) in cases {
|
||||
let (mut s, id) = setup(active);
|
||||
let was = s.active().unwrap().doc.artboards[active.unwrap_or(0)].rect;
|
||||
let source = format!("var A = app.activeDocument.artboards; {edit} vc.log(A.getActiveArtboardIndex()); app.doScript('Align', 'Set');");
|
||||
let out = log_with(&mut s, &source, &actions);
|
||||
let index = out[0].as_u64().unwrap() as usize;
|
||||
let board = s.active().unwrap().doc.artboards[index].rect;
|
||||
let left = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
|
||||
assert_eq!(left, board.x0, "{active:?} {edit}");
|
||||
assert_eq!(board, was, "the artboard active before the edit stays active: {active:?} {edit}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none,
|
||||
/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it.
|
||||
#[test]
|
||||
|
||||
@@ -2804,6 +2804,11 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
let steps = undo_steps(&s);
|
||||
// The lengths are read inside the run, after the refusal is caught, so a delete that ran before
|
||||
// the refusal shows here even though a failed run would put the tree back.
|
||||
let lengths = "vc.log([d.pageItems.length, d.layers[0].pageItems.length, d.groupItems.length, d.groupItems.length && d.groupItems[0].pageItems.length, \
|
||||
d.compoundPathItems.length]);";
|
||||
let counts = log(&mut s, &format!("var d = app.activeDocument; {lengths}"));
|
||||
for scope in [
|
||||
"app.activeDocument.layers[0].pageItems",
|
||||
"app.activeDocument.layers[0].groupItems",
|
||||
@@ -2815,9 +2820,13 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
|
||||
"app.activeDocument.groupItems.getByName('locked').pathItems",
|
||||
"app.activeDocument.compoundPathItems[0].pathItems",
|
||||
] {
|
||||
// The error is caught, so the run keeps whatever `removeAll()` did before it threw.
|
||||
let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);"));
|
||||
assert!(out[0].as_str().is_some_and(|m| m.contains("cannot delete objects on a locked artboard")), "{scope}: {out:?}");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("var d = app.activeDocument; try {{ {scope}.removeAll(); vc.log('ok'); }} catch (e) {{ vc.log(e.message); }} {lengths}"),
|
||||
);
|
||||
let err = out[0].as_str().unwrap_or_default();
|
||||
assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}");
|
||||
assert_eq!(out[1..], counts[..], "{scope}: nothing is deleted before the refusal");
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}");
|
||||
assert_eq!(undo_steps(&s), steps, "{scope}");
|
||||
let doc = &s.active().unwrap().doc;
|
||||
@@ -5190,6 +5199,38 @@ fn a_new_documents_chosen_artboard_is_reported_after_an_insert_before_it() {
|
||||
assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}");
|
||||
}
|
||||
|
||||
/// Without a chosen artboard, an artboard inserted before the default active one moves it to the
|
||||
/// next index, in an open document and in one the run makes, and the report gives that index.
|
||||
#[test]
|
||||
fn inserting_before_the_default_active_artboard_keeps_it() {
|
||||
let (mut s, _, _) = doc();
|
||||
let first = s.active().unwrap().doc.artboards[0].id;
|
||||
let r = run(&mut s, "var A = app.activeDocument.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());").unwrap();
|
||||
assert_eq!(r["log"], json!([1]));
|
||||
assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}]));
|
||||
assert_eq!(s.active().unwrap().active_artboard, Some(first));
|
||||
let r = run(&mut s, "var d = app.documents.add(); var A = d.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());")
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([1]));
|
||||
let list = r["activeArtboards"].as_array().cloned().unwrap_or_default();
|
||||
assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}");
|
||||
}
|
||||
|
||||
/// After the chosen artboard is removed, the artboard active in its place stays active when one is
|
||||
/// inserted before it.
|
||||
#[test]
|
||||
fn inserting_before_the_fallback_after_the_chosen_artboard_is_removed_keeps_it() {
|
||||
let (mut s, _, _) = doc();
|
||||
let r = run(
|
||||
&mut s,
|
||||
"var A = app.activeDocument.artboards; A.add([800, 300, 900, 100]); A.setActiveArtboardIndex(1); A.remove(1);\
|
||||
var was = A[A.getActiveArtboardIndex()].name; A.insert([1000, 300, 1100, 100], 0);\
|
||||
vc.log(A[A.getActiveArtboardIndex()].name == was);",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([true]), "{r}");
|
||||
}
|
||||
|
||||
/// `artboards.insert` gives nothing back; `artboards.add` gives the new artboard.
|
||||
#[test]
|
||||
fn artboards_insert_returns_nothing() {
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
//! The script object model's perspective grid members and `app.getPresetSettings`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The message of the run's failure.
|
||||
fn failure(s: &mut Session, source: &str) -> String {
|
||||
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn grid(s: &mut Session) -> Value {
|
||||
s.execute("perspective.grid.get", &json!({})).unwrap()["grid"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_and_hide_change_the_view_without_an_undo_step() {
|
||||
let mut s = doc();
|
||||
let before = undo_steps(&s);
|
||||
let out =
|
||||
log(&mut s, "var d = app.activeDocument; vc.log(d.hidePerspectiveGrid()); vc.log(d.showPerspectiveGrid()); vc.log(d.showPerspectiveGrid());");
|
||||
assert_eq!(out, vec![json!(false), json!(true), json!(true)]);
|
||||
assert_eq!(grid(&mut s)["visible"], true);
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
let out = log(&mut s, "var d = app.activeDocument; vc.log(d.hidePerspectiveGrid()); vc.log(d.hidePerspectiveGrid());");
|
||||
assert_eq!(out, vec![json!(true), json!(false)]);
|
||||
assert_eq!(grid(&mut s)["visible"], false);
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_view_migrates_legacy_attachments_without_an_undo_step() {
|
||||
use vectorcraft_tools::distort::perspective::{self as persp, PerspectiveGrid, Plane};
|
||||
|
||||
for (call, edit) in [("showPerspectiveGrid", false), ("hidePerspectiveGrid", false), ("showPerspectiveGrid", true), ("hidePerspectiveGrid", true)]
|
||||
{
|
||||
let mut s = doc();
|
||||
let made = s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap();
|
||||
let id = NodeId(made["id"].as_u64().unwrap());
|
||||
let st = s.doc_mut().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut st.doc);
|
||||
let mut g = PerspectiveGrid::current(d);
|
||||
g.visible = call == "hidePerspectiveGrid";
|
||||
g.attached.insert(id.0.to_string(), Plane::Right);
|
||||
d.unknown.insert(persp::DOC_KEY.into(), serde_json::to_value(&g).unwrap());
|
||||
let before = undo_steps(&s);
|
||||
let draw = if edit { "vc.run('shape.rectangle', {x: 50, y: 50, width: 10, height: 10});" } else { "" };
|
||||
run(&mut s, &format!("app.activeDocument.{call}(); {draw}")).unwrap();
|
||||
assert_eq!(undo_steps(&s), before + usize::from(edit));
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(PerspectiveGrid::current(d).attachment_of(d, id), Some((Plane::Right, 0.0)));
|
||||
assert!(d.node(id).unwrap().extras().perspective.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_view_commands_in_a_run_add_no_undo_step_but_an_edit_still_does() {
|
||||
let mut s = doc();
|
||||
let before = undo_steps(&s);
|
||||
run(&mut s, "vc.run('perspective.grid.show', {visible: true}); vc.run('perspective.plane.set', {plane: 'ground'});").unwrap();
|
||||
assert_eq!((grid(&mut s)["visible"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground")));
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
run(&mut s, "app.activeDocument.hidePerspectiveGrid(); vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});").unwrap();
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(grid(&mut s)["visible"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_view_run_after_an_edit_adds_no_undo_step() {
|
||||
let mut s = doc();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let drawn = s.active().unwrap().doc.node_count();
|
||||
run(&mut s, "app.activeDocument.showPerspectiveGrid(); vc.run('perspective.plane.set', {plane: 'ground'});").unwrap();
|
||||
assert_eq!((grid(&mut s)["visible"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground")));
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.node_count(), drawn - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_edit_that_changes_only_view_fields_keeps_its_undo_step_in_a_run() {
|
||||
let mut s = doc();
|
||||
let before = undo_steps(&s);
|
||||
s.execute("perspective.grid.set", &json!({"locked": true})).unwrap();
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let mut s = doc();
|
||||
let source = "vc.run('perspective.grid.set', {locked: true}); app.activeDocument.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE);";
|
||||
run(&mut s, source).unwrap();
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
assert_eq!((grid(&mut s)["locked"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground")));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!grid(&mut s).get("locked").and_then(Value::as_bool).unwrap_or(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_active_plane_round_trips_and_a_failed_run_puts_it_back() {
|
||||
let mut s = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; vc.log(d.getPerspectiveActivePlane());\
|
||||
vc.log(d.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE)); vc.log(d.getPerspectiveActivePlane());\
|
||||
d.setActivePlane(PerspectiveGridPlaneType.INVALIDGRIDPLANETYPE); vc.log(d.getPerspectiveActivePlane());",
|
||||
);
|
||||
let expected = ["PerspectiveGridPlaneType.GRIDLEFTPLANETYPE", "PerspectiveGridPlaneType.GRIDFLOORPLANETYPE"];
|
||||
assert_eq!(out[..3], [json!(expected[0]), json!(true), json!(expected[1])]);
|
||||
assert_eq!(out[3], json!("PerspectiveGridPlaneType.INVALIDGRIDPLANETYPE"));
|
||||
assert_eq!(grid(&mut s)["plane"], "none");
|
||||
failure(&mut s, "var d = app.activeDocument; d.setActivePlane(PerspectiveGridPlaneType.GRIDRIGHTPLANETYPE); d.showPerspectiveGrid(); throw 1;");
|
||||
assert_eq!(grid(&mut s)["plane"], "none");
|
||||
assert_eq!(grid(&mut s)["visible"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_plane_or_a_right_plane_on_a_one_point_grid_throws() {
|
||||
let mut s = doc();
|
||||
for bad in ["'left'", "0", "PerspectiveGridType.OnePointPerspectiveGridType", "undefined"] {
|
||||
let e = failure(&mut s, &format!("app.activeDocument.setActivePlane({bad});"));
|
||||
assert!(e.contains("PerspectiveGridPlaneType"), "{bad}: {e}");
|
||||
}
|
||||
s.execute("perspective.grid.preset", &json!({"kind": 1})).unwrap();
|
||||
let e = failure(&mut s, "app.activeDocument.setActivePlane(PerspectiveGridPlaneType.GRIDRIGHTPLANETYPE);");
|
||||
assert!(e.contains("one-point grid"), "{e}");
|
||||
assert_eq!(grid(&mut s)["plane"], "left");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; d.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE); vc.log(d.getPerspectiveActivePlane());",
|
||||
);
|
||||
assert_eq!(out, vec![json!("PerspectiveGridPlaneType.GRIDFLOORPLANETYPE")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_perspective_preset_checks_the_type_and_the_name() {
|
||||
let mut s = doc();
|
||||
let one = s.execute("perspective.presets.list", &json!({})).unwrap()["presets"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|p| p["kind"] == 1)
|
||||
.map(|p| p["name"].as_str().unwrap().to_string())
|
||||
.unwrap();
|
||||
let before = undo_steps(&s);
|
||||
for (call, message) in [
|
||||
(format!("PerspectiveGridType.TwoPointPerspectiveGridType, '{one}'"), "not a grid of that type"),
|
||||
(format!("PerspectiveGridType.InvalidPerspectiveGridType, '{one}'"), "has no presets"),
|
||||
("PerspectiveGridType.OnePointPerspectiveGridType, 'No Such Preset'".to_string(), "no perspective grid preset called"),
|
||||
(format!("'one', '{one}'"), "PerspectiveGridType value"),
|
||||
("PerspectiveGridType.OnePointPerspectiveGridType, 7".to_string(), "presetName must be a string"),
|
||||
(format!("PerspectiveGridType.OnePointPerspectiveGridType, '{}'", "x".repeat(5000)), "too long"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset({call});"));
|
||||
assert!(e.contains(message), "{call}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
assert_eq!(grid(&mut s)["kind"], 2);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("vc.log(app.activeDocument.selectPerspectivePreset(PerspectiveGridType.OnePointPerspectiveGridType, '{}'));", one.to_uppercase()),
|
||||
);
|
||||
assert_eq!(out, vec![json!(true)]);
|
||||
let g = grid(&mut s);
|
||||
assert_eq!((g["kind"].clone(), g["visible"].clone()), (json!(1), json!(true)));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_names_and_numbers_throw_with_nothing_changed() {
|
||||
let mut s = doc();
|
||||
s.execute("perspective.presets.save", &json!({"name": "Mine"})).unwrap();
|
||||
let before = (undo_steps(&s), grid(&mut s));
|
||||
for name in ["../Mine", "..\\\\Mine", "/Mine", "C:\\\\Mine", "Mine/..", "Mi\\u0000ne", "~/Mine"] {
|
||||
for call in [
|
||||
format!("app.activeDocument.selectPerspectivePreset(PerspectiveGridType.TwoPointPerspectiveGridType, '{name}');"),
|
||||
format!("app.getPresetSettings('{name}');"),
|
||||
] {
|
||||
let e = failure(&mut s, &call);
|
||||
assert!(e.contains("no perspective grid preset called") || e.contains("no startup preset called"), "{call}: {e}");
|
||||
}
|
||||
}
|
||||
// The script host refuses a number that is not finite before the member runs.
|
||||
for value in ["NaN", "Infinity", "-1e308", "1e308", "2"] {
|
||||
let refused = |e: &str, message: &str| e.contains(message) || e.contains("is not a finite number");
|
||||
let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset({value}, 'Mine');"));
|
||||
assert!(refused(&e, "PerspectiveGridType value"), "{value}: {e}");
|
||||
let e = failure(&mut s, &format!("app.activeDocument.setActivePlane({value});"));
|
||||
assert!(refused(&e, "PerspectiveGridPlaneType value"), "{value}: {e}");
|
||||
let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset(PerspectiveGridType.TwoPointPerspectiveGridType, {value});"));
|
||||
assert!(refused(&e, "presetName must be a string"), "{value}: {e}");
|
||||
}
|
||||
assert_eq!((undo_steps(&s), grid(&mut s)), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_document_throws_on_every_grid_member() {
|
||||
let mut s = doc();
|
||||
run(&mut s, "#targetengine keep\nvar held = app.activeDocument;").unwrap();
|
||||
let e = failure(&mut s, "#targetengine keep\nheld.showPerspectiveGrid();");
|
||||
assert!(e.contains("Stale document"), "{e}");
|
||||
let e = failure(&mut s, "var d = app.activeDocument; vc.run('file.close', {}); d.hidePerspectiveGrid();");
|
||||
assert!(e.contains("Stale document"), "{e}");
|
||||
let e = failure(&mut s, "Document.prototype.getPerspectiveActivePlane.call({});");
|
||||
assert!(e.contains("not a Document"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_preset_settings_gives_a_copy_add_document_takes() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.getPresetSettings('Basic CMYK'); vc.log(p.typename); vc.log(p.colorMode); vc.log(p.width); vc.log(p.height);\
|
||||
vc.log(p.numArtboards); p.width = 100; vc.log(app.getPresetSettings('Basic CMYK').width);\
|
||||
var d = app.documents.addDocument('Basic CMYK', p); vc.log(d.width); vc.log(d.documentColorSpace);\
|
||||
vc.log(app.getPresetSettings(DocumentPresetType.BasicRGB).colorMode);",
|
||||
);
|
||||
let expected = [json!("DocumentPreset"), json!("DocumentColorSpace.CMYK"), json!(612), json!(792), json!(1), json!(612)];
|
||||
assert_eq!(out[..6], expected);
|
||||
assert_eq!(out[6..], [json!(100), json!("DocumentColorSpace.CMYK"), json!("DocumentColorSpace.RGB")]);
|
||||
for (call, message) in [("'No Such Preset'", "no startup preset called"), ("3", "startup preset's name"), ("undefined", "startup preset's name")]
|
||||
{
|
||||
let e = failure(&mut s, &format!("app.getPresetSettings({call});"));
|
||||
assert!(e.contains(message), "{call}: {e}");
|
||||
}
|
||||
let e = failure(&mut s, &format!("app.getPresetSettings('{}');", "x".repeat(5000)));
|
||||
assert!(e.contains("too long"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_preset_settings_of_a_profile_gives_what_add_document_starts_from() {
|
||||
let mut s = Session::new();
|
||||
for preset in ["Video", "Web", "Mobile", "Print", "DocumentPresetType.Video"] {
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.getPresetSettings('{preset}'); var d = app.documents.addDocument('{preset}');\
|
||||
vc.log([p.width, p.height, p.units, p.colorMode]); vc.log([d.width, d.height, d.rulerUnits, d.documentColorSpace]);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], out[1], "{preset}");
|
||||
}
|
||||
let out = log(&mut s, "var p = app.getPresetSettings('Video'); vc.log([p.width, p.height]);");
|
||||
assert_ne!(out[0], json!([612, 792]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_preset_settings_given_back_to_add_document_makes_the_same_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("prefs.set", &json!({"key": "unitsGeneral", "value": "feet"})).unwrap();
|
||||
let layout = json!({"layout": "gridByColumn", "rows": 3, "spacing": 30});
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "artboards": 5, "artboardLayout": layout})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.getPresetSettings('Print'); vc.log(p.numArtboards); vc.log(p.units === undefined);\
|
||||
function boards(d) { var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); return r; }\
|
||||
var a = app.documents.addDocument('Print'); var b = app.documents.addDocument('Print', p);\
|
||||
vc.log(boards(a)); vc.log(boards(b)); vc.log(a.rulerUnits === b.rulerUnits);",
|
||||
);
|
||||
// A saved preset with the built-in preset's name changes neither the settings nor the document.
|
||||
assert_eq!(out[..2], [json!(1), json!(true)]);
|
||||
assert_eq!(out[2], out[3]);
|
||||
assert_eq!(out[2].as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(out[4], json!(true));
|
||||
for (artboards, layout) in [
|
||||
(6, json!({"layout": "gridByColumn", "columns": 4})),
|
||||
(150, json!({"layout": "gridByRow", "columns": 12})),
|
||||
(7, json!({"layout": "gridByRow", "columns": 3, "rightToLeft": true})),
|
||||
] {
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "artboards": artboards, "artboardLayout": layout})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.getPresetSettings('Print'); vc.log(p.numArtboards);\
|
||||
function boards(d) { var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); return r; }\
|
||||
vc.log(boards(app.documents.addDocument('Print'))); vc.log(boards(app.documents.addDocument('Print', p)));",
|
||||
);
|
||||
assert_eq!(out[0], json!(1), "{artboards} {layout}");
|
||||
assert_eq!(out[1].as_array().map(Vec::len), Some(1), "{layout}");
|
||||
assert_eq!(out[1], out[2], "{artboards} {layout}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_preview_preset_settings_can_be_given_back_to_add_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "previewMode": "pixel"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.getPresetSettings('Print'); vc.log(p.previewMode);\
|
||||
var a = app.documents.addDocument('Print'); var b = app.documents.addDocument('Print', p);\
|
||||
vc.log([a.width, a.height, a.documentColorSpace]); vc.log([b.width, b.height, b.documentColorSpace]);",
|
||||
);
|
||||
// The saved preset's Pixel Preview does not replace the built-in preset's preview mode.
|
||||
assert_eq!(out[0], json!("DocumentPreviewMode.DefaultPreview"));
|
||||
assert_eq!(out[1], out[2]);
|
||||
assert_eq!(out[1], json!([612, 792, "DocumentColorSpace.CMYK"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_presets_list_names_presets_add_document_takes() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var l = app.startupPresetsList; vc.log(l); l.push('Mine'); l[0] = 'x'; vc.log(app.startupPresetsList.length === l.length - 1);\
|
||||
vc.log(app.startupPresetsList[0] !== 'x');\
|
||||
for (var i = 0; i < l.length - 1; i++) { var n = app.startupPresetsList[i]; var p = app.getPresetSettings(n);\
|
||||
var d = app.documents.addDocument(n); vc.log([n, d.width === p.width && d.documentColorSpace === p.colorMode]); }",
|
||||
);
|
||||
let names: Vec<&str> = out[0].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
||||
// VectorCraft's own order puts Print first.
|
||||
assert_eq!(names.first(), Some(&"Print"));
|
||||
// Every New Document profile and both Basic presets, each once.
|
||||
let mut sorted = names.clone();
|
||||
sorted.sort_unstable();
|
||||
let mut listed: Vec<&str> = crate::cmd::newdoc::profile_names().chain(["Basic CMYK", "Basic RGB"]).collect();
|
||||
listed.sort_unstable();
|
||||
assert_eq!(sorted, listed);
|
||||
assert_eq!(out[1..3], [json!(true), json!(true)]);
|
||||
assert_eq!(out.len(), 3 + names.len());
|
||||
for (name, made) in names.iter().zip(&out[3..]) {
|
||||
assert_eq!(made, &json!([name, true]), "{name}");
|
||||
}
|
||||
assert_eq!(s.documents().len(), names.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn members_not_built_yet_say_so() {
|
||||
let mut s = doc();
|
||||
for (owner, member) in [
|
||||
("app", "saveWorkspace"),
|
||||
("app", "switchWorkspace"),
|
||||
("app", "deleteWorkspace"),
|
||||
("app", "resetWorkspace"),
|
||||
("app", "loadColorSettings"),
|
||||
("app", "showPresets"),
|
||||
("app.activeDocument", "exportPerspectiveGridPreset"),
|
||||
("app.activeDocument", "importPerspectiveGridPreset"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("{owner}.{member}('x');"));
|
||||
assert!(e.contains(&format!("{member} is not available yet")), "{member}: {e}");
|
||||
}
|
||||
}
|
||||
@@ -1659,6 +1659,102 @@ fn retraced_plugin_is_the_same_object_as_its_collection_handle() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retrace_keeps_the_tracing_note_and_tags() {
|
||||
let base = folder("retrace-attributes");
|
||||
let (mut s, _) = session(&base, false);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var p = app.activeDocument.rasterItems[0].trace(); p.note = 'keep me'; var tags = p.tags, t = tags.add(); t.name = 'job'; t.value = '42';\
|
||||
p.tracing.tracingOptions.threshold = 90; vc.log(p.note); vc.log(p.tags.length); vc.log(p.tags[0].name + '=' + p.tags[0].value);\
|
||||
vc.log(tags.length); vc.log(t.value); vc.log(t === p.tags[0]); vc.log(tags === p.tags);",
|
||||
);
|
||||
assert_eq!(out, [json!("keep me"), json!(1), json!("job=42"), json!(1), json!("42"), json!(true), json!(true)]);
|
||||
// Image Trace › Make on the tracing keeps them too.
|
||||
let id = traces(&s)[0];
|
||||
let r = s.execute("imageTrace.make", &json!({"id": id.0, "params": {"threshold": 100}})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let d = &s.active().unwrap().doc;
|
||||
let attrs = d.node(id).and_then(|n| n.extras().attrs.as_deref().cloned()).unwrap_or_default();
|
||||
assert_eq!(attrs.note, "keep me");
|
||||
let tags: Vec<(&str, &str)> = attrs.tags.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect();
|
||||
assert_eq!(tags, [("job", "42")]);
|
||||
let r = s.execute("imageTrace.makeAndExpand", &json!({"id": id.0})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let d = &s.active().unwrap().doc;
|
||||
let group = d.node(id).unwrap();
|
||||
assert!(matches!(group.kind, NodeKind::Group { .. }));
|
||||
let attrs = group.extras().attrs.as_deref().cloned().unwrap_or_default();
|
||||
assert_eq!(attrs.note, "keep me");
|
||||
let tags: Vec<(&str, &str)> = attrs.tags.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect();
|
||||
assert_eq!(tags, [("job", "42")]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Tracing again moves the tracing's attributes to the new tracing: it copies them once, when it
|
||||
/// reads the tracing out of the document, and not again for the new object.
|
||||
#[test]
|
||||
fn retrace_copies_the_tracing_attributes_once() {
|
||||
let base = folder("retrace-attribute-copies");
|
||||
let (mut s, _) = session(&base, false);
|
||||
log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var p = app.activeDocument.rasterItems[0].trace(); p.note = 'keep me'; var t = p.tags.add(); t.name = 'job'; t.value = '42';",
|
||||
);
|
||||
let id = traces(&s)[0];
|
||||
let before = vectorcraft_doc::attribute_copies();
|
||||
let r = s.execute("imageTrace.make", &json!({"id": id.0, "params": {"threshold": 100}})).unwrap();
|
||||
assert_eq!(vectorcraft_doc::attribute_copies() - before, 1, "copies of the attributes");
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let note = s.active().unwrap().doc.node(id).and_then(|n| n.extras().attrs.as_deref().map(|a| a.note.clone()));
|
||||
assert_eq!(note.as_deref(), Some("keep me"));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `pathItems.removeAll()` and `textFrames.removeAll()` refuse to leave an image at the bottom of an
|
||||
/// ordinary group named as a tracing, before the document changes.
|
||||
#[test]
|
||||
fn path_and_type_remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() {
|
||||
let setup = |bottom: &str| {
|
||||
format!(
|
||||
"var d = app.activeDocument; d.selection = [{bottom}]; vc.run('object.group');\
|
||||
var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);"
|
||||
)
|
||||
};
|
||||
for (name, bottom, list) in [
|
||||
("remove-all-trace-name-paths", "d.pathItems.rectangle(10, 10, 20, 20)", "pathItems"),
|
||||
// `edit.clear` also deletes the compound path its members leave empty.
|
||||
(
|
||||
"remove-all-trace-name-compound",
|
||||
"(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20), d.pathItems.rectangle(40, 40, 5, 5)];\
|
||||
vc.run('object.compoundPath.make'); return d.pageItems[0]; })()",
|
||||
"pathItems",
|
||||
),
|
||||
("remove-all-trace-name-type", "d.textFrames.pointText([10, 10])", "textFrames"),
|
||||
] {
|
||||
let base = folder(name);
|
||||
let (mut s, _) = session(&base, false);
|
||||
log(&mut s, &base, &setup(bottom));
|
||||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = app.activeDocument, m = ''; try {{ d.{list}.removeAll(); }} catch (e) {{ m = e.message; }}\
|
||||
vc.log(m); vc.log(d.pageItems[0].typename);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem")], "{list}");
|
||||
assert!(traces(&s).is_empty(), "{list}");
|
||||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{list}");
|
||||
assert_eq!(undo_steps(&s), steps, "{list}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_the_same_preset_in_bracket_form_does_not_trace_again() {
|
||||
let base = folder("retrace-bracket-preset");
|
||||
|
||||
@@ -1874,7 +1874,7 @@ fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() {
|
||||
/// to the Script Console.
|
||||
#[test]
|
||||
fn a_saves_warnings_go_to_the_console() {
|
||||
let base = folder("warnings");
|
||||
let base = folder("pdf-warnings");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! must load as an error or as a document that then renders and exports, without a panic; nor may
|
||||
//! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records
|
||||
//! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files,
|
||||
//! opcodes with random contents) opened or placed, nor EPS and PostScript files
|
||||
//! opcodes with random contents) opened or placed, nor binary CGM files (damaged files, elements
|
||||
//! with random contents) opened or placed, nor EPS and PostScript files
|
||||
//! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of
|
||||
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a
|
||||
//! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents
|
||||
@@ -4158,6 +4159,125 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Binary CGM files: opened and placed ----------
|
||||
|
||||
// The CGM reader waits on craft-libs#5410: everything here is behind the `cgm` feature.
|
||||
|
||||
/// One CGM element, in the long form past 30 bytes, padded to an even length.
|
||||
#[cfg(feature = "cgm")]
|
||||
fn cgm_el(class: u16, id: u16, data: &[u8]) -> Vec<u8> {
|
||||
let mut b = Vec::new();
|
||||
if data.len() < 31 {
|
||||
b.extend(((class << 12) | (id << 5) | data.len() as u16).to_be_bytes());
|
||||
} else {
|
||||
b.extend(((class << 12) | (id << 5) | 31).to_be_bytes());
|
||||
b.extend((data.len() as u16).to_be_bytes());
|
||||
}
|
||||
b.extend(data);
|
||||
if data.len() % 2 == 1 {
|
||||
b.push(0);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// A metafile of one picture holding `body`.
|
||||
#[cfg(feature = "cgm")]
|
||||
fn cgm_of(body: &[(u16, u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut b = cgm_el(0, 1, b"\x01x");
|
||||
b.extend(cgm_el(1, 1, &be16(&[3])));
|
||||
b.extend(cgm_el(1, 13, b"\x09Helvetica"));
|
||||
b.extend(cgm_el(0, 3, b"\x01p"));
|
||||
b.extend(cgm_el(2, 6, &be16(&[0, 0, 1000, 500])));
|
||||
b.extend(cgm_el(0, 4, &[]));
|
||||
for (class, id, data) in body {
|
||||
b.extend(cgm_el(*class, *id, data));
|
||||
}
|
||||
b.extend(cgm_el(0, 5, &[]));
|
||||
b.extend(cgm_el(0, 2, &[]));
|
||||
b
|
||||
}
|
||||
|
||||
/// A picture with lines, shapes, arcs, a figure, markers, text, a cell array and a clip.
|
||||
#[cfg(feature = "cgm")]
|
||||
fn cgm_sample() -> Vec<u8> {
|
||||
cgm_of(&[
|
||||
(5, 34, vec![8, 10, 20, 30, 40, 50, 60]),
|
||||
(5, 3, be16(&[3])),
|
||||
(5, 2, be16(&[2])),
|
||||
(4, 1, be16(&[0, 0, 100, 100, 200, 0])),
|
||||
(4, 2, be16(&[0, 10, 50, 10, 60, 10, 90, 10])),
|
||||
(5, 22, be16(&[1])),
|
||||
(5, 30, be16(&[1])),
|
||||
(4, 7, be16(&[300, 0, 400, 0, 350, 80])),
|
||||
(4, 8, be16(&[0, 200, 1, 100, 200, 1, 100, 300, 3])),
|
||||
(4, 11, be16(&[500, 0, 600, 100])),
|
||||
(4, 12, be16(&[700, 100, 50])),
|
||||
(4, 14, be16(&[800, 0, 850, 50, 900, 0, 0])),
|
||||
(4, 16, be16(&[100, 400, 1, 0, 0, 1, 50, 1])),
|
||||
(4, 19, be16(&[300, 400, 350, 400, 300, 420, 1, 0, 0, 1, 0])),
|
||||
(4, 26, be16(&[2, 0, 0, 10, 20, 30, 20, 40, 0])),
|
||||
(0, 8, vec![]),
|
||||
(4, 1, be16(&[500, 300, 600, 300])),
|
||||
(4, 15, be16(&[600, 350, 0, -1, 0, 1, 50])),
|
||||
(3, 10, vec![]),
|
||||
(0, 9, vec![]),
|
||||
(5, 6, be16(&[3])),
|
||||
(4, 3, be16(&[900, 400, 950, 450])),
|
||||
(3, 5, be16(&[0, 0, 500, 250])),
|
||||
(5, 15, be16(&[40])),
|
||||
(4, 4, [be16(&[100, 100, 0]), b"\x03abc".to_vec()].concat()),
|
||||
(4, 6, [be16(&[1]), b"\x02de".to_vec()].concat()),
|
||||
(4, 9, [be16(&[0, 0, 200, 100, 200, 0, 2, 2, 4, 1]), vec![0x12, 0, 0x34, 0]].concat()),
|
||||
])
|
||||
}
|
||||
|
||||
/// The sample the mutations start from opens with art, type and an image.
|
||||
#[cfg(feature = "cgm")]
|
||||
#[test]
|
||||
fn the_cgm_sample_opens() {
|
||||
let l = vectorcraft_engine::cmd::fileio::load("x.cgm", &cgm_sample()).unwrap();
|
||||
assert_eq!(l.format.id, "cgm");
|
||||
let (mut paths, mut images, mut texts) = (0, 0, 0);
|
||||
l.doc.walk(|n| match n.kind {
|
||||
vectorcraft_doc::NodeKind::Path { .. } => paths += 1,
|
||||
vectorcraft_doc::NodeKind::Image(_) => images += 1,
|
||||
vectorcraft_doc::NodeKind::Text(_) => texts += 1,
|
||||
_ => {}
|
||||
});
|
||||
assert!(paths > 10 && images == 1 && texts == 1, "{paths} paths, {images} images, {texts} texts, warnings {:?}", l.warnings);
|
||||
}
|
||||
|
||||
/// CGM elements VectorCraft reads, and some it skips: the class in the high byte, the id in the
|
||||
/// low one.
|
||||
#[cfg(feature = "cgm")]
|
||||
const CGM_ELEMENTS: [u16; 44] = [
|
||||
0x0008, 0x0009, 0x0103, 0x0104, 0x0105, 0x0107, 0x010A, 0x010C, 0x010D, 0x0113, 0x0201, 0x0202, 0x0203, 0x0207, 0x0301, 0x0302, 0x0305, 0x0306,
|
||||
0x030A, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, 0x0409, 0x040B, 0x040C, 0x040D, 0x040F, 0x0411, 0x0412, 0x0414, 0x0418,
|
||||
0x041A, 0x0503, 0x0504, 0x050F, 0x0510, 0x0512, 0x0522, 0x0801,
|
||||
];
|
||||
|
||||
#[cfg(feature = "cgm")]
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
#[test]
|
||||
fn mutated_cgm_pictures_never_panic(cut in 0usize..4096, edits in prop::collection::vec((0usize..4096, any::<u8>()), 0..16)) {
|
||||
let mut bytes = cgm_sample();
|
||||
let n = bytes.len();
|
||||
for &(at, b) in &edits {
|
||||
bytes[at % n] = b;
|
||||
}
|
||||
bytes.truncate(cut);
|
||||
survive_metafile("mutated CGM", "x.cgm", &bytes)?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_cgm_elements_never_panic(els in prop::collection::vec((prop::sample::select(CGM_ELEMENTS.to_vec()), arb_body()), 0..32)) {
|
||||
let body: Vec<(u16, u16, Vec<u8>)> = els.into_iter().map(|(e, d)| (e >> 8, e & 0xFF, d)).collect();
|
||||
survive_metafile("CGM elements", "x.cgm", &cgm_of(&body))?;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- HP-GL plot files: opened and placed ----------
|
||||
|
||||
/// A plot file with every kind of instruction the reader plays, printer escapes around it.
|
||||
|
||||
@@ -58,10 +58,11 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
/// the open documents; `Document.close` closes a document, and saves it to its own file only when it
|
||||
/// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and
|
||||
/// `Document.path` only name its file and folder. `app.open` reads the file it is given, and
|
||||
/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. Reading a
|
||||
/// preference changes nothing, and the matrix functions return new records. `app.copy` and `app.cut`
|
||||
/// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as Edit ›
|
||||
/// Copy does.
|
||||
/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. The perspective
|
||||
/// grid preset files of `Document`, and the workspace methods, `loadColorSettings` and
|
||||
/// `showPresets` of `Application`, throw "not available yet". Reading a preference changes nothing,
|
||||
/// and the matrix functions return new records. `app.copy` and `app.cut` fill VectorCraft's
|
||||
/// clipboard, which the desktop app offers to other apps after the run as Edit › Copy does.
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ %vcPaletteEvent File Folder UnitValue Window alert confirm localize prompt toSource"),
|
||||
("Window.", "__vcPaletteEvent alert confirm length prompt prototype"),
|
||||
@@ -103,22 +104,22 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
CompoundPathItems CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
|
||||
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \
|
||||
GraphicStyle GraphicStyles GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint \
|
||||
PathPointSelection PathPoints PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems \
|
||||
RulerUnits ScreenMode selection selection= Spot SpotColorKind Spots StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups \
|
||||
Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint Symbols Tag Tags TracingObject TracingOptions Transformation \
|
||||
View Views ZOrderMethod",
|
||||
PathPointSelection PathPoints PerspectiveGridPlaneType PerspectiveGridType PlacedItem PlacedItems PluginItem PointType \
|
||||
PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection selection= Spot SpotColorKind Spots \
|
||||
StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint \
|
||||
Symbols Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod",
|
||||
),
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= concatenateMatrix concatenateRotationMatrix concatenateScaleMatrix \
|
||||
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript \
|
||||
executeMenuCommand getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix \
|
||||
invertMatrix isEqualMatrix isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList \
|
||||
printerList redo redraw selection selection= selectTool showColorPicker textFonts toString typename undo unloadAction \
|
||||
unloadAction= \
|
||||
userInteractionLevel \
|
||||
userInteractionLevel=",
|
||||
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut deleteWorkspace \
|
||||
deleteWorkspace= documents doScript executeMenuCommand getIdentityMatrix getIsFileOpen getPresetSettings \
|
||||
getRotationMatrix getScaleMatrix getTranslationMatrix invertMatrix isEqualMatrix isSingularMatrix loadAction \
|
||||
loadAction= loadColorSettings loadColorSettings= open paste PPDFileList preferences printPresetsList printerList \
|
||||
redo redraw resetWorkspace resetWorkspace= saveWorkspace saveWorkspace= selection selection= selectTool \
|
||||
showColorPicker showPresets showPresets= startupPresetsList switchWorkspace switchWorkspace= textFonts toString \
|
||||
typename undo unloadAction unloadAction= userInteractionLevel userInteractionLevel=",
|
||||
),
|
||||
("Preferences.", "prototype"),
|
||||
("Preferences.prototype.", "constructor getBooleanPreference getIntegerPreference getRealPreference getStringPreference typename"),
|
||||
@@ -140,10 +141,13 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
|
||||
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
|
||||
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName gradients \
|
||||
gradients= graphicStyles groupItems height layers name pageItems paragraphStyles parent path pathItems patterns \
|
||||
patterns= placedItems rasterItems rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= \
|
||||
spots stories swatchGroups swatches symbolItems symbols tags textFrames toString typename views width",
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace \
|
||||
exportPerspectiveGridPreset exportPerspectiveGridPreset= fullName getPerspectiveActivePlane gradients gradients= \
|
||||
graphicStyles groupItems height hidePerspectiveGrid importPerspectiveGridPreset importPerspectiveGridPreset= \
|
||||
layers name pageItems paragraphStyles parent path pathItems patterns patterns= placedItems rasterItems \
|
||||
rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selectPerspectivePreset selection selection= \
|
||||
setActivePlane showPerspectiveGrid spots stories swatchGroups swatches symbolItems symbols tags textFrames \
|
||||
toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
("Views.prototype.", "constructor index length parent toString typename"),
|
||||
@@ -300,6 +304,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
),
|
||||
("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"),
|
||||
("PathPointSelection.", "ANCHORPOINT LEFTDIRECTION LEFTRIGHTPOINT NOSELECTION RIGHTDIRECTION"),
|
||||
("PerspectiveGridPlaneType.", "GRIDFLOORPLANETYPE GRIDLEFTPLANETYPE GRIDRIGHTPLANETYPE INVALIDGRIDPLANETYPE"),
|
||||
("PerspectiveGridType.", "InvalidPerspectiveGridType OnePointPerspectiveGridType ThreePointPerspectiveGridType TwoPointPerspectiveGridType"),
|
||||
("PointType.", "CORNER SMOOTH"),
|
||||
("PolarityValues.", "NEGATIVE POSITIVE"),
|
||||
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
|
||||
|
||||
+14
-4
@@ -563,6 +563,7 @@ impl Interp {
|
||||
|
||||
pub(crate) fn sync_host_files(&mut self) -> JsResult<()> {
|
||||
let mut updates = Vec::new();
|
||||
let mut untracked = Vec::new();
|
||||
for id in self.host_file_objects.clone() {
|
||||
self.use_fuel()?;
|
||||
let Some(object) = self.heap.object(id) else { continue };
|
||||
@@ -570,13 +571,22 @@ impl Interp {
|
||||
let class = h.class;
|
||||
for (name, file, previous) in &h.files {
|
||||
let Some(file_id) = file.as_object() else { continue };
|
||||
if crate::file_classes::file_path(self, file_id)?.as_ref() != Some(previous)
|
||||
&& let Some((get, set)) = self.file_accessors(class, name)
|
||||
{
|
||||
updates.push((id, name.clone(), file.clone(), previous.clone(), get, set));
|
||||
match crate::file_classes::file_path(self, file_id)? {
|
||||
// An object that is no longer a File (its prototype changed) is not tracked
|
||||
// any more, and the host keeps the path it has.
|
||||
None => untracked.push((id, name.clone())),
|
||||
Some(path) if path != *previous => {
|
||||
if let Some((get, set)) = self.file_accessors(class, name) {
|
||||
updates.push((id, name.clone(), file.clone(), previous.clone(), get, set));
|
||||
}
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, name) in untracked {
|
||||
self.keep_host_file(id, name, Value::Undefined)?;
|
||||
}
|
||||
for (id, name, file, previous, get, set) in updates {
|
||||
self.use_fuel()?;
|
||||
// A property the host changed since the assignment no longer holds this File: it is
|
||||
|
||||
@@ -1682,3 +1682,12 @@ fn a_refused_path_change_is_thrown_once() {
|
||||
assert!(first.contains("refused"), "{first}");
|
||||
assert_eq!(*seen.borrow(), ["/a", "/good"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_whose_prototype_changes_is_no_longer_tracked() {
|
||||
let (mut r, seen) = file_property_realm();
|
||||
r.set_es2015(true);
|
||||
let source = "var f = new File('/a'); it.file = f; Reflect.setPrototypeOf(f, Object.prototype); it.touch(); it.touch(); it.file !== f && it.file instanceof File";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
|
||||
assert_eq!(*seen.borrow(), ["/a"]);
|
||||
}
|
||||
|
||||
@@ -321,7 +321,8 @@ impl LiveBackend {
|
||||
Self { live: shared::Live::new(shared_cfg), config_dir, read_settings, default_folder }
|
||||
}
|
||||
|
||||
/// The folders the open window lets agents use, as the window opens them.
|
||||
/// The folders the open window lets agents use, read from the saved settings: the answer for a
|
||||
/// window that doesn't report the folders it enforces itself.
|
||||
fn window_folders(&self) -> Value {
|
||||
folders_answer(&(self.read_settings)(&self.config_dir).folders_with(self.default_folder.as_deref()))
|
||||
}
|
||||
@@ -330,7 +331,12 @@ impl LiveBackend {
|
||||
impl Backend for LiveBackend {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
match self.live.resolve()? {
|
||||
Route::Window(_) if method == FOLDERS_METHOD => Ok(self.window_folders()),
|
||||
// The window answers with the folders it enforces, which are none when a saved folder
|
||||
// can't be used; a window without the method gets the saved settings.
|
||||
Route::Window(w) if method == FOLDERS_METHOD => match w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params) {
|
||||
Err(e) if e.contains(&format!("unknown method `{FOLDERS_METHOD}`")) => Ok(self.window_folders()),
|
||||
answer => answer,
|
||||
},
|
||||
Route::Window(w) => w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
|
||||
Route::Headless(h) => h.borrow_mut().call(method, params),
|
||||
}
|
||||
|
||||
@@ -19,8 +19,13 @@ const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789a
|
||||
|
||||
/// A stand-in for the window's control server holding `token`: it authenticates as the shared
|
||||
/// server does and answers every request with `{"window": true, "method"}`. The count is of the
|
||||
/// requests it got after authentication.
|
||||
/// requests it got after authentication. It doesn't know `agent.folders`, as a window from before it.
|
||||
fn fake_window(token: &'static str) -> (u16, Arc<AtomicUsize>) {
|
||||
fake_window_with_folders(token, None)
|
||||
}
|
||||
|
||||
/// [`fake_window`], answering `agent.folders` with `folders` when given.
|
||||
fn fake_window_with_folders(token: &'static str, folders: Option<Value>) -> (u16, Arc<AtomicUsize>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let served = Arc::new(AtomicUsize::new(0));
|
||||
@@ -29,6 +34,7 @@ fn fake_window(token: &'static str) -> (u16, Arc<AtomicUsize>) {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(stream) = stream else { return };
|
||||
let count = count.clone();
|
||||
let folders = folders.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut writer = stream.try_clone().unwrap();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
@@ -38,7 +44,11 @@ fn fake_window(token: &'static str) -> (u16, Arc<AtomicUsize>) {
|
||||
let reply = if signed_in {
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}})
|
||||
match (&folders, req["method"] == FOLDERS_METHOD) {
|
||||
(Some(f), true) => json!({"id": req["id"], "ok": true, "result": f}),
|
||||
(None, true) => json!({"id": req["id"], "ok": false, "error": format!("unknown method `{FOLDERS_METHOD}`")}),
|
||||
_ => json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}}),
|
||||
}
|
||||
} else {
|
||||
let (reply, step) = handshake.reply(&line, token);
|
||||
signed_in = matches!(step, AuthStep::Authenticated);
|
||||
@@ -102,12 +112,25 @@ fn plain_mcp_reaches_the_window_while_agents_are_allowed() {
|
||||
let r = b.call("document.inspect", json!({})).unwrap();
|
||||
assert_eq!(r["window"], true, "{r}");
|
||||
assert!(served.load(Ordering::SeqCst) >= 1);
|
||||
// The window's folders are the agent folders as the window opens them: the default one here.
|
||||
// A window without `agent.folders`: the saved agent folders, the default one here.
|
||||
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
|
||||
assert_eq!(folders["read_folder"], json!(dir.file("Agents").to_string_lossy()));
|
||||
assert_eq!(folders["write_folder"], folders["read_folder"]);
|
||||
}
|
||||
|
||||
// `agent_folders` shows the folders the window enforces, not the saved ones: none here, as when a
|
||||
// saved folder can't be used and the window refuses every file.
|
||||
#[test]
|
||||
fn the_window_reports_the_folders_it_enforces() {
|
||||
let dir = TempFolder::new("agents-window-enforced");
|
||||
let (port, served) = fake_window_with_folders(TOKEN, Some(json!({"read_folder": null, "write_folder": null})));
|
||||
publish(&dir, port);
|
||||
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
|
||||
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
|
||||
assert_eq!(folders, json!({"read_folder": null, "write_folder": null}));
|
||||
assert!(served.load(Ordering::SeqCst) >= 1);
|
||||
}
|
||||
|
||||
// With agents off the app doesn't listen (its link is the gate), and plain `mcp` runs headless with
|
||||
// only the command's folders: the closed-app choice (an error here) is for agents the person let in.
|
||||
#[test]
|
||||
|
||||
@@ -1573,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.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`)",
|
||||
"{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.color.screenMarks|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",
|
||||
|
||||
@@ -3,11 +3,16 @@ name = "vectorcraft-metafile"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+, WMF and QuickDraw PICT import through craft-metafile"
|
||||
description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+, WMF, QuickDraw PICT and binary CGM import through craft-metafile"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# The binary CGM reader (`import_cgm`). Off until the craft-metafile CGM reader (craft-libs#5410)
|
||||
# merges and the workspace pins it; without it, `is_cgm` is false and `import_cgm` is refused.
|
||||
cgm = []
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-color = { workspace = true }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The metafile readers. EMF (with its EMF+ records) and WMF files, and QuickDraw pictures (PICT),
|
||||
//! are read by `craft_metafile`, and `picture` turns what they draw into document objects.
|
||||
//! and binary CGM files are read by `craft_metafile`, and `picture` turns what they draw into
|
||||
//! document objects.
|
||||
//!
|
||||
//! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the
|
||||
//! same pen join into one path. Clips become clipping groups around what they clip. Images keep
|
||||
@@ -92,3 +93,35 @@ pub(crate) fn import_pict(bytes: &[u8]) -> Result<crate::Picture, String> {
|
||||
})?;
|
||||
Ok(picture::convert(pic))
|
||||
}
|
||||
|
||||
/// The longer side of a CGM picture without a metric scale, points (8 inches).
|
||||
#[cfg(feature = "cgm")]
|
||||
const CGM_SIDE: f64 = 576.0;
|
||||
|
||||
/// Read the first picture of a binary CGM (ISO/IEC 8632-3) through `craft_metafile`.
|
||||
/// `craft_metafile::parse_cgm` comes with craft-libs#5410, so this waits on the `cgm` feature.
|
||||
#[cfg(feature = "cgm")]
|
||||
pub(crate) fn import_cgm(bytes: &[u8]) -> Result<crate::Picture, String> {
|
||||
let cgm = craft_metafile::parse_cgm(bytes, CGM_SIDE).map_err(|e| e.to_string())?;
|
||||
let n = cgm.notes;
|
||||
let mut p = picture::convert(cgm.picture);
|
||||
let notes = [
|
||||
(n.fills_approximated, "hatch, pattern and interpolated fills were filled with their fill color"),
|
||||
(n.more_pictures, "the file holds more than one picture: only the first was read"),
|
||||
(n.cie_colors, "colors in a CIE color model were read as RGB"),
|
||||
(n.text_path, "text set to run left, up or down was set to run right"),
|
||||
(n.restricted_text, "restricted text was set at its character height without fitting it to its box"),
|
||||
(n.character_spacing, "character spacing was not applied"),
|
||||
(n.text_cut, "text past 16,384 characters in one string was cut"),
|
||||
];
|
||||
p.warnings.extend(notes.iter().filter(|(on, _)| *on).map(|(_, w)| (*w).to_string()));
|
||||
if n.damaged_elements > 0 {
|
||||
let k = n.damaged_elements;
|
||||
p.warnings.push(format!(
|
||||
"{k} drawing element{} cut short or describing no shape {} left out",
|
||||
if k == 1 { "" } else { "s" },
|
||||
if k == 1 { "was" } else { "were" }
|
||||
));
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
//! A picture cut short by a reader limit, images and pattern brushes that can't be read, clips
|
||||
//! that can't be applied and raster operations other than a plain copy each add a warning.
|
||||
//! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of
|
||||
//! document.
|
||||
//! document, and [`import_cgm`] the first picture of a binary Computer Graphics Metafile (CGM).
|
||||
//!
|
||||
//! [`painted_layers`] gives the same walk's fills and strokes, layer by layer, to writers of other
|
||||
//! formats.
|
||||
@@ -236,5 +236,34 @@ pub fn import_pict(bytes: &[u8]) -> Result<Picture, String> {
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// Do `bytes` start like a binary CGM: BEGIN METAFILE, then METAFILE VERSION? Always false
|
||||
/// without the `cgm` feature (craft-libs#5410).
|
||||
pub fn is_cgm(bytes: &[u8]) -> bool {
|
||||
#[cfg(feature = "cgm")]
|
||||
return craft_metafile::is_cgm(bytes);
|
||||
#[cfg(not(feature = "cgm"))]
|
||||
{
|
||||
let _ = bytes;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the first picture of a binary Computer Graphics Metafile (CGM, ISO/IEC 8632-3) into a
|
||||
/// document whose one artboard is the picture's VDC extent. Without the `cgm` feature
|
||||
/// (craft-libs#5410), every file is refused.
|
||||
pub fn import_cgm(bytes: &[u8]) -> Result<Picture, String> {
|
||||
#[cfg(feature = "cgm")]
|
||||
{
|
||||
let mut p = import::import_cgm(bytes)?;
|
||||
p.document.limit_depth_noting(&mut p.warnings);
|
||||
Ok(p)
|
||||
}
|
||||
#[cfg(not(feature = "cgm"))]
|
||||
{
|
||||
let _ = bytes;
|
||||
Err("CGM files can't be read in this build".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -11,6 +11,9 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes};
|
||||
|
||||
use crate::*;
|
||||
|
||||
// The CGM reader waits on craft-libs#5410 (the `cgm` feature).
|
||||
#[cfg(feature = "cgm")]
|
||||
mod cgm;
|
||||
mod import;
|
||||
mod pict;
|
||||
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
//! Binary Computer Graphics Metafiles read from hand-built elements: the picture's frame and its
|
||||
//! scale, lines, shapes, arcs, figures, markers, text, cell arrays and clips; elements written in
|
||||
//! partitions; and files that aren't binary CGM, hold no picture, are cut short or hold more than
|
||||
//! one picture.
|
||||
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
use crate::{import_cgm, is_cgm};
|
||||
|
||||
/// Big-endian 16-bit words.
|
||||
fn be(v: &[i16]) -> Vec<u8> {
|
||||
v.iter().flat_map(|x| x.to_be_bytes()).collect()
|
||||
}
|
||||
|
||||
/// One element in the short form (or the long form past 30 bytes, in one partition), padded to
|
||||
/// an even length.
|
||||
fn el(class: u16, id: u16, data: &[u8]) -> Vec<u8> {
|
||||
let mut b = Vec::new();
|
||||
if data.len() < 31 {
|
||||
b.extend(((class << 12) | (id << 5) | data.len() as u16).to_be_bytes());
|
||||
} else {
|
||||
b.extend(((class << 12) | (id << 5) | 31).to_be_bytes());
|
||||
b.extend((data.len() as u16).to_be_bytes());
|
||||
}
|
||||
b.extend(data);
|
||||
if data.len() % 2 == 1 {
|
||||
b.push(0);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// A string parameter.
|
||||
fn s(text: &str) -> Vec<u8> {
|
||||
[vec![text.len() as u8], text.as_bytes().to_vec()].concat()
|
||||
}
|
||||
|
||||
/// A metafile of one picture: `descriptor` after METAFILE VERSION, `picture` after BEGIN PICTURE
|
||||
/// and `body` after BEGIN PICTURE BODY.
|
||||
fn cgm(descriptor: &[Vec<u8>], picture: &[Vec<u8>], body: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut b = el(0, 1, &s("test"));
|
||||
b.extend(el(1, 1, &be(&[1])));
|
||||
descriptor.iter().for_each(|e| b.extend(e));
|
||||
b.extend(el(0, 3, &s("p1")));
|
||||
picture.iter().for_each(|e| b.extend(e));
|
||||
b.extend(el(0, 4, &[]));
|
||||
body.iter().for_each(|e| b.extend(e));
|
||||
b.extend(el(0, 5, &[]));
|
||||
b.extend(el(0, 2, &[]));
|
||||
b
|
||||
}
|
||||
|
||||
/// A VDC extent of 1000 × 500 units: abstract, so 576 × 288 pt (0.576 pt a unit).
|
||||
fn extent() -> Vec<u8> {
|
||||
el(2, 6, &be(&[0, 0, 1000, 500]))
|
||||
}
|
||||
|
||||
/// Direct color selection: colors as 8-bit RGB.
|
||||
fn direct() -> Vec<u8> {
|
||||
el(2, 2, &be(&[1]))
|
||||
}
|
||||
|
||||
/// A VDC point (x, y) in points: y runs up from the bottom of the 1000 × 500 extent.
|
||||
fn pt(x: f64, y: f64) -> Point {
|
||||
Point::new(x * 0.576, (500.0 - y) * 0.576)
|
||||
}
|
||||
|
||||
fn all(d: &Document) -> Vec<Node> {
|
||||
let mut v = vec![];
|
||||
for l in &d.layers {
|
||||
for c in l.children().into_iter().flatten() {
|
||||
c.walk(&mut |n| v.push(n.clone()));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn paths(d: &Document) -> Vec<Node> {
|
||||
all(d).into_iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })).collect()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: Rect, tol: f64) -> bool {
|
||||
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() <= tol)
|
||||
}
|
||||
|
||||
fn fill_rgb(n: &Node) -> Option<[u8; 3]> {
|
||||
n.appearance.items.iter().find_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => f.paint.color().map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn stroke(n: &Node) -> Option<([u8; 3], f64)> {
|
||||
n.appearance.items.iter().find_map(|i| match i {
|
||||
AppearanceItem::Stroke(s) => s.paint.color().map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
([r, g, b], s.width)
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn images(d: &Document) -> Vec<(Node, image::RgbaImage)> {
|
||||
all(d)
|
||||
.into_iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Image(im) => {
|
||||
let decoded = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap();
|
||||
Some((n.clone(), image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picture_opens_on_its_extent_with_the_first_corner_at_the_bottom_left() {
|
||||
let bytes = cgm(&[], &[extent(), direct()], &[el(5, 22, &be(&[1])), el(5, 23, &[255, 0, 0]), el(4, 11, &be(&[100, 100, 300, 200]))]);
|
||||
assert!(is_cgm(&bytes));
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
assert!(p.warnings.is_empty(), "{:?}", p.warnings);
|
||||
assert!(near(p.document.artboards[0].rect, Rect::new(0.0, 0.0, 576.0, 288.0), 1e-9));
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 1, "{v:?}");
|
||||
assert_eq!(fill_rgb(&v[0]), Some([255, 0, 0]));
|
||||
assert!(v[0].appearance.stroke().is_none(), "edges are off by default");
|
||||
let b = v[0].geometric_bounds().unwrap();
|
||||
assert!(near(b, Rect::from_points(pt(100.0, 100.0), pt(300.0, 200.0)), 1e-4), "{b:?}");
|
||||
|
||||
// An extent whose first corner is its top left turns the picture over: the same rectangle
|
||||
// is then as far from the top as it was from the bottom.
|
||||
let flipped = cgm(&[], &[el(2, 6, &be(&[0, 500, 1000, 0])), direct()], &[el(5, 22, &be(&[1])), el(4, 11, &be(&[100, 100, 300, 200]))]);
|
||||
let b = paths(&import_cgm(&flipped).unwrap().document)[0].geometric_bounds().unwrap();
|
||||
assert!(near(b, Rect::new(57.6, 57.6, 172.8, 115.2), 1e-4), "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_metric_picture_keeps_its_size() {
|
||||
// 0.1 mm a unit: 100 × 50 mm.
|
||||
let metric = el(2, 1, &[be(&[1]), 0.1f32.to_be_bytes().to_vec()].concat());
|
||||
let p = import_cgm(&cgm(&[], &[metric, extent()], &[el(4, 1, &be(&[0, 0, 1000, 500]))])).unwrap();
|
||||
let size = p.document.artboards[0].rect.size();
|
||||
let mm = 72.0 / 25.4;
|
||||
assert!((size.width - 100.0 * mm).abs() < 1e-3 && (size.height - 50.0 * mm).abs() < 1e-3, "{size:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_take_their_width_color_type_caps_and_joins() {
|
||||
let bytes = cgm(
|
||||
&[],
|
||||
// Widths in VDC units.
|
||||
&[extent(), el(2, 3, &be(&[0])), el(2, 17, &be(&[-1, 200, 1, 3]))],
|
||||
&[
|
||||
// Color 9 from the color table: green.
|
||||
el(5, 34, &[9, 0, 200, 0]),
|
||||
el(5, 4, &[9]),
|
||||
el(5, 3, &be(&[10])),
|
||||
el(5, 2, &be(&[2])),
|
||||
el(5, 37, &be(&[2, 2])),
|
||||
el(5, 38, &be(&[4])),
|
||||
el(4, 1, &be(&[0, 0, 500, 0, 500, 250])),
|
||||
// Default color index 1 (black), a disjoint polyline: two separate lines.
|
||||
el(5, 4, &[1]),
|
||||
el(5, 2, &be(&[1])),
|
||||
el(4, 2, &be(&[0, 400, 100, 400, 200, 400, 300, 400])),
|
||||
// Line type -1 as the picture defines it: 200 units, a quarter on and three off.
|
||||
el(5, 2, &be(&[-1])),
|
||||
el(4, 1, &be(&[0, 450, 1000, 450])),
|
||||
],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 3, "{v:?}");
|
||||
let dash = v[2].appearance.stroke().unwrap().dash.clone().unwrap();
|
||||
assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 28.8).abs() < 1e-3 && (dash.pattern[1] - 86.4).abs() < 1e-3, "{dash:?}");
|
||||
let (rgb, w) = stroke(&v[0]).unwrap();
|
||||
assert_eq!(rgb, [0, 200, 0]);
|
||||
assert!((w - 5.76).abs() < 1e-4, "{w}");
|
||||
let st = v[0].appearance.stroke().unwrap();
|
||||
assert!(st.dash.as_ref().is_some_and(|d| d.is_dashed()), "line type 2 is dashed");
|
||||
assert_eq!((st.cap, st.join), (vectorcraft_doc::LineCap::Butt, vectorcraft_doc::LineJoin::Bevel));
|
||||
let NodeKind::Path { path, .. } = &v[1].kind else { panic!("a path") };
|
||||
assert_eq!(path.subpaths.len(), 2);
|
||||
assert_eq!(stroke(&v[1]).unwrap().0, [0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_ellipses_and_arcs_are_curves_in_their_place() {
|
||||
let bytes = cgm(
|
||||
&[],
|
||||
&[extent()],
|
||||
&[
|
||||
el(5, 22, &be(&[1])),
|
||||
// A circle of radius 100 at (500, 250).
|
||||
el(4, 12, &be(&[500, 250, 100])),
|
||||
// An ellipse 200 across and 50 high at (200, 100).
|
||||
el(4, 17, &be(&[200, 100, 300, 100, 200, 125])),
|
||||
// A half circle from (900, 250) through (800, 350) to (700, 250): the top half.
|
||||
el(4, 13, &be(&[900, 250, 800, 350, 700, 250])),
|
||||
// A quarter circle around (100, 400), from east to north, closed as a pie.
|
||||
el(4, 16, &be(&[100, 400, 1, 0, 0, 1, 50, 0])),
|
||||
],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
assert!(p.warnings.is_empty(), "{:?}", p.warnings);
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 4, "{v:?}");
|
||||
// Cubic Béziers stand in for the curves: within 0.03% of the radius.
|
||||
let tol = 0.05;
|
||||
assert!(near(v[0].geometric_bounds().unwrap(), Rect::from_points(pt(400.0, 150.0), pt(600.0, 350.0)), tol));
|
||||
assert!(near(v[1].geometric_bounds().unwrap(), Rect::from_points(pt(100.0, 75.0), pt(300.0, 125.0)), tol));
|
||||
assert!(near(v[2].geometric_bounds().unwrap(), Rect::from_points(pt(700.0, 250.0), pt(900.0, 350.0)), tol));
|
||||
assert!(v[2].appearance.fill().is_none(), "an open arc is stroked");
|
||||
assert!(near(v[3].geometric_bounds().unwrap(), Rect::from_points(pt(100.0, 400.0), pt(150.0, 450.0)), tol));
|
||||
assert!(fill_rgb(&v[3]).is_some(), "a closed arc is filled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edges_outline_shapes_and_polygon_sets_skip_their_hidden_edges() {
|
||||
let bytes = cgm(
|
||||
&[],
|
||||
&[extent(), direct()],
|
||||
&[
|
||||
el(5, 22, &be(&[1])),
|
||||
el(5, 30, &be(&[1])),
|
||||
el(5, 29, &[0, 0, 255]),
|
||||
// Two squares; the first one's left edge (from its last point) is hidden.
|
||||
el(4, 8, &be(&[0, 0, 1, 100, 0, 1, 100, 100, 1, 0, 100, 2, 200, 0, 1, 300, 0, 1, 300, 100, 1, 200, 100, 3])),
|
||||
],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 2, "a fill and its edges: {v:?}");
|
||||
let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") };
|
||||
assert_eq!(path.subpaths.len(), 2, "both squares fill");
|
||||
assert_eq!(stroke(&v[1]).unwrap().0, [0, 0, 255]);
|
||||
let NodeKind::Path { path, .. } = &v[1].kind else { panic!("a path") };
|
||||
// The first square's three visible edges are one open line, and the second square is one
|
||||
// closed outline.
|
||||
assert_eq!(path.subpaths.len(), 2, "one outline for each square");
|
||||
assert_eq!(path.subpaths.iter().filter(|s| s.closed).count(), 1, "{:?}", path.subpaths);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_figure_fills_its_lines_as_one_shape() {
|
||||
let bytes = cgm(
|
||||
&[],
|
||||
&[extent()],
|
||||
&[
|
||||
el(5, 22, &be(&[1])),
|
||||
el(0, 8, &[]),
|
||||
el(4, 1, &be(&[0, 0, 100, 0])),
|
||||
el(4, 15, &be(&[100, 50, 0, -1, 0, 1, 50])),
|
||||
el(4, 1, &be(&[100, 100, 0, 100])),
|
||||
el(0, 9, &[]),
|
||||
],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 1, "{v:?}");
|
||||
assert!(fill_rgb(&v[0]).is_some() && v[0].appearance.stroke().is_none());
|
||||
let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") };
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
assert!(near(v[0].geometric_bounds().unwrap(), Rect::from_points(pt(0.0, 0.0), pt(150.0, 100.0)), 0.05));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_comes_in_as_point_type_at_its_character_height() {
|
||||
let bytes = cgm(
|
||||
&[el(1, 13, &[s("Times-Roman"), s("Helvetica-BoldOblique")].concat())],
|
||||
&[extent()],
|
||||
&[
|
||||
el(5, 10, &be(&[2])),
|
||||
el(5, 15, &be(&[70])),
|
||||
// Not final: the rest of the string follows in APPEND TEXT.
|
||||
el(4, 4, &[be(&[100, 200, 0]), s("Hel")].concat()),
|
||||
el(4, 6, &[be(&[1]), s("lo")].concat()),
|
||||
// Restricted text: its box is not applied, and a warning says so.
|
||||
el(4, 5, &[be(&[300, 70, 100, 50, 1]), s("Box")].concat()),
|
||||
],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
assert_eq!(p.warnings, ["restricted text was set at its character height without fitting it to its box"]);
|
||||
let texts: Vec<_> = all(&p.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).collect();
|
||||
assert_eq!(texts.len(), 2);
|
||||
let NodeKind::Text(t) = &texts[0].kind else { panic!("text") };
|
||||
assert_eq!(t.plain_text(), "Hello");
|
||||
let st = &t.runs[0].style;
|
||||
assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Helvetica", "Bold Italic"));
|
||||
// The character height (70 units, 40.32 pt) is the cap height: 0.7 of the size.
|
||||
assert!((st.size - 57.6).abs() < 1e-3, "{}", st.size);
|
||||
assert!((t.xf.translation().to_point() - pt(100.0, 200.0)).hypot() < 1e-3, "{:?}", t.xf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_reader_left_out_or_set_differently_is_warned_about() {
|
||||
let bytes = cgm(
|
||||
&[],
|
||||
&[extent()],
|
||||
&[
|
||||
// Character spacing 0.5, then a rectangle with one corner and a circle without its radius.
|
||||
el(5, 13, &[0, 0, 0x80, 0]),
|
||||
el(4, 4, &[be(&[0, 0, 1]), s("spaced")].concat()),
|
||||
el(4, 11, &be(&[0, 0])),
|
||||
el(4, 12, &be(&[10, 10])),
|
||||
el(4, 11, &be(&[0, 0, 10, 10])),
|
||||
],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
assert!(p.warnings.iter().any(|w| w == "character spacing was not applied"), "{:?}", p.warnings);
|
||||
assert!(p.warnings.iter().any(|w| w == "2 drawing elements cut short or describing no shape were left out"), "{:?}", p.warnings);
|
||||
assert_eq!(paths(&p.document).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_arrays_become_images_packed_or_run_length() {
|
||||
// 2 × 2 cells over (0, 0) to (200, 100), first row along the bottom: red, green, then blue,
|
||||
// white.
|
||||
let corners = be(&[0, 0, 200, 100, 200, 0]);
|
||||
let packed = [corners.clone(), be(&[2, 2, 8, 1]), vec![255, 0, 0, 0, 255, 0], vec![0, 0, 255, 255, 255, 255]].concat();
|
||||
// Runs: a count (16 bits) and a color.
|
||||
let run = |color: [u8; 3]| [be(&[1]), color.to_vec()].concat();
|
||||
let runs = [corners.clone(), be(&[2, 2, 8, 0]), run([255, 0, 0]), run([0, 255, 0]), run([0, 0, 255]), run([255, 255, 255])].concat();
|
||||
// 4-bit indexed cells: each row of two cells takes one byte and is padded to a word.
|
||||
let indexed = [corners, be(&[2, 2, 4, 1]), vec![0x23, 0, 0x41, 0]].concat();
|
||||
for data in [packed, runs] {
|
||||
let p = import_cgm(&cgm(&[], &[extent(), direct()], &[el(4, 9, &data)])).unwrap();
|
||||
assert!(p.warnings.is_empty(), "{:?}", p.warnings);
|
||||
let imgs = images(&p.document);
|
||||
assert_eq!(imgs.len(), 1);
|
||||
let (n, px) = &imgs[0];
|
||||
assert_eq!(px.dimensions(), (2, 2));
|
||||
assert_eq!(px.get_pixel(0, 0).0, [255, 0, 0, 255]);
|
||||
assert_eq!(px.get_pixel(1, 0).0, [0, 255, 0, 255]);
|
||||
assert_eq!(px.get_pixel(0, 1).0, [0, 0, 255, 255]);
|
||||
// The first row is at the bottom of the picture: drawn upward from P.
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!(near(b, Rect::from_points(pt(0.0, 0.0), pt(200.0, 100.0)), 1e-3), "{b:?}");
|
||||
}
|
||||
// Indexed cells through the default color table.
|
||||
let p = import_cgm(&cgm(&[], &[extent()], &[el(4, 9, &indexed)])).unwrap();
|
||||
let px = &images(&p.document)[0].1;
|
||||
let row = |y| [px.get_pixel(0, y).0, px.get_pixel(1, y).0];
|
||||
assert_eq!(row(0), [[255, 0, 0, 255], [0, 255, 0, 255]]);
|
||||
assert_eq!(row(1), [[0, 0, 255, 255], [0, 0, 0, 255]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markers_are_drawn_at_their_points() {
|
||||
let bytes = cgm(&[], &[extent()], &[el(5, 6, &be(&[4])), el(4, 3, &be(&[100, 100, 900, 400]))]);
|
||||
let v = paths(&import_cgm(&bytes).unwrap().document);
|
||||
assert_eq!(v.len(), 2);
|
||||
// A nominal marker is 1/100 of the longer side across: 5.76 pt.
|
||||
let b = v[1].geometric_bounds().unwrap();
|
||||
assert!((b.center() - pt(900.0, 400.0)).hypot() < 1e-3 && (b.width() - 5.76).abs() < 1e-2, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clip_rectangle_clips_what_follows() {
|
||||
let bytes = cgm(
|
||||
&[],
|
||||
&[extent()],
|
||||
&[el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 100, 100])), el(3, 5, &be(&[0, 0, 500, 250])), el(4, 11, &be(&[0, 0, 1000, 500]))],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
let layer = p.document.layers[0].children().unwrap();
|
||||
assert!(matches!(layer[0].kind, NodeKind::Path { .. }), "the picture's own extent clips nothing");
|
||||
let NodeKind::Group { children, clip: true } = &layer[1].kind else { panic!("a clipping group: {:?}", layer[1].kind) };
|
||||
assert!(near(children[0].geometric_bounds().unwrap(), Rect::from_points(pt(0.0, 0.0), pt(500.0, 250.0)), 1e-3));
|
||||
// With the clip indicator off, nothing is clipped.
|
||||
let off = [el(3, 5, &be(&[0, 0, 500, 250])), el(3, 6, &be(&[0])), el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 1000, 500]))];
|
||||
let off = cgm(&[], &[extent()], &off);
|
||||
let p = import_cgm(&off).unwrap();
|
||||
assert!(matches!(p.document.layers[0].children().unwrap()[0].kind, NodeKind::Path { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn precisions_real_coordinates_partitions_and_default_replacements() {
|
||||
// Real VDC (fixed point 16.16), a line width set in the metafile's defaults, and a polyline
|
||||
// in two partitions.
|
||||
let fixed = |v: f64| ((v * 65536.0) as i32).to_be_bytes().to_vec();
|
||||
let mdr = el(1, 12, &[el(2, 3, &be(&[0])), el(5, 3, &fixed(100.0))].concat());
|
||||
let real_extent = el(2, 6, &[fixed(0.0), fixed(0.0), fixed(1000.0), fixed(500.0)].concat());
|
||||
let points: Vec<u8> = [0.0, 0.0, 500.0, 0.0, 500.0, 250.0, 1000.0, 500.0].iter().flat_map(|v| fixed(*v)).collect();
|
||||
let mut body = vec![];
|
||||
body.extend(((4u16 << 12) | (1 << 5) | 31).to_be_bytes());
|
||||
body.extend((0x8000u16 | 16).to_be_bytes());
|
||||
body.extend(&points[..16]);
|
||||
body.extend(16u16.to_be_bytes());
|
||||
body.extend(&points[16..]);
|
||||
let bytes = cgm(&[el(1, 3, &be(&[1])), mdr], &[real_extent], &[body]);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
assert!(p.warnings.is_empty(), "{:?}", p.warnings);
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 1);
|
||||
assert!(near(v[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 576.0, 288.0), 1e-3));
|
||||
assert!((stroke(&v[0]).unwrap().1 - 57.6).abs() < 1e-3, "{:?}", stroke(&v[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_are_not_binary_cgm_are_refused() {
|
||||
assert_eq!(import_cgm(b"").unwrap_err(), "not a CGM file");
|
||||
assert_eq!(import_cgm(&[0; 64]).unwrap_err(), "not a CGM file");
|
||||
assert!(!is_cgm(&[0; 64]));
|
||||
let clear = import_cgm(b"BEGMF 'drawing';\nmfversion 1;\n").unwrap_err();
|
||||
assert!(clear.contains("only binary CGM files"), "{clear}");
|
||||
// A metafile without a picture.
|
||||
let mut b = el(0, 1, &s("empty"));
|
||||
b.extend(el(1, 1, &be(&[1])));
|
||||
b.extend(el(0, 2, &[]));
|
||||
assert!(is_cgm(&b));
|
||||
assert_eq!(import_cgm(&b).unwrap_err(), "the CGM file holds no picture");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picture_cut_short_keeps_what_came_before() {
|
||||
let full = cgm(&[], &[extent()], &[el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 100, 100])), el(4, 11, &be(&[200, 0, 300, 100]))]);
|
||||
// Cut inside the second rectangle.
|
||||
let cut = &full[..full.len() - 10];
|
||||
let p = import_cgm(cut).unwrap();
|
||||
assert_eq!(paths(&p.document).len(), 1);
|
||||
assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_first_picture_is_read() {
|
||||
let mut b = cgm(&[], &[extent()], &[el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 100, 100]))]);
|
||||
// Drop END METAFILE and add a second picture.
|
||||
b.truncate(b.len() - 2);
|
||||
b.extend(el(0, 3, &s("p2")));
|
||||
b.extend(el(0, 4, &[]));
|
||||
b.extend(el(4, 11, &be(&[0, 0, 500, 500])));
|
||||
b.extend(el(0, 5, &[]));
|
||||
b.extend(el(0, 2, &[]));
|
||||
let p = import_cgm(&b).unwrap();
|
||||
assert_eq!(paths(&p.document).len(), 1);
|
||||
assert!(p.warnings.iter().any(|w| w.contains("only the first")), "{:?}", p.warnings);
|
||||
}
|
||||
@@ -108,6 +108,7 @@ egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
|
||||
egui_extras = { workspace = true }
|
||||
vectorcraft-apischema = { workspace = true }
|
||||
vectorcraft-testkit = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true, features = ["swatch-scans"] }
|
||||
vectorcraft-tools = { workspace = true, features = ["testing"] }
|
||||
# A variable font built in code (no font file is committed).
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
|
||||
@@ -3,12 +3,14 @@
|
||||
//! filter, into the colours themselves (`addon.color.filter`); below, under Inks, it opens Duotone's
|
||||
//! dialog and Print Ink Fixes' (`addon.color.printFixes`). The submenu applies the add-on's live
|
||||
//! effects, Duotone and Vector Halftone among them (Effect › Color Effects has them too), opens
|
||||
//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]), Create Swatch Legend ([`legend`]) and
|
||||
//! Randomize Fill Colors ([`random_fill`]) and opens the panel.
|
||||
//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]), Create Swatch Legend ([`legend`]), Create
|
||||
//! Screen Print Marks ([`screen_marks`]) and Randomize Fill Colors ([`random_fill`]) and opens the
|
||||
//! panel.
|
||||
|
||||
pub mod legend;
|
||||
pub mod nearest;
|
||||
pub mod random_fill;
|
||||
pub mod screen_marks;
|
||||
|
||||
use craft::imaging::ui::adjust::{AdjustContext, AdjustField, AdjustSliders};
|
||||
use craft::menu::Node;
|
||||
@@ -113,6 +115,7 @@ pub fn menu() -> Vec<Node> {
|
||||
cmd(print_fixes()),
|
||||
c("Find Nearest Swatch…", nearest::COMMAND),
|
||||
c("Create Swatch Legend…", legend::COMMAND),
|
||||
c("Create Screen Print Marks…", screen_marks::COMMAND),
|
||||
Sep,
|
||||
// Each selected object's stroke takes its own fill, or the other way (#5530).
|
||||
cp("Apply Fill to Stroke", "addon.color.fillToStroke", json!({})),
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Create Screen Print Marks in the interface (Object › Plug-ins › Color Effects › Create Screen
|
||||
//! Print Marks…): a dialog for where the registration targets go, their size, stroke weight, inset
|
||||
//! and ink, the spot ink and file lines with their type size and place, and whether every artboard
|
||||
//! gets marks. It previews on the canvas and runs `addon.color.screenMarks` on OK.
|
||||
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::addons::dialogs::{self, Spec};
|
||||
use crate::canvas::rulers::{general_lengths, stroke_lengths, type_lengths};
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.color.screenMarks";
|
||||
/// The target positions: (the command's name, the dialog's label), in the command's order.
|
||||
pub const POSITIONS: [(&str, &str); 8] = [
|
||||
("topLeft", "Top Left"),
|
||||
("top", "Top Center"),
|
||||
("topRight", "Top Right"),
|
||||
("left", "Left Center"),
|
||||
("right", "Right Center"),
|
||||
("bottomLeft", "Bottom Left"),
|
||||
("bottom", "Bottom Center"),
|
||||
("bottomRight", "Bottom Right"),
|
||||
];
|
||||
/// The positions ticked when the dialog opens: the command's default.
|
||||
const TICKED: [&str; 4] = ["top", "bottom", "left", "right"];
|
||||
|
||||
/// How the dialog's values reach the command.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// The positions ticked in `fields`, in the command's order.
|
||||
fn ticked(fields: &DialogFields) -> Vec<&'static str> {
|
||||
POSITIONS.iter().filter(|(key, _)| fields.bool(key).unwrap_or(false)).map(|(key, _)| *key).collect()
|
||||
}
|
||||
|
||||
/// Whether `fields` ask for anything to be drawn: a target, the file line, or the spot ink line of a document
|
||||
/// that has spot inks (`spots`).
|
||||
fn draws(fields: &DialogFields, spots: bool) -> bool {
|
||||
!ticked(fields).is_empty() || (spots && fields.bool("inks").unwrap_or(false)) || fields.bool("info").unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The command's params from the dialog's fields.
|
||||
pub(crate) fn params(fields: &DialogFields) -> Value {
|
||||
json!({
|
||||
"positions": ticked(fields),
|
||||
"size": fields.number("size").unwrap_or(36.0),
|
||||
"weight": fields.number("weight").unwrap_or(1.0),
|
||||
"inset": fields.number("inset").unwrap_or(18.0),
|
||||
"ink": fields.text("ink").unwrap_or(REGISTRATION),
|
||||
"inks": fields.bool("inks").unwrap_or(false),
|
||||
"info": fields.bool("info").unwrap_or(false),
|
||||
"textSize": fields.number("textSize").unwrap_or(9.0),
|
||||
"textPlace": fields.text("textPlace").unwrap_or("bottom"),
|
||||
"textAlign": fields.text("textAlign").unwrap_or("left"),
|
||||
"allArtboards": fields.bool("allArtboards").unwrap_or(false),
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens Create Screen Print Marks' dialog on the command's defaults. The ink list is [Registration] and the
|
||||
/// document's spot swatches, read once, when it opens.
|
||||
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let mut inks = vec![REGISTRATION.to_string()];
|
||||
if let Some(st) = app.session.active() {
|
||||
inks.extend(
|
||||
st.doc
|
||||
.swatches_iter()
|
||||
.filter(|w| w.spot && w.name != REGISTRATION && w.tint_of().is_none() && w.paint.color().is_some())
|
||||
.map(|w| w.name.clone()),
|
||||
);
|
||||
}
|
||||
let mut fields = DialogFields::from_pairs([
|
||||
("size", FieldValue::Number(36.0)),
|
||||
("weight", FieldValue::Number(1.0)),
|
||||
("inset", FieldValue::Number(18.0)),
|
||||
("ink", FieldValue::Text(REGISTRATION.into())),
|
||||
("inks", FieldValue::Bool(false)),
|
||||
("info", FieldValue::Bool(false)),
|
||||
("textSize", FieldValue::Number(9.0)),
|
||||
("textPlace", FieldValue::Text("bottom".into())),
|
||||
("textAlign", FieldValue::Text("left".into())),
|
||||
("allArtboards", FieldValue::Bool(false)),
|
||||
]);
|
||||
for (key, _) in POSITIONS {
|
||||
fields.set(key, FieldValue::Bool(TICKED.contains(&key)));
|
||||
}
|
||||
let (lengths, strokes, types) = (general_lengths(app), stroke_lengths(app), type_lengths(app));
|
||||
dialogs::open(app, &SPEC, fields, move |fields| {
|
||||
let ink_choices = inks.iter().map(|name| (name.clone(), name.clone().into())).collect();
|
||||
let places = vec![("bottom".to_string(), tl!("Bottom").into()), ("top".to_string(), tl!("Top").into())];
|
||||
let aligns = vec![("left".to_string(), tl!("Left").into()), ("right".to_string(), tl!("Right").into())];
|
||||
let mut rows = vec![Param::section(tl!("Targets:"))];
|
||||
rows.extend(POSITIONS.iter().map(|&(key, label)| Param::new(key, tl!(label), ParamKind::bool(TICKED.contains(&key)))));
|
||||
rows.extend([
|
||||
Param::number("size", tl!("Size:"), 36.0, 1.0, 2).length(lengths).bounds(Some(4.0), Some(1000.0)),
|
||||
Param::number("weight", tl!("Weight:"), 1.0, 0.1, 2).length(strokes).bounds(Some(0.1), Some(20.0)),
|
||||
Param::number("inset", tl!("Inset:"), 18.0, 1.0, 2).length(lengths).bounds(Some(-1000.0), Some(1000.0)),
|
||||
Param::new("ink", tl!("Ink:"), ParamKind::choice(ink_choices, Some(REGISTRATION.into()))),
|
||||
Param::section(tl!("Text:")),
|
||||
Param::new("inks", tl!("Spot Ink Names"), ParamKind::bool(false)),
|
||||
Param::new("info", tl!("File Name and Date"), ParamKind::bool(false)),
|
||||
Param::number("textSize", tl!("Type Size:"), 9.0, 1.0, 1).length(types).bounds(Some(4.0), Some(72.0)),
|
||||
Param::new("textPlace", tl!("Place:"), ParamKind::choice(places, Some("bottom".into()))),
|
||||
Param::new("textAlign", tl!("Align:"), ParamKind::choice(aligns, Some("left".into()))),
|
||||
Param::new("allArtboards", tl!("All Artboards"), ParamKind::bool(false)),
|
||||
]);
|
||||
let ok = draws(fields, inks.len() > 1);
|
||||
ParamDialog::new(COMMAND, tl!("Create Screen Print Marks"), rows)
|
||||
.ok_enabled(ok)
|
||||
.ok_reason(tl!("Tick a target or a line of text.").into())
|
||||
.values(Bind::bound(fields))
|
||||
.previews(true)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,145 @@
|
||||
use craft::behavior::Mixed;
|
||||
use craft::ui::contract::Role;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue};
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::addons::dialogs::tests as host;
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
/// The marks group of the active document's marks layer: its targets' rings' widths and its type lines.
|
||||
fn marks(app: &VectorcraftApp) -> Option<(Vec<f64>, Vec<String>)> {
|
||||
let doc = &app.session.active()?.doc;
|
||||
let layer = doc.layers.iter().find(|l| l.name.as_deref() == Some("Screen Print Marks"))?;
|
||||
let group: &Node = layer.children()?.first()?;
|
||||
let kids = group.children()?;
|
||||
let rings = kids
|
||||
.iter()
|
||||
.filter(|n| n.name.as_deref() == Some("Registration Target"))
|
||||
.map(|t| t.children().unwrap()[0].geometric_bounds().unwrap().width())
|
||||
.collect();
|
||||
let lines = kids
|
||||
.iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => Some(t.plain_text()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
Some((rings, lines))
|
||||
}
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
|
||||
app.run("swatch.new", json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// Keyboard and checkbox edits reach the preview; Cancel restores the drawing, while OK with Preview off applies the
|
||||
/// same values in one undo step.
|
||||
#[test]
|
||||
fn keyboard_and_checkbox_edits_reach_the_preview_ok_and_cancel() {
|
||||
for commit in [false, true] {
|
||||
let app = app();
|
||||
let before = app.session.active().unwrap().doc.clone();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 1000.0));
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
assert_eq!(panel.toggled("Preview"), Some(Mixed::Same(true)), "Preview starts on");
|
||||
assert!(panel.app().session.in_interaction(), "the opening marks are previewed");
|
||||
assert_eq!(marks(&panel.app()).map(|(rings, _)| rings.len()), Some(4), "four targets on opening");
|
||||
if commit {
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
}
|
||||
panel.click_role("Left Center", Role::CHECK_BOX);
|
||||
panel.click_role("Right Center", Role::CHECK_BOX);
|
||||
panel.click_role("Spot Ink Names", Role::CHECK_BOX);
|
||||
panel.click_role("Size", Role::SPIN_BUTTON);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text("40 pt");
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
let edited = |app: &VectorcraftApp| {
|
||||
let (rings, lines) = marks(app).expect("the marks layer");
|
||||
assert_eq!(rings.len(), 2, "the unticked sides draw no target");
|
||||
assert!(rings.iter().all(|w| (w - 20.0).abs() < 1e-6), "the typed size reaches the targets: {rings:?}");
|
||||
assert_eq!(lines, ["Plate Red"], "the spot ink line");
|
||||
};
|
||||
if commit {
|
||||
assert!(panel.app().session.active().unwrap().doc == before, "Preview off leaves the drawing alone");
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
edited(&panel.app());
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
} else {
|
||||
edited(&panel.app());
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "Preview adds no undo step");
|
||||
panel.click("Cancel");
|
||||
panel.frame();
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
assert!(panel.app().session.active().unwrap().doc == before, "Cancel or Undo restores the original drawing");
|
||||
assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// With no target ticked and no line, OK is off; a spot ink picked in the dialog strokes the targets.
|
||||
#[test]
|
||||
fn ok_needs_something_to_draw_and_the_ink_list_offers_the_spot_swatches() {
|
||||
let mut app = crate::testing::windowed(app());
|
||||
host::open_item(&mut app, "Color Effects", "Create Screen Print Marks…");
|
||||
let id = host::dialog_id(&app);
|
||||
for key in ["top", "bottom", "left", "right"] {
|
||||
host::set(&app, id, key, json!(false));
|
||||
}
|
||||
host::frame(&mut app);
|
||||
assert!(!host::confirm(&app, id), "nothing to draw: OK is off");
|
||||
host::set(&app, id, "topLeft", json!(true));
|
||||
host::set(&app, id, "ink", json!("Plate Red"));
|
||||
host::frame(&mut app);
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert!(!app.any_dialog_open());
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
let layer = &doc.layers[0];
|
||||
assert!(layer.locked, "the marks layer is locked at the bottom");
|
||||
let target = &layer.children().unwrap()[0].children().unwrap()[0];
|
||||
let ring = &target.children().unwrap()[0];
|
||||
let linked = match ring.appearance.stroke_paint() {
|
||||
vectorcraft_color::Paint::Solid { swatch, .. } => swatch,
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!(linked.as_deref(), Some("Plate Red"));
|
||||
}
|
||||
|
||||
/// The ticked positions go in the command's order; every other value goes as the dialog holds it.
|
||||
#[test]
|
||||
fn params_lists_the_ticked_positions_in_order() {
|
||||
let fields = DialogFields::from_pairs([
|
||||
("bottomRight", FieldValue::Bool(true)),
|
||||
("topLeft", FieldValue::Bool(true)),
|
||||
("top", FieldValue::Bool(false)),
|
||||
("textPlace", FieldValue::Text("top".into())),
|
||||
("info", FieldValue::Bool(true)),
|
||||
]);
|
||||
let p = super::params(&fields);
|
||||
assert_eq!(p["positions"], json!(["topLeft", "bottomRight"]));
|
||||
assert_eq!(p["textPlace"], json!("top"));
|
||||
assert_eq!(p["info"], json!(true));
|
||||
assert_eq!(p["ink"], json!("[Registration]"));
|
||||
assert!(p.get("time").is_none(), "the date is the time of the run");
|
||||
}
|
||||
|
||||
/// Spot Ink Names alone draws something only in a document with spot inks.
|
||||
#[test]
|
||||
fn the_spot_ink_line_alone_needs_spot_inks() {
|
||||
let fields = DialogFields::from_pairs([("inks", FieldValue::Bool(true))]);
|
||||
assert!(!super::draws(&fields, false));
|
||||
assert!(super::draws(&fields, true));
|
||||
}
|
||||
@@ -185,6 +185,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Resul
|
||||
typetools::numbers::COMMAND => typetools::numbers::open,
|
||||
color::legend::COMMAND => color::legend::open,
|
||||
color::nearest::COMMAND => color::nearest::open,
|
||||
color::screen_marks::COMMAND => color::screen_marks::open,
|
||||
color::random_fill::COMMAND => color::random_fill::open,
|
||||
select::COMMAND => select::open,
|
||||
select::points_only::COMMAND => select::points_only::open,
|
||||
|
||||
@@ -13,9 +13,10 @@ use std::sync::Arc;
|
||||
|
||||
use craft::automation::ControlChannel;
|
||||
use craft::automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem};
|
||||
use craft::control::agents::{AgentFolders, folders_answer};
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::file_access::{self, AutomationRoots};
|
||||
use vectorcraft_engine::file_access::{self, Access, AutomationRoots};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
@@ -112,6 +113,30 @@ fn roots_for(settings: &AgentSettings, default: Option<&std::path::Path>) -> Res
|
||||
Ok(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none))
|
||||
}
|
||||
|
||||
/// `agent.folders`: the folders the request's own automation roots let it open and save in, as the
|
||||
/// `agent_folders` tool shows them, with `read_folders` / `write_folders` listing every folder of a
|
||||
/// kind that has several (`--automation-read-root` given twice). Roots that grant nothing (a saved
|
||||
/// folder the window can't use) list no folder; a request that isn't confined says so.
|
||||
pub(crate) fn folders(roots: Option<&AutomationRoots>) -> Value {
|
||||
let Some(roots) = roots else {
|
||||
return json!({"read_folder": null, "write_folder": null, "unrestricted": true});
|
||||
};
|
||||
let (read, write): (Vec<&std::path::Path>, Vec<&std::path::Path>) =
|
||||
(roots.folders(Access::Read).collect(), roots.folders(Access::Write).collect());
|
||||
let mut folders = AgentFolders::default();
|
||||
folders.read = read.first().map(|p| p.to_path_buf());
|
||||
folders.write = write.first().map(|p| p.to_path_buf());
|
||||
let mut answer = folders_answer(&folders);
|
||||
for (key, all) in [("read_folders", &read), ("write_folders", &write)] {
|
||||
if all.len() > 1
|
||||
&& let Some(o) = answer.as_object_mut()
|
||||
{
|
||||
o.insert(key.into(), json!(all.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>()));
|
||||
}
|
||||
}
|
||||
answer
|
||||
}
|
||||
|
||||
/// Once per pass: brings the link in line with the launcher's switch and the saved settings. The
|
||||
/// control server starts, moves or stops; while it runs, its requests are the app's control channel
|
||||
/// and run inside the agent folders ([`VectorcraftApp::run_control`]).
|
||||
|
||||
@@ -54,8 +54,10 @@ fn app_with_agents(base: &Path, switch: AgentSwitch) -> (VectorcraftApp, Arc<Mut
|
||||
}
|
||||
|
||||
/// One request from an agent's client through the link's server, answered by the app's frames: the client
|
||||
/// thread hands its reply back over a channel, and the app runs a pass while it waits.
|
||||
/// thread hands its reply back over a channel, and the app runs passes until that reply arrives. The
|
||||
/// client's own call timeout ends a call the app never answers with an error, so the reply always comes.
|
||||
fn agent_request(app: &mut VectorcraftApp, client: &mut Option<ControlClient>, method: &str, params: Value) -> Result<Value, String> {
|
||||
use std::sync::mpsc::TryRecvError;
|
||||
let ctx = app.ui_ctx.clone().unwrap_or_default();
|
||||
let mut c = client.take().expect("a connected client");
|
||||
let sent = method.to_owned();
|
||||
@@ -64,15 +66,18 @@ fn agent_request(app: &mut VectorcraftApp, client: &mut Option<ControlClient>, m
|
||||
let r = c.call(&sent, params);
|
||||
let _ = done.send((c, r));
|
||||
});
|
||||
for _ in 0..2000 {
|
||||
loop {
|
||||
app.run_control(&ctx);
|
||||
app.poll_input(&ctx);
|
||||
if let Ok((c, r)) = reply.recv_timeout(std::time::Duration::from_millis(5)) {
|
||||
*client = Some(c);
|
||||
return r;
|
||||
match reply.try_recv() {
|
||||
Ok((c, r)) => {
|
||||
*client = Some(c);
|
||||
return r;
|
||||
}
|
||||
Err(TryRecvError::Empty) => std::thread::yield_now(),
|
||||
Err(TryRecvError::Disconnected) => panic!("the client thread for {method:?} stopped without a reply"),
|
||||
}
|
||||
}
|
||||
panic!("the app did not answer {method:?}")
|
||||
}
|
||||
|
||||
// With the launcher's switch naming VectorCraft, the window serves agents on loopback and publishes
|
||||
@@ -114,6 +119,28 @@ fn with_the_switch_off_nothing_listens() {
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_folders_reaches_the_window_with_unusable_saved_roots() {
|
||||
let base = folders("agent-folders-window");
|
||||
let (mut app, _) = app_with_agents(&base, AgentSwitch::fixed(true, true));
|
||||
app.run("prefs.agents", json!({"readRoot": s(base.join("in/a.svg"))})).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap_or_default();
|
||||
super::sync(&mut app, &ctx);
|
||||
let connection = read_connection(&base.join("settings")).unwrap().expect("the connection file is published");
|
||||
let token = std::fs::read_to_string(&connection.token_file).unwrap();
|
||||
let mut client = Some(ControlClient::connect(([127, 0, 0, 1], connection.port).into(), token.trim()).unwrap());
|
||||
|
||||
for params in [json!({}), Value::Null] {
|
||||
let answer = agent_request(&mut app, &mut client, "agent.folders", params).unwrap();
|
||||
assert_eq!(answer.get("read_folder"), Some(&Value::Null), "{answer}");
|
||||
assert_eq!(answer.get("write_folder"), Some(&Value::Null), "{answer}");
|
||||
assert_ne!(answer.get("unrestricted"), Some(&Value::Bool(true)), "{answer}");
|
||||
}
|
||||
let unexpected = agent_request(&mut app, &mut client, "agent.folders", json!({"unexpected": true}));
|
||||
assert!(unexpected.as_ref().is_err_and(|e| e.contains("takes no parameters")), "{unexpected:?}");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
// `prefs.agents` saves the person's settings, refuses unknown keys, and refuses every change from a
|
||||
// confined request: agents can't widen their own folders.
|
||||
#[test]
|
||||
@@ -134,6 +161,26 @@ fn prefs_agents_saves_and_agents_cannot_change_it() {
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
// `agent.folders` answers with the roots the request runs inside: roots that grant nothing (a saved
|
||||
// folder the window can't use) list no folder.
|
||||
#[test]
|
||||
fn agent_folders_reports_the_roots_a_request_runs_inside() {
|
||||
let base = folders("agent-folders");
|
||||
let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap().unwrap();
|
||||
let answer = super::folders(Some(&roots));
|
||||
assert!(answer["read_folder"].as_str().is_some_and(|f| f.ends_with("in")), "{answer}");
|
||||
assert!(answer["write_folder"].as_str().is_some_and(|f| f.ends_with("out")), "{answer}");
|
||||
assert!(answer.get("read_folders").is_none(), "{answer}");
|
||||
let two = AutomationRoots::new(&[&base.join("in"), &base.join("outside")], &[&base.join("out")]).unwrap().unwrap();
|
||||
let answer = super::folders(Some(&two));
|
||||
assert_eq!(answer["read_folders"].as_array().map(Vec::len), Some(2), "{answer}");
|
||||
assert!(answer.get("write_folders").is_none(), "{answer}");
|
||||
let none = super::folders(Some(&AutomationRoots::none()));
|
||||
assert_eq!((&none["read_folder"], &none["write_folder"]), (&Value::Null, &Value::Null), "{none}");
|
||||
assert_eq!(super::folders(None)["unrestricted"], true);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
// A control client started without automation roots runs unconfined, and it still can't change the
|
||||
// agent settings: only the person sets them.
|
||||
#[test]
|
||||
|
||||
@@ -1230,7 +1230,10 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
|
||||
}
|
||||
other => return other,
|
||||
};
|
||||
hide_in_reply(app, &mut reply, &req.params, before);
|
||||
// `agent.folders` names the request's own roots, which it may use whole.
|
||||
if method != "agent.folders" {
|
||||
hide_in_reply(app, &mut reply, &req.params, before);
|
||||
}
|
||||
Reply::Done(reply)
|
||||
}
|
||||
|
||||
@@ -1479,6 +1482,14 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val
|
||||
}
|
||||
"engine.commands" => ok(all_commands(app)),
|
||||
"document.inspect" => wrap(app.run("document.inspect", p.clone())),
|
||||
// Each request runs confined to the window's automation roots ([`VectorcraftApp::run_control`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
"agent.folders" => {
|
||||
if !p.is_null() && !p.as_object().is_some_and(|fields| fields.is_empty()) {
|
||||
return err("`agent.folders` takes no parameters");
|
||||
}
|
||||
ok(crate::agents::folders(vectorcraft_engine::file_access::current().as_deref()))
|
||||
}
|
||||
"ui.inspect" => ok(inspect(app, ctx)),
|
||||
"ui.docking" => ok(crate::panel_docking::inspect(app, ctx)),
|
||||
// A request that stops with a panic quoting the status text, after clearing the Color Guide's
|
||||
|
||||
@@ -29,7 +29,7 @@ use std::sync::{Arc, Weak};
|
||||
|
||||
use craft::behavior::{EditEvent, EditEvents, Mixed, Selection, SelectionChange, keyed};
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Sampler as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
@@ -53,6 +53,7 @@ use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, Nu
|
||||
use crate::VectorcraftApp;
|
||||
use crate::panels::paragraph::BulletGlyph;
|
||||
|
||||
use super::host::preview_canvas;
|
||||
use super::preview::LivePreview;
|
||||
|
||||
/// The dialog kind of Bullets and Numbering.
|
||||
@@ -131,6 +132,9 @@ pub(crate) struct BulletsDialog {
|
||||
active_document: bool,
|
||||
held: HeldAnswer<Map<String, Value>>,
|
||||
open: bool,
|
||||
/// The canvas the dialog previews on (from [`preview_canvas`]): the modal layer leaves it undimmed, and the wheel
|
||||
/// still moves its view.
|
||||
canvas: Option<egui::Id>,
|
||||
}
|
||||
|
||||
/// The preview from the opening drawing and the interaction that owns its undo snapshot.
|
||||
@@ -269,6 +273,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
active_document: true,
|
||||
held: HeldAnswer::default(),
|
||||
open: true,
|
||||
canvas: preview_canvas(app),
|
||||
};
|
||||
host.with(|h| h.open(dialog));
|
||||
app.bullets_preview = Some(Preview { document, live: LivePreview::default(), selection: None });
|
||||
@@ -572,11 +577,15 @@ impl StackDialog for BulletsDialog {
|
||||
FooterButton::new(common.cancel.clone(), DialogRole::Cancel),
|
||||
];
|
||||
let mut open = self.open;
|
||||
let canvas = self.canvas;
|
||||
let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open)).refusal(move || refusal.clone());
|
||||
let shown = dialog.show(ui, |ui, cx| {
|
||||
if finish && !measure::active(ui.ctx()) {
|
||||
cx.request_close_as(CloseReason::Activated);
|
||||
}
|
||||
if let Some(canvas) = canvas {
|
||||
cx.keep_view_open(canvas);
|
||||
}
|
||||
self.body(ui);
|
||||
});
|
||||
self.open = open;
|
||||
|
||||
@@ -18,7 +18,7 @@ use craft::imaging::ui::filter_gallery::{
|
||||
};
|
||||
use craft::theme::variant::Tone;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Bind, Props as _, Sampler as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id};
|
||||
use craft::ui::display::{Picture, PictureSize};
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
@@ -39,7 +39,7 @@ use vectorcraft_geom::{Affine, Point};
|
||||
use super::effect;
|
||||
use super::effect_params::{EffectCx, effect_params};
|
||||
use super::form::json_of;
|
||||
use super::host::{HeldOptions, open_held_with};
|
||||
use super::host::{HeldOptions, open_held_with, preview_canvas};
|
||||
use super::preview::LivePreview;
|
||||
use crate::VectorcraftApp;
|
||||
use crate::file_asks::Owner;
|
||||
@@ -343,6 +343,9 @@ pub(crate) struct EffectGalleryDialog {
|
||||
held: HeldAnswer<Value>,
|
||||
/// A Browse press waiting for the app's file dialog, with the layer it belongs to.
|
||||
asked: Option<LayerId>,
|
||||
/// The canvas the gallery previews on (from [`preview_canvas`]): the modal layer leaves it undimmed, and the
|
||||
/// wheel still moves its view.
|
||||
canvas: Option<egui::Id>,
|
||||
}
|
||||
|
||||
impl EffectGalleryDialog {
|
||||
@@ -363,6 +366,7 @@ impl EffectGalleryDialog {
|
||||
preview_on: true,
|
||||
held: HeldAnswer::new(),
|
||||
asked: None,
|
||||
canvas: preview_canvas(app),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,7 +427,8 @@ impl StackDialog for EffectGalleryDialog {
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<Value>> {
|
||||
let words = Env::of(ui).words::<CommonWords>();
|
||||
let EffectGalleryDialog { open, catalog, index, session, selected, preview_on, held, asked, .. } = self;
|
||||
let EffectGalleryDialog { open, catalog, index, session, selected, preview_on, held, asked, canvas, .. } = self;
|
||||
let canvas = *canvas;
|
||||
// The app accepted the held OK: this pass closes the dialog with it. A measuring run closes nothing.
|
||||
let finish = held.is_accepted() && !craft::ui::runtime::measure::active(ui.ctx());
|
||||
// A refusal is cleared once the stack changes, so one still held is for the stack shown.
|
||||
@@ -456,6 +461,9 @@ impl StackDialog for EffectGalleryDialog {
|
||||
if finish {
|
||||
cx.request_close_as(CloseReason::Activated);
|
||||
}
|
||||
if let Some(canvas) = canvas {
|
||||
cx.keep_view_open(canvas);
|
||||
}
|
||||
let Some(layer) = effects.get(current) else { return };
|
||||
let image = || color_image(&preview_rgba(&visible, PREVIEW_W, PREVIEW_H), PREVIEW_W, PREVIEW_H);
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
|
||||
@@ -15,12 +15,40 @@
|
||||
# Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language names,
|
||||
# OpenType, the built-in workspace names and the bracketed perspective grid preset names. Keep
|
||||
# placeholders, ellipses and the leading/trailing spaces of fragments when editing.
|
||||
# Rows from main without Georgian (2026-11-25)
|
||||
@msg this is a binary DXF file, which can't be read: save it from the CAD app as an ASCII DXF and open that ეს ორობითი DXF ფაილია და მისი წაკითხვა შეუძლებელია: CAD აპში შეინახეთ ის ASCII DXF-ად და ის გახსენით
|
||||
@msg `fontAxes` must be an object of axis tags and values, such as {"wght"} `fontAxes` უნდა იყოს ღერძების ტეგებისა და მნიშვნელობების ობიექტი, მაგალითად {"wght"}
|
||||
@msg `items` is a list of {kind, item} `items` არის {kind, item} ჩანაწერების სია
|
||||
@msg `items` must be a list of {id, points} `items` უნდა იყოს {id, points} ჩანაწერების სია
|
||||
@msg `items` must be an array of {id, anchors} `items` უნდა იყოს {id, anchors} ჩანაწერების მასივი
|
||||
@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout უნდა იყოს {layout?, columns?, spacing?, rightToLeft?}
|
||||
@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path სტრიქონი {line}, სვეტი {column}: დიაგრამის მონაცემთა ფაილი `{path}` ცვლადისთვის `{var}` ფარდობითი გზაა: მიუთითეთ `base` ან აბსოლუტური გზა
|
||||
@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} სტრიქონი {line}, სვეტი {column}: ცვლადის `{var}` დიაგრამის მონაცემთა ფაილის წაკითხვა შეუძლებელია: {e}
|
||||
@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} სტრიქონი {line}, სვეტი {column}: დიაგრამის მონაცემთა ფაილის გზა `{path}` ცვლადისთვის `{var}` არ გაიხსნება: {r}
|
||||
@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes სტრიქონი {line}, სვეტი {column}: დიაგრამის მონაცემთა ფაილი `{path}` ცვლადისთვის `{var}` {MAX_GRAPH_DATA_FILE} ბაიტზე დიდია
|
||||
@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes სტრიქონი {line}, სვეტი {column}: დიაგრამის მონაცემთა ფაილი `{path}` ცვლადისთვის `{var}` იძლევა დიაგრამის მნიშვნელობას, რომელიც {MAX_GRAPH_CSV} ბაიტზე გრძელია
|
||||
@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all სტრიქონი {line}, სვეტი {column}: დიაგრამის მონაცემთა ფაილები სულ {MAX_GRAPH_FILES_TOTAL} ბაიტზე მეტს შეიცავს
|
||||
@msg `base` is empty `base` ცარიელია
|
||||
@msg each format is an object {format, scale?, suffix?} თითოეული ფორმატი არის ობიექტი {format, scale?, suffix?}
|
||||
@msg each of `fonts` is {family, style?}; 1 to 1000 of them `fonts`-ის თითოეული ჩანაწერი არის {family, style?}; 1-დან 1000-მდე ჩანაწერი
|
||||
@msg each of `items` is {kind, item} `items`-ის თითოეული ჩანაწერი არის {kind, item}
|
||||
@msg files must be {name, dataBase64} files უნდა იყოს {name, dataBase64}
|
||||
@msg give `matches`: [{kind, name, target}] მიუთითეთ `matches`: [{kind, name, target}]
|
||||
@msg give color, none, swatch, gradient or opacity მიუთითეთ color, none, swatch, gradient ან opacity
|
||||
@msg give the settings to change, e.g. {"formats"}]} მიუთითეთ შესაცვლელი პარამეტრები, მაგ. {"formats"}]}
|
||||
@msg give {key, value} or {values} მიუთითეთ {key, value} ან {values}
|
||||
@msg missing `map` (rows [{from, to}] or {current}) აკლია `map` (სტრიქონები [{from, to}] ან {current})
|
||||
@msg not an RTF file: it doesn't start with {\\rtf RTF ფაილი არ არის: არ იწყება {\\rtf-ით
|
||||
@msg quotes must be {double?, single?} quotes უნდა იყოს {double?, single?}
|
||||
@msg text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} text უნდა იყოს {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?}
|
||||
@msg textureImage: give {path} or {name, dataBase64} of an image file, or a texture as effect.list gives it textureImage: მიუთითეთ გამოსახულების ფაილის {path} ან {name, dataBase64}, ან ტექსტურა ისე, როგორც effect.list იძლევა
|
||||
|
||||
# Georgian rows untranslated on main (catch-up, 2026-11-15)
|
||||
Add as Single Graphic ერთ გრაფიკად დამატება
|
||||
Expand as Wireframes კარკასებად გაშლა
|
||||
Add art with Add as Single Graphic, or drop art here. დაამატეთ ნახატი ბრძანებით „ერთ გრაფიკად დამატება“ ან ჩამოაგდეთ ნახატი აქ.
|
||||
Face მხარე
|
||||
Graphics map onto the Plane, Extrude and Revolve object types. გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“ და „ბრუნვა“.
|
||||
Graphics map onto the Plane, Extrude, Revolve and Inflate object types. გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“, „ბრუნვა“ და „გაბერვა“.
|
||||
Line Gap სტრიქონებს შორის ღრეჩო
|
||||
Manage Profiles პროფილების მართვა
|
||||
Mapped graphics განთავსებული გრაფიკა
|
||||
@@ -42,7 +70,7 @@
|
||||
Reset Profile პროფილის ჩამოყრა
|
||||
Select Object on Path ტრაექტორიაზე ობიექტის მონიშვნა
|
||||
Weather Icons ამინდის ხატულები
|
||||
Media Controls მედია მართვის საშუალებები
|
||||
Media Controls მედიის მართვის ელემენტები
|
||||
@id language.name ქართული
|
||||
@msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions 'caller', 'callee' და 'arguments' მკაცრი რეჟიმის ფუნქციებში ვერ გამოიყენება
|
||||
@msg 3D effects require finite coordinates within 100 million points 3D ეფექტებს სჭირდება სასრული კოორდინატები 100 მილიონი პუნქტის ფარგლებში
|
||||
@@ -904,7 +932,7 @@
|
||||
@msg glyph {g} is not an alternate of {ch} in {_1} {_2} გლიფი {g} არ არის სიმბოლოს {ch} ალტერნატივა შრიფტში {_1} {_2}
|
||||
@msg gradient must be "objects" or "mesh" gradient უნდა იყოს "objects" ან "mesh"
|
||||
@msg grays must be "profile" or "black", not `{g}` grays უნდა იყოს "profile" ან "black" და არა `{g}`
|
||||
@msg grayscale profiles can't be working spaces yet ნაცრისფერი გრადაციების პროფილები სამუშაო ფერთა სივრცედ ჯერ ვერ გამოიყენება
|
||||
@msg grayscale profiles can't be working spaces yet ნაცრისფერი ტონების პროფილები სამუშაო ფერთა სივრცედ ჯერ ვერ გამოიყენება
|
||||
@msg gridColors must be a preset name or two colours gridColors უნდა იყოს პრესეტის სახელი ან ორი ფერი
|
||||
@msg gridSize must be small, medium or large gridSize უნდა იყოს small, medium ან large
|
||||
@msg guide {g} is not selected დამხმარე ხაზი {g} მონიშნული არ არის
|
||||
@@ -2594,16 +2622,16 @@
|
||||
Find Matching Fonts შესაბამისი შრიფტების ძებნა
|
||||
Find more font matches მეტი შესაბამისი შრიფტის ძებნა
|
||||
Type your text to preview აკრიფეთ ტექსტი წინასწარი ნახვისთვის
|
||||
Select outlined text, then Find Matching Fonts. მონიშნეთ კონტურებად გარდაქმნილი ტექსტი, შემდეგ აირჩიეთ შესაბამისი შრიფტების ძებნა.
|
||||
Select outlined text, then Find Matching Fonts. მონიშნეთ კონტურებად გარდაქმნილი ტექსტი, შემდეგ დაწკაპეთ „შესაბამისი შრიფტების ძებნა“.
|
||||
No font matches the selected shapes. არცერთი შრიფტი არ შეესაბამება მონიშნულ ფიგურებს.
|
||||
Shapes past the first 2,048, or more than 16 groups deep, were not compared. პირველი 2048-ის შემდეგი ან 16 ჯგუფზე ღრმად მოთავსებული ფიგურები არ შედარდა.
|
||||
Shapes past the first 2,048, or more than 16 groups deep, were not compared. პირველი 2048-ის მიღმა მყოფი და 16 დონეზე ღრმად ჩადგმული ფიგურები არ შედარდა.
|
||||
Reset Retype Panel ხელახლა აკრეფის პანელის ჩამოყრა
|
||||
List Matching Fonts შესაბამისი შრიფტების სია
|
||||
Retype Preview ხელახლა აკრეფის პანელის წინასწარი ნახვა
|
||||
Retype Preview ხელახლა აკრეფის წინასწარი ნახვა
|
||||
@msg `count` must be a whole number from 1 to 96 `count` უნდა იყოს მთელი რიცხვი 1-დან 96-მდე
|
||||
@msg `size` must be small, medium or large `size` უნდა იყოს small, medium ან large
|
||||
@msg `text` must be a string of at most 100 characters `text` უნდა იყოს არაუმეტეს 100 სიმბოლოს სტრიქონი
|
||||
@msg Retype: select outlined text (paths or compound paths) ხელახლა აკრეფა: მონიშნეთ კონტურებად გარდაქმნილი ტექსტი (კონტურები ან შედგენილი კონტურები)
|
||||
@msg Retype: select outlined text (paths or compound paths) ხელახლა აკრეფა: მონიშნეთ კონტურებად გარდაქმნილი ტექსტი (ტრაექტორიები ან შედგენილი ტრაექტორიები)
|
||||
Change Case რეგისტრის შეცვლა
|
||||
UPPERCASE მთავრული
|
||||
lowercase პატარა ასოები
|
||||
@@ -3834,11 +3862,11 @@ digits Hindi ჰინდი
|
||||
digits Devanagari დევანაგარი
|
||||
digits Bengali ბენგალური
|
||||
digits Gurmukhi გურმუხი
|
||||
digits Gujarati გუჯარათი
|
||||
digits Gujarati გუჯარათული
|
||||
digits Odia ორია
|
||||
digits Tamil ტამილური
|
||||
digits Telugu ტელუგუ
|
||||
digits Kannada კანადა
|
||||
digits Kannada კანნადა
|
||||
digits Malayalam მალაიალამური
|
||||
Reset Panel პანელის ჩამოყრა
|
||||
Roman Baseline რომაული საბაზისო ხაზი
|
||||
@@ -5234,7 +5262,7 @@ antiAlias Sharp მკვეთრი
|
||||
With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. „პროფილების გარეშე“ და CMYK გამოტანის მიზნით ყველა CMYK ფერი DeviceCMYK-ად იწერება, თუ ის სხვა პროფილის CMYK დანიშნულებაში არ გარდაიქმნება.
|
||||
Flattener preset: გაბრტყელების პრესეტი:
|
||||
General › Thumbnails ზოგადი › ესკიზები
|
||||
Grayscale images ნაცრისფერი გამოსახულებები
|
||||
Grayscale images ნაცრისფერი ტონების გამოსახულებები
|
||||
Include non-printing layers არაბეჭდვადი შრეების ჩართვა
|
||||
Write pages longer than 200 in at full size in points 200 in-ზე გრძელი გვერდების სრული ზომით, პუნქტებში ჩაწერა
|
||||
Left: მარცხნივ:
|
||||
@@ -5513,10 +5541,10 @@ theme Appearance იერსახე
|
||||
Brush Options… ფუნჯის პარამეტრები…
|
||||
Options of Selected Object… მონიშნული ობიექტის პარამეტრები…
|
||||
Options of Selected Object მონიშნული ობიექტის პარამეტრები
|
||||
@msg no path painted with a brush is selected ფუნჯით დახატული კონტური მონიშნული არ არის
|
||||
@msg the selected paths are painted with brushes of different types მონიშნული კონტურები სხვადასხვა ტიპის ფუნჯებითაა დახატული
|
||||
@msg no path painted with a brush is selected ფუნჯით დახატული ტრაექტორია მონიშნული არ არის
|
||||
@msg the selected paths are painted with brushes of different types მონიშნული ტრაექტორიები სხვადასხვა ტიპის ფუნჯებითაა დახატული
|
||||
@msg give `params` or `reset`, not both მიუთითეთ `params` ან `reset`, არა ორივე
|
||||
@msg a bristle brush has no options of its own on a path ჯაგრის ფუნჯს კონტურზე საკუთარი პარამეტრები არ აქვს
|
||||
@msg a bristle brush has no options of its own on a path ჯაგრის ფუნჯს ტრაექტორიაზე საკუთარი პარამეტრები არ აქვს
|
||||
Current Brush მიმდინარე ფუნჯი
|
||||
Current Symbol მიმდინარე სიმბოლო
|
||||
Delete Brush ფუნჯის წაშლა
|
||||
@@ -6015,7 +6043,7 @@ theme Appearance იერსახე
|
||||
Data Recovery მონაცემების აღდგენა
|
||||
Default Language ნაგულისხმევი ენა
|
||||
Disable Auto Add/Delete ავტომატური დამატება/წაშლის გამორთვა
|
||||
Delete Removes Anchor Points and Keeps Paths Joined Delete შლის ღუზის წერტილებს და ინარჩუნებს კონტურებს შეერთებულად
|
||||
Delete Removes Anchor Points and Keeps Paths Joined Delete შლის საყრდენ წერტილებს და ტრაექტორიებს შეერთებულს ტოვებს
|
||||
Interpolate Control Points When Moving Anchors სახელურების ინტერპოლაცია საყრდენი წერტილების გადაადგილებისას
|
||||
Display All Blacks Accurately ყველა შავის ზუსტად ჩვენება
|
||||
Display All Blacks as Rich Black ყველა შავის მდიდარ შავად ჩვენება
|
||||
@@ -6175,7 +6203,7 @@ theme Appearance იერსახე
|
||||
When pasting text ტექსტის ჩასმისას
|
||||
XML ID XML ID
|
||||
Yards იარდები
|
||||
Zoom to Selection მონიშნულის მასშტაბირება
|
||||
Zoom to Selection მონიშნულზე მასშტაბირება
|
||||
Zoom with Mouse Wheel მაუსის ბორბლით მასშტაბირება
|
||||
Scroll Sideways with Cmd/Ctrl + Wheel ჰორიზონტალური გადაადგილება Cmd/Ctrl + ბორბლით
|
||||
Scrub Numeric Fields by Dragging რიცხვითი ველების შეცვლა გადათრევით
|
||||
@@ -6329,7 +6357,7 @@ axis Both ორივე
|
||||
Auto ავტომატური
|
||||
Center ცენტრში
|
||||
Transform in Perspective პერსპექტივაში გარდაქმნა
|
||||
Grayscale ნაცრისფერი გრადაციები
|
||||
Grayscale ნაცრისფერი ტონები
|
||||
High Color ბევრი ფერი
|
||||
Low Color ცოტა ფერი
|
||||
Embed ჩაშენება
|
||||
@@ -6551,8 +6579,8 @@ font-technology Variable ცვლადი
|
||||
A two-finger rotate gesture on a trackpad rotates the canvas view. ტრეკპადზე ორი თითით მობრუნების ჟესტი ტილოს ხედს აბრუნებს.
|
||||
Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. კლავიშის ხანგრძლივი დაჭერა უშვებს ხელსაწყოს ან ბრძანებას კლავიატურის მალსახმობების დაჭერის სვეტიდან; მოკლე დაჭერა უშვებს მის ჩვეულ მალსახმობს.
|
||||
How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. რამდენი წამი უნდა იყოს კლავიში დაჭერილი, სანამ ჩვეული მალსახმობის ნაცვლად მისი ხანგრძლივი დაჭერის მალსახმობი გაეშვება.
|
||||
Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete შლის არჩეულ ღუზის წერტილებს და თითოეულის გარშემო მრუდს ხელახლა არგებს, ნაცვლად იმისა, რომ იქ კონტური გახსნას.
|
||||
When you move anchor points, each curve with one moved end keeps its shape relative to its ends. როცა ღუზის წერტილებს გადაადგილებთ, ყოველი მრუდი, რომლის ერთი ბოლოც გადაადგილდა, ინარჩუნებს ფორმას თავის ბოლოებთან მიმართებით.
|
||||
Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete შლის მონიშნულ საყრდენ წერტილებს და თითოეულის ირგვლივ მრუდს თავიდან აგებს, ნაცვლად იმისა, რომ იქ ტრაექტორია გახსნას.
|
||||
When you move anchor points, each curve with one moved end keeps its shape relative to its ends. როცა საყრდენ წერტილებს გადაადგილებთ, ყოველი მრუდი, რომლის ერთი ბოლოც გადაადგილდა, ინარჩუნებს ფორმას თავის ბოლოებთან მიმართებით.
|
||||
Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. სანამ ხელსაწყოს მალსახმობ კლავიშს დაჭერილს გიჭირავთ, ეს ხელსაწყოა არჩეული; კლავიშის აშვების შემდეგ ისევ წინა ხელსაწყო აირჩევა.
|
||||
Shows the bounding box while you move the selection or draw a shape. აჩვენებს შემომსაზღვრელ ჩარჩოს, სანამ მონიშნულს გადაადგილებთ ან ფიგურას ხატავთ.
|
||||
Create Trim Marks draws Japanese-style marks instead of Roman ones. ჭრის ნიშნების შექმნა რომაულის ნაცვლად იაპონური სტილის ნიშნებს ხატავს.
|
||||
@@ -6589,7 +6617,7 @@ font-technology Variable ცვლადი
|
||||
The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. საბაზისო ხაზის წანაცვლების ბიჯი: ჰორიზონტალურ ტექსტში Alt და Shift ზემოთ ან ქვემოთ ისართან ერთად საბაზისო ხაზს ერთი ბიჯით ანაცვლებს, Cmd/Ctrl-თან ერთად კი ხუთით.
|
||||
Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. აჩვენებს იაპონური და სხვა აღმოსავლეთაზიური ტექსტის პარამეტრებს პანელებში სიმბოლო, აბზაცი, OpenType და გლიფები, ასევე ბრძანებას კომპოზიტური შრიფტები.
|
||||
Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. აჩვენებს არაბული, ებრაული და ინდური ტექსტის პარამეტრებს პანელებში სიმბოლო და აბზაცი, მაგალითად აბზაცის მიმართულებას, ქაშიდებს და ციფრებს.
|
||||
The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. მონიშვნის ხელსაწყოები ტექსტს მხოლოდ მის საბაზისო ხაზზე, არის ტექსტის ჩარჩოზე ან მის კონტურზე მონიშნავენ და არა მისი ყუთის შიგნით ნებისმიერ ადგილას.
|
||||
The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. მონიშვნის ხელსაწყოები ტექსტს მხოლოდ მის საბაზისო ხაზზე, არის ტექსტის ჩარჩოზე ან მის ტრაექტორიაზე მონიშნავენ და არა მისი ყუთის შიგნით ნებისმიერ ადგილას.
|
||||
Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. შრიფტების მენიუები ყოველ შრიფტს ინგლისური სახელით აჩვენებს; გამორთვისას შრიფტი, რომელსაც საკუთარ ენაზეც აქვს სახელი, იმ სახელს აჩვენებს.
|
||||
New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. ახალი არის ტექსტი ჩართული ავტომატური ზომით იწყება, ამიტომ ჰორიზონტალური ტექსტის მართკუთხა ჩარჩო სიმაღლეში იზრდება ან მცირდება, რომ ტექსტი დაეტიოს.
|
||||
Font lists and the Type › Font menu show a sample of each font beside its name. შრიფტების სიები და მენიუ შრიფტი თითოეული შრიფტის ნიმუშს მისი სახელის გვერდით აჩვენებს.
|
||||
@@ -6638,10 +6666,10 @@ font-technology Variable ცვლადი
|
||||
Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. ტილოზე თითოეული ნაჭრის ნომერს აჩვენებს ჩარჩოში მის ზედა მარცხენა კუთხეში; გამორთულისას ნაჭრების კონტურები კვლავ ჩანს.
|
||||
The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. მომხმარებლისა და ობიექტის ნაჭრების კონტურებისა და მათი ნომრების ჩარჩოების ფერი; ავტომატური ნაჭრები ამ ფერის უფრო მკრთალ ელფერს იყენებს.
|
||||
In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. აბზაცებში, სადაც სიტყვების გადატანა ჩართულია, სიაში მოცემული სიტყვა გადატანის დეფისს მხოლოდ მასში აკრეფილ დეფისებთან იღებს, ან არასდროს, თუ ისინი არ აქვს, მიუხედავად ენისა და რეგისტრისა.
|
||||
On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. დესკტოპზე ამ საქაღალდის .wasm პლაგინები იტვირთება გაშვებისას და ახალი საქაღალდის OK-ით დაყენებისას, უსაფრთხო რეჟიმის გარდა; ნებართვების მომთხოვნი კი მათი მიცემის შემდეგ. ვებში არ იტვირთება.
|
||||
On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. დესკტოპზე ამ საქაღალდის .wasm პლაგინები იტვირთება გაშვებისას და მაშინ, როცა OK ახალ საქაღალდეს აყენებს, უსაფრთხო რეჟიმის გარდა; ნებართვების მომთხოვნი პლაგინი მხოლოდ მათი მიცემის შემდეგ იტვირთება. ვებ-ვერსია არცერთს არ ტვირთავს.
|
||||
Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. დიდი ფილტრის ან ბრძანების პლაგინის გაშვებას მინიმუმ 250 მილიონ ინსტრუქციას აძლევს, იგივე დროის ლიმიტით; ჩვეულებრივი ბიუჯეტს ტოვებს. ცოცხალი ეფექტები, ექსპორტერები და იმპორტერები არ იცვლება.
|
||||
New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. ახალი ტექსტი იღებს ამ ენას, სანამ დოკუმენტის პარამეტრების ენაა ინგლისური: აშშ; დოკუმენტში უკვე არსებული ტექსტი ინარჩუნებს თავის ენას.
|
||||
New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. ახალი ტექსტი იღებს ამ ენას, სანამ დოკუმენტის პარამეტრების ენაა ინგლისური: აშშ და [ჩვეულებრივი სიმბოლოს სტილი] ენას არ ადგენს; დოკუმენტში უკვე არსებული ტექსტი ინარჩუნებს თავის ენას.
|
||||
New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. ახალი ტექსტი ამ ენას იღებს, როცა დოკუმენტის პარამეტრების ენაა ინგლისური: აშშ და [ჩვეულებრივი სიმბოლოს სტილი] ენას არ ადგენს; დოკუმენტში უკვე არსებული ტექსტი ინარჩუნებს თავის ენას.
|
||||
In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. აბზაცებში, სადაც სიტყვების გადატანა ჩართულია, სიაში მოცემული სიტყვა მხოლოდ მასში აკრეფილ დეფისებთან გადაიტანება, ან არსად, თუ ისინი არ აქვს, მიუხედავად ენისა და რეგისტრისა.
|
||||
On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. დესკტოპის ვერსიაში ამ საქაღალდის .wasm პლაგინები იტვირთება გაშვებისას და როცა აქ ახალი საქაღალდით OK-ს დააწკაპუნებთ, გარდა უსაფრთხო რეჟიმისა; ვებ-ვერსია მათ არ ტვირთავს.
|
||||
Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. ჩვეულებრივი ინარჩუნებს თითოეული პლაგინის საკუთარ ლიმიტებს; დიდით პლაგინის ფილტრს ან ბრძანებას შეუძლია შეასრულოს მინიმუმ 250 მილიონი ინსტრუქცია მისი შეყვანისთვის საჭირო ინსტრუქციების გარდა. დროის ლიმიტი იგივე რჩება.
|
||||
@@ -6663,7 +6691,7 @@ font-technology Variable ცვლადი
|
||||
The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. ინტერფეისის ენა; ავტომატური სისტემის ენას იყენებს. დიალოგი ენას იცვლის, როგორც კი რომელიმეს აირჩევთ.
|
||||
Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. ანიმირებული მასშტაბირება მუშაობს მხოლოდ მაშინ, როცა ეს ჩართულია; გამორთულისას ანიმირებული მასშტაბირება მკრთალია და მასშტაბირება არ ანიმირდება.
|
||||
The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. ბორბლით მასშტაბირება რბილად სრიალებს, მასშტაბის ხელსაწყო კი ადიდებს, როცა გვერდზე გადაათრევთ ან დაჭერილს გაჩერებთ; გამორთულისას ის ადიდებს არეს, რომელზეც გადაათრევთ.
|
||||
From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. შემდეგი გაშვებიდან დესკტოპის ვერსია ტილოს აჩვენებს ამ ტიპის გრაფიკული პროცესორით; ნამუშევარი ყოველთვის CPU-ზე იხატება. ავტომატური Windows-სა და macOS-ზე ინტეგრირებულს ანიჭებს უპირატესობას. ვებ-ვერსია მას არ იყენებს.
|
||||
From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. შემდეგი გაშვებიდან დესკტოპის ვერსია ტილოს ამ ტიპის გრაფიკული პროცესორით აჩვენებს; ნახატი ორივე შემთხვევაში CPU-ზე იხატება. „ავტომატური“ Windows-სა და macOS-ზე ინტეგრირებულს ანიჭებს უპირატესობას. ვებ-ვერსია მას არ იყენებს.
|
||||
From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. შემდეგი გაშვებიდან ფანჯარა აჩვენებს თითოეულ კადრს ეკრანის განახლების მოლოდინის გარეშე, სადაც გრაფიკული დრაივერი ამის საშუალებას იძლევა, წამში არაუმეტეს 240 კადრისა.
|
||||
From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. შემდეგი გაშვებიდან დესკტოპის ვერსია ხატავს ამ ტიპის გრაფიკული პროცესორით; ავტომატური უპირატესობას ანიჭებს ეკრანის მმართველს. ვებ-ვერსია მას არ იყენებს.
|
||||
From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. შემდეგი გაშვებიდან ფანჯარა აჩვენებს კადრებს ეკრანის განახლების მოლოდინის გარეშე, წამში არაუმეტეს 240-ისა; გამორთულისას ტემპს ეკრანი განსაზღვრავს. უპირატესობა აქვს გაშვებისას დაყენებულ ჩვენების რეჟიმს.
|
||||
@@ -6672,7 +6700,7 @@ font-technology Variable ცვლადი
|
||||
How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. რამდენი სამუშაო ნაკადი ხატავს ნახატს; -1 იყენებს ერთით ნაკლებს VectorCraft-ისთვის ხელმისაწვდომ ბირთვებზე, მაქსიმუმ 8-ს, 0 კი არცერთს. ვებ-ვერსია არასდროს იყენებს.
|
||||
From the next start on a Wayland desktop, X11 (XWayland) opens the window through XWayland; the other choices do so only when a pen is attached. შემდეგი გაშვებიდან Wayland-ის სამუშაო მაგიდაზე X11 (XWayland) ფანჯარას XWayland-ით ხსნის; სხვა არჩევანი ამას მხოლოდ მაშინ აკეთებს, როცა კალამი მიერთებულია.
|
||||
From the next start, the desktop version shows frames without waiting for the display's refresh, at most 240 a second; off, the display paces them. შემდეგი გაშვებიდან დესკტოპის ვერსია კადრებს აჩვენებს ეკრანის განახლების მოლოდინის გარეშე, წამში მაქსიმუმ 240-ს; გამორთულისას ტემპს ეკრანი განსაზღვრავს.
|
||||
The larger budget raises each object filter run's base instructions fivefold and keeps the same allowance per input byte; heavy filters, live effects, exporters and importers keep their own limits. დიდი ბიუჯეტი ობიექტის ფილტრის ყოველი გაშვების საბაზო ინსტრუქციებს ხუთჯერ ზრდის, შეყვანის ბაიტზე დანამატი კი იგივე რჩება; მძიმე ფილტრებს, ცოცხალ ეფექტებს, ექსპორტერებსა და იმპორტერებს თავისი ლიმიტები აქვთ.
|
||||
The larger budget raises each object filter run's base instructions fivefold and keeps the same allowance per input byte; heavy filters, live effects, exporters and importers keep their own limits. დიდი ბიუჯეტი ობიექტის ფილტრის ყოველი გაშვების საბაზო ინსტრუქციებს ხუთჯერ ზრდის, შეყვანის თითო ბაიტზე დაშვებული რაოდენობა კი იგივე რჩება; მძიმე ფილტრებს, ცოცხალ ეფექტებს, ექსპორტერებსა და იმპორტერებს საკუთარი ლიმიტები რჩებათ.
|
||||
Converts the artwork and artboards on the canvas to the display's color profile where the system does not already do so; off, the canvas is drawn in sRGB. ტილოზე არსებულ ნახატს და სამუშაო დაფებს გარდაქმნის ეკრანის ფერთა პროფილში, სადაც სისტემა ამას უკვე არ აკეთებს; გამორთულისას ტილო sRGB-ში იხატება.
|
||||
On the desktop, a save to a file is written in the background while you keep editing; off, you wait until it is written. დესკტოპის ვერსიაში ფაილში შენახვა ფონურ რეჟიმში იწერება, სანამ რედაქტირებას აგრძელებთ; გამორთულისას ელოდებით, სანამ ჩაიწერება.
|
||||
On the desktop, exports to files and packages are written in the background while you keep editing, except 3D exports; off, you wait for them. დესკტოპის ვერსიაში ფაილებში ექსპორტი და შეფუთვა ფონურ რეჟიმში იწერება, სანამ რედაქტირებას აგრძელებთ, გარდა 3D ექსპორტისა; გამორთულისას მათ ელოდებით.
|
||||
@@ -6681,14 +6709,14 @@ font-technology Variable ცვლადი
|
||||
On the desktop, the folder recovery copies are kept in; leave it blank for VectorCraft's own folder. The web version keeps them in the browser. დესკტოპის ვერსიაში საქაღალდე, სადაც აღდგენის ასლები ინახება; დატოვეთ ცარიელი VectorCraft-ის საკუთარი საქაღალდისთვის. ვებ-ვერსია მათ ბრაუზერში ინახავს.
|
||||
No timed recovery copies are made of documents with more than 20,000 objects. 20 000-ზე მეტი ობიექტის მქონე დოკუმენტებისთვის პერიოდული აღდგენის ასლები არ კეთდება.
|
||||
Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. „ბოლოს გახსნილი ფაილების გახსნა“ და „საწყისი ეკრანი“ აჩვენებს მაქსიმუმ ამდენ ბოლო ფაილს; 0 არცერთს არ აჩვენებს, VectorCraft კი მაინც იმახსოვრებს 30-მდე ფაილს.
|
||||
When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. დოკუმენტის გახსნისას მიბმული EPS გამოსახულება, რომელიც თავის შენახულ გადახედვას აჩვენებს, ინარჩუნებს მას EPS ფაილის ხელახლა წაკითხვის ნაცვლად; შეცვლილი ფაილები კვლავ „ბმულების განახლებას“ მისდევს.
|
||||
When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. დოკუმენტის გახსნისას დაკავშირებული EPS გამოსახულება, რომელიც თავის შენახულ გადახედვას აჩვენებს, ინარჩუნებს მას EPS ფაილის ხელახლა წაკითხვის ნაცვლად; შეცვლილი ფაილები კვლავ „ბმულების განახლებას“ მისდევს.
|
||||
In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. „პიქსელების წინასწარ ნახვაში“ გამოსახულებები გლუვად იხატება; გამორთულისას მათი პიქსელები მკვეთრი კიდეებით ჩანს. მის გარეთ გამოსახულებები ყოველთვის გლუვდება.
|
||||
PDF Text PDF-ის ტექსტი
|
||||
The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. PDF-ის ტექსტი, რომელსაც ხსნით ან ჩაშენებთ, შემოდის რედაქტირებად ტექსტად ან კონტურებად, რომლებიც ერთნაირად ჩანს კომპიუტერზე მისი შრიფტების გარეშე.
|
||||
Linked pages show the file's own text. მიბმული გვერდები ფაილის საკუთარ ტექსტს აჩვენებს.
|
||||
When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. როცა მიბმული ფაილი იცვლება, „ავტომატურად“ მას ხელახლა კითხულობს, „შეკითხვა ცვლილებისას“ ჯერ გეკითხებათ, „ხელით“ კი უცვლელად ტოვებს და სტატუსის ზოლში შენიშვნას აჩვენებს.
|
||||
Linked pages show the file's own text. დაკავშირებული გვერდები ფაილის საკუთარ ტექსტს აჩვენებს.
|
||||
When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. როცა დაკავშირებული ფაილი იცვლება, „ავტომატურად“ მას ხელახლა კითხულობს, „შეკითხვა ცვლილებისას“ ჯერ გეკითხებათ, „ხელით“ კი უცვლელად ტოვებს და სტატუსის ზოლში შენიშვნას აჩვენებს.
|
||||
On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. დესკტოპის ვერსიაში საქაღალდე, საიდანაც „შაბლონიდან შექმნა…“ და „შაბლონად შენახვა…“ იწყება; დატოვეთ ცარიელი თქვენი დოკუმენტების საქაღალდეში არსებული VectorCraft Templates-ისთვის.
|
||||
Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. „ორიგინალის რედაქტირება“ მიბმულ ფაილს მისი ტიპისთვის სისტემის ნაგულისხმევ აპში ხსნის; გამორთულისას მიბმული რასტრული გამოსახულება PhotoCraft-ში იხსნება, თუ ის დაინსტალირებულია.
|
||||
Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. „ორიგინალის რედაქტირება“ დაკავშირებულ ფაილს მისი ტიპისთვის სისტემის ნაგულისხმევ აპში ხსნის; გამორთულისას დაკავშირებული რასტრული გამოსახულება PhotoCraft-ში იხსნება, თუ ის დაინსტალირებულია.
|
||||
A file saved by an older VectorCraft version opens with [Converted] after its name, and Save asks where to save it; off, Save replaces the file. VectorCraft-ის ძველი ვერსიით შენახული ფაილი სახელის შემდეგ [Converted]-ით იხსნება, „შენახვა“ კი გეკითხებათ, სად შეინახოს; გამორთულისას „შენახვა“ ფაილს ცვლის.
|
||||
VectorCraft files and templates are saved compressed, so they are smaller, unless a save says otherwise; saves for versions that cannot open compressed files stay uncompressed. VectorCraft-ის ფაილები და შაბლონები შეკუმშულად, ანუ უფრო მცირე ზომით ინახება, თუ შენახვა სხვას არ მიუთითებს; შენახვები ვერსიებისთვის, რომლებიც შეკუმშულ ფაილებს ვერ ხსნის, შეუკუმშავი რჩება.
|
||||
Copy and Cut also give other apps SVG code of the art; on the desktop, the code is not copied as text when the art embeds more than 1 MiB of images. კოპირება და ამოჭრა სხვა აპებს ნახატის SVG კოდსაც აძლევს; დესკტოპზე კოდი ტექსტად არ კოპირდება, როცა ნახატში 1 MiB-ზე მეტი სურათია ჩაშენებული.
|
||||
@@ -6697,7 +6725,7 @@ font-technology Variable ცვლადი
|
||||
Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. ტრაექტორიების შენარჩუნება ან იერსახისა და ზედდაბეჭდვების შენარჩუნება ძველი ვექტორული ბუფერისთვის; VectorCraft არჩევანს ინახავს, მაგრამ ჯერ არ იყენებს.
|
||||
Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. ფორმატირების შენარჩუნება VectorCraft-ის ტექსტური ობიექტიდან კოპირებული ტექსტის სტილებს ინახავს ტექსტურ ობიექტში ჩასმისას; მხოლოდ ტექსტის შენარჩუნება მას ჩასმის ადგილის სტილს აძლევს.
|
||||
Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. ყველა შავის მდიდარ შავად ჩვენება სუფთა CMYK შავს (მხოლოდ შავი მელანი 100%-ზე) ტილოზე RGB შავად აჩვენებს; ყველა შავის ზუსტად ჩვენება მას სამუშაო CMYK სივრცით გარდაქმნის.
|
||||
Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. ყველა შავის მდიდარ შავად გამოტანა სუფთა CMYK შავს RGB შავად ხატავს RGB და ნაცრისფერი გრადაციების რასტრულ ექსპორტებში და ბიტმაპად ბეჭდვისას; ის არ ცვლის ვექტორულ ექსპორტებს, CMYK JPEG-ს, TIFF-სა და PSD-ს ან სხვა ბეჭდვას.
|
||||
Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. ყველა შავის მდიდარ შავად გამოტანა სუფთა CMYK შავს RGB შავად ხატავს RGB და ნაცრისფერი ტონების რასტრულ ექსპორტებში და ბიტმაპად ბეჭდვისას; ის არ ცვლის ვექტორულ ექსპორტებს, CMYK JPEG-ს, TIFF-სა და PSD-ს ან სხვა ბეჭდვას.
|
||||
On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. სენსორულ ეკრანზე გადადის სენსორულ სამუშაო სივრცეზე; პარამეტრის გამორთვისას ან სენსორული ეკრანის დაკარგვისას ბრუნდება წინა სამუშაო სივრცეზე.
|
||||
A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. ტილოზე ორი თითით შეხება აბრუნებს მოქმედებას, სენსორულ სამუშაო სივრცეში კი მონიშვნისა და ხატვის ხელსაწყოებს შორის გადართავს; სამი თითით შეხება ხელახლა ასრულებს. პრეზენტაციის რეჟიმში არცერთი არ მუშაობს.
|
||||
In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. გადატანის ჩართვისას სიის სიტყვა მხოლოდ აკრეფილ დეფისებთან გადაიტანება, ან არსად, თუ არ აქვს, რეგისტრის მიუხედავად; კორეულ სიტყვებს დეფისი არ ემატება, ინდური ენების სიტყვები კი სიმბოლოთა ჯგუფის შიგნით არ გადაიტანება.
|
||||
@@ -6923,7 +6951,7 @@ font-technology Variable ცვლადი
|
||||
@msg `Custom` stands for changed settings: save the preset under another name `Custom` შეცვლილ პარამეტრებს ნიშნავს: შეინახეთ პრესეტი სხვა სახელით
|
||||
@msg `to` must be "corner" or "smooth" `to` უნდა იყოს "corner" ან "smooth"
|
||||
@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` უნდა იყოს "emBox", "capHeight", "xHeight" ან "icfBox"
|
||||
@msg BMP files are RGB or grayscale: colorModel rgb or gray BMP ფაილები RGB-ა ან ნაცრისფერი: colorModel rgb ან gray
|
||||
@msg BMP files are RGB or grayscale: colorModel rgb or gray BMP ფაილები ან RGB-ია, ან ნაცრისფერი ტონების: colorModel rgb ან gray
|
||||
@msg Blend colors: select at least three objects with filled colours ფერების შერევა: მონიშნეთ მინიმუმ სამი ობიექტი ფერადი შევსებით
|
||||
@msg Combine Slices: the slices have no bounds ნაჭრების გაერთიანება: ნაჭრებს საზღვრები არ აქვს
|
||||
@msg Convert to Artboards: selection has no area სამუშაო დაფებად გარდაქმნა: მონიშნულს ფართობი არ აქვს
|
||||
@@ -7058,7 +7086,7 @@ font-technology Variable ცვლადი
|
||||
@msg `{name}` is a process colour: tints apply to global and spot colours `{name}` პროცესული ფერია: ტონირება გამოიყენება გლობალურ და სპოტ-ფერებზე
|
||||
@msg `{name}` is no recovery entry name `{name}` აღდგენის ჩანაწერის სახელი არ არის
|
||||
@msg `{name}` isn't a colour swatch `{name}` ფერის ნიმუში არ არის
|
||||
@msg a process color can't colorize a grayscale image with transparency: use a spot color, black or white პროცესული ფერი ვერ გააფერადებს გამჭვირვალობის მქონე ნაცრისფერ გამოსახულებას: გამოიყენეთ სპოტ-ფერი, შავი ან თეთრი
|
||||
@msg a process color can't colorize a grayscale image with transparency: use a spot color, black or white პროცესული ფერი ვერ გააფერადებს გამჭვირვალობის მქონე ნაცრისფერი ტონების გამოსახულებას: გამოიყენეთ სპოტ-ფერი, შავი ან თეთრი
|
||||
@msg `{path}` must be a bool or an object of bools `{path}` უნდა იყოს bool ან bool-ების ობიექტი
|
||||
@msg `{s}` is not a colour (#rrggbb or a preset name) `{s}` ფერი არ არის (#rrggbb ან პრესეტის სახელი)
|
||||
@msg `{tool}` isn't a Liquify tool `{tool}` გათხევადების ხელსაწყო არ არის
|
||||
@@ -7780,20 +7808,20 @@ font-technology Variable ცვლადი
|
||||
@msg CDR fountain, pattern, texture and PostScript fills were left out CDR-ის გრადიენტული, ნიმუშის, ტექსტურის და PostScript შევსებები გამოტოვებულია
|
||||
@msg colors in CDR color models VectorCraft doesn't read were opened as black CDR-ის იმ ფერის მოდელების ფერები, რომლებსაც VectorCraft ვერ კითხულობს, შავად გაიხსნა
|
||||
@msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR-ის ბიბლიოთეკის ფერები, რომლებსაც ნახაზი მხოლოდ ნომრით ინახავს, შავ სპოტ-ფერებად გაიხსნა
|
||||
@msg CDR outline arrowheads were left out CDR-ის მოხაზულობების ისრისპირები გამოტოვებულია
|
||||
@msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR-ის კონვერტები არ იქნა გამოყენებული, და მათ ქვეშ მყოფი ფორმები ინარჩუნებენ თავიანთ მოხაზულობას
|
||||
@msg CDR outline arrowheads were left out CDR-ის კონტურების ისრის წვერები გამოტოვებულია
|
||||
@msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR-ის გარსები არ იქნა გამოყენებული და მათ ქვეშ მყოფი ფიგურები თავიანთ მოხაზულობას ინარჩუნებს
|
||||
@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque CDR-ის ლინზები და ობიექტის გამჭვირვალობა არ იქნა გამოყენებული, და ობიექტები, რომლებზეც ისინია, გაუმჭვირვალედ ჩანს
|
||||
@msg parts of the drawing nested too deeply, or past the import limits, were left out ნახაზის ზედმეტად ღრმად ჩადგმული ან იმპორტის ლიმიტებს მიღმა არსებული ნაწილები გამოტოვებულია
|
||||
@msg damaged parts of the drawing were left out ნახაზის დაზიანებული ნაწილები გამოტოვებულია
|
||||
@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163 830 pt-ზე გრძელი CDR-ის გვერდები ამ სიგრძით გაიხსნა და მათ კიდეებთან ახლოს მყოფი გრაფიკა სამუშაო დაფის გარეთაა
|
||||
@msg this CMX file can't be read ({why}) ამ CMX ფაილის წაკითხვა შეუძლებელია ({why})
|
||||
@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out CMX-ის ტექსტები, გამოსახულებები, მართკუთხედები, ელიფსები, ამოჭრის კონტურები და სხვა ობიექტები, რომლებსაც VectorCraft ჯერ ვერ კითხულობს, გამოტოვებულია
|
||||
@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out CMX-ის ტექსტები, გამოსახულებები, მართკუთხედები, ელიფსები, მომჭრელი ტრაექტორიები და სხვა ობიექტები, რომლებსაც VectorCraft ჯერ ვერ კითხულობს, გამოტოვებულია
|
||||
@msg CMX fills other than uniform colors were left out CMX-ის შევსებები, გარდა ერთგვაროვანი ფერებისა, გამოტოვებულია
|
||||
@msg colors in CMX color models VectorCraft doesn't read were opened as black CMX-ის იმ ფერის მოდელების ფერები, რომლებსაც VectorCraft ვერ კითხულობს, შავად გაიხსნა
|
||||
@msg CMX library colors that the file stores only by number were opened as black spot colors CMX-ის ბიბლიოთეკის ფერები, რომლებსაც ფაილი მხოლოდ ნომრით ინახავს, შავ სპოტ-ფერებად გაიხსნა
|
||||
@msg CMX outline arrowheads were left out CMX-ის მოხაზულობების ისრისპირები გამოტოვებულია
|
||||
@msg CMX lenses were not applied CMX-ის ლინზები არ იქნა გამოყენებული
|
||||
@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163 830 pt-ზე გრძელი CMX-ის გვერდები ამ სიგრძით გაიხსნა და მათ კიდეებთან ახლოს მყოფი გრაფიკა სამუშაო დაფის გარეთაა
|
||||
@msg CMX outline arrowheads were left out CMX-ის კონტურების ისრის წვერები გამოტოვებულია
|
||||
@msg CMX lenses were not applied CMX-ის ლინზები არ გამოყენებულა
|
||||
@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163 830 pt-ზე გრძელი CMX-ის გვერდები ამ სიგრძით გაიხსნა და მათ კიდეებთან ახლოს მყოფი ნახატი სამუშაო დაფის გარეთაა
|
||||
@msg the PSD image is too large to read ({_1} × {_2} pixels) PSD გამოსახულება ზედმეტად დიდია წასაკითხად ({_1} × {_2} პიქსელი)
|
||||
@msg zipped 1-bit PSD image data with prediction can't be read zip-ით შეკუმშული 1-ბიტიანი PSD გამოსახულების მონაცემების წაკითხვა პროგნოზირებით ვერ ხერხდება
|
||||
@msg the PSD file's layer data uses an unknown compression ({m}) PSD ფაილის შრეების მონაცემები უცნობ შეკუმშვას იყენებს ({m})
|
||||
@@ -8246,9 +8274,9 @@ arrowhead Feather ბუმბული
|
||||
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` უნდა იყოს ობიექტი, რომელიც შეიცავს მხოლოდ `mode`-ს, მნიშვნელობით shaded ან wireframe
|
||||
@msg its 3D effect builds no solid მისი 3D ეფექტი სხეულს არ ქმნის
|
||||
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel უნდა იყოს none, ერთ-ერთი: {_1}, ან custom და {BEVEL_PROFILE}
|
||||
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom მოითხოვს {BEVEL_PROFILE}, წაკვეთის წერტილები
|
||||
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom-ს სჭირდება {BEVEL_PROFILE} — წაკვეთის წერტილები
|
||||
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} უნდა იყოს სტრიქონი
|
||||
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} უნდა შეიცავდეს 2-დან {most}-მდე [x, y] წერტილს, თითოეული წილი 0-სა და 1-ს შორის, [0, 0]-დან (ბოლო წახნაგის კიდე) [1, 1]-მდე (გვერდითი კედელი)
|
||||
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} უნდა შეიცავდეს 2-დან {most}-მდე [x, y] წერტილს, თითოეული წილი 0-სა და 1-ს შორის, [0, 0]-დან (თავსახურის კიდე) [1, 1]-მდე (გვერდითი კედელი)
|
||||
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}: ამ ნახატიდან სხეულების შექმნა შეუძლებელია: მისი სიმბოლოს ეგზემპლარები, გადასვლები და მომჭრელი ჯგუფები ზედმეტად ბევრ ობიექტს შეიცავს
|
||||
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}: სიმბოლოს „{symbol}“ ეგზემპლარიდან სხეულის შექმნა შეუძლებელია: სიმბოლოს ნახატი მიუწვდომელია
|
||||
@msg {_1}: the clipping path is too complex to cut the art with {_1}: მომჭრელი ტრაექტორია ზედმეტად რთულია ნახატის მოსაჭრელად
|
||||
@@ -8394,7 +8422,7 @@ mark-style Japanese იაპონური
|
||||
RGB RGB
|
||||
Rotate View ხედის შემობრუნება
|
||||
Scissors მაკრატელი
|
||||
Shades of Gray ნაცრისფერი გრადაციები
|
||||
Shades of Gray ნაცრისფერი ტონები
|
||||
Shear: დახრა:
|
||||
Shift+Click Shift+დაწკაპუნება
|
||||
Shift+Drag Shift+გადათრევა
|
||||
@@ -9529,8 +9557,8 @@ axis Y Axis Y ღერძი
|
||||
@msg `opacity` must be a number `opacity` უნდა იყოს რიცხვი
|
||||
@msg `opacity` must be a number from 0 to 100 `opacity` უნდა იყოს რიცხვი 0-დან 100-მდე
|
||||
@msg `opacity` must be true or false `opacity` უნდა იყოს true ან false
|
||||
@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke ტექსტის სიმბოლოებს საკუთარი გაუმჭვირვალობა არ აქვთ: დაამატეთ შევსება ან კონტური იერსახის პანელის ბრძანებით ახალი შევსების დამატება ან ახალი კონტურის დამატება
|
||||
@msg an object selected in a symbol instance has no fill or stroke opacity of its own სიმბოლოს ეგზემპლარში არჩეულ ობიექტს შევსების ან კონტურის საკუთარი გაუმჭვირვალობა არ აქვს
|
||||
@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke ტექსტის სიმბოლოებს საკუთარი გაუმჭვირვალობა არ აქვთ: დაამატეთ შევსება ან კონტური იერსახის პანელის ბრძანებით „ახალი შევსების დამატება“ ან „ახალი კონტურის დამატება“
|
||||
@msg an object selected in a symbol instance has no fill or stroke opacity of its own სიმბოლოს ეგზემპლარში მონიშნულ ობიექტს შევსების ან კონტურის საკუთარი გაუმჭვირვალობა არ აქვს
|
||||
@msg no target has that fill or stroke to take the opacity არცერთ სამიზნეს არ აქვს ის შევსება ან კონტური, რომელიც გაუმჭვირვალობას მიიღებს
|
||||
@msg `type` must be "path" or "compound" `type` უნდა იყოს "path" ან "compound"
|
||||
@msg `unit` must be 1-{MAX_UNIT} printable characters `unit` უნდა შედგებოდეს 1-{MAX_UNIT} დასაბეჭდი სიმბოლოსგან
|
||||
@@ -9584,7 +9612,7 @@ axis Y Axis Y ღერძი
|
||||
@msg `plates` requires a stop linked to a spot swatch `plates` მოითხოვს გადასვლის წერტილს, რომელიც სპოტ-ფერის ნიმუშთანაა დაკავშირებული
|
||||
@msg the output გამოტანა
|
||||
@msg the path has no anchor points ტრაექტორიას საყრდენი წერტილები არ აქვს
|
||||
@msg compound path {id} has a hidden, locked or guide member, so its members can't be replaced შედგენილ ტრაექტორიას {id} აქვს დამალული, ჩაკეტილი ან დამხმარე ხაზის წევრი, ამიტომ მისი წევრების ჩანაცვლება შეუძლებელია
|
||||
@msg compound path {id} has a hidden, locked or guide member, so its members can't be replaced შედგენილ ტრაექტორიას {id} აქვს წევრი, რომელიც დამალულია, ჩაკეტილია ან დამხმარე ხაზია, ამიტომ მისი წევრების ჩანაცვლება შეუძლებელია
|
||||
@msg compound path {id} has a member that isn't a path, so its members can't be replaced შედგენილ ტრაექტორიას {id} აქვს წევრი, რომელიც ტრაექტორია არ არის, ამიტომ მისი წევრების ჩანაცვლება შეუძლებელია
|
||||
@msg too many anchor points (limit {MAX_ANCHORS}) ძალიან ბევრი საყრდენი წერტილი (ლიმიტი {MAX_ANCHORS})
|
||||
@msg true or false true ან false
|
||||
@@ -9707,7 +9735,7 @@ axis Y Axis Y ღერძი
|
||||
@msg expected {count} paragraph styles, one per paragraph მოსალოდნელი იყო აბზაცის {count} სტილი, თითო აბზაცზე ერთი
|
||||
@msg the document has no Kinsoku set named '{shown}' დოკუმენტს არ აქვს Kinsoku-ის ნაკრები სახელით '{shown}'
|
||||
@msg must be 1-{MAX_FAMILY} printable characters უნდა შედგებოდეს 1-{MAX_FAMILY} დასაბეჭდი სიმბოლოსგან
|
||||
Read the objects it is given, and the document's settings, artboards, layers and swatches მიღებული ობიექტების და დოკუმენტის პარამეტრების, სამუშაო დაფების, შრეებისა და ფერის ნიმუშების წაკითხვა
|
||||
Read the objects it is given, and the document's settings, artboards, layers and swatches მიღებული ობიექტებისა და დოკუმენტის პარამეტრების, სამუშაო დაფების, შრეებისა და ფერის ნიმუშების წაკითხვა
|
||||
@msg `context` must list distinct sections: settings, artboards, layers or swatches `context`-ში განსხვავებული სექციები უნდა იყოს: settings, artboards, layers ან swatches
|
||||
@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` განკუთვნილია ფილტრისთვის ან `commands`-ის მქონე ცოცხალი ეფექტისთვის, `api` 3-ზე ან უფრო ახალზე, ნებართვით `doc.read`
|
||||
@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes პლაგინის მიერ მოთხოვნილი დოკუმენტის ინფორმაცია ზედმეტად დიდია გადასაცემად: მაქსიმუმ {MAX_CONTEXT_ITEMS} სამუშაო დაფა, შრე და ფერის ნიმუში {MAX_CONTEXT_BYTES} ბაიტში
|
||||
@@ -9823,8 +9851,8 @@ axis Y Axis Y ღერძი
|
||||
Action Set: მოქმედებების ნაკრები:
|
||||
Choose Align To at playback შესრულებისას სწორების სამიზნის არჩევა
|
||||
Align steps use the key object, key anchor or key guide when one is set. სწორების ნაბიჯები იყენებს საკვანძო ობიექტს, საკვანძო საყრდენ წერტილს ან საკვანძო დამხმარე ხაზს, თუ ის მითითებულია.
|
||||
With one whole object selected and no key, they use the artboard. ერთი მთლიანი მონიშნული ობიექტისას და გასაღების გარეშე ისინი იყენებს სამუშაო დაფას.
|
||||
Otherwise they use the selection. სხვა შემთხვევაში ისინი იყენებს მონიშნულს.
|
||||
With one whole object selected and no key, they use the artboard. თუ მონიშნულია ერთი მთლიანი ობიექტი და საკვანძო არაფერია მითითებული, ისინი სამუშაო დაფას იყენებს.
|
||||
Otherwise they use the selection. სხვა შემთხვევაში ისინი მონიშნულს იყენებენ.
|
||||
Function Key: ფუნქციური კლავიში:
|
||||
Record ჩაწერა
|
||||
Create New Set ახალი ნაკრების შექმნა
|
||||
@@ -9850,7 +9878,7 @@ axis Y Axis Y ღერძი
|
||||
Panel პანელი
|
||||
UI Frames UI ჩარჩოები
|
||||
Map Markers რუკის ნიშნულები
|
||||
Pin ქინძისთავი
|
||||
Pin სამაგრი
|
||||
Flag დროშა
|
||||
Crosshair სამიზნე
|
||||
Checkpoint საკონტროლო წერტილი
|
||||
@@ -10506,7 +10534,7 @@ anchor Points: წერტილები:
|
||||
Objects with Color Effects ობიექტები ფერის ეფექტებით
|
||||
RGB Images RGB გამოსახულებები
|
||||
CMYK Images CMYK გამოსახულებები
|
||||
Grayscale Images ნაცრისფერის გრადაციის გამოსახულებები
|
||||
Grayscale Images ნაცრისფერი ტონების გამოსახულებები
|
||||
@msg `kind` must be spotColors, colorEffects, rgbImages, cmykImages or grayImages `kind` უნდა იყოს spotColors, colorEffects, rgbImages, cmykImages ან grayImages
|
||||
|
||||
# Color Effects add-on: Vector Halftone (Effect › Color Effects).
|
||||
@@ -10788,7 +10816,7 @@ breakText Glyphs გლიფები
|
||||
Add Bounding Rectangle შემომსაზღვრელი მართკუთხედის დამატება
|
||||
Add Bounding Circle შემომსაზღვრელი წრეწირის დამატება
|
||||
Add Bounding Rectangle… შემომსაზღვრელი მართკუთხედის დამატება…
|
||||
Add Bounding Circle… შემომსაზღვრელი წრეწირის დამატება…
|
||||
Add Bounding Circle… შემომსაზღვრელი წრის დამატება…
|
||||
One per Object თითო თითოეულ ობიექტზე
|
||||
@msg nothing to enclose შემოსაზღვრელი არაფერია
|
||||
@msg `offset` must be 0 or more `offset` უნდა იყოს 0 ან მეტი
|
||||
@@ -10806,12 +10834,12 @@ breakText Glyphs გლიფები
|
||||
Convert Layers to Symbols შრეების სიმბოლოებად გარდაქმნა
|
||||
@msg {id} is no top-level layer {id} არ არის ზედა დონის შრე
|
||||
Marathi მარათჰი
|
||||
Gujarati გუჯარათი
|
||||
Gujarati გუჯარათული
|
||||
Bengali ბენგალური
|
||||
Punjabi პენჯაბური
|
||||
Tamil ტამილური
|
||||
Telugu ტელუგუ
|
||||
Kannada კანადა
|
||||
Kannada კანნადა
|
||||
Malayalam მალაიალამური
|
||||
Odia ორია
|
||||
Urdu ურდუ
|
||||
@@ -11267,13 +11295,13 @@ font-script Japanese იაპონური
|
||||
Ornamental ორნამენტული
|
||||
Scrollwork ხვეული
|
||||
Filigree Arrow ფილიგრანული ისარი
|
||||
Petal Sweep ფურცლების რკალი
|
||||
Petal Sweep ყვავილის ფურცლების რკალი
|
||||
Twin Curl ორმაგი ხვეული
|
||||
Vector Packs ვექტორული პაკეტები
|
||||
Compass Rose კომპასის ვარდი
|
||||
Botanical Sprig ბოტანიკური ტოტი
|
||||
Botanical Sprig ბოტანიკური რტო
|
||||
Facet Diamond წახნაგოვანი ბრილიანტი
|
||||
Tide Crest ტალღის ქედი
|
||||
Tide Crest ტალღის თხემი
|
||||
Leaf Vine ფოთლების ვაზი
|
||||
Blossom Chain ყვავილების ჯაჭვი
|
||||
Pennant Garland ალმების გირლანდა
|
||||
@@ -11310,7 +11338,7 @@ font-script Japanese იაპონური
|
||||
Rose Layers ვარდისფერი ფენები
|
||||
Monochrome Stack მონოქრომული დასტა
|
||||
# Tool cards (General › Show Tool Cards): one sentence on what each tool does.
|
||||
Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. ინსტრუმენტების ზოლის ინსტრუმენტისა და მისი კლავიშების მოქმედებას მინიშნების ნაცვლად ბარათზე აჩვენებს; საჭიროა მინიშნებების ჩვენება.
|
||||
Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. ინსტრუმენტების ზოლის ინსტრუმენტისა და მისი კლავიშების მოქმედებას მინიშნების ნაცვლად ბარათზე აჩვენებს; ამისთვის საჭიროა მინიშნებების ჩვენების ჩართვა.
|
||||
Selects whole objects and groups to move, resize or rotate them. მთლიანად მონიშნავს ობიექტებსა და ჯგუფებს მათი გადასაადგილებლად, ზომის შესაცვლელად ან მოსაბრუნებლად.
|
||||
Selects anchor points and path segments to reshape a path. მონიშნავს საყრდენ წერტილებსა და ტრაექტორიის სეგმენტებს ტრაექტორიის ფორმის შესაცვლელად.
|
||||
Draws paths point by point, with straight segments and smooth curves. ხატავს ტრაექტორიებს წერტილ-წერტილ, სწორი სეგმენტებითა და გლუვი მრუდებით.
|
||||
@@ -11331,7 +11359,7 @@ font-script Japanese იაპონური
|
||||
Sets the direction and length of a gradient. აყენებს გრადიენტის მიმართულებასა და სიგრძეს.
|
||||
Creates, selects and resizes artboards. ქმნის, მონიშნავს და ცვლის სამუშაო დაფების ზომას.
|
||||
Changes the width of a stroke along its length. ცვლის კონტურის სისქეს მისი სიგრძის გასწვრივ.
|
||||
Bends art by dragging pins placed on it. ღუნავს ნახატს მასზე დასმული ქინძისთავების გადათრევით.
|
||||
Bends art by dragging pins placed on it. ნახატს ღუნავს მასზე დასმული სამაგრების გადათრევით.
|
||||
Pushes the outlines of paths in the direction you drag. უბიძგებს ტრაექტორიების მოხაზულობას გადათრევის მიმართულებით.
|
||||
Twists the outlines of paths into swirls. ხვევს ტრაექტორიების მოხაზულობას გრიგალებად.
|
||||
Pulls the outlines of paths in toward the brush. იზიდავს ტრაექტორიების მოხაზულობას ფუნჯისკენ.
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1574,7 +1574,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.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`)",
|
||||
"{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.color.screenMarks|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",
|
||||
|
||||
@@ -338,6 +338,40 @@ pub(crate) fn format_target_kept(app: &mut VectorcraftApp) -> Result<FormatTarge
|
||||
Ok(format_target(app, editing))
|
||||
}
|
||||
|
||||
/// What a character field edits, as its edit target: the document, how many times File › Revert
|
||||
/// and Undo or Redo replaced its content (after which a node id can name another object), and the
|
||||
/// text the changes go to ([`format_target`]): the range or story the Type tool has selected, else
|
||||
/// the selected stories. With `caret` set, a caret keeps its offset, since the Character panel's
|
||||
/// Kerning field sets the pair at the caret ([`set_kerning`]). Without it, a caret and a range over
|
||||
/// the whole text both key as all of the text, which is what `text.setStyle` changes at a caret
|
||||
/// ([`range_style`]). A field drops a value typed and not yet committed when this changes, even
|
||||
/// where the new text has the same value.
|
||||
fn character_target(app: &VectorcraftApp, caret: bool) -> Option<(u64, u64, u64, FormatTarget)> {
|
||||
let st = app.session.active()?;
|
||||
// The range [`text_editing`] clamps to the stored text, or, while Real-time Drawing off leaves
|
||||
// typing unapplied, the Type tool's own offsets, which can reach into that typing, clamped to
|
||||
// the length the text has with it ([`pending_text_len`]). The same characters key the same
|
||||
// whether a drag or Select All, whose end lies past the text, selected them.
|
||||
let o = app.session.tool_options();
|
||||
let offset = |k: &str| o.get(k).and_then(Value::as_u64).map_or(0, |v| v as usize);
|
||||
let editing = text_editing(app).map(|(id, a, b)| {
|
||||
let unapplied_typing = o.get("typing").and_then(Value::as_bool) == Some(true)
|
||||
&& st.interaction.as_ref().is_some_and(|it| it.label == "Typing" && it.preview.is_some() && std::sync::Arc::ptr_eq(&it.doc, &st.doc));
|
||||
let (a, b, len) = if unapplied_typing {
|
||||
let (a, b) = (offset("start"), offset("end"));
|
||||
pending_text_len(st, id).map_or((a, b, None), |len| (a.min(len), b.min(len), Some(len)))
|
||||
} else {
|
||||
let len = st.doc.node(id).and_then(|node| match &node.kind {
|
||||
NodeKind::Text(t) => Some(vectorcraft_text::edit::runs_len(&t.runs)),
|
||||
_ => None,
|
||||
});
|
||||
(a, b, len)
|
||||
};
|
||||
if caret || (b > a && !(a == 0 && len.is_some_and(|len| b >= len))) { (id, a, b) } else { (id, 0, 0) }
|
||||
});
|
||||
Some((st.uid, st.reverts, st.history_restores, format_target(app, editing)))
|
||||
}
|
||||
|
||||
/// Apply a settings dialog to its opening text only. Compare before keeping typing so a
|
||||
/// refused confirmation on different text does not commit that text's in-progress edit.
|
||||
pub(crate) fn run_format_at_target(app: &mut VectorcraftApp, p: Value, target: &FormatTarget) -> Result<Value, String> {
|
||||
@@ -1230,6 +1264,7 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow
|
||||
let sets = font_menu::family_sets(hold.document.as_deref(), &hold.recently_added);
|
||||
let sample = font_menu::sample_text(app);
|
||||
let unit = type_unit(app);
|
||||
let target = character_target(app, true);
|
||||
let mut source = FontPickerSource::new(catalog)
|
||||
.settings(Bind::bound(&mut hold.settings))
|
||||
.filters(Bind::bound(&mut hold.filters))
|
||||
@@ -1244,7 +1279,8 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow
|
||||
.rows(rows)
|
||||
.font_picker(source)
|
||||
.axes_layout(AxesLayout::Button)
|
||||
.anti_alias_methods(&ANTI_ALIAS_METHODS);
|
||||
.anti_alias_methods(&ANTI_ALIAS_METHODS)
|
||||
.edit_target(target);
|
||||
if let Some(languages) = &languages {
|
||||
controls = controls.languages(languages);
|
||||
}
|
||||
@@ -1323,37 +1359,6 @@ fn snap_to_glyph(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// What the bars' Font Size field edits, as its edit target: the document, how many times File ›
|
||||
/// Revert and Undo or Redo replaced its content (after which a node id can name another object),
|
||||
/// and the text `text.setStyle` changes ([`format_target`]): the range or story the Type tool has
|
||||
/// selected, all of the edited text at a caret, else the selected stories. The field drops a value
|
||||
/// typed and not yet committed when this changes, even where the new text has the same size.
|
||||
fn size_target(app: &VectorcraftApp) -> Option<(u64, u64, u64, FormatTarget)> {
|
||||
let st = app.session.active()?;
|
||||
// The range [`text_editing`] clamps to the stored text, or, while Real-time Drawing off leaves
|
||||
// typing unapplied, the Type tool's own offsets, which can reach into that typing, clamped to
|
||||
// the length the text has with it ([`pending_text_len`]). A caret changes the whole text
|
||||
// wherever it is ([`range_style`]); a range over the whole text keys as a caret does.
|
||||
let o = app.session.tool_options();
|
||||
let offset = |k: &str| o.get(k).and_then(Value::as_u64).map_or(0, |v| v as usize);
|
||||
let editing = text_editing(app).map(|(id, a, b)| {
|
||||
let unapplied_typing = o.get("typing").and_then(Value::as_bool) == Some(true)
|
||||
&& st.interaction.as_ref().is_some_and(|it| it.label == "Typing" && it.preview.is_some() && std::sync::Arc::ptr_eq(&it.doc, &st.doc));
|
||||
let (a, b, len) = if unapplied_typing {
|
||||
let (a, b) = (offset("start"), offset("end"));
|
||||
pending_text_len(st, id).map_or((a, b, None), |len| (a.min(len), b.min(len), Some(len)))
|
||||
} else {
|
||||
let len = st.doc.node(id).and_then(|node| match &node.kind {
|
||||
NodeKind::Text(t) => Some(vectorcraft_text::edit::runs_len(&t.runs)),
|
||||
_ => None,
|
||||
});
|
||||
(a, b, len)
|
||||
};
|
||||
if b > a && !(a == 0 && len.is_some_and(|len| b >= len)) { (id, a, b) } else { (id, 0, 0) }
|
||||
});
|
||||
Some((st.uid, st.reverts, st.history_restores, format_target(app, editing)))
|
||||
}
|
||||
|
||||
/// The byte length text `id` will have once the typing that Real-time Drawing off leaves unapplied
|
||||
/// is applied: the stored text with the `text.editRange` preview's range replaced by its runs.
|
||||
/// `None` for a frame of a threaded story, whose text can reflow from other frames, when the
|
||||
@@ -1380,9 +1385,9 @@ fn pending_text_len(st: &DocState, id: NodeId) -> Option<usize> {
|
||||
|
||||
/// The Font Size field of the bars, named `name`: typed, stepped, scrubbed or picked from the
|
||||
/// presets, in the type unit, blank where the selected text's sizes differ. A value typed and not
|
||||
/// yet committed stays with the text it was typed for ([`size_target`]).
|
||||
/// yet committed stays with the text it was typed for ([`character_target`]).
|
||||
fn size_field(app: &mut VectorcraftApp, ui: &mut Ui, name: &'static str) {
|
||||
let target = size_target(app);
|
||||
let target = character_target(app, false);
|
||||
let unit = type_unit(app);
|
||||
let scale = unit_scale(unit);
|
||||
let units = Env::of(ui).units();
|
||||
|
||||
@@ -433,6 +433,282 @@ fn highlight_commands_ask_the_framework_to_focus_the_field_by_key() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A number field of the character controls, by name, and the attribute of a character it sets.
|
||||
type CharacterField = (&'static str, fn(&CharStyle) -> f64);
|
||||
|
||||
/// The Character panel's number fields with its options and the East Asian and Middle Eastern
|
||||
/// options shown. Properties shows the first four.
|
||||
const CHARACTER_FIELDS: [CharacterField; 13] = [
|
||||
("Font size", |s| s.size),
|
||||
("Leading", |s| s.leading.unwrap_or(0.0)),
|
||||
("Kerning", |s| s.kerning.unwrap_or(0.0)),
|
||||
("Tracking", |s| s.tracking),
|
||||
("Vertical scale", |s| s.v_scale),
|
||||
("Horizontal scale", |s| s.h_scale),
|
||||
("Baseline shift", |s| s.baseline_shift),
|
||||
("Rotation", |s| s.rotation),
|
||||
("Insert Aki Left", |s| s.aki_left),
|
||||
("Insert Aki Right", |s| s.aki_right),
|
||||
("Tsume", |s| s.tsume),
|
||||
("Horizontal Diacritic Position", |s| s.diacritic_horizontal),
|
||||
("Vertical Diacritic Position", |s| s.diacritic_vertical),
|
||||
];
|
||||
|
||||
/// A panel that shows the character controls: its name, how it draws and the fields it shows.
|
||||
type CharacterDraw = (&'static str, fn(&mut VectorcraftApp, &mut egui::Ui), &'static [CharacterField]);
|
||||
|
||||
/// The Character panel and Properties with the fields each shows.
|
||||
fn character_draws() -> [CharacterDraw; 2] {
|
||||
[("Character", show, &CHARACTER_FIELDS), ("Properties", super::super::properties::show, &CHARACTER_FIELDS[..4])]
|
||||
}
|
||||
|
||||
/// A document with two text objects, `Ab` and `Cd`, at 12 pt with a leading of 20 pt and a tracking
|
||||
/// of 10, and the East Asian and Middle Eastern options shown.
|
||||
fn two_styled_texts() -> (VectorcraftApp, u64, u64) {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.prefs.show_east_asian_options = true;
|
||||
app.session.prefs.show_indic_options = true;
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
let a = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = app.run("text.create", json!({"x": 20, "y": 140, "text": "Cd", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("text.setStyle", json!({"ids": [a, b], "leading": 20, "tracking": 10})).unwrap();
|
||||
(app, a, b)
|
||||
}
|
||||
|
||||
/// Types `3+` into the field `name` without committing it.
|
||||
fn type_unfinished(p: &mut crate::tests::panel_harness::Panel, name: &str) {
|
||||
p.focus(name);
|
||||
p.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
p.type_text("3+");
|
||||
}
|
||||
|
||||
/// Draws a frame, then types `1` and Enter into the focused field.
|
||||
fn finish_typing(p: &mut crate::tests::panel_harness::Panel) {
|
||||
p.frame();
|
||||
p.type_text("1");
|
||||
p.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
}
|
||||
|
||||
/// The attribute `read` of each run of the text `id`.
|
||||
fn run_values(app: &VectorcraftApp, id: u64, read: fn(&CharStyle) -> f64) -> Vec<(String, f64)> {
|
||||
block_text(app, NodeId(id)).runs.iter().map(|r| (r.text.clone(), read(&r.style))).collect()
|
||||
}
|
||||
|
||||
/// The number fields of the Character panel and Properties keep a value typed and not yet committed
|
||||
/// while the text it was typed for stays selected, and drop it when other text with the same value
|
||||
/// is selected.
|
||||
#[test]
|
||||
fn an_unfinished_character_value_does_not_reach_other_selected_text() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
for (panel, draw, fields) in character_draws() {
|
||||
for &(name, read) in fields {
|
||||
let (mut app, a, b) = two_styled_texts();
|
||||
let before = run_values(&app, a, read);
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let mut p = Panel::new(app, draw);
|
||||
type_unfinished(&mut p, name);
|
||||
finish_typing(&mut p);
|
||||
assert_eq!(run_values(&p.app(), a, read), [("Ab".to_string(), 4.0)], "{panel} {name}: an unchanged selection keeps 3+");
|
||||
p.app().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(run_values(&p.app(), a, read), before, "{panel} {name}: undone");
|
||||
|
||||
type_unfinished(&mut p, name);
|
||||
p.app().run("select.set", json!({"ids": [b]})).unwrap();
|
||||
finish_typing(&mut p);
|
||||
let app = p.app();
|
||||
assert_eq!(
|
||||
(run_values(&app, a, read), run_values(&app, b, read)),
|
||||
(before, vec![("Cd".to_string(), 1.0)]),
|
||||
"{panel} {name}: b takes 1, not 3+1"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// While the Type tool edits text, a value typed into the Character panel belongs to the selected
|
||||
/// characters: another range in the same text drops it.
|
||||
#[test]
|
||||
fn an_unfinished_character_value_does_not_reach_another_text_range() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
for (panel, draw, _) in character_draws() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Abcd", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.session.select_tool("type", Default::default()).unwrap();
|
||||
app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 2}));
|
||||
let mut p = Panel::new(app, draw);
|
||||
type_unfinished(&mut p, "Tracking");
|
||||
p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 2, "caret": 4}));
|
||||
finish_typing(&mut p);
|
||||
let want = vec![("Ab".to_string(), 0.0), ("cd".to_string(), 1.0)];
|
||||
assert_eq!(run_values(&p.app(), id, |s| s.tracking), want, "{panel}: the second range takes 1, not 3+1");
|
||||
}
|
||||
}
|
||||
|
||||
/// While the Type tool edits text, a range dragged over the whole text and Select All select the same
|
||||
/// characters, so a value typed with one selected is kept when the other replaces it.
|
||||
#[test]
|
||||
fn an_unfinished_character_value_survives_select_all_over_the_same_characters() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
for (panel, draw, _) in character_draws() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Abcd", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.session.select_tool("type", Default::default()).unwrap();
|
||||
app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 4}));
|
||||
let mut p = Panel::new(app, draw);
|
||||
type_unfinished(&mut p, "Tracking");
|
||||
p.app().run("select.all", json!({})).unwrap();
|
||||
finish_typing(&mut p);
|
||||
assert_eq!(run_values(&p.app(), id, |s| s.tracking), [("Abcd".to_string(), 4.0)], "{panel}: Select All keeps 3+");
|
||||
}
|
||||
}
|
||||
|
||||
/// At a caret the Kerning field sets the pair at the caret, so a value typed there does not reach
|
||||
/// the pair at another caret position in the same text, though both pairs have the same kerning.
|
||||
#[test]
|
||||
fn an_unfinished_kerning_does_not_reach_another_caret_position() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
for (panel, draw, _) in character_draws() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Abcd", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("text.setRangeStyle", json!({"id": id, "kerning": 10})).unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.session.select_tool("type", Default::default()).unwrap();
|
||||
app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 1, "caret": 1}));
|
||||
let mut p = Panel::new(app, draw);
|
||||
type_unfinished(&mut p, "Kerning");
|
||||
p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 3, "caret": 3}));
|
||||
finish_typing(&mut p);
|
||||
let kernings: Vec<f64> = run_values(&p.app(), id, |s| s.kerning.unwrap_or(0.0)).into_iter().map(|(_, k)| k).collect();
|
||||
assert!(kernings.contains(&1.0) && !kernings.contains(&4.0), "{panel}: the pair at the second caret takes 1, not 3+1: {kernings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Another document whose text has the same id and tracking drops the value.
|
||||
#[test]
|
||||
fn an_unfinished_character_value_does_not_reach_another_document() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let (mut app, a, _) = two_styled_texts();
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
let other = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_eq!(other, a, "both documents' texts have the same id");
|
||||
app.run("text.setStyle", json!({"ids": [a], "tracking": 10})).unwrap();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let mut p = Panel::new(app, show);
|
||||
type_unfinished(&mut p, "Tracking");
|
||||
p.app().run("document.activate", json!({"index": 1})).unwrap();
|
||||
finish_typing(&mut p);
|
||||
let tracking = |s: &CharStyle| s.tracking;
|
||||
let second = run_values(&p.app(), a, tracking);
|
||||
p.app().run("document.activate", json!({"index": 0})).unwrap();
|
||||
let first = run_values(&p.app(), a, tracking);
|
||||
assert_eq!((first, second), (vec![("Ab".to_string(), 10.0)], vec![("Ab".to_string(), 1.0)]), "the other document takes 1");
|
||||
}
|
||||
|
||||
/// File › Revert drops the value, though the restored text has the same id and tracking.
|
||||
#[test]
|
||||
fn an_unfinished_character_value_is_dropped_by_file_revert() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let (mut app, a, _) = two_styled_texts();
|
||||
let dir = vectorcraft_testkit::TempDir::new("character-value-revert");
|
||||
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
|
||||
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
|
||||
app.run("file.saveAs", json!({"path": dir.join("Type.vectorcraft")})).unwrap();
|
||||
// An unsaved change for Revert to undo, leaving the text as saved.
|
||||
app.run("shape.rectangle", json!({"x": 100, "y": 200, "width": 20, "height": 20})).unwrap();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let mut p = Panel::new(app, show);
|
||||
type_unfinished(&mut p, "Tracking");
|
||||
p.app().run("file.revert", json!({"confirmed": true})).unwrap();
|
||||
p.app().run("select.set", json!({"ids": [a]})).unwrap();
|
||||
finish_typing(&mut p);
|
||||
assert_eq!(run_values(&p.app(), a, |s| s.tracking), [("Ab".to_string(), 1.0)], "Revert drops the unfinished value");
|
||||
}
|
||||
|
||||
/// Undo drops the value, though the text it takes away and the text made and selected after it
|
||||
/// have the same id and tracking.
|
||||
#[test]
|
||||
fn an_unfinished_character_value_is_dropped_by_undo() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
let a = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let mut p = Panel::new(app, show);
|
||||
type_unfinished(&mut p, "Tracking");
|
||||
p.app().run("edit.undo", json!({})).unwrap();
|
||||
let b = p.app().run("text.create", json!({"x": 20, "y": 40, "text": "Cd", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_eq!(b, a, "the new text has the undone text's id");
|
||||
p.app().run("select.set", json!({"ids": [b]})).unwrap();
|
||||
finish_typing(&mut p);
|
||||
assert_eq!(run_values(&p.app(), b, |s| s.tracking), [("Cd".to_string(), 1.0)], "Undo drops the unfinished value");
|
||||
}
|
||||
|
||||
/// With Real-time Drawing off, a Type tool range that reaches into typing not applied yet is
|
||||
/// another range than the applied text it starts in.
|
||||
#[test]
|
||||
fn an_unfinished_character_value_does_not_reach_a_range_with_unapplied_typing() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
|
||||
let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.select_tool("type");
|
||||
app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
|
||||
app.session.set_tool_option("select", &json!({"start": 2, "end": 2}));
|
||||
let mut app = crate::testing::windowed(app);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
// The keymap builds in the first pass.
|
||||
crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]);
|
||||
crate::tests::synthetic::key_frame(&mut app, &ctx, vec![egui::Event::Text("Cd".into())]);
|
||||
assert_eq!(app.session.tool_options()["typing"], json!(true));
|
||||
let tracking = |s: &CharStyle| s.tracking;
|
||||
assert_eq!(run_values(&app, id, tracking), [("Ab".to_string(), 0.0)], "the typing is not applied yet");
|
||||
app.session.set_tool_option("select", &json!({"start": 0, "end": 2}));
|
||||
let mut p = Panel::new(app, show);
|
||||
type_unfinished(&mut p, "Tracking");
|
||||
p.app().session.set_tool_option("select", &json!({"start": 0, "end": 4}));
|
||||
finish_typing(&mut p);
|
||||
assert_eq!(run_values(&p.app(), id, tracking), [("AbCd".to_string(), 1.0)], "the longer range takes 1, not 3+1");
|
||||
}
|
||||
|
||||
/// Settling unapplied typing keeps an unfinished Character value for the Select All range.
|
||||
#[test]
|
||||
fn an_unfinished_character_value_survives_select_all_typing_settling() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
|
||||
let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.select_tool("type");
|
||||
app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
|
||||
app.session.set_tool_option("select", &json!({"start": 2, "end": 2}));
|
||||
let mut app = crate::testing::windowed(app);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
// The keymap builds in the first pass.
|
||||
crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]);
|
||||
crate::tests::synthetic::key_frame(&mut app, &ctx, vec![egui::Event::Text("Cd".into())]);
|
||||
assert_eq!(app.session.tool_options()["typing"], json!(true));
|
||||
let tracking = |s: &CharStyle| s.tracking;
|
||||
assert_eq!(run_values(&app, id, tracking), [("Ab".to_string(), 0.0)], "the typing is not applied yet");
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
assert_eq!(app.session.tool_options()["typing"], json!(true));
|
||||
let mut p = Panel::new(app, show);
|
||||
type_unfinished(&mut p, "Tracking");
|
||||
end_typing(&mut p.app());
|
||||
assert_eq!(run_values(&p.app(), id, tracking), [("AbCd".to_string(), 0.0)], "the typing is applied");
|
||||
finish_typing(&mut p);
|
||||
assert_eq!(run_values(&p.app(), id, tracking), [("AbCd".to_string(), 4.0)], "settling the typing keeps 3+");
|
||||
}
|
||||
|
||||
/// The slider list and its gestures are the framework's. What the app decides: which axes the selection
|
||||
/// shares, that a change carries only the axes that moved (so a mixed axis stays as it is), the
|
||||
/// command (the object, or the Type tool's range) and that Reset Panel leaves the settings.
|
||||
|
||||
@@ -33,8 +33,9 @@ struct Chip {
|
||||
fn chips(app: &VectorcraftApp) -> Vec<Chip> {
|
||||
let Some(st) = app.session.active() else { return Vec::new() };
|
||||
let d = &st.doc;
|
||||
let index = super::swatches::index_of(app);
|
||||
let none = Chip { name: tl!("None").to_owned(), color: None, params: json!({"none": true}) };
|
||||
let swatches = d.swatches_iter().filter_map(|s| match super::swatches::shown(d, s).0 {
|
||||
let swatches = d.swatches_iter().filter_map(|s| match super::swatches::shown(d, &index, s).0 {
|
||||
Paint::Solid { color, .. } => Some(Chip { name: s.name.clone(), color: Some(srgba(&color)), params: json!({"swatch": s.name}) }),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! proxy's paint command with the object's id) and onto the Gradient panel's ramp; a Fill/Stroke
|
||||
//! proxy or the Gradient panel's thumbnail dropped on the panel becomes a swatch (`swatch.new`).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::behavior::{EditEvent, IconId, Selection};
|
||||
@@ -36,12 +37,14 @@ use crate::panel_drag::PanelDrag;
|
||||
|
||||
mod actions;
|
||||
mod dnd;
|
||||
mod index;
|
||||
mod libraries;
|
||||
|
||||
#[cfg(test)]
|
||||
use actions::{deletable, delete, mergeable, new_swatch, selected_group};
|
||||
pub(crate) use actions::{menu_rows, menu_states, run};
|
||||
pub(crate) use dnd::{HeldRows, follow_drag};
|
||||
use index::{IndexCache, SwatchIndex};
|
||||
pub(crate) use libraries::{
|
||||
DOCUMENT_SWATCHES, SwatchLibraries, USER_SLOT, colour_libraries, library_entries, limit_key, limit_name, load_library, open_library,
|
||||
other_library, user_library, window_menu,
|
||||
@@ -134,6 +137,8 @@ pub(crate) struct Model {
|
||||
/// The rows of the last drag from the list (as it started) and what its last check found
|
||||
/// ([`dnd::follow`]).
|
||||
drag: Option<(Arc<HeldRows>, HeldRows)>,
|
||||
/// The swatch and color group names of the last document asked for ([`Model::index`]).
|
||||
index: IndexCache,
|
||||
}
|
||||
|
||||
impl Model {
|
||||
@@ -193,6 +198,11 @@ impl Model {
|
||||
active.filter(|_| changed).map(str::to_string)
|
||||
}
|
||||
|
||||
/// The names of `d`'s swatches and color groups, built again only when they change ([`IndexCache::get`]).
|
||||
fn index(&self, d: &Document) -> Arc<SwatchIndex> {
|
||||
self.index.get(d)
|
||||
}
|
||||
|
||||
/// Selected `old` renamed to `new`, or dropped from the selection with `None`; the lead and the anchor follow.
|
||||
fn rename(&mut self, old: &str, new: Option<&str>) {
|
||||
let moved = |k: &SwatchKey| -> Option<SwatchKey> {
|
||||
@@ -261,31 +271,47 @@ fn name_of(key: &SwatchKey) -> &str {
|
||||
/// The swatches and colour groups selected in the panel, in click order, without names that no longer exist
|
||||
/// (deleted, renamed or undone).
|
||||
pub(crate) fn selected(app: &VectorcraftApp) -> Vec<String> {
|
||||
selected_in(app, &app.ui.swatches_panel)
|
||||
if app.ui.swatches_panel.state.selection.items.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
selected_in(app, &app.ui.swatches_panel, &index_of(app))
|
||||
}
|
||||
|
||||
/// The swatches and colour groups selected in `model`, as [`selected`] reads them from the app's panel.
|
||||
fn selected_in(app: &VectorcraftApp, model: &Model) -> Vec<String> {
|
||||
/// The names of the active document ([`Model::index`]); an empty index without a document.
|
||||
pub(crate) fn index_of(app: &VectorcraftApp) -> Arc<SwatchIndex> {
|
||||
app.session.active().map_or_else(Default::default, |st| app.ui.swatches_panel.index(&st.doc))
|
||||
}
|
||||
|
||||
/// The swatches and color groups selected in `model`, as [`selected`] reads them from the app's panel, looked up in
|
||||
/// `index`, the active document's names.
|
||||
fn selected_in(app: &VectorcraftApp, model: &Model, index: &SwatchIndex) -> Vec<String> {
|
||||
let Some(st) = app.session.active() else { return vec![] };
|
||||
let mut names = model.names();
|
||||
names.retain(|n| n == REGISTRATION || st.doc.swatch_name_taken(n));
|
||||
names.retain(|n| n == REGISTRATION || index.name_taken(&st.doc, n));
|
||||
names
|
||||
}
|
||||
|
||||
/// The names the panel highlights: `sel` plus the swatches of selected colour groups (clicking a folder selects the
|
||||
/// whole group).
|
||||
fn highlighted<'a>(d: &'a Document, sel: &'a [String]) -> Vec<&'a str> {
|
||||
let mut out: Vec<&str> = sel.iter().map(String::as_str).collect();
|
||||
for g in d.swatch_groups.iter().filter(|g| sel.contains(&g.name)) {
|
||||
out.extend(g.swatches.iter().map(|w| w.name.as_str()));
|
||||
fn highlighted(d: &Document, index: &SwatchIndex, sel: &[String]) -> BTreeSet<String> {
|
||||
let mut out: BTreeSet<String> = sel.iter().cloned().collect();
|
||||
let mut seen = BTreeSet::new();
|
||||
for name in sel {
|
||||
if !seen.insert(name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
for g in index.groups(d, name) {
|
||||
out.extend(g.swatches.iter().map(|w| w.name.clone()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The `swatch`'s paint as the panel shows it, and whether it is global and spot. A tint swatch shows its base's kind;
|
||||
/// a spot colour shows the colour its art shows (a Lab one's CMYK equivalent when the Spot Colors options use those).
|
||||
pub(crate) fn shown(d: &Document, s: &Swatch) -> (Paint, bool, bool) {
|
||||
let (global, spot) = s.tint_of().and_then(|(base, _)| d.swatch(base)).map_or((s.global, s.spot), |b| (b.global, b.spot));
|
||||
/// `index` holds the names of `d`.
|
||||
pub(crate) fn shown(d: &Document, index: &SwatchIndex, s: &Swatch) -> (Paint, bool, bool) {
|
||||
let (global, spot) = s.tint_of().and_then(|(base, _)| index.swatch(d, base)).map_or((s.global, s.spot), |b| (b.global, b.spot));
|
||||
let paint = match s.paint {
|
||||
Paint::Solid { color, swatch: None, .. } if spot => Paint::solid(d.linked_color(color, true)),
|
||||
_ => s.paint.clone(),
|
||||
@@ -302,8 +328,8 @@ fn swatch_color(c: &Color) -> SwatchColor {
|
||||
}
|
||||
}
|
||||
|
||||
fn entry(d: &Document, s: &Swatch) -> SwatchEntry {
|
||||
let (paint, global, spot) = shown(d, s);
|
||||
fn entry(d: &Document, index: &SwatchIndex, s: &Swatch) -> SwatchEntry {
|
||||
let (paint, global, spot) = shown(d, index, s);
|
||||
let held = match &paint {
|
||||
Paint::Solid { color, .. } => match s.tint_of() {
|
||||
Some((base, tint)) => SwatchPaint::Tint { base: base.to_string(), tint, color: swatch_color(color) },
|
||||
@@ -332,19 +358,19 @@ fn registration_entry() -> SwatchEntry {
|
||||
|
||||
/// The panel's groups for the kind filter and the find field's `query` (a case-insensitive name match; a colour
|
||||
/// group whose name matches shows all its swatches). The first group holds the swatches outside any colour group:
|
||||
/// None first, then Registration, then the rest (the reference app's order).
|
||||
fn groups(app: &VectorcraftApp, kind: Kind, query: &str) -> Vec<SwatchGroup> {
|
||||
/// None first, then Registration, then the rest (the reference app's order). `index` holds the active document's names.
|
||||
fn groups(app: &VectorcraftApp, index: &SwatchIndex, kind: Kind, query: &str) -> Vec<SwatchGroup> {
|
||||
let Some(st) = app.session.active() else { return vec![] };
|
||||
let d = &st.doc;
|
||||
let q = query.trim().to_lowercase();
|
||||
let found = |n: &str| q.is_empty() || n.to_lowercase().contains(&q);
|
||||
let mut top = vec![];
|
||||
let (specials, rest): (Vec<_>, Vec<_>) = d.swatches.iter().partition(|s| s.paint.is_none());
|
||||
top.extend(specials.iter().filter(|s| kind.accepts(&s.paint, false) && found(&s.name)).map(|s| entry(d, s)));
|
||||
top.extend(specials.iter().filter(|s| kind.accepts(&s.paint, false) && found(&s.name)).map(|s| entry(d, index, s)));
|
||||
if matches!(kind, Kind::All | Kind::Color) && found(REGISTRATION) {
|
||||
top.push(registration_entry());
|
||||
}
|
||||
top.extend(rest.iter().filter(|s| kind.accepts(&s.paint, false) && found(&s.name)).map(|s| entry(d, s)));
|
||||
top.extend(rest.iter().filter(|s| kind.accepts(&s.paint, false) && found(&s.name)).map(|s| entry(d, index, s)));
|
||||
// PLAN: assumed the panel shows the first group, named "", without a folder header (the ungrouped swatches).
|
||||
let mut out = vec![SwatchGroup { name: String::new(), entries: top }];
|
||||
for g in &d.swatch_groups {
|
||||
@@ -354,7 +380,7 @@ fn groups(app: &VectorcraftApp, kind: Kind, query: &str) -> Vec<SwatchGroup> {
|
||||
if items.is_empty() && !(all && matches!(kind, Kind::Groups | Kind::All)) {
|
||||
continue;
|
||||
}
|
||||
out.push(SwatchGroup { name: g.name.clone(), entries: items.into_iter().map(|s| entry(d, s)).collect() });
|
||||
out.push(SwatchGroup { name: g.name.clone(), entries: items.into_iter().map(|s| entry(d, index, s)).collect() });
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -438,6 +464,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
};
|
||||
// The model leaves the app while the browser borrows the document, and comes back before the events run.
|
||||
let mut model = std::mem::take(&mut app.ui.swatches_panel);
|
||||
let Some(index) = app.session.active().map(|st| model.index(&st.doc)) else {
|
||||
app.ui.swatches_panel = model;
|
||||
return;
|
||||
};
|
||||
let view = app.ui.swatches_view;
|
||||
if model.view != Some(view) {
|
||||
(model.state.browser.view, model.state.browser.zoom) = view.preset();
|
||||
@@ -447,7 +477,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let active = model.kept(app, active);
|
||||
let focus = model.focus(app, active.as_deref());
|
||||
let query = if model.show_find { model.state.browser.filter.clone() } else { String::new() };
|
||||
let data = groups(app, model.kind, &query);
|
||||
let data = groups(app, &index, model.kind, &query);
|
||||
// Without a selection the swatch of the active paint is highlighted.
|
||||
let picked = model.names();
|
||||
let base = if picked.is_empty() { active.into_iter().collect() } else { picked };
|
||||
@@ -456,15 +486,15 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
return;
|
||||
};
|
||||
let revision = (st.uid, st.revision);
|
||||
let lit: Vec<String> = highlighted(&st.doc, &base).into_iter().map(str::to_string).collect();
|
||||
let lit = highlighted(&st.doc, &index, &base);
|
||||
let doc = Arc::clone(&st.doc);
|
||||
let start = dnd::DragStart::of(st);
|
||||
let start = dnd::DragStart::of(st, Arc::clone(&index));
|
||||
// The row menu, the drop rules and the drag payload read the document, its reverts and the drag start alone, so
|
||||
// the browser's rows replay while this version holds.
|
||||
let host = start.version(st.revision);
|
||||
let document = st.uid;
|
||||
let reverts = st.reverts;
|
||||
let foot = Footer::of(app, &model, held);
|
||||
let foot = Footer::of(app, &model, &index, held);
|
||||
let shown_app: &VectorcraftApp = app;
|
||||
let search = model.show_find;
|
||||
let state = &mut model.state;
|
||||
@@ -478,12 +508,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
.footer(|ui, _| footed = Some(foot.show(ui)))
|
||||
.show(ui, |ui, _| {
|
||||
let start = start.clone();
|
||||
let thumbs = Thumbs { revision, lit: lit.clone(), doc: Arc::clone(&doc) };
|
||||
let thumbs = Thumbs { revision, lit: lit.clone(), doc: Arc::clone(&doc), index: Arc::clone(&index) };
|
||||
let browser = SwatchesPanel::new(&data, Bind::bound(&mut *state), Srgba::rgb(0.0, 0.0, 0.0))
|
||||
.drag_payload(move |drag: &ListDrag<SwatchKey>| Some(dnd::drag_of(&start, &drag.grabbed, dragged_rows(drag))))
|
||||
.thumb(thumbs, thumb)
|
||||
.row_icons(|key| match key {
|
||||
SwatchKey::Swatch(name) => row_icons(shown_app, name),
|
||||
SwatchKey::Swatch(name) => row_icons(shown_app, &index, name),
|
||||
_ => vec![],
|
||||
})
|
||||
.row_items(|key| row_items(shown_app, key))
|
||||
@@ -593,9 +623,12 @@ struct Thumbs {
|
||||
/// The document's uid and revision.
|
||||
revision: (u64, u64),
|
||||
/// The selected swatches, those of selected colour groups, or the active paint's swatch.
|
||||
lit: Vec<String>,
|
||||
lit: BTreeSet<String>,
|
||||
#[memo_props(covered_by = "revision", reason = "a document's uid and revision change with every edit of it")]
|
||||
doc: Arc<Document>,
|
||||
/// The names of `doc`.
|
||||
#[memo_props(covered_by = "revision", reason = "the index is built from the document at this uid and revision")]
|
||||
index: Arc<SwatchIndex>,
|
||||
}
|
||||
|
||||
/// The thumbnail of swatch cell `info` (a colour group is the browser's folder row, not a thumbnail).
|
||||
@@ -606,8 +639,8 @@ fn thumb(t: &Thumbs, cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_,
|
||||
paint_swatch(cx, rect, &Paint::registration(), selected, (false, false), None);
|
||||
return;
|
||||
}
|
||||
let Some(s) = t.doc.swatch(name) else { return };
|
||||
let (paint, global, spot) = shown(&t.doc, s);
|
||||
let Some(s) = t.index.swatch(&t.doc, name) else { return };
|
||||
let (paint, global, spot) = shown(&t.doc, &t.index, s);
|
||||
paint_swatch(cx, rect, &paint, selected, (global, spot), Some(&t.doc));
|
||||
}
|
||||
|
||||
@@ -806,10 +839,11 @@ pub(super) fn kind_icons(paint: &Paint, global: bool, spot: bool) -> Vec<(IconSp
|
||||
}
|
||||
}
|
||||
|
||||
fn row_icons(app: &VectorcraftApp, name: &str) -> Vec<(IconSpec<'static>, String)> {
|
||||
/// The kind icons of swatch row `name`, looked up in `index`, the active document's names.
|
||||
fn row_icons(app: &VectorcraftApp, index: &SwatchIndex, name: &str) -> Vec<(IconSpec<'static>, String)> {
|
||||
let Some(st) = app.session.active() else { return vec![] };
|
||||
let Some(s) = st.doc.swatch(name) else { return vec![] };
|
||||
let (paint, global, spot) = shown(&st.doc, s);
|
||||
let Some(s) = index.swatch(&st.doc, name) else { return vec![] };
|
||||
let (paint, global, spot) = shown(&st.doc, index, s);
|
||||
kind_icons(&paint, global, spot)
|
||||
}
|
||||
|
||||
@@ -856,12 +890,12 @@ struct Footer {
|
||||
|
||||
impl Footer {
|
||||
/// The footer's state for the panel `model`, which is out of the app while the swatch browser borrows it, with
|
||||
/// `held` from the drag check ([`Footer::held`]).
|
||||
fn of(app: &VectorcraftApp, model: &Model, held: bool) -> Self {
|
||||
let sel = selected_in(app, model);
|
||||
let del = actions::deletable(app, &sel);
|
||||
/// `held` from the drag check ([`Footer::held`]); `index` holds the active document's names.
|
||||
fn of(app: &VectorcraftApp, model: &Model, index: &SwatchIndex, held: bool) -> Self {
|
||||
let sel = selected_in(app, model, index);
|
||||
let del = actions::deletable_in(app, index, &sel);
|
||||
let opts = actions::editable(app, &sel);
|
||||
let group = actions::selected_group(app, &sel).filter(|_| opts.is_none());
|
||||
let group = actions::selected_group_in(app, index, &sel).filter(|_| opts.is_none());
|
||||
Footer {
|
||||
kind: model.kind,
|
||||
libraries_open: library_panel::any_open::<SwatchLibraries>(&app.ui),
|
||||
|
||||
@@ -4,17 +4,26 @@ use craft::ui::runtime::commands::{CommandState, CommandStates};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::dnd::group_of;
|
||||
use super::index::SwatchIndex;
|
||||
use super::libraries::SwatchLibraries;
|
||||
use super::library_panel;
|
||||
use super::{View, active_paint, selected};
|
||||
use super::{View, active_paint, index_of, selected};
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
/// The selected swatches and groups that can be deleted: every color group in the document and
|
||||
/// every swatch that `Swatch::is_reserved` does not reserve (None and Registration). Names the
|
||||
/// document does not hold are left out.
|
||||
pub(super) fn deletable(app: &VectorcraftApp, sel: &[String]) -> Vec<String> {
|
||||
if sel.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
deletable_in(app, &index_of(app), sel)
|
||||
}
|
||||
|
||||
/// [`deletable`], looked up in `index`, the active document's names.
|
||||
pub(super) fn deletable_in(app: &VectorcraftApp, index: &SwatchIndex, sel: &[String]) -> Vec<String> {
|
||||
let Some(d) = app.session.active().map(|st| &st.doc) else { return vec![] };
|
||||
sel.iter().filter(|n| d.swatch(n).map_or_else(|| d.swatch_groups.iter().any(|g| g.name == **n), |w| !w.is_reserved())).cloned().collect()
|
||||
sel.iter().filter(|n| index.swatch(d, n).map_or_else(|| index.is_group(d, n), |w| !w.is_reserved())).cloned().collect()
|
||||
}
|
||||
|
||||
/// The selected swatch when exactly one swatch with an editor is selected (not None, Registration
|
||||
@@ -28,14 +37,30 @@ pub(super) fn editable(app: &VectorcraftApp, sel: &[String]) -> Option<String> {
|
||||
|
||||
/// The selected solid-colour swatches in selection order (Merge Swatches keeps the first).
|
||||
pub(super) fn mergeable(app: &VectorcraftApp, sel: &[String]) -> Vec<String> {
|
||||
if sel.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
mergeable_in(app, &index_of(app), sel)
|
||||
}
|
||||
|
||||
/// [`mergeable`], looked up in `index`, the active document's names.
|
||||
fn mergeable_in(app: &VectorcraftApp, index: &SwatchIndex, sel: &[String]) -> Vec<String> {
|
||||
let Some(st) = app.session.active() else { return vec![] };
|
||||
sel.iter().filter(|n| st.doc.swatch(n).is_some_and(|w| w.paint.color().is_some())).cloned().collect()
|
||||
sel.iter().filter(|n| index.swatch(&st.doc, n).is_some_and(|w| w.paint.color().is_some())).cloned().collect()
|
||||
}
|
||||
|
||||
/// The first selected colour group (Ungroup Color Group).
|
||||
pub(super) fn selected_group(app: &VectorcraftApp, sel: &[String]) -> Option<String> {
|
||||
if sel.is_empty() {
|
||||
return None;
|
||||
}
|
||||
selected_group_in(app, &index_of(app), sel)
|
||||
}
|
||||
|
||||
/// [`selected_group`], looked up in `index`, the active document's names.
|
||||
pub(super) fn selected_group_in(app: &VectorcraftApp, index: &SwatchIndex, sel: &[String]) -> Option<String> {
|
||||
let d = &app.session.active()?.doc;
|
||||
sel.iter().find(|n| d.swatch_groups.iter().any(|g| g.name == **n)).cloned()
|
||||
sel.iter().find(|n| index.is_group(d, n)).cloned()
|
||||
}
|
||||
|
||||
/// The selected color group when it is the whole selection (Color Group Options).
|
||||
@@ -175,12 +200,13 @@ pub(crate) fn menu_rows(app: &VectorcraftApp) -> Vec<PanelRow> {
|
||||
/// The enabled and checked state of the menu's rows.
|
||||
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
|
||||
let sel = selected(app);
|
||||
let (del, opts, group) = (deletable(app, &sel), editable(app, &sel), selected_group(app, &sel));
|
||||
let index = if sel.is_empty() { Default::default() } else { index_of(app) };
|
||||
let (del, opts, group) = (deletable_in(app, &index, &sel), editable(app, &sel), selected_group_in(app, &index, &sel));
|
||||
let art_selected = app.session.active().is_some_and(|st| !st.selection.objects.is_empty());
|
||||
let doc = app.session.active().is_some();
|
||||
let enabled = [
|
||||
("duplicate", opts.is_some()),
|
||||
("merge", mergeable(app, &sel).len() > 1),
|
||||
("merge", mergeable_in(app, &index, &sel).len() > 1),
|
||||
("delete", !del.is_empty()),
|
||||
("editGroup", group.is_some()),
|
||||
("ungroup", group.is_some()),
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use std::collections::HashSet;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use super::{Document, Paint, PanelDrag, REGISTRATION, Swatch, Value, VectorcraftApp, json, name_of, swatch_params};
|
||||
use super::{Document, IndexCache, Paint, PanelDrag, REGISTRATION, Swatch, SwatchIndex, Value, VectorcraftApp, json, name_of, swatch_params};
|
||||
use crate::panel_drag::SwatchRows;
|
||||
use craft::color_ui::ui::SwatchKey;
|
||||
use craft::keymap::Mods;
|
||||
@@ -85,22 +86,37 @@ enum HeldRow {
|
||||
}
|
||||
|
||||
impl HeldRow {
|
||||
/// Row `name` of `d`: its swatch, else the colour group of that name.
|
||||
fn of(d: &Document, name: &str) -> Option<Self> {
|
||||
match d.swatch(name) {
|
||||
/// Row `name` of `d`: its swatch, else the color group of that name. With no index, looks directly in `d`.
|
||||
fn of(d: &Document, index: Option<&SwatchIndex>, name: &str) -> Option<Self> {
|
||||
match index.map_or_else(|| d.swatch(name), |index| index.swatch(d, name)) {
|
||||
Some(w) => Some(HeldRow::Swatch(w.clone())),
|
||||
None => d.swatch_groups.iter().find(|g| g.name == name).cloned().map(HeldRow::Group),
|
||||
None => index
|
||||
.map_or_else(|| d.swatch_groups.iter().find(|g| g.name == name), |index| index.groups(d, name).next())
|
||||
.cloned()
|
||||
.map(HeldRow::Group),
|
||||
}
|
||||
}
|
||||
/// Whether `d` holds this row unchanged.
|
||||
fn unchanged_in(&self, d: &Document) -> bool {
|
||||
/// Whether `d` holds this row unchanged. With no index, looks directly in `d`.
|
||||
fn unchanged_in(&self, d: &Document, index: Option<&SwatchIndex>) -> bool {
|
||||
match self {
|
||||
HeldRow::Swatch(w) => d.swatch(&w.name) == Some(w),
|
||||
HeldRow::Group(g) => d.swatch_groups.iter().any(|x| x == g),
|
||||
HeldRow::Swatch(w) => index.map_or_else(|| d.swatch(&w.name), |index| index.swatch(d, &w.name)) == Some(w),
|
||||
HeldRow::Group(g) => index.map_or_else(|| d.swatch_groups.iter().any(|x| x == g), |index| index.groups(d, &g.name).any(|x| x == g)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The index that checks `rows` held rows against `d`: `index` when it holds the names of `d`, else an index of `d`
|
||||
/// from `cache` for more than one row, else none, so that a single row is looked up directly in `d`.
|
||||
fn checking_index(d: &Document, index: &Arc<SwatchIndex>, cache: &IndexCache, rows: usize) -> Option<Arc<SwatchIndex>> {
|
||||
if index.of(d) {
|
||||
Some(Arc::clone(index))
|
||||
} else if rows > 1 {
|
||||
Some(cache.get(d))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest undo step of `st` and the one under it, and the next redo step and the one under it
|
||||
/// ([`HistoryEntry::serial`]), 0 for none.
|
||||
fn steps(st: &DocState) -> [u64; 4] {
|
||||
@@ -111,20 +127,23 @@ fn steps(st: &DocState) -> [u64; 4] {
|
||||
|
||||
/// A document as a drag from the list finds it: its `uid` and its count of File › Revert
|
||||
/// ([`DocState::reverts`]), its state, its newest steps ([`steps`]) and the state undoing the newest
|
||||
/// undo step gives back (that step's document).
|
||||
/// undo step gives back (that step's document), with the names of the document's swatches and color groups.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct DragStart {
|
||||
uid: u64,
|
||||
reverts: u64,
|
||||
doc: Arc<Document>,
|
||||
index: Arc<SwatchIndex>,
|
||||
steps: [u64; 4],
|
||||
back: Option<Arc<Document>>,
|
||||
}
|
||||
|
||||
impl DragStart {
|
||||
pub(super) fn of(st: &DocState) -> Self {
|
||||
/// The start of a drag in `st`; `index` holds the names of `st`'s document, and a new one is built when it does not.
|
||||
pub(super) fn of(st: &DocState, index: Arc<SwatchIndex>) -> Self {
|
||||
let index = if index.of(&st.doc) { index } else { Arc::new(SwatchIndex::new(&st.doc)) };
|
||||
let back = st.history.undo.last().map(|e| Arc::clone(&e.doc));
|
||||
DragStart { uid: st.uid, reverts: st.reverts, doc: Arc::clone(&st.doc), steps: steps(st), back }
|
||||
DragStart { uid: st.uid, reverts: st.reverts, doc: Arc::clone(&st.doc), index, steps: steps(st), back }
|
||||
}
|
||||
|
||||
/// A version of this start in the document's `revision` ([`DocState::revision`]): it changes with
|
||||
@@ -138,8 +157,12 @@ impl DragStart {
|
||||
|
||||
/// Rows `names` as this document holds them.
|
||||
fn rows(&self, names: &[String]) -> HeldRows {
|
||||
let rows: Vec<_> = names.iter().map(|n| (n.clone(), HeldRow::of(&self.doc, n))).collect();
|
||||
let back = rows.iter().map(|(_, r)| r.as_ref().zip(self.back.as_deref()).is_some_and(|(r, d)| r.unchanged_in(d))).collect();
|
||||
let rows: Vec<_> = names.iter().map(|n| (n.clone(), HeldRow::of(&self.doc, Some(&self.index), n))).collect();
|
||||
let count = rows.iter().filter(|(_, row)| row.is_some()).count();
|
||||
let indexes = IndexCache::default();
|
||||
let back = self.back.as_deref().map(|d| (d, checking_index(d, &self.index, &indexes, count)));
|
||||
let back =
|
||||
rows.iter().map(|(_, r)| r.as_ref().zip(back.as_ref()).is_some_and(|(r, (d, index))| r.unchanged_in(d, index.as_deref()))).collect();
|
||||
HeldRows { uid: self.uid, reverts: self.reverts, doc: Arc::downgrade(&self.doc), steps: self.steps, rows, back }
|
||||
}
|
||||
}
|
||||
@@ -192,8 +215,8 @@ impl std::fmt::Debug for HeldRows {
|
||||
/// between are not known, and every row is left out of the drop. The panel checks the rows on every
|
||||
/// pass and after every command the app runs ([`follow_drag`]), so only the steps of one command go
|
||||
/// unseen. One undo step is one change: the states between the commands of a `command.batch` are
|
||||
/// not kept, and a row the batch leaves as it found it stays in the drop.
|
||||
fn checked(held: HeldRows, st: &DocState) -> HeldRows {
|
||||
/// not kept, and a row the batch leaves as it found it stays in the drop. `index` holds the names of `st`'s document.
|
||||
fn checked(held: HeldRows, st: &DocState, index: &Arc<SwatchIndex>) -> HeldRows {
|
||||
let now = steps(st);
|
||||
let same = std::ptr::eq(held.doc.as_ptr(), Arc::as_ptr(&st.doc));
|
||||
if same && held.steps == now {
|
||||
@@ -221,15 +244,31 @@ fn checked(held: HeldRows, st: &DocState) -> HeldRows {
|
||||
Some(i) => (undo.get(i..), false),
|
||||
None => (after(undo, below).and_then(|i| undo.get(i..)), true),
|
||||
};
|
||||
let unchanged = |r: &HeldRow, b: &[HistoryEntry]| b.iter().chain(left).all(|e| r.unchanged_in(&e.doc)) && r.unchanged_in(&st.doc);
|
||||
let rows: Vec<_> = held
|
||||
.rows
|
||||
.into_iter()
|
||||
.zip(held.back)
|
||||
.map(|((name, row), back)| (name, row.filter(|r| (back || !undone) && between.is_some_and(|b| unchanged(r, b)))))
|
||||
.collect();
|
||||
let last = undo.last();
|
||||
let back = rows.iter().map(|(_, r)| r.as_ref().zip(last).is_some_and(|(r, e)| r.unchanged_in(&e.doc))).collect();
|
||||
// Each state is looked at once for every row still held, and states with the same swatch lists share an index.
|
||||
let mut kept: Vec<bool> = held.rows.iter().zip(&held.back).map(|((_, row), back)| row.is_some() && (*back || !undone)).collect();
|
||||
let indexes = IndexCache::default();
|
||||
match between {
|
||||
Some(b) => {
|
||||
for e in b.iter().chain(left) {
|
||||
let count = kept.iter().filter(|&&keep| keep).count();
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
let at = checking_index(&e.doc, index, &indexes, count);
|
||||
for ((_, row), keep) in held.rows.iter().zip(&mut kept) {
|
||||
*keep = *keep && row.as_ref().is_some_and(|r| r.unchanged_in(&e.doc, at.as_deref()));
|
||||
}
|
||||
}
|
||||
for ((_, row), keep) in held.rows.iter().zip(&mut kept) {
|
||||
*keep = *keep && row.as_ref().is_some_and(|r| r.unchanged_in(&st.doc, Some(index)));
|
||||
}
|
||||
}
|
||||
None => kept.fill(false),
|
||||
}
|
||||
let rows: Vec<_> = held.rows.into_iter().zip(kept).map(|((name, row), keep)| (name, row.filter(|_| keep))).collect();
|
||||
let count = rows.iter().filter(|(_, row)| row.is_some()).count();
|
||||
let last = undo.last().filter(|_| count > 0).map(|e| (&*e.doc, checking_index(&e.doc, index, &indexes, count)));
|
||||
let back = rows.iter().map(|(_, r)| r.as_ref().zip(last.as_ref()).is_some_and(|(r, (d, at))| r.unchanged_in(d, at.as_deref()))).collect();
|
||||
HeldRows { uid: held.uid, reverts: held.reverts, doc: Arc::downgrade(&st.doc), steps: now, rows, back }
|
||||
}
|
||||
|
||||
@@ -242,17 +281,18 @@ pub(super) fn follow(app: &mut VectorcraftApp, r: &SwatchRows) -> Vec<String> {
|
||||
if st.uid != r.held.uid || st.reverts != r.held.reverts {
|
||||
return vec![];
|
||||
}
|
||||
let index = app.ui.swatches_panel.index(&st.doc);
|
||||
let kept = &mut app.ui.swatches_panel.drag;
|
||||
let from = match kept {
|
||||
Some((start, now)) if Arc::ptr_eq(start, &r.held) => now.clone(),
|
||||
_ => (*r.held).clone(),
|
||||
};
|
||||
let now = checked(from, st);
|
||||
let now = checked(from, st, &index);
|
||||
let names = if now.rows.len() == r.names.len() {
|
||||
r.names
|
||||
.iter()
|
||||
.zip(&now.rows)
|
||||
.filter(|(n, (h, row))| *n == h && row.as_ref().is_some_and(|row| row.unchanged_in(&st.doc)))
|
||||
.filter(|(n, (h, row))| *n == h && row.as_ref().is_some_and(|row| row.unchanged_in(&st.doc, Some(&index))))
|
||||
.map(|(n, _)| n.clone())
|
||||
.collect()
|
||||
} else {
|
||||
@@ -365,9 +405,10 @@ fn footer_rows(app: &VectorcraftApp, r: &SwatchRows) -> Vec<String> {
|
||||
if !sel.contains(&r.grabbed) {
|
||||
return r.names.clone();
|
||||
}
|
||||
super::shown_keys(&super::groups(app, super::Kind::All, ""))
|
||||
let sel: HashSet<&str> = sel.iter().map(String::as_str).collect();
|
||||
super::shown_keys(&super::groups(app, &super::index_of(app), super::Kind::All, ""))
|
||||
.iter()
|
||||
.filter(|k| matches!(k, SwatchKey::Group(_)) == r.groups && sel.iter().any(|s| s == name_of(k)))
|
||||
.filter(|k| matches!(k, SwatchKey::Group(_)) == r.groups && sel.contains(name_of(k)))
|
||||
.map(|k| name_of(k).to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! The Swatches panel's name lookups: the document's swatches and color groups by name, built for one version of the
|
||||
//! document's swatch lists and kept in the panel's [`Model`](super::Model) from pass to pass.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, PoisonError, Weak};
|
||||
|
||||
use vectorcraft_color::swatch::{REGISTRATION, registration};
|
||||
use vectorcraft_color::{Swatch, SwatchGroup};
|
||||
use vectorcraft_doc::{Document, Shared};
|
||||
|
||||
/// The swatches and color groups of one version of a document's swatch lists, by name. A name that several swatches
|
||||
/// hold finds the swatch [`Document::swatch`] finds: the first in [`Document::swatches_iter`] order.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct SwatchIndex {
|
||||
/// The identity of the document's ungrouped swatch list, without keeping its contents.
|
||||
listed: Weak<Vec<Swatch>>,
|
||||
/// The identity of the document's color group list, without keeping its contents.
|
||||
grouped: Weak<Vec<SwatchGroup>>,
|
||||
/// Each swatch name: the color group that holds it (`None` outside any group) and its position there.
|
||||
swatches: HashMap<String, (Option<usize>, usize)>,
|
||||
/// Each color group name: the positions of the groups of that name, in document order.
|
||||
groups: HashMap<String, Vec<usize>>,
|
||||
}
|
||||
|
||||
impl SwatchIndex {
|
||||
/// The names of `d`'s swatches and color groups.
|
||||
pub(crate) fn new(d: &Document) -> Self {
|
||||
#[cfg(test)]
|
||||
counts::built(d.swatches_iter().count() + d.swatch_groups.len());
|
||||
let mut swatches = HashMap::new();
|
||||
for (i, s) in d.swatches.iter().enumerate() {
|
||||
swatches.entry(s.name.clone()).or_insert((None, i));
|
||||
}
|
||||
let mut groups: HashMap<String, Vec<usize>> = HashMap::new();
|
||||
for (g, group) in d.swatch_groups.iter().enumerate() {
|
||||
groups.entry(group.name.clone()).or_default().push(g);
|
||||
for (i, s) in group.swatches.iter().enumerate() {
|
||||
swatches.entry(s.name.clone()).or_insert((Some(g), i));
|
||||
}
|
||||
}
|
||||
SwatchIndex { listed: Shared::downgrade(&d.swatches), grouped: Shared::downgrade(&d.swatch_groups), swatches, groups }
|
||||
}
|
||||
|
||||
/// Whether the index holds the names of `d`: `d` has the swatch lists the index was built from.
|
||||
pub(super) fn of(&self, d: &Document) -> bool {
|
||||
std::ptr::eq(Weak::as_ptr(&self.listed), &*d.swatches) && std::ptr::eq(Weak::as_ptr(&self.grouped), &*d.swatch_groups)
|
||||
}
|
||||
|
||||
/// Swatch `name` of `d`, a document with the lists the index was built from, as [`Document::swatch`] finds it: the
|
||||
/// built-in Registration swatch when no swatch of the document has its name.
|
||||
pub(crate) fn swatch<'d>(&self, d: &'d Document, name: &str) -> Option<&'d Swatch> {
|
||||
#[cfg(test)]
|
||||
counts::looked_up(1);
|
||||
let found = self.swatches.get(name).and_then(|&(group, i)| match group {
|
||||
None => d.swatches.get(i),
|
||||
Some(g) => d.swatch_groups.get(g)?.swatches.get(i),
|
||||
});
|
||||
found.filter(|s| s.name == name).or_else(|| (name == REGISTRATION).then(registration))
|
||||
}
|
||||
|
||||
/// The color groups of `d` named `name`, in document order.
|
||||
pub(crate) fn groups<'a>(&'a self, d: &'a Document, name: &'a str) -> impl Iterator<Item = &'a SwatchGroup> {
|
||||
#[cfg(test)]
|
||||
counts::looked_up(1);
|
||||
self.groups.get(name).into_iter().flatten().filter_map(|&g| d.swatch_groups.get(g)).filter(move |g| g.name == name)
|
||||
}
|
||||
|
||||
/// Whether `name` is a color group of `d`.
|
||||
pub(crate) fn is_group(&self, d: &Document, name: &str) -> bool {
|
||||
self.groups(d, name).next().is_some()
|
||||
}
|
||||
|
||||
/// Whether a swatch or a color group of `d` uses `name`, as [`Document::swatch_name_taken`] tells.
|
||||
pub(crate) fn name_taken(&self, d: &Document, name: &str) -> bool {
|
||||
self.swatch(d, name).is_some() || self.is_group(d, name)
|
||||
}
|
||||
}
|
||||
|
||||
/// The index of the last document asked for, shared by the panel's passes and by the menu states, which read it
|
||||
/// whether or not the panel is shown.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct IndexCache(Mutex<Option<Arc<SwatchIndex>>>);
|
||||
|
||||
impl IndexCache {
|
||||
/// The names of `d`: the kept index when `d` still has the swatch lists it was built from, otherwise a new one,
|
||||
/// kept for the calls that follow. Edits that leave the swatches and color groups alone keep the index.
|
||||
pub(crate) fn get(&self, d: &Document) -> Arc<SwatchIndex> {
|
||||
let mut kept = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match &*kept {
|
||||
Some(index) if index.of(d) => Arc::clone(index),
|
||||
_ => Arc::clone(kept.insert(Arc::new(SwatchIndex::new(d)))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for IndexCache {
|
||||
fn clone(&self) -> Self {
|
||||
IndexCache(Mutex::new(self.0.lock().unwrap_or_else(PoisonError::into_inner).clone()))
|
||||
}
|
||||
}
|
||||
|
||||
/// How much work this thread's panel lookups did: the names each index build added and each lookup.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod counts {
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
/// Names looked up, and names added by index builds.
|
||||
static LOOKUPS: Cell<usize> = const { Cell::new(0) };
|
||||
/// Index builds.
|
||||
static BUILDS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
pub(super) fn looked_up(n: usize) {
|
||||
LOOKUPS.with(|c| c.set(c.get() + n));
|
||||
}
|
||||
|
||||
pub(super) fn built(names: usize) {
|
||||
BUILDS.with(|c| c.set(c.get() + 1));
|
||||
looked_up(names);
|
||||
}
|
||||
|
||||
/// The lookups and the index builds since the last call, which starts the counts again.
|
||||
pub(crate) fn take() -> (usize, usize) {
|
||||
(LOOKUPS.with(|c| c.replace(0)), BUILDS.with(|c| c.replace(0)))
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use vectorcraft_color::Color;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
mod context_menu;
|
||||
mod lookups;
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
@@ -55,7 +56,7 @@ fn key_of(app: &VectorcraftApp, name: &str) -> SwatchKey {
|
||||
|
||||
/// The rows in panel order, as the browser shows every swatch.
|
||||
fn shown_rows(app: &VectorcraftApp) -> Vec<SwatchKey> {
|
||||
shown_keys(&groups(app, Kind::All, ""))
|
||||
shown_keys(&groups(app, &index_of(app), Kind::All, ""))
|
||||
}
|
||||
|
||||
/// Feeds the browser event `event` to the panel's handler.
|
||||
@@ -96,7 +97,7 @@ fn dropped_below(app: &mut VectorcraftApp, drag: PanelDrag, mods: Mods) {
|
||||
|
||||
/// The drag the row `name` starts in the active document, carrying rows `names`.
|
||||
fn rows_drag(app: &VectorcraftApp, name: &str, names: &[&str]) -> PanelDrag {
|
||||
let start = dnd::DragStart::of(app.session.active().expect("a document"));
|
||||
let start = dnd::DragStart::of(app.session.active().expect("a document"), index_of(app));
|
||||
dnd::drag_of(&start, &key_of(app, name), names.iter().map(|n| n.to_string()).collect())
|
||||
}
|
||||
|
||||
@@ -1388,7 +1389,7 @@ fn the_active_tint_or_gradient_swatch_is_highlighted_and_a_tint_edits_its_base()
|
||||
assert_eq!(active_swatch(&app).as_deref(), Some("Ink"), "no tint swatch yet: its base");
|
||||
app.run("swatch.new", json!({})).unwrap();
|
||||
assert_eq!(active_swatch(&app).as_deref(), Some("Ink 40%"));
|
||||
let tint = groups(&app, Kind::Color, "Ink 40").into_iter().flat_map(|g| g.entries).find(|e| e.name == "Ink 40%").unwrap();
|
||||
let tint = groups(&app, &index_of(&app), Kind::Color, "Ink 40").into_iter().flat_map(|g| g.entries).find(|e| e.name == "Ink 40%").unwrap();
|
||||
assert_eq!(tint.kind, SwatchKind::Spot, "a tint swatch shows its base's kind");
|
||||
app.run("paint.setFill", json!({"swatch": "Sunset"})).unwrap();
|
||||
assert_eq!(active_swatch(&app).as_deref(), Some("Sunset"), "the applied gradient swatch");
|
||||
@@ -1517,7 +1518,7 @@ fn lab_spot_tiles_show_the_colour_the_spot_colors_options_pick() {
|
||||
app.run("swatch.new", json!({"name": "Ink", "color": lab, "spot": true})).unwrap();
|
||||
let tile = |app: &VectorcraftApp| {
|
||||
let d = doc(app);
|
||||
shown(&d, d.swatch("Ink").expect("the Ink swatch")).0.color().unwrap()
|
||||
shown(&d, &index_of(app), d.swatch("Ink").expect("the Ink swatch")).0.color().unwrap()
|
||||
};
|
||||
assert_eq!(tile(&app), lab);
|
||||
app.run("swatch.spotOptions", json!({"useLab": false})).unwrap();
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
//! The panel's name lookups: what one pass over the panel costs as the swatch list grows, when the name index is built
|
||||
//! again, and that the index finds what the document finds.
|
||||
|
||||
use super::*;
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use egui::Event;
|
||||
use vectorcraft_color::SwatchGroup;
|
||||
|
||||
/// An app whose document holds `n` swatches besides the defaults: `n / 2` global colors, and a tint of each in color
|
||||
/// groups of ten. Every swatch and color group is selected in the panel.
|
||||
fn crowded(n: usize) -> VectorcraftApp {
|
||||
let mut app = app();
|
||||
{
|
||||
let st = app.session.doc_mut().unwrap();
|
||||
let d = Arc::make_mut(&mut st.doc);
|
||||
let bases: Vec<String> = (0..n / 2).map(|i| format!("Ink {i}")).collect();
|
||||
for (i, name) in bases.iter().enumerate() {
|
||||
let color = Color::cmyk(i as f32 / n as f32, 0.5, 0.2, 0.0);
|
||||
d.swatches.push(Swatch { name: name.clone(), paint: Paint::solid(color), global: true, spot: false });
|
||||
}
|
||||
for (g, chunk) in bases.chunks(10).enumerate() {
|
||||
let swatches = chunk
|
||||
.iter()
|
||||
.map(|base| {
|
||||
let paint = Paint::Solid { color: Color::cmyk(0.1, 0.25, 0.1, 0.0), swatch: Some(base.clone()), tint: 0.5 };
|
||||
Swatch { name: format!("{base} 50%"), paint, global: false, spot: false }
|
||||
})
|
||||
.collect();
|
||||
d.swatch_groups.push(SwatchGroup { name: format!("Tints {g}"), swatches });
|
||||
}
|
||||
}
|
||||
let d = doc(&app);
|
||||
let mut keys: Vec<SwatchKey> = d.swatches_iter().map(|s| SwatchKey::Swatch(s.name.clone())).collect();
|
||||
keys.extend(d.swatch_groups.iter().map(|g| SwatchKey::Group(g.name.clone())));
|
||||
app.ui.swatches_panel.state.selection = Selection::new(keys.clone(), keys.last().cloned(), keys.first().cloned());
|
||||
app
|
||||
}
|
||||
|
||||
/// One pass of the panel with the pointer moving over it, as while it is hovered.
|
||||
fn hovered(panel: &mut Panel) {
|
||||
panel.frame_with(vec![Event::PointerMoved(Pos2::new(140.0, 300.0))]);
|
||||
}
|
||||
|
||||
/// The app's name lookup work in one hovered pass over [`crowded`]`(n)`, after the panel's first passes: the panel's
|
||||
/// index lookups and the document's own swatch and color group name comparisons. The browser's work is not counted.
|
||||
fn lookups_in_a_pass(n: usize) -> usize {
|
||||
let mut panel = Panel::new(crowded(n), show);
|
||||
let d = doc(&panel.app());
|
||||
assert_eq!(selected(&panel.app()).len(), d.swatches_iter().count() + d.swatch_groups.len(), "every swatch and group is selected");
|
||||
index::counts::take();
|
||||
let scans = vectorcraft_doc::swatches::swatch_scans();
|
||||
hovered(&mut panel);
|
||||
index::counts::take().0 + vectorcraft_doc::swatches::swatch_scans() - scans
|
||||
}
|
||||
|
||||
/// With every swatch selected, the app's name lookup work in one hovered pass scales with the swatch count: twice
|
||||
/// the swatches, at most twice the panel index lookups and document name comparisons. The browser's work is not counted.
|
||||
#[test]
|
||||
fn a_hovered_pass_looks_up_names_in_proportion_to_the_swatch_count() {
|
||||
let small = lookups_in_a_pass(200);
|
||||
let large = lookups_in_a_pass(400);
|
||||
assert!(small > 0, "the app looks names up during the pass");
|
||||
assert!(large <= 2 * small, "app name lookup work in one pass: {small} with 200 swatches, {large} with 400");
|
||||
}
|
||||
|
||||
/// The app's name lookup work in one check of a drag of every swatch of [`crowded`]`(n)` from the list, after an edit
|
||||
/// of the art: the drag's rows are checked against the new undo step's state and the current one.
|
||||
fn lookups_in_a_drag_check(n: usize) -> usize {
|
||||
let mut app = crowded(n);
|
||||
let names: Vec<String> = doc(&app).swatches_iter().map(|s| s.name.clone()).collect();
|
||||
let rows: Vec<&str> = names.iter().map(String::as_str).collect();
|
||||
index_of(&app);
|
||||
index::counts::take();
|
||||
let drag = rows_drag(&app, rows[0], &rows);
|
||||
assert_eq!(index::counts::take().1, 0, "starting a drag builds no index when the panel's index exists");
|
||||
let PanelDrag::Paint { rows: Some(held), .. } = &drag else { panic!("a rows drag") };
|
||||
assert_eq!(dnd::follow(&mut app, held), names, "the drag holds every swatch");
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
|
||||
index::counts::take();
|
||||
let scans = vectorcraft_doc::swatches::swatch_scans();
|
||||
let kept = dnd::follow(&mut app, held);
|
||||
let (lookups, builds) = index::counts::take();
|
||||
let work = lookups + vectorcraft_doc::swatches::swatch_scans() - scans;
|
||||
assert_eq!(builds, 0, "an edit of the art alone builds no index during the drag check");
|
||||
assert_eq!(kept, names, "an edit of the art keeps every row");
|
||||
work
|
||||
}
|
||||
|
||||
/// Checking a drag of every swatch from the list, as the panel does on every pass and after every command, does name
|
||||
/// lookup work in proportion to the swatch count: twice the swatches, at most twice the work.
|
||||
#[test]
|
||||
fn a_drag_check_looks_up_names_in_proportion_to_the_swatch_count() {
|
||||
let small = lookups_in_a_drag_check(200);
|
||||
let large = lookups_in_a_drag_check(400);
|
||||
assert!(small > 0, "the check looks names up");
|
||||
assert!(large <= 2 * small, "name lookup work in one drag check: {small} with 200 swatches, {large} with 400");
|
||||
}
|
||||
|
||||
/// Starting a one-row drag after a swatch edit uses the panel's index and checks the undo state without building an index.
|
||||
#[test]
|
||||
fn a_one_row_drag_after_a_swatch_edit_builds_no_name_index() {
|
||||
let mut app = crowded(200);
|
||||
app.run("swatch.new", json!({"name": "Fresh", "color": "#336699"})).unwrap();
|
||||
index_of(&app);
|
||||
index::counts::take();
|
||||
let drag = rows_drag(&app, "Ink 0", &["Ink 0"]);
|
||||
assert_eq!(index::counts::take().1, 0, "starting a one-row drag builds no index after a swatch edit");
|
||||
let PanelDrag::Paint { rows: Some(held), .. } = &drag else { panic!("a rows drag") };
|
||||
assert_eq!(dnd::follow(&mut app, held), ["Ink 0"], "the drag holds its row");
|
||||
}
|
||||
|
||||
/// Highlighting a selection looks each selected name up once in the index, however many color groups the document
|
||||
/// holds, and lights every selected name.
|
||||
#[test]
|
||||
fn highlighting_looks_each_selected_name_up_once() {
|
||||
for n in [200, 400] {
|
||||
let app = crowded(n);
|
||||
let sel = selected(&app);
|
||||
let st = app.session.active().unwrap();
|
||||
let index = index_of(&app);
|
||||
index::counts::take();
|
||||
let lit = highlighted(&st.doc, &index, &sel);
|
||||
assert_eq!(index::counts::take().0, sel.len(), "index lookups to highlight {} selected names", sel.len());
|
||||
assert_eq!(lit.len(), sel.len(), "every selected name is lit");
|
||||
}
|
||||
}
|
||||
|
||||
/// Passes at one revision of the document build no index; after a swatch edit the panel builds one that finds the new
|
||||
/// swatch, the passes that follow build none, and an edit of the art alone builds none.
|
||||
#[test]
|
||||
fn passes_at_one_document_revision_build_no_name_index() {
|
||||
let mut panel = Panel::new(crowded(40), show);
|
||||
index::counts::take();
|
||||
hovered(&mut panel);
|
||||
hovered(&mut panel);
|
||||
assert_eq!(index::counts::take().1, 0, "no index build at the same revision");
|
||||
panel.app().run("swatch.new", json!({"name": "Fresh", "color": "#336699"})).unwrap();
|
||||
select_rows(&mut panel.app(), &["Fresh"]);
|
||||
hovered(&mut panel);
|
||||
assert_eq!(index::counts::take().1, 1, "the edit builds one index");
|
||||
hovered(&mut panel);
|
||||
hovered(&mut panel);
|
||||
assert_eq!(index::counts::take().1, 0, "no index build at the new revision once a pass built it");
|
||||
assert_eq!(selected(&panel.app()), ["Fresh"]);
|
||||
panel.app().run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
|
||||
hovered(&mut panel);
|
||||
assert_eq!(index::counts::take().1, 0, "an edit of the art alone builds no index");
|
||||
}
|
||||
|
||||
/// The menu states, which are worked out while the panel is closed too, build one index per version of the swatch
|
||||
/// lists, and none without a selection.
|
||||
#[test]
|
||||
fn menu_states_of_a_closed_panel_build_one_name_index_per_revision() {
|
||||
let mut app = crowded(40);
|
||||
let mut states = craft::ui::runtime::commands::CommandStates::new();
|
||||
index::counts::take();
|
||||
menu_states(&app, &mut states);
|
||||
menu_states(&app, &mut states);
|
||||
assert_eq!(index::counts::take().1, 1, "one index build at one revision");
|
||||
app.run("swatch.new", json!({"name": "Fresh", "color": "#336699"})).unwrap();
|
||||
menu_states(&app, &mut states);
|
||||
menu_states(&app, &mut states);
|
||||
assert_eq!(index::counts::take().1, 1, "one index build at the new revision");
|
||||
let mut idle = crowded(40);
|
||||
idle.ui.swatches_panel.state.selection = Selection::new(vec![], None, None);
|
||||
index::counts::take();
|
||||
menu_states(&idle, &mut states);
|
||||
assert_eq!(index::counts::take().1, 0, "no index build without a selection");
|
||||
}
|
||||
|
||||
/// Every name of `app`'s document, a few it does not hold and Registration, as the index and the document find them.
|
||||
fn check_index(app: &VectorcraftApp) {
|
||||
let st = app.session.active().unwrap();
|
||||
let d = &st.doc;
|
||||
let index = SwatchIndex::new(d);
|
||||
let names = d.swatches_iter().map(|s| s.name.as_str()).chain(d.swatch_groups.iter().map(|g| g.name.as_str()));
|
||||
for name in names.chain(["Missing", REGISTRATION, "", "twin"]) {
|
||||
let at = |s: Option<&Swatch>| s.map(|s| s as *const Swatch);
|
||||
assert_eq!(at(index.swatch(d, name)), at(d.swatch(name)), "the swatch named {name:?}");
|
||||
assert_eq!(index.name_taken(d, name), d.swatch_name_taken(name), "whether {name:?} is taken");
|
||||
let groups = |found: Vec<&SwatchGroup>| found.into_iter().map(|g| g as *const SwatchGroup).collect::<Vec<_>>();
|
||||
let want = groups(d.swatch_groups.iter().filter(|g| g.name == name).collect());
|
||||
assert_eq!(groups(index.groups(d, name).collect()), want, "the color groups named {name:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A swatch `name` of color `hex`.
|
||||
fn named(name: &str, hex: &str) -> Swatch {
|
||||
Swatch { name: name.into(), paint: Paint::solid(Color::from_hex(hex).unwrap()), global: true, spot: false }
|
||||
}
|
||||
|
||||
/// A name that two swatches hold finds the first, as the document finds it, and groups of one name are all found; a
|
||||
/// rename of the first leaves the name to the second.
|
||||
#[test]
|
||||
fn repeated_names_find_what_the_document_finds() {
|
||||
let mut app = app();
|
||||
{
|
||||
let d = Arc::make_mut(&mut app.session.doc_mut().unwrap().doc);
|
||||
d.swatches.push(named("Twin", "#aa0000"));
|
||||
d.swatch_groups.push(SwatchGroup { name: "Pair".into(), swatches: vec![named("Twin", "#0000aa"), named("Solo", "#00aa00")] });
|
||||
d.swatch_groups.push(SwatchGroup { name: "Pair".into(), swatches: vec![] });
|
||||
}
|
||||
check_index(&app);
|
||||
app.run("swatch.edit", json!({"name": "Twin", "newName": "Once"})).unwrap();
|
||||
check_index(&app);
|
||||
let index = index_of(&app);
|
||||
let d = &app.session.active().unwrap().doc;
|
||||
assert_eq!(index.swatch(d, "Twin").and_then(|s| s.paint.color()), Color::from_hex("#0000aa"), "the grouped Twin is left");
|
||||
}
|
||||
|
||||
/// The panel lights the swatches of a selected group and deletes what it deleted before; after a rename at a new
|
||||
/// revision, the selection drops the old name and the index finds the new one.
|
||||
#[test]
|
||||
fn renamed_names_leave_the_selection_and_the_index() {
|
||||
let mut app = app();
|
||||
{
|
||||
let d = Arc::make_mut(&mut app.session.doc_mut().unwrap().doc);
|
||||
d.swatch_groups.push(SwatchGroup { name: "Pair".into(), swatches: vec![named("Deep Sea", "#0000aa"), named("Solo", "#00aa00")] });
|
||||
}
|
||||
select_rows(&mut app, &["Pair", "Solo"]);
|
||||
let mut panel = Panel::new(app, show);
|
||||
assert_eq!(selected(&panel.app()), ["Pair", "Solo"]);
|
||||
let (lit, kinds) = {
|
||||
let app = panel.app();
|
||||
let st = app.session.active().unwrap();
|
||||
let index = index_of(&app);
|
||||
(highlighted(&st.doc, &index, &["Pair".into()]), deletable(&app, &["Pair".into(), "Deep Sea".into(), "[None]".into()]))
|
||||
};
|
||||
assert_eq!(lit, BTreeSet::from(["Pair".into(), "Deep Sea".into(), "Solo".into()]), "a selected group lights its swatches");
|
||||
assert_eq!(kinds, ["Pair", "Deep Sea"]);
|
||||
panel.app().run("swatch.edit", json!({"name": "Solo", "newName": "Renamed"})).unwrap();
|
||||
hovered(&mut panel);
|
||||
assert_eq!(selected(&panel.app()), ["Pair"], "the old name leaves the selection");
|
||||
check_index(&panel.app());
|
||||
let app = panel.app();
|
||||
let index = index_of(&app);
|
||||
let d = &app.session.active().unwrap().doc;
|
||||
assert!(index.swatch(d, "Solo").is_none() && index.swatch(d, "Renamed").is_some(), "the index follows the rename");
|
||||
}
|
||||
@@ -80,3 +80,26 @@ fn a_previewing_command_dialog_keeps_the_canvas_open() {
|
||||
crate::dialogs::command::open(&mut app, crate::addons::pathtools::BOUNDING_RECTANGLE, "Bounding Rectangle", Map::new()).unwrap();
|
||||
assert!(wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas scrolls the view under the command's dialog");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_effect_gallery_keeps_the_canvas_open() {
|
||||
let (mut app, ctx) = app();
|
||||
app.run("ui.effectGalleryDialog", json!({})).unwrap();
|
||||
assert!(wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas scrolls the view under the Effect Gallery");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bullets_and_numbering_keeps_the_canvas_open() {
|
||||
let (mut app, ctx) = app();
|
||||
app.run("text.create", json!({"x": 100, "y": 150, "text": "One"})).unwrap();
|
||||
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
|
||||
assert!(wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas scrolls the view under Bullets and Numbering");
|
||||
}
|
||||
|
||||
/// New Character Style does not preview, so the canvas stays covered.
|
||||
#[test]
|
||||
fn new_character_style_leaves_the_canvas_covered() {
|
||||
let (mut app, ctx) = app();
|
||||
app.run("ui.newCharStyle", json!({})).unwrap();
|
||||
assert!(!wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas does not reach the view");
|
||||
}
|
||||
|
||||
@@ -371,7 +371,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's
|
||||
| PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` |
|
||||
| DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` |
|
||||
| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`); SVG Options › Units writes `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, the `viewBox` staying in points, for software that reads physical size such as LaserGRBL (#4462, `crates/svg/tests/it/roundtrip.rs`) |
|
||||
| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open. REGION entities open as filled paths of their faces' boundary loops (lines, circles, ellipses and spline edges), read from the text data of DXF R13 to 2010 and the binary data in the ACDSDATA section of DXF 2013 and later, DWG included; edges of other curve types come in straight, an outline that breaks off is closed with a straight line, and a spline edge whose endpoint lies on two parts of a self-crossing curve is trimmed at the nearer one, each with a warning ([REGION group codes](https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-644BF0F0-FD79-4C5E-AD5A-0053FCC5A5A4), `crates/cad/src/import/tests_region.rs`) |
|
||||
| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open. REGION entities open as filled paths of their faces' boundary loops (lines, circles, ellipses and spline edges), read from the text data of DXF R13 to 2010 and the binary data in the ACDSDATA section of DXF 2013 and later, DWG included; edges of other curve types come in straight, an outline that breaks off is closed with a straight line, and a spline edge whose endpoint lies on two parts of a self-crossing curve is trimmed at the nearer one, each with a warning ([REGION group codes](https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-644BF0F0-FD79-4C5E-AD5A-0053FCC5A5A4), `crates/cad/src/import/tests_region.rs`). DXF and DWG import draw a pattern hatch as its pattern lines (groups 53, 43–46 and 49) clipped to its boundary and cut into their dashes and dots, and fill a gradient hatch (groups 450–470) with a linear or radial gradient in its colors at its angle; hatches follow their island style (normal, outer, ignore); the mapping of each named gradient to a linear or radial one is VectorCraft's own (`pattern_hatches_draw_their_lines_inside_the_boundary`, `gradient_hatches_keep_their_gradient`; [HATCH group codes](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-C6C71CED-CE0F-4184-82A5-07AD6241F15B.htm)) |
|
||||
| HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines; Export As opens HP-GL Options) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` |
|
||||
| DWG | open, export | yes (open and place: craft-dwg converts the drawing to DXF, in a child process on desktop, and the DXF reader reads it with the DXF import options) | no (export DXF instead) | `crates/cad/src/import/tests_dwg.rs`, `crates/engine/src/cmd/fileio/tests_dwgimport.rs` (drawings written as DXF and converted to DWG by craft-dwg's writer); not in the web build |
|
||||
| EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` |
|
||||
|
||||
+138
-28
File diff suppressed because one or more lines are too long
@@ -1120,7 +1120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Variables: a type object holds one text variable. `variable.bind` and Make Text Dynamic refuse a second one and name the text variable the object has; a visibility variable can still share the object, and a document saved with two text variables on one object opens with both.
|
||||
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
|
||||
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document; showing or hiding a perspective grid and choosing its active plane change only the view and add no undo step. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: `Document.exportForScreens` writes the artboards, assets or whole document of an `ExportForScreensItemToExport` into a folder as JPEG, PNG-24, PNG-8, SVG or PDF with a file name prefix, with the option classes and enumerations the reference pages https://www.indesignjs.de/indesignapi/illustrator/Document.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html and https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html describe, and writes only where the script's `File` objects may (`docs/mcp.md`). With PNG8 transparency enabled, `matte: false` preserves transparency without a white background. Raster width and height requests outside an effective scale of 0.01 to 64 pixels per point are rejected before the underlying export command writes output; files written by earlier exports in the same script call remain. SVG embeds raster images and rejects `RasterImageLocation.LINK`. `crates/engine/src/tests/script_screens.rs`.
|
||||
- Scripts: `Document.rasterize` replaces page items with an embedded image and `Document.imageCapture` writes a PNG of the art or of an area of the page, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/ describe; `object.rasterize` takes `ids` and `clipBounds` for them (`docs/mcp.md`). `Document.windowCapture` is not there yet. `crates/engine/src/tests/script_raster_capture.rs`.
|
||||
- Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips, and the same holds for a visible image or placed document whose frame encloses an area, unless deleting the paths makes a live geometry effect leave no clipping region where there was one before; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.rs`.
|
||||
@@ -1128,26 +1128,27 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`.
|
||||
- Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`.
|
||||
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips, and the same holds for a visible image or placed document whose frame encloses an area, unless deleting the paths makes a live geometry effect leave no clipping region where there was one before; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Loading the built-in preset the tracing already has, by its name with or without brackets (`[Default]`), with unchanged options does not trace again. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. Tracing again and `releaseTracing()` throw, with nothing changed, when the tracing holds added artwork, an opacity mask on the tracing or on an object the trace made included; the source image keeps its own mask. A tracing saved without `made` is checked only for artwork added during the same run, so tracing it again or releasing it discards artwork that was added before the run without an error, and the opacity mask check applies with or without `made`. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. `remove()` also refuses a shown source image. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error, and so does a `groupItems.removeAll()` or `compoundPathItems.removeAll()` that would leave an image at the bottom of such a group. `crates/engine/src/tests/script_dom_tracing.rs`.
|
||||
- Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Tracing again keeps the tracing's note, tags and URL. Loading the built-in preset the tracing already has, by its name with or without brackets (`[Default]`), with unchanged options does not trace again. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. Tracing again and `releaseTracing()` throw, with nothing changed, when the tracing holds added artwork, an opacity mask on the tracing or on an object the trace made included; the source image keeps its own mask. A tracing saved without `made` is checked only for artwork added during the same run, so tracing it again or releasing it discards artwork that was added before the run without an error, and the opacity mask check applies with or without `made`. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. `remove()` also refuses a shown source image. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error, and so does a `groupItems.removeAll()`, `compoundPathItems.removeAll()`, `pathItems.removeAll()` or `textFrames.removeAll()` that would leave an image at the bottom of such a group. `crates/engine/src/tests/script_dom_tracing.rs`.
|
||||
- Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`.
|
||||
- Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font, fill and stroke colors, stroke weight) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
|
||||
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
|
||||
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
|
||||
- Scripts: a document's perspective grid is shown, hidden, given its active plane and reset to a built-in or saved preset of the type the script names; `app.getPresetSettings` gives the settings of a startup preset as a `DocumentPreset`; and `app.startupPresetsList` lists the startup presets' names, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and https://ai-scripting.docsforadobe.dev/jsobjref/Application/ list them (`docs/mcp.md`). Showing, hiding and the active plane add no undo step in a script run, as outside one. Workspaces, `loadColorSettings`, `showPresets` and perspective grid preset files are not there yet. `crates/engine/src/tests/script_dom_perspective.rs`.
|
||||
- Scripts: each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; scripts add, rename, recolor, group, duplicate, apply and remove them through the Swatches, Symbols, Graphic Styles and Brushes commands, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/, https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/, https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/Brush/ describe them (`docs/mcp.md`). A path's fill or stroke takes a `SpotColor` of a spot at a tint (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/). Gradients and patterns are not there yet. `crates/engine/src/tests/script_dom_resources.rs`, `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; a compound path's `pathItems` are `PathItems` objects whose `add()` and shape methods make the new path inside it; `removeAll()` on a compound path's `pathItems` throws when it would empty a compound path that clips a group or layer keeping other objects that are not ruler guides. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. In a Shaper group, new empty groups and compound paths and turning clipping on are refused, since the group keeps its source art at the bottom. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`.
|
||||
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws unless the base settings hold a profile. `crates/engine/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`); a batch submitted after a spool failure was reported clears it once the worker sends every job of the batch without a failure, while a failure reported after submission stays. `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
|
||||
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
|
||||
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, converted through the profiles assigned to that document, while Cancel, and OK with both the color and its model unchanged, return a new object based on the color given, in its own model. Stopping the run closes the picker and ends a screen color sample the picker started. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`.
|
||||
- Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`.
|
||||
- Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; once a script calls `setActiveArtboardIndex` on a document, untargeted paste and Fit to Artwork Bounds use that artboard instead of the Artboard tool's selection at the start of the run; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`.
|
||||
- Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After the script adds, inserts or removes an artboard, the artboard active before the change stays active, also when the script never chose one, and playback acts on it at the index `getActiveArtboardIndex()` gives. After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; once a script calls `setActiveArtboardIndex` on a document or adds, inserts or removes one of its artboards, untargeted paste and Fit to Artwork Bounds use the active artboard instead of the Artboard tool's selection at the start of the run; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`.
|
||||
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. A line's menu copies that line or the selected range. `crates/engine/src/tests/script_console.rs`.
|
||||
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
|
||||
- Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`.
|
||||
@@ -2576,7 +2577,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge.
|
||||
- DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`).
|
||||
- DXF Options' Always Export Group as Block Reference (`groupBlocks`, off by default and not set by a preset) writes each group with output as a block of its contents, placed by an INSERT on its layer, with groups inside it as blocks placed inside that block, in every version from R12 to 2018; a group whose contents write no entity (an empty group, or one whose objects are all hidden or left out) writes no block or INSERT; the drawing reads back with the same art bounds (`groups_are_blocks_placed_by_inserts_in_every_version`, `blocks_read_back_at_the_place_their_group_was`, `group_blocks_write_a_group_as_an_insert`). Behavior reference: [Export artwork, AutoCAD export options](https://helpx.adobe.com/illustrator/using/exporting-artwork.html).
|
||||
- DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build and R1.x and R2.x drawings return an error that says to save the drawing as DXF. DWG is not written: Export As keeps it greyed out, exporting to it says to export DXF, and Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged).
|
||||
- DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build returns an error that says to save the drawing as DXF. A drawing of a DWG version the converter does not read (R1.0 to R9, an R10 drawing marked `AD1006`, a code the reader does not list such as `AC1010`, or a code newer than 2018's `AC1032`) returns an error that names its version and says to save it as DXF or as a DWG from R10 to 2018 (`a_dwg_version_the_reader_skips_is_named_with_what_to_save_it_as`). DWG is not written: Export As keeps it greyed out, exporting to it says to export DXF, and Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged).
|
||||
- `.dws` drawing standards files and `.dwt` drawing templates, which are DWG files, open and place as DWG drawings, are listed in the open and place dialogs, and go through the DXF Import Options; a `.dwt` opens as a new untitled document (`a_dwt_template_opens_untitled_and_a_dws_opens_as_its_drawing`, `a_dwt_or_dws_drawing_places_as_a_dwg_does`, `dwt_and_dws_are_read_only_and_exporting_them_says_to_write_dxf`; scores and estimates unchanged).
|
||||
- Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md).
|
||||
- `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `craft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`). Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`).
|
||||
@@ -3353,6 +3354,12 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov
|
||||
|
||||
A VectorCraft addition (it replaces a script some users ran), so no area score moves. Object › Plug-ins › Color Effects › Create Swatch Legend… (`addon.color.swatchLegend`) opens a dialog (columns, chip size, gap, values, selected swatches only, with a preview) and draws a chip per colour swatch (the selected ones, else all) filled with and linked to its swatch, labelled with its name and values (HEX, RGB, CMYK, Lab or Grayscale; by default its own model; spot swatches marked), black on light chips and white on dark ones, in a grid of chosen columns, chip size and spacing, as one selected group in one undo step (#4919). Tests: `cmd::addons::color::legend::tests` (engine), `addons::color::legend::tests::create_swatch_legend_opens_its_dialog_previews_and_runs_on_ok` (ui-egui).
|
||||
|
||||
## Create Screen Print Marks (2026-11-29)
|
||||
|
||||
A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Create Screen Print Marks… (`addon.color.screenMarks`) opens a dialog (the eight target positions, size, stroke weight, inset, ink, the spot ink and file lines with their type size, place and alignment, all artboards, with a preview) and draws registration targets (a circle half the target's width with a cross through it) inside the artboard in [Registration] or a spot ink, with an optional line naming the document's spot inks, each in its own ink, and an optional line with the file name and the date and time in UTC. The marks are document art: one group per artboard on a locked "Screen Print Marks" layer made at the bottom of the stack, so they print, separate and export with the rest of the art, where Create Trim Marks draws trim marks only and the PDF export's printer's marks exist only in the exported file. The lines move in past a top or bottom target they would cross. They stay where they are when moving would cross another target or leave the artboard. Marks copied with a duplicated artboard belong to the copy, and another artboard's marks lying on a copied artboard stay with their own artboard. Moving an artboard with its art, by Move Artboard or a new position, takes its own marks, and deleting it makes its marks ordinary art. A paste that makes the deleted marks layer again makes it the marks layer. Running it again replaces that artboard's marks; one undo step, none when the marks come out the same. Remaining: saved presets of the dialog's settings. Tests: `cmd::addons::color::screen_marks::tests` (engine), `addons::color::screen_marks::tests` (ui-egui).
|
||||
|
||||
With art enabled, artboard moves and cuts take eligible screen print marks by their recorded owner, including marks outside every artboard. Tests: `overlapping_artboard_copies_keep_one_marks_group_per_owner`, `off_board_marks_follow_artboard_copies_and_cuts_by_owner`, `moving_an_artboard_uses_marks_ownership_instead_of_containment` in `cmd::addons::color::screen_marks::tests`.
|
||||
|
||||
## Stroke Weight Up and Down shortcuts (2026-11-06)
|
||||
|
||||
Cmd/Ctrl+Alt+. (`stroke.weightUp`) and Cmd/Ctrl+Alt+, (`stroke.weightDown`) raise and lower the weight of each selected stroke from its own weight, with the keys a [public feature request reply](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/32307397-increment-decrement-stroke-weight-key-commands) names: a quarter unit of Units › Stroke at a time up to one unit, whole units above it, no lower than a quarter unit and no higher than 1000 pt. Type steps its stroked characters; objects without a stroke are left alone; with nothing selected the weight of the next object drawn steps. Each press is one undo step (#5797). Evidence: `tests::strokeux::stroke_weight_up_and_down_step_each_selected_stroke`, `stroke_weight_up_with_nothing_selected_sets_up_new_art`, `cmd::stroke::tests::weight_steps_follow_units_and_stop_at_their_bounds`. Scores unchanged.
|
||||
|
||||
Reference in New Issue
Block a user