Merge main into feat/type-path-center-on-top

This commit is contained in:
dotCooCoo committed 2026-11-11 22:03:31 -08:00
commit 3172abc41b
234 files changed
+13280 -7009

No files matched your search

+1
View File
@@ -749,6 +749,7 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
/// The most presets one presets file imports: each is looked up among the saved ones.
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::DecodedImages;
pub use docmenu::guide_indexes;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
+4
View File
@@ -6,12 +6,15 @@ mod cleanup;
mod color;
mod contour;
mod document;
mod image;
mod pathtools;
mod pen;
mod select;
mod shapes;
mod typetools;
pub(crate) use image::DecodedImages;
use super::CommandSpec;
/// The commands of every built-in add-on.
@@ -21,6 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(color::specs());
v.extend(contour::specs());
v.extend(document::specs());
v.extend(image::specs());
v.extend(pathtools::specs());
v.extend(pen::specs());
v.extend(select::specs());
+598
View File
@@ -0,0 +1,598 @@
//! Image Tools (`addon.image.*`), a built-in add-on. Remove Background makes the background of the
//! selected images transparent in their own pixels, as one undo step. The background is the most
//! common color along an image's edges, the average of its four corners, or colors the caller
//! picks. It is cleared where it reaches in from an edge, or wherever it is. The work is done here,
//! on the pixels; nothing is sent anywhere. It is a VectorCraft addition. Its submenu (Object ›
//! Plug-ins › Image Tools) and dialog are the UI's.
#[cfg(test)]
mod tests;
use std::collections::{HashMap, HashSet};
use std::io::Cursor;
use std::sync::{Arc, Weak};
use image::{DynamicImage, ImageBuffer, LumaA, Rgba};
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_doc::{ImageBlob, NodeId, NodeKind};
use vectorcraft_geom::Affine;
use super::super::fileio::{MAX_RASTER_ALLOC, ppi};
use super::super::menucmds::has_image;
use super::super::{CommandSpec, Result, Session, bad, checked_ids_param, cmd, hex_with_alpha, number_or, switch_or, text_param};
/// Remove Background's command.
pub const REMOVE_BACKGROUND: &str = "addon.image.removeBackground";
const C: &str = REMOVE_BACKGROUND;
/// The most colors `colors` lists.
const MAX_COLORS: usize = 16;
/// Bytes a pixel takes while it is worked on, beside its pixels: its level, whether the edge search
/// reached it, and its place in the search's stack (4 bytes, twice that while the stack grows).
const WORK_BYTES: u64 = 10;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.image.removeBackground",
"Remove Background…",
["Object", "Plug-ins", "Image Tools"],
None,
"{background?: \"edges\" (default: the most common color along the image's edges; nothing is cleared when the edges hold at least as many clear pixels as pixels of that color) | \"corners\" (the average of the image's four corner pixels that are not clear; nothing is cleared when all four are clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 colors, each a hex color \"#rrggbb\" or \"#rgb\" with or without the # or one of black, white, red, green and blue; needed with background: colors, and checked but not used with edges or corners), contiguous?: bool (true: only background pixels that reach in from an edge are cleared; false: they are cleared wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a background color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (with distance, % of the largest RGB distance; with channels, % of 255 steps on one channel; a pixel this near a background color is cleared; 10), softness?: 0..100 (% past the tolerance over which pixels fade from cleared to kept; 10), ids?: [id…] (default: the selected images)} make the background of each image transparent in its own pixels, as one undo step: the image stays an image, embedded as a PNG with an alpha channel at the depth of its pixels (16-bit images keep 16 bits and grayscale images stay gray) with the source's color profile and resolution, and a linked image is embedded; a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, and a result with no pixel left are refused, and an image whose pixels do not change is left as it is (no undo step when none changes) → {changed: the images changed, ids, cleared: the pixels made fully clear in them}",
has_image,
remove_background
)]
}
/// Where the background's colors come from.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Background {
/// The most common color along the image's edges.
Edges,
/// The average of the image's four corner pixels that are not clear.
Corners,
/// These colors.
Colors(Vec<[u8; 3]>),
}
/// How near a color is to a background color.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Match {
/// The RGB distance, as a percentage of the largest one (black to white).
Distance,
/// The largest difference on one of red, green and blue, as a percentage of a channel's range.
Channels,
}
/// What Remove Background clears: the background, whether only where it reaches in from an edge,
/// and how near a color must be to it (a percentage, measured as `measure` says) to be cleared, and
/// to fade out past that.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Settings {
pub background: Background,
pub contiguous: bool,
pub measure: Match,
pub tolerance: f64,
pub softness: f64,
}
impl Settings {
/// The settings `p` gives, each checked.
fn read(p: &Value) -> Result<Self> {
let percent = |key: &str| -> Result<f64> {
let v = number_or(p, key, 10.0, C)?;
if v.is_finite() && (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) }
};
let (tolerance, softness) = (percent("tolerance")?, percent("softness")?);
let colors = match p.get("colors") {
None | Some(Value::Null) => None,
Some(v) => Some(colors(v)?),
};
let background = match text_param(p, "background", C)? {
None | Some("edges") => Background::Edges,
Some("corners") => Background::Corners,
Some("colors") => Background::Colors(colors.ok_or_else(colors_error)?),
Some(_) => return Err(bad(C, "`background` must be edges, corners or colors")),
};
let measure = match text_param(p, "match", C)? {
None | Some("distance") => Match::Distance,
Some("channels") => Match::Channels,
Some(_) => return Err(bad(C, "`match` must be distance or channels")),
};
let contiguous = switch_or(p, "contiguous", true, C)?;
Ok(Self { background, contiguous, measure, tolerance, softness })
}
}
fn colors_error() -> crate::EngineError {
bad(C, "`colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue")
}
/// The colors `v` lists: an array of strings, or one string of them split by commas or spaces.
/// Each is read as [`Color::from_hex`] reads it; one with an alpha part is refused.
fn colors(v: &Value) -> Result<Vec<[u8; 3]>> {
// One past the most is enough to tell a list that is too long.
let texts: Vec<&str> = match v {
Value::String(s) => s.split([',', ' ', '\t', '\n']).filter(|t| !t.is_empty()).take(MAX_COLORS + 1).collect(),
Value::Array(a) => a.iter().take(MAX_COLORS + 1).map(Value::as_str).collect::<Option<_>>().ok_or_else(colors_error)?,
_ => return Err(colors_error()),
};
if texts.is_empty() || texts.len() > MAX_COLORS {
return Err(colors_error());
}
texts.into_iter().map(|t| rgb8(t).ok_or_else(colors_error)).collect()
}
/// The 8-bit RGB of the color `t` writes.
fn rgb8(t: &str) -> Option<[u8; 3]> {
if hex_with_alpha(t) {
return None;
}
let [r, g, b] = Color::from_hex(t)?.to_rgb_uncalibrated();
Some([r, g, b].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8))
}
fn remove_background(s: &mut Session, p: &Value) -> Result<Value> {
let settings = Settings::read(p)?;
// A preview step keeps the pixels it decodes for the next step; other runs keep none.
let mut kept = std::mem::take(&mut s.decoded_images);
let previewing = s.previewing;
let found = changes(s, p, &settings, previewing.then_some(&mut kept));
s.decoded_images = kept;
let changes = found?;
let ids: Vec<u64> = changes.iter().map(|(id, ..)| id.0).collect();
let made_clear: u64 = changes.iter().map(|(_, out, _)| out.cleared).sum();
if !changes.is_empty() {
s.edit("Remove Background", |d, _| {
for (id, out, xf) in changes {
let key = out.blob.content_key();
d.images.entry(key.clone()).or_insert(out.blob);
if let Some(NodeKind::Image(im)) = d.node_mut(id).map(|n| &mut n.kind) {
im.key = key;
(im.width, im.height, im.xf) = (out.width, out.height, xf);
im.link = None;
}
}
Ok(())
})?;
}
Ok(json!({ "changed": ids.len(), "ids": ids, "cleared": made_clear }))
}
/// The images `p` names (`ids`, or the selected images) whose pixels change, each with its pixels
/// cleared as `settings` say and the transform that keeps its place and size. Decoded pixels are
/// taken from and kept in `kept` when it is given.
fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Vec<(NodeId, Cleared, Affine)>> {
let st = s.doc()?;
let ids: Vec<NodeId> = if p.get("ids").is_some_and(|v| !v.is_null()) {
// Each image once, however often `ids` names it.
let mut given = HashSet::new();
let ids: Vec<NodeId> = checked_ids_param(s, p, "ids", C)?.into_iter().filter(|id| given.insert(*id)).collect();
if let Some(id) = ids.iter().find(|id| !matches!(st.doc.node(**id).map(|n| &n.kind), Some(NodeKind::Image(_)))) {
return Err(bad(C, format!("object {} is not an image", id.0)));
}
ids
} else {
st.selection.objects.iter().copied().filter(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))).collect()
};
if ids.is_empty() {
return Err(bad(C, "select an image"));
}
// Every image is checked before any is decoded.
let mut images = vec![];
for id in ids {
let Some(NodeKind::Image(im)) = st.doc.node(id).map(|n| &n.kind) else { continue };
let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image's pixels are missing"))?;
// The preview stands in for a file that hasn't been read, or that is kept at its preview.
if im.link.is_some() && blob.is_proxy() {
return Err(bad(C, "the linked image shows its preview: embed or relink it first"));
}
if blob.is_cmyk() {
return Err(bad(C, "a CMYK image has no transparency to set"));
}
images.push((id, im, blob));
}
// Each image's pixels once, however many objects show them.
let mut cleared: HashMap<&str, Option<Cleared>> = HashMap::new();
let mut changes = vec![];
for (id, im, blob) in images {
let out = match cleared.get(im.key.as_str()) {
Some(out) => out.clone(),
None => {
let out = clear(blob, settings, kept.as_deref_mut())?;
cleared.insert(&im.key, out.clone());
out
}
};
if let Some(out) = out {
// A file read at another size than the object's keeps the object's place and size.
let xf = if (out.width, out.height) == (im.width, im.height) {
im.xf
} else {
im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(out.width), f64::from(im.height) / f64::from(out.height))
};
changes.push((id, out, xf));
}
}
Ok(changes)
}
/// An image with its background cleared: its PNG, its size in pixels, and how many of its pixels
/// were made fully clear.
#[derive(Clone, Debug)]
pub(crate) struct Cleared {
pub blob: ImageBlob,
pub width: u32,
pub height: u32,
pub cleared: u64,
}
/// An image's pixels as straight RGBA, at 8 or 16 bits a sample.
#[derive(Clone)]
enum Pixels {
Eight(image::RgbaImage),
Sixteen(ImageBuffer<Rgba<u16>, Vec<u16>>),
}
/// The most bytes of decoded pixels and ICC profiles [`DecodedImages`] keeps (128 MiB, or 32 MiB in
/// the web app).
const KEEP_BYTES: u64 = MAX_RASTER_ALLOC / 16;
/// The images Remove Background decoded during an interaction's preview steps, the most recently
/// used first, at most [`KEEP_BYTES`] in all. The next preview step runs the command again on the
/// same bytes and takes their pixels from here instead of decoding them again. The session holds
/// it and empties it when the interaction ends (OK or Cancel). A run that is not a preview step
/// does not read or fill it.
#[derive(Default)]
pub(crate) struct DecodedImages(Vec<Decoded>);
/// An image decoded by [`clear`]: the bytes it was decoded from (held weakly, so they are not kept
/// alive for it, and an entry whose bytes are gone is dropped), its pixels, whether it was gray,
/// and its ICC profile.
struct Decoded {
source: Weak<Vec<u8>>,
pixels: Arc<Pixels>,
gray: bool,
icc: Option<Vec<u8>>,
}
#[cfg(test)]
thread_local! {
/// How many times this thread decoded an image in [`clear`].
pub(crate) static DECODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
impl DecodedImages {
/// Drops every image kept.
pub(crate) fn empty(&mut self) {
self.0.clear();
}
/// How many images are kept.
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.0.len()
}
/// The pixels, gray flag and ICC profile kept for `bytes`, if they are kept. Images whose bytes
/// are gone are dropped first.
fn get(&mut self, bytes: &Arc<Vec<u8>>) -> Option<(Arc<Pixels>, bool, Option<Vec<u8>>)> {
self.0.retain(|d| d.source.strong_count() > 0);
let at = self.0.iter().position(|d| std::ptr::eq(d.source.as_ptr(), Arc::as_ptr(bytes)))?;
let d = self.0.remove(at);
let found = (Arc::clone(&d.pixels), d.gray, d.icc.clone());
self.0.insert(0, d);
Some(found)
}
/// Keeps `pixels` decoded from `bytes` first, in place of anything kept for the same bytes, and
/// drops images whose bytes are gone and the least recently used past [`KEEP_BYTES`].
fn keep(&mut self, bytes: &Arc<Vec<u8>>, pixels: Arc<Pixels>, gray: bool, icc: Option<Vec<u8>>) {
self.0.retain(|d| d.source.strong_count() > 0 && !std::ptr::eq(d.source.as_ptr(), Arc::as_ptr(bytes)));
self.0.insert(0, Decoded { source: Arc::downgrade(bytes), pixels, gray, icc });
let mut total = 0u64;
self.0.retain(|d| {
total = total.saturating_add(d.bytes());
total <= KEEP_BYTES
});
}
}
impl Decoded {
/// How many bytes the entry keeps: its pixels and its ICC profile.
fn bytes(&self) -> u64 {
self.pixels.bytes().saturating_add(self.icc.as_ref().map_or(0, |icc| icc.len() as u64))
}
}
impl Pixels {
/// How many bytes the pixels take.
fn bytes(&self) -> u64 {
match self {
Self::Eight(img) => img.as_raw().len() as u64,
Self::Sixteen(img) => img.as_raw().len() as u64 * 2,
}
}
/// The width and height in pixels.
fn dimensions(&self) -> (u32, u32) {
match self {
Self::Eight(img) => img.dimensions(),
Self::Sixteen(img) => img.dimensions(),
}
}
/// Pixel `i` (row by row from the top left) at 16 bits a sample (an 8-bit sample `v` is
/// `v * 257`).
fn rgba16(&self, i: usize) -> [u16; 4] {
let mut out = [0u16; 4];
match self {
Self::Eight(img) => {
for (o, v) in out.iter_mut().zip(img.as_raw().get(i * 4..i * 4 + 4).unwrap_or_default()) {
*o = u16::from(*v) * 257;
}
}
Self::Sixteen(img) => {
for (o, v) in out.iter_mut().zip(img.as_raw().get(i * 4..i * 4 + 4).unwrap_or_default()) {
*o = *v;
}
}
}
out
}
}
/// `blob` with its background cleared as `settings` say, or `None` when no pixel changes. A CMYK
/// image, one that can't be decoded or is too large to change, and a result with no pixel left are
/// errors. The PNG keeps the source's ICC profile and resolution. The decoded pixels are taken
/// from and kept in `kept` when it is given.
pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Option<Cleared>> {
if blob.is_cmyk() {
return Err(bad(C, "a CMYK image has no transparency to set"));
}
let found = kept.as_deref_mut().and_then(|k| k.get(&blob.bytes));
let (source, gray, icc) = match found {
Some(found) => found,
None => decode(blob, kept)?,
};
// The pixels kept for the next run stay as they are; ones not kept are worked on in place.
let mut px = Arc::try_unwrap(source).unwrap_or_else(|kept| Pixels::clone(&kept));
let (w, h) = px.dimensions();
let levels = levels(w as usize, h as usize, &|i| px.rgba16(i), settings);
let Some(cleared) = apply(&mut px, &levels) else { return Ok(None) };
let left = match &px {
Pixels::Eight(img) => img.pixels().any(|p| p.0[3] > 0),
Pixels::Sixteen(img) => img.pixels().any(|p| p.0[3] > 0),
};
if !left {
return Err(bad(C, "every pixel matches the background: no image would be left"));
}
let out = match (px, gray) {
(Pixels::Eight(img), false) => DynamicImage::ImageRgba8(img),
(Pixels::Sixteen(img), false) => DynamicImage::ImageRgba16(img),
(Pixels::Eight(img), true) => {
DynamicImage::ImageLumaA8(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]])))
}
(Pixels::Sixteen(img), true) => {
DynamicImage::ImageLumaA16(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]])))
}
};
let mut png = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
if let Some(icc) = icc {
use image::ImageEncoder as _;
encoder.set_icc_profile(icc).map_err(|e| bad(C, e.to_string()))?;
}
out.write_with_encoder(encoder).map_err(|e| bad(C, e.to_string()))?;
// The resolution the file declares, which sizes the image at 100% when it is replaced or relinked.
if let Some(r) = ppi::resolution(&blob.bytes) {
png = ppi::with_png_resolution(&png, r);
}
Ok(Some(Cleared { blob: ImageBlob::png(png), width: w, height: h, cleared }))
}
/// `blob`'s pixels as straight RGBA, whether they were gray, and its ICC profile. An image that
/// can't be decoded or is too large to change is an error. The pixels are kept in `kept`, when it
/// is given, if a copy of them fits the decode allowance beside the work.
fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>) -> Result<(Arc<Pixels>, bool, Option<Vec<u8>>)> {
let reader =
|| image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(C, "the image's pixels can't be read"));
let mut decoder = reader()?.into_decoder().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?;
// The ICC profile the colors are in goes with them into the PNG.
let (w, h, kind, icc) = {
use image::ImageDecoder as _;
let (w, h) = decoder.dimensions();
(w, h, decoder.color_type(), decoder.icc_profile().ok().flatten())
};
drop(decoder);
// The file's pixels, those worked on (as many again for the PNG made of them) and the work,
// checked from the header before anything is decoded.
let deep = kind.bytes_per_pixel() > kind.channel_count();
let per_pixel = u64::from(kind.bytes_per_pixel()) + 2 * if deep { 8 } else { 4 } + WORK_BYTES;
if u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC) {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to change")));
}
let mut reader = reader()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_RASTER_ALLOC);
reader.limits(limits);
let img = reader.decode().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?;
#[cfg(test)]
DECODES.with(|c| c.set(c.get() + 1));
let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16);
let px = Arc::new(if deep { Pixels::Sixteen(img.into_rgba16()) } else { Pixels::Eight(img.into_rgba8()) });
// A kept copy is worked on as a copy: one more set of the pixels worked on.
let with_copy = per_pixel + if deep { 8 } else { 4 };
if let Some(kept) = kept
&& u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(with_copy)).is_some_and(|n| n <= MAX_RASTER_ALLOC)
&& px.bytes().saturating_add(icc.as_ref().map_or(0, |icc| icc.len() as u64)) <= KEEP_BYTES
{
kept.keep(&blob.bytes, Arc::clone(&px), gray, icc.clone());
}
Ok((px, gray, icc))
}
/// Each pixel's alpha scaled by its level (255 keeps it). Returns how many pixels were made fully
/// clear, or `None` when no pixel changed.
fn apply(px: &mut Pixels, levels: &[u8]) -> Option<u64> {
let (mut changed, mut cleared) = (false, 0u64);
match px {
Pixels::Eight(img) => {
for (p, &l) in img.pixels_mut().zip(levels) {
let a = ((u32::from(p.0[3]) * u32::from(l) + 127) / 255) as u8;
changed |= a != p.0[3];
cleared += u64::from(a == 0 && p.0[3] != 0);
p.0[3] = a;
}
}
Pixels::Sixteen(img) => {
for (p, &l) in img.pixels_mut().zip(levels) {
let a = ((u32::from(p.0[3]) * u32::from(l) + 127) / 255) as u16;
changed |= a != p.0[3];
cleared += u64::from(a == 0 && p.0[3] != 0);
p.0[3] = a;
}
}
}
changed.then_some(cleared)
}
/// How much of each of the `w` × `h` pixels `px` gives (row by row, straight RGBA at 16 bits a
/// sample) stays, from 0 (cleared) to 255 (kept), as `settings` say. Each pixel's distance to the
/// background is worked out once. A pixel past the first `u32::MAX` is left kept by the edge search.
pub(crate) fn levels(w: usize, h: usize, px: &dyn Fn(usize) -> [u16; 4], settings: &Settings) -> Vec<u8> {
let n = w.saturating_mul(h);
let refs: Vec<[u16; 3]> = match &settings.background {
Background::Colors(refs) => refs.iter().map(|c| c.map(|v| u16::from(v) * 257)).collect(),
Background::Edges => match edge_color(w, h, px) {
Some(edge) => vec![edge],
None => return vec![255; n],
},
Background::Corners => match corner_color(w, h, px) {
Some(corner) => vec![corner],
None => return vec![255; n],
},
};
let mut out: Vec<u8> = (0..n)
.map(|i| {
let [r, g, b, _] = px(i);
level([r, g, b], &refs, settings)
})
.collect();
if settings.contiguous {
// Out from the edges, through clear pixels and pixels that lose some alpha; the pixels it
// doesn't reach are kept.
let reaches = |out: &[u8], i: usize| out.get(i).is_some_and(|l| *l < 255) || px(i)[3] == 0;
let mut seen = vec![false; n];
let mut stack: Vec<u32> = vec![];
for i in border(w, h).filter(|&i| reaches(&out, i)) {
if let (Some(s), Ok(at)) = (seen.get_mut(i), u32::try_from(i)) {
*s = true;
stack.push(at);
}
}
while let Some(at) = stack.pop() {
let i = at as usize;
let (x, y) = (i % w, i / w);
let next = [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)];
for j in next.into_iter().flatten() {
if let Some(s) = seen.get_mut(j)
&& !*s
&& reaches(&out, j)
&& let Ok(at) = u32::try_from(j)
{
*s = true;
stack.push(at);
}
}
}
for (l, s) in out.iter_mut().zip(&seen) {
if !*s {
*l = 255;
}
}
}
out
}
/// The level of a pixel of color `c`: 0 within the tolerance of the nearest of `refs`, 255 from
/// the tolerance plus the softness on, and in proportion between them.
fn level(c: [u16; 3], refs: &[[u16; 3]], settings: &Settings) -> u8 {
let Settings { tolerance, softness, measure, .. } = *settings;
let d = refs.iter().map(|r| apart(c, *r, measure)).fold(f64::INFINITY, f64::min);
if d <= tolerance {
0
} else if d >= tolerance + softness {
255
} else {
((d - tolerance) / softness * 255.0).round().clamp(0.0, 255.0) as u8
}
}
/// How far apart `a` and `b` are, as a percentage, measured as `measure` says: the RGB distance of
/// the largest one (black to white), or the largest difference on one channel of the channel's range.
/// A difference of `k` 8-bit steps on one channel is exactly `k / 255 × 100` with channels.
fn apart(a: [u16; 3], b: [u16; 3], measure: Match) -> f64 {
match measure {
Match::Distance => {
let sq: f64 = a.iter().zip(b).map(|(x, y)| (f64::from(*x) - f64::from(y)).powi(2)).sum();
sq.sqrt() / (65_535.0 * 3f64.sqrt()) * 100.0
}
Match::Channels => f64::from(a.iter().zip(b).map(|(x, y)| x.abs_diff(y)).max().unwrap_or(0)) / 65_535.0 * 100.0,
}
}
/// The pixels on the edges of a `w` × `h` image, each once.
fn border(w: usize, h: usize) -> impl Iterator<Item = usize> {
let top = (0..w).filter(move |_| h > 0);
let bottom = (0..w).filter(move |_| h > 1).map(move |x| (h - 1) * w + x);
let sides = (1..h.saturating_sub(1)).flat_map(move |y| [Some(y * w), (w > 1).then(|| y * w + w - 1)].into_iter().flatten());
top.chain(bottom).chain(sides)
}
/// The most common color along an image's edges: its edge pixels grouped by 16 levels a channel,
/// with the clear ones as a group of their own, as the average of the largest group. `None` when
/// the clear edge pixels are at least as many as that group: the background is already cleared.
fn edge_color(w: usize, h: usize, px: &dyn Fn(usize) -> [u16; 4]) -> Option<[u16; 3]> {
let mut groups: HashMap<[u16; 3], (u64, [u64; 3])> = HashMap::new();
let mut clear = 0u64;
for i in border(w, h) {
let [r, g, b, a] = px(i);
if a == 0 {
clear += 1;
continue;
}
let e = groups.entry([r >> 12, g >> 12, b >> 12]).or_default();
e.0 += 1;
for (s, v) in e.1.iter_mut().zip([r, g, b]) {
*s += u64::from(v);
}
}
// Equal groups go by color, so the result doesn't depend on the map's order.
let (_, (n, sums)) = groups.into_iter().max_by(|a, b| a.1.0.cmp(&b.1.0).then(b.0.cmp(&a.0)))?;
if clear >= n {
return None;
}
Some(sums.map(|s| ((s + n / 2) / n.max(1)) as u16))
}
/// The average of the four corner pixels of a `w` × `h` image that are not clear (a corner of a
/// one-pixel-wide image counts twice). `None` when all four are clear: the background is already
/// cleared.
fn corner_color(w: usize, h: usize, px: &dyn Fn(usize) -> [u16; 4]) -> Option<[u16; 3]> {
if w == 0 || h == 0 {
return None;
}
let corners = [0, w - 1, (h - 1) * w, (h - 1) * w + w - 1];
let (mut n, mut sums) = (0u64, [0u64; 3]);
for [r, g, b, a] in corners.map(px) {
if a > 0 {
n += 1;
for (s, v) in sums.iter_mut().zip([r, g, b]) {
*s += u64::from(v);
}
}
}
(n > 0).then(|| sums.map(|s| ((s + n / 2) / n) as u16))
}
+480
View File
@@ -0,0 +1,480 @@
use std::io::Cursor;
use std::sync::Arc;
use image::{DynamicImage, ImageBuffer, Luma, Rgb};
use serde_json::{Value, json};
use vectorcraft_doc::{ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind};
use vectorcraft_geom::Affine;
use super::{Background, Match, REMOVE_BACKGROUND as C, Settings, level, levels};
use crate::Session;
use crate::cmd::fileio::ppi;
const WHITE: [u8; 4] = [255, 255, 255, 255];
const RED: [u8; 4] = [200, 0, 0, 255];
/// The command's defaults with `background`.
fn settings(background: Background) -> Settings {
Settings { background, contiguous: true, measure: Match::Distance, tolerance: 10.0, softness: 10.0 }
}
fn png(img: DynamicImage) -> Vec<u8> {
let mut out = Vec::new();
img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
}
/// 12 × 10 pixels: white, with a red block from (3, 3) to (9, 7) that holds one white pixel at
/// (6, 5), which no white edge pixel reaches.
fn framed() -> image::RgbaImage {
image::RgbaImage::from_fn(12, 10, |x, y| {
let block = (3..9).contains(&x) && (3..7).contains(&y);
image::Rgba(if block && (x, y) != (6, 5) { RED } else { WHITE })
})
}
/// A session with `bytes` opened as a document, its image selected.
fn open(bytes: &[u8]) -> (Session, NodeId) {
let mut s = Session::new();
s.execute("document.open", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap();
s.execute("select.all", &json!({})).unwrap();
let id = s.doc().unwrap().selection.objects[0];
(s, id)
}
fn image_of(s: &Session, id: NodeId) -> ImageObject {
let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") };
(**im).clone()
}
fn bytes_of(s: &Session, id: NodeId) -> Arc<Vec<u8>> {
s.doc().unwrap().doc.images[&image_of(s, id).key].bytes.clone()
}
fn pixels(s: &Session, id: NodeId) -> DynamicImage {
image::load_from_memory(&bytes_of(s, id)).unwrap()
}
fn alpha(img: &DynamicImage, x: u32, y: u32) -> u8 {
img.to_rgba8().get_pixel(x, y).0[3]
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
#[test]
fn the_edge_colors_are_cleared_where_they_reach_in_from_an_edge() {
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed())));
let before = (image_of(&s, id), undo_len(&s));
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(r, json!({"changed": 1, "ids": [id.0], "cleared": 12 * 10 - 6 * 4}));
let out = pixels(&s, id);
assert_eq!(out.color(), image::ColorType::Rgba8);
assert_eq!((alpha(&out, 0, 0), alpha(&out, 11, 9), alpha(&out, 2, 4)), (0, 0, 0), "the white around the block");
assert_eq!(out.to_rgba8().get_pixel(4, 4).0, RED, "the block");
assert_eq!(alpha(&out, 6, 5), 255, "white inside the block, which no edge reaches");
let after = image_of(&s, id);
assert_eq!((after.width, after.height, after.xf), (12, 10, before.0.xf), "the same place and size");
assert_eq!(undo_len(&s), before.1 + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(image_of(&s, id), before.0);
}
/// Picked colors, like the other backgrounds, are cleared where they reach in from an edge, and with
/// `contiguous: false` wherever they are.
#[test]
fn picked_colors_are_cleared_from_the_edges_or_wherever_they_are() {
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed())));
s.execute(C, &json!({"background": "colors", "colors": ["#fff"], "tolerance": 0, "softness": 0})).unwrap();
let out = pixels(&s, id);
assert_eq!((alpha(&out, 0, 0), alpha(&out, 6, 5), alpha(&out, 4, 4)), (0, 255, 255), "not inside the block");
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed())));
s.execute(C, &json!({"background": "colors", "colors": ["#fff"], "contiguous": false, "tolerance": 0, "softness": 0})).unwrap();
let out = pixels(&s, id);
assert_eq!((alpha(&out, 0, 0), alpha(&out, 6, 5), alpha(&out, 4, 4)), (0, 0, 255), "inside the block too; the red stays");
}
/// With `contiguous: false` the edge color is cleared inside the subject too.
#[test]
fn the_edge_color_can_be_cleared_wherever_it_is() {
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed())));
let r = s.execute(C, &json!({"contiguous": false})).unwrap();
assert_eq!(r["cleared"], 12 * 10 - 6 * 4 + 1);
let out = pixels(&s, id);
assert_eq!((alpha(&out, 0, 0), alpha(&out, 6, 5), alpha(&out, 4, 4)), (0, 0, 255));
}
/// `colors` as one string split by commas and spaces, written as other color params take them.
#[test]
fn picked_colors_can_be_one_string_of_colors() {
for colors in ["#00ff00, ffffff", "green white", "#0f0,#FFF"] {
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed())));
s.execute(C, &json!({"background": "colors", "colors": colors, "contiguous": false, "tolerance": 0, "softness": 0})).unwrap();
let out = pixels(&s, id);
assert_eq!((alpha(&out, 0, 0), alpha(&out, 6, 5), alpha(&out, 4, 4)), (0, 0, 255), "{colors}");
}
}
/// A subject along a whole edge stays: only the most common edge color is the background.
#[test]
fn a_subject_along_one_edge_is_not_the_background() {
let img = image::RgbaImage::from_fn(10, 10, |_, y| image::Rgba(if y >= 7 { RED } else { WHITE }));
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img)));
s.execute(C, &json!({})).unwrap();
let out = pixels(&s, id);
assert_eq!((alpha(&out, 5, 0), alpha(&out, 5, 9), alpha(&out, 0, 8)), (0, 255, 255));
}
/// The preview steps of one interaction, as the dialog's are, decode an image once and give what a
/// run on freshly decoded pixels gives. The pixels are kept only until the interaction ends (OK or
/// Cancel), and a run that is not a preview step keeps none.
#[test]
fn preview_steps_on_the_same_pixels_decode_them_once() {
let decodes = || super::DECODES.with(std::cell::Cell::get);
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed())));
let start = decodes();
let p = json!({"background": "colors", "colors": "#c80000", "contiguous": false, "tolerance": 0, "softness": 0});
s.begin_interaction("Remove Background").unwrap();
s.preview(C, &json!({"tolerance": 0, "softness": 0})).unwrap();
s.preview(C, &json!({"tolerance": 20, "softness": 0})).unwrap();
s.preview(C, &p).unwrap();
assert_eq!((decodes() - start, s.decoded_images.len()), (1, 1), "decoded once for three preview steps");
s.commit_interaction().unwrap();
assert_eq!(s.decoded_images.len(), 0, "OK lets the pixels go");
let (mut fresh, fresh_id) = open(&png(DynamicImage::ImageRgba8(framed())));
fresh.execute(C, &p).unwrap();
assert_eq!((decodes() - start, fresh.decoded_images.len()), (2, 0), "a run that is not a preview step keeps nothing");
assert_eq!(bytes_of(&s, id), bytes_of(&fresh, fresh_id), "the same result");
assert_eq!((alpha(&pixels(&s, id), 4, 4), alpha(&pixels(&s, id), 0, 0)), (0, 255), "the red cleared, the white kept");
s.execute("edit.undo", &json!({})).unwrap();
s.begin_interaction("Remove Background").unwrap();
s.preview(C, &json!({})).unwrap();
assert_eq!(s.decoded_images.len(), 1);
s.cancel_interaction().unwrap();
assert_eq!(s.decoded_images.len(), 0, "Cancel lets the pixels go");
s.execute(C, &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute(C, &json!({})).unwrap();
assert_eq!(decodes() - start, 5, "each run that is not a preview step decodes");
}
/// Pixels a preview step takes from the step before keep what they were decoded with: a 16-bit gray
/// image with an ICC profile comes out as a run on freshly decoded pixels gives it.
#[test]
fn reused_pixels_keep_their_depth_gray_and_profile() {
use image::{ImageDecoder as _, ImageEncoder as _};
let icc = b"a profile's bytes".to_vec();
let gray16 = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 7_000u16 } else { 61_000 }]));
let mut bytes = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes);
encoder.set_icc_profile(icc.clone()).unwrap();
DynamicImage::ImageLuma16(gray16).write_with_encoder(encoder).unwrap();
let decodes = || super::DECODES.with(std::cell::Cell::get);
let (mut s, id) = open(&bytes);
let start = decodes();
s.begin_interaction("Remove Background").unwrap();
s.preview(C, &json!({"tolerance": 0, "softness": 0})).unwrap();
s.preview(C, &json!({})).unwrap();
assert_eq!(decodes() - start, 1, "the second step took the pixels of the first");
let (mut fresh, fresh_id) = open(&bytes);
fresh.execute(C, &json!({})).unwrap();
assert_eq!(bytes_of(&s, id), bytes_of(&fresh, fresh_id), "the same result");
let DynamicImage::ImageLumaA16(out) = pixels(&s, id) else { panic!("16-bit gray with alpha") };
assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([61_000, 0], [7_000, 65_535]));
let result = bytes_of(&s, id);
let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(result.as_slice())).unwrap();
assert_eq!(decoder.icc_profile().unwrap(), Some(icc));
}
/// Once the background is cleared, most edge pixels are clear and a second run clears nothing: the
/// subject's color along an edge is not taken for the background.
#[test]
fn a_second_run_leaves_the_subject() {
let img = image::RgbaImage::from_fn(10, 10, |x, y| {
image::Rgba(if y >= 7 {
RED
} else if (4..6).contains(&x) && (3..5).contains(&y) {
[0, 0, 200, 255]
} else {
WHITE
})
});
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img)));
s.execute(C, &json!({})).unwrap();
let (first, steps) = (image_of(&s, id), undo_len(&s));
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(r, json!({"changed": 0, "ids": [], "cleared": 0}));
assert_eq!((image_of(&s, id), undo_len(&s)), (first, steps), "no change and no undo step");
let out = pixels(&s, id);
assert_eq!((alpha(&out, 5, 0), alpha(&out, 5, 9), alpha(&out, 4, 3)), (0, 255, 255), "the red and the blue stay");
}
#[test]
fn tolerance_and_softness_set_how_near_a_color_is_cleared() {
// White; 1.96 % from white; 21.6 % from white.
let px = [WHITE, [250, 250, 250, 255], [200, 200, 200, 255]];
let at = |i: usize| px[i].map(|v| u16::from(v) * 257);
let run = |tolerance, softness| levels(3, 1, &at, &Settings { tolerance, softness, ..settings(Background::Colors(vec![[255; 3]])) });
assert_eq!(run(0.0, 0.0), [0, 255, 255], "only white itself at 0");
assert_eq!(run(2.0, 0.0), [0, 0, 255]);
assert_eq!(run(0.0, 10.0), [0, 50, 255], "1.96 % into a 10 % fade");
assert_eq!(run(100.0, 0.0), [0, 0, 0], "everything at 100");
}
#[test]
fn a_result_with_no_pixel_left_is_refused_and_changes_nothing() {
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed())));
let before = (image_of(&s, id), undo_len(&s));
let e = s.execute(C, &json!({"background": "colors", "colors": "#ffffff", "tolerance": 100})).unwrap_err();
assert!(e.to_string().contains("every pixel matches the background"), "{e}");
assert_eq!((image_of(&s, id), undo_len(&s)), before);
}
#[test]
fn an_image_whose_pixels_do_not_change_is_left_with_no_undo_step() {
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed())));
let before = (image_of(&s, id), undo_len(&s));
let r = s.execute(C, &json!({"background": "colors", "colors": "#00ff00", "tolerance": 0, "softness": 0})).unwrap();
assert_eq!(r, json!({"changed": 0, "ids": [], "cleared": 0}));
assert_eq!((image_of(&s, id), undo_len(&s)), before);
// An image whose edges and corners are already clear has no edge or corner color to clear,
// whatever color the clear pixels hold.
let ring =
image::RgbaImage::from_fn(6, 6, |x, y| image::Rgba(if (1..5).contains(&x) && (1..5).contains(&y) { WHITE } else { [255, 255, 255, 0] }));
for p in [json!({}), json!({"background": "corners", "contiguous": false})] {
let (mut s, _) = open(&png(DynamicImage::ImageRgba8(ring.clone())));
assert_eq!(s.execute(C, &p).unwrap()["changed"], 0, "{p}");
}
}
/// The corners' color: 40 × 30 pixels of light gray around a red block, cleared within 5 steps on
/// each channel (`match: channels`, a tolerance of `5 / 255 × 100`, no softness), from the edges
/// or wherever it is.
#[test]
fn the_corners_color_is_cleared() {
let img = image::RgbaImage::from_fn(40, 30, |x, y| {
image::Rgba(if (10..30).contains(&x) && (8..22).contains(&y) { [200, 40, 40, 255] } else { [240, 240, 240, 255] })
});
for contiguous in [false, true] {
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img.clone())));
let p = json!({"background": "corners", "contiguous": contiguous, "match": "channels", "tolerance": 5.0 / 255.0 * 100.0, "softness": 0});
let r = s.execute(C, &p).unwrap();
assert_eq!(r["cleared"], 40 * 30 - 14 * 20, "{p}");
let out = pixels(&s, id).to_rgba8();
assert_eq!((out.get_pixel(0, 0).0[3], out.get_pixel(15, 15).0), (0, [200, 40, 40, 255]), "{p}");
}
// A clear corner is left out of the average: the other three are white, and white is cleared.
let mut img = image::RgbaImage::from_pixel(8, 8, image::Rgba(WHITE));
img.put_pixel(0, 0, image::Rgba([0; 4]));
img.put_pixel(4, 4, image::Rgba(RED));
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img)));
let r = s.execute(C, &json!({"background": "corners", "tolerance": 0, "softness": 0})).unwrap();
let out = pixels(&s, id);
assert_eq!((alpha(&out, 7, 7), alpha(&out, 3, 3), alpha(&out, 4, 4)), (0, 0, 255));
assert_eq!(r["cleared"], 8 * 8 - 2, "the pixels made clear, not the corner that was clear already");
}
/// One picked color matched by channel at a tolerance of 0: cleared wherever it is, and a pixel a
/// long way from it kept.
#[test]
fn one_picked_color_is_cleared_by_channel() {
let mut img = image::RgbaImage::from_pixel(4, 4, image::Rgba([10, 20, 30, 255]));
img.put_pixel(2, 2, image::Rgba([250, 250, 250, 255]));
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img)));
let p = json!({"background": "colors", "colors": "#0a141e", "contiguous": false, "match": "channels", "tolerance": 0, "softness": 0});
assert_eq!(s.execute(C, &p).unwrap()["cleared"], 15);
let out = pixels(&s, id);
assert_eq!((alpha(&out, 0, 0), alpha(&out, 2, 2)), (0, 255));
}
/// With `match: channels`, a tolerance of `t / 255 × 100` clears a color `k` 8-bit steps from the
/// background on one channel exactly when `k ≤ t`, for every `t` and `k` from 0 to 255; with
/// `distance` the same color is nearer when the others match.
#[test]
fn channels_match_the_largest_difference_on_one_channel() {
for t in 0..=255u16 {
let s = Settings { measure: Match::Channels, tolerance: f64::from(t) / 255.0 * 100.0, softness: 0.0, ..settings(Background::Edges) };
for k in 0..=255u16 {
for c in [[k * 257, 0, 0], [0, k * 257, 0], [0, 0, k * 257]] {
assert_eq!(level(c, &[[0; 3]], &s) == 0, k <= t, "t {t}, k {k}");
}
}
}
let at = |measure| {
level([0, 40 * 257, 0], &[[0; 3]], &Settings { measure, tolerance: 32.0 / 255.0 * 100.0, softness: 0.0, ..settings(Background::Edges) })
};
assert_eq!((at(Match::Channels), at(Match::Distance)), (255, 0), "40 steps on green: past 32 on one channel; 9 % of the RGB distance");
}
#[test]
fn sixteen_bit_and_gray_images_keep_their_depth_and_channels() {
let deep = ImageBuffer::from_fn(8, 8, |x, y| Rgb(if (2..6).contains(&x) && (2..6).contains(&y) { [51_400, 0, 1] } else { [65_535; 3] }));
let (mut s, id) = open(&png(DynamicImage::ImageRgb16(deep)));
s.execute(C, &json!({})).unwrap();
let DynamicImage::ImageRgba16(out) = pixels(&s, id) else { panic!("16-bit RGBA") };
assert_eq!(out.get_pixel(0, 0).0[3], 0);
assert_eq!(out.get_pixel(3, 3).0, [51_400, 0, 1, 65_535], "16-bit samples kept as they were");
// Samples one 8-bit step apart are told apart: only the background is cleared at 0.
let near = ImageBuffer::from_fn(4, 4, |x, y| Rgb(if (1..3).contains(&x) && (1..3).contains(&y) { [65_280; 3] } else { [65_535; 3] }));
let (mut s, id) = open(&png(DynamicImage::ImageRgb16(near)));
s.execute(C, &json!({"tolerance": 0, "softness": 0})).unwrap();
let DynamicImage::ImageRgba16(out) = pixels(&s, id) else { panic!("16-bit RGBA") };
assert_eq!((out.get_pixel(0, 0).0[3], out.get_pixel(1, 1).0[3]), (0, 65_535));
let gray = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 30u8 } else { 240 }]));
let (mut s, id) = open(&png(DynamicImage::ImageLuma8(gray)));
s.execute(C, &json!({})).unwrap();
let DynamicImage::ImageLumaA8(out) = pixels(&s, id) else { panic!("gray with alpha") };
assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([240, 0], [30, 255]));
let gray16 = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 7_000u16 } else { 61_000 }]));
let (mut s, id) = open(&png(DynamicImage::ImageLuma16(gray16)));
s.execute(C, &json!({})).unwrap();
let DynamicImage::ImageLumaA16(out) = pixels(&s, id) else { panic!("16-bit gray with alpha") };
assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([61_000, 0], [7_000, 65_535]));
}
/// The ICC profile the colors are in stays with them.
#[test]
fn the_color_profile_is_kept() {
use image::{ImageDecoder as _, ImageEncoder as _};
let icc = b"a profile's bytes".to_vec();
let mut bytes = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes);
encoder.set_icc_profile(icc.clone()).unwrap();
DynamicImage::ImageRgba8(framed()).write_with_encoder(encoder).unwrap();
let blob = ImageBlob::png(bytes);
let out = super::clear(&blob, &settings(Background::Edges), None).unwrap().unwrap();
let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(out.blob.bytes.as_slice())).unwrap();
assert_eq!(decoder.icc_profile().unwrap(), Some(icc));
}
/// The resolution the file declares stays with the pixels, so a later Replace or relink sizes the
/// image as before.
#[test]
fn the_resolution_is_kept() {
let bytes = ppi::with_png_resolution(&png(DynamicImage::ImageRgba8(framed())), (300.0, 150.0));
let (mut s, id) = open(&bytes);
s.execute(C, &json!({})).unwrap();
let (x, y) = ppi::resolution(&bytes_of(&s, id)).expect("a resolution");
assert_eq!((x.round(), y.round()), (300.0, 150.0));
}
#[test]
fn a_cmyk_image_is_refused() {
let inks = vectorcraft_doc::cmyk::Inks::new(4, 2, [0, 0, 0, 0].repeat(8)).unwrap();
let tiff = ImageBlob::cmyk_tiff(&inks).unwrap();
let (mut s, id) = open(&tiff.bytes);
let before = (image_of(&s, id), undo_len(&s));
let e = s.execute(C, &json!({})).unwrap_err();
assert!(e.to_string().contains("a CMYK image has no transparency to set"), "{e}");
assert_eq!((image_of(&s, id), undo_len(&s)), before);
}
/// A linked image of `blob`, `width` × `height` pixels as the object records it, beside the open
/// document's image.
fn place_linked(s: &mut Session, key: &str, blob: ImageBlob, (width, height): (u32, u32)) -> NodeId {
s.edit("Place", |d, sel| {
d.images.insert(key.into(), blob);
let id = d.alloc_id();
let im = ImageObject {
key: key.into(),
width,
height,
xf: Default::default(),
link: Some(LinkInfo::new("/nowhere/art.png")),
placement: Default::default(),
pixels: None,
};
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
sel.set([id]);
Ok(id)
})
.unwrap()
}
#[test]
fn a_linked_image_is_embedded_and_one_that_shows_its_preview_is_refused() {
let bytes = png(DynamicImage::ImageRgba8(framed()));
let (mut s, _) = open(&bytes);
let linked = place_linked(&mut s, "linked", ImageBlob::png(bytes.clone()), (12, 10));
let clip = vectorcraft_doc::links::PlacementOptions { clip: true, ..Default::default() };
s.edit("Placement", |d, _| {
if let Some(NodeKind::Image(im)) = d.node_mut(linked).map(|n| &mut n.kind) {
im.placement = clip;
}
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"ids": [linked.0, linked.0]})).unwrap();
assert_eq!(r, json!({"changed": 1, "ids": [linked.0], "cleared": 12 * 10 - 6 * 4}), "an image named twice changes once");
let im = image_of(&s, linked);
assert_eq!((im.link, alpha(&pixels(&s, linked), 0, 0)), (None, 0), "embedded, with its background cleared");
assert_eq!(im.placement, clip, "its Placement Options kept, as Embed keeps them");
// Pixels the file wasn't read for: the preview, as an image whose file is missing shows it.
let preview = Arc::new(bytes);
let missing = place_linked(&mut s, "missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }, (12, 10));
let before = (image_of(&s, missing), undo_len(&s));
let e = s.execute(C, &json!({})).unwrap_err();
assert!(e.to_string().contains("the linked image shows its preview: embed or relink it first"), "{e}");
assert_eq!((image_of(&s, missing), undo_len(&s)), before);
}
/// An object whose pixels were read at another size than it records keeps its place and size.
#[test]
fn an_image_read_at_another_size_keeps_its_place_and_size() {
let bytes = png(DynamicImage::ImageRgba8(framed()));
let (mut s, _) = open(&bytes);
let id = place_linked(&mut s, "linked", ImageBlob::png(bytes), (24, 20));
s.execute(C, &json!({"ids": [id.0]})).unwrap();
let im = image_of(&s, id);
assert_eq!((im.width, im.height, im.xf), (12, 10, Affine::scale_non_uniform(2.0, 2.0)));
}
#[test]
fn bad_params_are_refused_and_change_nothing() {
let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed())));
let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let before = (image_of(&s, id), undo_len(&s));
// With `ids`, the command is available when one of them is an image.
let not_image = format!("object {rect} is not an image");
let cases: [(Value, &str); 18] = [
(json!({"background": "sky"}), "`background` must be edges, corners or colors"),
(json!({"background": 5}), "`background` must be a string"),
(json!({"match": "rgb"}), "`match` must be distance or channels"),
(json!({"match": true}), "`match` must be a string"),
(json!({"contiguous": "yes"}), "`contiguous` must be true or false"),
(json!({"contiguous": 1}), "`contiguous` must be true or false"),
(json!({"tolerance": 101}), "`tolerance` must be from 0 to 100"),
(json!({"softness": -1}), "`softness` must be from 0 to 100"),
(json!({"tolerance": "5"}), "`tolerance` must be a number"),
(json!({"background": "colors"}), "`colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue"),
(json!({"background": "colors", "colors": []}), "`colors` must list"),
(json!({"background": "colors", "colors": "#12"}), "`colors` must list"),
(json!({"background": "colors", "colors": "#ffffff80"}), "`colors` must list"),
(json!({"colors": ["#ffffff", 7]}), "`colors` must list"),
(json!({"background": "colors", "colors": vec!["#000"; 17]}), "`colors` must list"),
(json!({"background": "colors", "colors": "#000 ".repeat(100_000)}), "`colors` must list"),
(json!({"ids": [id.0, rect]}), &not_image),
(json!({"ids": [rect]}), "select an image"),
];
for (p, msg) in cases {
let e = s.execute(C, &p).unwrap_err().to_string();
assert!(e.contains(msg), "{p}: {e}");
}
assert_eq!((image_of(&s, id), undo_len(&s)), before);
}
#[test]
fn an_image_too_large_to_change_is_refused_before_it_is_decoded() {
let run = |w: u32, h: u32| {
let (mut s, _) = open(&crate::tests_linkspanel::png_header(w, h));
s.execute(C, &json!({})).unwrap_err().to_string()
};
// As gray samples, RGBA worked on and kept for the PNG, and the work: 19 bytes a pixel.
let over = run(10_632, 10_631);
assert!(over.contains("an image of 10632 × 10631 pixels is too large to change"), "{over}");
// Within the allowance it is decoded, and its missing rows can't be read.
let within = run(10_631, 10_631);
assert!(within.contains("the image's pixels can't be read"), "{within}");
}
+3
View File
@@ -131,6 +131,8 @@ fn insert_custom(s: &mut Session, label: &str, live: Option<LiveShape>, cs: Cust
&& let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id))
{
cs.write_to_node(n);
// A shape drawn pixel-aligned (Align New Objects to Pixel Grid) snaps its stored outline.
super::super::object::snap_if_aligned(n);
}
Ok(val)
}
@@ -270,6 +272,7 @@ fn box3d(s: &mut Session, p: &Value) -> Result<Value> {
&& let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id))
{
cs.write_to_node(n);
super::super::object::snap_if_aligned(n);
}
Ok(val)
}
+101 -19
View File
@@ -19,12 +19,12 @@
//! shape that a Convert to Shape or Outline Object effect on them gives them, below or above the
//! image as its Contents row says; new ones go right below that row.
use std::sync::Arc;
use std::{collections::HashMap, sync::Arc};
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::appearance::SharedStack;
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer};
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer};
use vectorcraft_geom::Rect;
use super::edit::{outermost, roots_of, selected_roots};
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eyedropper",
[],
None,
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}",
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}",
has_doc,
copy_from
),
@@ -1198,7 +1198,7 @@ fn target_contents(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
/// Sample enabled attributes, refusing object transparency that a text range cannot store.
/// Sample enabled attributes with transform-aware character dimensions and atomic validation.
fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "appearance.copyFrom";
let clicked = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?;
@@ -1270,9 +1270,6 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?,
};
let picked = Picked::of(&node);
if !reverse && !defaults_only {
s.eyedropper_sample = Some(node);
}
// The highlighted characters' type objects and ranges: after Select All in threaded text, all
// the text of every frame of the story, except a frame the attributes come from, in place of
// the object selection.
@@ -1285,6 +1282,15 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
Some((id, start, end)) if targets.contains(&id) => vec![(id, Some((start, end)))],
_ => vec![],
};
let target_ids = || targets.iter().copied().filter(|_| ranges.is_empty()).chain(ranges.iter().map(|(id, _)| *id));
// Prepare every dimensional copy before changing defaults or the remembered sample. A bad
// source or target transform must refuse the entire pick, including a multi-frame range.
let characters = if attrs.character && !append {
let d = &s.doc()?.doc;
copied_character_styles(&node, target_ids().filter_map(|id| d.node(id)))?
} else {
HashMap::new()
};
// Character styles cannot represent object transparency. Refuse before even changing
// paint defaults; applying it to the object would also alter the unselected characters.
if attrs.appearance.transparency {
@@ -1298,11 +1304,33 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
if !reverse {
picked.to_defaults(s, &attrs.appearance);
}
// The session's bounds check follows the selection. Check text targets reached through
// explicit IDs, a reverse pick, or a highlighted story as well. Paragraph changes can
// move point text even when character copying is disabled.
let text_ids: Vec<_> = if attrs.paragraph && !append && picked.text.is_some() {
let d = &s.doc()?.doc;
target_ids().filter(|id| d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))).collect()
} else {
characters.keys().copied().collect()
};
let check_text_bounds = |d: &Document| {
if !text_ids.is_empty() && !crate::sanity::objects_in_range(d, &text_ids) {
return Err(bad(C, "sampled text would exceed the canvas (coordinates out of range)"));
}
Ok(())
};
// Remember the pick only after the document edit has passed its own validation.
let finish = |s: &mut Session, ids: &[NodeId]| {
if !reverse {
if !defaults_only {
s.eyedropper_sample = Some(node);
}
picked.to_defaults(s, &attrs.appearance);
}
json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })
};
if (targets.is_empty() && ranges.is_empty()) || attrs.is_empty() {
return Ok(json!({ "ids": [] }));
return Ok(finish(s, &[]));
}
if !ranges.is_empty() {
let ids: Vec<NodeId> = ranges.iter().map(|(f, _)| *f).collect();
@@ -1312,24 +1340,26 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
let (start, end) = range.unwrap_or((0, vectorcraft_text::edit::runs_len(&t.runs)));
let placed = picked.placed(Some(t.local_bounds()));
vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| picked.run(st, &placed, &attrs));
vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| Picked::run(st, &placed, &attrs, characters.get(&id)));
if let Some((_, para)) = picked.text.as_ref().filter(|_| attrs.paragraph) {
t.edit_paras(Some(t.paragraphs_in(start, end)), |p| *p = para.clone());
}
super::typecmd::refresh_bounds(t);
}
check_text_bounds(d)?;
Ok(count_changed(d, &before, &ids))
})?;
return Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }));
return Ok(finish(s, &ids));
}
// When every target comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
super::overprint::edit_counted(s, "Eyedropper", |d| {
for id in &targets {
if let Some(n) = d.node_mut(*id) {
picked.apply(n, &attrs, append);
picked.apply(n, &attrs, append, characters.get(id));
}
}
check_text_bounds(d)?;
// The paints the pick wrote, with a weight going with the paint of its stroke, as in `set_item`. `append` adds
// only the colors of the visible rows the source has.
let (fill, stroke) = (attrs.appearance.fill, attrs.appearance.stroke);
@@ -1369,7 +1399,59 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
let object = super::graph::capture_series_object_opacity(d, &objects);
Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object))
})?;
Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::<Vec<_>>() }))
Ok(finish(s, &targets))
}
/// Read source typography in document space, then compensate for each target's transform.
/// Paint stays in its existing sampling path; character scale never changes object placement.
fn copied_character_styles<'a>(source: &Node, targets: impl Iterator<Item = &'a Node>) -> Result<HashMap<NodeId, CharStyle>> {
const C: &str = "appearance.copyFrom";
let mut styles = HashMap::new();
let NodeKind::Text(source) = &source.kind else { return Ok(styles) };
let Some(run) = source.runs.first() else { return Ok(styles) };
let mut targets = targets
.filter_map(|n| match &n.kind {
NodeKind::Text(t) => Some((n.id, t)),
_ => None,
})
.peekable();
if targets.peek().is_none() {
return Ok(styles);
}
let effective = source.effective_char_style(&run.style).ok_or_else(|| bad(C, "source text transform is collapsed or unrepresentable"))?;
if !copied_dimensions_fit(&run.style, &effective) {
return Err(bad(C, "character dimensions cannot be represented with the source text transform"));
}
for (id, text) in targets {
let scale = text.style_scale().ok_or_else(|| bad(C, "target text transform is collapsed or unrepresentable"))?;
let mut local = effective.clone();
local.size /= scale.points;
local.leading = local.leading.map(|v| v / scale.points);
local.baseline_shift /= scale.points;
local.tcy_up_down /= scale.points;
local.tcy_left_right /= scale.points;
local.h_scale /= scale.horizontal;
// As with dimensional type commands, reject overflow and underflow before layout.
if !copied_dimensions_fit(&effective, &local) {
return Err(bad(C, "character dimensions cannot be represented with the target text transform"));
}
styles.insert(id, local);
}
Ok(styles)
}
/// Bound each converted type dimension and refuse loss to zero before layout reads it.
fn copied_dimensions_fit(from: &CharStyle, to: &CharStyle) -> bool {
[
(from.size, to.size),
(from.leading.unwrap_or(0.0), to.leading.unwrap_or(0.0)),
(from.baseline_shift, to.baseline_shift),
(from.tcy_up_down, to.tcy_up_down),
(from.tcy_left_right, to.tcy_left_right),
(from.h_scale, to.h_scale),
]
.iter()
.all(|(from, to)| to.is_finite() && to.abs() <= crate::MAX_COORD && (*from == 0.0 || *to != 0.0))
}
/// What the Eyedropper picks up from an object.
@@ -1422,8 +1504,8 @@ impl Picked {
/// Copy character attributes and the enabled paint attributes through the same path for
/// whole text objects and highlighted character ranges.
fn run(&self, st: &mut CharStyle, placed: &Appearance, a: &EyedropperAttrs) {
if let Some((cs, _)) = self.text.as_ref().filter(|_| a.character) {
fn run(st: &mut CharStyle, placed: &Appearance, a: &EyedropperAttrs, character: Option<&CharStyle>) {
if let Some(cs) = character {
*st = CharStyle {
fill: std::mem::take(&mut st.fill),
stroke: std::mem::take(&mut st.stroke),
@@ -1439,7 +1521,7 @@ impl Picked {
/// Apply attributes `a` to `n`. `append` adds the fills and strokes (and effects) on top of its
/// stack instead. Type takes the paints on its characters, and character and paragraph
/// attributes from type.
fn apply(&self, n: &mut Node, a: &EyedropperAttrs, append: bool) {
fn apply(&self, n: &mut Node, a: &EyedropperAttrs, append: bool, character: Option<&CharStyle>) {
let ap = &a.appearance;
if ap.transparency {
n.opacity = self.opacity;
@@ -1456,7 +1538,7 @@ impl Picked {
let placed = self.placed(Some(t.local_bounds()));
let text = self.text.as_ref();
for r in &mut t.runs {
self.run(&mut r.style, &placed, a);
Self::run(&mut r.style, &placed, a, character);
}
if let Some((_, para)) = text.filter(|_| a.paragraph) {
// The source's first paragraph's attributes, on every paragraph.
+5 -1
View File
@@ -162,7 +162,8 @@ fn constrained_turn(s: &Session, rotation: f64) -> f64 {
}
}
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`.
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. A new path or
/// compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is on.
fn insert_look_turned(
s: &mut Session,
label: &str,
@@ -180,6 +181,7 @@ fn insert_look_turned(
let id = d.alloc_id();
let mut n = Node::new(id, kind);
look.apply(d, &mut n);
super::object::align_new_object(d, &mut n);
n.name = name;
n.bbox_angle = bbox_angle;
let mut into = None;
@@ -512,6 +514,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
n.name = Some(name.into());
n.blend = BlendMode::Screen;
n.opacity = op;
super::object::align_new_object(d, &mut n);
std::sync::Arc::new(n)
})
.collect();
@@ -603,6 +606,7 @@ fn grid_group(s: &mut Session, label: &str, (paths, bbox_angle): (Vec<PathData>,
Node::path(d.alloc_id(), pd, Appearance::default())
};
look.apply(d, &mut n);
super::object::align_new_object(d, &mut n);
n.bbox_angle = bbox_angle;
std::sync::Arc::new(n)
})
+3 -1
View File
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Setup",
[],
None,
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), alignNewObjectsToPixelGrid?: bool (Align New Objects to Pixel Grid: paths and compound paths drawn from then on are pixel-aligned, as object.setPixelAligned; art already in the document, pasted, duplicated or placed keeps its own setting), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
has_doc,
setup
)]
@@ -46,6 +46,7 @@ pub(crate) fn setup_json(d: &Document) -> Value {
"smallCapsSize": s.small_caps_size,
"exportText": s.export_text.id(),
"backgroundContents": s.background.id(),
"alignNewObjectsToPixelGrid": s.align_new_objects_to_pixel_grid,
})
}
@@ -140,6 +141,7 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value
"smallCapsSize" => s.small_caps_size = percent(k, v, 1.0, vectorcraft_doc::setup::MAX_SMALL_CAPS)?,
"exportText" => s.export_text = v.as_str().and_then(ExportText::parse).ok_or_else(|| bad(C, "exportText must be editable or appearance"))?,
"backgroundContents" => s.background = background_param(v, C)?,
"alignNewObjectsToPixelGrid" => s.align_new_objects_to_pixel_grid = flag(k, v)?,
// Read-only values `document.setup` reports.
"gridColorsName" | "warnings" => {}
_ => return Err(bad(C, format!("unknown setting `{k}`"))),
+7 -3
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New…",
["File"],
None,
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792, units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode}; the size is remembered in file.newPresets' Recent",
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792, units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode}; the size is remembered in file.newPresets' Recent",
always,
super::newdoc::file_new
),
@@ -673,10 +673,14 @@ fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> {
/// the step before. As any new edit it ends the steps to redo, so Redo never swaps the document
/// under an interaction that would then preview on, or cancel to, the document from before (#1719).
/// A typing session also ends in the Type tool, whose caret and marked text (IME) must follow the
/// document.
/// document. A preview that Real-time Drawing off left unapplied is applied first, as the tool's own
/// commit applies it; when it fails, the interaction is canceled.
pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> {
let typing = typing_in_progress(s);
s.commit_interaction()?;
match s.unapplied_interaction_preview().filter(|_| !s.previewing) {
Some((cmd, p)) if s.preview(&cmd, &p).is_err() => s.cancel_interaction()?,
_ => s.commit_interaction()?,
}
if typing {
s.set_tool_option("endTyping", &Value::Bool(true));
}
+75 -6
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand…",
["Object"],
None,
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
has_selection,
expand
),
@@ -1283,9 +1283,12 @@ fn breaks(g: &Gradient, t0: f64, t1: f64, max_gap: f64) -> Vec<(f64, (Color, f32
/// cover the box (linear: along the vector `t0..t1` and across it `s0..s1` in points; radial:
/// `0..t1`, each level's ellipse centred on the way from the focal point to the start).
/// A conic gradient also has its placement, the box and the radius in its frame that reaches
/// past the box's corners ([`Frame::pieces`] and [`Frame::mesh`] go around its center).
/// past the box's corners ([`Frame::pieces`] and [`Frame::mesh`] go around its center). A
/// diamond gradient has its frame ([`vectorcraft_color::GradientGeom::diamond_frame`]; `None`
/// when it has no extent), the box and the level of the square that reaches its corners.
struct Frame {
conic: Option<(vectorcraft_color::GradientGeom, Rect, f64)>,
diamond: Option<(Option<Affine>, Rect, f64)>,
radial: bool,
start: Point,
focal: Point,
@@ -1323,7 +1326,11 @@ impl Frame {
let reach = if reach.is_finite() { reach * 1.01 / (std::f64::consts::PI * CONIC_MESH_GAP).cos() } else { 1.0 };
(geom, bounds, reach)
});
Self { conic, radial, start: geom.start, focal: geom.focal_point(), along, across, t0, t1, s0, s1 }
let diamond = (g.gradient.kind == GradientKind::Diamond).then(|| {
let reach = corners.iter().map(|c| geom.param_at(GradientKind::Diamond, *c)).fold(0.0f64, f64::max);
(geom.diamond_frame(), bounds, if reach.is_finite() { reach.max(1e-6) * 1.01 } else { 1.0 })
});
Self { conic, diamond, radial, start: geom.start, focal: geom.focal_point(), along, across, t0, t1, s0, s1 }
}
/// Linear: the point at parameter `t` along and `s` across. Radial: the point at parameter `t`
@@ -1351,6 +1358,34 @@ impl Frame {
};
return GradientMesh::from_grid(&us, &[0.0, 1.0], &at, &|_, c, _| br[c].1);
}
if let Some((frame, b, reach)) = &self.diamond {
let Some(frame) = frame else {
// No extent: the whole box is the last stop.
let last = g.sample_keep_model(1.0);
let at = |u: f64, v: f64| Point::new(b.x0 + u * b.width(), b.y0 + v * b.height());
return GradientMesh::from_grid(&[0.0, 1.0], &[0.0, 1.0], &at, &|_, _, _| last);
};
// Rings of squares where the color changes, with columns at the corners: each patch
// lies between two rings along one side, where the level runs straight across it.
let br = breaks(g, 0.0, *reach, f64::INFINITY);
let ts: Vec<f64> = br.iter().map(|(t, _)| t / reach).collect();
let at = |u: f64, v: f64| *frame * (diamond_perimeter(u).to_vec2() * (v * reach)).to_point();
const CORNERS: [f64; 5] = [0.0, 0.25, 0.5, 0.75, 1.0];
let mut mesh = GradientMesh::from_grid(&CORNERS, &ts, &at, &|r, _, _| br[r].1);
// Every column is at a corner, where `from_grid`'s tangent is the mean of the two
// sides: each handle along a ring points a third of the way along its own side, so
// the sides stay straight.
let side = |v: f64, from: usize, to: Option<&f64>| to.map_or(vectorcraft_geom::Vec2::ZERO, |&u| (at(u, v) - at(CORNERS[from], v)) / 3.0);
for (r, &v) in ts.iter().enumerate() {
for c in 0..CORNERS.len() {
if let Some(point) = mesh.points.get_mut(r * CORNERS.len() + c) {
point.handles[0] = side(v, c, CORNERS.get(c + 1));
point.handles[1] = side(v, c, c.checked_sub(1).and_then(|i| CORNERS.get(i)));
}
}
}
return mesh;
}
// Rings as close as the columns around them, so the mesh draws smoothly.
let gap = if self.radial { (self.t1 - self.t0) / RADIAL_MESH_COLS as f64 } else { f64::INFINITY };
let br = breaks(g, self.t0, self.t1, gap);
@@ -1367,9 +1402,9 @@ impl Frame {
/// `n` solid shapes covering the box in paint order, each coloured as the gradient in the
/// middle of its band: for a linear gradient, rectangles from each band's start to the far
/// end, for a radial one, nested ellipses (largest first), for a conic one, wedges around the
/// center from each band's start to the seam. Each paints over the ones below except its
/// band, so no seam shows between bands. With translucent stops each shape is just its band,
/// so nothing doubles up.
/// center from each band's start to the seam, for a diamond one, nested squares (largest
/// first). Each paints over the ones below except its band, so no seam shows between bands.
/// With translucent stops each shape is just its band, so nothing doubles up.
fn pieces(&self, g: &Gradient, n: usize) -> Vec<(PathData, (Color, f32))> {
let opaque = g.stops.iter().all(|s| s.opacity >= 1.0);
if let Some((geom, b, _)) = &self.conic {
@@ -1379,6 +1414,29 @@ impl Frame {
.map(|(pts, t)| (PathData::single(SubPath::polyline(&pts, true)), g.sample_keep_model(t as f32)))
.collect();
}
if let Some((frame, b, reach)) = &self.diamond {
let Some(frame) = frame else {
return vec![(shapes::rectangle(*b), g.sample_keep_model(1.0))];
};
// Nested squares about the center, largest first, as a radial gradient's ellipses.
let step = reach / n as f64;
let square = |t: f64| -> SubPath {
let pts: Vec<Point> = [0.0, 0.25, 0.5, 0.75].iter().map(|&u| *frame * (diamond_perimeter(u).to_vec2() * t).to_point()).collect();
SubPath::polyline(&pts, true)
};
return (0..n)
.rev()
.map(|k| {
let mut shape = PathData::single(square((k + 1) as f64 * step));
if !opaque && k > 0 {
let mut hole = square(k as f64 * step);
hole.reverse();
shape.subpaths.push(hole);
}
(shape, g.sample_keep_model(((k as f64 + 0.5) * step) as f32))
})
.collect();
}
let step = (self.t1 - self.t0) / n as f64;
let color = |k: usize| g.sample_keep_model((self.t0 + (k as f64 + 0.5) * step) as f32);
if self.radial {
@@ -1410,3 +1468,14 @@ impl Frame {
.collect()
}
}
/// The point a fraction `u` (0..1) of the way around the square with corners (1, 0), (0, 1),
/// (-1, 0) and (0, -1), from the first: a diamond gradient's last stop in its frame.
fn diamond_perimeter(u: f64) -> Point {
const CORNERS: [(f64, f64); 5] = [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0), (1.0, 0.0)];
let s = if u.is_finite() { u.clamp(0.0, 1.0) * 4.0 } else { 0.0 };
let i = (s.floor() as usize).min(3);
let f = s - i as f64;
let ((x0, y0), (x1, y1)) = (CORNERS.get(i).copied().unwrap_or((1.0, 0.0)), CORNERS.get(i + 1).copied().unwrap_or((1.0, 0.0)));
Point::new(x0 + (x1 - x0) * f, y0 + (y1 - y0) * f)
}
+3 -1
View File
@@ -2,7 +2,7 @@
//! save, export and serialize by path or bytes (base64), the format table, `command.batch` and
//! `action.batch` (the Actions panel menu's Batch…).
//!
//! - `load`: `document.open` (native, legacy, SVG/SVGZ, PDF/.ai/.ait, DXF, raster images).
//! - `load`: `document.open` (native, legacy, SVG/SVGZ, PDF/.ai/.ait, DXF, HP-GL, raster images).
//! - `action_batch`: play an action on every file in a folder or every data set.
//! - `encode`: one encoder per writable format, with typed options parsed from the params.
//! - `svg`: the SVG Options (styling, fonts, images, object ids, artboards…).
@@ -205,6 +205,8 @@ mod tests_eps;
#[cfg(test)]
mod tests_dxfimport;
#[cfg(test)]
mod tests_hpgl;
#[cfg(test)]
mod tests_metafile;
#[cfg(test)]
+62 -12
View File
@@ -11,7 +11,7 @@ use serde_json::json;
use super::super::{Result, Session, bad};
#[cfg(not(target_arch = "wasm32"))]
use super::super::{bool_or, find_command, str_param};
use super::super::{check_switches, find_command, switch_or, text_param};
#[cfg(target_arch = "wasm32")]
pub(super) fn action_batch(_: &mut Session, _: &Value) -> Result<Value> {
@@ -68,12 +68,24 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> {
));
}
}
let source = str_param(p, "source").unwrap_or("folder");
let destination = str_param(p, "destination").unwrap_or("none");
// Every option is checked before the destination folder is made.
let source = text_param(p, "source", C)?.unwrap_or("folder");
if !matches!(source, "folder" | "datasets") {
return Err(bad(C, "`source` must be `folder` or `datasets`"));
}
let destination = text_param(p, "destination", C)?.unwrap_or("none");
if !matches!(destination, "none" | "saveAndClose" | "folder") {
return Err(bad(C, "`destination` must be `none`, `saveAndClose` or `folder`"));
}
let dest_folder = str_param(p, "destinationFolder").map(absolute_path);
let dest_folder = text_param(p, "destinationFolder", C)?.map(absolute_path);
text_param(p, "folder", C)?;
let label = text_param(p, "label", C)?.unwrap_or("Batch").to_string();
let dataset_file_naming = text_param(p, "datasetFileNaming", C)?.unwrap_or("fileDataSetName");
let override_open = switch_or(p, "overrideOpen", true, C)?;
let stop_on_error = switch_or(p, "stopOnError", true, C)?;
let override_save = switch_or(p, "overrideSave", true, C)?;
let override_export = switch_or(p, "overrideExport", true, C)?;
check_switches(p, &["includeSubdirs"], C)?;
if destination == "folder" {
let Some(ref folder) = dest_folder else {
return Err(bad(C, "`destinationFolder` is required when destination is `folder`"));
@@ -81,17 +93,15 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> {
may_write(folder)?;
std::fs::create_dir_all(folder).map_err(|e| bad(C, format!("{folder}: {e}")))?;
}
let label = str_param(p, "label").unwrap_or("Batch").to_string();
let override_open = bool_or(p, "overrideOpen", true);
let run = Run {
label: &label,
steps: cmds,
stop_on_error: bool_or(p, "stopOnError", true),
override_save: bool_or(p, "overrideSave", true),
override_export: bool_or(p, "overrideExport", true),
stop_on_error,
override_save,
override_export,
destination,
dest_folder: dest_folder.as_deref(),
dataset_file_naming: p.get("datasetFileNaming").map_or("fileDataSetName", |v| v.as_str().unwrap_or("")),
dataset_file_naming,
};
match source {
"folder" => batch_folder(s, C, p, override_open, &run),
@@ -186,9 +196,9 @@ fn retargeting_save(c: &Value, redirected: bool) -> bool {
fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: &Run<'_>) -> Result<Value> {
use super::{absolute_path, may_read};
let folder = str_param(p, "folder").map(absolute_path).ok_or_else(|| bad(cmd, "missing `folder`"))?;
let folder = text_param(p, "folder", cmd)?.map(absolute_path).ok_or_else(|| bad(cmd, "missing `folder`"))?;
may_read(&folder)?;
let include_subdirs = bool_or(p, "includeSubdirs", false);
let include_subdirs = switch_or(p, "includeSubdirs", false, cmd)?;
let files = collect_files(&folder, include_subdirs, 0)?;
if files.len() > MAX_BATCH_FILES {
return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} files")));
@@ -810,6 +820,46 @@ mod tests {
assert!(dest.join("b.svg").is_file(), "b.svg written");
}
#[test]
fn batch_refuses_options_of_the_wrong_type_before_it_writes() {
let src = tmp("types-src");
let dest = tmp("types-dest");
write_svg(&src, "a.svg", "#f00");
let mut s = Session::new();
let cases = [
("stopOnError", json!("false"), "`stopOnError` must be true or false"),
("overrideOpen", json!(0), "`overrideOpen` must be true or false"),
("overrideSave", json!("true"), "`overrideSave` must be true or false"),
("overrideExport", json!([]), "`overrideExport` must be true or false"),
("includeSubdirs", json!(1), "`includeSubdirs` must be true or false"),
("source", json!(1), "`source` must be a string"),
("source", json!("files"), "`source` must be `folder` or `datasets`"),
("destination", json!(true), "`destination` must be a string"),
("folder", json!(5), "`folder` must be a string"),
("label", json!(5), "`label` must be a string"),
("datasetFileNaming", json!(3), "`datasetFileNaming` must be a string"),
];
for (key, value, message) in cases {
let out = dest.join(key);
let mut p = json!({
"folder": src.to_string_lossy(),
"destination": "folder",
"destinationFolder": out.to_string_lossy(),
"commands": [{"command": "object.unlockAll", "params": {}}],
});
p[key] = value;
let e = s.execute("action.batch", &p).unwrap_err().to_string();
assert!(e.contains(message), "{key}: {e}");
assert!(!out.exists(), "{key}: the destination folder was created");
}
let e = s
.execute("action.batch", &json!({"folder": src.to_string_lossy(), "destination": "folder", "destinationFolder": 7, "commands": [{"command": "object.unlockAll"}]}))
.unwrap_err()
.to_string();
assert!(e.contains("`destinationFolder` must be a string"), "{e}");
assert!(s.active().is_none(), "no file was opened");
}
#[cfg(unix)]
#[test]
fn batch_folder_keeps_backslash_in_source_file_name() {
+2 -2
View File
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts Line truncated
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content o Line truncated
always,
load::open
),
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch…",
[],
None,
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
always,
action_batch::action_batch
),
+12 -1
View File
@@ -479,6 +479,8 @@ pub const FORMATS: &[Format] = &[
},
Format { id: "emf", label: "EMF", extensions: &["emf"], mime: "image/emf", read: true, write: true, raster: false, options: metafile::OPTIONS },
Format { id: "wmf", label: "WMF", extensions: &["wmf"], mime: "image/wmf", read: true, write: true, raster: false, options: metafile::OPTIONS },
// HP-GL/2 plot files, read by `vectorcraft_cad::hpgl` into paths; exports don't write them.
reader("hpgl", "HP-GL", &["plt", "hpgl", "hgl", "hpg"], "application/vnd.hp-hpgl", false),
Format {
id: "tga",
label: "Targa",
@@ -552,6 +554,10 @@ pub const OPEN_EXTS: &[&str] = &[
"dxf",
"emf",
"wmf",
"plt",
"hpgl",
"hgl",
"hpg",
"eps",
"epsf",
"ps",
@@ -565,9 +571,10 @@ pub const OPEN_EXTS: &[&str] = &[
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF or JPEG XL type, nor one for the `.pns`, `.dib` and `.rle` names of
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
/// The packaging declares no type for HP-GL plot files 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",
"heic", "heif", "jxl", "plt", "hpgl", "hgl", "hpg",
];
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
@@ -641,6 +648,10 @@ pub const PLACE_EXTS: &[&str] = &[
"dxf",
"emf",
"wmf",
"plt",
"hpgl",
"hgl",
"hpg",
"eps",
"epsf",
"ps",
+15
View File
@@ -134,6 +134,17 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
if clipboard::looks_like_svg(&String::from_utf8_lossy(&bytes[..bytes.len().min(4096)])) {
return format("svg");
}
// HP-GL has no signature: a file that starts with plotter instructions, named as one or with an
// extension no other format (text, the formats VectorCraft names as unsupported, and the files
// File › Open takes in other ways included) reads.
let ext = super::extension(name);
let other = by_name.is_some_and(|f| f.id != "hpgl")
|| super::TEXT_EXTS.contains(&ext.as_str())
|| super::unsupported(&ext).is_some()
|| super::opens_as_other(&ext);
if !other && vectorcraft_cad::hpgl::is_hpgl(bytes) {
return format("hpgl");
}
by_name
}
@@ -487,6 +498,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
let (doc, warnings) = super::metafile::import(bytes)?;
(doc, warnings, false)
}
"hpgl" => {
let i = vectorcraft_cad::hpgl::import(bytes).map_err(err)?;
(i.document, i.warnings, false)
}
"affinity" => {
let i = super::affinity::import(&title, bytes)?;
preview_only = i.preview_only;
+3 -3
View File
@@ -42,7 +42,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
name: "compatibility",
ty: "string",
default: "\"1.7\"",
description: "PDF version: 1.3 (transparency flattened) | 1.4 | 1.5 | 1.6 | 1.7 | 2.0",
description: "PDF version: 1.3 (transparency flattened) | 1.4 | 1.5 | 1.6 | 1.7 | 2.0 (a pdfA2b file at 1.4 with a page longer than 14,400 pt is written as 1.6, with a UserUnit as at 1.6, and a warning; see document.exportPdf)",
},
FormatOption {
name: "preserveEditing",
@@ -99,7 +99,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
name: "longPagesInPoints",
ty: "boolean",
default: "false",
description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files from 1.5 on keep the UserUnit)",
description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files keep the UserUnit)",
},
FormatOption {
name: "createLayers",
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption; PDF/X files, 1.3 and 1.4 write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files from 1.5 on keep the UserUnit); apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIn Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), out Line truncated
has_doc,
export_pdf
),
+104
View File
@@ -0,0 +1,104 @@
//! HP-GL plotter files through the commands: `document.open` by extension or by content, File ›
//! Place as one group of paths, the dialogs' filters and the format list, and files that aren't
//! HP-GL refused with a message.
use serde_json::json;
use vectorcraft_doc::NodeKind;
use super::*;
fn b64(bytes: &[u8]) -> String {
vectorcraft_format::base64_encode(bytes)
}
/// An inch-wide red square and a black diagonal, with the thinnest pen.
const PLOT: &[u8] = b"IN;SP2;PW0;PA0,0;PD1016,0,1016,1016,0,1016,0,0;PU;SP1;PD1016,1016;PU;";
#[test]
fn document_open_reads_a_plot_file() {
let mut s = Session::new();
let r = s.execute("document.open", &json!({"name": "part.plt", "dataBase64": b64(PLOT)})).unwrap();
assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("hpgl"), Some("part.plt")), "{r}");
let st = s.doc().unwrap();
let board = st.doc.artboards[0].rect;
assert!((board.width() - 72.25).abs() < 1e-9 && (board.height() - 72.25).abs() < 1e-9, "{board:?}");
let mut paths = vec![];
st.doc.walk(|n| {
if let NodeKind::Path { .. } = n.kind {
paths.push(n.clone());
}
});
assert_eq!(paths.len(), 2);
// Opened as artwork: Save asks for a name.
assert!(st.path.is_none());
// A plot file opens by its content in any of its names, and under a name no format reads.
for name in ["drawing.prn", "PART.HPGL", "part.hgl", "part.hpg"] {
let r = Session::new().execute("document.open", &json!({"name": name, "dataBase64": b64(PLOT)})).unwrap();
assert_eq!(r["format"].as_str(), Some("hpgl"), "{name}: {r}");
}
}
#[test]
fn file_place_places_a_plot_file_as_one_group() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
let p = json!({"name": "part.plt", "dataBase64": b64(PLOT), "thumbnail": 16});
let info = s.execute("file.place.info", &p).unwrap();
assert_eq!(info["format"], "hpgl", "{info}");
assert!((info["width"].as_f64().unwrap() - 72.25).abs() < 1e-9, "{info}");
let r = s.execute("file.place", &p).unwrap();
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("hpgl"), Some(1)), "{r}");
let doc = &s.doc().unwrap().doc;
let group = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
let NodeKind::Group { children, clip, .. } = &group.kind else { panic!("a group, got {:?}", group.kind) };
assert_eq!((children.len(), *clip), (2, false), "the art's bounds, not clipped");
}
#[test]
fn files_that_are_not_hpgl_are_refused() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
let before = s.doc().unwrap().doc.artboards[0].rect.size();
let script = b"set terminal png\nplot sin(x)\n";
let e = s.execute("document.open", &json!({"name": "graph.plt", "dataBase64": b64(script)})).expect_err("refused");
assert!(e.to_string().contains("not an HP-GL file"), "{e}");
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), before);
assert!(s.execute("file.place", &json!({"name": "graph.plt", "dataBase64": b64(script)})).is_err());
// Text that isn't a plot opens by its name, not as HP-GL.
assert!(detect("notes.txt", b"IN THE BEGINNING").is_none_or(|f| f.id != "hpgl"));
// Only a plot file's own names, and names no other format reads, are read by their content:
// text, other formats' files and the formats named as unsupported (a DWG drawing starts with
// `AC` and digits) aren't, even when they start like a plot.
for name in ["notes.txt", "notes.svg", "picture.tga", "drawing.dxf", "site.dwg", "old.pct"] {
for bytes in [&b"IN"[..], b"in 5;", b"AC1032\0\0", PLOT] {
assert!(detect(name, bytes).is_none_or(|f| f.id != "hpgl"), "{name}: {:?}", String::from_utf8_lossy(bytes));
}
}
let text = s.execute("file.place", &json!({"name": "notes.txt", "dataBase64": b64(b"IN 5; PA 10;")})).unwrap();
assert_eq!(text["format"], "txt", "{text}");
}
/// 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]
fn a_plot_file_by_its_name_may_start_with_any_instruction() {
let plot = b"SI0.2,0.3;SP1;PA0,0;PD1016,0;";
let r = Session::new().execute("document.open", &json!({"name": "part.plt", "dataBase64": b64(plot)})).unwrap();
assert_eq!(r["format"].as_str(), Some("hpgl"), "{r}");
assert!(detect("drawing.prn", plot).is_none_or(|f| f.id != "hpgl"));
}
#[test]
fn the_dialogs_and_the_format_list_name_hpgl() {
let exts = ["plt", "hpgl", "hgl", "hpg"];
for e in exts {
assert!(OPEN_EXTS.contains(&e) && PLACE_EXTS.contains(&e) && UNASSOCIATED_EXTS.contains(&e), "{e}");
assert_eq!(format_for_name(&format!("a.{e}")).map(|f| f.id), Some("hpgl"), "{e}");
}
let filter = ("HP-GL", &exts[..]);
assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter));
let r = Session::new().execute("document.formats", &json!({})).unwrap();
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "hpgl").unwrap().clone();
assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)));
}
+5 -2
View File
@@ -1,7 +1,10 @@
//! Object → Flatten Transparency: transparent art becomes opaque art that looks the same.
//!
//! The targets (`ids` or the selection) split into groups of overlapping objects. Groups without
//! transparency stay as they are (their type and strokes are outlined on request). The others are
//! The targets (`ids` or the selection) split into groups: each object with transparency with the
//! objects it overlaps, and the objects without transparency whose stacking order with a member
//! would change when the group takes its topmost object's place. Objects without transparency
//! that overlap only others without it stay as they are (their type and strokes are outlined on
//! request), as do groups without transparency. The others are
//! cut into atomic regions: the faces of the planar arrangement of every fill, outlined stroke and
//! clipping path in them ([`po::regions`]). The same paints cover each whole region, so its colour
//! is exact: those paints composited as the renderer composites them ([`Composer`], blend modes by
+346 -27
View File
@@ -99,17 +99,77 @@ pub(super) fn masked(n: &Node) -> bool {
n.extras().mask.as_ref().is_some_and(|m| !m.disabled)
}
/// Where `n` can paint: its visual bounds grown by its effects (and a margin for antialiasing).
pub(super) fn reach(n: &Node) -> Option<Rect> {
/// Where `n` paints: its visual bounds grown by its effects.
pub(super) fn painted(n: &Node) -> Option<Rect> {
if !n.visible {
return None;
}
let b = match n.children() {
Some(ch) if !n.clips() && !matches!(n.kind, NodeKind::Compound { .. }) => ch.iter().filter_map(|c| reach(c)).reduce(|a, b| a.union(b))?,
Some(ch) if !n.clips() && !matches!(n.kind, NodeKind::Compound { .. }) => ch.iter().filter_map(|c| painted(c)).reduce(|a, b| a.union(b))?,
_ => n.visual_bounds()?,
};
let fx = n.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(effects::outset(&n.appearance.effects, b), f64::max);
Some(b.inflate(fx + 1.0, fx + 1.0))
Some(b.inflate(fx, fx))
}
/// Where `n` can paint: where it paints ([`painted`]) and a margin of 1 pt for antialiasing,
/// once, however deep its groups nest.
pub(super) fn reach(n: &Node) -> Option<Rect> {
painted(n).map(|b| b.inflate(1.0, 1.0))
}
type Cancelled = vectorcraft_doc::cancel::Cancelled;
/// Whether `b` has finite coordinates and isn't inside out.
pub(super) fn finite(b: &Rect) -> bool {
[b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.x0 <= b.x1 && b.y0 <= b.y1
}
/// Whether boxes `a` and `b` overlap or touch.
fn touch(a: &Rect, b: &Rect) -> bool {
a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1
}
/// Indices joined into sets, each set knowing whether it holds an object with transparency.
struct Sets {
parent: Vec<usize>,
seeded: Vec<bool>,
}
impl Sets {
fn find(&mut self, mut i: usize) -> usize {
while self.parent[i] != i {
self.parent[i] = self.parent[self.parent[i]];
i = self.parent[i];
}
i
}
/// Joins the sets of `a` and `b`: → the set they are now, named by its lowest index.
fn join(&mut self, a: usize, b: usize) -> usize {
let (a, b) = (self.find(a), self.find(b));
let (lo, hi) = (a.min(b), a.max(b));
self.parent[hi] = lo;
self.seeded[lo] |= self.seeded[hi];
lo
}
/// The sets, each in index order, by their first index.
fn groups(&mut self) -> Vec<Vec<usize>> {
let mut groups: Vec<Vec<usize>> = vec![];
let mut slot: Vec<Option<usize>> = vec![None; self.parent.len()];
for i in 0..self.parent.len() {
let r = self.find(i);
match slot[r] {
Some(g) => groups[g].push(i),
None => {
slot[r] = Some(groups.len());
groups.push(vec![i]);
}
}
}
groups
}
}
/// Indices of `bounds` grouped by overlap (transitively), each group in index order. Boxes that
@@ -121,16 +181,15 @@ pub(super) fn reach(n: &Node) -> Option<Rect> {
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
/// its group, ending no further right, is closed early: whatever overlaps it overlaps that box.
/// Fails only when cancelled ([`vectorcraft_doc::cancel`]).
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, vectorcraft_doc::cancel::Cancelled> {
fn find(p: &mut [usize], mut i: usize) -> usize {
while p[i] != i {
p[i] = p[p[i]];
i = p[i];
}
i
}
let mut parent: Vec<usize> = (0..bounds.len()).collect();
let finite = |b: &Rect| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.x0 <= b.x1 && b.y0 <= b.y1;
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> {
Ok(sweep(bounds, None)?.groups())
}
/// [`overlapping`]'s sweep. With `see_through`, two boxes are joined only when one of them is
/// see-through, and an open box is closed early only inside a later see-through box.
fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, Cancelled> {
let mut sets = Sets { parent: (0..bounds.len()).collect(), seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect() };
let joins = |a: usize, b: usize| see_through.is_none_or(|s| s[a] || s[b]);
let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect();
let n = boxes.len();
// Each box's place in the tree: by top (then index).
@@ -190,29 +249,140 @@ pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, ve
stack.push((2 * node + 1, mid, hi));
stack.push((2 * node, lo, mid));
}
// Whatever overlaps a box inside this one overlaps this one, and joins it when this one is
// see-through.
let shadows = see_through.is_none_or(|s| s[boxes[k].0]);
for &o in &met {
let (a, c) = (find(&mut parent, boxes[k].0), find(&mut parent, boxes[o].0));
parent[a.max(c)] = a.min(c);
if joins(boxes[k].0, boxes[o].0) {
sets.join(boxes[k].0, boxes[o].0);
}
let ob = boxes[o].1;
if ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
if shadows && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
set(&mut low, leaf[o], f64::NEG_INFINITY);
}
}
set(&mut low, leaf[k], b.y1);
}
let mut groups: Vec<Vec<usize>> = vec![];
let mut slot: Vec<Option<usize>> = vec![None; bounds.len()];
for i in 0..bounds.len() {
let r = find(&mut parent, i);
match slot[r] {
Some(g) => groups[g].push(i),
None => {
slot[r] = Some(groups.len());
groups.push(vec![i]);
Ok(sets)
}
/// Boxes in blocks of nearby ones, each block with the box around it, to find the boxes a box
/// touches.
struct Blocks {
order: Vec<usize>,
boxes: Vec<Option<Rect>>,
around: Vec<Rect>,
}
impl Blocks {
const SIZE: usize = 32;
/// The finite boxes of `boxes`, in vertical strips by their centers and in blocks down each
/// strip.
fn new(boxes: &[Option<Rect>]) -> Self {
let boxes: Vec<Option<Rect>> = boxes.iter().map(|b| b.filter(finite)).collect();
let mut order: Vec<usize> = (0..boxes.len()).filter(|&i| boxes[i].is_some()).collect();
let center = |i: usize| boxes[i].map_or_else(Default::default, |b| b.center());
order.sort_by(|&a, &b| center(a).x.total_cmp(&center(b).x));
let strip = ((order.len() as f64 / Self::SIZE as f64).sqrt().ceil() as usize).max(1) * Self::SIZE;
for s in order.chunks_mut(strip) {
s.sort_by(|&a, &b| center(a).y.total_cmp(&center(b).y));
}
let around = order.chunks(Self::SIZE).filter_map(|c| c.iter().filter_map(|&i| boxes[i]).reduce(|a, b| a.union(b))).collect();
Self { order, boxes, around }
}
/// Puts the indices of the boxes that touch `q` in `out`. `work` counts the boxes looked at;
/// fails only when cancelled.
fn touching(&self, q: &Rect, out: &mut Vec<usize>, work: &mut usize) -> Result<(), Cancelled> {
out.clear();
for (b, around) in self.around.iter().enumerate() {
*work += 1;
if work.is_multiple_of(4096) {
vectorcraft_doc::cancel::check()?;
}
if !touch(around, q) {
continue;
}
for &i in &self.order[b * Self::SIZE..((b + 1) * Self::SIZE).min(self.order.len())] {
*work += 1;
if self.boxes[i].is_some_and(|r| touch(&r, q)) {
out.push(i);
}
}
}
Ok(())
}
Ok(groups)
}
/// Objects (in paint order) grouped for flattening, each group in paint order and the groups by
/// their first object; a group takes the place of its topmost object. `reach` is where each
/// object can paint ([`reach`]), `painted` where it paints ([`painted`]), and `see_through` whether
/// it has transparency. An object whose box is missing or not finite is a group of its own.
///
/// An object joins every see-through object its reach touches. An object without transparency
/// that touches only others without transparency stays a group of its own, unless a group would
/// change its stacking order with it: it joins (and groups join each other) where its reach
/// touches a member's and moving the members to their group's top would put the two the other way
/// round. With a `fringe` (how far a group's image can reach past
/// its art and cover what is under it), an object or group under a group's top whose painted box
/// that far around a member's touches joins it too. Fails only when cancelled
/// ([`vectorcraft_doc::cancel`]).
pub(super) fn flatten_groups(
reach: &[Option<Rect>],
painted: &[Option<Rect>],
see_through: &[bool],
fringe: f64,
) -> Result<Vec<Vec<usize>>, Cancelled> {
let n = reach.len();
let mut sets = sweep(reach, Some(see_through))?;
let mut members: Vec<Vec<usize>> = vec![vec![]; n];
for i in 0..n {
let r = sets.find(i);
members[r].push(i);
}
// The topmost object of each set (by its name).
let mut top: Vec<usize> = (0..n).map(|r| members[r].last().copied().unwrap_or(r)).collect();
let index = Blocks::new(reach);
// Each member of a set with transparency is looked at.
let mut work: Vec<usize> = vec![];
for i in 0..n {
let r = sets.find(i);
if sets.seeded[r] {
work.push(i);
}
}
let (mut near, mut looked) = (vec![], 0usize);
while let Some(i) = work.pop() {
let Some(q) = reach[i].filter(finite) else { continue };
// Painted boxes within the fringe have reaches within it too.
index.touching(&q.inflate(fringe, fringe), &mut near, &mut looked)?;
for &k in &near {
let (ri, rk) = (sets.find(i), sets.find(k));
if ri == rk {
continue;
}
let (ti, tk) = (top[ri], top[rk]);
let crossed = reach[k].is_some_and(|b| touch(&q, &b)) && (i < k) != (ti < tk);
let covered = fringe > 0.0 && tk < ti && painted[i].zip(painted[k]).is_some_and(|(a, b)| touch(&a.inflate(fringe, fringe), &b));
if !crossed && !covered {
continue;
}
// The members of a set whose top moves are looked at again, from there.
let t = ti.max(tk);
if ti != t {
work.extend_from_slice(&members[ri]);
}
if tk != t {
work.extend_from_slice(&members[rk]);
}
let r = sets.join(ri, rk);
let moved = std::mem::take(&mut members[if r == ri { rk } else { ri }]);
members[r].extend(moved);
top[r] = t;
}
}
Ok(sets.groups())
}
#[cfg(test)]
@@ -292,4 +462,153 @@ mod tests {
let odd = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(f64::NAN, 0.0, 10.0, 10.0)), Some(Rect::new(5.0, 5.0, 20.0, 20.0))];
assert_eq!(overlapping(&odd).unwrap(), vec![vec![0, 2], vec![1]]);
}
/// A filled rectangle, unstroked.
fn filled(id: u64, r: Rect) -> Node {
let look = vectorcraft_doc::Appearance::basic(
vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)),
vectorcraft_color::Paint::None,
0.0,
);
Node::path(vectorcraft_doc::NodeId(id), vectorcraft_geom::shapes::rectangle(r), look)
}
/// The antialiasing margin goes around the outermost group once, not once per group.
#[test]
fn reach_adds_its_margin_once_however_deep_the_groups() {
let r = Rect::new(10.0, 20.0, 30.0, 50.0);
let inner = Node::group(vectorcraft_doc::NodeId(2), vec![Arc::new(filled(1, r))]);
let outer = Node::group(vectorcraft_doc::NodeId(3), vec![Arc::new(inner)]);
assert_eq!(painted(&outer), Some(r));
assert_eq!(reach(&outer), Some(r.inflate(1.0, 1.0)));
assert_eq!(reach(&filled(1, r)), reach(&outer));
}
/// The group of each object, the topmost object of each group and whether it is see-through.
fn sets_of(groups: &[Vec<usize>], n: usize, see_through: &[bool]) -> (Vec<usize>, Vec<usize>, Vec<bool>) {
let mut of = vec![usize::MAX; n];
for (g, ids) in groups.iter().enumerate() {
for &i in ids {
of[i] = g;
}
}
let top = groups.iter().map(|g| *g.last().unwrap()).collect();
let seeded = groups.iter().map(|g| g.iter().any(|&i| see_through[i])).collect();
(of, top, seeded)
}
/// What [`flatten_groups`] must give: every object in one group, in paint order, the groups by
/// their first object; see-through objects with all that their reach touches; groups without
/// transparency of one object; no two objects that paint over each other the other way round
/// once each group takes its top's place; nothing within `fringe` of a member of a group under
/// that group's top.
fn check(reach: &[Option<Rect>], painted: &[Option<Rect>], see: &[bool], fringe: f64, groups: &[Vec<usize>], what: &str) {
let n = reach.len();
let mut all: Vec<usize> = groups.iter().flatten().copied().collect();
all.sort_unstable();
assert_eq!(all, (0..n).collect::<Vec<_>>(), "{what}: every object once");
assert!(groups.iter().all(|g| g.is_sorted()) && groups.windows(2).all(|w| w[0][0] < w[1][0]), "{what}: in order");
let (of, top, seeded) = sets_of(groups, n, see);
for (g, ids) in groups.iter().enumerate() {
assert!(seeded[g] || ids.len() == 1, "{what}: {ids:?} has no transparency");
}
for i in 0..n {
for j in 0..n {
if i == j || of[i] == of[j] {
continue;
}
let (gi, gj) = (of[i], of[j]);
if let (Some(a), Some(b)) = (reach[i], reach[j]) {
assert!(!(touch(&a, &b) && (see[i] || see[j])), "{what}: {i} and {j} touch, one see-through");
if seeded[gi] && touch(&a, &b) {
assert_eq!(i < j, top[gi] < top[gj], "{what}: {i} and {j} change places");
}
}
let (Some(a), Some(b)) = (painted[i], painted[j]) else { continue };
if seeded[gi] && fringe > 0.0 && touch(&a.inflate(fringe, fringe), &b) {
assert!(top[gj] > top[gi], "{what}: {j} under the image of {i}'s group");
}
}
}
}
/// Boxes of many sizes, some see-through, group as they must, with and without a fringe.
#[test]
fn flatten_groups_keep_stacking_order_and_leave_opaque_art_alone() {
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
let mut next = |m: f64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % 1000) as f64 / 1000.0 * m
};
for round in 0..60 {
let n = 4 + round;
let painted: Vec<Option<Rect>> = (0..n)
.map(|i| {
if i % 13 == 5 {
return None;
}
let (x, y) = (next(120.0).round(), next(120.0).round());
Some(Rect::new(x, y, x + next(25.0).round(), y + next(25.0).round()))
})
.collect();
let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect();
let see: Vec<bool> = (0..n).map(|_| next(1.0) < 0.15).collect();
for fringe in [0.0, 0.7] {
let groups = flatten_groups(&reach, &painted, &see, fringe).unwrap();
check(&reach, &painted, &see, fringe, &groups, &format!("round {round}, fringe {fringe}"));
}
}
}
/// A row of opaque boxes whose reaches touch, with see-through ones at its ends and far from
/// it: only the boxes next to a see-through one join it.
#[test]
fn an_opaque_row_stays_apart_from_the_see_through_boxes_at_its_ends() {
let n = 200;
// 10 pt boxes 1.5 pt apart: their 1 pt reaches overlap.
let painted: Vec<Option<Rect>> = (0..n).map(|i| Some(Rect::new(11.5 * i as f64, 0.0, 11.5 * i as f64 + 10.0, 10.0))).collect();
let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect();
let mut see = vec![false; n];
see[0] = true;
see[n - 1] = true;
let groups = flatten_groups(&reach, &painted, &see, 0.0).unwrap();
check(&reach, &painted, &see, 0.0, &groups, "row");
assert_eq!(groups[0], vec![0, 1]);
assert_eq!(groups.last(), Some(&vec![n - 2, n - 1]));
assert_eq!(groups.len(), n - 2);
// Without transparency every box is a group of its own.
assert_eq!(flatten_groups(&reach, &painted, &vec![false; n], 0.0).unwrap().len(), n);
}
/// An opaque box between a member and its group's top that paints over the member joins, and
/// so on along a chain; one under the member stays, but for one within the fringe.
#[test]
fn boxes_the_group_would_cross_join_it() {
// In paint order: D under A, A, B over A, C over B, then the see-through T over A.
let d = Rect::new(40.0, 80.0, 65.0, 120.0);
let a = Rect::new(60.0, 50.0, 105.0, 90.0);
let b = Rect::new(20.0, 20.0, 65.0, 55.0);
let c = Rect::new(0.0, 0.0, 25.0, 25.0);
let t = Rect::new(100.0, 50.0, 140.0, 90.0);
let painted = [Some(d), Some(a), Some(b), Some(c), Some(t)];
let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect();
let see = [false, false, false, false, true];
let groups = flatten_groups(&reach, &painted, &see, 0.0).unwrap();
assert_eq!(groups, vec![vec![0], vec![1, 2, 3, 4]]);
// C away from B: it stays.
let far = [Some(d), Some(a), Some(b), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(t)];
let reach_far: Vec<Option<Rect>> = far.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect();
assert_eq!(flatten_groups(&reach_far, &far, &see, 0.0).unwrap(), vec![vec![0], vec![1, 2, 4], vec![3]]);
// B 0.5 pt above A, not overlapping it: their antialiased edges can share pixels, so B joins.
let gap = [Some(d), Some(a), Some(Rect::new(20.0, 20.0, 65.0, 49.5)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(t)];
let reach_gap: Vec<Option<Rect>> = gap.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect();
assert_eq!(flatten_groups(&reach_gap, &gap, &see, 0.0).unwrap(), vec![vec![0], vec![1, 2, 4], vec![3]]);
// D a little left of A, under it: the fringe takes it in.
let near = [Some(Rect::new(40.0, 80.0, 59.8, 120.0)), Some(a), Some(b), Some(c), Some(t)];
let reach_near: Vec<Option<Rect>> = near.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect();
assert_eq!(flatten_groups(&reach_near, &near, &see, 0.0).unwrap()[0], vec![0]);
assert_eq!(flatten_groups(&reach_near, &near, &see, 0.24).unwrap(), vec![vec![0, 1, 2, 3, 4]]);
}
}
+89 -7
View File
@@ -1,4 +1,4 @@
use super::analysis::{Scratch, has_effects, masked, outlined_text, overlapping, reach};
use super::analysis::{Scratch, finite, flatten_groups, has_effects, masked, outlined_text, overlapping, painted, reach};
use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE};
use super::options::FlattenOptions;
use super::{
@@ -115,7 +115,7 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() };
// Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing).
vectorcraft_doc::cancel::check()?;
let mut queue = overlapping(&reaches)?;
let mut queue = groups(src, roots, &plain, &reaches, &see_through, o)?;
queue.reverse();
while let Some(g) = queue.pop() {
vectorcraft_doc::cancel::check()?;
@@ -196,6 +196,46 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
Ok(out)
}
/// `roots` of `src` (`plain`: as plain art; `reaches`: where each can paint, clipped) in the
/// groups that flatten together ([`flatten_groups`]), each in paint order, by their first object.
/// Objects that overlap (as [`overlapping`] groups them) stay in one group when one of them is
/// inside a clip group or clipping layer: [`inside_and_under`] and [`place_of`] then decide where
/// they go.
fn groups(
src: &Document,
roots: &[NodeId],
plain: &[Node],
reaches: &[Option<Rect>],
see_through: &[bool],
o: &FlattenOptions,
) -> Result<Vec<Vec<usize>>> {
// An image clipped to its regions, opaque over white, reaches a pixel past them; a group's
// image is no larger than the art it overlaps, so its pixels are no wider than this.
let opaque_edge = o.no_transparency.is_some() && o.clip_complex_regions && !o.preserve_alpha;
let ppi = o.line_art_ppi.min(o.gradient_ppi).max(1.0);
let extent = |ids: &mut dyn Iterator<Item = usize>| ids.filter_map(|i| reaches[i].filter(finite)).reduce(|a, b| a.union(b)).unwrap_or_default();
// Where the widest such pixel is wider than the margins of two reaches, objects that close
// overlap too.
let widest = if opaque_edge { 1.0 / raster_scale(extent(&mut (0..reaches.len())), ppi) } else { 0.0 };
let grow = ((widest - 2.0) / 2.0).max(0.0);
let near: Vec<Option<Rect>> = reaches.iter().map(|b| b.map(|b| b.inflate(grow, grow))).collect();
let mut out = vec![];
for g in overlapping(if grow > 0.0 { &near } else { reaches })? {
let clipped = || clips_count() && g.iter().any(|&i| !clip_ancestors(src, roots[i]).is_empty());
if g.len() < 2 || !g.iter().any(|&i| see_through[i]) || clipped() {
out.push(g);
continue;
}
let fringe = if opaque_edge { 1.0 / raster_scale(extent(&mut g.iter().copied()), ppi) } else { 0.0 };
let local = |v: &[Option<Rect>]| g.iter().map(|&i| v[i]).collect::<Vec<_>>();
let painted: Vec<Option<Rect>> = g.iter().map(|&i| painted(&plain[i])).collect();
let see: Vec<bool> = g.iter().map(|&i| see_through[i]).collect();
out.extend(flatten_groups(&local(reaches), &painted, &see, fringe)?.into_iter().map(|l| l.into_iter().map(|k| g[k]).collect::<Vec<_>>()));
}
out.sort_by_key(|g| g.first().copied());
Ok(out)
}
/// `plain` (object `id` of `src` as plain art) inside a clip group for each clip group and
/// clipping layer around `id`, innermost first, each clipped by that group's or layer's clipping
/// path. `plain` itself when nothing around it clips. With `fills` (clipping paths, and an area),
@@ -482,11 +522,7 @@ fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool
/// amounts (a CMYK TIFF), so its CMYK colours keep their numbers (#2160); other images are PNGs.
/// Fails when the image can't be encoded.
fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Option<PathData>, o: &FlattenOptions) -> Result<Raster> {
let mut scale = ppi / 72.0;
scale = scale.min((MAX_PIXELS / (rect.width() * rect.height()).max(1.0)).sqrt());
// No side longer than the renderer draws: the image grows by a pixel on each side and is
// rounded up to whole pixels below.
scale = scale.min((f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 4.0) / rect.width().max(rect.height()).max(1.0));
let scale = raster_scale(rect, ppi);
let px = 1.0 / scale;
let rect = rect.inflate(px, px);
let clip = clip.map(|c| Some(po::offset_path(&c, px, po::Join::Miter, 4.0)).filter(|g| !g.is_empty()).unwrap_or(c));
@@ -559,6 +595,14 @@ fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Optio
Ok(Raster { blob: ImageBlob::new("image/png", png), width: img.width, height: img.height, xf, clip })
}
/// Pixels per point of an image of `rect` at `ppi`: lower when the image would be larger than
/// [`MAX_PIXELS`], or have a side longer than the renderer draws (the image grows by a pixel on
/// each side and is rounded up to whole pixels).
fn raster_scale(rect: Rect, ppi: f64) -> f64 {
let scale = (ppi / 72.0).min((MAX_PIXELS / (rect.width() * rect.height()).max(1.0)).sqrt());
scale.min((f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 4.0) / rect.width().max(rect.height()).max(1.0))
}
/// `n` at full opacity with Normal blending throughout (objects, fills and strokes).
pub(super) fn opaque(n: &mut Node) {
n.opacity = 1.0;
@@ -877,4 +921,42 @@ mod tests {
assert_eq!(flat.parent_of(g), Some(layer));
assert_eq!(flat.children(Some(layer)).and_then(|c| c.last()).map(|c| c.id), Some(g));
}
/// In a file without transparency with Clip Complex Regions on, art under a group's opaque
/// image within one of its pixels joins the group, also where a long image is made at a lower
/// resolution and its pixels are wider than at the preset's.
#[test]
fn art_under_the_edge_of_a_long_opaque_image_joins_its_group() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 31000, "height": 100})).unwrap();
let rect = |s: &mut Session, x: f64, w: f64| {
let id = s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": w, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true, "ids": [id]})).unwrap();
NodeId(id)
};
// 0.5 pt left of A: wider than a pixel at 300 ppi, narrower than one of a 30,000 pt image.
let d = rect(&mut s, 40.0, 19.5);
let a = rect(&mut s, 60.0, 40.0);
let t = rect(&mut s, 95.0, 30_000.0);
s.execute("transparency.set", &json!({"ids": [t.0], "opacity": 50})).unwrap();
let o = FlattenOptions { no_transparency: Some(Default::default()), clip_complex_regions: true, ..FlattenOptions::default() };
let doc = &s.doc().unwrap().doc;
let long = plan(doc, &[d, a, t], &o, false).unwrap();
assert!(long.kept.is_empty(), "{:?}", long.kept);
assert_eq!(long.flat.iter().map(|f| f.roots.clone()).collect::<Vec<_>>(), vec![vec![d, a, t]]);
// Short, the image has 300 ppi pixels: D stays.
let short = rect(&mut s, 95.0, 40.0);
s.execute("transparency.set", &json!({"ids": [short.0], "opacity": 50})).unwrap();
let doc = &s.doc().unwrap().doc;
assert_eq!(plan(doc, &[d, a, short], &o, false).unwrap().kept, vec![d]);
// 100,000 pt long, its pixels are over 3 pt wide: art 3 pt away, whose reach doesn't touch
// A's, joins too.
let far = rect(&mut s, 40.0, 17.0);
let longer = rect(&mut s, 95.0, 100_000.0);
s.execute("transparency.set", &json!({"ids": [longer.0], "opacity": 50})).unwrap();
let doc = &s.doc().unwrap().doc;
let p = plan(doc, &[far, a, longer], &o, false).unwrap();
assert!(p.kept.is_empty(), "{:?}", p.kept);
assert_eq!(p.flat.iter().map(|f| f.roots.clone()).collect::<Vec<_>>(), vec![vec![far, a, longer]]);
}
}
+7 -7
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gradient",
["Window", "Gradient"],
None,
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial or conic, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial and conic: the vector turns about the center), aspect?: % (radial and conic; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool, dither?: bool (fills only: a linear, radial or conic gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool, dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
has_doc,
edit_gradient
),
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gradient Vector",
[],
None,
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial and conic: the extent ellipse's height / width, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space)",
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space)",
has_doc,
set_gradient_geom
),
@@ -118,7 +118,7 @@ type Parsed<T> = std::result::Result<T, String>;
/// Parse a kind name.
fn parse_kind(k: &str) -> Parsed<GradientKind> {
GradientKind::parse(k).ok_or_else(|| format!("unknown gradient kind `{k}` (linear, radial, conic, freeform)"))
GradientKind::parse(k).ok_or_else(|| format!("unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform)"))
}
/// The `method` param of `p`, if given: how the colours between the stops mix.
@@ -275,7 +275,7 @@ pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> {
gp.swatch = str_param(g, "swatch").map(str::to_string);
let geom = GeomEdit::parse(g)?;
let aspect = geom.aspect.map(|a| aspect_for(kind, a)).transpose()?;
if kind == GradientKind::Conic {
if matches!(kind, GradientKind::Conic | GradientKind::Diamond) {
no_focal(&geom)?;
}
if let Some((start, end)) = geom.vector {
@@ -315,7 +315,7 @@ fn aspect_for(kind: GradientKind, a: f64) -> Parsed<f64> {
Ok(a)
}
/// An error when `e` gives a focal point: a conic gradient has none (`null` is allowed).
/// An error when `e` gives a focal point: a conic or diamond gradient has none (`null` is allowed).
fn no_focal(e: &GeomEdit) -> Parsed<()> {
match e.focal {
Some(Some(_)) => Err("`focal` applies to radial gradients".into()),
@@ -645,7 +645,7 @@ impl GeomEdit {
/// the paint's space (text space for type runs) to the document and `bounds` (in that space) fits
/// an unplaced gradient, so what the document shows carries over where `e` keeps it. An error
/// when `e` gives what the gradient's kind can't take (a negative aspect other than a conic's, or
/// a conic's focal point).
/// a conic's or diamond's focal point).
fn vector_paint(
cur: &Paint,
e: &GeomEdit,
@@ -656,7 +656,7 @@ fn vector_paint(
let mut gp = gradient_for_edit(cur, model);
let kind = gp.gradient.kind;
let edit_aspect = e.aspect.map(|a| aspect_for(kind, a)).transpose()?;
if kind == GradientKind::Conic {
if matches!(kind, GradientKind::Conic | GradientKind::Diamond) {
no_focal(e)?;
}
let Some(from_doc) = invert(to_doc) else { return Ok(None) };
+48 -16
View File
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Check Links",
[],
None,
"{ids?: [image or placed document ids] (default: every linked image and placed document)} where each linked file is and whether it changed since it was read → {links: [{name, path, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}",
"{ids?: [image or placed document ids] (default: every linked image and placed document)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
has_doc,
check
),
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Links",
[],
None,
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels)}], missing, modified, embedded}",
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
has_doc,
list
),
@@ -113,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Link Info",
[],
None,
"{id?} an image's or placed document's Link Info (default: the one selected) → image.info's fields (id, name, linked, link, colorMode, pixelWidth, pixelHeight, width, height) and status: ok|modified|missing|embedded, format, ppi: [x, y] (the file's), effectivePpi: [x, y] (at its placed size), scale: [x%, y%] (of its 100% size), rotation (degrees, counter-clockwise), placement: {preserve, align, clip}; linked images also fileName, location (its folder), page?, fileSize? (bytes), modified?, created? (ms since the Unix epoch), refused? (why the path is not followed); a placed document has document: true, pageWidth and pageHeight (pt) instead of pixels, ppi and colorMode, and its scale is of its artboard's or page's 100% size",
"{id?} an image's or placed document's Link Info (default: the one selected) → image.info's fields (id, name, linked, link, colorMode, pixelWidth, pixelHeight, width, height) and status: ok|modified|missing|embedded, format, ppi: [x, y] (the file's), effectivePpi: [x, y] (at its placed size), scale: [x%, y%] (of its 100% size), rotation (degrees, counter-clockwise), placement: {preserve, align, clip}; linked images also fileName, location (its folder), page?, fileSize? (bytes), modified?, created? (ms since the Unix epoch), refused? (why the path is not followed); a placed document has document: true, pageWidth and pageHeight (pt) instead of pixels, ppi and colorMode, and its scale is of its artboard's or page's 100% size; under automation read roots, a link whose file is outside the roots has no link, path or location, and fileSize and modified come only from the file",
has_doc,
info
),
@@ -882,17 +882,35 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
}
/// Groups (of the document saved at `doc_path`) as `{name, path, ids}` rows (those with objects in
/// the layers), with `refused`: why the path isn't followed, when it isn't.
/// the layers), with `refused`: why the path isn't followed, when it isn't. `path` is left out
/// where [`path_shown`] says so.
fn rows<'a>(gs: impl Iterator<Item = &'a Group>, doc_path: Option<&str>) -> Vec<Value> {
gs.filter(|g| !g.ids.is_empty())
.map(|g| {
let mut row = json!({ "name": g.link.name(), "path": g.link.path, "ids": ids_json(&g.ids) });
let mut row = json!({ "name": g.link.name(), "ids": ids_json(&g.ids) });
note_path(&mut row, "path", &g.link.path, doc_path);
note_refused(&mut row, &g.link, doc_path);
row
})
.collect()
}
/// May a reply to the caller asking now carry the link path `path` (of the document saved at
/// `doc_path`)? Always without read roots in force; with them, only when the file it names (a
/// relative path taken from the document's folder) lies inside them.
fn path_shown(path: &str, doc_path: Option<&str>) -> bool {
crate::file_access::current().is_none() || fileio::document_path(path, doc_path).is_ok_and(|p| crate::file_access::check_read(&p).is_ok())
}
/// `row[key] = path` when [`path_shown`] says so; otherwise `row` has no `key`.
fn note_path(row: &mut Value, key: &str, path: &str, doc_path: Option<&str>) {
if path_shown(path, doc_path) {
row[key] = json!(path);
} else if let Some(o) = row.as_object_mut() {
o.remove(key);
}
}
/// `row["refused"]`: why the path of `link` isn't followed, when it isn't ([`refused`]).
fn note_refused(row: &mut Value, link: &LinkInfo, doc_path: Option<&str>) {
if let Some(r) = refused(link, doc_path) {
@@ -1188,10 +1206,12 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
let (status, found) = probe(g, LinkBase::of(st));
missing += usize::from(status == Status::Missing);
modified += usize::from(status == Status::Modified);
let mut row = json!({ "name": g.link.name(), "path": g.link.path, "status": status.as_str(), "ids": ids_json(&g.ids) });
note_refused(&mut row, &g.link, LinkBase::of(st).doc);
let doc_path = LinkBase::of(st).doc;
let mut row = json!({ "name": g.link.name(), "status": status.as_str(), "ids": ids_json(&g.ids) });
note_path(&mut row, "path", &g.link.path, doc_path);
note_refused(&mut row, &g.link, doc_path);
if let Some(f) = found.filter(|f| f.path != g.link.path) {
row["found"] = json!(f.path);
note_path(&mut row, "found", &f.path, doc_path);
}
if stale(&st.doc, g) {
row["preview"] = json!(true);
@@ -1663,14 +1683,15 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("linked".into(), json!(link.is_some()));
o.insert("status".into(), json!(status));
}
let doc_path = LinkBase::of(st).doc;
if let Some(l) = link {
row["path"] = json!(l.path);
note_path(&mut row, "path", &l.path, doc_path);
if let Some(page) = l.page {
row["page"] = json!(page);
}
}
if let Some(f) = found {
row["found"] = json!(f);
note_path(&mut row, "found", f, doc_path);
}
if preview {
row["preview"] = json!(true);
@@ -1811,13 +1832,17 @@ fn placement_json(o: PlacementOptions) -> Value {
/// Link Info's fields of the linked file `l` (of object `id` of `st`) into `out`.
fn file_fields(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) {
// Whether the path is shown is judged for the caller asking, before the opener's roots apply.
let shown = path_shown(&l.path, LinkBase::of(st).doc);
// A confined caller reads within its own roots; anyone else within what the caller that
// opened the document may read (never wider than the caller asking now).
let roots = crate::file_access::current().or_else(|| st.opened_by.clone());
crate::file_access::confine(roots.as_ref(), || file_fields_here(st, id, l, out));
crate::file_access::confine(roots.as_ref(), || file_fields_here(st, id, l, shown, out));
}
fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) {
/// [`file_fields`]; without `shown`, the link's path (`path`, `link`) and folder (`location`)
/// and the size and date the document keeps of its file are left out.
fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, shown: bool, out: &mut Value) {
let base = LinkBase::of(st);
let status = groups(&st.doc, Some(&[id])).first().map_or(Status::Missing, |g| probe(g, base).0);
let doc_path = base.doc;
@@ -1825,13 +1850,20 @@ fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Va
let stamp = path.as_deref().and_then(file_stamp);
out["status"] = json!(status.as_str());
note_refused(out, l, doc_path);
out["path"] = json!(l.path);
if shown {
out["path"] = json!(l.path);
out["location"] = json!(l.folder());
} else if let Some(o) = out.as_object_mut() {
for k in ["path", "link", "location"] {
o.remove(k);
}
}
out["fileName"] = json!(l.name());
out["location"] = json!(l.folder());
let kept = |v: Option<u64>| v.filter(|_| shown);
for (k, v) in [
("page", l.page.map(u64::from)),
("fileSize", stamp.map(|s| s.0).or(l.size)),
("modified", stamp.and_then(|s| s.1).or(l.modified)),
("fileSize", stamp.map(|s| s.0).or(kept(l.size))),
("modified", stamp.and_then(|s| s.1).or(kept(l.modified))),
("created", path.as_deref().and_then(file_created)),
] {
if let Some(v) = v {
+1 -1
View File
@@ -871,7 +871,7 @@ fn rasterize(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
fn has_image(s: &Session) -> std::result::Result<(), String> {
pub(crate) fn has_image(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
let st = s.active().ok_or("no document open")?;
if st.selection.objects.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))) {
+17 -3
View File
@@ -7,7 +7,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Artboard, Background, ColorMode, Document, Unit};
use vectorcraft_geom::{Point, Rect};
use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param};
use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param, switch_or};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Document Presets",
[],
None,
"{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode}]}]}; file.new {preset: name} starts from one",
"{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one",
always,
list
),
@@ -144,6 +144,10 @@ pub struct DocSettings {
#[serde(deserialize_with = "de_ppi")]
pub raster_effects_ppi: f64,
pub preview_mode: PreviewMode,
/// Align New Objects to Pixel Grid ([`vectorcraft_doc::DocSetup::align_new_objects_to_pixel_grid`]):
/// on in the Mobile and Web presets, off in the others and in a saved or Recent preset from
/// before it.
pub align_new_objects_to_pixel_grid: bool,
}
impl Default for DocSettings {
@@ -163,6 +167,7 @@ impl Default for DocSettings {
color_mode: ColorMode::Rgb,
raster_effects_ppi: 72.0,
preview_mode: PreviewMode::Default,
align_new_objects_to_pixel_grid: false,
}
}
}
@@ -211,6 +216,7 @@ impl DocSettings {
"colorMode": color_mode_id(self.color_mode),
"rasterEffectsPpi": self.raster_effects_ppi,
"previewMode": self.preview_mode.id(),
"alignNewObjectsToPixelGrid": self.align_new_objects_to_pixel_grid,
})
}
@@ -273,6 +279,7 @@ impl DocSettings {
if let Some(m) = p.get("previewMode").filter(|v| !v.is_null()) {
self.preview_mode = m.as_str().and_then(PreviewMode::parse).ok_or_else(|| bad(cmd, "previewMode must be default, pixel or overprint"))?;
}
self.align_new_objects_to_pixel_grid = switch_or(p, "alignNewObjectsToPixelGrid", self.align_new_objects_to_pixel_grid, cmd)?;
let extent = self.boards().iter().fold(Rect::ZERO, |a, r| a.union(*r));
if extent.width().max(extent.height()) + self.bleed.iter().fold(0.0f64, |a, b| a.max(*b)) * 2.0 > crate::MAX_COORD {
return Err(bad(cmd, "the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size"));
@@ -330,6 +337,7 @@ impl DocSettings {
d.raster_effects_ppi = self.raster_effects_ppi;
d.setup.bleed = self.bleed;
d.setup.background = self.background;
d.setup.align_new_objects_to_pixel_grid = self.align_new_objects_to_pixel_grid;
d.artboards = self
.boards()
.into_iter()
@@ -543,6 +551,10 @@ pub const CATEGORIES: &[Category] = &[
),
];
/// The built-in categories whose presets start with Align New Objects to Pixel Grid on
/// (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>).
const PIXEL_ALIGNED_CATEGORIES: [&str; 2] = ["Mobile", "Web"];
/// The category tabs in order: Recent, Saved, then the built-in categories.
pub fn category_names() -> impl Iterator<Item = &'static str> {
["Recent", "Saved"].into_iter().chain(CATEGORIES.iter().map(|c| c.0))
@@ -551,7 +563,8 @@ pub fn category_names() -> impl Iterator<Item = &'static str> {
/// The built-in presets of one category: screen sizes in pixels, the others in `general`
/// (Preferences ▸ Units ▸ General).
fn builtin(c: &Category, general: Unit) -> impl Iterator<Item = DocSettings> + '_ {
let (_, color_mode, ppi, presets) = *c;
let (category, color_mode, ppi, presets) = *c;
let align = PIXEL_ALIGNED_CATEGORIES.contains(&category);
presets.iter().map(move |&(name, w, h, units)| DocSettings {
name: name.into(),
width: units.to_pt(w),
@@ -559,6 +572,7 @@ fn builtin(c: &Category, general: Unit) -> impl Iterator<Item = DocSettings> + '
units: if units == Unit::Pixels { units } else { general },
color_mode,
raster_effects_ppi: ppi,
align_new_objects_to_pixel_grid: align,
..DocSettings::default()
})
}
+2 -1
View File
@@ -37,7 +37,8 @@ pub(crate) use bounds::{bounds_rewrite, object_bounds_transform};
pub use commands::specs;
pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip};
pub(crate) use pixelgrid::{
can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned,
align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap,
snap_if_aligned,
};
pub(super) use shape::recut;
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
+10
View File
@@ -22,6 +22,16 @@ pub(crate) fn can_align(n: &Node) -> bool {
matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. })
}
/// For an object being drawn into `d`: when the document's Align New Objects to Pixel Grid is on
/// and [`can_align`] accepts `n`, turn `n`'s pixel-aligned property on. The edit that adds it snaps
/// it to the pixel grid ([`refresh`]). Pasted, duplicated, placed and imported objects do not come
/// through here.
pub(crate) fn align_new_object(d: &Document, n: &mut Node) {
if d.setup.align_new_objects_to_pixel_grid && can_align(n) {
n.extras_mut().pixel_aligned = true;
}
}
/// `object.setPixelAligned`: turn the pixel-aligned property of the objects given (or the selected
/// objects) on or off. Turning it on snaps them to the pixel grid at once. Every object must be
/// one [`can_align`] accepts, else nothing changes. When every object already has the value, the
+3 -3
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fill",
[],
None,
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector), method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial and conic; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic), dither?: bool (linear, radial and conic fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial or conic `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
has_doc,
|s, p| set_paint(s, p, true)
),
@@ -641,7 +641,7 @@ fn paint_new_art(s: &mut Session, paint: &Paint, fill: bool) {
}
}
/// Does `p` ask for `span: "selection"` (#2127)? Only a linear, radial or conic gradient the targets
/// Does `p` ask for `span: "selection"` (#2127)? Only a linear, radial, conic or diamond gradient the targets
/// would each fit to their own bounds can span them: one with its own vector (`start`/`end`),
/// a freeform one or a gradient swatch already has its placement.
fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String> {
@@ -656,7 +656,7 @@ fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String>
return Err("span: \"selection\" places a `gradient`, not a swatch".into());
}
if g.gradient.kind == vectorcraft_color::GradientKind::Freeform || g.freeform.is_some() {
return Err("span: \"selection\" places a linear, radial or conic gradient, not a freeform one".into());
return Err("span: \"selection\" places a linear, radial, conic or diamond gradient, not a freeform one".into());
}
if g.geom.is_some() {
return Err(
+3 -3
View File
@@ -5,7 +5,7 @@
//! the file declares ([`fileio::ppi`]; 72 ppi when it declares none), linked to its file with
//! `link` ([`super::links`]).
//! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options
//! (`dxf`, [`fileio::dxfimport`]).
//! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`).
//! - An EMF or WMF picture becomes one group, clipped to its frame (`crop: "crop"`) or bounded by
//! its art (`crop: "bounding"`).
//! - An EPS file (or a PostScript .ai) becomes one group, clipped to its bounding box or bounded by
@@ -69,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place…",
["File"],
Some("Cmd+Shift+P"),
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, PDF/.ai, EMF/WMF (clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF (clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
has_doc,
place
),
@@ -264,7 +264,7 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
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") {
let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "hpgl") {
// 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.
+12 -10
View File
@@ -52,7 +52,7 @@ use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
use vectorcraft_plugins::permissions::{self, Grant, Permission};
use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission};
/// What a plug-in error looks like to the user. A run the caller cancelled changed nothing.
fn err(e: vectorcraft_plugins::Error) -> EngineError {
@@ -741,17 +741,18 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
}
// Installed plug-ins stay installed after a restart (#2541). The module is written first and its
// grant only once it is there; when the grant can't be written, the store gets the module it
// held back. A failed write of that module is only logged, and the grant then doesn't cover
// the new module. A stored module that can't be read back isn't replaced by one that needs a
// grant.
// held back. A failed write of that module is only logged: the store then holds the new module,
// which the grant doesn't cover. A write that reports a failure may still have put the old
// module back, so the store is read again to tell which module it holds. A stored module that
// can't be read back isn't replaced by one that needs a grant.
let previous = s.stored_plugin_bytes(plugin.id());
let mut stored = (previous.is_ok() || !m.asks_permissions()) && s.store_plugin(plugin.id(), &bytes);
let holds_new = |s: &Session| s.stored_plugin_bytes(plugin.id()).is_ok_and(|held| held.as_deref() == Some(&bytes[..]));
if m.asks_permissions() {
let g = Grant { id: m.id.clone(), hash: plugin.hash().to_string(), permissions: wanted };
registry::grant(g.clone());
registry::grant(GrantToken::after_engine_approval(g.clone()));
if stored && !s.store_grant(&m.id, Some(g)) {
s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref());
stored = false;
stored = !s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref()) && holds_new(s);
}
} else {
// This module takes the id over, so nothing the user approved for the id applies any more.
@@ -764,7 +765,7 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
// stays; one that can't be opened or read may approve the old bytes once it reads again.
if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) {
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref()));
stored = !back;
stored = !back && holds_new(s);
if !back || matches!(previous, Ok(None)) {
s.ignore_stored_grant(&m.id);
}
@@ -786,7 +787,8 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
if changed {
s.store_disabled_plugins();
}
let mut v = describe_installed(&registry::install(plugin));
let installed = registry::install(plugin).map_err(err)?;
let mut v = describe_installed(&installed);
if !unknown.is_empty() {
v["unknownCommands"] = json!(unknown);
}
@@ -885,7 +887,7 @@ fn load_folder(s: &Session, folder: &str) -> Value {
None if crate::file_access::current().is_none() => Ok(()),
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
};
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_approver()) {
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) {
Ok(r) => {
for id in &r.loaded {
s.attach_plugin_storage(id);
@@ -32,6 +32,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.color.strokeToFill",
"addon.color.swatchLegend",
"addon.contour.set",
"addon.image.removeBackground",
"addon.pathtools.addPoints",
"addon.pathtools.close",
"addon.pathtools.corner",
+1
View File
@@ -404,6 +404,7 @@ fn gradient_key(g: &Gradient) -> Option<GradientKey<'_>> {
GradientKind::Radial => 1,
GradientKind::Freeform => 2,
GradientKind::Conic => 3,
GradientKind::Diamond => 4,
};
let method = match g.method {
GradientMethod::Classic => 0,
+199
View File
@@ -87,6 +87,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_dynamic_type,
dynamic_text
),
cmd!(
"type.dynamicTextPreset",
"Dynamic Text Presets",
["Type", "Dynamic Text Presets"],
None,
"{preset: \"circle\"|\"arch\"|\"bow\", position?: \"above\"|\"center\"|\"below\", flip?: bool, ids?|id?} put the selected point type and type on a path on a new path of the preset's shape with Dynamic Text on, so the text is sized to fill it (see type.dynamicText). Circle: a circle as wide as the text, the text running clockwise round all of it from its bottom; Arch: an arc of a circle bulging upward over 120°, as wide as the text; Bow: the same arc bulging downward. The width is, for point type, the length on the page of the longer side of the text's bounds, and for type on a path the longer side of its path's bounds on the page (so the same preset again leaves it as it is); the new path is centered where they were, and the shape is upright on the page when the object is rotated or scaled. position (omitted: above) sets Type on a Path Options › Align to Path: above stands the type on the path (descender), center centers it on the path (center), below hangs it from the path (ascender); flip true then turns the text to the other side of its path, running the other way. Type on a Path Options › effect and spacing stay. Area type in the selection is left as it is; a selection holding type on a path in a thread is refused. When nothing changes, no undo step is recorded → {ids, fitScale (the first object's factor)}",
has_preset_type,
dynamic_text_preset
),
cmd!(
"type.fillPlaceholder",
"Fill with Placeholder Text",
@@ -796,6 +805,196 @@ pub(crate) fn bake_dynamic_text(t: &mut TextObject) -> bool {
true
}
/// The shapes of `type.dynamicTextPreset`.
const PRESETS: [&str; 3] = ["circle", "arch", "bow"];
/// Point type and type on a path among `ids` and their descendants: the type
/// `type.dynamicTextPreset` puts on a path.
fn preset_ids(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
text_ids(d, ids)
.into_iter()
.filter(|id| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, TextKind::Point | TextKind::OnPath { .. })))
.collect()
}
/// `type.dynamicTextPreset` is enabled for a selection holding point type or type on a path, and
/// no type on a path in a thread.
fn has_preset_type(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
let st = s.active().ok_or("no document open")?;
let d = &st.doc;
let ids = preset_ids(d, &st.selection.objects);
if ids.is_empty() {
return Err("select point type or type on a path".into());
}
let frames = threaded_ids(d, &ids);
if !frames.is_empty() {
return Err(format!("type on a path in a thread cannot use Dynamic Text: {frames}"));
}
Ok(())
}
/// The path of Dynamic Text preset `preset` (one of [`PRESETS`]) `w` wide, centered on `c`, with
/// the start bracket the text starts at. Circle: a circle `w` across, run clockwise from its
/// bottom; Arch and Bow: a 120° arc of a circle whose chord is `w`, bulging up or down, run from
/// left to right.
fn preset_path(preset: &str, c: vectorcraft_geom::Point, w: f64) -> (vectorcraft_geom::PathData, f64) {
let h = w / 2.0;
if preset == "circle" {
// `shapes::ellipse` runs clockwise on screen from its left: its bottom is 3/4 of the way.
return (shapes::ellipse(Rect::new(c.x - h, c.y - h, c.x + h, c.y + h)), 0.75);
}
// A chord of `w` under 120°: radius w/√3, and the arc rises a half radius above its chord.
let r = w / 3f64.sqrt();
let arch = preset == "arch";
let cy = if arch { c.y - r / 4.0 + r } else { c.y + r / 4.0 - r };
let circle = Rect::new(c.x - r, cy - r, c.x + r, cy + r);
// `shapes::ellipse_arc` runs counterclockwise on screen: right to left over the top.
let mut path = if arch {
shapes::ellipse_arc(circle, 30.0, 150.0, shapes::EllipseMode::Arc)
} else {
shapes::ellipse_arc(circle, 210.0, 330.0, shapes::EllipseMode::Arc)
};
if arch {
path.reverse();
}
(path, 0.0)
}
/// `t` (point type or type on a path) on the path of `preset` with Dynamic Text on, Align to Path
/// `align`, and flipped when `flip`. The shape is made upright on the page and mapped back through
/// the object's transform, so a rotated or scaled object still shows a circle, an arch or a bow.
/// Point type: the path is as wide as the longer side of the text's layout bounds is long on the
/// page, centered on them; with no layout area (empty text), four ems of its first character
/// wide, centered on its estimated bounds. Type on a path: as wide as the longer side of its
/// path's bounds on the page, centered on them, so the same preset again gives the same path.
/// When the object's transform can't be undone, or undoing it gives a path that isn't finite, the
/// shape is made in the text's own space.
fn with_preset(t: &TextObject, preset: &str, align: vectorcraft_doc::PathAlign, flip: bool) -> TextObject {
let invertible = t.xf.is_finite() && t.xf.determinant() != 0.0 && t.xf.inverse().is_finite();
// The transform the shape was made upright through, with the shape.
let ((path, start, w), xf) = invertible
.then(|| preset_shape(t, preset, t.xf).map(|s| (s, t.xf)))
.flatten()
.or_else(|| preset_shape(t, preset, Affine::IDENTITY).map(|s| (s, Affine::IDENTITY)))
.unwrap_or_else(|| {
let (path, start) = preset_path(preset, vectorcraft_geom::Point::ZERO, 48.0);
((path, start, 48.0), Affine::IDENTITY)
});
let mut out = t.clone();
out.kind = TextKind::OnPath { path, start, end: None };
out.path_align = align;
out.dynamic_text = true;
if flip {
out.flip_on_path();
}
// The same preset again measures the path it made, which can differ in the last bits: a path
// within a billionth of its width of the old one on the page keeps the old one, so nothing
// changes.
if let (TextKind::OnPath { path: old, .. }, TextKind::OnPath { path: new, .. }) = (&t.kind, &mut out.kind)
&& same_path(&old.transformed(xf), &new.transformed(xf), w * 1e-9)
{
*new = old.clone();
}
refresh_bounds(&mut out);
out
}
/// The path of `preset` for `t` made upright through transform `xf` (see [`with_preset`]), in the
/// text's space, with its start bracket and its width on the page; None when the path isn't
/// finite.
fn preset_shape(t: &TextObject, preset: &str, xf: Affine) -> Option<(vectorcraft_geom::PathData, f64, f64)> {
// How long `(x, y)` in the text's space is on the page.
let on_page = |x: f64, y: f64| (xf * vectorcraft_geom::Point::new(x, y) - xf * vectorcraft_geom::Point::ZERO).hypot();
// The center on the page, and the width measured (0 when nothing can be measured).
let (c, longer) = match &t.kind {
TextKind::OnPath { path, .. } => path
.transformed(xf)
.bounds()
.filter(|b| b.is_finite())
.map_or((xf * vectorcraft_geom::Point::ZERO, 0.0), |b| (b.center(), b.width().max(b.height()))),
_ => {
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).bounds;
match Some(lay).filter(|b| b.area() > 0.0 && b.is_finite()) {
Some(b) => (xf * b.center(), on_page(b.width(), 0.0).max(on_page(0.0, b.height()))),
None => (xf * Some(t.estimate_bounds()).filter(|b| b.is_finite()).map_or(vectorcraft_geom::Point::ZERO, |b| b.center()), 0.0),
}
}
};
// Without a measured width: four ems of the first character, else 48 pt.
let size = t.first_style().size;
let w = if longer.is_finite() && longer > 1e-6 {
longer
} else if size.is_finite() && size > 0.0 && on_page(size * 4.0, 0.0) > 1e-6 {
on_page(size * 4.0, 0.0)
} else {
48.0
};
let (path, start) = preset_path(preset, c, w);
let path = path.transformed(xf.inverse());
let finite = path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite());
(finite && w.is_finite()).then_some((path, start, w))
}
/// Whether paths `a` and `b` have the same subpaths, closed alike, with every anchor and handle
/// within `eps` of each other.
fn same_path(a: &vectorcraft_geom::PathData, b: &vectorcraft_geom::PathData, eps: f64) -> bool {
let near = |p: vectorcraft_geom::Point, q: vectorcraft_geom::Point| (p - q).hypot() <= eps;
a.subpaths.len() == b.subpaths.len()
&& a.subpaths.iter().zip(&b.subpaths).all(|(s, t)| {
s.closed == t.closed
&& s.anchors.len() == t.anchors.len()
&& s.anchors.iter().zip(&t.anchors).all(|(x, y)| x.kind == y.kind && near(x.p, y.p) && near(x.h_in, y.h_in) && near(x.h_out, y.h_out))
})
}
/// Type › Dynamic Text Presets: put the selected point type and type on a path on a new path of
/// the preset's shape with Dynamic Text on, in one undo step, and none when nothing changes.
fn dynamic_text_preset(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.dynamicTextPreset";
let key = "preset";
let preset = choice(p, C, key, &PRESETS)?.ok_or_else(|| bad(C, format!("`{key}` must be one of {}", PRESETS.join(", "))))?;
let align = match choice(p, C, "position", &["above", "center", "below"])? {
Some("center") => vectorcraft_doc::PathAlign::Center,
Some("below") => vectorcraft_doc::PathAlign::Ascender,
_ => vectorcraft_doc::PathAlign::Descender,
};
let flip = switch_or(p, "flip", false, C)?;
let (ids, changed) = {
let d = &s.doc()?.doc;
let ids = preset_ids(d, &targets(s, p)?);
if ids.is_empty() {
return Err(bad(C, "select point type or type on a path"));
}
let frames = threaded_ids(d, &ids);
if !frames.is_empty() {
return Err(bad(C, format!("type on a path in a thread cannot use Dynamic Text: {frames}")));
}
let changed: Vec<(NodeId, TextObject)> = ids
.iter()
.filter_map(|id| match d.node(*id).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => Some((*id, with_preset(t, preset, align, flip))).filter(|(_, new)| new != &**t),
_ => None,
})
.collect();
(ids, changed)
};
if !changed.is_empty() {
s.edit("Dynamic Text", |d, _| {
for (id, new) in &changed {
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
**t = new.clone();
}
}
Ok(())
})?;
}
let d = &s.doc()?.doc;
let fit =
ids.first().and_then(|id| path_text(d.node(*id))).map_or(1.0, |t| vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).fit_scale);
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "fitScale": fit}))
}
// ---------- placeholder / insert ----------
/// VectorCraft's own placeholder copy (not the classical Latin text).
+3
View File
@@ -282,6 +282,9 @@ pub struct Session {
pub(crate) in_tool_actions: bool,
/// While [`Session::preview`] runs its command: its edits are the interaction's own.
previewing: bool,
/// The images Remove Background decoded during the interaction's preview steps, emptied when
/// it ends ([`cmd::DecodedImages`]).
pub(crate) decoded_images: cmd::DecodedImages,
/// Envelope Options with no envelope selected: the options and fidelity new envelopes get
/// (`None`: the reference app's defaults, fidelity 50); not saved.
pub(crate) envelope_defaults: Option<(vectorcraft_doc::live::EnvelopeOptions, f64)>,
+38 -16
View File
@@ -189,11 +189,15 @@ fn home_folder() -> String {
}
/// The folders `Folder.temp`, `Folder.desktop` and the others name, `null` where there is none.
/// On the web every one is `null`, and no platform folder is looked up.
fn locations(home: &str) -> Data {
if cfg!(target_arch = "wasm32") {
return Data::Object(PLACES.iter().map(|k| (k.to_string(), Data::Null)).collect());
}
let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
let join = |a: &str, b: &str| Path::new(a).join(b).to_string_lossy().into_owned();
let exe = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_string_lossy().into_owned()));
let temp = std::env::temp_dir().to_string_lossy().into_owned();
let temp = temp_folder().to_string_lossy().into_owned();
let (user_data, app_data, common, system, trash) = if WINDOWS {
(env("APPDATA"), env("PROGRAMDATA"), env("CommonProgramFiles"), env("SystemRoot"), None)
} else if cfg!(target_os = "macos") {
@@ -209,7 +213,6 @@ fn locations(home: &str) -> Data {
(Some(data.clone()), Some("/usr/share".to_string()), Some("/usr/share".to_string()), Some("/".to_string()), Some(join(&data, "Trash")))
};
let s = |v: Option<String>| v.map_or(Data::Null, Data::String);
let web = cfg!(target_arch = "wasm32");
let places = vec![
("appData", app_data),
("appPackage", exe.clone()),
@@ -222,7 +225,15 @@ fn locations(home: &str) -> Data {
("trash", trash),
("userData", user_data),
];
Data::Object(places.into_iter().map(|(k, v)| (k.to_string(), if web { Data::Null } else { s(v) })).collect())
Data::Object(places.into_iter().map(|(k, v)| (k.to_string(), s(v))).collect())
}
/// The names [`locations`] gives.
const PLACES: [&str; 10] = ["appData", "appPackage", "commonFiles", "desktop", "myDocuments", "startup", "system", "temp", "trash", "userData"];
/// The folder for temporary files: the platform's, or on the web the root, where nothing is read.
fn temp_folder() -> std::path::PathBuf {
if cfg!(target_arch = "wasm32") { std::path::PathBuf::from("/") } else { std::env::temp_dir() }
}
/// The start of an absolute path.
@@ -349,12 +360,12 @@ impl Pathname {
}
}
/// `s` with every character but letters, digits and `-_.!~*'()` written as `%xx` escapes of its
/// `s` with every character but letters, digits and `/-_.!~*'()` written as `%xx` escapes of its
/// UTF-8 bytes (RFC 2396).
fn encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || b"-_.!~*'()".contains(&b) {
if b.is_ascii_alphanumeric() || b"/-_.!~*'()".contains(&b) {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
@@ -842,7 +853,23 @@ fn temp_name(host: &Host, _: &[Data]) -> Result<Data, HostError> {
let mut disk = host.disk.borrow_mut();
disk.temps += 1;
let name = format!("vc{:05}.tmp", disk.temps);
Ok(Data::String(std::env::temp_dir().join(name).to_string_lossy().into_owned()))
Ok(Data::String(temp_folder().join(name).to_string_lossy().into_owned()))
}
fn locations_of(host: &Host, _: &[Data]) -> Result<Data, HostError> {
Ok(locations(&host.disk.borrow().home))
}
fn encode_text(_: &Host, a: &[Data]) -> Result<Data, HostError> {
Ok(Data::String(encode(&arg_text(a, 0))))
}
fn decode_text(_: &Host, a: &[Data]) -> Result<Data, HostError> {
Ok(Data::String(decode(&arg_text(a, 0))))
}
fn encoding_available(_: &Host, a: &[Data]) -> Result<Data, HostError> {
Ok(Data::Bool(Encoding::parse(&arg_text(a, 0)).is_some()))
}
/// The folder `Folder.current` starts at in the run `host` serves: the script's own folder.
@@ -851,10 +878,6 @@ fn start_folder(host: &Host, _: &[Data]) -> Result<Data, HostError> {
Ok(Data::String(disk.pathname(&disk.start, &disk.start, false).fs()))
}
fn locations_of(host: &Host, _: &[Data]) -> Result<Data, HostError> {
Ok(locations(&host.disk.borrow().home))
}
/// Adds `File` and `Folder` to the realm, their host functions acting for the run `link` holds.
pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> {
let unchecked = |f: fn(&Host, &[Data]) -> Result<Data, HostError>| {
@@ -871,7 +894,6 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
("noPicker".into(), value(NO_PICKER)),
("badMode".into(), value(BAD_MODE)),
]);
let pure = |f: fn(&str) -> Data| HostItem::Function(Rc::new(move |a| Ok(f(&arg_text(&a, 0)))));
let system = if WINDOWS {
"Windows"
} else if cfg!(target_os = "macos") {
@@ -884,10 +906,10 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
("system".into(), value(system)),
("lineFeed".into(), value(if WINDOWS { "Windows" } else { "Unix" })),
("current".into(), unchecked(start_folder)),
("locations".into(), unchecked(locations_of)),
("encode".into(), pure(|s| Data::String(encode(s)))),
("decode".into(), pure(|s| Data::String(decode(s)))),
("encodingAvailable".into(), pure(|s| Data::Bool(Encoding::parse(s).is_some()))),
("locations".into(), call(link, locations_of)),
("encode".into(), call(link, encode_text)),
("decode".into(), call(link, decode_text)),
("encodingAvailable".into(), call(link, encoding_available)),
("parse".into(), call(link, parse)),
("relative".into(), call(link, relative)),
("tempName".into(), call(link, temp_name)),
@@ -955,7 +977,7 @@ mod tests {
#[test]
fn uri_escapes_are_utf8_both_ways() {
assert_eq!(encode("caf\u{e9} 1"), "caf%C3%A9%201");
assert_eq!(encode("a-_.!~*'()/b"), "a-_.!~*'()%2Fb");
assert_eq!(encode("a-_.!~*'()/b"), "a-_.!~*'()/b");
assert_eq!(decode("caf%C3%A9%20x"), "caf\u{e9} x");
assert_eq!(decode("100%"), "100%");
assert_eq!(decode("%E9"), "%E9", "a lone Latin-1 escape is not UTF-8");
+1
View File
@@ -115,6 +115,7 @@ impl Session {
recovery: Default::default(),
in_tool_actions: false,
previewing: false,
decoded_images: Default::default(),
envelope_defaults: None,
liquify_stroke: None,
plane_widget_press: false,
+2
View File
@@ -335,6 +335,7 @@ impl Session {
pub fn commit_interaction(&mut self) -> Result<()> {
self.clear_deferred_overlay_cache();
self.decoded_images.empty();
if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) {
self.paint = paint;
}
@@ -414,6 +415,7 @@ impl Session {
pub fn cancel_interaction(&mut self) -> Result<()> {
self.clear_deferred_overlay_cache();
self.decoded_images.empty();
self.pending_paint = None;
if let Some(paint) = self
.active()
+39 -5
View File
@@ -39,6 +39,7 @@ use std::sync::{Arc, Mutex, MutexGuard};
use std::time::SystemTime;
use vectorcraft_pdf::{PdfPreset, builtin_preset};
use vectorcraft_plugins::permissions::GrantToken;
use vectorcraft_plugins::safe_mode;
use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError};
@@ -190,6 +191,9 @@ fn lock_disabled(_: &Path) -> Option<std::fs::File> {
thread_local! {
/// Tests: [`Session::put_back_plugin`] fails on this thread, as on a full volume.
pub(crate) static PUT_BACK_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: [`Session::put_back_plugin`] writes the old module back on this thread and then
/// reports a failure, as when the last flush of a copy fails.
pub(crate) static PUT_BACK_FAILS_AFTER_WRITE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: moving a plug-in's settings and cache back from `<folder>.removed` ([`move_back`])
/// fails on this thread, as when another program holds a file in the folder.
pub(crate) static MOVE_BACK_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
@@ -389,9 +393,11 @@ impl Session {
match grants.get(&m.id).filter(|g| grant_covers(g, &plugin)) {
Some(g) => {
asks_nothing.remove(&m.id);
vectorcraft_plugins::registry::grant(g.clone());
vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone()));
vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id));
vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string()));
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
log::warn!("skipping the stored plug-in {}: {e}", path.display());
}
}
None => {
log::warn!("skipping the stored plug-in {}: the user hasn't granted this module the permissions it lists", path.display())
@@ -401,7 +407,9 @@ impl Session {
Ok(plugin) => {
asks_nothing.insert(plugin.id().to_string());
vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id()));
vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string()));
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
log::warn!("skipping the stored plug-in {}: {e}", path.display());
}
}
Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()),
}
@@ -475,6 +483,27 @@ impl Session {
}
}
/// [`Session::plugin_approver`] for a folder load: a module the store's grants approve gets
/// that grant recorded for the process too, since the registry installs only a module that a
/// recorded grant covers ([`vectorcraft_plugins::registry::install`]).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn plugin_folder_approver(&self) -> impl Fn(&vectorcraft_plugins::Plugin) -> bool + use<> {
let grants = self.plugin_dir.as_deref().map(|dir| self.counted_grants(dir));
move |plugin| {
let m = plugin.manifest();
match &grants {
Some(grants) if m.asks_permissions() => match grants.get(&m.id).filter(|g| grant_covers(g, plugin)) {
Some(g) => {
vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone()));
true
}
None => false,
},
_ => vectorcraft_plugins::registry::approved(plugin),
}
}
}
/// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those this session
/// doesn't count ([`Session::ignore_stored_grant`]).
fn counted_grants(&self, dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
@@ -504,16 +533,21 @@ impl Session {
/// Return the store's module for the plug-in `id` to `previous`, the bytes it held before a
/// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed. → whether the
/// store now holds `previous`.
/// write reported success; a write that reports a failure may still have put `previous` back.
pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) -> bool {
#[cfg(test)]
if PUT_BACK_FAILS.get() {
return false;
}
match previous {
let back = match previous {
Some(bytes) => self.store_plugin(id, bytes),
None => self.unstore_plugin(id),
};
#[cfg(test)]
if PUT_BACK_FAILS_AFTER_WRITE.get() {
return false;
}
back
}
/// The file the plug-in `id` is stored in, spelled as [`Session::load_stored_plugins`] names it
+1
View File
@@ -161,6 +161,7 @@ mod script_include;
mod script_io;
mod script_run;
mod scripts;
mod select_effects;
mod select_ids_first;
mod shaper;
mod shapetools;
@@ -115,6 +115,9 @@ fn constrain_angle_draws_boxes_along_the_turned_axes() {
let mut s = new_doc();
set_pref(&mut s, "constrainAngle", json!(90));
for tool in ["rectangle", "ellipse"] {
// The shape drawn before stays selected, and a press on its box's corner handle would
// scale it instead of drawing.
s.execute("select.none", &json!({})).unwrap();
s.select_tool(tool, ViewInfo::default()).unwrap();
// 60 right and 20 down on the page: along axes turned 90°, 20 wide and 60 high.
gesture(&mut s, Mods::default(), &[(Down, 100.0, 100.0), (Drag, 130.0, 110.0), (Drag, 160.0, 120.0), (Up, 160.0, 120.0)]);
+194
View File
@@ -234,6 +234,200 @@ fn svg_export_writes_the_drawn_size() {
assert!(!sizes.iter().any(|v| (v - 12.0).abs() < 1e-3), "the stored size is not written: {sizes:?}");
}
/// 12 pt point type at (100, 100), selected, with its layout bounds.
fn point(s: &mut Session, content: &str) -> (NodeId, vectorcraft_geom::Rect) {
let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": content, "size": 12})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let b = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s, id)).bounds;
(id, b)
}
/// Type on a path's path, start bracket and end bracket.
fn on_path(t: &TextObject) -> (vectorcraft_geom::PathData, f64, Option<f64>) {
match &t.kind {
vectorcraft_doc::TextKind::OnPath { path, start, end } => (path.clone(), *start, *end),
k => panic!("not type on a path: {k:?}"),
}
}
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-6
}
#[test]
fn presets_put_point_type_on_a_fitted_circle_arch_or_bow() {
let mut s = session();
let (id, b) = point(&mut s, "Round and round");
let w = b.width().max(b.height());
let before = undo_len(&s);
let r = s.execute("type.dynamicTextPreset", &json!({"preset": "circle"})).unwrap();
assert_eq!(r["ids"], json!([id.0]));
assert_eq!(undo_len(&s), before + 1);
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Dynamic Text");
let t = text(&s, id);
assert!(t.dynamic_text);
assert_eq!(t.path_align, vectorcraft_doc::PathAlign::Descender, "above by default");
let (path, start, end) = on_path(&t);
assert!(path.is_closed());
assert_eq!((start, end), (0.75, None));
let pb = path.bounds().unwrap();
assert!(close(pb.width(), w) && close(pb.height(), w), "{pb:?} vs {w}");
assert!(close(pb.center().x, b.center().x) && close(pb.center().y, b.center().y), "{pb:?} vs {b:?}");
// The start bracket, 3/4 of the way round, is the circle's bottom.
let bottom = path.subpaths[0].anchors[3].p;
assert!(close(bottom.y, pb.y1) && close(bottom.x, pb.center().x), "{bottom:?}");
// Round a circle as wide as the text, the text grows to fill it and does not overflow.
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
assert!(lay.fit_scale > 2.0 && !lay.overflow, "{} {}", lay.fit_scale, lay.overflow);
assert_eq!(r["fitScale"], json!(lay.fit_scale));
assert_eq!(t.cached_bounds, Some(lay.bounds));
// Undo gives the point type back.
s.execute("edit.undo", &json!({})).unwrap();
assert!(matches!(text(&s, id).kind, vectorcraft_doc::TextKind::Point) && !text(&s, id).dynamic_text);
for (preset, up) in [("arch", true), ("bow", false)] {
s.execute("type.dynamicTextPreset", &json!({"preset": preset, "ids": [id.0]})).unwrap();
let t = text(&s, id);
let (path, start, end) = on_path(&t);
assert!(!path.is_closed() && t.dynamic_text);
assert_eq!((start, end), (0.0, None));
let a = &path.subpaths[0].anchors;
let (first, middle, last) = (a[0].p, a[1].p, a[a.len() - 1].p);
// Left to right, the chord as wide as the text, the arc rising (or falling) half its radius.
assert!(first.x < last.x && close(last.x - first.x, w) && close(first.y, last.y), "{preset}: {first:?} {last:?}");
let pb = path.bounds().unwrap();
assert!(close(pb.height(), w / 3f64.sqrt() / 2.0), "{preset}: {pb:?}");
assert!(close(pb.center().y, b.center().y), "{preset}: {pb:?} vs {b:?}");
assert_eq!(middle.y < first.y, up, "{preset}: {middle:?} {first:?}");
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
assert!(lay.fit_scale > 1.0 && !lay.overflow, "{preset}: {}", lay.fit_scale);
s.execute("edit.undo", &json!({})).unwrap();
}
}
#[test]
fn preset_position_and_flip_set_align_to_path_and_direction() {
let mut s = session();
let (id, _) = point(&mut s, "Over the hill");
for (position, align) in [
("above", vectorcraft_doc::PathAlign::Descender),
("center", vectorcraft_doc::PathAlign::Center),
("below", vectorcraft_doc::PathAlign::Ascender),
] {
s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "position": position})).unwrap();
assert_eq!(text(&s, id).path_align, align, "{position}");
}
// Flipped, the arch runs right to left and the text stands on its other side.
s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "flip": true})).unwrap();
let t = text(&s, id);
let (path, start, end) = on_path(&t);
let a = &path.subpaths[0].anchors;
assert!(a[0].p.x > a[a.len() - 1].p.x, "{path:?}");
assert_eq!((start, end), (0.0, None));
assert_eq!(t.path_align, vectorcraft_doc::PathAlign::Descender);
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
// A flipped circle runs the other way round from its bottom.
s.execute("type.dynamicTextPreset", &json!({"preset": "circle", "flip": true})).unwrap();
let (path, start, end) = on_path(&text(&s, id));
assert_eq!((start, end), (0.25, None));
let at = path.subpaths[0].anchors[1].p;
assert!(close(at.y, path.bounds().unwrap().y1), "reversed, the bottom is a quarter of the way: {at:?}");
// The effect and Spacing of Type on a Path Options stay.
s.execute("type.pathOptions", &json!({"effect": "skew", "spacing": 5})).unwrap();
s.execute("type.dynamicTextPreset", &json!({"preset": "bow"})).unwrap();
let t = text(&s, id);
assert_eq!((t.path_effect.id(), t.path_spacing), ("skew", 5.0));
}
#[test]
fn presets_fit_type_on_a_path_to_its_path_and_record_nothing_when_nothing_changes() {
let mut s = session();
let id = on_line(&mut s, "Along the line");
s.execute("type.dynamicTextPreset", &json!({"preset": "bow"})).unwrap();
let (path, ..) = on_path(&text(&s, id));
let a = &path.subpaths[0].anchors;
// The bow is as wide as the 400 pt line, centered where it was.
assert!(close(a[0].p.x, 100.0) && close(a[a.len() - 1].p.x, 500.0), "{a:?}");
assert!(close(path.bounds().unwrap().center().y, 300.0));
// The same preset again: nothing changes and no undo step is recorded.
let before = undo_len(&s);
let r = s.execute("type.dynamicTextPreset", &json!({"preset": "bow"})).unwrap();
assert_eq!(r["ids"], json!([id.0]));
assert_eq!(undo_len(&s), before);
// Another position is a change.
s.execute("type.dynamicTextPreset", &json!({"preset": "bow", "position": "below"})).unwrap();
assert_eq!(undo_len(&s), before + 1);
// The fit follows later edits to the text.
let f = fit(&s, id);
s.execute("text.setText", &json!({"ids": [id.0], "text": "Along the line and on past it"})).unwrap();
assert!(fit(&s, id) < f * 0.8, "{} vs {f}", fit(&s, id));
// On a rotated object the arch still bulges up the page, and on a squashed one the circle is
// round on the page.
let (turned, _) = point(&mut s, "Turned");
s.execute("object.rotate", &json!({"ids": [turned.0], "angle": 45})).unwrap();
s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "ids": [turned.0]})).unwrap();
let t = text(&s, turned);
let page = on_path(&t).0.transformed(t.xf);
let a = &page.subpaths[0].anchors;
assert!(close(a[0].p.y, a[2].p.y) && a[1].p.y < a[0].p.y && a[0].p.x < a[2].p.x, "{a:?}");
// The same preset again leaves the rotated arch as it is.
let before = undo_len(&s);
s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "ids": [turned.0]})).unwrap();
assert_eq!(undo_len(&s), before);
let (squashed, _) = point(&mut s, "Squashed");
s.execute("object.scale", &json!({"ids": [squashed.0], "sx": 200, "sy": 50})).unwrap();
s.execute("type.dynamicTextPreset", &json!({"preset": "circle", "ids": [squashed.0]})).unwrap();
let t = text(&s, squashed);
let pb = on_path(&t).0.transformed(t.xf).bounds().unwrap();
assert!(close(pb.width(), pb.height()), "{pb:?}");
// Empty 12 pt point type gets a circle four ems (48 pt) across.
let (empty, _) = point(&mut s, "");
s.execute("type.dynamicTextPreset", &json!({"preset": "circle"})).unwrap();
let (path, ..) = on_path(&text(&s, empty));
let pb = path.bounds().unwrap();
assert!(close(pb.width(), 48.0) && close(pb.height(), 48.0), "{pb:?}");
}
#[test]
fn presets_refuse_bad_params_area_type_and_threads() {
let mut s = session();
let (id, _) = point(&mut s, "Point");
let before = undo_len(&s);
for p in [
json!({}),
json!({"preset": "square"}),
json!({"preset": 1}),
json!({"preset": "arch", "position": "top"}),
json!({"preset": "arch", "position": true}),
json!({"preset": "arch", "flip": "yes"}),
] {
let e = err(s.execute("type.dynamicTextPreset", &p));
let key = ["position", "flip"].into_iter().find(|k| p.get(k).is_some()).unwrap_or("preset");
assert!(e.contains(key), "{p}: {e}");
}
assert_eq!(undo_len(&s), before);
assert!(matches!(text(&s, id).kind, vectorcraft_doc::TextKind::Point));
// Area type alone is refused; beside point type it is left as it is.
let area =
s.execute("text.create", &json!({"x": 10, "y": 300, "text": "Area", "area": {"width": 100, "height": 50}})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [area]})).unwrap();
assert!(err(s.execute("type.dynamicTextPreset", &json!({"preset": "circle"}))).contains("select point type or type on a path"));
s.execute("select.set", &json!({"ids": [area, id.0]})).unwrap();
let r = s.execute("type.dynamicTextPreset", &json!({"preset": "circle"})).unwrap();
assert_eq!(r["ids"], json!([id.0]));
assert!(matches!(text(&s, NodeId(area)).kind, vectorcraft_doc::TextKind::Area { .. }) && !text(&s, NodeId(area)).dynamic_text);
// Type on a path in a thread is refused by id.
let threaded = on_line(&mut s, "Threaded story");
let frame = s.execute("shape.rectangle", &json!({"x": 100, "y": 400, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [threaded.0, frame]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
let before = undo_len(&s);
let e = err(s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "ids": [threaded.0, id.0]})));
assert!(e.contains("in a thread") && e.contains(&threaded.0.to_string()), "{e}");
assert_eq!(undo_len(&s), before);
}
/// The id of the first text object in `s`'s document.
fn first_text(s: &Session) -> NodeId {
let mut found = None;
+285
View File
@@ -215,6 +215,291 @@ fn type_picks_up_font_and_size() {
assert_eq!((st.size, justify, st.fill.color().unwrap().to_hex()), (12.0, preserved_alignment, "#00ff00".into()));
}
/// Sample document-space typography between text objects with different local transforms.
#[test]
fn scaled_type_pick_matches_effective_character_dimensions() {
for source_area in [false, true] {
for target_area in [false, true] {
let mut s = session();
let create = |s: &mut Session, area: bool, x: f64| {
let mut p = json!({"x": x, "y": 100, "text": "Sample", "size": 12});
if area {
p["area"] = json!({"width": 160, "height": 80});
}
id_of(s.execute("text.create", &p).unwrap())
};
let src = create(&mut s, source_area, 100.0);
s.execute("object.transform", &json!({"matrix": [3, 0, 0, 2, 0, 0]})).unwrap();
let dst = create(&mut s, target_area, 300.0);
s.execute("object.transform", &json!({"matrix": [0.5, 0, 0, 1.5, 0, 0]})).unwrap();
let before = node(&s, dst);
let source = node(&s, src);
let history = undo_len(&s);
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
let after = node(&s, dst);
let NodeKind::Text(t) = &after.kind else { panic!("not text") };
let NodeKind::Text(old) = &before.kind else { panic!("not text") };
let effective = t.effective_char_style(&t.first_style()).unwrap();
assert!((effective.size - 24.0).abs() < 1e-8, "sampled font size: {}", effective.size);
assert!((effective.h_scale - 150.0).abs() < 1e-8, "sampled horizontal scale: {}", effective.h_scale);
assert_eq!(t.xf, old.xf, "sampling keeps the target's transform");
assert_eq!(node(&s, src), source);
assert_eq!(undo_len(&s), history + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(node(&s, dst), before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(node(&s, dst), after);
}
}
}
/// A text object snapshot, including the local attributes and retained affine transform.
fn sampled_type(s: &Session, id: NodeId) -> vectorcraft_doc::TextObject {
let NodeKind::Text(t) = node(s, id).kind else { panic!("not text") };
*t
}
/// Compare the dimensional character attributes that text controls display in document units.
fn assert_sampled_dimensions(actual: &vectorcraft_doc::CharStyle, expected: &vectorcraft_doc::CharStyle) {
assert_eq!(actual.leading.is_some(), expected.leading.is_some());
for (a, e) in [
(actual.size, expected.size),
(actual.h_scale, expected.h_scale),
(actual.v_scale, expected.v_scale),
(actual.leading.unwrap_or(0.0), expected.leading.unwrap_or(0.0)),
(actual.baseline_shift, expected.baseline_shift),
(actual.tcy_up_down, expected.tcy_up_down),
(actual.tcy_left_right, expected.tcy_left_right),
] {
assert!((a - e).abs() < 1e-8, "sampled dimension: {a} != {e}");
}
}
/// Rotation, shear, reflection and grouping stay on the objects while typography is copied.
#[test]
fn scaled_type_pick_preserves_affines_and_document_dimensions() {
for grouped in [false, true] {
let mut s = session();
let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": 12})).unwrap());
s.execute("text.setStyle", &json!({"leading": 18})).unwrap();
s.execute("text.setFormat", &json!({"hScale": 80, "vScale": 125, "baselineShift": 3, "tcyUpDown": 2, "tcyLeftRight": -1})).unwrap();
if grouped {
s.execute("object.group", &json!({})).unwrap();
}
s.execute("object.transform", &json!({"matrix": [0, -3, -2, 1, 0, 0]})).unwrap();
let src_text = sampled_type(&s, src);
let expected = src_text.effective_char_style(&src_text.first_style()).unwrap();
let dst = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Target", "size": 20})).unwrap());
if grouped {
s.execute("object.group", &json!({})).unwrap();
}
s.execute("object.transform", &json!({"matrix": [-1, 0.5, 1, 2, 0, 0]})).unwrap();
let before = sampled_type(&s, dst);
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
let after = sampled_type(&s, dst);
assert_sampled_dimensions(&after.effective_char_style(&after.first_style()).unwrap(), &expected);
assert_eq!(after.xf, before.xf);
assert_eq!(sampled_type(&s, src), src_text);
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
let reopened = vectorcraft_format::load(&bytes).unwrap();
let NodeKind::Text(t) = &reopened.node(dst).unwrap().kind else { panic!("not text") };
assert_sampled_dimensions(&t.effective_char_style(&t.first_style()).unwrap(), &expected);
}
}
/// A transformed target compensates only the highlighted characters, retaining the others.
#[test]
fn scaled_type_pick_changes_only_the_highlighted_range() {
let mut s = session();
let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": 12})).unwrap());
s.execute("object.transform", &json!({"matrix": [3, 0, 0, 2, 0, 0]})).unwrap();
let source = sampled_type(&s, src);
let expected = source.effective_char_style(&source.first_style()).unwrap();
let dst = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Sample", "size": 10})).unwrap());
s.execute("object.transform", &json!({"matrix": [0.5, 0, 0, 3, 0, 0]})).unwrap();
let before = sampled_type(&s, dst);
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"id": dst.0, "start": 1, "end": 4}));
s.select_tool("eyedropper", ViewInfo::default()).unwrap();
let history = undo_len(&s);
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
let after = sampled_type(&s, dst);
assert_eq!(after.runs.len(), 3);
assert_eq!((&*after.runs[0].text, &*after.runs[1].text, &*after.runs[2].text), ("S", "amp", "le"));
assert_eq!(after.runs[0].style, before.first_style());
assert_eq!(after.runs[2].style, before.first_style());
assert_sampled_dimensions(&after.effective_char_style(&after.runs[1].style).unwrap(), &expected);
assert_eq!(after.xf, before.xf);
assert_eq!(undo_len(&s), history + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(sampled_type(&s, dst), before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(sampled_type(&s, dst), after);
}
/// Reject unusable source or target transforms before any part of a multi-object pick changes.
#[test]
fn scaled_type_pick_rejects_unrepresentable_dimensions_atomically() {
for (bad_source, factor) in [(true, 0.0), (false, 0.0), (false, 1e-306), (true, f64::from_bits(1))] {
let mut s = session();
let size = if bad_source && factor > 0.0 { 0.1 } else { 24.0 };
let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": size, "color": "#00ff00"})).unwrap());
if bad_source {
s.execute("object.transform", &json!({"matrix": [factor, 0, 0, factor, 0, 0]})).unwrap();
}
let good = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Good", "size": 10})).unwrap());
let other = id_of(s.execute("text.create", &json!({"x": 300, "y": 200, "text": "Other", "size": 12})).unwrap());
if !bad_source {
s.execute("object.transform", &json!({"matrix": [factor, 0, 0, factor, 0, 0]})).unwrap();
}
s.execute("select.set", &json!({"ids": [good.0, other.0]})).unwrap();
let doc = s.doc().unwrap().doc.clone();
let selection = s.doc().unwrap().selection.clone();
let paint = s.paint.clone();
let sample = s.eyedropper_sample.clone();
let history = undo_len(&s);
let error = s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap_err();
assert!(error.to_string().contains("transform"), "{error}");
assert_eq!(s.doc().unwrap().doc, doc);
assert_eq!(s.doc().unwrap().selection, selection);
assert_eq!(s.paint, paint);
assert_eq!(s.eyedropper_sample, sample);
assert_eq!(undo_len(&s), history);
// A paint-only pick does not need a usable text transform.
s.execute("appearance.copyFrom", &json!({"source": src.0, "apply": {"character": false, "paragraph": false}})).unwrap();
}
}
/// A failed dimensional pick retains highlighted characters and the previously remembered sample.
#[test]
fn scaled_type_pick_rejection_preserves_the_highlighted_range_and_sample() {
let mut s = session();
let saved = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Saved", "size": 18})).unwrap());
s.execute("select.none", &json!({})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": saved.0})).unwrap();
let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Source", "size": 24, "color": "#00ff00"})).unwrap());
s.execute("object.transform", &json!({"matrix": [0, 0, 0, 0, 0, 0]})).unwrap();
let dst = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Sample", "size": 10})).unwrap());
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"id": dst.0, "start": 1, "end": 4}));
s.select_tool("eyedropper", ViewInfo::default()).unwrap();
let doc = s.doc().unwrap().doc.clone();
let selection = s.doc().unwrap().selection.clone();
let range = s.tool_options();
let paint = s.paint.clone();
let sample = s.eyedropper_sample.clone();
let history = undo_len(&s);
assert!(s.execute("appearance.copyFrom", &json!({"source": src.0})).is_err());
assert_eq!(s.doc().unwrap().doc, doc);
assert_eq!(s.doc().unwrap().selection, selection);
assert_eq!(s.tool_options(), range);
assert_eq!(s.paint, paint);
assert_eq!(s.eyedropper_sample, sample);
assert_eq!(undo_len(&s), history);
// Alt-click can still apply the last successful sample after the rejected pick.
s.execute("select.none", &json!({})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": dst.0, "reverse": true})).unwrap();
assert_eq!(sampled_type(&s, dst).first_style().size, 18.0);
}
/// A pick that would extend text beyond the canvas keeps the previous sample and defaults.
#[test]
fn scaled_type_pick_canvas_rejection_preserves_sample_and_defaults() {
for mode in ["selection", "ids", "reverse", "range"] {
let mut s = session();
let saved = id_of(s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Saved", "size": 18, "color": "#0000ff"})).unwrap());
let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": 96, "color": "#ff0000"})).unwrap());
let dst = id_of(s.execute("text.create", &json!({"x": MAX_COORD - 100.0, "y": 200, "text": "WWWW", "size": 10})).unwrap());
s.execute("appearance.copyFrom", &json!({"source": saved.0, "ids": []})).unwrap();
let pick = match mode {
"ids" | "reverse" => {
s.execute("select.none", &json!({})).unwrap();
if mode == "ids" { json!({"source": src.0, "ids": [dst.0]}) } else { json!({"source": dst.0, "ids": [src.0], "reverse": true}) }
}
"range" => {
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"id": dst.0, "start": 0, "end": 3}));
s.select_tool("eyedropper", ViewInfo::default()).unwrap();
json!({"source": src.0})
}
_ => json!({"source": src.0}),
};
let doc = s.doc().unwrap().doc.clone();
let selection = s.doc().unwrap().selection.clone();
let range = s.tool_options();
let paint = s.paint.clone();
let sample = s.eyedropper_sample.clone();
let history = undo_len(&s);
let error = s.execute("appearance.copyFrom", &pick).unwrap_err();
assert!(error.to_string().contains("coordinates out of range"), "{mode}: {error}");
assert_eq!(s.doc().unwrap().doc, doc, "{mode}");
assert_eq!(s.doc().unwrap().selection, selection, "{mode}");
assert_eq!(s.tool_options(), range, "{mode}");
assert_eq!(s.paint, paint, "{mode}");
assert_eq!(s.eyedropper_sample, sample, "{mode}");
assert_eq!(undo_len(&s), history, "{mode}");
}
}
/// Changing justification can move explicitly targeted point text outside the canvas even
/// when character copying is disabled.
#[test]
fn paragraph_only_pick_rejects_out_of_bounds_explicit_target() {
let mut s = session();
let saved = id_of(s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Saved", "color": "#0000ff"})).unwrap());
let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "color": "#ff0000"})).unwrap());
s.execute("text.setStyle", &json!({"justify": "left"})).unwrap();
let dst = id_of(s.execute("text.create", &json!({"x": 100, "y": 200, "text": "WWWW", "size": 16})).unwrap());
s.execute("text.setStyle", &json!({"justify": "right"})).unwrap();
s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, MAX_COORD - 101.0, 0]})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": saved.0, "ids": []})).unwrap();
let doc = s.doc().unwrap().doc.clone();
let selection = s.doc().unwrap().selection.clone();
let paint = s.paint.clone();
let sample = s.eyedropper_sample.clone();
let history = undo_len(&s);
let pick = json!({"source": src.0, "ids": [dst.0], "apply": {"character": false}});
let error = s.execute("appearance.copyFrom", &pick).unwrap_err();
assert!(error.to_string().contains("coordinates out of range"), "{error}");
assert_eq!(s.doc().unwrap().doc, doc);
assert_eq!(s.doc().unwrap().selection, selection);
assert_eq!(s.paint, paint);
assert_eq!(s.eyedropper_sample, sample);
assert_eq!(undo_len(&s), history);
}
/// Disabled character copying and append preserve typography; reverse and cached picks convert it.
#[test]
fn scaled_type_pick_respects_options_and_reverse_sampling() {
let mut s = session();
let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": 12})).unwrap());
s.execute("object.scale", &json!({"sx": 300, "sy": 200})).unwrap();
let source = sampled_type(&s, src);
let expected = source.effective_char_style(&source.first_style()).unwrap();
let dst = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Target", "size": 20})).unwrap());
s.execute("object.scale", &json!({"sx": 50, "sy": 150})).unwrap();
let before = sampled_type(&s, dst);
for options in [json!({"pickUp": {"character": false}}), json!({"apply": {"character": false}}), json!({"append": true})] {
let mut p = json!({"source": src.0, "ids": [dst.0]});
p.as_object_mut().unwrap().extend(options.as_object().unwrap().clone());
s.execute("appearance.copyFrom", &p).unwrap();
assert_sampled_dimensions(&sampled_type(&s, dst).first_style(), &before.first_style());
}
s.execute("select.set", &json!({"ids": [src.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": dst.0, "reverse": true})).unwrap();
let after = sampled_type(&s, dst);
assert_sampled_dimensions(&after.effective_char_style(&after.first_style()).unwrap(), &expected);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": dst.0, "reverse": true})).unwrap();
let cached = sampled_type(&s, dst);
assert_sampled_dimensions(&cached.effective_char_style(&cached.first_style()).unwrap(), &expected);
}
#[test]
fn alt_click_applies_the_selection_to_the_clicked_object() {
let mut s = session();
+48
View File
@@ -450,6 +450,54 @@ fn objects_without_transparency_stay_unless_outlined() {
}
}
/// A row of opaque rectangles 1.5 pt apart (closer than twice the antialiasing margin), with a
/// see-through one touching each end: only the two next to a see-through one are flattened, and
/// the document looks the same.
#[test]
fn opaque_art_that_touches_only_opaque_art_stays() {
let _settings = settings_lock();
let mut s = session();
let under = rect(&mut s, 0.0, 50.0, 10.0, 10.0, "#2060c0");
run(&mut s, "transparency.set", json!({"ids": [under], "opacity": 50}));
let row: Vec<u64> = (1..15).map(|i| rect(&mut s, 11.5 * f64::from(i), 50.0, 10.0, 10.0, "#e04010")).collect();
let over = rect(&mut s, 11.5 * 15.0, 50.0, 10.0, 10.0, "#20a040");
run(&mut s, "transparency.set", json!({"ids": [over], "opacity": 50, "blend": "Multiply"}));
let before = picture(&s);
run(&mut s, "select.all", json!({}));
let (ids, vector, rasterized) = flatten(&mut s, json!({}));
assert_eq!((vector, rasterized), (4, 0), "two groups of two regions each");
let (ends, kept) = (row[0], row.last().copied().unwrap());
assert!(!exists(&s, under) && !exists(&s, over) && !exists(&s, ends) && !exists(&s, kept));
assert!(row[1..row.len() - 1].iter().all(|id| exists(&s, *id) && ids.contains(id)), "the rest of the row stays");
assert_eq!(ids.len(), row.len() - 2 + 2);
let diff = changed(&before, &picture(&s));
assert!(diff == 0.0, "{:.2}% of the pixels changed", diff * 100.0);
}
/// Opaque art between a see-through object's group and the top of that group, painting over a
/// member, joins the group (along a chain too), so it still paints over it; opaque art under the
/// group stays.
#[test]
fn opaque_art_the_group_would_move_under_joins_it() {
let _settings = settings_lock();
let mut s = session();
let d = rect(&mut s, 40.0, 80.0, 25.0, 40.0, "#f0d000");
let a = rect(&mut s, 60.0, 50.0, 45.0, 40.0, "#e01010");
let b = rect(&mut s, 20.0, 20.0, 45.0, 35.0, "#10a010");
let c = rect(&mut s, 0.0, 0.0, 25.0, 25.0, "#1010e0");
let t = rect(&mut s, 100.0, 50.0, 40.0, 40.0, "#000000");
run(&mut s, "transparency.set", json!({"ids": [t], "opacity": 50}));
let before = picture(&s);
let (ids, ..) = flatten(&mut s, json!({"ids": [d, a, b, c, t]}));
assert!(exists(&s, d) && ids.contains(&d), "the art under the group stays");
assert!([a, b, c, t].iter().all(|id| !exists(&s, *id)), "the others are flattened together");
// Where B paints over A, and C over B, they still do.
for p in [Point::new(62.5, 52.5), Point::new(22.5, 22.5), Point::new(62.5, 85.5), Point::new(102.5, 70.5)] {
assert_eq!(pixel(&picture(&s), p), pixel(&before, p), "at {p:?}");
}
assert!(changed(&before, &picture(&s)) == 0.0);
}
#[test]
fn outlined_type_keeps_its_underline() {
let _settings = settings_lock();
+136 -2
View File
@@ -32,7 +32,7 @@ fn fill_gradient(s: &Session, id: NodeId) -> GradientPaint {
#[test]
fn new_gradient_defaults_follow_the_cmyk_document_mode() {
for kind in ["linear", "radial", "conic", "freeform"] {
for kind in ["linear", "radial", "conic", "diamond", "freeform"] {
let mut s = Session::new();
s.execute("file.new", &json!({"width":200,"height":200,"colorMode":"cmyk"})).unwrap();
let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0);
@@ -586,7 +586,7 @@ fn a_conic_gradient_is_set_edited_transformed_and_saved() {
assert_eq!(fill_gradient(&s, id).gradient.kind, GradientKind::Conic, "{name}");
}
let e = s.execute("paint.editGradient", &json!({"kind": "spiral"})).unwrap_err().to_string();
assert!(e.contains("(linear, radial, conic, freeform)"), "{e}");
assert!(e.contains("(linear, radial, conic, diamond, freeform)"), "{e}");
// Placed, an angle turns the vector about the center.
s.execute("paint.setGradientGeom", &json!({"start": [200, 150], "end": [260, 150], "aspect": 50})).unwrap();
s.execute("paint.editGradient", &json!({"angle": 90})).unwrap();
@@ -747,3 +747,137 @@ fn making_a_gradient_conic_is_one_undo_step() {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(fill_gradient(&s, id), before);
}
/// A diamond gradient through `paint.setFill`, the Gradient panel's edits, transforms, the params
/// agents and swatches read, and the native format.
#[test]
fn a_diamond_gradient_is_set_edited_transformed_and_saved() {
let mut s = session();
let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond"}})).unwrap();
let g = fill_gradient(&s, id);
assert_eq!(g.gradient.kind, GradientKind::Diamond);
// Unplaced, it runs from the box's center out to a square whose edges pass through the box's
// corners.
let geom = g.resolve(node(&s, id).geometric_bounds().unwrap());
assert_eq!((geom.start, geom.end), (Point::new(200.0, 150.0), Point::new(350.0, 150.0)));
for (p, t) in [
(Point::new(300.0, 200.0), 1.0),
(Point::new(100.0, 100.0), 1.0),
(Point::new(250.0, 150.0), 1.0 / 3.0),
(Point::new(200.0, 175.0), 1.0 / 6.0),
] {
assert!((geom.param_at(GradientKind::Diamond, p) - t).abs() < 1e-9, "{p:?}");
}
s.execute("paint.editGradient", &json!({"kind": "linear"})).unwrap();
s.execute("paint.editGradient", &json!({"kind": "DIAMOND"})).unwrap();
assert_eq!(fill_gradient(&s, id).gradient.kind, GradientKind::Diamond);
let e = s.execute("paint.editGradient", &json!({"kind": "spiral"})).unwrap_err().to_string();
assert!(e.contains("(linear, radial, conic, diamond, freeform)"), "{e}");
// Placed, an angle turns the vector about the center.
s.execute("paint.setGradientGeom", &json!({"start": [200, 150], "end": [260, 150], "aspect": 50})).unwrap();
s.execute("paint.editGradient", &json!({"angle": 90})).unwrap();
let g = fill_geom(&s, id);
assert!(g.start.distance(Point::new(200.0, 150.0)) < 1e-9 && g.end.distance(Point::new(200.0, 90.0)) < 1e-9, "{g:?}");
// A reflection keeps each point's color.
let p = Point::new(230.0, 170.0);
let before = g.param_at(GradientKind::Diamond, p);
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
let m = fill_geom(&s, id);
assert!(m.aspect > 0.0, "{m:?}");
assert!((m.param_at(GradientKind::Diamond, Point::new(170.0, 170.0)) - before).abs() < 1e-9);
// A rotation carries it along.
let before = m.param_at(GradientKind::Diamond, p);
s.execute("object.rotate", &json!({"angle": 30, "origin": [200, 150]})).unwrap();
let r = vectorcraft_geom::Affine::rotate_about(-30f64.to_radians(), Point::new(200.0, 150.0));
let after = fill_geom(&s, id).param_at(GradientKind::Diamond, r * p);
assert!((after - before).abs() < 1e-9, "{before} vs {after}");
// The params give it back, and the native format keeps it.
s.execute("paint.editGradient", &json!({"aspect": 60})).unwrap();
let want = fill_gradient(&s, id);
let params = vectorcraft_tools::params::gradient_params(&want);
assert_eq!((params["kind"].as_str(), params["aspect"].as_f64()), (Some("diamond"), Some(60.0)));
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
s.execute("paint.setFill", &json!({ "gradient": params })).unwrap();
let got = fill_gradient(&s, id);
assert_eq!((&got.gradient, got.geom), (&want.gradient, want.geom));
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
let Paint::Gradient(g) = back.node(id).unwrap().appearance.fill_paint() else { panic!("the gradient is lost") };
assert_eq!((g.gradient.kind, g.geom), (GradientKind::Diamond, want.geom));
}
/// A diamond refuses a negative aspect and a focal point, from every command that gives one, and
/// the gradient stays as it was; a null focal point is allowed.
#[test]
fn a_diamond_refuses_a_negative_aspect_and_a_focal_point() {
let mut s = session();
let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond", "start": [200, 150], "end": [260, 150], "aspect": 50}})).unwrap();
let before = fill_gradient(&s, id);
for p in [
json!({"gradient": {"kind": "diamond", "aspect": -50}}),
json!({"gradient": {"kind": "diamond", "start": [0, 0], "end": [10, 0], "aspect": -50}}),
] {
assert!(s.execute("paint.setFill", &p).unwrap_err().to_string().contains("aspect"), "{p}");
}
assert!(s.execute("paint.editGradient", &json!({"aspect": -50})).is_err());
assert!(s.execute("paint.setGradientGeom", &json!({"aspect": -50})).is_err());
assert!(s.execute("paint.editGradient", &json!({"kind": "radial", "aspect": -50})).is_err());
let e = s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond", "start": [200, 150], "end": [260, 150], "focal": [210, 150]}}));
assert!(e.unwrap_err().to_string().contains("focal"));
assert!(s.execute("paint.setGradientGeom", &json!({"focal": [210, 150]})).unwrap_err().to_string().contains("focal"));
assert_eq!(fill_gradient(&s, id), before);
s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond", "start": [200, 150], "end": [260, 150], "focal": null}})).unwrap();
assert_eq!(fill_gradient(&s, id).geom.unwrap().focal, None);
}
/// A free distort that is not affine moves a diamond by the warp near its center, as it moves a
/// radial gradient.
#[test]
fn a_warp_moves_a_diamond_by_its_center() {
let warped = |kind: &str| {
let mut s = session();
let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
s.execute("paint.setFill", &json!({"gradient": {"kind": kind, "start": [20, 30], "end": [90, 30], "aspect": 60}})).unwrap();
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 0], [140, 130], [-20, 100]]})).unwrap();
fill_geom(&s, id)
};
let (diamond, radial) = (warped("diamond"), warped("radial"));
assert!(diamond.start.distance(radial.start) < 1e-9, "{diamond:?} vs {radial:?}");
}
/// Saved as `.ai`, as PDF with its editing data and as SVG with its editing data, then opened, a
/// turned, squashed diamond comes back as it was.
#[test]
fn a_diamond_survives_saving_as_ai_pdf_and_svg() {
let mut s = session();
let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond", "start": [180, 140], "end": [240, 110], "aspect": 60}})).unwrap();
let want = fill_gradient(&s, id);
for format in ["ai", "pdf", "svg"] {
let r = s.execute("file.saveCopy", &json!({"format": format, "preserveEditing": true})).unwrap();
let mut back = session();
back.execute("document.open", &json!({"name": format!("t.{format}"), "dataBase64": r["dataBase64"]})).unwrap();
let mut found = None;
back.doc().unwrap().doc.walk(|n| {
if let (None, Paint::Gradient(g)) = (&found, n.appearance.fill_paint()) {
found = Some(*g.clone());
}
});
let got = found.unwrap_or_else(|| panic!("{format}: the gradient is lost"));
assert_eq!((got.gradient.kind, got.geom), (GradientKind::Diamond, want.geom), "{format}");
}
}
/// Turning a gradient diamond is one undo step, and undoing it gives the gradient back as it was.
#[test]
fn making_a_gradient_diamond_is_one_undo_step() {
let mut s = session();
let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
s.execute("paint.setFill", &json!({"gradient": {"kind": "radial"}})).unwrap();
let (before, steps) = (fill_gradient(&s, id), s.doc().unwrap().history.undo.len());
s.execute("paint.editGradient", &json!({"kind": "diamond", "angle": 45})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(fill_gradient(&s, id), before);
}
+53
View File
@@ -296,6 +296,59 @@ fn link_info_stays_within_the_asking_callers_roots() {
assert_ne!(i["status"], "ok", "{i}");
}
/// A confined caller's `links.list`, `links.check` and `links.info` replies, and its
/// `document.open` reply, leave out the path and folder of a linked file outside its read roots
/// and keep the row with the file's name. A file found by name inside the roots shows its path.
#[test]
fn link_paths_outside_the_read_roots_are_left_out() {
let away = Folder::new("lrr-away");
let home = Folder::new("lrr-home");
let pic = away.file("photo.png");
let bytes = png(60, 30, RED);
write(&pic, &bytes);
let mut s = session();
let id = place(&mut s, &pic);
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[]).unwrap().unwrap();
let ask = |s: &mut Session, cmd: &str, p: Value| crate::file_access::confine(Some(&roots), || run(s, cmd, p));
let hidden = |r: &Value| assert!(!r.to_string().contains("lrr-away"), "{r}");
let list = ask(&mut s, "links.list", json!({}));
hidden(&list);
let row = &list["links"][0];
assert_eq!((row["id"].as_u64(), row["name"].as_str(), row["status"].as_str()), (Some(id.0), Some("photo.png"), Some("missing")), "{list}");
let check = ask(&mut s, "links.check", json!({}));
hidden(&check);
assert_eq!((check["links"][0]["name"].as_str(), check["missing"].as_u64()), (Some("photo.png"), Some(1)), "{check}");
let info = ask(&mut s, "links.info", json!({"id": id.0}));
hidden(&info);
assert_eq!(
(info["fileName"].as_str(), info["status"].as_str(), info["linked"].as_bool()),
(Some("photo.png"), Some("missing"), Some(true)),
"{info}"
);
for k in ["path", "link", "location", "fileSize", "modified", "created"] {
assert!(info.get(k).is_none(), "{k}: {info}");
}
// Unconfined, the same replies carry the paths.
assert_eq!(run(&mut s, "links.list", json!({}))["links"][0]["path"], json!(pic));
let i = run(&mut s, "links.info", json!({"id": id.0}));
assert_eq!((&i["path"], &i["link"], i["fileSize"].as_u64()), (&json!(pic), &json!(pic), Some(bytes.len() as u64)), "{i}");
// Saved inside the roots next to a copy of the file: the copy is found by name and shown.
save(&mut s, &home.file("poster.vectorcraft"));
let copy = home.file("photo.png");
write(&copy, &bytes);
let check = ask(&mut s, "links.check", json!({}));
hidden(&check);
assert_eq!((check["links"][0]["status"].as_str(), &check["links"][0]["found"]), (Some("ok"), &json!(copy)), "{check}");
let list = ask(&mut s, "links.list", json!({}));
hidden(&list);
assert_eq!(list["links"][0]["found"], json!(copy), "{list}");
// Opened again without the copy: the missing link's row has no path.
std::fs::remove_file(&copy).unwrap();
let opened = ask(&mut Session::new(), "document.open", json!({"path": home.file("poster.vectorcraft")}));
hidden(&opened);
assert_eq!(opened["missingLinks"][0]["name"], "photo.png", "{opened}");
}
/// A 600×300 pt image at the centre of the artboard, its placement options set to `options`,
/// relinked to a 300×100 px file → the image's id and session.
fn relinked(name: &str, options: Value) -> (Session, NodeId, Folder) {
+51
View File
@@ -292,6 +292,57 @@ fn a_saved_preset_with_the_resolution_out_of_range_reads_in_range() {
assert_eq!(s.doc().unwrap().doc.raster_effects_ppi, 1.0);
}
/// Advanced Options › Align New Objects to Pixel Grid starts on in the Mobile and Web presets and
/// off in the others and without a preset; a `file.new` param overrides the preset; the document
/// takes the value; saved presets and Recent keep it, and a saved preset from before it reads off.
#[test]
fn align_new_objects_to_pixel_grid_follows_the_preset() {
let align = |s: &Session| s.doc().unwrap().doc.setup.align_new_objects_to_pixel_grid;
let mut s = Session::new();
for category in ["Mobile", "Web"] {
assert!(presets(&mut s, category).iter().all(|p| p["alignNewObjectsToPixelGrid"] == true), "{category}");
}
for category in ["Print", "Film & Video", "Art & Illustration", "Branding", "Social"] {
assert!(presets(&mut s, category).iter().all(|p| p["alignNewObjectsToPixelGrid"] == false), "{category}");
}
s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap();
assert!(align(&s));
assert_eq!(presets(&mut s, "Recent")[0]["alignNewObjectsToPixelGrid"], true);
s.execute("file.new", &json!({"preset": "Phone 390×844"})).unwrap();
assert!(align(&s));
s.execute("file.new", &json!({"preset": "Letter"})).unwrap();
assert!(!align(&s));
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
assert!(!align(&s));
s.execute("file.new", &json!({"preset": "Web 1920×1080", "alignNewObjectsToPixelGrid": false})).unwrap();
assert!(!align(&s));
s.execute("file.new", &json!({"preset": "A4", "alignNewObjectsToPixelGrid": true})).unwrap();
assert!(align(&s));
assert!(Session::new().execute("file.new", &json!({"alignNewObjectsToPixelGrid": "on"})).is_err());
// A Recent entry passed back makes the document it was made as.
let recent = presets(&mut s, "Recent")[0].clone();
assert_eq!((recent["name"].as_str(), recent["alignNewObjectsToPixelGrid"].as_bool()), (Some("A4"), Some(true)));
s.execute("file.new", &recent).unwrap();
assert!(align(&s));
// Saved presets keep it.
s.execute("file.newPresets.save", &json!({"name": "Icons", "width": 64, "height": 64, "alignNewObjectsToPixelGrid": true})).unwrap();
s.execute("file.newPresets.save", &json!({"name": "Banner", "preset": "Web 1920×1080", "alignNewObjectsToPixelGrid": false})).unwrap();
let saved: Vec<Value> = presets(&mut s, "Saved").iter().map(|p| p["alignNewObjectsToPixelGrid"].clone()).collect();
assert_eq!(saved, [json!(true), json!(false)]);
s.execute("file.new", &json!({"preset": "Icons"})).unwrap();
assert!(align(&s));
s.execute("file.new", &json!({"preset": "Banner"})).unwrap();
assert!(!align(&s));
let prefs: crate::Prefs = serde_json::from_value(s.prefs.to_json()).unwrap();
assert_eq!(prefs.new_doc_presets, s.prefs.new_doc_presets);
// A saved preset from before the setting reads off, whatever its name.
let mut old = Session::new();
old.apply_prefs(serde_json::from_value(json!({"newDocPresets": [{"name": "My Web", "width": 100, "height": 100}]})).unwrap());
assert_eq!(presets(&mut old, "Saved")[0]["alignNewObjectsToPixelGrid"], false);
old.execute("file.new", &json!({"preset": "My Web"})).unwrap();
assert!(!align(&old));
}
#[test]
fn rearrange_keeps_its_grid() {
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3}));
+71
View File
@@ -393,6 +393,77 @@ fn a_mirrored_or_flat_conic_expands_as_the_canvas_draws_it() {
}
}
/// Three opaque stops running from the center out to the square.
fn diamond_stops() -> Value {
json!({"kind": "diamond", "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 0.5, "color": "#ff00ff"}, {"offset": 1, "color": "#004080"}]})
}
#[test]
fn a_diamond_gradient_becomes_nested_squares_or_a_mesh_that_paint_it() {
// Objects: nested squares about the center, largest first, together painting what the
// canvas painted.
let mut s = session();
gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), diamond_stops(), false);
let before = render(&s);
run(&mut s, "object.expand", json!({"steps": 120}));
let g = selected(&s);
let (_, squares) = clip_parts(&g);
assert_eq!(squares.len(), 120);
let corners = |n: &Node| n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect::<Vec<_>>();
let (outer, inner) = (corners(squares[0]), corners(squares[119]));
assert_eq!((outer.len(), inner.len()), (4, 4));
let reach = |pts: &[vectorcraft_geom::Point]| pts.iter().map(|p| p.distance(vectorcraft_geom::Point::new(100.0, 100.0))).fold(0.0, f64::max);
assert!(reach(&outer) > reach(&inner) * 100.0, "largest first: {outer:?} then {inner:?}");
let after = render(&s);
assert!(differing(&before, &after, 48) < 200, "{}", differing(&before, &after, 48));
assert!(mean_diff(&before, &after) < 2.0, "{}", mean_diff(&before, &after));
// Translucent stops: each square is a ring with the next one cut out, so none doubles up.
let mut s = session();
let gr = json!({"kind": "diamond", "stops": [{"offset": 0, "color": "#ff0000", "opacity": 0.5}, {"offset": 1, "color": "#0000ff"}]});
gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gr, false);
let before = render(&s);
run(&mut s, "object.expand", json!({"steps": 60}));
let g = selected(&s);
let (_, squares) = clip_parts(&g);
assert!(squares[..59].iter().all(|n| n.path_data().unwrap().subpaths.len() == 2), "rings");
assert!(mean_diff(&before, &render(&s)) < 4.0, "{}", mean_diff(&before, &render(&s)));
// Mesh: rings of patches about the center.
let mut s = session();
gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), diamond_stops(), false);
let before = render(&s);
run(&mut s, "object.expand", json!({"gradient": "mesh"}));
let g = selected(&s);
let (_, content) = clip_parts(&g);
let NodeKind::Mesh(m) = &content[0].kind else { panic!("a mesh node: {:?}", content[0].kind) };
assert!(m.is_valid());
let after = render(&s);
assert!(differing(&before, &after, 48) < 200, "{}", differing(&before, &after, 48));
assert!(mean_diff(&before, &after) < 2.5, "{}", mean_diff(&before, &after));
}
/// A turned, squashed diamond, and one whose square is flat (as a file can hold it), expand as
/// the canvas draws them.
#[test]
fn a_turned_or_flat_diamond_expands_as_the_canvas_draws_it() {
for aspect in [0.6, 0.0] {
for how in [json!({"steps": 120}), json!({"gradient": "mesh"})] {
let mut s = session();
let id = gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), diamond_stops(), false);
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let n = d.node_mut(id).unwrap();
let Paint::Gradient(mut g) = n.appearance.fill_paint().clone() else { panic!("a gradient fill") };
let (start, end) = (vectorcraft_geom::Point::new(90.0, 110.0), vectorcraft_geom::Point::new(130.0, 80.0));
g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect, focal: None });
n.appearance.set_fill(Paint::Gradient(g));
let before = render(&s);
run(&mut s, "object.expand", how.clone());
let after = render(&s);
assert!(differing(&before, &after, 48) < 200, "{aspect} {how}: {}", differing(&before, &after, 48));
assert!(mean_diff(&before, &after) < 2.5, "{aspect} {how}: {}", mean_diff(&before, &after));
}
}
}
#[test]
fn the_mesh_option_makes_a_mesh_that_paints_the_gradient() {
for gradient in [
+3 -4
View File
@@ -73,14 +73,13 @@ fn arrowheads_are_part_of_the_outline() {
assert_eq!(path_of(&n).subpaths.len(), 1, "line and head are one shape");
}
/// Outline Stroke of a Lens-profile line covers 7/12 of the full-width rectangle.
/// Outline Stroke of a Lens-profile line covers 2/3 of the full-width rectangle.
#[test]
fn a_lens_profile_outlines_to_seven_twelfths_of_the_rectangle() {
fn a_lens_profile_outlines_to_two_thirds_of_the_rectangle() {
let mut s = session();
line(&mut s, json!({"weight": 10, "profile": "lens"}));
let n = outline(&mut s);
// Each half of the lens swells on a cubic, flat at the middle (#5714).
assert!(near(area(&n), 7.0 / 12.0 * 10.0 * 100.0, 2.0), "{}", area(&n));
assert!(near(area(&n), 2.0 / 3.0 * 10.0 * 100.0, 2.0), "{}", area(&n));
}
#[test]
+125
View File
@@ -767,6 +767,131 @@ fn objects_on_path_members_stay_on_the_grid() {
assert!(points(&s, a).iter().all(|(_, y)| *y > 105.0), "followed the path: {:?}", points(&s, a));
}
fn align_new(s: &Session) -> bool {
s.doc().unwrap().doc.setup.align_new_objects_to_pixel_grid
}
/// Align New Objects to Pixel Grid (`document.setup`): while it is on, a rectangle and an open path
/// drawn in the document are pixel-aligned and snapped in the step that makes them, and type is
/// not; art already in the document, duplicates and pastes keep their own setting; turning it off
/// leaves the next drawing as it is drawn, and the object's own setting can be turned off while
/// the document's stays on.
#[test]
fn align_new_objects_makes_new_paths_pixel_aligned() {
let mut s = new_doc();
assert!(!align_new(&s));
assert_eq!(s.execute("document.setup", &json!({})).unwrap()["alignNewObjectsToPixelGrid"], false);
let old = path(&mut s, "M10.3 120.6 L40.7 120.6 L40.7 130.3 L10.3 130.3 Z", 2.0);
let old_points = points(&s, old);
let steps = undo_len(&s);
let r = s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
assert_eq!(r["alignNewObjectsToPixelGrid"], true);
assert!(align_new(&s));
assert_eq!(undo_len(&s), steps + 1, "one undo step");
// Art already in the document stays as it was.
assert!(!aligned(&s, old));
assert_eq!(points(&s, old), old_points);
// A rectangle is drawn pixel-aligned: with the 2 pt stroke `path` left as the current one, its
// edges go to whole points.
let steps = undo_len(&s);
let rect = s.execute("shape.rectangle", &json!({"x": 10.3, "y": 20.6, "width": 30.4, "height": 9.7})).unwrap()["id"].as_u64().unwrap();
assert!(aligned(&s, rect));
assert_eq!(points(&s, rect), [(10.0, 21.0), (41.0, 21.0), (41.0, 30.0), (10.0, 30.0)]);
assert_eq!(undo_len(&s), steps + 1, "made and snapped in one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(NodeId(rect)).is_none());
s.execute("edit.redo", &json!({})).unwrap();
assert!(aligned(&s, rect));
// An open path from the Pen.
let line = s.execute("path.create", &json!({"anchors": [{"x": 50.3, "y": 60.2}, {"x": 90.6, "y": 60.2}]})).unwrap()["id"].as_u64().unwrap();
assert!(aligned(&s, line));
// Its horizontal segment goes to a whole point.
assert!(points(&s, line).iter().all(|(_, y)| *y == 60.0), "{:?}", points(&s, line));
// Type cannot be pixel-aligned.
let text = s.execute("text.create", &json!({"x": 10.3, "y": 200.6, "text": "Hi"})).unwrap()["id"].as_u64().unwrap();
assert!(!aligned(&s, text));
// A duplicate and a paste of art that is not pixel-aligned keep it so.
s.execute("select.set", &json!({"ids": [old]})).unwrap();
s.execute("edit.duplicate", &json!({"dx": 100.3, "dy": 0.4})).unwrap();
let copy = s.doc().unwrap().selection.objects[0].0;
assert!(copy != old && !aligned(&s, copy));
s.execute("select.set", &json!({"ids": [old]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
let pasted = s.doc().unwrap().selection.objects[0].0;
assert!(pasted != old && pasted != copy && !aligned(&s, pasted));
// The object's own setting turns off while the document's stays on.
s.execute("object.setPixelAligned", &json!({"ids": [rect], "on": false})).unwrap();
assert!(!aligned(&s, rect) && align_new(&s));
// Off: the next rectangle is drawn as it is given, and the first one stays pixel-aligned.
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": false})).unwrap();
let plain = s.execute("shape.rectangle", &json!({"x": 10.3, "y": 20.6, "width": 30.4, "height": 9.7})).unwrap()["id"].as_u64().unwrap();
assert!(!aligned(&s, plain));
let drawn = [(10.3, 20.6), (40.7, 20.6), (40.7, 30.3), (10.3, 30.3)];
assert!(points(&s, plain).iter().zip(drawn).all(|(a, b)| close(*a, b)), "{:?}", points(&s, plain));
assert!(aligned(&s, line));
// A value that is not true or false changes nothing.
let steps = undo_len(&s);
assert!(s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": "yes"})).is_err());
assert!(!align_new(&s));
assert_eq!(undo_len(&s), steps);
}
/// While Align New Objects to Pixel Grid is on, the paths of a new rectangular grid, polar grid
/// and flare are pixel-aligned (the group is not), and a new 3D Box add-on shape is snapped as
/// Align to Pixel Grid snaps the same box drawn without it.
#[test]
fn align_new_objects_reaches_grids_flares_and_add_on_shapes() {
let mut s = new_doc();
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
let doc = |s: &Session| s.doc().unwrap().doc.clone();
let children = |s: &Session, id: u64| -> Vec<u64> { doc(s).node(NodeId(id)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect() };
let grid = s.execute("shape.rectangularGrid", &json!({"x": 10.3, "y": 20.6, "width": 100.4, "height": 50.7})).unwrap()["id"].as_u64().unwrap();
assert!(!aligned(&s, grid));
let lines = children(&s, grid);
assert!(!lines.is_empty() && lines.iter().all(|id| aligned(&s, *id)));
// Under the 1 pt stroke, a divider sits on a half point across its length, and the frame
// has every corner on half points.
let half = |v: f64| ((v - 0.5) - (v - 0.5).round()).abs() < 1e-9;
let snapped =
|p: &[(f64, f64)]| halves(p) || (p.iter().all(|q| q.1 == p[0].1) && half(p[0].1)) || (p.iter().all(|q| q.0 == p[0].0) && half(p[0].0));
assert!(lines.iter().all(|id| snapped(&points(&s, *id))), "{:?}", lines.iter().map(|id| points(&s, *id)).collect::<Vec<_>>());
let polar = s.execute("shape.polarGrid", &json!({"x": 200.3, "y": 20.6, "width": 80.4, "height": 80.7})).unwrap()["id"].as_u64().unwrap();
assert!(!aligned(&s, polar) && children(&s, polar).iter().all(|id| aligned(&s, *id)));
let flare = s.execute("shape.flare", &json!({"cx": 100.3, "cy": 200.6})).unwrap()["id"].as_u64().unwrap();
assert!(!aligned(&s, flare) && children(&s, flare).iter().all(|id| aligned(&s, *id)));
// Seen straight on, the box's front face has horizontal and vertical edges to snap.
let params = json!({"x": 20.3, "y": 300.6, "width": 60.4, "height": 40.7, "angleX": 0, "angleY": 0, "angleZ": 0});
let drawn = s.execute("addon.shapes.box3d", &params).unwrap()["id"].as_u64().unwrap();
assert!(aligned(&s, drawn));
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": false})).unwrap();
let later = s.execute("addon.shapes.box3d", &params).unwrap()["id"].as_u64().unwrap();
assert!(!aligned(&s, later));
let unaligned = points(&s, later);
s.execute("object.setPixelAligned", &json!({"ids": [later]})).unwrap();
assert_eq!(points(&s, drawn), points(&s, later));
assert_ne!(points(&s, drawn), unaligned, "the box has segments to snap");
}
/// The document's Align New Objects to Pixel Grid is saved in the native file only when on and
/// read back; a file from before it opens with it off.
#[test]
fn align_new_objects_is_saved_and_read_back() {
let mut s = new_doc();
let off = serde_json::to_value(&s.doc().unwrap().doc.setup).unwrap();
assert!(off.get("alignNewObjectsToPixelGrid").is_none(), "{off}");
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
assert!(!back.setup.align_new_objects_to_pixel_grid);
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
let on = serde_json::to_value(&s.doc().unwrap().doc.setup).unwrap();
assert_eq!(on["alignNewObjectsToPixelGrid"], true);
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
assert!(back.setup.align_new_objects_to_pixel_grid);
let mut older = on;
older.as_object_mut().unwrap().remove("alignNewObjectsToPixelGrid");
assert!(!serde_json::from_value::<vectorcraft_doc::DocSetup>(older).unwrap().align_new_objects_to_pixel_grid);
}
fn selected_ids(s: &Session) -> Vec<u64> {
let mut ids: Vec<u64> = s.doc().unwrap().selection.objects.iter().map(|i| i.0).collect();
ids.sort_unstable();
@@ -1060,6 +1060,30 @@ fn link_info_gives_the_artboards_size_not_pixels() {
);
}
/// A confined caller's Link Info of a placed document whose file is outside its read roots has no
/// `link`, `path` or `location`, and keeps the file's name.
#[test]
fn link_info_leaves_out_a_placed_documents_path_outside_the_read_roots() {
let away = Folder::new("placed-lrr-away");
let home = Folder::new("placed-lrr-home");
let src = away.file("logo.vectorcraft");
source(&src, 100.0, 50.0, RED, 0);
let mut s = session();
let id = place(&mut s, &src);
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[]).unwrap().unwrap();
let i = crate::file_access::confine(Some(&roots), || s.execute("links.info", &json!({"id": id.0}))).unwrap();
assert!(!i.to_string().contains("placed-lrr-away"), "{i}");
assert_eq!(
(i["fileName"].as_str(), i["document"].as_bool(), i["status"].as_str()),
(Some("logo.vectorcraft"), Some(true), Some("missing")),
"{i}"
);
let l = crate::file_access::confine(Some(&roots), || s.execute("links.list", &json!({}))).unwrap();
assert!(!l.to_string().contains("placed-lrr-away") && l["links"][0]["name"] == "logo.vectorcraft", "{l}");
let i = s.execute("links.info", &json!({"id": id.0})).unwrap();
assert_eq!((&i["link"], &i["path"]), (&json!(src), &json!(src)), "unconfined: {i}");
}
/// Save As reads its defaults from the catalog; using them must retain current editable links.
#[test]
fn native_save_catalog_defaults_keep_placed_documents_editable() {
+302 -7
View File
@@ -1587,7 +1587,7 @@ fn a_module_without_permissions_ends_the_grant_of_its_id() {
/// that holds such a module and a grant for its id has that grant forgotten when it is attached.
#[test]
fn a_module_without_permissions_ends_the_grant_kept_in_the_store() {
use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex};
use vectorcraft_plugins::permissions::{Grant, GrantToken, Permission, sha256_hex};
let folder = crate::tests_links::Folder::new("plugin-store-stale-grant");
let id = "test.engine.permissions.storedstale";
let other = "test.engine.permissions.storedother";
@@ -1634,7 +1634,11 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() {
let future = json!({"id": id, "hash": "00", "permissions": ["doc.read", "ui.panel"]});
std::fs::write(&grants, serde_json::to_vec(&json!([future, other_entry])).unwrap()).unwrap();
vectorcraft_plugins::registry::remove(id);
vectorcraft_plugins::registry::grant(Grant { id: id.into(), hash: sha256_hex(&approved), permissions: vec![Permission::DocRead] });
vectorcraft_plugins::registry::grant(GrantToken::after_engine_approval(Grant {
id: id.into(),
hash: sha256_hex(&approved),
permissions: vec![Permission::DocRead],
}));
let mut fourth = session();
fourth.attach_plugin_store(folder.0.clone());
assert_eq!(ids(), vec![other.to_string()]);
@@ -2165,7 +2169,7 @@ fn a_plugin_folder_ends_the_process_grant_of_an_id_it_replaces() {
/// With a store attached, a matching grant held only by the process doesn't count.
#[test]
fn a_stored_grant_covers_only_the_stored_module_it_recorded() {
use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex};
use vectorcraft_plugins::permissions::{Grant, GrantToken, Permission, sha256_hex};
let folder = crate::tests_links::Folder::new("plugin-store-recorded-module");
let id = "test.engine.permissions.storedbytes";
let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
@@ -2210,7 +2214,11 @@ fn a_stored_grant_covers_only_the_stored_module_it_recorded() {
assert!(starts());
let mut attached = session();
attached.attach_plugin_store(folder.0.clone());
vectorcraft_plugins::registry::grant(Grant { id: id.into(), hash: sha256_hex(&changed), permissions: vec![Permission::DocRead] });
vectorcraft_plugins::registry::grant(GrantToken::after_engine_approval(Grant {
id: id.into(),
hash: sha256_hex(&changed),
permissions: vec![Permission::DocRead],
}));
let inspected = run(&mut attached, "plugin.inspect", json!({"dataBase64": vectorcraft_format::base64_encode(&changed)}));
assert_eq!(inspected["needsApproval"], true, "a grant held only by the process doesn't count with a store attached");
run(&mut attached, "plugin.remove", json!({"id": id}));
@@ -2297,6 +2305,194 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() {
vectorcraft_plugins::registry::revoke(id);
}
/// Runs the test `name` of this module again in a process of its own → whether this is that
/// process. The list of disabled plug-ins is kept for the whole process, and the other tests here
/// read it again each time they attach a plug-in store.
fn in_own_process(name: &str) -> bool {
const CHILD: &str = "VECTORCRAFT_TEST_PLUGIN_DISABLED_LIST";
if std::env::var_os(CHILD).is_some() {
return true;
}
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", &format!("tests::plugins::{name}"), "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"{name} failed in its own process:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
false
}
/// An update whose grant can't be written, and whose old module can't be put back either, stays in
/// the store: a disabled plug-in is turned on, as for any update the store holds. The old grant
/// doesn't cover the new module, so the next start skips it until it is approved.
#[test]
fn an_update_left_in_the_store_by_a_failed_put_back_turns_a_disabled_plugin_on() {
if !in_own_process("an_update_left_in_the_store_by_a_failed_put_back_turns_a_disabled_plugin_on") {
return;
}
use vectorcraft_plugins::{permissions::sha256_hex, registry, safe_mode};
let folder = crate::tests_links::Folder::new("plugin-store-failed-put-back-update");
let id = "test.engine.permissions.putbackupdate";
let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let changed = asking(id, r#"["doc.read","doc.write"]"#, &json!({"objects": []}));
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&first), "grant": ["doc.read"]}));
run(&mut s, "plugin.setEnabled", json!({"id": id, "enabled": false}));
let grants = folder.0.join("grants.json");
let recorded = std::fs::read(&grants).unwrap();
std::fs::remove_file(&grants).unwrap();
std::fs::create_dir_all(grants.join("block")).unwrap();
crate::store::PUT_BACK_FAILS.set(true);
let update = json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read", "doc.write"], "replace": true});
let installed = s.execute("plugin.install", &update);
crate::store::PUT_BACK_FAILS.set(false);
assert_eq!(installed.unwrap()["hash"], sha256_hex(&changed), "the new module runs in this session");
assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&changed)));
assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), changed, "the store holds the new module");
assert!(safe_mode::disabled().is_empty(), "the module the store holds is turned on");
let saved = std::fs::read(folder.0.join(crate::store::DISABLED_FILE)).unwrap();
assert!(safe_mode::parse_disabled_file(&saved).is_empty(), "nothing disabled is saved");
std::fs::remove_dir_all(&grants).unwrap();
std::fs::write(&grants, &recorded).unwrap();
registry::remove(id);
registry::revoke(id);
let mut next = session();
next.attach_plugin_store(folder.0.clone());
assert!(registry::get(id).is_none(), "the old grant doesn't cover the new module");
safe_mode::set_disabled(vec![]);
}
/// An update whose grant can't be written, and whose put-back writes the old module and then
/// reports a failure, leaves the old module in the store: a disabled plug-in stays disabled, and the
/// next start doesn't load it.
#[test]
fn an_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off() {
if !in_own_process("an_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off") {
return;
}
use vectorcraft_plugins::{registry, safe_mode};
let folder = crate::tests_links::Folder::new("plugin-store-put-back-fails-after-write");
let id = "test.engine.permissions.putbacklate";
let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let changed = asking(id, r#"["doc.read","doc.write"]"#, &json!({"objects": []}));
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&first), "grant": ["doc.read"]}));
run(&mut s, "plugin.setEnabled", json!({"id": id, "enabled": false}));
let disabled = safe_mode::disabled();
assert!(!disabled.is_empty());
let grants = folder.0.join("grants.json");
let recorded = std::fs::read(&grants).unwrap();
std::fs::remove_file(&grants).unwrap();
std::fs::create_dir_all(grants.join("block")).unwrap();
crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(true);
let update = json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read", "doc.write"], "replace": true});
let installed = s.execute("plugin.install", &update);
crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(false);
installed.unwrap();
assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), first, "the store holds the old module");
assert_eq!(safe_mode::disabled(), disabled, "the plug-in stays disabled");
let saved = std::fs::read(folder.0.join(crate::store::DISABLED_FILE)).unwrap();
assert!(!safe_mode::parse_disabled_file(&saved).is_empty(), "the disabled list on disk is kept");
std::fs::remove_dir_all(&grants).unwrap();
std::fs::write(&grants, &recorded).unwrap();
registry::remove(id);
registry::revoke(id);
let mut next = session();
next.attach_plugin_store(folder.0.clone());
assert!(registry::get(id).is_none(), "the disabled old module doesn't load");
safe_mode::set_disabled(vec![]);
}
/// A module without permissions whose install can't remove the old grant, and whose put-back writes
/// the old module and then reports a failure, leaves the old module in the store: a disabled plug-in
/// stays disabled.
#[test]
fn a_plain_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off() {
if !in_own_process("a_plain_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off") {
return;
}
use vectorcraft_plugins::safe_mode;
let folder = crate::tests_links::Folder::new("plugin-store-plain-put-back-fails-after-write");
let id = "test.engine.permissions.plainputbacklate";
let empty = json!({"objects": []});
let approved = asking(id, r#"["doc.read"]"#, &empty);
let plain = asking(id, "null", &empty);
let grants = folder.0.join("grants.json");
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]}));
run(&mut s, "plugin.setEnabled", json!({"id": id, "enabled": false}));
let disabled = safe_mode::disabled();
assert!(!disabled.is_empty());
let file = s.stored_plugin_file(id).unwrap();
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
let entry = serde_json::from_slice::<Vec<Value>>(&std::fs::read(&grants).unwrap()).unwrap().remove(0);
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
std::fs::write(&grants, &full).unwrap();
crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(true);
let installed = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(false);
installed.unwrap();
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store holds the old module");
assert_eq!(safe_mode::disabled(), disabled, "the plug-in stays disabled");
let saved = std::fs::read(folder.0.join(crate::store::DISABLED_FILE)).unwrap();
assert!(!safe_mode::parse_disabled_file(&saved).is_empty(), "the disabled list on disk is kept");
std::fs::remove_file(&grants).unwrap();
run(&mut s, "plugin.remove", json!({"id": id}));
safe_mode::set_disabled(vec![]);
}
/// A first install whose grant can't be written, and whose module can't be taken out of the store
/// again, stays in the store: the plug-in's file is turned on. No grant covers the module, so the
/// next start skips it until it is approved.
#[test]
fn a_first_install_left_in_the_store_by_a_failed_put_back_turns_its_file_on() {
if !in_own_process("a_first_install_left_in_the_store_by_a_failed_put_back_turns_its_file_on") {
return;
}
use vectorcraft_plugins::{registry, safe_mode};
let folder = crate::tests_links::Folder::new("plugin-store-failed-put-back-first");
let id = "test.engine.permissions.putbackfirst";
let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let mut s = session();
s.attach_plugin_store(folder.0.clone());
let module = s.stored_plugin_file(id).unwrap();
run(&mut s, "plugin.setEnabled", json!({"file": module, "enabled": false}));
let grants = folder.0.join("grants.json");
std::fs::create_dir_all(grants.join("block")).unwrap();
crate::store::PUT_BACK_FAILS.set(true);
let installed = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&first), "grant": ["doc.read"]}));
crate::store::PUT_BACK_FAILS.set(false);
installed.unwrap();
assert!(registry::get(id).is_some(), "the module runs in this session");
assert_eq!(std::fs::read(&module).unwrap(), first, "the store holds the module");
assert!(safe_mode::disabled().is_empty(), "the file the store holds is turned on");
let saved = std::fs::read(folder.0.join(crate::store::DISABLED_FILE)).unwrap();
assert!(safe_mode::parse_disabled_file(&saved).is_empty(), "nothing disabled is saved");
std::fs::remove_dir_all(&grants).unwrap();
registry::remove(id);
registry::revoke(id);
let mut next = session();
next.attach_plugin_store(folder.0.clone());
assert!(registry::get(id).is_none(), "no grant covers the module");
safe_mode::set_disabled(vec![]);
}
/// A plug-in folder reports a changed module as needing approval and still loads the other files;
/// granted on its own, the changed module loads from the folder. A session without a store uses the
/// grants held by the process.
@@ -2480,8 +2676,15 @@ fn a_run_past_the_memory_budget_fails_before_the_plugin_starts() {
params.join(",")
);
let module = wat::parse_str(tpl::module(&manifest, "unreachable", "", 1)).unwrap();
// One page of memory: the input and the parameters share 32 KiB.
registry::install(Plugin::load(&module, Limits { max_memory_bytes: 1 << 16, ..Limits::default() }).unwrap());
// One page of memory: the input and the parameters share 32 KiB. The module lists permissions,
// so its grant is recorded first.
let plugin = Plugin::load(&module, Limits { max_memory_bytes: 1 << 16, ..Limits::default() }).unwrap();
registry::grant(vectorcraft_plugins::permissions::GrantToken::after_engine_approval(vectorcraft_plugins::permissions::Grant {
id: id.into(),
hash: plugin.hash().to_string(),
permissions: plugin.manifest().permissions(),
}));
registry::install(plugin).unwrap();
let mut s = session();
let small = rect(&mut s, 10.0, "#ff0000");
let long = rect(&mut s, 30.0, "#00ff00");
@@ -2522,7 +2725,7 @@ fn a_run_past_the_memory_budget_fails_before_the_plugin_starts() {
assert!(e.contains(says), "{says}: {e}");
assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before, "{says}");
}
assert!(registry::remove(id));
assert!(registry::remove(id) && registry::revoke(id));
}
/// What the user granted is kept in the plug-in store with the module: the next session installs
@@ -2613,6 +2816,41 @@ fn granted_permissions_are_kept_and_folders_skip_the_rest() {
run(&mut granted, "plugin.remove", json!({"id": id}));
}
/// The registry installs a module that lists permissions only under a grant the process holds, so
/// a start and a `plugin.reload` record the store's grant for the module they load. A module in the
/// folder that nobody granted is reported and skipped, and records nothing.
#[test]
fn stored_and_reload_grants_still_install() {
let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner());
let store = crate::tests_links::Folder::new("plugin-store-grants-reload");
let id = "test.engine.permissions.reload";
let lone = "test.engine.permissions.reload.lone";
let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let mut s = session();
s.attach_plugin_store(store.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": ["doc.read"]}));
let forget = || {
vectorcraft_plugins::registry::remove(id);
vectorcraft_plugins::registry::revoke(id);
};
forget();
let mut next = session();
next.attach_plugin_store(store.0.clone());
assert!(vectorcraft_plugins::registry::get(id).is_some(), "installed again from the store");
assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.hash), Some(vectorcraft_plugins::permissions::sha256_hex(&wasm)));
forget();
let dir = crate::tests_links::Folder::new("plugin-folder-grants-reload");
std::fs::write(dir.0.join("granted.wasm"), &wasm).unwrap();
std::fs::write(dir.0.join("lone.wasm"), asking(lone, r#"["doc.read"]"#, &json!({"objects": []}))).unwrap();
let r = run(&mut next, "plugin.reload", json!({"path": dir.0.display().to_string()}));
assert_eq!(r["loaded"], json!([id]), "{r}");
assert!(vectorcraft_plugins::registry::granted(id).is_some(), "the store's grant is the process's too");
let why = r["failed"][0]["error"].as_str().unwrap();
assert!(why.contains("needs approval") && r["failed"][0]["file"].as_str().unwrap().ends_with("lone.wasm"), "{r}");
assert!(vectorcraft_plugins::registry::get(lone).is_none() && vectorcraft_plugins::registry::granted(lone).is_none());
run(&mut next, "plugin.remove", json!({"id": id}));
}
/// A grant covers the module it was given to: another module under the id, listing the same
/// permissions, isn't installed from the store at the next start, a folder load reports it as
/// needing approval, and `plugin.install` asks for `grant` again, even with `replace: true`. It
@@ -3784,3 +4022,60 @@ fn a_filter_that_calls_commands_is_given_the_edit_in_progress() {
assert_eq!(x, json!(17.0), "undoing the filter brings back the moved rectangle");
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// Installs a filter `id` that calls commands and hands back what it is given, with `commands` (a
/// JSON list of command specs) in its manifest.
fn install_echo_calling(s: &mut Session, id: &str, commands: &str) {
let grant = json!(["doc.read", "doc.write", "commands"]);
let manifest = format!(
r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["select.all"],"commands":{commands}}}"#
);
let wasm = wat::parse_str(tpl::module(&manifest, tpl::ECHO, "", 1)).unwrap();
run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true}));
}
/// With Real-time Drawing off, a 50 × 50 rectangle at (10, 10) whose move by 7 pt is still being
/// dragged: the tool has stored the move, which the document does not hold yet.
fn deferred_move(s: &mut Session) -> NodeId {
let r = NodeId(run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50}))["id"].as_u64().unwrap());
run(s, "prefs.set", json!({"key": "realTimeDrawing", "value": false}));
let move_by = vectorcraft_tools::Action::Preview("object.move".into(), json!({"dx": 7, "dy": 0}));
s.apply_actions(vec![vectorcraft_tools::Action::Begin("Move".into()), move_by]).unwrap();
assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 10.0, "the move is not applied while it is dragged");
r
}
/// The rectangle a run named `label` during [`deferred_move`] left: moved, with the interaction
/// ended and the move an undo step of its own before the run's.
fn assert_moved_once(s: &Session, r: NodeId, label: &str) {
assert!(!s.in_interaction());
assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 17.0, "the filter was given the moved rectangle");
let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect();
assert_eq!(labels, [label, "Move"]);
}
/// With Real-time Drawing off, `plugin.run` of a filter that calls commands during a drag applies
/// the dragged move first and gives the filter the moved rectangle, which it hands back as it was.
#[test]
fn a_filter_that_calls_commands_is_given_a_deferred_move() {
let id = "test.engine.callsdeferred";
let mut s = session();
install_echo_calling(&mut s, id, "[]");
let r = deferred_move(&mut s);
run(&mut s, "plugin.run", json!({"id": id}));
assert_moved_once(&s, r, &format!("Test {id}"));
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// A plug-in command that calls commands, run with Real-time Drawing off during a drag, is given
/// the moved rectangle as `plugin.run` is.
#[test]
fn a_plugin_command_that_calls_commands_is_given_a_deferred_move() {
let id = "test.engine.callsdeferredcmd";
let mut s = session();
install_echo_calling(&mut s, id, r#"[{"id":"same","label":"Same"}]"#);
let r = deferred_move(&mut s);
run(&mut s, &format!("plugin.{id}.same"), json!({}));
assert_moved_once(&s, r, "Same");
run(&mut s, "plugin.remove", json!({"id": id}));
}
+36
View File
@@ -2047,6 +2047,42 @@ fn real_time_drawing_turned_on_mid_drag_still_commits_deferred_preview() {
assert_eq!(paths(&s), 1, "the deferred rectangle is committed");
}
/// With Real-time Drawing off, Undo during a drag keeps the dragged move as its own step and takes
/// back only that: the rectangle drawn before stays, and Redo brings the move back.
#[test]
fn undo_during_a_deferred_drag_takes_back_only_the_drag() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let r = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap());
set_pref(&mut s, "realTimeDrawing", json!(false));
let x = |s: &Session| s.doc().unwrap().doc.node(r).and_then(vectorcraft_doc::Node::geometric_bounds).map(|b| b.x0);
let move_by = vectorcraft_tools::Action::Preview("object.move".into(), json!({"dx": 7, "dy": 0}));
s.apply_actions(vec![vectorcraft_tools::Action::Begin("Move".into()), move_by]).unwrap();
assert_eq!(x(&s), Some(10.0));
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.in_interaction());
assert_eq!(x(&s), Some(10.0), "the rectangle stays");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(x(&s), Some(17.0), "Redo brings the move back");
}
/// Undo during a drag whose stored preview fails cancels the drag, as its release would, and then
/// takes back the step before it.
#[test]
fn undo_during_a_deferred_drag_that_fails_cancels_it() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
set_pref(&mut s, "realTimeDrawing", json!(false));
let bad = vectorcraft_tools::Action::Preview("no.such.command".into(), json!({}));
s.apply_actions(vec![vectorcraft_tools::Action::Begin("Bad".into()), bad]).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.in_interaction());
let d = s.doc().unwrap();
assert_eq!(d.doc.layers.iter().map(|l| l.children().map_or(0, |c| c.len())).sum::<usize>(), 0, "the rectangle is undone");
assert!(d.history.undo.iter().all(|e| e.label != "Bad"));
}
/// Repeated overlay redraws with Real-time Drawing off reuse the cached deferred feedback.
#[test]
fn deferred_preview_overlays_are_cached_across_redraws() {
+37 -1
View File
@@ -55,6 +55,42 @@ fn file_constructor_identity_and_folder_path() {
let _ = std::fs::remove_dir_all(base);
}
/// `exists` is true only when the path names an entry of the object's own kind.
#[test]
fn script_file_exists_checks_the_kind() {
let base = folder("kind");
write(&base.join("main/data.txt"), b"x");
std::fs::create_dir_all(base.join("main/sub")).unwrap();
let log =
logged(&base, "vc.log([new File('sub').exists, new Folder('data.txt').exists, new File('data.txt').exists, new Folder('sub').exists]);");
assert_eq!(log, json!([[false, false, true, true]]));
let _ = std::fs::remove_dir_all(base);
}
/// A property a script puts on `Object.prototype` is not read as part of what the app returns.
#[test]
fn script_file_ignores_inherited_result_fields() {
let base = folder("inherited");
write(&base.join("main/data.txt"), b"data");
let log = logged(
&base,
"Object.prototype.error = 'inherited'; Object.prototype.exists = true;\n\
var f = new File('data.txt'); var opened = f.open('r');\n\
vc.log([f.exists, new File('nope').exists, opened, f.error, f.read()]);",
);
assert_eq!(log, json!([[true, false, true, "", "data"]]));
let _ = std::fs::remove_dir_all(base);
}
/// `File.encode`, `File.decode`, `File.isEncodingAvailable` and the `Folder` locations are counted as
/// calls to the app.
#[test]
fn script_file_class_functions_are_counted() {
let source = "File.encode('x'); File.decode('y'); Folder.isEncodingAvailable('UTF-8'); Folder.temp;";
let r = Session::new().execute("script.run", &json!({"source": source})).unwrap();
assert_eq!(r["hostCallCounts"]["fileCalls"], 4, "{r}");
}
#[test]
fn file_names_are_uri_encoded_and_current_relative() {
let base = folder("names");
@@ -74,7 +110,7 @@ fn file_names_are_uri_encoded_and_current_relative() {
assert_eq!(
log,
json!([
["caf%C3%A9%20x.txt", "caf\u{e9} x.txt", "caf%C3%A9%20x.txt", true, "%C3%A9%20%2F", "\u{e9}", "sub/y.txt", true, true],
["caf%C3%A9%20x.txt", "caf\u{e9} x.txt", "caf%C3%A9%20x.txt", true, "%C3%A9%20/", "\u{e9}", "sub/y.txt", true, true],
["sub", "w", "w"],
["literal%20name.txt", "literal%2520name.txt", "literal%2520name.txt", true, "p%41", "p%41"]
])
+236
View File
@@ -0,0 +1,236 @@
//! Clicks, hovers and marquees with the selection tools leave out the area that raster effects
//! (drop shadows, glows, blurs) paint beyond an object: there they reach the object under the
//! effect, or nothing.
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_geom::{Point, Rect};
use vectorcraft_tools::{Cursor, Mods, PointerEvent, PointerKind};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s
}
fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
/// A rectangle filled with `color`.
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64, color: &str) -> NodeId {
let id = id_of(&run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h})));
run(s, "select.set", json!({"ids": [id.0]}));
run(s, "paint.setFill", json!({"color": color}));
id
}
/// A drop shadow on the whole of `id`, `dx` to the right, with no blur.
fn shadow(s: &mut Session, id: NodeId, dx: f64) {
run(s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [id.0], "params": {"x": dx, "y": 0, "blur": 0}, "item": null}));
}
fn pixel(s: &Session, x: u32, y: u32) -> [u8; 4] {
let doc = s.doc().unwrap().doc.clone();
let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
vectorcraft_render::Renderer::new().render(&doc, 200, 200, vectorcraft_geom::Affine::IDENTITY, &opts).pixel(x, y)
}
fn press(s: &mut Session, tool: &str, from: (f64, f64), to: (f64, f64), mods: Mods) -> Vec<NodeId> {
let v = ViewInfo::default();
s.select_tool(tool, v).unwrap();
for (k, (x, y)) in [(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] {
if k == PointerKind::Drag && from == to {
continue;
}
s.pointer(&PointerEvent::new(k, x, y).with_mods(mods), v).unwrap();
}
s.active().unwrap().selection.objects.clone()
}
/// Click with the Selection tool at (x, y) on a 100% view: what is selected afterwards.
fn click(s: &mut Session, x: f64, y: f64) -> Vec<NodeId> {
press(s, "selection", (x, y), (x, y), Mods::default())
}
fn bounds(s: &Session, id: NodeId) -> Rect {
s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap()
}
const WHITE: [u8; 4] = [255; 4];
const BLUE: [u8; 4] = [0, 0, 255, 255];
/// Blue B at x 100 to 160, red A over its left edge's side at x 20 to 80, and A's shadow
/// 40 pt to the right, from x 60 to 120: over the canvas from 80 to 100 and over B from 100 to 120.
fn shadow_over_b(s: &mut Session) -> (NodeId, NodeId) {
let b = rect(s, 100.0, 20.0, 60.0, 60.0, "#0000ff");
let a = rect(s, 20.0, 20.0, 60.0, 60.0, "#ff0000");
shadow(s, a, 40.0);
(a, b)
}
#[test]
fn a_click_on_a_drop_shadow_selects_the_object_under_it() {
let mut s = session();
let (a, b) = shadow_over_b(&mut s);
// The shadow paints over B and over the canvas.
assert_ne!(pixel(&s, 110, 50), BLUE);
assert_ne!(pixel(&s, 90, 50), WHITE);
run(&mut s, "select.none", json!({}));
assert_eq!(click(&mut s, 110.0, 50.0), [b]);
assert_eq!(click(&mut s, 50.0, 50.0), [a]);
}
#[test]
fn a_click_on_a_drop_shadow_over_the_canvas_selects_nothing_and_clears_the_selection() {
let mut s = session();
let (a, _) = shadow_over_b(&mut s);
run(&mut s, "select.set", json!({"ids": [a.0]}));
assert!(click(&mut s, 90.0, 50.0).is_empty());
}
#[test]
fn a_click_on_an_outer_glow_or_a_gaussian_blur_outside_the_path_selects_what_is_under_it() {
let mut s = session();
let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000");
run(&mut s, "effect.apply", json!({"effect": "stylize.outerGlow", "ids": [a.0], "params": {"blur": 20, "mode": "normal"}, "item": null}));
assert_ne!(pixel(&s, 88, 50), WHITE);
run(&mut s, "select.none", json!({}));
assert!(click(&mut s, 88.0, 50.0).is_empty());
// A red square whose blur reaches over the canvas and over the left edge of a blue one.
let mut s = session();
let b = rect(&mut s, 92.0, 20.0, 60.0, 60.0, "#0000ff");
let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000");
run(&mut s, "effect.apply", json!({"effect": "blur.gaussian", "ids": [a.0], "params": {"radius": 20}, "item": null}));
assert_ne!(pixel(&s, 98, 50), BLUE);
assert_ne!(pixel(&s, 87, 50), WHITE);
run(&mut s, "select.none", json!({}));
assert_eq!(click(&mut s, 98.0, 50.0), [b]);
// (With B deselected, so that the press does not take its bounding box handle.)
run(&mut s, "select.none", json!({}));
assert!(click(&mut s, 87.0, 50.0).is_empty());
}
/// The first point of `area` (x0, y0, x1, y1) that the canvas paints, scanning rows.
fn painted_in(s: &Session, (x0, y0, x1, y1): (u32, u32, u32, u32)) -> Option<(f64, f64)> {
let doc = s.doc().unwrap().doc.clone();
let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
let img = vectorcraft_render::Renderer::new().render(&doc, 200, 200, vectorcraft_geom::Affine::IDENTITY, &opts);
(y0..y1)
.flat_map(|y| (x0..x1).map(move |x| (x, y)))
.find(|&(x, y)| img.pixel(x, y) != WHITE)
.map(|(x, y)| (f64::from(x) + 0.5, f64::from(y) + 0.5))
}
#[test]
fn a_click_on_the_drop_shadow_of_a_group_or_of_point_type_selects_neither() {
let mut s = session();
let a = rect(&mut s, 20.0, 20.0, 30.0, 30.0, "#ff0000");
let b = rect(&mut s, 60.0, 20.0, 30.0, 30.0, "#ff0000");
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let g = id_of(&run(&mut s, "object.group", json!({})));
shadow(&mut s, g, 80.0);
// The group's shadow lies from x 100 to 170.
assert_ne!(pixel(&s, 110, 35), WHITE);
run(&mut s, "select.none", json!({}));
assert!(click(&mut s, 110.0, 35.0).is_empty());
assert_eq!(click(&mut s, 35.0, 35.0), [g]);
// Type 40 pt high at y 150 with its shadow 90 pt to the right.
let t = id_of(&run(&mut s, "text.create", json!({"x": 20, "y": 150, "text": "HH", "size": 40})));
shadow(&mut s, t, 90.0);
let right = bounds(&s, t).x1;
assert!(right < 100.0, "{right}");
let at = painted_in(&s, (right.ceil() as u32 + 10, 110, 199, 160)).expect("the type's shadow paints");
run(&mut s, "select.none", json!({}));
assert!(click(&mut s, at.0, at.1).is_empty(), "{at:?}");
}
#[test]
fn a_click_on_the_drop_shadow_of_a_symbols_art_does_not_select_the_instance() {
let mut s = session();
let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000");
shadow(&mut s, a, 40.0);
run(&mut s, "select.set", json!({"ids": [a.0]}));
let inst = id_of(&run(&mut s, "symbol.new", json!({"name": "Shadowed"})));
assert_ne!(pixel(&s, 100, 50), WHITE);
run(&mut s, "select.none", json!({}));
assert!(click(&mut s, 100.0, 50.0).is_empty());
assert_eq!(click(&mut s, 50.0, 50.0), [inst]);
}
#[test]
fn a_click_on_the_drop_shadow_of_an_image_outside_its_frame_does_not_select_it() {
let mut s = session();
let mut png = vec![];
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [65, 65]}));
let im = NodeId(r["ids"][0].as_u64().unwrap());
// The frame lies from x 50 to 80 and the shadow from 90 to 120.
shadow(&mut s, im, 40.0);
assert_ne!(pixel(&s, 105, 65), WHITE);
run(&mut s, "select.none", json!({}));
assert!(click(&mut s, 105.0, 65.0).is_empty());
assert_eq!(click(&mut s, 65.0, 65.0), [im]);
}
#[test]
fn shift_click_direct_selection_and_hover_on_a_drop_shadow_pass_through_it() {
let mut s = session();
let (a, b) = shadow_over_b(&mut s);
// Shift-click on the shadow over B adds B and keeps A.
run(&mut s, "select.set", json!({"ids": [a.0]}));
let shift = Mods { shift: true, ..Mods::default() };
let mut sel = press(&mut s, "selection", (110.0, 50.0), (110.0, 50.0), shift);
sel.sort_by_key(|n| n.0);
let mut both = vec![a, b];
both.sort_by_key(|n| n.0);
assert_eq!(sel, both);
// Direct Selection takes B through the shadow, and nothing over the canvas.
run(&mut s, "select.none", json!({}));
let sel = press(&mut s, "directSelection", (110.0, 50.0), (110.0, 50.0), Mods::default());
assert!(sel.contains(&b) && !sel.contains(&a), "{sel:?}");
run(&mut s, "select.none", json!({}));
assert!(press(&mut s, "directSelection", (90.0, 50.0), (90.0, 50.0), Mods::default()).is_empty());
// With A selected, the pointer over its shadow is the plain arrow, and over A the move pointer.
run(&mut s, "select.set", json!({"ids": [a.0]}));
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::Move);
assert_eq!(s.cursor(Point::new(110.0, 50.0), Mods::default(), v), Cursor::Arrow);
assert_eq!(s.cursor(Point::new(92.0, 50.0), Mods::default(), v), Cursor::Arrow);
}
#[test]
fn a_drag_from_the_drop_shadow_of_a_selected_object_does_not_move_it() {
let mut s = session();
let (a, b) = shadow_over_b(&mut s);
run(&mut s, "select.set", json!({"ids": [a.0]}));
let before = bounds(&s, a);
// From the shadow over the canvas: a marquee that touches nothing.
assert!(press(&mut s, "selection", (92.0, 50.0), (96.0, 60.0), Mods::default()).is_empty());
assert_eq!(bounds(&s, a), before);
// From the shadow over B: B moves, A stays.
run(&mut s, "select.set", json!({"ids": [a.0]}));
let b_before = bounds(&s, b);
assert_eq!(press(&mut s, "selection", (110.0, 50.0), (110.0, 60.0), Mods::default()), [b]);
assert_eq!(bounds(&s, a), before);
assert!((bounds(&s, b).y0 - b_before.y0 - 10.0).abs() < 1e-6, "{:?}", bounds(&s, b));
}
#[test]
fn a_marquee_that_touches_only_a_drop_shadow_does_not_select_its_object() {
let mut s = session();
let (_, b) = shadow_over_b(&mut s);
run(&mut s, "select.none", json!({}));
assert!(press(&mut s, "selection", (85.0, 40.0), (95.0, 60.0), Mods::default()).is_empty());
// From above B, over B and the shadow: B only.
assert_eq!(press(&mut s, "selection", (105.0, 5.0), (115.0, 30.0), Mods::default()), [b]);
}
+52
View File
@@ -44,6 +44,7 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
assert!(libs.len() >= 8 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}");
assert!(libs.iter().any(|l| l["id"] == "game-hud" && l["name"] == "Game HUD"), "{libs:?}");
assert!(libs.iter().any(|l| l["id"] == "status-effects" && l["name"] == "Status Effects"), "{libs:?}");
assert!(libs.iter().any(|l| l["id"] == "textures" && l["name"] == "Textures" && l["count"] == 8), "{libs:?}");
for l in libs {
let id = l["id"].as_str().unwrap();
let g = run(&mut s, "graphicStyle.library", json!({"library": id}));
@@ -64,6 +65,10 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
let status = run(&mut s, "graphicStyle.library", json!({"library": "status-effects"}));
let status_names: Vec<&str> = status["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]);
let textures = run(&mut s, "graphicStyle.library", json!({"library": "textures"}));
let texture_names: Vec<&str> = textures["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
let expected = ["Fine Grain", "Canvas Weave", "Burlap Sack", "Cracked Glaze", "Mosaic Floor", "Quilted Squares", "Leaded Glass", "Damp Paper"];
assert_eq!(texture_names, expected);
let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0);
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "game-hud", "name": "Mana Glow", "apply": true, "ids": [id.0]}));
assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec!["Mana Glow"], Some("Mana Glow")));
@@ -167,6 +172,53 @@ fn add_with_null_ids_applies_to_selection() {
assert_eq!(doc(&s).node(id).unwrap().extras().graphic_style, Some(style.id));
}
#[test]
fn textures_styles_apply_their_texture_effects_and_keep_their_params_through_save_and_open() {
let mut s = session();
let (_, lib) = cmd::stylelib::library(&s, "textures").unwrap();
let mut ids = vec![];
for (i, g) in lib.styles.iter().enumerate() {
let id = rect(&mut s, (i % 4) as f64 * 50.0, (i / 4) as f64 * 50.0, 40.0, 40.0);
let before = undo_len(&s);
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "textures", "name": g.name, "apply": true, "ids": [id.0]}));
assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec![g.name.as_str()], Some(g.name.as_str())));
assert_eq!(undo_len(&s), before + 1, "{}: added and applied as one step", g.name);
ids.push(id);
}
let effects = |s: &Session| -> Vec<Vec<(String, Value)>> {
ids.iter().map(|id| doc(s).node(*id).unwrap().appearance.effects.iter().map(|e| (e.id.clone(), e.params.clone())).collect()).collect()
};
let applied = effects(&s);
let effect_ids: Vec<Vec<&str>> = applied.iter().map(|fx| fx.iter().map(|(id, _)| id.as_str()).collect()).collect();
assert_eq!(
effect_ids,
[
["texture.grain"],
["texture.texturizer"],
["texture.texturizer"],
["texture.craquelure"],
["texture.mosaicTiles"],
["texture.patchwork"],
["texture.stainedGlass"],
["sketch.waterPaper"],
]
);
assert_eq!(applied[1][0].1["texture"], "canvas");
assert_eq!(applied[3][0].1["crackSpacing"], 12.0);
for (fx, g) in applied.iter().zip(&lib.styles) {
let want: Vec<(String, Value)> = g.appearance.effects.iter().map(|e| (e.id.clone(), e.params.clone())).collect();
assert_eq!(fx, &want, "{} applies the library's params", g.name);
}
let b64 = run(&mut s, "document.serialize", json!({"format": "vectorcraft"}))["dataBase64"].as_str().unwrap().to_string();
run(&mut s, "document.open", json!({"name": "textures.vectorcraft", "dataBase64": b64}));
assert_eq!(effects(&s), applied, "the params survive a save and open");
for g in &lib.styles {
let saved = doc(&s).graphic_style(&g.name).unwrap();
assert!(saved.same_look(g), "{} keeps its look", g.name);
assert!(ids.iter().any(|id| doc(&s).node(*id).unwrap().extras().graphic_style == Some(saved.id)), "{} stays linked", g.name);
}
}
/// A document with pattern `name` (a dot) and its swatch.
fn add_pattern(s: &mut Session, name: &str, radius: f64) {
s.edit("Pattern", |d, _| {
+3 -3
View File
@@ -221,9 +221,9 @@ fn new_width_point_adjust_adjoining_uses_sampled_widths() {
let (mut s, id) = line_session();
let original = vec![(0.0, 9.0, 9.0), (0.25, 1.0, 0.0), (0.75, 3.0, 0.0), (1.0, 7.0, 7.0)];
s.execute("stroke.widthProfile.set", &json!({"ids": [id.0], "points": original})).unwrap();
// At t=0.5 the old left side is where the profile's curve is there (#5714) and the right
// side is 0pt. Indexed editing of that sampled point is the existing convention: scale the
// nonzero side, add from zero.
// At t=0.5 the old left side is where the profile's curve is there and the right side is
// 0pt. Indexed editing of that sampled point is the existing convention: scale the nonzero
// side, add from zero.
let sampled = vectorcraft_doc::WidthProfile { points: original }.at(0.5).0;
let index = if indexed { Some(set(&mut s, json!({"id": id.0, "t": 0.5, "left": sampled * 5.0, "right": 0}))) } else { None };
set(&mut s, json!({"id": id.0, "index": index, "t": 0.5, "left": 20, "right": 5, "adjustAdjoining": true}));