Merge main into fix/dwg-listed-without-decoder

This commit is contained in:
dotCooCoo committed 2026-12-04 19:11:56 -08:00
commit 348b561d3c
128 files changed
+10626 -1055

No files matched your search

+4 -1
View File
@@ -8,10 +8,12 @@
//! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their
//! visual bounds share, Randomize Opacity gives each selected object a random
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object.
//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object,
//! and Add Artboard Guides puts a rectangular guide around artboards ([`artboard_guides`]).
//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view
//! command) are the UI's.
mod artboard_guides;
pub mod marks;
#[cfg(test)]
mod tests;
@@ -144,6 +146,7 @@ pub fn specs() -> Vec<CommandSpec> {
),
]
.into_iter()
.chain(artboard_guides::specs())
.chain(marks::specs())
.collect()
}
@@ -0,0 +1,206 @@
//! Add Artboard Guides (`addon.arrange.artboardGuides`): a rectangular guide around each chosen
//! artboard, `offset` outside its edges (inside when negative), on a top-level layer named
//! Artboard Guides. Its dialog is the UI's.
#[cfg(test)]
mod tests;
use std::collections::HashSet;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{Anchor, PathData, Point, Rect, shapes};
use super::super::super::panelcmds::{artboard_at, listed_artboards};
use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or};
use super::{LIMIT, number_in};
use crate::sanity::rect_in_range;
use crate::{DocState, Result, Session};
/// The command.
pub(crate) const COMMAND: &str = "addon.arrange.artboardGuides";
/// The top-level layer the guides go on, made when the document has none of that name.
pub(crate) const LAYER: &str = "Artboard Guides";
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.arrange.artboardGuides",
"Add Artboard Guides",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{offset?: pt −1000000..1000000 (0: on the artboard's edges; more than 0 outside them, less than 0 inside), artboards?: [index…] (0-based; default: the active artboard, `artboard`), artboard?: index (the active artboard, which the app passes; default the view's, which the journal then records as `artboard` for a replay), all?: false (true: every artboard; not with `artboards`)} add a rectangular guide path around each of those artboards, `offset` from its edges, as one undo step. The guides go on the topmost top-level layer named Artboard Guides, which keeps its lock and visibility; a new one is made above the others when there is none. The guide paths have the current paint (Release Guides makes them paths with it). A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no step. It is an error when an inset leaves an artboard no width or no height, and when an edge of a guide would lie more than 4,000,000 pt from the origin along either axis. Off without artboards → {ids, layer: id (null when nothing was added and there is no such layer), skipped (guides already there)}",
has_artboards,
artboard_guides
)]
}
/// A document with at least one artboard is open.
fn has_artboards(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
if s.doc().map_err(|e| e.to_string())?.doc.artboards.is_empty() { Err("the document has no artboards".into()) } else { Ok(()) }
}
/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no
/// longer has it, the artboard the document opened on, else the first.
fn active_artboard(st: &DocState) -> 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)).unwrap_or(0)
}
/// The topmost top-level layer named [`LAYER`].
fn guide_layer(d: &Document) -> Option<NodeId> {
d.layers.iter().rev().find(|l| matches!(l.kind, NodeKind::Layer { .. }) && l.name.as_deref() == Some(LAYER)).map(|l| l.id)
}
/// `r`'s corners as an exact hash key, whichever way round `r` runs.
fn rect_key(r: Rect) -> [u64; 4] {
let r = r.abs();
[r.x0, r.y0, r.x1, r.y1].map(|v| if v == 0.0 { 0 } else { v.to_bits() })
}
#[cfg(test)]
thread_local! {
static GUIDE_NODES_VISITED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn guide_rectangles(d: &Document, layer: Option<NodeId>) -> HashSet<[u64; 4]> {
let mut rects = HashSet::new();
if let Some(n) = layer.and_then(|id| d.node(id)) {
n.walk(&mut |c| {
#[cfg(test)]
GUIDE_NODES_VISITED.with(|count| count.set(count.get() + 1));
// The anchors' bounds: `traces` only accepts segments that stay between their anchors.
if let NodeKind::Path { path, guide: true, .. } = &c.kind
&& let [sp] = &path.subpaths[..]
&& let Some(first) = sp.anchors.first()
{
let r = sp.anchors.iter().fold(Rect::from_points(first.p, first.p), |r, a| r.union_pt(a.p));
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
if traces(path, &corners) {
rects.insert(rect_key(r));
}
}
});
}
rects
}
/// Does the segment from `a` to `b` run straight along a horizontal or vertical line, from `a` to `b`
/// without turning back? Its handles lie on that line, and the curve's position along it never reverses.
fn straight(a: &Anchor, b: &Anchor) -> bool {
let along = |f: fn(Point) -> f64, g: fn(Point) -> f64| {
if [a.h_out, b.h_in].iter().any(|h| g(*h) != g(a.p)) || g(a.p) != g(b.p) {
return false;
}
let s = (f(b.p) - f(a.p)).signum();
let [p0, p1, p2, p3] = [a.p, a.h_out, b.h_in, b.p].map(|p| f(p) * s);
// The derivative along the line, as a quadratic Bernstein form: never negative on [0, 1].
let (u, v, w) = (p1 - p0, p2 - p1, p3 - p2);
let curve = u - 2.0 * v + w;
let vertex = if curve > 0.0 && (0.0..=1.0).contains(&((u - v) / curve)) { u - (u - v) * (u - v) / curve } else { 0.0 };
u >= 0.0 && w >= 0.0 && vertex >= 0.0
};
if a.p == b.p {
return a.h_out == a.p && b.h_in == a.p;
}
along(|p| p.x, |p| p.y) || along(|p| p.y, |p| p.x)
}
/// Is `path` one closed run of straight segments through `corners`, from any corner, either way round?
fn traces(path: &PathData, corners: &[Point; 4]) -> bool {
let [sp] = &path.subpaths[..] else { return false };
if !sp.closed || sp.anchors.len() < 4 {
return false;
}
let n = sp.anchors.len();
if (0..n).any(|i| !straight(&sp.anchors[i], &sp.anchors[(i + 1) % n])) {
return false;
}
// A last anchor on the first one only closes the path: the check above has kept its handles on that
// point, so the corners are read without it.
let m = if sp.anchors[n - 1].p == sp.anchors[0].p { n - 1 } else { n };
let points: Vec<Point> = sp
.anchors
.iter()
.take(m)
.enumerate()
.filter_map(|(i, a)| {
let prev = sp.anchors[(i + m - 1) % m].p;
let next = sp.anchors[(i + 1) % m].p;
let interior = (prev.x == a.p.x && a.p.x == next.x && a.p.y > prev.y.min(next.y) && a.p.y < prev.y.max(next.y))
|| (prev.y == a.p.y && a.p.y == next.y && a.p.x > prev.x.min(next.x) && a.p.x < prev.x.max(next.x));
(!interior).then_some(a.p)
})
.collect();
let [first, second, _, _] = &points[..] else { return false };
let (Some(start), Some(next)) = (corners.iter().position(|c| c == first), corners.iter().position(|c| c == second)) else {
return false;
};
// 1 runs the way `corners` does, 3 the other way.
let step = (next + 4 - start) % 4;
(step == 1 || step == 3) && points.iter().enumerate().all(|(k, p)| *p == corners[(start + k * step) % 4])
}
fn artboard_guides(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = COMMAND;
let offset = number_in(p, "offset", 0.0, (-LIMIT, LIMIT), C)?;
let all = switch_or(p, "all", false, C)?;
let listed = p.get("artboards").filter(|v| !v.is_null());
if all && listed.is_some() {
return Err(bad(C, "give `all` or `artboards`, not both"));
}
let st = s.doc()?;
let d = &st.doc;
if d.artboards.is_empty() {
return Err(bad(C, "the document has no artboards"));
}
// The active artboard: the one the app passes, else the view's, recorded for a replay.
let active = artboard_at(d, p, "artboard", C)?;
let indices: Vec<usize> = match listed {
Some(v) => listed_artboards(d, v, "artboards", C)?,
None if all => (0..d.artboards.len()).collect(),
None => vec![active.unwrap_or_else(|| active_artboard(st))],
};
if let (false, None, None, Some(&i)) = (all, listed, active, indices.first()) {
s.note_journal("artboard", json!(i));
}
let st = s.doc()?;
let d = &st.doc;
let layer = guide_layer(d);
let mut existing = guide_rectangles(d, layer);
let (mut rects, mut skipped) = (Vec::with_capacity(indices.len()), 0);
for i in indices {
let Some(board) = d.artboards.get(i) else { continue };
let r = board.rect.inflate(offset, offset);
if !(r.width() > 0.0 && r.height() > 0.0) {
return Err(bad(C, format!("the inset leaves artboard {i} ({}) no width or height", board.name)));
}
if !rect_in_range(r) {
return Err(bad(C, "the guide would reach past the edge of the canvas"));
}
if !existing.insert(rect_key(r)) {
skipped += 1;
} else {
rects.push(r);
}
}
if rects.is_empty() {
return Ok(json!({ "ids": [], "layer": layer.map(|l| l.0), "skipped": skipped }));
}
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
let (layer, ids) = s.edit("Add Artboard Guides", |d, _| {
let layer = guide_layer(d).unwrap_or_else(|| d.add_layer(Some(LAYER)));
let mut ids = Vec::with_capacity(rects.len());
for r in &rects {
let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), Default::default());
look.apply(d, &mut n);
if let NodeKind::Path { guide, .. } = &mut n.kind {
*guide = true;
}
ids.push(d.insert(Some(layer), usize::MAX, n)?);
}
Ok((layer, ids))
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "layer": layer.0, "skipped": skipped }))
}
@@ -0,0 +1,336 @@
//! Add Artboard Guides: the guide rectangles it adds and where, the artboards it takes, the layer
//! it reuses, one undo step (none when nothing is added), when it is off, and bad params refused
//! without a change.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{PathData, Point, Rect, SubPath};
use super::{COMMAND, LAYER};
use crate::Session;
/// A new document with one 400 × 300 pt artboard and a second one beside it.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("artboard.new", &json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
s
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn board(s: &Session, i: usize) -> Rect {
s.doc().unwrap().doc.artboards[i].rect
}
fn ids(r: &Value) -> Vec<NodeId> {
r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect()
}
/// The guide rectangle of path `id`: its bounds, and that it is a guide on layer `layer`.
fn guide(s: &Session, layer: NodeId, id: NodeId) -> Rect {
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
assert!(matches!(n.kind, NodeKind::Path { guide: true, .. }), "{id:?} is a guide path");
assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == id), "{id:?} is on the guides layer");
n.geometric_bounds().unwrap()
}
fn near(a: Rect, b: Rect) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-9)
}
fn layer_names(s: &Session) -> Vec<String> {
s.doc().unwrap().doc.layers.iter().map(|l| l.display_name()).collect()
}
#[test]
fn a_positive_offset_puts_a_guide_outside_the_active_artboard_on_a_new_layer() {
let mut s = session();
let n = steps(&s);
let before = layer_names(&s);
let r = s.execute(COMMAND, &json!({"offset": 9})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
let layer = NodeId(r["layer"].as_u64().unwrap());
assert_eq!(r["skipped"], json!(0));
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
// The active artboard is the first when the view has not picked one.
assert!(near(guide(&s, layer, id), board(&s, 0).inflate(9.0, 9.0)), "{:?}", guide(&s, layer, id));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.last().unwrap().id, layer, "the new layer goes above the others");
assert_eq!(d.layers.last().unwrap().display_name(), LAYER);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer_names(&s), before, "undo takes the layer away with the guide");
}
#[test]
fn the_active_artboard_is_the_one_the_view_keeps() {
let mut s = session();
let second = s.doc().unwrap().doc.artboards[1].id;
s.doc_mut().unwrap().active_artboard = Some(second);
let r = s.execute(COMMAND, &json!({})).unwrap();
let layer = NodeId(r["layer"].as_u64().unwrap());
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
assert!(near(guide(&s, layer, id), board(&s, 1)), "offset 0: on the artboard's edges");
assert_eq!(s.journal.last().unwrap().1["artboard"], json!(1), "the journal records the artboard for a replay");
// The artboard the app passes wins over the view's.
let r = s.execute(COMMAND, &json!({"offset": 4, "artboard": 0})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
assert!(near(guide(&s, layer, id), board(&s, 0).inflate(4.0, 4.0)));
assert!(s.execute(COMMAND, &json!({"artboard": 5})).is_err(), "no such artboard");
}
#[test]
fn a_negative_offset_insets_every_artboard_and_reuses_the_layer_keeping_its_lock_and_visibility() {
let mut s = session();
let layer = NodeId(s.execute("layer.new", &json!({"name": LAYER})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.new", &json!({"name": "Art"})).unwrap();
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
s.execute("layer.setProps", &json!({"ids": [layer.0], "visible": false})).unwrap();
let (layers, n) = (s.doc().unwrap().doc.layers.len(), steps(&s));
let r = s.execute(COMMAND, &json!({"offset": -12, "all": true})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step for every artboard");
assert_eq!(r["layer"], json!(layer.0), "the layer of that name is reused");
assert_eq!(s.doc().unwrap().doc.layers.len(), layers, "no layer is added");
let added = ids(&r);
assert_eq!(added.len(), 2);
for (i, id) in added.into_iter().enumerate() {
assert!(near(guide(&s, layer, id), board(&s, i).inflate(-12.0, -12.0)), "artboard {i}");
}
let l = s.doc().unwrap().doc.node(layer).unwrap().clone();
assert!(l.locked && !l.visible, "the layer keeps its lock and visibility");
}
#[test]
fn listed_artboards_get_a_guide_each_and_a_guide_already_there_is_not_added_again() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1]})).unwrap();
let layer = NodeId(r["layer"].as_u64().unwrap());
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
assert!(near(guide(&s, layer, id), board(&s, 1).inflate(5.0, 5.0)));
// Again: nothing to add, and no undo step.
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1, 1]})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}));
assert_eq!(steps(&s), n, "a run that adds nothing makes no step");
assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before) || *s.doc().unwrap().doc == *before);
// Both artboards: only the new one is added.
let both = s.execute(COMMAND, &json!({"offset": 5, "artboards": [0, 1]})).unwrap();
assert_eq!(both["skipped"], json!(1));
let [first] = ids(&both)[..] else { panic!("one guide: {both}") };
assert!(near(guide(&s, layer, first), board(&s, 0).inflate(5.0, 5.0)));
assert_eq!(steps(&s), n + 1);
}
#[test]
fn a_guide_grouped_inside_the_layer_is_not_added_again() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
let layer = NodeId(r["layer"].as_u64().unwrap());
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let d = &s.doc().unwrap().doc;
assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == group));
assert!(d.node(group).unwrap().children().unwrap().iter().any(|c| c.id == id));
let (before, n) = (d.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}));
assert_eq!(steps(&s), n, "a run that adds nothing makes no step");
assert!(*s.doc().unwrap().doc == *before, "the document is unchanged");
}
#[test]
fn a_guide_drawn_the_other_way_round_or_from_another_corner_is_not_added_again() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
let layer = NodeId(r["layer"].as_u64().unwrap());
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0).inflate(5.0, 5.0);
let corners = [Point::new(b.x0, b.y1), Point::new(b.x1, b.y1), Point::new(b.x1, b.y0), Point::new(b.x0, b.y0)];
// Reversed from the top-left corner, reversed from the bottom-left one, and the same way round from the bottom-right one.
for points in [vec![corners[3], corners[0], corners[1], corners[2]], corners.to_vec(), vec![corners[1], corners[0], corners[3], corners[2]]] {
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
if let Some(NodeKind::Path { path, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
*path = PathData::single(SubPath::polyline(&points, true));
}
let n = steps(&s);
let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}), "{points:?}");
assert_eq!(steps(&s), n);
}
}
#[test]
fn collinear_midpoints_do_not_add_another_guide_or_history_step() {
let mut s = session();
let r = s.execute(COMMAND, &json!({})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0);
let points = [
Point::new(b.center().x, b.y0),
Point::new(b.x1, b.y0),
Point::new(b.x1, b.center().y),
Point::new(b.x1, b.y1),
Point::new(b.center().x, b.y1),
Point::new(b.x0, b.y1),
Point::new(b.x0, b.center().y),
Point::new(b.x0, b.y0),
];
for reverse in [false, true] {
let mut points = points.to_vec();
if reverse {
points.reverse();
}
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") };
*path = PathData::single(SubPath::polyline(&points, true));
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}));
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc, before);
}
}
#[test]
fn a_closing_anchor_on_the_first_one_does_not_add_another_guide_or_history_step() {
let mut s = session();
let r = s.execute(COMMAND, &json!({})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0);
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)];
for reverse in [false, true] {
let mut points = corners.to_vec();
if reverse {
points.reverse();
}
points.push(points[0]);
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") };
*path = PathData::single(SubPath::polyline(&points, true));
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}), "reverse: {reverse}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc, before);
}
}
#[test]
fn handles_along_a_side_still_match_and_handles_off_it_do_not() {
let mut s = session();
let r = s.execute(COMMAND, &json!({})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0);
let mid = Point::new(b.center().x, b.y0);
let points = [mid, Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1), Point::new(b.x0, b.y0)];
let corner = points[1];
let set = |s: &mut Session, h_in: Point, h_out: Point, corner_in: Point| {
let mut sp = SubPath::polyline(&points, true);
sp.anchors[0].h_in = h_in;
sp.anchors[0].h_out = h_out;
sp.anchors[1].h_in = corner_in;
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") };
*path = PathData::single(sp);
};
// The extra anchor's handles lie along the top side: the guide still matches.
// Then a handle past the corner on a segment that still runs one way (along x: 0, 9, 6, 8 eighths).
let eighth = (corner.x - mid.x) / 8.0;
for (h_out, corner_in) in
[(Point::new(mid.x + 20.0, b.y0), corner), (Point::new(mid.x + 9.0 * eighth, b.y0), Point::new(mid.x + 6.0 * eighth, b.y0))]
{
set(&mut s, Point::new(mid.x - 20.0, b.y0), h_out, corner_in);
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}), "{h_out:?} {corner_in:?}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc, before);
}
// A handle off the side bends it: the path is not that guide, so one is added.
set(&mut s, Point::new(mid.x - 20.0, b.y0), Point::new(mid.x + 20.0, b.y0 + 10.0), corner);
let other = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(other["skipped"], json!(0));
assert_eq!(ids(&other).len(), 1);
}
#[test]
fn every_artboard_shares_one_walk_of_existing_guides() {
let mut s = session();
s.execute(COMMAND, &json!({"all": true})).unwrap();
super::GUIDE_NODES_VISITED.with(|count| count.set(0));
s.execute(COMMAND, &json!({})).unwrap();
let single = super::GUIDE_NODES_VISITED.with(|count| count.replace(0));
assert!(single > 0);
let n = steps(&s);
let r = s.execute(COMMAND, &json!({"all": true})).unwrap();
assert_eq!(super::GUIDE_NODES_VISITED.with(|count| count.get()), single);
assert!(ids(&r).is_empty());
assert_eq!(r["skipped"], json!(2));
assert_eq!(steps(&s), n);
}
#[test]
fn release_guides_gives_back_a_rectangle_path() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"offset": 3})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
s.execute("view.guides.release", &json!({"ids": [id.0]})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(matches!(n.kind, NodeKind::Path { guide: false, .. }));
assert!(near(n.geometric_bounds().unwrap(), board(&s, 0).inflate(3.0, 3.0)));
}
#[test]
fn an_inset_that_leaves_no_width_or_height_and_bad_params_are_refused_without_a_change() {
let mut s = session();
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
// The second artboard is 100 pt tall: an inset of 50 leaves it no height.
for p in [
json!({"offset": -50, "all": true}),
json!({"offset": -200}),
json!({"offset": "9 pt"}),
json!({"offset": 1_000_001}),
json!({"offset": -1e308}),
json!({"all": 1}),
json!({"all": true, "artboards": [0]}),
json!({"artboards": []}),
json!({"artboards": [2]}),
json!({"artboards": [-1]}),
json!({"artboards": [0.5]}),
json!({"artboards": "0"}),
] {
assert!(s.execute(COMMAND, &p).is_err(), "{p}");
}
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before, "the document is unchanged");
let e = s.execute(COMMAND, &json!({"offset": -150})).unwrap_err().to_string();
assert!(e.contains("no width or height"), "{e}");
}
#[test]
fn a_guide_past_the_edge_of_the_canvas_is_refused() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 3_999_000, "y": 0, "width": 500, "height": 100})).unwrap();
let n = steps(&s);
let e = s.execute(COMMAND, &json!({"offset": 600, "artboards": [2]})).unwrap_err().to_string();
assert!(e.contains("past the edge of the canvas"), "{e}");
assert_eq!(steps(&s), n);
s.execute(COMMAND, &json!({"offset": 400, "artboards": [2]})).unwrap();
}
#[test]
fn it_is_off_without_artboards() {
let mut s = session();
let enabled = |s: &Session| s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled;
assert!(enabled(&s));
Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear();
assert!(!enabled(&s));
assert!(s.execute(COMMAND, &json!({})).is_err());
}
+3 -1
View File
@@ -22,7 +22,9 @@ use vectorcraft_color::Swatch;
use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
use vectorcraft_geom::{PathData, Rect};
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
pub use flavours::{
AI, BITMAP, DWG, DXF, EMF, EPS, FILE_HEAD, Flavour, HPGL, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture,
};
pub use flavours::{ImageRead, read_image, read_pixels};
pub(crate) use resources::SwatchChoices;
pub use resources::{ArtResources, SymbolOptions, art_resources};
+57 -14
View File
@@ -1,5 +1,6 @@
//! Clipboard flavours: what Copy offers other apps besides SVG (PNG, PDF and plain text) and what
//! Paste takes from them (bitmaps, plain text, PDF, EPS and Windows metafiles).
//! Paste takes from them (bitmaps, plain text, PDF, EPS, Windows metafiles, and copied CAD drawing
//! and plot files).
//!
//! The UI owns the platform clipboard (`Services::system_clipboard` in the egui frontend): on Copy
//! it publishes [`Session::clipboard_flavours`]; before a Paste it turns what another app put on
@@ -34,9 +35,20 @@ pub const EPS: &str = "application/postscript";
/// reads it as `document.open` does, from its editing data. The type is VectorCraft's own: no
/// system clipboard carries it, and Paste asks for [`PDF`] to get it.
pub const AI: &str = "application/x-ai";
/// A DXF drawing file copied in a file manager ([`file_flavour`]): Paste reads it with
/// `clipboard.importCad`. No system clipboard carries it, and Paste takes it when it asks for any
/// vector art.
pub const DXF: &str = "image/vnd.dxf";
/// A DWG drawing file copied in a file manager, read as [`DXF`] is.
pub const DWG: &str = "image/vnd.dwg";
/// An HP-GL plot file (`.plt`, `.hpgl`…) copied in a file manager, read as [`DXF`] is.
pub const HPGL: &str = "application/vnd.hp-hpgl";
/// What Paste reads from other apps, best first: vector art before text, text before bitmaps
/// (word processors offer a picture of copied text too).
pub const PASTE_ORDER: [&str; 6] = [SVG, PDF, EPS, EMF, TEXT, BITMAP];
/// The types Paste asks for that a copied CAD drawing or plot file ([`DXF`], [`DWG`], [`HPGL`])
/// pastes as.
const VECTOR_ART: [&str; 4] = [SVG, PDF, EPS, EMF];
/// Is `text` only an address (a web page's, an image's, a file's)? A browser's Copy Image puts the
/// image's address as text next to the picture: then the picture is what Paste takes (#597). An
/// address alone pastes as text, and nothing is fetched.
@@ -76,25 +88,31 @@ pub const FILE_HEAD: usize = 4096;
/// What a file copied in a file manager pastes as, if one of `mimes` (`image/*`: any bitmap):
/// SVG, PDF, EPS, a Windows metafile or a bitmap (its own `image/…` type), told from its first
/// [`FILE_HEAD`] bytes and its name. A `.ai` or `.ait` file is [`AI`] when its bytes are a PDF (it
/// pastes when PDF is asked for) and EPS when they are PostScript. The file's bytes are that
/// flavour's data.
/// pastes when PDF is asked for) and EPS when they are PostScript. A DXF or DWG drawing or an
/// HP-GL plot file is [`DXF`], [`DWG`] or [`HPGL`], and pastes when any vector art (SVG, PDF, EPS
/// or EMF) is asked for. The file's bytes are that flavour's data.
pub fn file_flavour(name: &str, head: &[u8], mimes: &[&str]) -> Option<&'static str> {
let f = fileio::detect(name, head)?;
let (asked, mime) = match f.id {
"svg" => (SVG, SVG),
let (asked, mime): (&[&str], _) = match f.id {
"svg" => (&[SVG], SVG),
// `detect` names gzip data SVGZ (a compressed native file aside); `clipboard.importSvg`
// reads SVGZ data.
"svgz" if unpacks_to_svg(head) => (SVG, SVG),
"pdf" => (PDF, PDF),
"ps" => (EPS, EPS),
"eps" => (EPS, EPS),
"ai" | "ait" if head.starts_with(b"%PDF") => (PDF, AI),
"ai" | "ait" if vectorcraft_pdf::is_postscript(head) => (EPS, EPS),
"emf" | "wmf" => (EMF, EMF),
_ if f.raster => (BITMAP, f.mime),
"svgz" if unpacks_to_svg(head) => (&[SVG], SVG),
"pdf" => (&[PDF], PDF),
"ps" => (&[EPS], EPS),
"eps" => (&[EPS], EPS),
"ai" | "ait" if head.starts_with(b"%PDF") => (&[PDF], AI),
"ai" | "ait" if vectorcraft_pdf::is_postscript(head) => (&[EPS], EPS),
"emf" | "wmf" => (&[EMF], EMF),
// A file with a drawing's or a plot file's name may hold something else (`.plt` is also a
// chart program's script): it pastes only when its bytes are a drawing or a plot.
"dxf" if vectorcraft_cad::is_dxf(head) => (&VECTOR_ART, DXF),
"dwg" if vectorcraft_cad::is_dwg(head) => (&VECTOR_ART, DWG),
"hpgl" if vectorcraft_cad::hpgl::is_named_hpgl(head) => (&VECTOR_ART, HPGL),
_ if f.raster => (&[BITMAP], f.mime),
_ => return None,
};
mimes.contains(&asked).then_some(mime)
mimes.iter().any(|m| asked.contains(m)).then_some(mime)
}
/// Does gzip data `head` (a file's first bytes, often a stream cut short) unpack to SVG markup?
@@ -222,6 +240,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
import_eps
),
cmd!(
query "clipboard.importCad",
"Load CAD Drawing into Clipboard",
[],
None,
"{dataBase64 (a DXF or DWG drawing, or an HP-GL plot file), format: dxf|dwg|hpgl (what the data is; data of another format is refused), center?: [x, y]} replace the clipboard with the drawing's objects as document.open reads the file (DXF and DWG: the Model layout at 1:1 in its own unit), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste. The app runs it for a .dxf, .dwg or HP-GL file copied in a file manager",
has_doc,
import_cad
),
]
}
@@ -565,6 +592,22 @@ fn import_eps(s: &mut Session, p: &Value) -> Result<Value> {
import_picture(s, p, C, "Clipboard.eps", &bytes)
}
fn import_cad(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "clipboard.importCad";
let (is_it, name, not_it): (fn(&[u8]) -> bool, _, _) = match p.get("format").and_then(Value::as_str) {
Some("dxf") => (vectorcraft_cad::is_dxf, "Clipboard.dxf", "the data isn't a DXF drawing"),
Some("dwg") => (vectorcraft_cad::is_dwg, "Clipboard.dwg", "the data isn't a DWG drawing"),
Some("hpgl") => (vectorcraft_cad::hpgl::is_named_hpgl, "Clipboard.plt", "the data isn't an HP-GL plot file"),
_ => return Err(bad(C, "format must be dxf, dwg or hpgl")),
};
let bytes = data_param(p, C)?;
// Data of another format is refused, not read as the format its name gives.
if !is_it(&bytes) {
return Err(bad(C, not_it));
}
import_picture(s, p, C, name, &bytes)
}
/// Replace the clipboard with the objects of the picture `bytes`, read as the file `name` is
/// opened (command `cmd`).
fn import_picture(s: &mut Session, p: &Value, cmd: &str, name: &str, bytes: &[u8]) -> Result<Value> {
+44 -9
View File
@@ -99,12 +99,19 @@ fn family_names(d: &Document) -> Result<BTreeSet<String>> {
note(family);
}
}
let mut graphs = Vec::new();
let (mut graphs, mut dimensions) = (Vec::new(), Vec::new());
view.visit_stored(|node, _| {
// A dimension's options name the family its label is redrawn in.
if let Some(dimension) = &node.extras().dimension {
dimensions.push(dimension.options.font_family.clone());
}
if node.extras().graph.is_some() {
graphs.push(node.id);
}
});
for mut family in dimensions {
note(&mut family);
}
for id in graphs {
if let Some(node) = view.stored_node_mut(id) {
graph_families(node, &mut note);
@@ -112,6 +119,9 @@ fn family_names(d: &Document) -> Result<BTreeSet<String>> {
}
fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) {
graph_families(node, note);
if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_mut()) {
note(&mut dimension.options.font_family);
}
if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) {
brush_graphs(Arc::make_mut(&mut mask.art), note);
}
@@ -145,9 +155,15 @@ pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)
visit(&mut font.family);
}
}
// A live dimension makes its label again from its options.
if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_deref_mut()) {
visit(&mut dimension.options.font_family);
// A dimension redraws its label from its own options, so they follow the label's family.
// A spelling that already names the same font, or one too long for the options, is kept.
if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_mut()) {
let family = &mut dimension.options.font_family;
let mut renamed = family.clone();
visit(&mut renamed);
if !CompositeFont::same_name(&renamed, family) && renamed.len() <= ALIAS_BYTES_MAX {
*family = renamed;
}
}
graph_families(node, visit);
}
@@ -170,12 +186,22 @@ impl CompositeImport {
}
}
/// The longest family name in bytes that a dimension's options keep (`DimensionOptions::validate`).
const ALIAS_BYTES_MAX: usize = 256;
fn composite_alias(base: &str, reserved: &BTreeSet<String>, cmd: &str) -> Result<String> {
let db = FontDb::global();
let mut number = 2_u64;
loop {
let suffix = format!(" {number}");
let stem: String = base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())).collect();
let bytes = ALIAS_BYTES_MAX.saturating_sub(suffix.len());
let mut stem = String::new();
for c in base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())) {
if stem.len() + c.len_utf8() > bytes {
break;
}
stem.push(c);
}
let name = format!("{}{suffix}", stem.trim_end());
if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str())
&& !reserved.contains(&name.to_lowercase())
@@ -189,7 +215,13 @@ fn composite_alias(base: &str, reserved: &BTreeSet<String>, cmd: &str) -> Result
/// Plan used incoming definitions before changing either document or the font database.
/// Keep existing meanings even for an uninstalled family that destination art still names.
pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<String>, target: &Document, cmd: &str) -> Result<CompositeImport> {
pub(super) fn plan_import(
source: Vec<CompositeFont>,
source_families: BTreeSet<String>,
dimension_families: BTreeSet<String>,
target: &Document,
cmd: &str,
) -> Result<CompositeImport> {
if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX {
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
}
@@ -230,12 +262,15 @@ pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<
let mut names = BTreeMap::new();
let mut combined = target.composite_fonts.to_vec();
for font in source {
let equivalent = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom;
let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equivalent);
let dimension = dimension_families.contains(&font.name.to_lowercase());
let equal = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom;
// A dimension keeps its own spelling of a reused name of the same font, so only an alias
// under another name has to fit the bytes its options keep.
let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equal);
let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name));
if needs_alias {
// A repeated import reuses its already-installed equal alias.
reused = target.composite_fonts.iter().find(equivalent);
reused = target.composite_fonts.iter().find(|other| equal(other) && (!dimension || other.name.len() <= ALIAS_BYTES_MAX));
}
let name = match reused {
Some(other) => other.name.clone(),
+3 -3
View File
@@ -117,8 +117,8 @@ pub use save::{
};
pub(crate) use screens::{
PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS,
check_settings as check_screen_settings, export as export_screens, safe_file_name, store_settings as store_screen_settings,
with_export_preset as with_screen_export_preset,
check_settings as check_screen_settings, export as export_screens, safe_file_name, sharing_names as sharing_screen_names,
store_settings as store_screen_settings, with_export_preset as with_screen_export_preset,
};
pub use screens::{
PRESET_FILE_EXTS as SCREEN_EXPORT_PRESET_EXTS, PRESET_FILE_FORMAT as SCREEN_EXPORT_PRESET_FORMAT, PRESET_KEYS as SCREEN_EXPORT_PRESET_KEYS,
@@ -183,7 +183,7 @@ pub use formats::{
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters,
export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions,
open_exts, open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_exts, place_filters, places_with_importer,
plugin_formats, read_extensions, readable_format, readable_format_for_name, titled_for_export, writable_format,
plugin_formats, read_extensions, readable_format, readable_format_for_name, reads_as_dwg, titled_for_export, writable_format,
};
pub(crate) use formats::{is_own_title, reads};
+5
View File
@@ -28,6 +28,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
// file, format and saved state share their data with the open ones until a step changes them.
let start = s.docs.clone();
let active = s.active;
let style_trail = s.script_in_run.then(|| s.script_style_trail.clone());
// A rollback puts back the swatch renames recorded before the batch, including any its steps pushed out of the record.
let swatch_renames = s.swatch_renames.clone();
let opens = s.plugin_events_mark();
@@ -46,6 +47,10 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
Err(e) => {
s.swatch_renames = swatch_renames;
roll_back(s, start, &stash);
if let Some(mut trail) = style_trail {
trail.resources_scanned = s.script_style_trail.resources_scanned;
s.script_style_trail = trail;
}
// The documents the steps opened are closed again: plug-ins are not told of them.
s.forget_plugin_opens_since(opens);
s.notify_text_tool("batch.rollBack");
+3 -3
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Document",
[],
None,
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer f Line truncated
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), embedIcc?: true (webp: the sRGB profile in an ICCP chunk), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chos Line truncated
has_doc,
export::export
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export for Screens",
["File", "Export"],
None,
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0; a native, .ai or EPS file of an artboard holds the grown artboard with a bleed of 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/[email protected]); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is Line truncated
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0; a native, .ai or EPS file of an artboard holds the grown artboard with a bleed of 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/[email protected]); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is Line truncated
has_doc,
screens::export_for_screens
),
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch",
[],
None,
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each addon.arrange.artboardGuides, edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
has_doc,
batch::batch
),
+6 -4
View File
@@ -113,14 +113,16 @@ pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> {
UNSUPPORTED.iter().find(|u| u.id == k || u.extensions.contains(&k.as_str()))
}
/// Formats VectorCraft opens but doesn't write, with what to export instead.
const READ_ONLY_HINTS: &[(&str, &str)] = &[("dwg", "DWG files open but can't be written: export DXF instead, which CAD apps open")];
/// Formats VectorCraft opens but doesn't write (by id or extension), with what to export instead.
const READ_ONLY_HINTS: &[(&[&str], &str)] =
&[(&["dwg", "dws", "dwt"], "DWG files open but can't be written: export DXF instead, which CAD apps open")];
/// What to write instead of the format an id or extension (any case, leading dot allowed) names,
/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG).
/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG,
/// also a `.dws` or `.dwt` file).
pub fn write_hint(id_or_ext: &str) -> Option<&'static str> {
let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase();
unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(id, _)| *id == k).map(|(_, hint)| *hint))
unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(ids, _)| ids.contains(&k.as_str())).map(|(_, hint)| *hint))
}
impl Unsupported {
+1
View File
@@ -352,6 +352,7 @@ impl RasterOptions {
interlaced: self.interlaced.unwrap_or(false),
quality: self.quality()?.unwrap_or(90).min(100),
webp_lossless: self.lossless.unwrap_or(true),
webp_embed_icc: embed_icc,
jpeg: JpegOptions {
color_model,
method: parse(self.method.as_deref(), jpeg::Method::from_id, "method", "baseline, optimized or progressive")?,
+3 -2
View File
@@ -74,8 +74,9 @@ pub(super) fn distinct_names_by(names: impl IntoIterator<Item = String>, key: im
/// Write an export's files for the destination `path` → `{path, bytes, files?, linked?, …extra}`
/// (`files`: every file when there are several; `linked`: the images it links to); with no path
/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`. Every path is
/// checked against the file access in force before the first file is written, so a refused path
/// writes none of them.
/// checked against the file access in force before the first file is written, so a path that
/// check refuses writes none of them. A write that fails after that check leaves the files
/// written before it.
pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_doc::Document, enc: &Encoded, extra: Value) -> Result<Value> {
let files = enc.named(doc, path.unwrap_or(name));
let (main, linked) = files.split_at(enc.files.len());
+47 -16
View File
@@ -159,7 +159,7 @@ const EMBED_ICC: FormatOption = FormatOption {
name: "embedIcc",
ty: "boolean",
default: "true",
description: "embed the colour profile: sRGB (RGB), the working CMYK space (CMYK) or gray with sRGB's tone curve; PNG: mark the file as sRGB (an sRGB chunk)",
description: "embed the colour profile: sRGB (RGB), the working CMYK space (CMYK) or gray with sRGB's tone curve; PNG: mark the file as sRGB (an sRGB chunk); WebP: the sRGB profile in an ICCP chunk",
};
const IMAGE_MAP: FormatOption = FormatOption {
@@ -470,7 +470,22 @@ pub const FORMATS: &[Format] = &[
read: true,
write: true,
raster: true,
options: &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, LOSSLESS, WEBP_QUALITY],
options: &[
ARTBOARD,
ARTBOARDS,
RANGE,
USE_ARTBOARDS,
RECT,
PPI,
SCALE,
WIDTH,
HEIGHT,
BACKGROUND,
ANTI_ALIAS,
LOSSLESS,
WEBP_QUALITY,
EMBED_ICC,
],
},
Format {
id: "tiff",
@@ -562,10 +577,19 @@ pub const FORMATS: &[Format] = &[
// composite, the layers combined, or the preview with a note. Exports don't write them.
reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true),
// DWG drawings, converted to DXF by craft-dwg (`vectorcraft_cad::dwg`) and read by the DXF
// reader with the DXF import options. Exports don't write them.
reader("dwg", "DWG", &["dwg"], "image/vnd.dwg", false),
// reader with the DXF import options; `.dws` drawing standards files are DWG drawings too.
// Exports don't write them.
reader("dwg", "DWG", &["dwg", "dws"], "image/vnd.dwg", false),
// `.dwt` drawing templates, DWG drawings read as `dwg` is; a template opens as a new untitled
// document. Exports don't write them.
reader("dwt", "DWG Template", &["dwt"], "image/vnd.dwg", false),
];
/// Is `id` a format read as a DWG drawing: `dwg` (also `.dws` files) or a `dwt` template?
pub fn reads_as_dwg(id: &str) -> bool {
matches!(id, "dwg" | "dwt")
}
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
pub const OPEN_EXTS: &[&str] = &[
"vectorcraft",
@@ -626,6 +650,8 @@ pub const OPEN_EXTS: &[&str] = &[
"cmx",
"pcraft",
"dwg",
"dws",
"dwt",
];
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
@@ -634,10 +660,10 @@ pub const OPEN_EXTS: &[&str] = &[
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft`
/// documents or DWG drawings either.
/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either.
pub const UNASSOCIATED_EXTS: &[&str] = &[
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc",
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg",
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt",
];
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
@@ -729,6 +755,8 @@ pub const PLACE_EXTS: &[&str] = &[
"cmx",
"pcraft",
"dwg",
"dws",
"dwt",
"txt",
"rtf",
"docx",
@@ -775,15 +803,15 @@ pub(crate) fn reads(f: &Format) -> bool {
/// Whether format `f` reads in a build that decodes DWG drawings when `dwg`.
fn reads_in(f: &Format, dwg: bool) -> bool {
f.read && (dwg || f.id != "dwg")
f.read && (dwg || !reads_as_dwg(f.id))
}
/// `exts` less `.dwg` in a build without a DWG decoder (`dwg` false).
/// `exts` less `.dwg`, `.dws` and `.dwt` in a build without a DWG decoder (`dwg` false).
fn listed_in(exts: &[&'static str], dwg: bool) -> Vec<&'static str> {
exts.iter().copied().filter(|e| dwg || *e != "dwg").collect()
exts.iter().copied().filter(|e| dwg || !matches!(*e, "dwg" | "dws" | "dwt")).collect()
}
/// The extensions File › Open reads as a document in this build: [`OPEN_EXTS`], less `.dwg` where
/// The extensions File › Open reads as a document in this build: [`OPEN_EXTS`], less `.dwg`, `.dws` and `.dwt` where
/// no DWG decoder is built in ([`vectorcraft_cad::dwg::DECODES`]).
pub fn open_exts() -> &'static [&'static str] {
static EXTS: std::sync::LazyLock<Vec<&'static str>> = std::sync::LazyLock::new(|| listed_in(OPEN_EXTS, vectorcraft_cad::dwg::DECODES));
@@ -1192,13 +1220,16 @@ mod dwg_listing_tests {
assert_eq!(listed_in(OPEN_EXTS, true), OPEN_EXTS);
assert_eq!(listed_in(PLACE_EXTS, true), PLACE_EXTS);
assert!(format_filters_in(true).any(|(_, exts)| exts.contains(&"dwg")));
// Without a decoder, nothing offers DWG drawings.
assert!(readable_format_in("dwg", false).is_none(), "DWG is not readable");
// Without a decoder, nothing offers DWG drawings, standards files or templates.
for e in ["dwg", "dws", "dwt"] {
assert!(readable_format_in(e, false).is_none(), ".{e} is not readable");
assert!(!listed_in(OPEN_EXTS, false).contains(&e), "File › Open does not list .{e}");
assert!(!listed_in(PLACE_EXTS, false).contains(&e), "File › Place does not list .{e}");
assert!(format_filters_in(false).all(|(_, exts)| !exts.contains(&e)), "no filter lists .{e}");
}
assert!(readable_format_in("dxf", false).is_some(), "DXF still is");
assert!(!listed_in(OPEN_EXTS, false).contains(&"dwg"), "File › Open does not list .dwg");
assert!(!listed_in(PLACE_EXTS, false).contains(&"dwg"), "File › Place does not list .dwg");
assert_eq!(listed_in(OPEN_EXTS, false).len(), OPEN_EXTS.len() - 1, "every other extension stays");
assert!(format_filters_in(false).all(|(_, exts)| !exts.contains(&"dwg")), "no DWG filter");
let drawing_exts = OPEN_EXTS.iter().filter(|e| matches!(**e, "dwg" | "dws" | "dwt")).count();
assert_eq!(listed_in(OPEN_EXTS, false).len(), OPEN_EXTS.len() - drawing_exts, "every other extension stays");
// This build lists DWG exactly when it decodes it.
let dwg = vectorcraft_cad::dwg::DECODES;
assert_eq!(open_exts().contains(&"dwg"), dwg);
+14 -11
View File
@@ -47,12 +47,14 @@ impl Loaded {
/// PDF, an EPS or `.ai` without ruler units, a raster image, a metafile, an Affinity file or
/// what an importer plug-in reads, as the reference app opens such files (#5820). A native
/// document (also one that an SVG, PDF, `.ai` or EPS file carries, `restored`), an SVG (the
/// units of its root's size, pixels when it gives none), a DXF or DWG drawing (the unit it was
/// read in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows
/// change, not its art.
/// units of its root's size, pixels when it gives none), a DXF or DWG drawing (also a DWG
/// template; the unit it was read in) and a `.ai` or EPS with ruler units keep theirs. Only the
/// units the document shows change, not its art.
pub(crate) fn with_unit_prefs(mut self, prefs: &Prefs) -> Self {
let records_units =
self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf" | "dwg");
let records_units = self.restored
|| self.doc.units_from_file
|| matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf")
|| super::reads_as_dwg(self.format.id);
if !records_units {
self.doc.units = crate::units::pref_unit(&prefs.units_general);
}
@@ -126,7 +128,8 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
return format("dxf");
}
if vectorcraft_cad::is_dwg(bytes) {
return format("dwg");
// A template keeps its meaning from the extension.
return by_name.filter(|f| f.id == "dwt").or_else(|| format("dwg"));
}
if let Some(kind) = vectorcraft_metafile::sniff(bytes) {
return format(kind.id());
@@ -563,8 +566,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
}
read
}
// A DWG drawing is read as the DXF craft-dwg converts it to.
"dxf" | "dwg" => {
// A DWG drawing (or template) is read as the DXF craft-dwg converts it to.
"dxf" | "dwg" | "dwt" => {
let (doc, warnings) = super::dxfimport::import(bytes, &opts.dxf)?;
(doc, warnings, false)
}
@@ -1021,9 +1024,9 @@ fn open_loaded(
.cloned()
.collect();
let source_path = path.clone().filter(|_| !losses.is_empty());
// A template (saved by Save as Template, or an .ait, .vctemplate or .cdt file) opens as a new
// untitled document.
let template = as_template || doc.template || matches!(format.id, "ait" | "template" | "cdt");
// A template (saved by Save as Template, or an .ait, .vctemplate, .cdt or .dwt file) opens as a
// new untitled document.
let template = as_template || doc.template || matches!(format.id, "ait" | "template" | "cdt" | "dwt");
if template {
doc.template = false;
doc.title = s.next_untitled();
+44 -1
View File
@@ -282,7 +282,11 @@ impl Row {
// The resolution is stored in the file too.
ScreenSize::Ppi(ppi) => o["ppi"] = json!(ppi),
size => {
o["scale"] = json!(size.scale_for(C, region)?);
let scale = size.scale_for(C, region)?;
if !scale.is_finite() || !(0.01..=64.0).contains(&scale) {
return Err(bad(C, "the effective raster scale must be between 0.01 and 64 pixels per point"));
}
o["scale"] = json!(scale);
if let Some(m) = o.as_object_mut() {
m.remove("ppi");
}
@@ -638,6 +642,25 @@ fn fold(name: &str) -> String {
.collect()
}
thread_local! {
/// The [`fold`]ed names the exports run by [`sharing_names`] on this thread have taken so far.
static SHARED_NAMES: std::cell::RefCell<Option<HashSet<String>>> = const { std::cell::RefCell::new(None) };
}
/// `f`, with every `document.exportForScreens` it runs on this thread naming its files around
/// the names the ones before it took, so a later export does not write over an earlier one's file
/// (it numbers its own: `-2`, `-3`…).
pub(crate) fn sharing_names<T>(f: impl FnOnce() -> T) -> T {
let outer = SHARED_NAMES.with(|n| n.borrow_mut().replace(HashSet::new()));
let r = f();
SHARED_NAMES.with(|n| *n.borrow_mut() = outer);
r
}
/// The key the names taken by an earlier export are held under in [`Output::taken`]: no file of
/// this export has it.
const EARLIER_EXPORT: &str = "\0earlier export";
/// The file names (and bytes) an export wrote, or the files it returns.
#[derive(Default)]
struct Output {
@@ -1194,6 +1217,11 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
let ungrown = (grown && o.assets.is_none() && o.layers.is_none() && o.selection.is_none()).then_some(original);
let crop = rows.iter().any(|r| r.format.id != "pdf");
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
for row in rows.iter().filter(|row| row.format.raster) {
for item in &items {
row.options_for(item.region, item.artboard)?;
}
}
// Before the folder is made or any row is written, with the artboards each file holds.
let single: Option<Vec<usize>> = items.iter().map(|i| i.artboard).collect::<Option<Vec<_>>>().filter(|a| naming.single_pdf && a.len() > 1);
let st = s.doc()?;
@@ -1348,6 +1376,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
create_dir(dir)?;
}
let mut out = Output::default();
// The names earlier exports of a [`sharing_names`] run took into the same files.
if !o.zip {
SHARED_NAMES.with(|n| {
for name in n.borrow().iter().flatten() {
out.taken.insert(name.clone(), EARLIER_EXPORT.to_string());
}
});
}
// The notes on the options, then the encoders' notes for every file, each once.
let mut notes: Vec<Note> = Vec::new();
for text in unused {
@@ -1426,6 +1462,13 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
files += 1;
}
}
if !o.zip {
SHARED_NAMES.with(|n| {
if let Some(shared) = n.borrow_mut().as_mut() {
shared.extend(out.taken.keys().cloned());
}
});
}
// A cancel that came while the last file was encoded returns no files. A folder export
// without a ZIP has written every file by now, so it returns them.
if o.zip || folder.is_none() {
@@ -62,6 +62,35 @@ fn document_open_reads_a_dwg_drawing_as_its_dxf() {
assert!(open(&mut s, "plan.dwg", &plan_dwg(), json!({"dxf": {"layout": "Sheet 9"}})).is_err());
}
/// A DWG drawing copied in a file manager pastes the objects its DXF pastes; a DXF given as DWG is
/// refused.
#[test]
fn a_copied_dwg_drawing_pastes_as_its_dxf_does() {
use crate::cmd::clipboard::{DWG, PASTE_ORDER, file_flavour};
let dwg = plan_dwg();
assert_eq!(file_flavour("plan.dwg", &dwg, &PASTE_ORDER), Some(DWG));
let pasted = |data: &[u8], format: &str| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
s.execute("clipboard.importCad", &json!({"dataBase64": b64(data), "format": format})).unwrap();
s.execute("edit.paste", &json!({"center": [300, 200]})).unwrap();
leaves(&s).iter().map(|n| n.geometric_bounds()).collect::<Vec<_>>()
};
let (from_dwg, from_dxf) = (pasted(&dwg, "dwg"), pasted(&plan(), "dxf"));
assert!(!from_dwg.is_empty());
assert_eq!(from_dwg.len(), from_dxf.len());
for (a, b) in from_dwg.iter().zip(&from_dxf) {
let close = match (a, b) {
(Some(a), Some(b)) => [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-3),
(a, b) => a.is_none() && b.is_none(),
};
assert!(close, "{a:?} {b:?}");
}
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
assert!(s.execute("clipboard.importCad", &json!({"dataBase64": b64(&plan()), "format": "dwg"})).is_err());
}
#[test]
fn a_dwg_opened_is_never_written_back_as_dwg() {
let dir = std::env::temp_dir().join(format!("vc-dwg-save-{}", std::process::id()));
@@ -111,3 +140,69 @@ fn dwg_is_read_only_and_detected_by_content() {
assert!(!r["writable"].as_array().unwrap().contains(&json!("dwg")));
assert!(r["unsupported"].as_array().unwrap().iter().all(|u| u["id"] != "dwg"));
}
/// A `.dwt` drawing template opens as a new untitled document and a `.dws` standards file as the
/// drawing it is, each read as a `.dwg` with the same content is; a DXF named `.dwt` stays a DXF.
#[test]
fn a_dwt_template_opens_untitled_and_a_dws_opens_as_its_drawing() {
let dir = std::env::temp_dir().join(format!("vc-dwt-open-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let dwg = plan_dwg();
let mut s = Session::new();
open(&mut s, "plan.dwg", &dwg, json!({})).unwrap();
let (want_layers, want_leaves) = (layer_names(&s), leaves(&s).len());
let template = dir.join("plan.dwt");
std::fs::write(&template, &dwg).unwrap();
let r = s.execute("document.open", &json!({"path": template.to_string_lossy()})).unwrap();
assert_eq!(r["format"], "dwt");
assert!(r["title"].as_str().is_some_and(|t| t.starts_with("Untitled")), "a template opens untitled: {}", r["title"]);
let st = s.doc().unwrap();
assert!(st.path.is_none());
assert_eq!(st.doc.units, vectorcraft_doc::Unit::Millimeters, "the drawing's unit");
assert_eq!((layer_names(&s), leaves(&s).len()), (want_layers.clone(), want_leaves));
let standards = dir.join("plan.dws");
std::fs::write(&standards, &dwg).unwrap();
let r = s.execute("document.open", &json!({"path": standards.to_string_lossy()})).unwrap();
assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("dwg"), Some("plan.dws")));
assert_eq!((layer_names(&s), leaves(&s).len()), (want_layers, want_leaves));
assert_eq!(detect("plan.dwt", &plan()).map(|f| f.id), Some("dxf"), "the content tells");
let _ = std::fs::remove_dir_all(&dir);
}
/// File › Place reads a `.dwt` or `.dws` drawing as it reads a `.dwg`: fitted to the artboard with
/// the same `dxf` options, in one undo step.
#[test]
fn a_dwt_or_dws_drawing_places_as_a_dwg_does() {
let dwg = plan_dwg();
let place = |name: &str| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute("file.place", &json!({"name": name, "dataBase64": b64(&dwg), "dxf": {"fit": true, "center": false}})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{name}: one undo step");
let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap());
let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
(r["format"].as_str().map(str::to_string), [b.x0, b.y0, b.x1, b.y1])
};
let (format, want) = place("plan.dwg");
assert_eq!(format.as_deref(), Some("dwg"));
assert_eq!(place("plan.dws"), (Some("dwg".to_string()), want));
assert_eq!(place("plan.dwt"), (Some("dwt".to_string()), want));
}
#[test]
fn dwt_and_dws_are_read_only_and_exporting_them_says_to_write_dxf() {
let f = format("dwt").unwrap();
assert!(f.read && !f.write);
assert_eq!(readable_format("dws").map(|f| f.id), Some("dwg"));
for ext in ["dws", "dwt"] {
assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext), "{ext}");
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let e = s.execute("document.export", &json!({"format": ext})).unwrap_err().to_string();
assert!(e.contains("export DXF instead"), "{ext}: {e}");
}
}
@@ -184,6 +184,33 @@ fn dxf_is_readable_and_detected_by_content() {
assert!(r["readable"].as_array().unwrap().contains(&json!("dxf")));
}
/// A DXF drawing copied in a file manager pastes as its objects at 1:1, centred where the paste
/// puts it; data that isn't a DXF drawing, and a format `clipboard.importCad` doesn't read, are
/// refused.
#[test]
fn a_copied_dxf_drawing_pastes_as_its_objects() {
use crate::cmd::clipboard::{BITMAP, DXF, PASTE_ORDER, TEXT, file_flavour};
let dxf = plan();
assert_eq!(file_flavour("plan.dxf", &dxf, &PASTE_ORDER), Some(DXF));
assert_eq!(file_flavour("plan.txt", &dxf, &PASTE_ORDER), Some(DXF), "the content tells");
assert_eq!(file_flavour("plan.dxf", &dxf, &[TEXT, BITMAP]), None, "not when only text or a bitmap is asked for");
assert_eq!(file_flavour("plan.dxf", b"a note, not a drawing", &PASTE_ORDER), None, "by its bytes, not its name");
let mut s = page();
let r = s.execute("clipboard.importCad", &json!({"dataBase64": b64(&dxf), "format": "dxf"})).unwrap();
assert!(r["count"].as_u64().is_some_and(|n| n > 0), "{r}");
s.execute("edit.paste", &json!({"center": [300, 200]})).unwrap();
let doc = &s.doc().unwrap().doc;
let pasted: Vec<_> = doc.layers.iter().flat_map(|l| l.children().into_iter().flatten()).collect();
let b = pasted.iter().fold(None, |b, n| vectorcraft_geom::union_opt(b, n.geometric_bounds())).unwrap();
assert!((b.width() - 200.0 * MM).abs() < 1e-6 && (b.height() - 100.0 * MM).abs() < 1e-6, "{b:?}");
assert!((b.center().x - 300.0).abs() < 1e-6 && (b.center().y - 200.0).abs() < 1e-6, "{b:?}");
let mut refused = |p: Value| s.execute("clipboard.importCad", &p).unwrap_err().to_string();
let plot = b64(b"IN;SP1;PA0,0;PD100,0;");
assert!(refused(json!({"dataBase64": plot, "format": "dxf"})).contains("isn't a DXF drawing"));
assert!(refused(json!({"dataBase64": b64(&dxf), "format": "svg"})).contains("format must be"));
assert!(refused(json!({"dataBase64": b64(&dxf)})).contains("format must be"));
}
/// A document of one 600 × 400 artboard.
fn page() -> Session {
let mut s = Session::new();
@@ -80,6 +80,34 @@ fn files_that_are_not_hpgl_are_refused() {
assert_eq!(text["format"], "txt", "{text}");
}
/// A plot file copied in a file manager pastes as its paths, also one named as a plot file that
/// starts with an instruction plot files seldom start with; a file of that name holding something
/// else does not paste as a plot, and data that isn't one is refused.
#[test]
fn a_copied_plot_file_pastes_as_its_paths() {
use crate::cmd::clipboard::{BITMAP, HPGL, PASTE_ORDER, TEXT, file_flavour};
let script = b"set terminal png\nplot sin(x)\n";
assert_eq!(file_flavour("part.plt", PLOT, &PASTE_ORDER), Some(HPGL));
assert_eq!(file_flavour("part.plt", b"SI0.2,0.3;SP1;PA0,0;PD1016,0;", &PASTE_ORDER), Some(HPGL));
assert_eq!(file_flavour("graph.plt", script, &PASTE_ORDER), None);
assert_eq!(file_flavour("part.plt", PLOT, &[TEXT, BITMAP]), None);
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
s.execute("clipboard.importCad", &json!({"dataBase64": b64(PLOT), "format": "hpgl"})).unwrap();
s.execute("edit.paste", &json!({"center": [150, 100]})).unwrap();
let mut paths = vec![];
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Path { .. } = n.kind {
paths.extend(n.geometric_bounds());
}
});
assert_eq!(paths.len(), 2, "{paths:?}");
assert!(paths.iter().all(|b| (b.width() - 72.0).abs() < 0.5), "an inch wide: {paths:?}");
for (data, format) in [(&script[..], "hpgl"), (PLOT, "dwg")] {
assert!(s.execute("clipboard.importCad", &json!({"dataBase64": b64(data), "format": format})).is_err(), "{format}");
}
}
/// A plot file named as one opens when its first instruction is one a plot file seldom starts with;
/// under another name it isn't taken for HP-GL.
#[test]
@@ -229,6 +229,31 @@ fn png_says_it_is_srgb_unless_embed_icc_is_false() {
assert!(f["options"].get("embedIcc").is_some(), "png lists embedIcc");
}
/// WebP, lossless or lossy, holds the sRGB profile in an `ICCP` chunk unless `embedIcc` is false,
/// in Export As and in Export for Screens' `settings.webp`, without a note on an unused option.
#[test]
fn webp_embeds_the_srgb_profile_unless_embed_icc_is_false() {
let mut s = session(40.0, 30.0, 1);
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap();
let has_iccp = |file: &[u8]| file.windows(4).any(|w| w == b"ICCP");
for lossless in [true, false] {
let on = s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap();
assert!(has_iccp(&b64(&on)), "lossless {lossless}");
let off = s.execute("document.export", &json!({"format": "webp", "lossless": lossless, "embedIcc": false})).unwrap();
assert!(!has_iccp(&b64(&off)), "lossless {lossless}");
assert_eq!(off["warnings"], json!([]), "lossless {lossless}: embedIcc is a WebP option");
}
let screens = |s: &mut Session, settings: Value| {
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp"}], "settings": settings})).unwrap();
b64(&r["files"][0])
};
assert!(has_iccp(&screens(&mut s, json!({}))));
assert!(!has_iccp(&screens(&mut s, json!({"webp": {"embedIcc": false}}))));
let r = s.execute("document.formats", &json!({})).unwrap();
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "webp").unwrap();
assert!(f["options"].get("embedIcc").is_some(), "webp lists embedIcc");
}
#[test]
fn formats_list_the_raster_options() {
let mut s = Session::new();
+7 -6
View File
@@ -95,13 +95,13 @@ fn webp_is_lossless_by_default_and_lossy_when_asked() {
(b64(&r), r["warnings"].clone())
};
let (lossless, warnings) = export(&mut s, json!({}));
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default");
assert_eq!(webp_chunks(&lossless), [*b"VP8X", *b"ICCP", *b"VP8L"], "lossless with the profile by default");
assert_eq!(warnings, json!([]));
// Quality doesn't change a lossless file.
assert_eq!(export(&mut s, json!({"lossless": true, "quality": 10})).0, lossless);
let (lossy, warnings) = export(&mut s, json!({"lossless": false}));
assert_eq!(webp_chunks(&lossy), [*b"VP8 "], "opaque art is a plain lossy file");
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ICCP", *b"VP8 "], "opaque art has no alpha chunk");
assert_eq!(warnings, json!([]), "no note: the file is lossy");
assert_eq!(export(&mut s, json!({"lossless": false, "quality": 90})).0, lossy, "quality 90 by default");
// At quality 90 each channel stays within 4 levels of the exact pixels on average.
@@ -114,10 +114,11 @@ fn webp_is_lossless_by_default_and_lossy_when_asked() {
// Lower quality, smaller file.
let low = export(&mut s, json!({"lossless": false, "quality": 10})).0;
let high = export(&mut s, json!({"lossless": false, "quality": 95})).0;
assert_eq!(webp_chunks(&low), [*b"VP8 "]);
assert_eq!(webp_chunks(&low), [*b"VP8X", *b"ICCP", *b"VP8 "]);
assert!(low.len() < high.len(), "{} vs {} bytes", low.len(), high.len());
for q in [0, 100] {
assert_eq!(webp_chunks(&export(&mut s, json!({"lossless": false, "quality": q})).0), [*b"VP8 "], "quality {q}");
let file = export(&mut s, json!({"lossless": false, "quality": q, "embedIcc": false})).0;
assert_eq!(webp_chunks(&file), [*b"VP8 "], "quality {q}: a plain lossy file without the profile");
}
}
@@ -130,7 +131,7 @@ fn lossy_webp_keeps_translucent_pixels() {
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let file = |s: &mut Session, lossless: bool| b64(&s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap());
let (lossless, lossy) = (file(&mut s, true), file(&mut s, false));
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ALPH", *b"VP8 "]);
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ICCP", *b"ALPH", *b"VP8 "]);
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
assert_eq!((lw, lh), (w, h));
let at = |px: &[u8], x: u32, y: u32| -> [u8; 4] {
@@ -161,7 +162,7 @@ fn webp_quality_out_of_its_range_is_refused() {
assert!(s.execute("document.export", &json!({"format": "webp", "quality": 101})).is_err());
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp", "lossless": false, "quality": 100}]})).unwrap();
let file = b64(&r["files"][0]);
assert_eq!(webp_chunks(&file), [*b"VP8 "]);
assert_eq!(webp_chunks(&file), [*b"VP8X", *b"ICCP", *b"VP8 "]);
}
#[test]
+9 -5
View File
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reorder",
[],
None,
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path whose layer and groups are shown and unlocked and that is not on a locked artboard (unless it is new art there that is still selected), and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
has_doc,
move_node
),
@@ -1051,7 +1051,8 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
}
// A path in a compound path keeps no paint, live shape or pixel alignment of its own, as
// Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when
// the path was, or when the compound path it leaves was.
// the path was, or when the compound path it leaves was. A compound path that is
// pixel-aligned snaps the path it takes in.
if let Some(c) = into {
let mut aligned = from_aligned;
if let Some(m) = d.node_mut(id) {
@@ -1061,9 +1062,12 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
*live = None;
}
}
if aligned && let Some(cn) = d.node_mut(c) {
cn.extras_mut().pixel_aligned = true;
super::object::snap_if_aligned(cn);
if let Some(cn) = d.node_mut(c) {
aligned |= cn.extras().pixel_aligned;
if aligned {
cn.extras_mut().pixel_aligned = true;
super::object::snap_if_aligned(cn);
}
}
}
if let Some((appearance, aligned)) = out_of
+14 -2
View File
@@ -44,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
"{on?: bool (default: toggle)} show non-printing red outlines and badges on missing linked images and placed documents in the active document; transient view state, no undo step; reads no files (the desktop app scans in the background, links.marked inspects now) → {on}",
has_doc, show_missing_links),
cmd!(query "links.marked", "Marked Missing Links", [], None,
"{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}",
"{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off; a caller whose read folders do not cover the same files as the document's, or a script command, gets its own answer and the canvas markers stay as they are → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}",
has_doc, marked),
cmd!(
query "links.check",
@@ -2693,7 +2693,19 @@ fn marked(s: &mut Session, _: &Value) -> Result<Value> {
Some(json!({"id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1]}))
})
.collect();
st.missing_link_markers = Some((st.doc.clone(), ids));
// The canvas draws the markers the link watch finds with the read roots the document was
// opened with ([`Session::start_link_scan`]). An answer found with other read roots stays the
// caller's, as is one found by a script command, whose file-read gate the link watch does
// not have.
let same_roots = !crate::file_access::in_script_command()
&& match (crate::file_access::current(), &st.opened_by) {
(None, None) => true,
(Some(a), Some(b)) => Arc::ptr_eq(&a, b) || a.same_reads(b),
_ => false,
};
if same_roots {
st.missing_link_markers = Some((st.doc.clone(), ids));
}
Ok(json!({"on": st.show_missing_links, "images": images}))
}
+1 -1
View File
@@ -314,7 +314,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Shape Properties",
[],
None,
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the corners a rounded star cuts drops its selected anchors and segments, and is an error with radius or kind), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the corners a rounded star cuts drops its selected anchors and segments, and is an error with radius or kind), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once no corner stores a radius or a corner kind other than round (a corner that an anchor move straightens draws no arc but keeps its radius and the path stays live); sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
has_selection,
set_live_shape
),
+7 -2
View File
@@ -598,14 +598,19 @@ fn round_strokes(n: &mut Node) -> bool {
/// Snap path object `n`'s horizontal and vertical straight segments ([`snap_segments`]). A path
/// with Live Corners snaps the outline its corners are cut from. Another live shape is moved and
/// scaled as a whole instead, from its path's bounds to the bounds of the snapped path, so that it
/// stays a live shape. Returns whether it changed.
/// stays a live shape. Relative radii of corners the snap straightens or bends are converted as an
/// anchor edit converts them ([`vectorcraft_doc::rebase_relative_radii`]). Returns whether it changed.
fn snap_path_node(n: &mut Node, half: bool, sc: Scaling) -> bool {
let NodeKind::Path { path, live, .. } = &mut n.kind else { return false };
let Some(shape) = live.as_deref_mut() else { return snap_segments(path, half) };
if let LiveShape::Path { base, .. } = shape {
if let LiveShape::Path { base, radii, radii_relative, .. } = shape {
let before = radii_relative.then(|| base.clone());
if !snap_segments(base, half) {
return false;
}
if let Some(before) = before {
vectorcraft_doc::rebase_relative_radii(&before, base, radii);
}
*path = shape.to_path();
return true;
}
+18 -2
View File
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Anchors",
[],
None,
"{dx, dy (a move by 0, or one that the pixel-grid snap of pixel-aligned paths takes back, changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); with rounded Live Corners, each selected anchor's uncut corner moves by (dx, dy) and is recut at its radius, so a grabbed arc end can move off a snap target; refused while an object of a symbol instance's art is selected",
"{dx, dy (a move by 0, or one that the pixel-grid snap of pixel-aligned paths takes back, changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); with Live Corners that store a radius (rounded, or straightened by an earlier move), each selected anchor's uncut corner moves by (dx, dy) and is recut at its radius, so a grabbed arc end can move off a snap target, and a straightened corner that bends again rounds again; refused while an object of a symbol instance's art is selected",
has_selection,
move_anchors
),
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Anchor Point",
[],
None,
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with rounded Live Corners, the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y)",
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again",
has_doc,
move_anchor
),
@@ -266,6 +266,22 @@ fn snap_undoes(s: &Session, ids: impl IntoIterator<Item = NodeId>, apply: impl F
let (Some(NodeKind::Path { path, live, .. }), Some(anchors)) = (st.doc.node(id).map(|n| &n.kind), st.selection.anchors.get(&id)) else {
continue;
};
// Relative radii of corners the edit bent and the snap straightened again are converted
// twice, and can come back off by rounding: an outline back where it was, with the same
// kinds and those radii, counts as no change.
if let Some(vectorcraft_doc::LiveShape::Path { base, radii, kinds, radii_relative: true }) = live.as_deref() {
if let Some(NodeKind::Path { path: after_path, live: after, .. }) = doc.node_mut(id).map(|n| &mut n.kind)
&& let Some(vectorcraft_doc::LiveShape::Path { base: b, radii: r, kinds: k, radii_relative: true }) = after.as_deref()
&& b == base
&& k == kinds
&& r.len() == radii.len()
&& r.iter().zip(radii).all(|(x, y)| (x - y).abs() <= 1e-12 * x.abs().max(y.abs()).max(1.0))
{
after.clone_from(live);
after_path.clone_from(path);
}
continue;
}
// A live path keeps its variant through an anchor edit, so only a rectangle or polygon
// needs the comparison below.
if !matches!(live.as_deref(), Some(vectorcraft_doc::LiveShape::Rectangle { .. } | vectorcraft_doc::LiveShape::Polygon { .. })) {
+2 -2
View File
@@ -360,7 +360,7 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
let (natural, warnings) = (s.frame, s.warnings.clone());
return Ok(Loaded { name, format, art: Art::Document(s, link.clone(), !crop), natural, warnings, link: Some(link), board: None });
}
let anchored = matches!(format.id, "dxf" | "dwg") && (opts.dxf.fit || !opts.dxf.center);
let anchored = (format.id == "dxf" || fileio::reads_as_dwg(format.id)) && (opts.dxf.fit || !opts.dxf.center);
let (mut doc, warnings) = {
// Of the open options, only a DXF or DWG drawing's apply (the colour mode stays the file's).
let o = fileio::LoadOptions { dxf: opts.dxf, ..Default::default() };
@@ -383,7 +383,7 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
let board = doc.artboards.first().map(|a| a.rect).filter(|_| anchored);
let layers = std::mem::take(&mut doc.layers);
let symbols = doc.symbol_boxes();
let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "dwg" | "hpgl") {
let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "hpgl") || fileio::reads_as_dwg(format.id) {
// An SVG with `crop: "crop"` asked for is framed and clipped by its viewBox (its artboard),
// as a PDF by its page: art drawn on a shared canvas keeps its place and scale (#788). By
// default, as Illustrator places one, it is its art's bounds.
+14 -8
View File
@@ -545,16 +545,22 @@ fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, bru
/// Discover the incoming resource frontier and its composite-font users before planning
/// names or changing either document. Resource order and the no-composite fast path stay shared.
fn collect_resources(src: &Document, nodes: &mut [Node], composites: bool) -> (Used, Vec<Brush>, BTreeSet<String>) {
fn collect_resources(src: &Document, nodes: &mut [Node], composites: bool) -> (Used, Vec<Brush>, BTreeSet<String>, BTreeSet<String>) {
let mut used = Used::default();
let mut families = BTreeSet::new();
let mut note_family = |name: &mut String| {
families.insert(name.to_lowercase());
let mut dimension_families = BTreeSet::new();
let mut note_families = |node: &mut Node| {
if let Some(dimension) = &node.extras().dimension {
dimension_families.insert(dimension.options.font_family.to_lowercase());
}
node_families(node, &mut |name| {
families.insert(name.to_lowercase());
});
};
for n in nodes.iter_mut() {
refs(n, &mut |r| used.note(r));
if composites {
each_mut(n, &mut |node| node_families(node, &mut note_family));
each_mut(n, &mut note_families);
}
}
let src_brushes = vectorcraft_brush::library(src);
@@ -585,18 +591,18 @@ fn collect_resources(src: &Document, nodes: &mut [Node], composites: bool) -> (U
for mut a in art {
refs(&mut a, &mut |r| used.note(r));
if composites {
each_mut(&mut a, &mut |node| node_families(node, &mut note_family));
each_mut(&mut a, &mut note_families);
}
}
}
(used, src_brushes, families)
(used, src_brushes, families, dimension_families)
}
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
/// `nodes` at the names they got.
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> {
let composites = !src.composite_fonts.is_empty() || !dst.composite_fonts.is_empty();
let (used, mut src_brushes, families) = collect_resources(src, nodes, composites);
let (used, mut src_brushes, families, dimension_families) = collect_resources(src, nodes, composites);
let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::<Vec<_>>();
// A family the source does not define as a composite font, which the destination defines as
// one, would draw in the destination's composite font after placement.
@@ -604,7 +610,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd:
.iter()
.any(|family| CompositeFont::named(&src.composite_fonts, family).is_none() && CompositeFont::named(&dst.composite_fonts, family).is_some());
// All representability/validation errors precede incoming or destination mutation.
let plan = if fonts.is_empty() && !undefined_clash { None } else { Some(plan_import(fonts, families, dst, cmd)?) };
let plan = if fonts.is_empty() && !undefined_clash { None } else { Some(plan_import(fonts, families, dimension_families, dst, cmd)?) };
let staged;
let mut aliased = false;
let src = if let Some(plan) = &plan {
@@ -4,6 +4,7 @@
/// Commands a plug-in may call when its manifest lists them, in order.
pub(super) const ALLOWED: &[&str] = &[
"addon.arrange.artboardGuides",
"addon.arrange.grid",
"addon.arrange.groupOverlapping",
"addon.arrange.groupRows",