mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 22:39:07 +00:00
Merge main into fix/plugin-ignored-grants-shared
This commit is contained in:
@@ -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());
|
||||
|
||||
@@ -113,7 +113,8 @@ pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for path in &files {
|
||||
let opened_before = s.documents().len();
|
||||
let one = |s: &mut Session| -> Result<String> {
|
||||
s.execute("document.open", &json!({ "path": path }))?;
|
||||
// A PSD or PSB is traced as its merged image, not as the first of its layers.
|
||||
s.execute("document.open", &json!({ "path": path, "layers": false }))?;
|
||||
s.execute("select.all", &json!({}))?;
|
||||
s.execute(trace, &json!({ "preset": preset }))?;
|
||||
let stem = fileio::file_stem(path);
|
||||
|
||||
@@ -333,6 +333,34 @@ fn batch_trace_folder_traces_and_saves_each_image() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A layered PSD is traced as its merged image: a white layer under a black square gives the
|
||||
/// square's shape, not a trace of the white layer alone.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn batch_trace_folder_traces_a_layered_psd_as_its_merged_image() {
|
||||
const C: &str = "addon.document.batchTraceFolder";
|
||||
let dir = folder("batch-trace-psd");
|
||||
let (src, out) = (dir.join("in"), dir.join("out"));
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 24, "height": 24})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 24, "height": 24})).unwrap();
|
||||
s.execute("layer.new", &json!({"name": "Square"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 6, "y": 6, "width": 12, "height": 12})).unwrap();
|
||||
let psd = s.execute("document.export", &json!({"format": "psd"})).unwrap();
|
||||
std::fs::write(src.join("two.psd"), vectorcraft_format::base64_decode(psd["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
|
||||
let r =
|
||||
s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg", "preset": "Black and White Logo", "expand": true})).unwrap();
|
||||
assert_eq!(r["traced"].as_array().unwrap().len(), 1, "{r}");
|
||||
let svg = std::fs::read_to_string(out.join("two.svg")).unwrap();
|
||||
assert!(svg.contains("fill=\"#000000\""), "the black square is traced: {svg}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Batch Trace Folder rejects optional values with the wrong type before opening images.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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]}), ¬_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}");
|
||||
}
|
||||
@@ -285,3 +285,54 @@ fn the_tool_draws_a_path_one_step_per_anchor_and_closes_it() {
|
||||
assert_eq!(path(&s, id).subpaths[0].anchors.len(), 3);
|
||||
assert_eq!(steps(&s), n + 8);
|
||||
}
|
||||
|
||||
/// #6634: the tool's closing drag on the first anchor sets that anchor's incoming handle to the
|
||||
/// mirror of the pointer and does not give it symmetric handles: a corner keeps its outgoing
|
||||
/// handle, a smooth anchor turns it to stay in line at its own length, and Alt pressed mid-drag
|
||||
/// keeps it where the drag had turned it.
|
||||
#[test]
|
||||
fn the_tools_closing_drag_does_not_make_the_first_anchor_symmetric() {
|
||||
// An open path whose first anchor, at (50, 50), has the handles `first`, drawn on from its last
|
||||
// anchor; the closing gesture is then up to the caller.
|
||||
let draw = |first: Value| {
|
||||
let mut s = session();
|
||||
let mut a = json!({"x": 50, "y": 50});
|
||||
a.as_object_mut().unwrap().extend(first.as_object().unwrap().clone());
|
||||
let anchors = json!([a, {"x": 150, "y": 50}, {"x": 150, "y": 150}]);
|
||||
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
|
||||
s.select_tool("smartPen", view()).unwrap();
|
||||
gesture(&mut s, &[(150.0, 150.0)], Mods::default());
|
||||
(s, id)
|
||||
};
|
||||
let first = |s: &Session, id: NodeId| {
|
||||
let sp = &path(s, id).subpaths[0];
|
||||
assert!(sp.closed, "{sp:?}");
|
||||
sp.anchors[0]
|
||||
};
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-6;
|
||||
|
||||
// A corner: the first segment keeps its shape.
|
||||
let (mut s, id) = draw(json!({"out": [80, 30]}));
|
||||
gesture(&mut s, &[(50.0, 50.0), (50.0, 100.0)], Mods::default());
|
||||
let a = first(&s, id);
|
||||
assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(50.0, 0.0), Point::new(80.0, 30.0), AnchorKind::Corner), "{a:?}");
|
||||
|
||||
// A smooth anchor: the outgoing handle turns opposite the incoming one, keeping its length 30.
|
||||
let (mut s, id) = draw(json!({"in": [20, 50], "out": [80, 50]}));
|
||||
assert_eq!(path(&s, id).subpaths[0].anchors[0].kind, AnchorKind::Smooth);
|
||||
gesture(&mut s, &[(50.0, 50.0), (50.0, 100.0)], Mods::default());
|
||||
let a = first(&s, id);
|
||||
assert_eq!((a.h_in, a.kind), (Point::new(50.0, 0.0), AnchorKind::Smooth), "{a:?}");
|
||||
assert!(near(a.h_out, Point::new(50.0, 80.0)), "{a:?}");
|
||||
|
||||
// Alt pressed mid-drag: a corner, its outgoing handle where the drag had turned it.
|
||||
let (mut s, id) = draw(json!({"in": [20, 50], "out": [80, 50]}));
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), view()).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 50.0, 100.0), view()).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 80.0, 100.0).with_mods(alt), view()).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 100.0).with_mods(alt), view()).unwrap();
|
||||
let a = first(&s, id);
|
||||
assert_eq!((a.h_in, a.kind), (Point::new(20.0, 0.0), AnchorKind::Corner), "{a:?}");
|
||||
assert!(near(a.h_out, Point::new(50.0, 80.0)), "{a:?}");
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -21,7 +21,7 @@ use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::patterncmds::add_pattern;
|
||||
use super::swatch::str_list;
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, stem};
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, shown_id, shown_library_id, stem};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
|
||||
|
||||
/// The extension of saved brush libraries: native documents.
|
||||
@@ -462,6 +462,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<BrushLibrary>
|
||||
if let Some(found) = s.brush_libraries.get(key) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(found) = concealed_library_id(s, key).and_then(|id| s.brush_libraries.get(&id)) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(b) = BUILTIN.iter().find(|b| b.id == key) {
|
||||
return Some((builtin_info(b), builtin_library(key)?));
|
||||
}
|
||||
@@ -476,20 +479,22 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.brush_libraries.rescan();
|
||||
let concealed = concealed_library_ids(s, []);
|
||||
let libs: Vec<Value> = libraries(s)
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len());
|
||||
json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.brush_libraries.path(&l.id)})
|
||||
let (id, path) = (shown_id(&concealed, &l.id), s.brush_libraries.shown_path(&l.id));
|
||||
json!({"id": id, "name": l.name, "category": l.category, "count": count, "path": path})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.brush_libraries.user_dir() }))
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.brush_libraries.shown_user_dir() }))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (info, lib) = library_param(s, p, "brush.library")?;
|
||||
let brushes: Vec<Value> = lib.brushes.iter().map(|b| json!({"name": b.name, "type": b.kind.type_id()})).collect();
|
||||
Ok(json!({"id": info.id, "name": info.name, "category": info.category, "brushes": brushes}))
|
||||
Ok(json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "brushes": brushes}))
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -545,7 +550,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let (added, existing): (Vec<&String>, Vec<&String>) = doc_names.iter().partition(|n| !before.contains(*n));
|
||||
let applied: Vec<u64> = paths.iter().map(|id| id.0).collect();
|
||||
Ok(json!({"library": info.id, "names": doc_names, "added": added, "existing": existing, "applied": applied}))
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "names": doc_names, "added": added, "existing": existing, "applied": applied}))
|
||||
}
|
||||
|
||||
fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -571,5 +576,5 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
BrushLibrary::from_document(&loaded.doc, &[], stem(file).to_string()).map_err(|e| bad(C, e))
|
||||
})?;
|
||||
Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ pub(crate) use symbols::{
|
||||
};
|
||||
use symbols::{
|
||||
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_instance_reset_transform, symbol_list, symbol_new, symbol_options,
|
||||
symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
|
||||
symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_sort, symbol_spray, symbol_unused, symbol_update,
|
||||
};
|
||||
|
||||
const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES;
|
||||
@@ -312,6 +312,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
symbol_unused
|
||||
),
|
||||
cmd!(
|
||||
"symbol.sortByName",
|
||||
"Sort by Name",
|
||||
["Window", "Symbols"],
|
||||
None,
|
||||
"{} sort the document's symbols by name, ignoring case (symbols whose names differ only in case keep their order), as one undo step; the current symbol stays current; no undo step is added when they are already in order",
|
||||
has_doc,
|
||||
symbol_sort
|
||||
),
|
||||
cmd!(query "symbol.selectInstances", "Select All Instances", [], None, "{name} select every instance of a symbol → {count}", has_doc, symbol_select_instances),
|
||||
cmd!(
|
||||
"symbol.spray",
|
||||
|
||||
@@ -140,6 +140,27 @@ pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "names": names }))
|
||||
}
|
||||
|
||||
/// `symbol.sortByName`: the symbols in name order, ignoring case; a stable sort, so names that
|
||||
/// differ only in case keep their order. The current symbol is stored by name first, so a document
|
||||
/// whose current symbol is its first one keeps that symbol current. Nothing is changed, and no undo
|
||||
/// step is added, when the symbols are already in order.
|
||||
pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let key = |sym: &Symbol| sym.name.to_lowercase();
|
||||
let d = &s.doc()?.doc;
|
||||
if d.symbols.is_sorted_by_key(key) {
|
||||
return ok();
|
||||
}
|
||||
let current = current_symbol(d).or_else(|| symbol_names(d).into_iter().next());
|
||||
s.edit("Sort by Name", |d, _| {
|
||||
if let Some(name) = current {
|
||||
d.unknown.insert(CURRENT_SYMBOL.into(), json!(name));
|
||||
}
|
||||
d.symbols.sort_by_cached_key(key);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
fn symbol_names(d: &Document) -> Vec<String> {
|
||||
d.symbols.iter().map(|s| s.name.clone()).collect()
|
||||
}
|
||||
|
||||
@@ -19,8 +19,8 @@ use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, always, bad, bool_or, check_numbers, cmd, color_value, f64_or, f64_req, has_selection, ids_param,
|
||||
str_param, unique_name,
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, f64_req, has_selection, ids_param, switch_or,
|
||||
text_param, unique_name,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -166,13 +166,15 @@ pub(crate) struct Scope {
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
pub(crate) fn of(p: &Value) -> Self {
|
||||
Self {
|
||||
fill: bool_or(p, "fill", true),
|
||||
stroke: bool_or(p, "stroke", true),
|
||||
images: bool_or(p, "includeImages", true),
|
||||
patterns: bool_or(p, "includePatterns", true),
|
||||
}
|
||||
/// The scope `p` gives; each switch left out (or null) is on. A switch that is not true or false,
|
||||
/// such as `"false"`, is an error that names `cmd`.
|
||||
pub(crate) fn of(p: &Value, cmd: &str) -> Result<Self> {
|
||||
Ok(Self {
|
||||
fill: switch_or(p, "fill", true, cmd)?,
|
||||
stroke: switch_or(p, "stroke", true, cmd)?,
|
||||
images: switch_or(p, "includeImages", true, cmd)?,
|
||||
patterns: switch_or(p, "includePatterns", true, cmd)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,18 +416,18 @@ impl ColorVisitor for Visit<'_, '_> {
|
||||
}
|
||||
|
||||
pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
|
||||
run_pass(s, p, cmd, label, Recolor::new(Scope::of(p), f))
|
||||
run_pass(s, p, cmd, label, Recolor::new(Scope::of(p, cmd)?, f))
|
||||
}
|
||||
|
||||
/// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel.
|
||||
fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
|
||||
run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p), f) })
|
||||
run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p, cmd)?, f) })
|
||||
}
|
||||
|
||||
/// [`recolor`] with solid colours and gradient stops mapped through `links`, with their swatch
|
||||
/// link and tint.
|
||||
pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, links: &LinkMap) -> Result<Value> {
|
||||
run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p), f, links))
|
||||
run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p, cmd)?, f, links))
|
||||
}
|
||||
|
||||
/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`;
|
||||
@@ -548,8 +550,9 @@ fn saturate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn adjust_balance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.colors.adjustBalance";
|
||||
check_numbers(p, &["r", "g", "b", "c", "m", "y", "k", "gray", "tint"], C)?;
|
||||
let convert = switch_or(p, "convert", false, C)?;
|
||||
let given = |keys: &[&str]| keys.iter().any(|k| p.get(*k).is_some());
|
||||
let mode = match str_param(p, "mode") {
|
||||
let mode = match text_param(p, "mode", C)? {
|
||||
Some(m) => m.to_ascii_lowercase(),
|
||||
None if given(&["c", "m", "y", "k"]) => "cmyk".into(),
|
||||
None if given(&["gray"]) => "gray".into(),
|
||||
@@ -592,11 +595,10 @@ fn adjust_balance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(*tint, *c) = (t, base.tinted(t));
|
||||
true
|
||||
};
|
||||
return run_pass(s, p, C, "Adjust Colors", Recolor::links(Scope::of(p), &shift));
|
||||
return run_pass(s, p, C, "Adjust Colors", Recolor::links(Scope::of(p, C)?, &shift));
|
||||
}
|
||||
other => return Err(bad(C, format!("unknown mode `{other}` (rgb|cmyk|gray|global)"))),
|
||||
};
|
||||
let convert = bool_or(p, "convert", false);
|
||||
let f = move |c| {
|
||||
let out = adjust(c);
|
||||
if convert { out } else { keep_model(c, out) }
|
||||
@@ -703,7 +705,7 @@ fn blend(s: &mut Session, order: BlendOrder) -> Result<Value> {
|
||||
fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.harmony";
|
||||
let base = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?;
|
||||
let rule = str_param(p, "rule").ok_or_else(|| bad(C, "missing `rule`"))?;
|
||||
let rule = text_param(p, "rule", C)?.ok_or_else(|| bad(C, "missing `rule`"))?;
|
||||
let rule = Harmony::parse(rule).ok_or_else(|| {
|
||||
let ids: Vec<String> = Harmony::ALL.iter().map(|h| h.id()).collect();
|
||||
bad(C, format!("unknown rule `{rule}` ({})", ids.join("|")))
|
||||
@@ -713,7 +715,7 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(n) = p.get("steps").and_then(Value::as_u64) {
|
||||
opts.steps = n.min(u32::MAX as u64) as u32;
|
||||
}
|
||||
if let Some(v) = str_param(p, "variation") {
|
||||
if let Some(v) = text_param(p, "variation", C)? {
|
||||
opts.variation = Variation::parse(v).ok_or_else(|| bad(C, format!("unknown variation `{v}` (tintsShades|warmCool|vividMuted)")))?;
|
||||
}
|
||||
if let Some(a) = p.get("amount").and_then(Value::as_f64) {
|
||||
|
||||
@@ -109,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Text",
|
||||
[],
|
||||
None,
|
||||
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
has_doc,
|
||||
text_create
|
||||
),
|
||||
@@ -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)
|
||||
})
|
||||
@@ -752,7 +756,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let w = f64_or(a, "width", 200.0);
|
||||
let h = f64_or(a, "height", 100.0);
|
||||
t.kind = vectorcraft_doc::TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h)) };
|
||||
t.area.fit = new_area_fit(s, a, "text.create")?;
|
||||
new_area_fit(s, a, "text.create", &mut t)?;
|
||||
}
|
||||
t.system_layout = s.doc()?.doc.setup.system_layout;
|
||||
if bool_or(p, "placeholder", false) {
|
||||
@@ -827,11 +831,16 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The fit new area type gets: `fit`/`fitMinPercent` from `p` (as `text.areaOptions` takes
|
||||
/// them), else Auto Size when the "Auto Size New Area Type" preference is on.
|
||||
pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str) -> Result<vectorcraft_doc::AreaFit> {
|
||||
/// The fit new area type `t` gets: `fit`/`fitMinPercent` from `p` (as `text.areaOptions` takes
|
||||
/// them, `block` turning Dynamic Text on), else Auto Size when the "Auto Size New Area Type"
|
||||
/// preference is on; and Block's `wordGap` and `lineGap`.
|
||||
pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject) -> Result<()> {
|
||||
let default = if s.prefs.auto_size_area_type { vectorcraft_doc::AreaFit::AutoHeight } else { vectorcraft_doc::AreaFit::None };
|
||||
Ok(super::typecmd::fit_param(p, default, c)?.unwrap_or(default))
|
||||
let (word_gap, line_gap) = super::typecmd::block_gaps(p, c)?;
|
||||
(t.area.fit, t.dynamic_text) = super::typecmd::fit_param(p, default, false, c)?.unwrap_or((default, false));
|
||||
t.area.word_gap = word_gap.unwrap_or(t.area.word_gap);
|
||||
t.area.line_gap = line_gap.unwrap_or(t.area.line_gap);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -42,7 +42,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
|
||||
("brushes", "Brushes"),
|
||||
("spotColors", "Spot Colors"),
|
||||
("patterns", "Pattern Objects"),
|
||||
("gradients", "Gradient Swatches"),
|
||||
("gradients", "Gradient Objects"),
|
||||
("symbols", "Symbols"),
|
||||
("fonts", "Fonts"),
|
||||
("fontDetails", "Font Details"),
|
||||
@@ -131,7 +131,8 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the
|
||||
/// rows of its objects filled or stroked with a pattern.
|
||||
/// rows of its objects filled or stroked with a pattern and with a gradient.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn sections(
|
||||
d: &Document,
|
||||
info: &Value,
|
||||
@@ -139,6 +140,7 @@ fn sections(
|
||||
images: &[ImageRow],
|
||||
repeats: &[(String, String)],
|
||||
pattern_objects: &[(String, String)],
|
||||
gradient_objects: &[(String, String)],
|
||||
category: Option<&str>,
|
||||
) -> Vec<Section> {
|
||||
let names = |k: &str| -> Vec<(String, String)> {
|
||||
@@ -183,7 +185,7 @@ fn sections(
|
||||
"brushes" => names("brushNames"),
|
||||
"spotColors" => names("spotColors"),
|
||||
"patterns" => pattern_objects.to_vec(),
|
||||
"gradients" => d.swatches_iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| (s.name.clone(), String::new())).collect(),
|
||||
"gradients" => gradient_objects.to_vec(),
|
||||
"symbols" => names("symbols"),
|
||||
"fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(),
|
||||
"fontDetails" => {
|
||||
@@ -254,19 +256,37 @@ pub fn report(s: &mut Session, selection_only: bool) -> Result<String> {
|
||||
Ok(v["text"].as_str().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
/// The type object `n` holds and the runs its layout draws, when it uses a pattern: the runs with a
|
||||
/// glyph outline (list markers and ruby included) or an underline or strikethrough bar. Spaces and
|
||||
/// line breaks draw no outline. A type object's characters carry their own fill and stroke, and the
|
||||
/// type object's own fills and strokes paint on its characters, so only those runs paint. The type
|
||||
/// is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the renderer lays it out.
|
||||
/// The pattern paint `p` uses: the pattern's name.
|
||||
fn pattern_label(p: &Paint) -> Option<String> {
|
||||
match p {
|
||||
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient paint `p` uses: the name of the gradient swatch it is linked to, else its kind
|
||||
/// ("Linear gradient", "Radial gradient" or "Freeform gradient").
|
||||
fn gradient_label(p: &Paint) -> Option<String> {
|
||||
match p {
|
||||
Paint::Gradient(g) => Some(g.swatch.clone().filter(|s| !s.is_empty()).unwrap_or_else(|| format!("{} gradient", g.gradient.kind.label()))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The type object `n` holds and the runs its layout draws, when it uses a pattern or a gradient:
|
||||
/// the runs with a glyph outline (list markers and ruby included) or an underline or strikethrough
|
||||
/// bar. Spaces and line breaks draw no outline. A type object's characters carry their own fill and
|
||||
/// stroke, and the type object's own fills and strokes paint on its characters, so only those runs
|
||||
/// paint. The type is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the
|
||||
/// renderer lays it out.
|
||||
fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet<usize>)> {
|
||||
let NodeKind::Text(t) = &n.kind else { return None };
|
||||
let is_pattern = |p: &Paint| matches!(p, Paint::Pattern { .. });
|
||||
let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_));
|
||||
let own = n.appearance.items.iter().any(|i| match i {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => is_pattern(&f.paint),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => is_pattern(&s.paint),
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => is_listed(&f.paint),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => is_listed(&s.paint),
|
||||
});
|
||||
if !own && !t.runs.iter().any(|r| is_pattern(&r.style.fill) || is_pattern(&r.style.stroke)) {
|
||||
if !own && !t.runs.iter().any(|r| is_listed(&r.style.fill) || is_listed(&r.style.stroke)) {
|
||||
return None;
|
||||
}
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
@@ -277,42 +297,38 @@ fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::T
|
||||
Some((t, painted))
|
||||
}
|
||||
|
||||
/// The patterns `n`'s own fills and strokes paint, each once. A hidden fill or stroke and a stroke
|
||||
/// with no width paint nothing, and neither does any fill or stroke of a guide (drawn in the guide
|
||||
/// color), of a compound path's member (`members`: the compound path's own fills and strokes paint
|
||||
/// it) or of type whose layout draws nothing (`painted_runs`). An image's fills and strokes paint
|
||||
/// only where an effect gives them a shape.
|
||||
fn own_patterns<'a>(
|
||||
/// The patterns or gradients (`label`: [`pattern_label`] or [`gradient_label`]) that `n`'s own
|
||||
/// fills and strokes paint, each once. A hidden fill or stroke and a stroke with no width paint
|
||||
/// nothing, and neither does any fill or stroke of a guide (drawn in the guide color), of a compound
|
||||
/// path's member (`members`: the compound path's own fills and strokes paint it) or of type whose
|
||||
/// layout draws nothing (`painted_runs`). An image's fills and strokes paint only where an effect
|
||||
/// gives them a shape.
|
||||
fn own_paints(
|
||||
d: &Document,
|
||||
n: &'a Node,
|
||||
n: &Node,
|
||||
members: &HashSet<*const Node>,
|
||||
painted_runs: Option<&(&vectorcraft_doc::TextObject, BTreeSet<usize>)>,
|
||||
) -> Vec<&'a str> {
|
||||
label: fn(&Paint) -> Option<String>,
|
||||
) -> Vec<String> {
|
||||
if matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
|| members.contains(&std::ptr::from_ref(n))
|
||||
|| painted_runs.is_some_and(|(_, r)| r.is_empty())
|
||||
|| !n.appearance.items.iter().any(|i| label(i.paint()).is_some())
|
||||
{
|
||||
return vec![];
|
||||
}
|
||||
// The patterns an image's shaped fills and strokes paint (their effects can transform the
|
||||
// pattern, so they are matched by name).
|
||||
let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_)).then(|| {
|
||||
vectorcraft_render::effects::image_paint(Some(d), n)
|
||||
.into_iter()
|
||||
.filter_map(|(_, _, item)| match item.paint() {
|
||||
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let mut out: Vec<&str> = vec![];
|
||||
// The patterns or gradients an image's shaped fills and strokes paint (their effects can
|
||||
// transform the paint, so they are matched by label).
|
||||
let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_))
|
||||
.then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().filter_map(|(_, _, item)| label(item.paint())).collect());
|
||||
let mut out: Vec<String> = vec![];
|
||||
for item in &n.appearance.items {
|
||||
let Paint::Pattern { pattern, .. } = item.paint() else { continue };
|
||||
let Some(name) = label(item.paint()) else { continue };
|
||||
let paints = item.visible()
|
||||
&& !matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0)
|
||||
&& shaped.as_ref().is_none_or(|s| s.contains(pattern));
|
||||
if paints && !out.contains(&pattern.as_str()) {
|
||||
out.push(pattern);
|
||||
&& shaped.as_ref().is_none_or(|s| s.contains(&name));
|
||||
if paints && !out.contains(&name) {
|
||||
out.push(name);
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -354,6 +370,11 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `pattern_objects` and `pattern_rows` hold the `patternObjects` entries and the rows of the objects filled or stroked with a pattern, in walk order.
|
||||
let mut pattern_objects: Vec<Value> = vec![];
|
||||
let mut pattern_rows: Vec<(String, String)> = vec![];
|
||||
// `gradient_objects`, `gradient_rows` and `gradients` hold the `gradientObjects` entries, the rows of the objects filled or stroked
|
||||
// with a gradient, in walk order, and the gradients they use.
|
||||
let mut gradient_objects: Vec<Value> = vec![];
|
||||
let mut gradient_rows: Vec<(String, String)> = vec![];
|
||||
let mut gradients = BTreeSet::new();
|
||||
// The objects the walk has visited: a selection can hold a group and objects inside it, and each object counts once.
|
||||
// The set holds each object's address, so two objects that share an id (as a damaged file can hold) count as two.
|
||||
let mut seen: HashSet<*const Node> = HashSet::new();
|
||||
@@ -412,27 +433,17 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(k) = k {
|
||||
*counts.entry(k).or_default() += 1;
|
||||
}
|
||||
// The paint kinds this object's fills and strokes use, each once.
|
||||
let mut kinds = BTreeSet::new();
|
||||
// The patterns this object's fills and strokes use, each once.
|
||||
let mut used_patterns: Vec<&str> = vec![];
|
||||
let painted_runs = painted_runs(d, n);
|
||||
for pattern in own_patterns(d, n, &members, painted_runs.as_ref()) {
|
||||
patterns.insert(pattern.to_string());
|
||||
used_patterns.push(pattern);
|
||||
}
|
||||
for item in &n.appearance.items {
|
||||
let paint = item.paint();
|
||||
// Objects counts an object with a pattern when Pattern Objects lists it, below.
|
||||
if let Paint::Gradient(_) = paint {
|
||||
kinds.insert("gradients");
|
||||
}
|
||||
if let Paint::Solid { swatch: Some(name), .. } = paint
|
||||
if let Paint::Solid { swatch: Some(name), .. } = item.paint()
|
||||
&& d.swatch(name).is_some_and(|s| s.spot)
|
||||
{
|
||||
spot.insert(name.clone());
|
||||
}
|
||||
}
|
||||
// The patterns and the gradients this object's fills and strokes paint, each once.
|
||||
let painted_runs = painted_runs(d, n);
|
||||
let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), pattern_label);
|
||||
let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), gradient_label);
|
||||
// The characters' own paints: an inline graphic draws no outline and does not take its
|
||||
// run's paint (a list marker set in its run does), and a stroke with no width paints
|
||||
// nothing.
|
||||
@@ -440,23 +451,32 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for run in painted.iter().filter_map(|i| t.runs.get(*i)) {
|
||||
let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke);
|
||||
for paint in std::iter::once(&run.style.fill).chain(stroke) {
|
||||
if let Paint::Pattern { pattern, .. } = paint {
|
||||
patterns.insert(pattern.clone());
|
||||
if !used_patterns.contains(&pattern.as_str()) {
|
||||
used_patterns.push(pattern);
|
||||
for (used, label) in
|
||||
[(&mut used_patterns, pattern_label as fn(&Paint) -> Option<String>), (&mut used_gradients, gradient_label)]
|
||||
{
|
||||
if let Some(name) = label(paint)
|
||||
&& !used.contains(&name)
|
||||
{
|
||||
used.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Objects counts the objects that Pattern Objects and Gradient Objects list.
|
||||
if !used_patterns.is_empty() {
|
||||
let name = n.display_name();
|
||||
patterns.extend(used_patterns.iter().cloned());
|
||||
pattern_rows.push((name.clone(), used_patterns.join(", ")));
|
||||
pattern_objects.push(json!({ "id": n.id.0, "name": name, "patterns": used_patterns }));
|
||||
pattern_rows.push((name, used_patterns.join(", ")));
|
||||
kinds.insert("patterns");
|
||||
*counts.entry("patterns").or_default() += 1;
|
||||
}
|
||||
for k in kinds {
|
||||
*counts.entry(k).or_default() += 1;
|
||||
if !used_gradients.is_empty() {
|
||||
let name = n.display_name();
|
||||
gradients.extend(used_gradients.iter().cloned());
|
||||
gradient_rows.push((name.clone(), used_gradients.join(", ")));
|
||||
gradient_objects.push(json!({ "id": n.id.0, "name": name, "gradients": used_gradients }));
|
||||
*counts.entry("gradients").or_default() += 1;
|
||||
}
|
||||
if n.extras().mask.is_some() {
|
||||
*counts.entry("opacityMasks").or_default() += 1;
|
||||
@@ -506,10 +526,12 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"patterns": d.patterns.len(),
|
||||
"patternNames": patterns,
|
||||
"patternObjects": pattern_objects,
|
||||
"gradientNames": gradients,
|
||||
"gradientObjects": gradient_objects,
|
||||
});
|
||||
// The document's name: its file's, else its title.
|
||||
out["document"]["name"] = json!(st.title());
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, category);
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, &gradient_rows, category);
|
||||
if text {
|
||||
return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) }));
|
||||
}
|
||||
@@ -583,12 +605,14 @@ mod tests {
|
||||
&json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap();
|
||||
let t = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
// The type's characters take the current gradient fill, so it is a gradient object too.
|
||||
assert_eq!(
|
||||
(i["objects"]["paths"].as_u64(), i["objects"]["textObjects"].as_u64(), i["objects"]["gradients"].as_u64()),
|
||||
(Some(1), Some(1), Some(1))
|
||||
(Some(1), Some(1), Some(2))
|
||||
);
|
||||
assert_eq!((i["gradientObjects"][0]["id"].clone(), i["gradientObjects"][1]["id"].clone()), (r.clone(), t));
|
||||
assert_eq!(i["fonts"][0], "Source Sans 3 Regular");
|
||||
assert_eq!(i["document"]["artboards"][0]["width"], 200.0);
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
@@ -842,6 +866,124 @@ mod tests {
|
||||
assert!(!text.contains("Unused"), "{text}");
|
||||
}
|
||||
|
||||
/// Document Info › Gradient Objects lists each object filled or stroked with a gradient once,
|
||||
/// with the gradients it uses (a linked swatch by name, else the gradient's kind), one in a
|
||||
/// group and a type object whose characters use a gradient included; a gradient swatch no art
|
||||
/// uses adds no row, paint that draws nothing is left out by the rules Pattern Objects follows,
|
||||
/// and Objects counts the listed objects. With Selection Only it lists the objects in the
|
||||
/// selection, each once, and the report writes the same rows.
|
||||
#[test]
|
||||
fn info_lists_the_gradient_objects() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let square =
|
||||
|s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let ramp = |kind: &str| json!({"kind": kind, "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
|
||||
s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp("linear")})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Spare", "gradient": ramp("radial")})).unwrap();
|
||||
let (a, b, c, f) = (square(&mut s, 100.0), square(&mut s, 200.0), square(&mut s, 300.0), square(&mut s, 0.0));
|
||||
s.execute("paint.setFill", &json!({"ids": [a], "swatch": "Ramp"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [a], "gradient": ramp("linear")})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": a, "name": "Both"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [b], "gradient": ramp("radial")})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [f], "gradient": ramp("freeform")})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [b, c]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].clone();
|
||||
// A type object whose characters are filled with the gradient.
|
||||
let t = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [t], "swatch": "Ramp"})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": t, "name": "Type"})).unwrap();
|
||||
// A hidden gradient fill and a gradient stroke with no width paint nothing, so neither object is listed.
|
||||
let (d, e) = (square(&mut s, 100.0), square(&mut s, 200.0));
|
||||
s.execute("paint.setStroke", &json!({"ids": [d], "none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [d], "swatch": "Ramp"})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [d], "index": 0, "visible": false})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [e], "gradient": ramp("linear")})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap();
|
||||
// Type with no characters, or of only spaces and a line break, paints nothing, and neither
|
||||
// does a guide made from a path with a gradient.
|
||||
let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Ramp"})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({"ids": [empty]})).unwrap();
|
||||
let blank = s.execute("text.create", &json!({"x": 0, "y": 320, "text": " \n"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [blank], "swatch": "Ramp"})).unwrap();
|
||||
let guide = square(&mut s, 300.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [guide], "swatch": "Ramp"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [guide]})).unwrap();
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
// Nor does a compound path's member's own gradient fill, or an image's gradient fill
|
||||
// without an effect that gives it a shape.
|
||||
let (m1, m2) = (square(&mut s, 320.0), square(&mut s, 340.0));
|
||||
s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [compound], "color": "#000000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [compound], "none": true})).unwrap();
|
||||
let node = |s: &Session, id: &Value| s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone();
|
||||
let (member, paint) = (node(&s, &compound).children().unwrap()[0].id, node(&s, &a).appearance);
|
||||
let pic = square(&mut s, 360.0);
|
||||
s.execute("select.set", &json!({"ids": [pic]})).unwrap();
|
||||
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
|
||||
let image = s.doc().unwrap().selection.objects[0];
|
||||
s.edit("own paint", |d, _| {
|
||||
d.node_mut(member).unwrap().appearance = paint.clone();
|
||||
d.node_mut(image).unwrap().appearance = paint;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// Underlined spaces draw a bar in the gradient, so that type object is listed.
|
||||
let bar = s.execute("text.create", &json!({"x": 0, "y": 340, "text": " "})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [bar], "swatch": "Ramp"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [bar]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"underline": true})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": bar, "name": "Bar"})).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
i["gradientObjects"],
|
||||
json!([
|
||||
{"id": a, "name": "Both", "gradients": ["Ramp", "Linear gradient"]},
|
||||
{"id": b, "name": "<Rectangle>", "gradients": ["Radial gradient"]},
|
||||
{"id": f, "name": "<Rectangle>", "gradients": ["Freeform gradient"]},
|
||||
{"id": t, "name": "Type", "gradients": ["Ramp"]},
|
||||
{"id": bar, "name": "Bar", "gradients": ["Ramp"]},
|
||||
])
|
||||
);
|
||||
assert_eq!(i["gradientNames"], json!(["Freeform gradient", "Linear gradient", "Radial gradient", "Ramp"]));
|
||||
// Objects counts the objects that Gradient Objects lists.
|
||||
assert_eq!(i["objects"]["gradients"].as_u64(), Some(5), "{}", i["objects"]);
|
||||
s.execute("select.set", &json!({"ids": [d, e, empty, blank, guide, compound, image.0]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
|
||||
assert!(i["objects"]["gradients"].is_null() && i["gradientObjects"] == json!([]), "{}", i["objects"]);
|
||||
let i = s.execute("document.info", &json!({"category": "gradients"})).unwrap();
|
||||
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("gradients"), Some("Gradient Objects")));
|
||||
assert_eq!(
|
||||
i["sections"][0]["rows"],
|
||||
json!([
|
||||
["Both", "Ramp, Linear gradient"],
|
||||
["<Rectangle>", "Radial gradient"],
|
||||
["<Rectangle>", "Freeform gradient"],
|
||||
["Type", "Ramp"],
|
||||
["Bar", "Ramp"]
|
||||
])
|
||||
);
|
||||
// A selection that holds the group and the object inside it lists that object once.
|
||||
for ids in [json!([group, b]), json!([b, group])] {
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "gradients"})).unwrap();
|
||||
assert_eq!(i["sections"][0]["rows"], json!([["<Rectangle>", "Radial gradient"]]), "{ids}");
|
||||
assert_eq!(i["objects"]["gradients"].as_u64(), Some(1), "{ids}");
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [t]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "gradients"})).unwrap();
|
||||
assert_eq!((i["sections"][0]["rows"].clone(), i["gradientNames"].clone()), (json!([["Type", "Ramp"]]), json!(["Ramp"])));
|
||||
let text = s.execute("document.info", &json!({"category": "gradients", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(
|
||||
text.contains("\nGRADIENT OBJECTS\nBoth: Ramp, Linear gradient\n<Rectangle>: Radial gradient\n<Rectangle>: Freeform gradient\nType: Ramp\nBar: Ramp\n"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(!text.contains("Spare"), "{text}");
|
||||
}
|
||||
|
||||
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
|
||||
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
|
||||
/// it counts that object once.
|
||||
|
||||
@@ -13,8 +13,8 @@ use super::edit::selected_roots;
|
||||
use super::pathops::Beside;
|
||||
use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Point, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, f64_req, has_doc, has_selection, id_param, ok,
|
||||
str_param, switch_or,
|
||||
CommandSpec, EngineError, Point, Result, Session, bad, checked_ids_param, cmd, f64_req, has_doc, has_selection, id_param, number_or, ok,
|
||||
str_param, switch_or, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -482,7 +482,7 @@ fn save_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let ids = st.selection.objects.clone();
|
||||
let saved = &st.doc.saved_selections;
|
||||
let name = str_param(p, "name").and_then(SavedSelection::clean_name).unwrap_or_else(|| SavedSelection::default_name(saved));
|
||||
let name = text_param(p, "name", C)?.and_then(SavedSelection::clean_name).unwrap_or_else(|| SavedSelection::default_name(saved));
|
||||
let existing = saved.iter().position(|x| x.name == name);
|
||||
if existing.is_none() && saved.len() >= SavedSelection::MAX {
|
||||
return Err(bad(C, format!("a document keeps at most {} saved selections", SavedSelection::MAX)));
|
||||
@@ -577,10 +577,12 @@ fn edit_saved(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for e in edits {
|
||||
let name = str_param(e, "name").ok_or_else(|| bad(C, "missing name"))?;
|
||||
let i = *index.get(name).ok_or_else(|| bad(C, format!("no saved selection `{name}`")))?;
|
||||
let delete = switch_or(e, "delete", false, C)?;
|
||||
let new_name = text_param(e, "newName", C)?;
|
||||
let Some(slot) = after.get_mut(i) else { continue };
|
||||
if bool_or(e, "delete", false) {
|
||||
if delete {
|
||||
*slot = None;
|
||||
} else if let Some(n) = str_param(e, "newName").and_then(SavedSelection::clean_name)
|
||||
} else if let Some(n) = new_name.and_then(SavedSelection::clean_name)
|
||||
&& let Some(x) = slot
|
||||
{
|
||||
x.name = n;
|
||||
@@ -764,7 +766,7 @@ fn clear_guides(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
fn guide_add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pos = f64_req(p, "pos", "guide.add")?;
|
||||
let vertical = bool_or(p, "vertical", false);
|
||||
let vertical = switch_or(p, "vertical", false, "guide.add")?;
|
||||
let artboard = match p.get("artboard").filter(|v| !v.is_null()) {
|
||||
Some(v) => {
|
||||
let boards = &s.doc()?.doc.artboards;
|
||||
@@ -845,7 +847,7 @@ fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let list = p.get("indexes").and_then(Value::as_array).ok_or_else(|| bad("guide.select", "missing indexes"))?;
|
||||
let ids = guide_ids(&s.doc()?.doc);
|
||||
let picked = list.iter().map(|v| guide_index_in(&ids, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?;
|
||||
if bool_or(p, "toggle", false) {
|
||||
if switch_or(p, "toggle", false, "guide.select")? {
|
||||
// Added to (or taken from) what is selected, the art included.
|
||||
s.select(|_, sel| {
|
||||
for i in picked {
|
||||
@@ -924,7 +926,9 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if moving.is_empty() {
|
||||
return Err(bad("guide.move", "no guide selected (or give an index)"));
|
||||
}
|
||||
let (dx, dy, copy) = (f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0), bool_or(p, "copy", false));
|
||||
let dx = number_or(p, "dx", 0.0, "guide.move")?;
|
||||
let dy = number_or(p, "dy", 0.0, "guide.move")?;
|
||||
let copy = switch_or(p, "copy", false, "guide.move")?;
|
||||
if !s.doc()?.selection.is_empty() {
|
||||
let ids = super::edit::selected_roots(s)?;
|
||||
return super::object::apply_transform(
|
||||
|
||||
@@ -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}`"))),
|
||||
|
||||
+104
-25
@@ -9,9 +9,9 @@ use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use super::clipboard::SwatchChoices;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, clock_date, cmd, date_param,
|
||||
f64_or, f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param,
|
||||
index, ok, point_param, str_param, switch_or,
|
||||
CommandSpec, Result, Session, always, bad, can_clear_history, can_redo, can_undo, check_numbers, checked_ids_param, clock_date, cmd, date_param,
|
||||
f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index,
|
||||
number_or, ok, point_param, str_param, switch_or,
|
||||
};
|
||||
use crate::{Clipboard, EngineError, inspect};
|
||||
|
||||
@@ -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
|
||||
),
|
||||
@@ -184,7 +184,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste in Front",
|
||||
["Edit"],
|
||||
Some("Cmd+F"),
|
||||
"{swatchConflict?, artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
"{swatchConflict?, artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one), artboards?: [index…] (a copy on each of these artboards, placed as on `artboard`, the copies in artboard order; `artboard` wins when both are given; default while the Artboard tool is chosen with several artboards selected: those; art copied from no artboard keeps its place on the first and its offset to it on the others; an index the document lacks, a repeated one or an empty list is an error)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Front)
|
||||
),
|
||||
@@ -193,7 +193,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste in Back",
|
||||
["Edit"],
|
||||
Some("Cmd+B"),
|
||||
"{swatchConflict?, artboard?: index (as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
"{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Back)
|
||||
),
|
||||
@@ -202,7 +202,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste in Place",
|
||||
["Edit"],
|
||||
Some("Cmd+Shift+V"),
|
||||
"{swatchConflict?, artboard?: index (as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}",
|
||||
"{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::InPlace)
|
||||
),
|
||||
@@ -237,7 +237,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
fn file_close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = p.get("index").and_then(Value::as_u64).map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?;
|
||||
let i = opt_u64(p, "file.close", "index")?.map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?;
|
||||
if !s.close_document(i) {
|
||||
return Err(bad("file.close", "no such document"));
|
||||
}
|
||||
@@ -269,7 +269,7 @@ fn doc_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn doc_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("document.node", "missing id"))?;
|
||||
let mut opts = slice_opts(p, "document.node")?;
|
||||
let summary = bool_or(p, "summary", false);
|
||||
let summary = switch_or(p, "summary", false, "document.node")?;
|
||||
if !summary && (opts.depth.is_some() || opts.child_limit.is_some()) {
|
||||
// The full object JSON is never truncated: a slice without `summary` would
|
||||
// otherwise silently return the whole subtree.
|
||||
@@ -663,7 +663,8 @@ fn undo_group_begin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.end_undo_group(bool_or(p, "cancel", false));
|
||||
let cancel = switch_or(p, "cancel", false, "edit.undoGroup.end")?;
|
||||
s.end_undo_group(cancel);
|
||||
ok()
|
||||
}
|
||||
|
||||
@@ -672,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));
|
||||
}
|
||||
@@ -1231,6 +1236,9 @@ impl PasteMode {
|
||||
|
||||
fn paste(s: &mut Session, p: &Value, mode: PasteMode) -> Result<Value> {
|
||||
let choices = SwatchChoices::parse(mode.label(), p)?;
|
||||
if mode == PasteMode::Offset {
|
||||
check_numbers(p, &["dx", "dy"], "edit.paste")?;
|
||||
}
|
||||
// Taken out of the session for the edit (and put back whatever happens).
|
||||
let clip = std::mem::take(&mut s.clipboard);
|
||||
let r = paste_clip(s, p, mode, &clip, &choices);
|
||||
@@ -1246,15 +1254,79 @@ pub(crate) fn place_clip(s: &mut Session, clip: &Clipboard, center: vectorcraft_
|
||||
paste_clip(s, &json!({ "center": [center.x, center.y] }), PasteMode::Library, clip, &choices)
|
||||
}
|
||||
|
||||
/// Paste in Place, in Front or in Back onto artboard `artboard` (the active one, #693): where the
|
||||
/// objects were on the artboard they were copied from, on that one; without it (or a copy from no
|
||||
/// artboard), where they were.
|
||||
fn onto_artboard(doc: &Document, p: &Value, clip: &Clipboard) -> Affine {
|
||||
let target = p.get("artboard").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).and_then(|i| doc.artboards.get(i));
|
||||
match (target, clip.source_artboard) {
|
||||
(Some(t), Some(src)) => Affine::translate(t.rect.origin() - src.origin()),
|
||||
_ => Affine::IDENTITY,
|
||||
/// The artboards Paste in Place, in Front or in Back puts a copy on, in artboard order: `artboard`
|
||||
/// (the active one, #693), else `artboards`, else, while the Artboard tool is chosen with several
|
||||
/// artboards selected, those (noted in the journal as `artboards`, so a replay pastes on the same
|
||||
/// ones); `None` when none is named. A named index that is not an artboard of the document, a
|
||||
/// repeated one or an empty list is an error.
|
||||
fn paste_targets(s: &mut Session, p: &Value, cmd: &str) -> Result<Option<Vec<usize>>> {
|
||||
let n = s.doc()?.doc.artboards.len();
|
||||
let one = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n);
|
||||
let single = match p.get("artboard") {
|
||||
Some(v) => Some(one(v).ok_or_else(|| bad(cmd, "`artboard` must be the index of an artboard of the document"))?),
|
||||
None => None,
|
||||
};
|
||||
let listed = match p.get("artboards") {
|
||||
Some(v) => {
|
||||
let list = v.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(cmd, "`artboards` must be a list of artboard indices"))?;
|
||||
let mut all = list
|
||||
.iter()
|
||||
.map(one)
|
||||
.collect::<Option<Vec<usize>>>()
|
||||
.ok_or_else(|| bad(cmd, "`artboards` names an artboard the document does not have"))?;
|
||||
all.sort_unstable();
|
||||
if all.windows(2).any(|w| w[0] == w[1]) {
|
||||
return Err(bad(cmd, "`artboards` names an artboard twice"));
|
||||
}
|
||||
Some(all)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if let Some(i) = single {
|
||||
return Ok(Some(vec![i]));
|
||||
}
|
||||
if listed.is_some() {
|
||||
return Ok(listed);
|
||||
}
|
||||
let picked = artboard_tool_picks(s);
|
||||
if picked.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
s.note_journal("artboards", json!(picked));
|
||||
Ok(Some(picked))
|
||||
}
|
||||
|
||||
/// The artboards of the active document the Artboard tool has selected, in artboard order, while
|
||||
/// that tool is chosen with two or more of them selected; otherwise none. Indices the document
|
||||
/// does not have are left out.
|
||||
pub(crate) fn artboard_tool_picks(s: &Session) -> Vec<usize> {
|
||||
if s.tool_id() != "artboard" {
|
||||
return Vec::new();
|
||||
}
|
||||
let n = s.active().map_or(0, |d| d.doc.artboards.len());
|
||||
let mut picked: Vec<usize> = s.tool_options_of("artboard")["selected"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|v| v.as_u64().and_then(|i| usize::try_from(i).ok()))
|
||||
.filter(|i| *i < n)
|
||||
.collect();
|
||||
picked.sort_unstable();
|
||||
picked.dedup();
|
||||
if picked.len() < 2 {
|
||||
picked.clear();
|
||||
}
|
||||
picked
|
||||
}
|
||||
|
||||
/// Paste in Place, in Front or in Back onto artboards `targets`: one copy on each, where the objects
|
||||
/// were on the artboard they were copied from. A copy from no artboard keeps its place on the first
|
||||
/// target and its offset to that one on the others; without targets, the objects go where they were.
|
||||
fn onto_artboards(doc: &Document, targets: Option<&[usize]>, clip: &Clipboard) -> Vec<Affine> {
|
||||
let rects: Vec<_> = targets.unwrap_or_default().iter().filter_map(|i| doc.artboards.get(*i)).map(|a| a.rect.origin()).collect();
|
||||
let Some(first) = rects.first().copied() else { return vec![Affine::IDENTITY] };
|
||||
let src = clip.source_artboard.map_or(first, |r| r.origin());
|
||||
rects.iter().map(|o| Affine::translate(*o - src)).collect()
|
||||
}
|
||||
|
||||
/// Insert clipboard resources atomically in the active editable context using the requested placement mode.
|
||||
@@ -1268,6 +1340,12 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let targets = match mode {
|
||||
PasteMode::Front => paste_targets(s, p, "edit.pasteInFront")?,
|
||||
PasteMode::Back => paste_targets(s, p, "edit.pasteInBack")?,
|
||||
PasteMode::InPlace => paste_targets(s, p, "edit.pasteInPlace")?,
|
||||
_ => None,
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let same_doc = clip.source_doc == Some(st.uid);
|
||||
let parent = st.target_parent_for_path()?;
|
||||
@@ -1315,14 +1393,15 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
(_, Some((_, dv))) => vec![Affine::translate(dv)],
|
||||
(PasteMode::Offset | PasteMode::Library | PasteMode::Drag, None) => vec![match point_param(p, "center") {
|
||||
Some(c) => clip.bounds().map_or(Affine::IDENTITY, |b| Affine::translate(c - b.center())),
|
||||
None => Affine::translate((f64_or(p, "dx", off), f64_or(p, "dy", off))),
|
||||
None => Affine::translate((number_or(p, "dx", off, mode.label())?, number_or(p, "dy", off, mode.label())?)),
|
||||
}],
|
||||
(PasteMode::AllArtboards, None) => {
|
||||
let src = clip.source_artboard.or_else(|| st.doc.artboards.first().map(|a| a.rect)).map(|r| r.origin()).unwrap_or_default();
|
||||
st.doc.artboards.iter().map(|a| Affine::translate(a.rect.origin() - src)).collect()
|
||||
}
|
||||
// In place, in front, in back: onto the active artboard when the UI names it.
|
||||
_ => vec![onto_artboard(&st.doc, p, clip)],
|
||||
// In place, in front, in back: onto the active artboard when the UI names it, or onto each
|
||||
// artboard the Artboard tool has selected.
|
||||
_ => onto_artboards(&st.doc, targets.as_deref(), clip),
|
||||
};
|
||||
// Guides alone don't follow a plain paste's offset or the view centre: they stay where they
|
||||
// were. With objects they move as the objects do.
|
||||
@@ -1489,8 +1568,8 @@ fn layer_named(d: &mut Document, name: &str) -> NodeId {
|
||||
|
||||
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = selected_roots(s)?;
|
||||
let dx = f64_or(p, "dx", 0.0);
|
||||
let dy = f64_or(p, "dy", 0.0);
|
||||
let dx = number_or(p, "dx", 0.0, "edit.duplicate")?;
|
||||
let dy = number_or(p, "dy", 0.0, "edit.duplicate")?;
|
||||
let ids = s.edit("Duplicate", |d, sel| duplicate_in(d, sel, &roots, Affine::translate((dx, dy))))?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
@@ -881,3 +881,56 @@ fn move_takes_several_effects_that_land_together_in_order() {
|
||||
assert!(s.execute("effect.move", &json!({"from": [0, 9], "to": 0, "fromItem": null, "ids": [id.0]})).is_err());
|
||||
assert_eq!(node(&s, id).appearance, before);
|
||||
}
|
||||
|
||||
/// A 3D effect's shadow is set with `effect.setParams` in one undo step, saved in the native file,
|
||||
/// drawn in exports and kept as a path by Expand Appearance; settings out of range are refused
|
||||
/// without an undo step.
|
||||
#[test]
|
||||
fn a_3d_shadow_is_one_undo_step_saved_exported_and_expanded() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for (params, why) in [
|
||||
(json!({"shadowBounds": 401}), "shadowBounds must be a number from 10 to 400"),
|
||||
(json!({"shadowPosition": "left"}), "shadowPosition must be behind or below"),
|
||||
] {
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": params})).unwrap_err().to_string();
|
||||
assert!(e.contains(why), "{params}: {e}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
let params = json!({"shadow": true, "shadowPosition": "below", "shadowDistance": 20, "shadowBounds": 150});
|
||||
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": params})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let art = effects::solid_art(&node(&s, id)).unwrap();
|
||||
let shadow = art.children().unwrap()[0].clone();
|
||||
assert!(matches!(shadow.kind, NodeKind::Path { .. }));
|
||||
// Saved and opened again, the effect keeps its shadow settings and draws the same shadow.
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
let fx = &restored.node(id).unwrap().appearance.effects[0];
|
||||
for (key, value) in params.as_object().unwrap() {
|
||||
assert_eq!(fx.params.get(key), Some(value), "{key}");
|
||||
}
|
||||
assert_eq!(effects::solid_art(restored.node(id).unwrap()).unwrap(), art);
|
||||
// SVG export draws it: one more shape than without the shadow.
|
||||
let shapes = |s: &mut Session| {
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string());
|
||||
vectorcraft_testkit::svg_shapes(&svg)
|
||||
};
|
||||
let with = shapes(&mut s);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let without = shapes(&mut s);
|
||||
assert_eq!(with, without + 1);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
|
||||
let mut shadows = 0;
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if n.path_data().is_some() && n.path_data() == shadow.path_data() && n.appearance.items == shadow.appearance.items {
|
||||
shadows += 1;
|
||||
}
|
||||
});
|
||||
assert_eq!(shadows, 1);
|
||||
}
|
||||
|
||||
@@ -36,6 +36,9 @@ pub const MAX_STEPS: u32 = 1000;
|
||||
const FREEFORM_MESH: u32 = 8;
|
||||
/// Columns (around the centre) of the mesh a radial gradient expands to.
|
||||
const RADIAL_MESH_COLS: usize = 8;
|
||||
/// Largest turn between a conic gradient's mesh columns, so their straight outer edges stay
|
||||
/// close enough to a circle to reach past the box.
|
||||
const CONIC_MESH_GAP: f64 = 1.0 / 32.0;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -44,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) | \"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
|
||||
),
|
||||
@@ -1279,7 +1282,13 @@ fn breaks(g: &Gradient, t0: f64, t1: f64, max_gap: f64) -> Vec<(f64, (Color, f32
|
||||
/// end, the vector across it (radial: the ellipse's other axis), and the parameter ranges that
|
||||
/// 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). 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,
|
||||
@@ -1309,7 +1318,19 @@ impl Frame {
|
||||
}
|
||||
// Keep a sliver of span so the art maps back invertibly.
|
||||
t1 = t1.max(t0 + 1e-6);
|
||||
Self { radial, start: geom.start, focal: geom.focal_point(), along, across, t0, t1, s0, s1 }
|
||||
let conic = (g.gradient.kind == GradientKind::Conic).then(|| {
|
||||
let to_unit = geom.conic_frame().inverse();
|
||||
let reach = corners.iter().map(|c| (to_unit * *c).to_vec2().hypot()).fold(0.0f64, f64::max).max(1e-6);
|
||||
// Past the corners, and far enough out that the chords between columns at most
|
||||
// CONIC_MESH_GAP of a turn apart stay outside them.
|
||||
let reach = if reach.is_finite() { reach * 1.01 / (std::f64::consts::PI * CONIC_MESH_GAP).cos() } else { 1.0 };
|
||||
(geom, bounds, reach)
|
||||
});
|
||||
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`
|
||||
@@ -1325,6 +1346,46 @@ impl Frame {
|
||||
/// A gradient mesh covering the box: columns (linear) or rings (radial) where the colour
|
||||
/// changes, so it paints the gradient exactly.
|
||||
fn mesh(&self, g: &Gradient) -> GradientMesh {
|
||||
if let Some((geom, _, reach)) = &self.conic {
|
||||
// Columns around the center where the color changes, at most CONIC_MESH_GAP of a turn
|
||||
// apart so the outer edge stays past the box; the seam is two columns in one place.
|
||||
let br = breaks(g, 0.0, 1.0, CONIC_MESH_GAP);
|
||||
let us: Vec<f64> = br.iter().map(|(t, _)| *t).collect();
|
||||
let frame = geom.conic_frame();
|
||||
let at = |u: f64, v: f64| {
|
||||
let a = u * std::f64::consts::TAU;
|
||||
frame * Point::new(reach * v * a.cos(), reach * v * a.sin())
|
||||
};
|
||||
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);
|
||||
@@ -1340,13 +1401,44 @@ 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). 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.
|
||||
/// 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, 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 {
|
||||
return geom
|
||||
.conic_wedges(*b, n, opaque)
|
||||
.into_iter()
|
||||
.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);
|
||||
let opaque = g.stops.iter().all(|s| s.opacity >= 1.0);
|
||||
if self.radial {
|
||||
let ellipse = |t: f64| {
|
||||
let c = self.focal + (self.start - self.focal) * t;
|
||||
@@ -1376,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)
|
||||
}
|
||||
|
||||
@@ -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…).
|
||||
@@ -50,6 +50,7 @@ mod pdfimport;
|
||||
pub mod pngtext;
|
||||
pub mod ppi;
|
||||
pub mod progress;
|
||||
mod psdlayers;
|
||||
pub mod psdread;
|
||||
mod pxrread;
|
||||
mod save;
|
||||
@@ -204,6 +205,8 @@ mod tests_eps;
|
||||
#[cfg(test)]
|
||||
mod tests_dxfimport;
|
||||
#[cfg(test)]
|
||||
mod tests_hpgl;
|
||||
#[cfg(test)]
|
||||
mod tests_metafile;
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -218,6 +221,8 @@ mod tests_pdfx;
|
||||
#[cfg(test)]
|
||||
mod tests_psd;
|
||||
#[cfg(test)]
|
||||
mod tests_psdlayers;
|
||||
#[cfg(test)]
|
||||
mod tests_psdread;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -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")));
|
||||
@@ -716,6 +726,11 @@ fn collect_files(folder: &str, include_subdirs: bool, depth: usize) -> Result<Ve
|
||||
}
|
||||
}
|
||||
files.sort();
|
||||
// Names that are not valid text come back lossily, so different names can give one path: each
|
||||
// folder is listed once.
|
||||
files.dedup();
|
||||
subdirs.sort();
|
||||
subdirs.dedup();
|
||||
for sub in subdirs {
|
||||
let mut nested = collect_files(&sub, true, depth + 1)?;
|
||||
files.append(&mut nested);
|
||||
@@ -749,6 +764,22 @@ mod tests {
|
||||
d
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn folders_whose_names_alias_after_lossy_conversion_are_listed_once() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let root = tmp("alias");
|
||||
// `a\u{FFFD}` is a real folder; two others with bytes that aren't text give the same name.
|
||||
let real = root.join("a\u{FFFD}");
|
||||
std::fs::create_dir_all(&real).unwrap();
|
||||
write_svg(&real, "x.svg", "red");
|
||||
for bad in [b"a\xFF", b"a\xFE"] {
|
||||
let _ = std::fs::create_dir_all(root.join(std::ffi::OsStr::from_bytes(bad)));
|
||||
}
|
||||
let files = collect_files(&root.to_string_lossy(), true, 0).unwrap();
|
||||
assert_eq!(files.len(), 1, "{files:?}");
|
||||
}
|
||||
|
||||
fn write_svg(dir: &std::path::Path, name: &str, fill: &str) -> std::path::PathBuf {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(
|
||||
@@ -789,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() {
|
||||
|
||||
@@ -188,17 +188,24 @@ impl Builder {
|
||||
let kind = match g.kind {
|
||||
AfKind::Linear => GradientKind::Linear,
|
||||
AfKind::Radial => GradientKind::Radial,
|
||||
AfKind::Conical => {
|
||||
self.warn("conical gradients import as radial gradients");
|
||||
GradientKind::Radial
|
||||
}
|
||||
AfKind::Conical => GradientKind::Conic,
|
||||
};
|
||||
let (u, v): (Vec2, Vec2) = (x - o, y - o);
|
||||
if kind == GradientKind::Radial && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 {
|
||||
if kind.is_centered() && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 {
|
||||
self.warn("skewed elliptical gradients import as upright ellipses");
|
||||
}
|
||||
let aspect = if u.hypot() > 0.0 { (v.hypot() / u.hypot()).clamp(0.01, 100.0) } else { 1.0 };
|
||||
let geom = GradientGeom { start: o, end: x, aspect: if kind == GradientKind::Radial { aspect } else { 1.0 }, focal: None };
|
||||
let geom = match kind {
|
||||
// A conic sweeps from unit +x towards unit +y: its unit frame carried onto the
|
||||
// page as a transform carries it (mirrored when the transform is a reflection).
|
||||
GradientKind::Conic => {
|
||||
let mut geom = GradientGeom { start: Point::ZERO, end: Point::new(1.0, 0.0), aspect: 1.0, focal: None };
|
||||
geom.transform(m, GradientKind::Conic);
|
||||
geom
|
||||
}
|
||||
GradientKind::Radial => GradientGeom { start: o, end: x, aspect, focal: None },
|
||||
_ => GradientGeom { start: o, end: x, aspect: 1.0, focal: None },
|
||||
};
|
||||
let mut gp = GradientPaint::new(Gradient::new(kind, stops));
|
||||
gp.angle = (-(u.y)).atan2(u.x).to_degrees();
|
||||
gp.geom = Some(geom);
|
||||
|
||||
@@ -76,7 +76,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// starts (one for all the steps in that document), so a step may open, switch or close documents.
|
||||
/// A step that acts on the active artboard ([`crate::ON_ACTIVE_ARTBOARD`]) and names none gets
|
||||
/// `artboard`, as the Artboards panel shows it in the document the step runs in: past that
|
||||
/// document's last artboard, the last one. A step that resizes the active artboard
|
||||
/// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names
|
||||
/// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with
|
||||
/// several artboards selected, pastes on those. A step that resizes the active artboard
|
||||
/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`.
|
||||
/// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them.
|
||||
fn run_steps(
|
||||
@@ -104,9 +106,14 @@ fn run_steps(
|
||||
} else {
|
||||
crate::FIT_ACTIVE_ARTBOARD.contains(&id.as_str()).then_some("index")
|
||||
};
|
||||
// A paste step that names its `artboards` keeps them; one that names neither key, while the
|
||||
// Artboard tool is chosen with several artboards selected, pastes on those.
|
||||
let names_artboards = id.starts_with("edit.pasteIn")
|
||||
&& (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty()));
|
||||
if let Some(a) = artboard
|
||||
&& let Some(key) = key
|
||||
&& params.get(key).is_none()
|
||||
&& !names_artboards
|
||||
&& let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1))
|
||||
&& let Some(o) = params.as_object_mut()
|
||||
{
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,8 +1,8 @@
|
||||
//! EPS export for every EPS path (`document.export {format: eps}`, `document.exportEps`, Export As
|
||||
//! → EPS Options): the options parsed from the params, transparency flattened with a flattener
|
||||
//! preset, one file of the art's bounds or one per artboard (with a central file of the whole
|
||||
//! document when there are several and art shows), the preview and thumbnail rendered,
|
||||
//! and the native document embedded for reopening.
|
||||
//! document when there are several and art shows), the preview rendered and the thumbnail made
|
||||
//! from it, and the native document embedded for reopening.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
@@ -11,6 +11,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_eps::{EpsOptions, Level, Overprint, Preview, Raster};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_render::Rendered;
|
||||
|
||||
use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_expanded};
|
||||
use super::super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param};
|
||||
@@ -231,14 +232,38 @@ fn pages(doc: &Document, set: &Settings) -> Result<Vec<(Option<usize>, Rect, Poi
|
||||
}
|
||||
}
|
||||
|
||||
/// `rect` of `doc` drawn at a pixel a point (fewer when larger than `max` a side), straight RGBA,
|
||||
/// transparent or on white.
|
||||
fn render(r: &mut vectorcraft_render::Renderer, doc: &Document, rect: Rect, max: f64, transparent: bool) -> Result<Raster> {
|
||||
/// Pixels a point for `rect`: one, or fewer when it is larger than `max` a side.
|
||||
fn fit(rect: Rect, max: f64) -> f64 {
|
||||
let long = rect.width().max(rect.height());
|
||||
let scale = if long > max { max / long } else { 1.0 };
|
||||
if long > max { max / long } else { 1.0 }
|
||||
}
|
||||
|
||||
/// `rect` of `doc` drawn at [`fit`]'s scale for `max`, transparent or on white.
|
||||
fn render(r: &mut vectorcraft_render::Renderer, doc: &Document, rect: Rect, max: f64, transparent: bool) -> Result<Rendered> {
|
||||
let scale = fit(rect, max);
|
||||
vectorcraft_render::raster_size(rect, scale).map_err(|e| bad(C, e))?;
|
||||
let img = r.render_region(doc, rect, scale, !transparent);
|
||||
Ok(Raster { width: img.width, height: img.height, rgba: img.to_straight() })
|
||||
Ok(r.render_region(doc, rect, scale, !transparent))
|
||||
}
|
||||
|
||||
/// `img` as the writer takes it: straight RGBA.
|
||||
fn straight(img: &Rendered) -> Raster {
|
||||
Raster { width: img.width, height: img.height, rgba: img.to_straight() }
|
||||
}
|
||||
|
||||
/// The thumbnail of `rect` made from `preview`, the same rect rendered larger: at the size a
|
||||
/// thumbnail render of `rect` has, each pixel the average of the preview's pixels under it, on white.
|
||||
fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result<Raster> {
|
||||
let (width, height) = vectorcraft_render::raster_size(rect, fit(rect, THUMBNAIL)).map_err(|e| bad(C, e))?;
|
||||
let mut rgba = preview.area_resized(width, height).map_err(|e| bad(C, e))?.pixels;
|
||||
// Premultiplied over white: each channel gains the white the pixel's alpha leaves showing.
|
||||
for px in rgba.as_chunks_mut::<4>().0 {
|
||||
let clear = 255 - px[3];
|
||||
for c in &mut px[..3] {
|
||||
*c = c.saturating_add(clear);
|
||||
}
|
||||
px[3] = 255;
|
||||
}
|
||||
Ok(Raster { width, height, rgba })
|
||||
}
|
||||
|
||||
/// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of
|
||||
@@ -318,11 +343,18 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
for (board, region, origin) in pages {
|
||||
let rect = vectorcraft_eps::preview_rect(region, origin);
|
||||
let preview = match set.eps.preview {
|
||||
let shown = match set.eps.preview {
|
||||
Preview::None => None,
|
||||
kind => Some(render(&mut renderer, doc, rect, preview_limit, set.eps.transparent_preview && kind == Preview::TiffColor)?),
|
||||
};
|
||||
let thumbnail = set.thumbnails.then(|| render(&mut renderer, doc, rect, THUMBNAIL, false)).transpose()?;
|
||||
// The thumbnail is made from the preview; only a file without one renders it.
|
||||
let thumbnail = match (set.thumbnails, &shown) {
|
||||
(false, _) => None,
|
||||
(true, Some(img)) => Some(thumbnail_of(img, rect)?),
|
||||
(true, None) => Some(straight(&render(&mut renderer, doc, rect, THUMBNAIL, false)?)),
|
||||
};
|
||||
let preview = shown.as_ref().map(straight);
|
||||
drop(shown);
|
||||
let o = EpsOptions {
|
||||
region,
|
||||
origin,
|
||||
|
||||
@@ -9,14 +9,14 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind, SymbolBoxes};
|
||||
|
||||
use crate::DocState;
|
||||
|
||||
use super::super::{Result, Session, bad, bool_or, edit, f64_or, str_param};
|
||||
use super::super::{Result, Session, bad, check_switches, edit, number_or, switch_or, text_param};
|
||||
use super::encode::single_artboard;
|
||||
use super::{
|
||||
ARTBOARD_PARAMS, Format, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded, write_or_return,
|
||||
};
|
||||
|
||||
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = writable("document.serialize", Some(str_param(p, "format").unwrap_or("vectorcraft")), None)?;
|
||||
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
|
||||
let expanded = expand_presets(s, "document.serialize", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?;
|
||||
@@ -53,11 +53,11 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path");
|
||||
let path = text_param(p, "path", "document.export")?;
|
||||
if let Some(path) = path {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?;
|
||||
}
|
||||
let f = writable("document.export", str_param(p, "format"), path)?;
|
||||
let f = writable("document.export", text_param(p, "format", "document.export")?, path)?;
|
||||
let expanded = expand_presets(s, "document.export", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.export")?;
|
||||
@@ -86,7 +86,7 @@ pub fn export_doc<'a>(st: &'a DocState, f: &Format, p: &Value) -> Result<Cow<'a,
|
||||
/// The document an export of `st` writes: the whole document, or with `selectedOnly` just the
|
||||
/// selected objects, each in its layers and groups (a clipping group keeps its clipping path).
|
||||
pub fn export_source<'a>(st: &'a DocState, p: &Value) -> Result<Cow<'a, Document>> {
|
||||
if !bool_or(p, "selectedOnly", false) {
|
||||
if !switch_or(p, "selectedOnly", false, "document.export")? {
|
||||
return Ok(Cow::Borrowed(&*st.doc));
|
||||
}
|
||||
let keep: HashSet<NodeId> = edit::roots_of(&st.doc, st.selection.in_paint_order(&st.doc)).into_iter().collect();
|
||||
@@ -237,7 +237,8 @@ fn expand_presets<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a, Va
|
||||
/// The document an export of `f` writes: the active one (see [`export_source`]), or for text
|
||||
/// with `selectionOnly` the selected objects alone.
|
||||
fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(Cow<'a, Document>, bool)> {
|
||||
if f.id == "txt" && bool_or(p, "selectionOnly", false) {
|
||||
check_switches(p, &["selectedOnly"], cmd)?;
|
||||
if switch_or(p, "selectionOnly", false, cmd)? && f.id == "txt" {
|
||||
let doc = selection(s, cmd, true)?.0;
|
||||
let display_doc_title = super::has_own_title(&doc);
|
||||
return Ok((Cow::Owned(doc), display_doc_title));
|
||||
@@ -309,11 +310,11 @@ pub(crate) fn isolated(doc: &Document, ids: &[NodeId], name: &str) -> Option<(Do
|
||||
/// are guides, not artwork, and are left out.
|
||||
pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.exportSelection";
|
||||
if let Some(path) = str_param(p, "path") {
|
||||
let path = text_param(p, "path", C)?;
|
||||
if let Some(path) = path {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
|
||||
}
|
||||
let path = str_param(p, "path");
|
||||
let f = writable(C, str_param(p, "format"), path)?;
|
||||
let f = writable(C, text_param(p, "format", C)?, path)?;
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (d, bounds) = selection(s, C, f.id == "txt")?;
|
||||
@@ -327,11 +328,12 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// `transparent`, with the encoder's warnings.
|
||||
pub(super) fn export_for_office(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.exportForOffice";
|
||||
if let Some(path) = str_param(p, "path") {
|
||||
let path = text_param(p, "path", C)?;
|
||||
if let Some(path) = path {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
|
||||
}
|
||||
let path = str_param(p, "path");
|
||||
let ppi = f64_or(p, "ppi", 150.0);
|
||||
let ppi = number_or(p, "ppi", 150.0, C)?;
|
||||
let transparent = switch_or(p, "transparent", false, C)?;
|
||||
let doc = &s.doc()?.doc;
|
||||
let artboard = match p.get("artboard") {
|
||||
None | Some(Value::Null) => 0,
|
||||
@@ -340,7 +342,7 @@ pub(super) fn export_for_office(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if artboard >= doc.artboards.len() {
|
||||
return Err(bad(C, format!("no artboard {artboard} (0-based; the document has {})", doc.artboards.len())));
|
||||
}
|
||||
let background = if bool_or(p, "transparent", false) { "transparent" } else { "white" };
|
||||
let background = if transparent { "transparent" } else { "white" };
|
||||
let opts = with_black_output(s, &json!({ "ppi": ppi, "background": background, "artboard": artboard }));
|
||||
let (bytes, warnings) = encode_with_warnings(doc, "png", &opts)?;
|
||||
// The pixel size, from the PNG header.
|
||||
|
||||
@@ -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",
|
||||
@@ -493,7 +495,8 @@ pub const FORMATS: &[Format] = &[
|
||||
// Affinity Photo's `.afphoto` opens by its content but isn't listed: Finder shouldn't offer a
|
||||
// vector app for a raster editor's documents.
|
||||
reader("affinity", "Affinity", &["af", "afdesign", "afpub"], "application/x-affinity", false),
|
||||
// Photoshop's large document format: read like a PSD (its merged image), never written.
|
||||
// The large document form of PSD: read like a PSD (its layers, or its merged image), never
|
||||
// written.
|
||||
reader("psb", "PSB", &["psb"], "image/x-psb", true),
|
||||
// PostScript programs, read as EPS files are; Print to PostScript writes them, exports don't.
|
||||
reader("ps", "PostScript", &["ps"], "application/postscript", false),
|
||||
@@ -551,6 +554,10 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"dxf",
|
||||
"emf",
|
||||
"wmf",
|
||||
"plt",
|
||||
"hpgl",
|
||||
"hgl",
|
||||
"hpg",
|
||||
"eps",
|
||||
"epsf",
|
||||
"ps",
|
||||
@@ -564,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
|
||||
@@ -640,6 +648,10 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"dxf",
|
||||
"emf",
|
||||
"wmf",
|
||||
"plt",
|
||||
"hpgl",
|
||||
"hgl",
|
||||
"hpg",
|
||||
"eps",
|
||||
"epsf",
|
||||
"ps",
|
||||
|
||||
@@ -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,11 +498,25 @@ 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;
|
||||
(i.doc, i.warnings, false)
|
||||
}
|
||||
// A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with
|
||||
// `layers: false`, its merged image opens. Layers that can't be read leave the merged image.
|
||||
"psd" | "psb" if opts.layers => {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
match super::psdlayers::import(bytes, opts.hidden_layers, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) {
|
||||
Ok(Some((doc, warnings))) => (doc, warnings, false),
|
||||
Ok(None) => (raster_doc(&title, bytes)?, vec![], false),
|
||||
Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false),
|
||||
}
|
||||
}
|
||||
_ if format.raster => (raster_doc(&title, bytes)?, vec![], false),
|
||||
_ => return Err(err(format!("{} files can't be opened yet", format.label))),
|
||||
};
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -28,8 +28,10 @@ pub struct LoadOptions {
|
||||
/// What a PDF's text becomes.
|
||||
pub text_as: TextAs,
|
||||
/// A PDF's optional content groups become layers (else one layer per page, without the art
|
||||
/// that is off).
|
||||
/// that is off), and a PSD or PSB file's layers become layers (else its merged image opens).
|
||||
pub layers: bool,
|
||||
/// A PSD or PSB file's hidden layers come in, hidden (`hiddenLayers`; else they are left out).
|
||||
pub hidden_layers: bool,
|
||||
/// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]).
|
||||
pub dxf: vectorcraft_cad::ImportOptions,
|
||||
/// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its
|
||||
@@ -57,6 +59,7 @@ impl Default for LoadOptions {
|
||||
grays: Grays::default(),
|
||||
text_as: TextAs::default(),
|
||||
layers: true,
|
||||
hidden_layers: false,
|
||||
dxf: Default::default(),
|
||||
editing_data: true,
|
||||
trust_editing_data: false,
|
||||
@@ -69,7 +72,8 @@ impl Default for LoadOptions {
|
||||
impl LoadOptions {
|
||||
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
|
||||
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
|
||||
/// `textAs` (`text` | `outlines`), `layers` (true | false), `editingData` (true | false | `always`),
|
||||
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
|
||||
/// `editingData` (true | false | `always`),
|
||||
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]) and `dxf` (the DXF
|
||||
/// import options).
|
||||
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
|
||||
@@ -95,6 +99,10 @@ impl LoadOptions {
|
||||
None => true,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "layers must be true or false"))?,
|
||||
};
|
||||
let hidden_layers = match p.get("hiddenLayers").filter(|v| !v.is_null()) {
|
||||
None => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "hiddenLayers must be true or false"))?,
|
||||
};
|
||||
let (editing_data, trust_editing_data) = match p.get("editingData").filter(|v| !v.is_null()) {
|
||||
None => (true, false),
|
||||
Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true),
|
||||
@@ -108,7 +116,21 @@ impl LoadOptions {
|
||||
.ok_or_else(|| bad(cmd, format!("legacyNameEncoding must be one of {}", vectorcraft_eps::NameEncoding::LABELS.join(", "))))?,
|
||||
};
|
||||
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
|
||||
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, legacy_names, native: true })
|
||||
Ok(Self {
|
||||
pages,
|
||||
crop,
|
||||
password,
|
||||
color_mode,
|
||||
grays,
|
||||
text_as,
|
||||
layers,
|
||||
hidden_layers,
|
||||
dxf,
|
||||
editing_data,
|
||||
trust_editing_data,
|
||||
legacy_names,
|
||||
native: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// Does the document read only part of the file, or read it differently (a page range, another
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,8 @@
|
||||
//! Reading Photoshop documents (PSD, and PSB, the large document format) for File › Open and
|
||||
//! File › Place (#918): the merged image, the flattened picture every PSD carries after its layers,
|
||||
//! as a linked PSD shows. Written from Adobe's public "Photoshop File Formats Specification"
|
||||
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). Layers aren't read.
|
||||
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). File › Open reads the
|
||||
//! layers with [`super::psdlayers`], which shares this reader.
|
||||
//!
|
||||
//! Every mode Photoshop saves a merged image in is read: Bitmap, Grayscale, Duotone (as its
|
||||
//! grayscale data), Indexed, RGB, CMYK and Lab, at 1, 8, 16 and 32 bits per channel, stored raw,
|
||||
@@ -16,7 +17,7 @@ use vectorcraft_color::cms::{Lab, lab::lab_to_srgb};
|
||||
|
||||
/// Photoshop's colour modes (the header's numbers), as far as the merged image is concerned.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
pub(super) enum Mode {
|
||||
Bitmap,
|
||||
Gray,
|
||||
Indexed,
|
||||
@@ -27,7 +28,7 @@ enum Mode {
|
||||
|
||||
impl Mode {
|
||||
/// The channels holding colour (an alpha channel may follow them).
|
||||
fn colors(self) -> usize {
|
||||
pub(super) fn colors(self) -> usize {
|
||||
match self {
|
||||
Mode::Bitmap | Mode::Gray | Mode::Indexed => 1,
|
||||
Mode::Rgb | Mode::Lab => 3,
|
||||
@@ -46,68 +47,68 @@ pub fn is_psb(bytes: &[u8]) -> bool {
|
||||
is_psd(bytes) && bytes.get(4..6) == Some(&[0, 2])
|
||||
}
|
||||
|
||||
const TRUNCATED: &str = "the PSD file is cut short";
|
||||
pub(super) const TRUNCATED: &str = "the PSD file is cut short";
|
||||
const DAMAGED: &str = "the PSD file's header is damaged";
|
||||
|
||||
/// Big-endian reads through `b`, each checked against its end.
|
||||
struct Reader<'a> {
|
||||
pub(super) struct Reader<'a> {
|
||||
b: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
fn new(b: &'a [u8]) -> Self {
|
||||
pub(super) fn new(b: &'a [u8]) -> Self {
|
||||
Self { b, at: 0 }
|
||||
}
|
||||
fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
pub(super) fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
let s = self.at.checked_add(n).and_then(|end| self.b.get(self.at..end)).ok_or(TRUNCATED)?;
|
||||
self.at += n;
|
||||
Ok(s)
|
||||
}
|
||||
fn array<const N: usize>(&mut self) -> Result<[u8; N], String> {
|
||||
pub(super) fn array<const N: usize>(&mut self) -> Result<[u8; N], String> {
|
||||
self.take(N)?.try_into().map_err(|_| TRUNCATED.to_string())
|
||||
}
|
||||
fn u8(&mut self) -> Result<u8, String> {
|
||||
pub(super) fn u8(&mut self) -> Result<u8, String> {
|
||||
self.array::<1>().map(|[v]| v)
|
||||
}
|
||||
fn u16(&mut self) -> Result<u16, String> {
|
||||
pub(super) fn u16(&mut self) -> Result<u16, String> {
|
||||
self.array().map(u16::from_be_bytes)
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32, String> {
|
||||
pub(super) fn u32(&mut self) -> Result<u32, String> {
|
||||
self.array().map(u32::from_be_bytes)
|
||||
}
|
||||
/// A section length: 4 bytes in a PSD, 8 in a PSB.
|
||||
fn length(&mut self, psb: bool) -> Result<usize, String> {
|
||||
pub(super) fn length(&mut self, psb: bool) -> Result<usize, String> {
|
||||
let n = if psb { self.array().map(u64::from_be_bytes)? } else { u64::from(self.u32()?) };
|
||||
usize::try_from(n).map_err(|_| TRUNCATED.to_string())
|
||||
}
|
||||
/// A section: its length, then that many bytes.
|
||||
fn section(&mut self, psb: bool) -> Result<&'a [u8], String> {
|
||||
pub(super) fn section(&mut self, psb: bool) -> Result<&'a [u8], String> {
|
||||
let n = self.length(psb)?;
|
||||
self.take(n)
|
||||
}
|
||||
fn rest(&self) -> &'a [u8] {
|
||||
pub(super) fn rest(&self) -> &'a [u8] {
|
||||
self.b.get(self.at..).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixed-size header and the sections before the image data.
|
||||
struct Header<'a> {
|
||||
psb: bool,
|
||||
pub(super) struct Header<'a> {
|
||||
pub(super) psb: bool,
|
||||
channels: usize,
|
||||
width: u32,
|
||||
height: u32,
|
||||
depth: u16,
|
||||
mode: Mode,
|
||||
pub(super) width: u32,
|
||||
pub(super) height: u32,
|
||||
pub(super) depth: u16,
|
||||
pub(super) mode: Mode,
|
||||
/// Colour mode data: an indexed image's palette (256 reds, then greens, then blues).
|
||||
palette: &'a [u8],
|
||||
/// The image resources.
|
||||
resources: &'a [u8],
|
||||
/// The layer and mask information.
|
||||
layers: &'a [u8],
|
||||
pub(super) layers: &'a [u8],
|
||||
}
|
||||
|
||||
fn header<'a>(r: &mut Reader<'a>) -> Result<Header<'a>, String> {
|
||||
pub(super) fn header<'a>(r: &mut Reader<'a>) -> Result<Header<'a>, String> {
|
||||
if !is_psd(r.b) {
|
||||
return Err("not a PSD file".into());
|
||||
}
|
||||
@@ -183,41 +184,45 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
/// count is negative: in the layer info, or for 16- and 32-bit documents (whose layer info is
|
||||
/// empty) in their `Lr16` / `Lr32` block.
|
||||
fn merged_alpha(layers: &[u8], psb: bool) -> bool {
|
||||
let count_negative = |info: &[u8]| info.get(..2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0);
|
||||
layer_info(layers, psb).is_some_and(|info| info.get(..2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0))
|
||||
}
|
||||
|
||||
/// Do tagged blocks with this key give an 8-byte length in a PSB?
|
||||
pub(super) fn long_key(key: &[u8; 4]) -> bool {
|
||||
matches!(key, b"Lr16" | b"Lr32" | b"Layr" | b"LMsk" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD")
|
||||
}
|
||||
|
||||
/// The layer info: the layer count, the layer records and their channels. It is the first part of
|
||||
/// the layer and mask information, or for 16- and 32-bit documents (whose first part is empty) the
|
||||
/// `Lr16` / `Lr32` block after it. `None` when the file has neither.
|
||||
pub(super) fn layer_info(layers: &[u8], psb: bool) -> Option<&[u8]> {
|
||||
let mut r = Reader::new(layers);
|
||||
let Ok(info) = r.section(psb) else { return false };
|
||||
let info = r.section(psb).ok()?;
|
||||
if !info.is_empty() {
|
||||
return count_negative(info);
|
||||
return Some(info);
|
||||
}
|
||||
// The global layer mask info, then tagged blocks: signature, key, length (8 bytes for the
|
||||
// layer blocks of a PSB), data padded to 4 bytes.
|
||||
if r.section(false).is_err() {
|
||||
return false;
|
||||
}
|
||||
r.section(false).ok()?;
|
||||
while r.rest().len() >= 12 {
|
||||
let (Ok(_), Ok(key)) = (r.take(4), r.array::<4>()) else { return false };
|
||||
let layer_block = matches!(&key, b"Lr16" | b"Lr32" | b"Layr");
|
||||
let long = layer_block || matches!(&key, b"LMsk" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD");
|
||||
let Ok(data) = r.section(psb && long) else {
|
||||
return false;
|
||||
};
|
||||
if layer_block {
|
||||
return count_negative(data);
|
||||
}
|
||||
if r.take((4 - data.len() % 4) % 4).is_err() {
|
||||
return false;
|
||||
r.take(4).ok()?;
|
||||
let key = r.array::<4>().ok()?;
|
||||
let data = r.section(psb && long_key(&key)).ok()?;
|
||||
if matches!(&key, b"Lr16" | b"Lr32" | b"Layr") {
|
||||
return Some(data);
|
||||
}
|
||||
r.take((4 - data.len() % 4) % 4).ok()?;
|
||||
}
|
||||
false
|
||||
None
|
||||
}
|
||||
|
||||
/// The most bytes one channel row may take (a PSB at 32 bits).
|
||||
fn row_bytes(width: usize, depth: u16) -> usize {
|
||||
pub(super) fn row_bytes(width: usize, depth: u16) -> usize {
|
||||
if depth == 1 { width.div_ceil(8) } else { width * usize::from(depth / 8) }
|
||||
}
|
||||
|
||||
/// Undo PackBits: `src` into `dst` (a row; a short or overlong run leaves the rest as it is).
|
||||
fn unpack_bits(mut src: &[u8], dst: &mut [u8]) {
|
||||
pub(super) fn unpack_bits(mut src: &[u8], dst: &mut [u8]) {
|
||||
let mut at = 0;
|
||||
while let Some((&n, rest)) = src.split_first() {
|
||||
src = rest;
|
||||
@@ -269,32 +274,77 @@ fn channel_data(data: &[u8], h: &Header<'_>, channels: usize, row: usize) -> Res
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
2 | 3 => {
|
||||
let mut out = Vec::new();
|
||||
flate2::read::ZlibDecoder::new(r.rest())
|
||||
.take(wanted as u64)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| format!("the PSD file's image data can't be read: {e}"))?;
|
||||
if out.len() < wanted {
|
||||
return Err(TRUNCATED.into());
|
||||
}
|
||||
if method == 3 {
|
||||
// Each row stores the difference from the sample before it.
|
||||
match h.depth {
|
||||
8 => out.chunks_exact_mut(row).for_each(|r| (1..r.len()).for_each(|i| r[i] = r[i].wrapping_add(r[i - 1]))),
|
||||
16 => out.chunks_exact_mut(row).for_each(|r| {
|
||||
let mut prev = 0u16;
|
||||
for s in r.as_chunks_mut::<2>().0 {
|
||||
prev = prev.wrapping_add(u16::from_be_bytes(*s));
|
||||
*s = prev.to_be_bytes();
|
||||
}
|
||||
}),
|
||||
_ => return Err("zipped 32-bit PSD image data with prediction can't be read".into()),
|
||||
2 | 3 => inflate(r.rest(), wanted, method == 3, h.depth, row),
|
||||
m => Err(format!("the PSD file's image data uses an unknown compression ({m})")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `wanted` bytes of zipped image data, rows of `row` bytes; with `predicted`, each row stores the
|
||||
/// difference from the sample before it. In 32-bit data a row stores the first bytes of its samples,
|
||||
/// then their second bytes, and so on, and the differences run byte by byte along the whole row (as
|
||||
/// psd-tools, MIT, reads it: <https://github.com/psd-tools/psd-tools>, `compression/__init__.py`).
|
||||
fn inflate(src: &[u8], wanted: usize, predicted: bool, depth: u16, row: usize) -> Result<Vec<u8>, String> {
|
||||
let mut out = Vec::new();
|
||||
flate2::read::ZlibDecoder::new(src)
|
||||
.take(wanted as u64)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| format!("the PSD file's image data can't be read: {e}"))?;
|
||||
if out.len() < wanted {
|
||||
return Err(TRUNCATED.into());
|
||||
}
|
||||
if predicted && row > 0 {
|
||||
match depth {
|
||||
8 => out.chunks_exact_mut(row).for_each(|r| (1..r.len()).for_each(|i| r[i] = r[i].wrapping_add(r[i - 1]))),
|
||||
16 => out.chunks_exact_mut(row).for_each(|r| {
|
||||
let mut prev = 0u16;
|
||||
for s in r.as_chunks_mut::<2>().0 {
|
||||
prev = prev.wrapping_add(u16::from_be_bytes(*s));
|
||||
*s = prev.to_be_bytes();
|
||||
}
|
||||
}),
|
||||
32 => {
|
||||
let w = row / 4;
|
||||
let mut planes = vec![0u8; row];
|
||||
for r in out.chunks_exact_mut(row) {
|
||||
let mut prev = 0u8;
|
||||
for (dst, &b) in planes.iter_mut().zip(r.iter()) {
|
||||
prev = prev.wrapping_add(b);
|
||||
*dst = prev;
|
||||
}
|
||||
for (x, s) in r.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
for (k, v) in s.iter_mut().enumerate() {
|
||||
*v = planes.get(k * w + x).copied().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 1-bit.
|
||||
_ => return Err("zipped 1-bit PSD image data with prediction can't be read".into()),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One channel of a layer: its compression method, then `rows` rows of `row` bytes (PackBits rows
|
||||
/// after their byte counts, 4 bytes each in a PSB).
|
||||
pub(super) fn layer_channel(data: &[u8], rows: usize, row: usize, psb: bool, depth: u16) -> Result<Vec<u8>, String> {
|
||||
let mut r = Reader::new(data);
|
||||
let method = r.u16()?;
|
||||
let wanted = rows.checked_mul(row).ok_or(TRUNCATED)?;
|
||||
match method {
|
||||
0 => r.take(wanted).map(<[u8]>::to_vec),
|
||||
1 => {
|
||||
let size = if psb { 4 } else { 2 };
|
||||
let counts = r.take(rows.checked_mul(size).ok_or(TRUNCATED)?)?;
|
||||
let mut out = vec![0; wanted];
|
||||
for (dst, n) in out.chunks_exact_mut(row.max(1)).zip(counts.chunks_exact(size)) {
|
||||
let n = n.iter().fold(0usize, |n, &b| n << 8 | usize::from(b));
|
||||
unpack_bits(r.take(n)?, dst);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
m => Err(format!("the PSD file's image data uses an unknown compression ({m})")),
|
||||
2 | 3 => inflate(r.rest(), wanted, method == 3, depth, row),
|
||||
m => Err(format!("the PSD file's layer data uses an unknown compression ({m})")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,7 +354,7 @@ fn srgb_encode(v: f32) -> f32 {
|
||||
}
|
||||
|
||||
/// Sample `x` of a channel row, 0..1.
|
||||
fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 {
|
||||
pub(super) fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 {
|
||||
match depth {
|
||||
1 => {
|
||||
// Bitmap: a set bit is black.
|
||||
@@ -321,10 +371,25 @@ fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 {
|
||||
}
|
||||
}
|
||||
|
||||
fn byte(v: f32) -> u8 {
|
||||
pub(super) fn byte(v: f32) -> u8 {
|
||||
(v.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
/// The sRGB color of a pixel whose color channels `v` gives (0..1, as stored), in `h`'s mode.
|
||||
pub(super) fn to_rgb(h: &Header<'_>, v: impl Fn(usize) -> f32, cmyk: &impl Fn([f32; 4]) -> [f32; 3]) -> [f32; 3] {
|
||||
match h.mode {
|
||||
Mode::Bitmap | Mode::Gray => [v(0); 3],
|
||||
Mode::Indexed => {
|
||||
let i = usize::from(byte(v(0)));
|
||||
[0, 256, 512].map(|at| h.palette.get(at + i).map_or(0.0, |&c| f32::from(c) / 255.0))
|
||||
}
|
||||
Mode::Rgb => [v(0), v(1), v(2)],
|
||||
// Inks are stored as 1 − amount.
|
||||
Mode::Cmyk => cmyk([0, 1, 2, 3].map(|c| 1.0 - v(c))),
|
||||
Mode::Lab => lab_to_srgb(Lab { l: v(0) * 100.0, a: v(1) * 255.0 - 128.0, b: v(2) * 255.0 - 128.0 }),
|
||||
}
|
||||
}
|
||||
|
||||
/// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink
|
||||
/// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than
|
||||
/// `max_alloc` bytes.
|
||||
@@ -348,17 +413,7 @@ pub fn decode(bytes: &[u8], max_alloc: u64, cmyk: impl Fn([f32; 4]) -> [f32; 3])
|
||||
let planes: Vec<&[u8]> = (0..channels).map(|c| data.get((c * rows + y) * row..(c * rows + y + 1) * row).unwrap_or_default()).collect();
|
||||
for (x, px) in line.enumerate() {
|
||||
let v = |c: usize| planes.get(c).map_or(0.0, |p| sample(p, x, h.depth, linear && c < colors));
|
||||
let rgb = match h.mode {
|
||||
Mode::Bitmap | Mode::Gray => [v(0); 3],
|
||||
Mode::Indexed => {
|
||||
let i = usize::from(byte(v(0)));
|
||||
[0, 256, 512].map(|at| h.palette.get(at + i).map_or(0.0, |&c| f32::from(c) / 255.0))
|
||||
}
|
||||
Mode::Rgb => [v(0), v(1), v(2)],
|
||||
// Inks are stored as 1 − amount.
|
||||
Mode::Cmyk => cmyk([0, 1, 2, 3].map(|c| 1.0 - v(c))),
|
||||
Mode::Lab => lab_to_srgb(Lab { l: v(0) * 100.0, a: v(1) * 255.0 - 128.0, b: v(2) * 255.0 - 128.0 }),
|
||||
};
|
||||
let rgb = to_rgb(&h, v, &cmyk);
|
||||
let a = if alpha { v(colors) } else { 1.0 };
|
||||
// The merged image is stored on white: take the white back out.
|
||||
let straight = |c: f32| if a <= 0.0 { 0.0 } else { (c - (1.0 - a)) / a };
|
||||
|
||||
@@ -267,6 +267,66 @@ mod native {
|
||||
synth::container(&[("doc.dat", &doc, method)], Some(&png()))
|
||||
}
|
||||
|
||||
/// A version-12 document at 144 ppi holding a 100 px square filled with a red-to-blue conical
|
||||
/// gradient centered at (50, 40) px, 40 px across: its unit +y points down the page, or up
|
||||
/// (`mirror`).
|
||||
fn conical_document(mirror: bool) -> Vec<u8> {
|
||||
let stop = |id: u32, c: F| F::Def(id, vec![tag(b"RGBA")], vec![(tag(b"_col"), c)]);
|
||||
let positions = [[0.0f32, 0.5], [1.0, 0.5]].iter().map(|p| p.iter().flat_map(|v| v.to_le_bytes()).collect()).collect();
|
||||
let grad = F::Obj(
|
||||
tag(b"Grad"),
|
||||
vec![
|
||||
(tag(b"Cols"), F::Shared(vec![stop(23, rgba(1.0, 0.0, 0.0, 1.0)), stop(24, rgba(0.0, 0.0, 1.0, 1.0))])),
|
||||
(tag(b"Posn"), F::Records(8, positions)),
|
||||
],
|
||||
);
|
||||
let fill = F::Def(22, vec![tag(b"FilG")], vec![(tag(b"Type"), F::Enum(3, 0)), (tag(b"Grad"), grad)]);
|
||||
let unit = F::F64s(vec![40.0, 0.0, 50.0, 0.0, if mirror { -40.0 } else { 40.0 }, 40.0]);
|
||||
let gradient = F::Def(21, vec![tag(b"FDsc")], vec![(tag(b"FDeX"), unit), (tag(b"FDeF"), fill)]);
|
||||
let square = F::Def(
|
||||
20,
|
||||
vec![tag(b"ShpN")],
|
||||
vec![
|
||||
(tag(b"Shpe"), F::Def(25, vec![tag(b"ShNR")], vec![])),
|
||||
(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 100.0, 100.0])),
|
||||
(tag(b"BFFl"), F::Shared(vec![gradient])),
|
||||
],
|
||||
);
|
||||
let spread =
|
||||
F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 200.0, 200.0])), (tag(b"Chld"), F::Shared(vec![square]))]);
|
||||
let doc = synth::stream(&[
|
||||
(tag(b"UVCn"), F::Obj(tag(b"UVCn"), vec![(tag(b"UPPI"), F::F64(144.0))])),
|
||||
(tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))])),
|
||||
]);
|
||||
synth::container(&[("doc.dat", &doc, Method::Stored)], Some(&png()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conical_gradients_open_as_conic_gradients() {
|
||||
use vectorcraft_color::{GradientKind, Paint};
|
||||
for mirror in [false, true] {
|
||||
let mut s = Session::new();
|
||||
let r = open_bytes(&mut s, "conic.af", &conical_document(mirror), None).unwrap();
|
||||
assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("conical")), "{r}");
|
||||
let mut paint = None;
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if let Paint::Gradient(g) = n.appearance.fill_paint() {
|
||||
paint = Some(g.clone());
|
||||
}
|
||||
});
|
||||
let g = paint.expect("a gradient fill");
|
||||
assert_eq!(g.gradient.kind, GradientKind::Conic);
|
||||
let geom = g.geom.unwrap();
|
||||
// At 144 ppi: centered at (25, 20) pt, 20 pt across, red where the sweep starts.
|
||||
assert!(geom.start.distance(kurbo::Point::new(25.0, 20.0)) < 1e-9 && (geom.length() - 20.0).abs() < 1e-9, "{geom:?}");
|
||||
assert_eq!(geom.is_mirrored(), mirror, "{geom:?}");
|
||||
// A quarter turn on lies along the unit +y: below the center, or above it mirrored.
|
||||
let quarter = kurbo::Point::new(25.0, if mirror { 10.0 } else { 30.0 });
|
||||
assert!((geom.param_at(GradientKind::Conic, quarter) - 0.25).abs() < 1e-9, "{geom:?}");
|
||||
assert_eq!(g.gradient.stops[0].color.to_hex(), "#ff0000");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_artboards_curves_and_paints_open_as_editable_art() {
|
||||
for method in [Method::Stored, Method::Zlib, Method::Zstd] {
|
||||
|
||||
@@ -218,6 +218,106 @@ fn placed_images_are_written_and_previews_are_black_and_white_on_request() {
|
||||
assert!(l3.contains("/FlateDecode filter >> image"));
|
||||
}
|
||||
|
||||
/// The PNG thumbnail of an EPS file, decoded.
|
||||
fn thumbnail_png(bytes: &[u8]) -> image::RgbaImage {
|
||||
let png = vectorcraft_eps::thumbnail(bytes).expect("a thumbnail");
|
||||
image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap().to_rgba8()
|
||||
}
|
||||
|
||||
/// The TIFF preview of an EPS file, decoded.
|
||||
fn preview_tiff(bytes: &[u8]) -> image::RgbaImage {
|
||||
let tiff = vectorcraft_eps::sections(bytes).unwrap().1.expect("a preview");
|
||||
image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff).unwrap().to_rgba8()
|
||||
}
|
||||
|
||||
/// The size of a thumbnail render of the rect an EPS file's preview shows (its bounding box).
|
||||
fn thumbnail_size(bytes: &[u8]) -> (u32, u32) {
|
||||
let b: Vec<f64> = dsc(&postscript(bytes), "BoundingBox").unwrap().split(' ').map(|v| v.parse().unwrap()).collect();
|
||||
let rect = vectorcraft_geom::Rect::new(b[0], b[1], b[2], b[3]);
|
||||
let long = rect.width().max(rect.height());
|
||||
vectorcraft_render::raster_size(rect, if long > 128.0 { 128.0 / long } else { 1.0 }).unwrap()
|
||||
}
|
||||
|
||||
/// The thumbnail is the color preview made smaller, the area average of its pixels at the size a
|
||||
/// 128 px render has, not a second render of the document; it shows the same picture as one.
|
||||
#[test]
|
||||
fn the_thumbnail_is_made_from_the_preview() {
|
||||
let mut s = session(1000.0, 700.0, 1);
|
||||
s.execute("paint.setFill", &json!({"color": "#2060c0"})).unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x": 37.3, "y": 41.9, "width": 811.7, "height": 563.1})).unwrap();
|
||||
let r = s.execute("document.exportEps", &json!({"useArtboards": true, "previewFormat": "tiffColor", "transparentPreview": false})).unwrap();
|
||||
let bytes = b64(&r);
|
||||
let preview = preview_tiff(&bytes);
|
||||
assert_eq!(preview.dimensions(), (1000, 700));
|
||||
let thumb = thumbnail_png(&bytes);
|
||||
assert_eq!(thumb.dimensions(), (128, 90));
|
||||
// An opaque preview's straight pixels are its premultiplied ones.
|
||||
let shown = vectorcraft_render::Rendered { width: 1000, height: 700, pixels: preview.into_raw() };
|
||||
assert!(thumb.as_raw() == &shown.area_resized(128, 90).unwrap().pixels, "the thumbnail isn't the preview made smaller");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let fresh = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(0.0, 0.0, 1000.0, 700.0), 0.128, true);
|
||||
let mut diffs: Vec<u8> = thumb.as_raw().iter().zip(&fresh.pixels).map(|(a, b)| a.abs_diff(*b)).collect();
|
||||
diffs.sort_unstable();
|
||||
let mean = diffs.iter().map(|d| f64::from(*d)).sum::<f64>() / diffs.len() as f64;
|
||||
let p95 = diffs[diffs.len() * 95 / 100];
|
||||
assert!(mean <= 8.0 && p95 <= 32, "mean {mean}, 95th percentile {p95}");
|
||||
}
|
||||
|
||||
/// A thumbnail is opaque color on white whatever the preview: a transparent color preview's, and a
|
||||
/// black-and-white preview's, which keeps the art's colors.
|
||||
#[test]
|
||||
fn thumbnails_of_transparent_and_black_and_white_previews_are_opaque_color() {
|
||||
let mut s = session(400.0, 200.0, 1);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let fresh = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 200.0), 0.32, true);
|
||||
let red: [u8; 4] = fresh.pixels[(32 * 128 + 10) * 4..][..4].try_into().unwrap();
|
||||
for preview in ["tiffColor", "tiffBw"] {
|
||||
let r = s.execute("document.exportEps", &json!({"useArtboards": true, "previewFormat": preview})).unwrap();
|
||||
let thumb = thumbnail_png(&b64(&r));
|
||||
assert_eq!(thumb.dimensions(), (128, 64), "{preview}");
|
||||
assert_eq!(thumb.get_pixel(10, 32).0, red, "{preview}");
|
||||
assert_eq!(thumb.get_pixel(120, 32).0, [255, 255, 255, 255], "{preview}");
|
||||
assert!(thumb.pixels().all(|p| p[3] == 255), "{preview}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A page that fits in a thumbnail gets its preview's own pixels, unresampled.
|
||||
#[test]
|
||||
fn a_small_page_s_thumbnail_is_its_preview() {
|
||||
let mut s = session(100.0, 60.0, 1);
|
||||
s.execute("shape.ellipse", &json!({"x": 10.5, "y": 7.25, "width": 70, "height": 41})).unwrap();
|
||||
let bytes = b64(&s.execute("document.exportEps", &json!({"useArtboards": true, "transparentPreview": false})).unwrap());
|
||||
let thumb = thumbnail_png(&bytes);
|
||||
assert_eq!(thumb.dimensions(), (100, 60));
|
||||
assert!(thumb == preview_tiff(&bytes), "the thumbnail isn't the preview");
|
||||
}
|
||||
|
||||
/// Every file has a thumbnail at the size a thumbnail render has, with any page shape, on Save
|
||||
/// too and without a preview; with thumbnails off there is none.
|
||||
#[test]
|
||||
fn every_file_s_thumbnail_has_the_thumbnail_size() {
|
||||
let mut s = session(333.3, 77.7, 2);
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
|
||||
s.execute("shape.rectangle", &json!({"x": 3.7, "y": 5.1, "width": 300, "height": 61.3})).unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x": second + 1.0, "y": 2.0, "width": 20, "height": 70})).unwrap();
|
||||
for preview in ["tiffColor", "tiffBw", "none"] {
|
||||
let r = s.execute("document.exportEps", &json!({"useArtboards": true, "previewFormat": preview})).unwrap();
|
||||
let files = r["files"].as_array().unwrap();
|
||||
assert_eq!(files.len(), 3);
|
||||
for f in files {
|
||||
let bytes = b64(f);
|
||||
assert_eq!(thumbnail_png(&bytes).dimensions(), thumbnail_size(&bytes), "{preview} {}", f["name"]);
|
||||
}
|
||||
}
|
||||
assert_eq!(thumbnail_size(&b64(&s.execute("document.exportEps", &json!({"range": "1"})).unwrap())), (128, 30));
|
||||
let saved = b64(&s.execute("document.save", &json!({"format": "eps", "previewFormat": "tiffColor"})).unwrap());
|
||||
assert_eq!(thumbnail_png(&saved).dimensions(), thumbnail_size(&saved));
|
||||
let r = s.execute("document.exportEps", &json!({"useArtboards": true, "thumbnails": false})).unwrap();
|
||||
assert!(r["files"].as_array().unwrap().iter().all(|f| vectorcraft_eps::thumbnail(&b64(f)).is_none()));
|
||||
}
|
||||
|
||||
/// Two placed images whose pixel data can't be decoded are left out of the EPS, and `warnings`
|
||||
/// holds the note raster exports give, once, without naming either image's key.
|
||||
#[test]
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -141,6 +141,31 @@ fn packbits_zip_and_psb_files_read() {
|
||||
zip.extend(z.finish().unwrap());
|
||||
let px = pixels(&psd(1, 1, (3, 1), 16, 1, &[], &[], &[], &zip));
|
||||
assert_eq!(px.iter().map(|p| p[0]).collect::<Vec<_>>(), [16, 32, 48]);
|
||||
// Zipped with prediction, 32 bits: the row's first bytes, then its second bytes and so on,
|
||||
// each byte stored as the difference from the byte before it.
|
||||
let samples = [0.0f32, 1.0, 0.0].map(f32::to_be_bytes);
|
||||
let planes: Vec<u8> = (0..4).flat_map(|k| samples.iter().map(move |s| s[k])).collect();
|
||||
let deltas: Vec<u8> = planes.iter().scan(0u8, |prev, &b| Some(b.wrapping_sub(std::mem::replace(prev, b)))).collect();
|
||||
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
std::io::Write::write_all(&mut z, &deltas).unwrap();
|
||||
let mut zip = vec![0, 3];
|
||||
zip.extend(z.finish().unwrap());
|
||||
let px = pixels(&psd(1, 1, (3, 1), 32, 1, &[], &[], &[], &zip));
|
||||
assert_eq!(px.iter().map(|p| p[0]).collect::<Vec<_>>(), [0, 255, 0]);
|
||||
// The same layout as another implementation writes it: psd-tools 1.26.1 (MIT,
|
||||
// <https://github.com/psd-tools/psd-tools>), `compression.compress(data,
|
||||
// Compression.ZIP_WITH_PREDICTION, 3, 2, 32)` of the samples 0, 1, 0.25 and 0.5, 0.125, 1,
|
||||
// reads as the same samples stored raw.
|
||||
let theirs = [
|
||||
0x78, 0x9c, 0x63, 0xb0, 0xff, 0x7f, 0xa8, 0x81, 0xa1, 0x81, 0x01, 0x04, 0xec, 0xff, 0x33, 0x1e, 0x64, 0x68, 0x80, 0xb0, 0x01, 0x59, 0xd1,
|
||||
0x06, 0x01,
|
||||
];
|
||||
let mut zip = vec![0, 3];
|
||||
zip.extend(theirs);
|
||||
let samples: Vec<u8> = [0.0f32, 1.0, 0.25, 0.5, 0.125, 1.0].iter().flat_map(|v| v.to_be_bytes()).collect();
|
||||
let stored = pixels(&psd(1, 1, (3, 2), 32, 1, &[], &[], &[], &raw(&[&samples])));
|
||||
assert_eq!(pixels(&psd(1, 1, (3, 2), 32, 1, &[], &[], &[], &zip)), stored);
|
||||
assert_eq!(stored.iter().map(|p| p[0]).collect::<Vec<_>>()[..2], [0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(¢er(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(¢er(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]]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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]]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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|freeform (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 or radial, 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), aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial 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: the extent ellipse's height / width; 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), 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, 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.
|
||||
@@ -274,9 +274,16 @@ pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> {
|
||||
gp.angle = f64_or(g, "angle", 0.0);
|
||||
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 matches!(kind, GradientKind::Conic | GradientKind::Diamond) {
|
||||
no_focal(&geom)?;
|
||||
}
|
||||
if let Some((start, end)) = geom.vector {
|
||||
let mut g = GradientGeom { start, end, aspect: geom.aspect.unwrap_or(1.0), focal: None };
|
||||
g.set_focal(geom.focal.flatten());
|
||||
let mut g = GradientGeom { start, end, aspect: aspect.unwrap_or(1.0), focal: None };
|
||||
// Only a radial gradient has a focal point (as `paint.setGradientGeom` keeps it).
|
||||
if kind == GradientKind::Radial {
|
||||
g.set_focal(geom.focal.flatten());
|
||||
}
|
||||
gp.angle = g.angle_deg();
|
||||
gp.geom = Some(g);
|
||||
}
|
||||
@@ -286,13 +293,36 @@ pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> {
|
||||
Ok(gp)
|
||||
}
|
||||
|
||||
/// The `aspect` param (a percentage) as a ratio.
|
||||
/// The `aspect` param (a percentage) as a ratio of 0.005 to 327.67, its sign kept: a negative one
|
||||
/// mirrors a conic gradient's sweep ([`aspect_for`]).
|
||||
fn aspect_param(p: &Value) -> Parsed<Option<f64>> {
|
||||
p.get("aspect")
|
||||
.map(|v| v.as_f64().map(|a| (a / 100.0).clamp(0.005, 327.67)).ok_or_else(|| "`aspect` must be a number (%)".to_string()))
|
||||
.map(|v| {
|
||||
v.as_f64()
|
||||
.filter(|a| a.is_finite())
|
||||
.map(|a| (a.abs() / 100.0).clamp(0.005, 327.67).copysign(a))
|
||||
.ok_or_else(|| "`aspect` must be a number (%)".to_string())
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Aspect ratio `a` ([`aspect_param`]) for a gradient of `kind`: a negative one mirrors a conic's
|
||||
/// sweep, and is an error for the other kinds.
|
||||
fn aspect_for(kind: GradientKind, a: f64) -> Parsed<f64> {
|
||||
if a < 0.0 && kind != GradientKind::Conic {
|
||||
return Err("a negative `aspect` applies to conic gradients".into());
|
||||
}
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
/// 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()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `paint` without the placement it had on the art it came from (a swatch, or the default paint
|
||||
/// for new art): a placed gradient keeps its angle and fits each object it lands on (freeform
|
||||
/// points are placed afresh, coloured along the stops, which follow the points' colours).
|
||||
@@ -400,7 +430,7 @@ fn apply_gradient_edit_in_model(
|
||||
if let Some(g) = &mut gp.geom {
|
||||
let r = a.to_radians();
|
||||
let dir = vectorcraft_geom::Vec2::new(r.cos(), -r.sin());
|
||||
if gp.gradient.kind == GradientKind::Radial {
|
||||
if gp.gradient.kind.is_centered() {
|
||||
g.end = g.start + dir * g.length();
|
||||
} else {
|
||||
let c = g.start.midpoint(g.end);
|
||||
@@ -411,6 +441,7 @@ fn apply_gradient_edit_in_model(
|
||||
}
|
||||
}
|
||||
if let Some(asp) = aspect_param(p)? {
|
||||
let asp = aspect_for(gp.gradient.kind, asp)?;
|
||||
if gp.geom.is_none()
|
||||
&& let Some(b) = bounds
|
||||
{
|
||||
@@ -472,7 +503,20 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let p = &link_stops(&s.doc()?.doc, p).map_err(|e| bad(C, e))?;
|
||||
// Validate against the defaults first so bad params fail without touching the document.
|
||||
let default_paint = if stroke { s.paint.stroke.clone() } else { s.paint.fill.clone() };
|
||||
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(p, &default_paint, &stored), None, &|_| true, model)
|
||||
// A negative aspect for selected conic gradients gives a default of another kind its size.
|
||||
let default_kind = str_param(p, "kind").and_then(GradientKind::parse).or(match &default_paint {
|
||||
Paint::Gradient(g) => Some(g.gradient.kind),
|
||||
_ => None,
|
||||
});
|
||||
let for_default = match p.get("aspect").and_then(Value::as_f64) {
|
||||
Some(a) if a < 0.0 && !ids.is_empty() && default_kind != Some(GradientKind::Conic) => {
|
||||
let mut q = p.clone();
|
||||
q["aspect"] = json!(-a);
|
||||
std::borrow::Cow::Owned(q)
|
||||
}
|
||||
_ => std::borrow::Cow::Borrowed(p),
|
||||
};
|
||||
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model)
|
||||
.map_err(|e| bad(C, e))?;
|
||||
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
|
||||
edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| {
|
||||
@@ -599,11 +643,23 @@ impl GeomEdit {
|
||||
|
||||
/// `cur` with the vector, aspect and focal point of `e` (given in the document). `to_doc` maps
|
||||
/// 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.
|
||||
fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option<Rect>, model: Option<vectorcraft_color::cms::Model>) -> Option<Paint> {
|
||||
let from_doc = invert(to_doc)?;
|
||||
/// 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 or diamond's focal point).
|
||||
fn vector_paint(
|
||||
cur: &Paint,
|
||||
e: &GeomEdit,
|
||||
to_doc: Affine,
|
||||
bounds: Option<Rect>,
|
||||
model: Option<vectorcraft_color::cms::Model>,
|
||||
) -> Parsed<Option<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 matches!(kind, GradientKind::Conic | GradientKind::Diamond) {
|
||||
no_focal(e)?;
|
||||
}
|
||||
let Some(from_doc) = invert(to_doc) else { return Ok(None) };
|
||||
let map = |mut g: GradientGeom, a: Affine| {
|
||||
if a != Affine::IDENTITY {
|
||||
g.transform(a, kind);
|
||||
@@ -611,8 +667,8 @@ fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option<Rect>,
|
||||
g
|
||||
};
|
||||
let shown = gp.geom.or_else(|| bounds.map(|b| gp.resolve(b))).map(|g| map(g, to_doc));
|
||||
let (start, end) = e.vector.or_else(|| shown.map(|g| (g.start, g.end)))?;
|
||||
let aspect = e.aspect.or_else(|| shown.map(|g| g.aspect)).unwrap_or(1.0);
|
||||
let Some((start, end)) = e.vector.or_else(|| shown.map(|g| (g.start, g.end))) else { return Ok(None) };
|
||||
let aspect = edit_aspect.or_else(|| shown.map(|g| g.aspect)).unwrap_or(1.0);
|
||||
let mut geom = GradientGeom { start, end, aspect, focal: None };
|
||||
match (e.focal, shown) {
|
||||
_ if kind != GradientKind::Radial => {}
|
||||
@@ -623,7 +679,7 @@ fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option<Rect>,
|
||||
let geom = map(geom, from_doc);
|
||||
gp.angle = geom.angle_deg();
|
||||
gp.geom = Some(geom);
|
||||
Some(Paint::Gradient(Box::new(gp)))
|
||||
Ok(Some(Paint::Gradient(Box::new(gp))))
|
||||
}
|
||||
|
||||
fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -658,14 +714,15 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
run_stroke_weight(&mut r.style);
|
||||
}
|
||||
let (paint, b) = run_paint_mut(r, stroke, lb);
|
||||
if let Some(np) = vector_paint(paint, &edit, xf, Some(b), model) {
|
||||
if let Some(np) = vector_paint(paint, &edit, xf, Some(b), model).map_err(|e| bad(C, e))? {
|
||||
*paint = np;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let b = item_paint_bounds(n, index, !stroke);
|
||||
if let Some(np) = vector_paint(n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None), &edit, Affine::IDENTITY, b, model) {
|
||||
let cur = n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None);
|
||||
if let Some(np) = vector_paint(cur, &edit, Affine::IDENTITY, b, model).map_err(|e| bad(C, e))? {
|
||||
n.appearance.set_paint_at(index, !stroke, np);
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -17,7 +17,9 @@ use vectorcraft_doc::{
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes};
|
||||
|
||||
use super::typecmd::refresh_bounds;
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, f64_or, f64_req, has_doc, has_selection, named_id, ok, str_param};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, cmd, f64_req, has_doc, has_selection, named_id, number_or, ok, str_param, switch_or, text_param,
|
||||
};
|
||||
|
||||
mod axis;
|
||||
mod columns;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{GraphSpec, Value};
|
||||
use super::{GraphSpec, Result, Value, bad};
|
||||
|
||||
pub(super) const LABEL_SIZE: f64 = 9.0;
|
||||
|
||||
@@ -22,6 +22,16 @@ pub(super) fn count_param(p: &Value, key: &str, max: u64) -> Option<usize> {
|
||||
usize::try_from(n.min(max)).ok()
|
||||
}
|
||||
|
||||
/// [`count_param`], or `None` when `p` leaves `key` out or gives null. A negative number is an error, and so is any
|
||||
/// other value, such as `"5"`.
|
||||
pub(super) fn count_given(p: &Value, key: &str, max: u64, cmd: &str) -> Result<Option<usize>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) if !v.is_number() => Err(bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
Some(_) => count_param(p, key, max).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be 0 or more"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A "nice" axis: (min, max, step).
|
||||
pub(super) fn nice_axis(lo: f64, hi: f64, ticks: usize) -> (f64, f64, f64) {
|
||||
let (lo, hi) = if (hi - lo).abs() < 1e-12 { (lo.min(0.0), lo.max(0.0) + 1.0) } else { (lo, hi) };
|
||||
|
||||
@@ -12,7 +12,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Graph",
|
||||
[],
|
||||
None,
|
||||
"{type: column|stackedColumn|bar|stackedBar|line|area|scatter|pie|radar, x, y, width, height, series?: [..], categories?: [..], rows?: [[number|null]], csv?} → {id}; an empty CSV cell or a null is a blank value, a number in straight quotes is a label",
|
||||
"{type: column|stackedColumn|bar|stackedBar|line|area|scatter|pie|radar, x, y, width, height, series?: [..], categories?: [..], rows?: [[number|null]], csv?} → {id}; an empty CSV cell or a null is a blank value, a number in straight quotes is a label; a `type` that is not a string, a `width` or `height` that is not a number, and data of the wrong type (as `graph.setData` reads it) are refused",
|
||||
has_doc,
|
||||
create
|
||||
),
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Data…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{id?, series?, categories?, rows?, csv?: first row = series labels (first cell empty); then one row per category: label; values…; an empty cell or a null is a blank value; a quoted number a label; a `|` in a label a line break, transpose?: true swaps rows and columns (Transpose row/column), switchXY?: true swaps each scatter series' y and x columns (Switch x/y)} replace the graph's data; no data → the current {csv, series, categories, rows}",
|
||||
"{id?, series?, categories?, rows?, csv?: first row = series labels (first cell empty); then one row per category: label; values…; an empty cell or a null is a blank value; a quoted number a label; a `|` in a label a line break, transpose?: true swaps rows and columns (Transpose row/column), switchXY?: true swaps each scatter series' y and x columns (Switch x/y)} replace the graph's data; a `csv` that is not a string, `series` or `categories` that are not lists, `rows` that are not lists of numbers and nulls, or a `transpose` or `switchXY` that is not true or false is refused and the graph stays as it was; no data → the current {csv, series, categories, rows}",
|
||||
has_selection,
|
||||
set_data
|
||||
),
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Type…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?, axisMax?, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as 3 pt bands filled with the series colour), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); no options → the current ones",
|
||||
"{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as 3 pt bands filled with the series colour), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones",
|
||||
has_selection,
|
||||
set_type
|
||||
),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::edit::{regenerate, spec_of, target};
|
||||
use super::series::{switch_xy, transpose};
|
||||
use super::{Document, EngineError, GraphKind, GraphSpec, NodeId, Result, Session, Value, bad, bool_or, json, str_param};
|
||||
use super::{Document, EngineError, GraphKind, GraphSpec, NodeId, Result, Session, Value, bad, json, switch_or, text_param};
|
||||
|
||||
// ---------- data ----------
|
||||
|
||||
@@ -101,7 +101,7 @@ pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> {
|
||||
return Err(bad("graph.applyCsv", format!("node {} is not a graph", id.0)));
|
||||
};
|
||||
let mut spec = current.clone();
|
||||
apply_data(&mut spec, &json!({ "csv": csv }));
|
||||
apply_data(&mut spec, &json!({ "csv": csv }), "graph.applyCsv")?;
|
||||
keep_right_series(&mut spec);
|
||||
if spec == *current {
|
||||
return Ok(());
|
||||
@@ -115,34 +115,58 @@ fn keep_right_series(g: &mut GraphSpec) {
|
||||
g.right_series.retain(|i| *i < count);
|
||||
}
|
||||
|
||||
pub(super) fn apply_data(g: &mut GraphSpec, p: &Value) -> bool {
|
||||
/// Apply the data `p` gives (`csv`, `series`, `categories`, `rows`) to `g`; true when it gave any. A null is read as a
|
||||
/// key left out. A `csv` that is not a string, a `series` or `categories` that is not a list, and `rows` that are not
|
||||
/// lists of numbers and nulls are errors, and `g` is left as it was.
|
||||
pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result<bool> {
|
||||
let list = |key: &str| -> Result<Option<&Vec<Value>>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Array(a)) => Ok(Some(a)),
|
||||
Some(v) => Err(bad(cmd, format!("`{key}` must be a list, not {v}"))),
|
||||
}
|
||||
};
|
||||
let csv = text_param(p, "csv", cmd)?;
|
||||
let strings = |a: &Vec<Value>| a.iter().map(|x| x.as_str().map(str::to_string).unwrap_or_else(|| x.to_string())).collect::<Vec<_>>();
|
||||
let series = list("series")?.map(strings);
|
||||
let categories = list("categories")?.map(strings);
|
||||
// A null is a blank cell.
|
||||
let rows = list("rows")?
|
||||
.map(|rows| {
|
||||
rows.iter()
|
||||
.map(|r| {
|
||||
let bad_row = || bad(cmd, format!("`rows` must be lists of numbers or nulls, not {r}"));
|
||||
r.as_array()
|
||||
.ok_or_else(bad_row)?
|
||||
.iter()
|
||||
.map(|v| if v.is_null() { Ok(None) } else { v.as_f64().map(|v| Some(v).filter(|v| v.is_finite())).ok_or_else(bad_row) })
|
||||
.collect::<Result<Vec<_>>>()
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
})
|
||||
.transpose()?;
|
||||
let mut changed = false;
|
||||
if let Some(csv) = str_param(p, "csv") {
|
||||
if let Some(csv) = csv {
|
||||
let (s, c, r) = parse_csv(csv);
|
||||
g.series = s;
|
||||
g.categories = c;
|
||||
g.set_cells(r);
|
||||
changed = true;
|
||||
}
|
||||
let strings =
|
||||
|v: &Value| v.as_array().map(|a| a.iter().map(|x| x.as_str().map(str::to_string).unwrap_or_else(|| x.to_string())).collect::<Vec<_>>());
|
||||
if let Some(s) = p.get("series").and_then(strings) {
|
||||
if let Some(s) = series {
|
||||
g.series = s;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(c) = p.get("categories").and_then(strings) {
|
||||
if let Some(c) = categories {
|
||||
g.categories = c;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(rows) = p.get("rows").and_then(Value::as_array) {
|
||||
// `null` (or anything that isn't a finite number) is a blank cell.
|
||||
g.set_cells(
|
||||
rows.iter().map(|r| r.as_array().map(|a| a.iter().map(|v| v.as_f64().filter(|v| v.is_finite())).collect()).unwrap_or_default()).collect(),
|
||||
);
|
||||
if let Some(rows) = rows {
|
||||
g.set_cells(rows);
|
||||
changed = true;
|
||||
}
|
||||
drop_empty_rows(g);
|
||||
changed
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// Drop rows with neither a value nor a label; a label-only row stays, its values blank. Each kept row keeps its own
|
||||
@@ -184,13 +208,13 @@ pub(super) fn set_data(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "graph.setData";
|
||||
let id = target(s, p, C)?;
|
||||
let mut spec = spec_of(s, id)?;
|
||||
let flip = bool_or(p, "transpose", false);
|
||||
let swap = bool_or(p, "switchXY", false);
|
||||
let flip = switch_or(p, "transpose", false, C)?;
|
||||
let swap = switch_or(p, "switchXY", false, C)?;
|
||||
if swap && spec.kind != GraphKind::Scatter {
|
||||
return Err(bad(C, "Switch x/y is for scatter graphs"));
|
||||
}
|
||||
// Transpose and Switch x/y act after any new data in the same call.
|
||||
let changed = apply_data(&mut spec, p);
|
||||
let changed = apply_data(&mut spec, p, C)?;
|
||||
if flip {
|
||||
// The categories become series: at most as many as a graph has series.
|
||||
if spec.cells().len() > vectorcraft_doc::MAX_GRAPH_SERIES {
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
use super::axis::{MAX_TICK_MARKS, count_param, one_line};
|
||||
use super::axis::{MAX_TICK_MARKS, count_given, one_line};
|
||||
use super::data::apply_data;
|
||||
use super::generate::{children_bounds, generate};
|
||||
use super::series::{picked_series, reselect_series};
|
||||
use super::{
|
||||
Affine, Document, EngineError, GraphKind, GraphSpec, Node, NodeId, Rect, Result, Session, TickLength, Value, ValueAxisSide, bad, bool_or, f64_or,
|
||||
f64_req, json, named_id, str_param,
|
||||
Affine, Document, EngineError, GraphKind, GraphSpec, Node, NodeId, Rect, Result, Session, TickLength, Value, ValueAxisSide, bad, f64_req, json,
|
||||
named_id, number_or, switch_or, text_param,
|
||||
};
|
||||
|
||||
/// An axis bound `p` gives for `key`: `None` when left out, `Some(None)` for null (calculated from the data), or the
|
||||
/// number. Any other value, such as `"10"`, is an error.
|
||||
fn bound_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<f64>>> {
|
||||
match p.get(key) {
|
||||
None => Ok(None),
|
||||
Some(Value::Null) => Ok(Some(None)),
|
||||
Some(v) => v.as_f64().map(|x| Some(Some(x))).ok_or_else(|| bad(cmd, format!("`{key}` must be a number or null, not {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Regenerate graph `id` from `spec` (adjusting the plot rect for any move/scale since the last
|
||||
/// generation, which is recorded in the spec's `placed` bounds).
|
||||
pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> {
|
||||
@@ -33,12 +43,14 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R
|
||||
|
||||
pub(super) fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "graph.create";
|
||||
let kind =
|
||||
str_param(p, "type").map(|t| GraphKind::parse(t).ok_or_else(|| bad(C, format!("unknown graph type `{t}`")))).transpose()?.unwrap_or_default();
|
||||
let kind = text_param(p, "type", C)?
|
||||
.map(|t| GraphKind::parse(t).ok_or_else(|| bad(C, format!("unknown graph type `{t}`"))))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let (x, y) = (f64_req(p, "x", C)?, f64_req(p, "y", C)?);
|
||||
let (w, h) = (f64_or(p, "width", 200.0).abs().max(1.0), f64_or(p, "height", 150.0).abs().max(1.0));
|
||||
let (w, h) = (number_or(p, "width", 200.0, C)?.abs().max(1.0), number_or(p, "height", 150.0, C)?.abs().max(1.0));
|
||||
let mut spec = GraphSpec { kind, rect: Rect::new(x, y, x + w, y + h), ..GraphSpec::default() };
|
||||
if !apply_data(&mut spec, p) {
|
||||
if !apply_data(&mut spec, p, C)? {
|
||||
// Starter data so the new graph shows something (edit it with Object → Graph → Data…).
|
||||
spec.series = vec!["Series 1".into(), "Series 2".into()];
|
||||
spec.categories = vec!["A".into(), "B".into(), "C".into(), "D".into()];
|
||||
@@ -150,7 +162,8 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
spec.right_series.retain(|i| *i < count);
|
||||
spec.right_series.sort_unstable();
|
||||
spec.right_series.dedup();
|
||||
if p.get("seriesIndexes").is_some() && str_param(p, "type").is_none() && str_param(p, "valueAxis").is_none() {
|
||||
let (new_type, new_axis) = (text_param(p, "type", C)?, text_param(p, "valueAxis", C)?);
|
||||
if p.get("seriesIndexes").is_some() && new_type.is_none() && new_axis.is_none() {
|
||||
return Err(bad(C, "`seriesIndexes` needs a `type` or a `valueAxis`"));
|
||||
}
|
||||
let picked = picked_series(s, p, id, count, C)?;
|
||||
@@ -196,7 +209,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Series picked with Group Selection stay selected through the regeneration (their groups are new nodes).
|
||||
let reselect: Vec<u32> = if p.get("seriesIndexes").is_none() { picked.iter().filter_map(|i| u32::try_from(*i).ok()).collect() } else { vec![] };
|
||||
if let Some(t) = str_param(p, "type") {
|
||||
if let Some(t) = new_type {
|
||||
let kind = GraphKind::parse(t).ok_or_else(|| bad(C, format!("unknown graph type `{t}`")))?;
|
||||
if picked.is_empty() {
|
||||
spec.kind = kind;
|
||||
@@ -215,7 +228,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(v) = str_param(p, "valueAxis") {
|
||||
if let Some(v) = new_axis {
|
||||
let side = ValueAxisSide::parse(v).ok_or_else(|| bad(C, format!("unknown value axis `{v}` (left, right or both)")))?;
|
||||
if picked.is_empty() {
|
||||
spec.value_axis = side;
|
||||
@@ -231,54 +244,58 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
spec.separate_scales = bool_or(p, "separateScales", spec.separate_scales);
|
||||
spec.separate_scales = switch_or(p, "separateScales", spec.separate_scales, C)?;
|
||||
for (key, slot) in [
|
||||
("tickLength", &mut spec.tick_length),
|
||||
("rightTickLength", &mut spec.right_tick_length),
|
||||
("categoryTickLength", &mut spec.category_tick_length),
|
||||
] {
|
||||
if let Some(v) = str_param(p, key) {
|
||||
if let Some(v) = text_param(p, key, C)? {
|
||||
*slot = TickLength::parse(v).ok_or_else(|| bad(C, format!("unknown {key} `{v}` (none, short or full)")))?;
|
||||
}
|
||||
}
|
||||
for (key, slot) in
|
||||
[("tickMarks", &mut spec.tick_marks), ("rightTickMarks", &mut spec.right_tick_marks), ("categoryTickMarks", &mut spec.category_tick_marks)]
|
||||
{
|
||||
*slot = count_param(p, key, MAX_TICK_MARKS as u64).map_or(*slot, |n| n.max(1));
|
||||
*slot = count_given(p, key, MAX_TICK_MARKS as u64, C)?.map_or(*slot, |n| n.max(1));
|
||||
}
|
||||
spec.ticks_between_labels = bool_or(p, "ticksBetweenLabels", spec.ticks_between_labels);
|
||||
if let Some(v) = str_param(p, "piePosition") {
|
||||
spec.ticks_between_labels = switch_or(p, "ticksBetweenLabels", spec.ticks_between_labels, C)?;
|
||||
if let Some(v) = text_param(p, "piePosition", C)? {
|
||||
spec.pie_position =
|
||||
vectorcraft_doc::PiePosition::parse(v).ok_or_else(|| bad(C, format!("unknown piePosition `{v}` (even, ratio or stacked)")))?;
|
||||
}
|
||||
if let Some(v) = str_param(p, "pieSort") {
|
||||
if let Some(v) = text_param(p, "pieSort", C)? {
|
||||
spec.pie_sort = vectorcraft_doc::PieSort::parse(v).ok_or_else(|| bad(C, format!("unknown pieSort `{v}` (none, all or first)")))?;
|
||||
}
|
||||
for (key, slot) in
|
||||
[("prefix", &mut spec.prefix), ("suffix", &mut spec.suffix), ("rightPrefix", &mut spec.right_prefix), ("rightSuffix", &mut spec.right_suffix)]
|
||||
{
|
||||
if let Some(v) = str_param(p, key) {
|
||||
if let Some(v) = text_param(p, key, C)? {
|
||||
// A label, not a paragraph: one line, at most MAX_AFFIX characters.
|
||||
*slot = one_line(v);
|
||||
}
|
||||
}
|
||||
spec.right_ticks = count_param(p, "rightTicks", 100).unwrap_or(spec.right_ticks);
|
||||
if let Some(v) = p.get("rightAxisMin") {
|
||||
spec.right_axis_min = v.as_f64();
|
||||
spec.right_ticks = count_given(p, "rightTicks", 100, C)?.unwrap_or(spec.right_ticks);
|
||||
for (key, slot) in [
|
||||
("rightAxisMin", &mut spec.right_axis_min),
|
||||
("rightAxisMax", &mut spec.right_axis_max),
|
||||
("axisMin", &mut spec.axis_min),
|
||||
("axisMax", &mut spec.axis_max),
|
||||
] {
|
||||
if let Some(v) = bound_param(p, key, C)? {
|
||||
*slot = v;
|
||||
}
|
||||
}
|
||||
if let Some(v) = p.get("rightAxisMax") {
|
||||
spec.right_axis_max = v.as_f64();
|
||||
}
|
||||
spec.column_width = f64_or(p, "columnWidth", spec.column_width).clamp(1.0, 1000.0);
|
||||
spec.cluster_width = f64_or(p, "clusterWidth", spec.cluster_width).clamp(1.0, 1000.0);
|
||||
spec.legend = bool_or(p, "legend", spec.legend);
|
||||
spec.drop_shadow = bool_or(p, "dropShadow", spec.drop_shadow);
|
||||
spec.first_row_in_front = bool_or(p, "firstRowInFront", spec.first_row_in_front);
|
||||
spec.first_column_in_front = bool_or(p, "firstColumnInFront", spec.first_column_in_front);
|
||||
spec.filled_lines = bool_or(p, "filledLines", spec.filled_lines);
|
||||
spec.legend_across_top = bool_or(p, "legendAcrossTop", spec.legend_across_top);
|
||||
spec.column_width = number_or(p, "columnWidth", spec.column_width, C)?.clamp(1.0, 1000.0);
|
||||
spec.cluster_width = number_or(p, "clusterWidth", spec.cluster_width, C)?.clamp(1.0, 1000.0);
|
||||
spec.legend = switch_or(p, "legend", spec.legend, C)?;
|
||||
spec.drop_shadow = switch_or(p, "dropShadow", spec.drop_shadow, C)?;
|
||||
spec.first_row_in_front = switch_or(p, "firstRowInFront", spec.first_row_in_front, C)?;
|
||||
spec.first_column_in_front = switch_or(p, "firstColumnInFront", spec.first_column_in_front, C)?;
|
||||
spec.filled_lines = switch_or(p, "filledLines", spec.filled_lines, C)?;
|
||||
spec.legend_across_top = switch_or(p, "legendAcrossTop", spec.legend_across_top, C)?;
|
||||
// After `legend`, which the Graph Type dialog sends too.
|
||||
if let Some(v) = str_param(p, "pieLegend") {
|
||||
if let Some(v) = text_param(p, "pieLegend", C)? {
|
||||
(spec.legend, spec.pie_legend_in_wedges) = match v.to_ascii_lowercase().as_str() {
|
||||
"none" => (false, false),
|
||||
"standard" => (true, false),
|
||||
@@ -286,16 +303,10 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => return Err(bad(C, format!("unknown pieLegend `{v}` (none, standard or wedges)"))),
|
||||
};
|
||||
}
|
||||
spec.mark_points = bool_or(p, "markPoints", spec.mark_points);
|
||||
spec.connect_points = bool_or(p, "connectPoints", spec.connect_points);
|
||||
spec.edge_to_edge = bool_or(p, "edgeToEdge", spec.edge_to_edge);
|
||||
spec.ticks = count_param(p, "ticks", 100).unwrap_or(spec.ticks);
|
||||
if let Some(v) = p.get("axisMin") {
|
||||
spec.axis_min = v.as_f64();
|
||||
}
|
||||
if let Some(v) = p.get("axisMax") {
|
||||
spec.axis_max = v.as_f64();
|
||||
}
|
||||
spec.mark_points = switch_or(p, "markPoints", spec.mark_points, C)?;
|
||||
spec.connect_points = switch_or(p, "connectPoints", spec.connect_points, C)?;
|
||||
spec.edge_to_edge = switch_or(p, "edgeToEdge", spec.edge_to_edge, C)?;
|
||||
spec.ticks = count_given(p, "ticks", 100, C)?.unwrap_or(spec.ticks);
|
||||
let label = format!("{} Graph", spec.kind.label());
|
||||
s.edit("Graph Type", |d, sel| {
|
||||
regenerate(d, id, spec)?;
|
||||
|
||||
@@ -2638,9 +2638,12 @@ fn counts_come_back_from_the_dialog_as_floats_and_are_capped() {
|
||||
s.execute("graph.setType", &json!({"tickMarks": 3.0, "ticks": 4.0, "categoryTickMarks": 2.6})).unwrap();
|
||||
let g = spec(&s, id);
|
||||
assert_eq!((g.tick_marks, g.ticks, g.category_tick_marks), (3, 4, 3));
|
||||
s.execute("graph.setType", &json!({"categoryTickMarks": 0, "rightTickMarks": 1e300, "rightTicks": -2.0})).unwrap();
|
||||
s.execute("graph.setType", &json!({"categoryTickMarks": 0, "rightTickMarks": 1e300})).unwrap();
|
||||
let g = spec(&s, id);
|
||||
assert_eq!((g.category_tick_marks, g.right_tick_marks, g.right_ticks), (1, 20, 0));
|
||||
// A negative count is refused.
|
||||
s.execute("graph.setType", &json!({"rightTicks": -2.0})).unwrap_err();
|
||||
assert_eq!(spec(&s, id).right_ticks, 0);
|
||||
// A file's values come back as drawn.
|
||||
let mut fields = s.execute("graph.setType", &json!({})).unwrap();
|
||||
assert_eq!(fields["rightTickMarks"], 20);
|
||||
@@ -4498,3 +4501,93 @@ fn a_legend_label_with_kept_negative_space_before_stays_below_the_entry_above_it
|
||||
let (first, next) = (bounds("2024"), bounds("20\n25"));
|
||||
assert!(next.y0 >= first.y1, "the second legend label starts below the first one: {first:?} {next:?}");
|
||||
}
|
||||
|
||||
/// A graph command given a value of the wrong type refuses it, naming the key, and leaves the graph and the undo
|
||||
/// history as they were; a null axis bound still goes back to the calculated value.
|
||||
#[test]
|
||||
fn graph_commands_refuse_params_of_the_wrong_type() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = graph(&mut s, "line");
|
||||
s.execute("graph.setType", &json!({"id": id.0, "axisMin": 0, "axisMax": 10})).unwrap();
|
||||
let spec = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().extras().graph.as_deref().cloned().unwrap();
|
||||
let undo_len = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let (before, steps) = (spec(&s), undo_len(&s));
|
||||
let refused = |s: &mut Session, cmd: &str, p: serde_json::Value, msg: &str| {
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(msg), "{cmd} {p}: {e}");
|
||||
};
|
||||
for (key, v, msg) in [
|
||||
("axisMin", json!("10"), "`axisMin` must be a number or null, not \"10\""),
|
||||
("axisMax", json!(true), "`axisMax` must be a number or null"),
|
||||
("rightAxisMin", json!([1]), "`rightAxisMin` must be a number or null"),
|
||||
("rightAxisMax", json!({}), "`rightAxisMax` must be a number or null"),
|
||||
("columnWidth", json!("50"), "`columnWidth` must be a number, not \"50\""),
|
||||
("clusterWidth", json!(false), "`clusterWidth` must be a number"),
|
||||
("ticks", json!("5"), "`ticks` must be a number, not \"5\""),
|
||||
("ticks", json!(-2), "`ticks` must be 0 or more"),
|
||||
("rightTicks", json!("5"), "`rightTicks` must be a number"),
|
||||
("tickMarks", json!("2"), "`tickMarks` must be a number"),
|
||||
("rightTickMarks", json!(-1), "`rightTickMarks` must be 0 or more"),
|
||||
("categoryTickMarks", json!(true), "`categoryTickMarks` must be a number"),
|
||||
("legend", json!("false"), "`legend` must be true or false"),
|
||||
("markPoints", json!(0), "`markPoints` must be true or false"),
|
||||
("connectPoints", json!("no"), "`connectPoints` must be true or false"),
|
||||
("edgeToEdge", json!(1), "`edgeToEdge` must be true or false"),
|
||||
("separateScales", json!("true"), "`separateScales` must be true or false"),
|
||||
("ticksBetweenLabels", json!(1), "`ticksBetweenLabels` must be true or false"),
|
||||
("firstRowInFront", json!("yes"), "`firstRowInFront` must be true or false"),
|
||||
("firstColumnInFront", json!(0), "`firstColumnInFront` must be true or false"),
|
||||
("filledLines", json!("on"), "`filledLines` must be true or false"),
|
||||
("dropShadow", json!(1), "`dropShadow` must be true or false"),
|
||||
("legendAcrossTop", json!("x"), "`legendAcrossTop` must be true or false"),
|
||||
("type", json!(5), "`type` must be a string"),
|
||||
("valueAxis", json!(true), "`valueAxis` must be a string"),
|
||||
("tickLength", json!(1), "`tickLength` must be a string"),
|
||||
("rightTickLength", json!(1), "`rightTickLength` must be a string"),
|
||||
("categoryTickLength", json!(1), "`categoryTickLength` must be a string"),
|
||||
("prefix", json!(1), "`prefix` must be a string"),
|
||||
("suffix", json!(true), "`suffix` must be a string"),
|
||||
("rightPrefix", json!([]), "`rightPrefix` must be a string"),
|
||||
("rightSuffix", json!(2), "`rightSuffix` must be a string"),
|
||||
("pieLegend", json!(1), "`pieLegend` must be a string"),
|
||||
("piePosition", json!(1), "`piePosition` must be a string"),
|
||||
("pieSort", json!(1), "`pieSort` must be a string"),
|
||||
] {
|
||||
refused(&mut s, "graph.setType", json!({"id": id.0, key: v}), msg);
|
||||
}
|
||||
for (key, v, msg) in [
|
||||
("csv", json!(5), "`csv` must be a string"),
|
||||
("series", json!("a"), "`series` must be a list, not \"a\""),
|
||||
("categories", json!({}), "`categories` must be a list"),
|
||||
("rows", json!("1,2"), "`rows` must be a list"),
|
||||
("rows", json!([1, 2]), "`rows` must be lists of numbers or nulls, not 1"),
|
||||
("rows", json!([[1, "2"]]), "`rows` must be lists of numbers or nulls"),
|
||||
("transpose", json!("true"), "`transpose` must be true or false"),
|
||||
("switchXY", json!(1), "`switchXY` must be true or false"),
|
||||
] {
|
||||
refused(&mut s, "graph.setData", json!({"id": id.0, key: v}), msg);
|
||||
}
|
||||
assert_eq!(spec(&s), before);
|
||||
assert_eq!(undo_len(&s), steps);
|
||||
let count = |s: &Session| s.doc().unwrap().doc.node_count();
|
||||
let objects = count(&s);
|
||||
for (key, v, msg) in [
|
||||
("type", json!(1), "`type` must be a string"),
|
||||
("width", json!("300"), "`width` must be a number, not \"300\""),
|
||||
("height", json!(true), "`height` must be a number"),
|
||||
("csv", json!(1), "`csv` must be a string"),
|
||||
("rows", json!([[true]]), "`rows` must be lists of numbers or nulls"),
|
||||
] {
|
||||
let mut p = json!({"type": "column", "x": 0, "y": 0, "width": 100, "height": 100});
|
||||
p[key] = v;
|
||||
refused(&mut s, "graph.create", p, msg);
|
||||
}
|
||||
assert_eq!((count(&s), undo_len(&s)), (objects, steps));
|
||||
// A null is a key left out, except for an axis bound, where it goes back to the calculated value.
|
||||
s.execute("graph.setType", &json!({"id": id.0, "legend": null, "ticks": null, "prefix": null, "axisMin": null})).unwrap();
|
||||
assert_eq!(spec(&s).axis_min, None);
|
||||
assert_eq!(spec(&s).axis_max, Some(10.0));
|
||||
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, null], [2, 3]], "series": null, "transpose": null})).unwrap();
|
||||
assert_eq!(spec(&s).cells(), vec![vec![Some(1.0), None], vec![Some(2.0), Some(3.0)]]);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_doc::Node;
|
||||
use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, color_value, f64_or, has_selection, str_param};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, color_value, has_selection, number_or, switch_or, text_param};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
@@ -27,28 +27,28 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.vectorHalftone";
|
||||
let shape = match str_param(p, "shape") {
|
||||
let shape = match text_param(p, "shape", C)? {
|
||||
Some(v) => DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line)")))?,
|
||||
None => DotShape::Circle,
|
||||
};
|
||||
let frequency = f64_or(p, "frequency", 20.0);
|
||||
let frequency = number_or(p, "frequency", 20.0, C)?;
|
||||
if !(1.0..=300.0).contains(&frequency) {
|
||||
return Err(bad(C, "frequency must be between 1 and 300 lines per inch"));
|
||||
}
|
||||
let angle = f64_or(p, "angle", 45.0);
|
||||
let angle = number_or(p, "angle", 45.0, C)?;
|
||||
if !angle.is_finite() {
|
||||
return Err(bad(C, "invalid angle"));
|
||||
}
|
||||
let mono = match str_param(p, "mode").unwrap_or("mono") {
|
||||
let mono = match text_param(p, "mode", C)?.unwrap_or("mono") {
|
||||
"mono" => true,
|
||||
"cmyk" => false,
|
||||
other => return Err(bad(C, format!("unknown mode `{other}` (mono|cmyk)"))),
|
||||
};
|
||||
let color = match p.get("color") {
|
||||
None | Some(Value::Null) => Color::BLACK,
|
||||
Some(v) => color_value(v).ok_or_else(|| bad(C, "invalid color"))?,
|
||||
None => Color::BLACK,
|
||||
};
|
||||
let (invert, clip, keep) = (bool_or(p, "invert", false), bool_or(p, "clip", true), bool_or(p, "keepOriginal", false));
|
||||
let (invert, clip, keep) = (switch_or(p, "invert", false, C)?, switch_or(p, "clip", true, C)?, switch_or(p, "keepOriginal", false, C)?);
|
||||
let ht = Halftone { shape, frequency, angle, mono, color, from_art: false, invert, clip };
|
||||
|
||||
let roots = selected_roots(s)?;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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(_)))) {
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -36,6 +36,9 @@ pub(crate) use arrange::group_nodes;
|
||||
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::{keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned};
|
||||
pub(crate) use pixelgrid::{
|
||||
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};
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -12,7 +12,7 @@ use vectorcraft_geom::FillRule;
|
||||
|
||||
use super::appearance::{ItemTarget, item_target};
|
||||
use super::edit::selected_roots;
|
||||
use super::{CommandSpec, Result, Session, bad, bool_or, cmd, f64_or, has_doc, ids_param, targets};
|
||||
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, ids_param, number_or, switch_or, targets};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -221,15 +221,16 @@ fn overprint_black_tree(n: &mut Node, op: &OverprintBlack, spots: &[String]) ->
|
||||
}
|
||||
|
||||
pub(crate) fn overprint_black(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.colors.overprintBlack";
|
||||
let op = OverprintBlack {
|
||||
remove: bool_or(p, "remove", false),
|
||||
min_k: (f64_or(p, "percentage", 100.0) / 100.0).clamp(0.0, 1.0) as f32,
|
||||
fill: bool_or(p, "fill", true),
|
||||
stroke: bool_or(p, "stroke", true),
|
||||
rich: bool_or(p, "includeCmyBlacks", false),
|
||||
spot: bool_or(p, "includeSpotBlacks", false),
|
||||
remove: switch_or(p, "remove", false, C)?,
|
||||
min_k: (number_or(p, "percentage", 100.0, C)? / 100.0).clamp(0.0, 1.0) as f32,
|
||||
fill: switch_or(p, "fill", true, C)?,
|
||||
stroke: switch_or(p, "stroke", true, C)?,
|
||||
rich: switch_or(p, "includeCmyBlacks", false, C)?,
|
||||
spot: switch_or(p, "includeSpotBlacks", false, C)?,
|
||||
};
|
||||
let ids = match ids_param(p, "ids", "edit.colors.overprintBlack")? {
|
||||
let ids = match ids_param(p, "ids", C)? {
|
||||
Some(v) => v,
|
||||
None => selected_roots(s)?,
|
||||
};
|
||||
|
||||
@@ -14,7 +14,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::fileio::{create_dir, write_file};
|
||||
use super::links::LinkBase;
|
||||
use super::{CommandSpec, Result, Session, bad, bool_or, cmd, has_doc, str_param, unique_name};
|
||||
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_param, unique_name};
|
||||
|
||||
const C: &str = "file.package";
|
||||
|
||||
@@ -451,19 +451,20 @@ impl Session {
|
||||
/// name, the report's Document Info text and the document.
|
||||
fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
|
||||
let o = Options {
|
||||
copy_links: bool_or(p, "copyLinks", true),
|
||||
links_folder: bool_or(p, "linksFolder", true),
|
||||
relink: bool_or(p, "relink", true),
|
||||
copy_fonts: bool_or(p, "copyFonts", true),
|
||||
report: bool_or(p, "report", true),
|
||||
copy_links: switch_or(p, "copyLinks", true, C)?,
|
||||
links_folder: switch_or(p, "linksFolder", true, C)?,
|
||||
relink: switch_or(p, "relink", true, C)?,
|
||||
copy_fonts: switch_or(p, "copyFonts", true, C)?,
|
||||
report: switch_or(p, "report", true, C)?,
|
||||
};
|
||||
let given_name = text_param(p, "name", C)?;
|
||||
let folder = text_param(p, "folder", C)?;
|
||||
let doc_path = s.doc()?.path.clone().ok_or_else(|| bad(C, "save the document first: Package collects a saved document"))?;
|
||||
let stem = Path::new(&doc_path).file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned());
|
||||
let name = str_param(p, "name").map_or_else(|| format!("{stem} Folder"), str::to_string);
|
||||
let name = given_name.map_or_else(|| format!("{stem} Folder"), str::to_string);
|
||||
if name.trim().is_empty() || name == "." || name == ".." || name.contains(['/', '\\', ':', '*', '?', '"', '<', '>', '|']) {
|
||||
return Err(bad(C, format!("`{name}` can't name a folder")));
|
||||
}
|
||||
let folder = str_param(p, "folder");
|
||||
let root = folder.map(|f| Path::new(f).join(&name));
|
||||
let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None };
|
||||
let doc = s.doc()?.doc.clone();
|
||||
|
||||
@@ -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|freeform, 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; 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), dither?: bool (linear and radial 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 or radial `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 or radial 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 or radial 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(
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Close Path",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?: usize (the open subpath to close, 0 included; default: the last open one), in?: [x,y] (handle into the first anchor), independent?: bool}",
|
||||
"{id, subpath?: usize (the open subpath to close, 0 included; default: the last open one), in?: [x,y] (handle into the first anchor, placed as path.setHandle places it: a smooth first anchor keeps its outgoing handle in line at its own length, a corner keeps it where it is), out?: [x,y] (the first anchor's outgoing handle, placed after `in`; the anchor becomes a corner), independent?: bool (`in` makes the first anchor a corner and leaves its outgoing handle)}",
|
||||
has_doc,
|
||||
close
|
||||
),
|
||||
@@ -202,14 +202,18 @@ fn append_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Close the active open subpath of `id`, optionally setting the incoming handle of the first anchor.
|
||||
/// Close the active open subpath of `id`, optionally setting the handles of the first anchor. The
|
||||
/// incoming handle moves as Move Direction Handle moves it: the outgoing handle turns with it only
|
||||
/// on a smooth anchor, so the first segment of a path that starts at a corner keeps its shape.
|
||||
fn close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("path.close", "missing id"))?;
|
||||
let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize);
|
||||
let h_in = match p.get("in").filter(|h| !h.is_null()) {
|
||||
None => None,
|
||||
Some(h) => Some(finite_numbers(h).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.close", "`in` must be [x, y]"))?),
|
||||
let handle = |key: &str| match p.get(key).filter(|h| !h.is_null()) {
|
||||
None => Ok(None),
|
||||
Some(h) => finite_numbers(h).map(|[x, y]| Some(Point::new(x, y))).ok_or_else(|| bad("path.close", format!("`{key}` must be [x, y]"))),
|
||||
};
|
||||
let h_in = handle("in")?;
|
||||
let h_out = handle("out")?;
|
||||
let independent = switch_or(p, "independent", false, "path.close")?;
|
||||
s.edit("Close Path", |d, sel| {
|
||||
let path = path_mut(d, id)?;
|
||||
@@ -218,11 +222,13 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => path.subpaths.iter_mut().rev().find(|s| !s.closed).ok_or_else(|| EngineError::Other("path is already closed".into()))?,
|
||||
};
|
||||
sp.closed = true;
|
||||
if let (Some(h), Some(first)) = (h_in, sp.anchors.first_mut()) {
|
||||
first.h_in = h;
|
||||
if !independent {
|
||||
first.h_out = first.p - (h - first.p);
|
||||
first.kind = AnchorKind::Smooth;
|
||||
if let Some(first) = sp.anchors.first_mut() {
|
||||
if let Some(h) = h_in {
|
||||
first.set_handle(false, h, independent);
|
||||
}
|
||||
if let Some(h) = h_out {
|
||||
first.h_out = h;
|
||||
first.kind = AnchorKind::Corner;
|
||||
}
|
||||
}
|
||||
let top = compound_or_self(d, id);
|
||||
|
||||
@@ -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
|
||||
@@ -47,7 +47,10 @@ use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
use vectorcraft_pdf::CropTo;
|
||||
|
||||
use super::fileio::{self, Format, RasterImage};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, finite_numbers, has_doc, object_param, str_param, unique_name};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, bool_or, check_numbers, check_switches, cmd, finite_numbers, has_doc, object_param, str_param,
|
||||
switch_or, unique_name,
|
||||
};
|
||||
use crate::{EngineError, MAX_COORD};
|
||||
|
||||
const PLACE: &str = "file.place";
|
||||
@@ -66,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
|
||||
),
|
||||
@@ -261,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.
|
||||
@@ -556,8 +559,9 @@ fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
|
||||
let replace = bool_or(p, "replace", false);
|
||||
let template = bool_or(p, "template", false);
|
||||
let replace = switch_or(p, "replace", false, PLACE)?;
|
||||
let template = switch_or(p, "template", false, PLACE)?;
|
||||
check_switches(p, &["link"], PLACE)?;
|
||||
let at = at_param(p)?;
|
||||
let rect = rect_param(p)?;
|
||||
if replace && (template || at.is_some() || rect.is_some()) {
|
||||
@@ -778,6 +782,8 @@ impl Session {
|
||||
/// desktop the Place dialog's OK with several files does this off the UI thread).
|
||||
pub fn prepare_place_queue(&self, params: &Value) -> Result<QueueJob> {
|
||||
has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?;
|
||||
check_switches(params, &["link", "template"], QUEUE)?;
|
||||
check_numbers(params, &["thumbnail"], QUEUE)?;
|
||||
Ok(QueueJob { params: params.clone(), files: queued_files(params)? })
|
||||
}
|
||||
|
||||
@@ -846,6 +852,8 @@ fn info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// `file.place.info` with `p`, without the session (on the desktop the Place dialog reads its
|
||||
/// files' lines this way off the UI thread).
|
||||
pub fn read_info(p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["link"], "file.place.info")?;
|
||||
check_numbers(p, &["thumbnail"], "file.place.info")?;
|
||||
// A PDF/.ai page linked or not has the same size and art.
|
||||
let mut l = load(p, "file.place.info", None, false)?;
|
||||
let natural = l.natural;
|
||||
|
||||
@@ -108,7 +108,7 @@ pub(in crate::cmd) fn windows_1252(b: u8) -> char {
|
||||
}
|
||||
|
||||
/// Byte `b` of Mac Roman.
|
||||
pub(super) fn mac_roman(b: u8) -> char {
|
||||
pub(in crate::cmd) fn mac_roman(b: u8) -> char {
|
||||
const HIGH: [char; 128] = [
|
||||
'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', //
|
||||
'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', //
|
||||
|
||||
@@ -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.
|
||||
@@ -766,7 +767,7 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let writes = s.grant_writes();
|
||||
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, writes);
|
||||
}
|
||||
@@ -788,7 +789,8 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if changed {
|
||||
s.store_disabled_plugins();
|
||||
}
|
||||
let mut v = describe_installed(®istry::install(plugin));
|
||||
let installed = registry::install(plugin).map_err(err)?;
|
||||
let mut v = describe_installed(&installed);
|
||||
if !unknown.is_empty() {
|
||||
v["unknownCommands"] = json!(unknown);
|
||||
}
|
||||
@@ -887,7 +889,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);
|
||||
@@ -1098,7 +1100,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}",
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}",
|
||||
always,
|
||||
remove
|
||||
),
|
||||
|
||||
@@ -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",
|
||||
@@ -396,6 +397,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"paraStyle.apply",
|
||||
"paraStyle.delete",
|
||||
"paraStyle.duplicate",
|
||||
"paraStyle.edit",
|
||||
"paraStyle.list",
|
||||
"paraStyle.new",
|
||||
"paraStyle.redefine",
|
||||
@@ -484,6 +486,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"select.object.brushStrokes",
|
||||
"select.object.clippingMasks",
|
||||
"select.object.directionHandles",
|
||||
"select.object.notAlignedToPixelGrid",
|
||||
"select.object.pointText",
|
||||
"select.object.slices",
|
||||
"select.object.strayPoints",
|
||||
@@ -578,6 +581,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"symbol.replace",
|
||||
"symbol.selectInstances",
|
||||
"symbol.setCurrent",
|
||||
"symbol.sortByName",
|
||||
"symbol.spray",
|
||||
"symbol.unused",
|
||||
"symbol.update",
|
||||
|
||||
@@ -13,9 +13,7 @@ use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::colorcmds::{NotChanged, Recolor, Scope, left_out};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, check_switches, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param,
|
||||
};
|
||||
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -566,8 +564,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() && group.is_none() {
|
||||
return Err(bad(C, "select artwork to recolour, or give a colour `group`"));
|
||||
}
|
||||
check_switches(p, &["includeImages", "includePatterns"], C)?;
|
||||
let scope = Scope { fill: true, stroke: true, ..Scope::of(p) };
|
||||
let scope =
|
||||
Scope { fill: true, stroke: true, images: switch_or(p, "includeImages", true, C)?, patterns: switch_or(p, "includePatterns", true, C)? };
|
||||
let label = if ids.is_empty() { "Edit Color Group" } else { "Recolor Artwork" };
|
||||
// `model`: keep each colour's model (default), take the new colour's own, or the document's.
|
||||
// A given `model` must be a string; only a missing one means "keep". A row's own `model`
|
||||
|
||||
@@ -111,8 +111,13 @@ pub trait RecoveryStore: Send + Sync {
|
||||
fn announced(&self, _area: &str) -> Option<bool> {
|
||||
None
|
||||
}
|
||||
/// Tidy away area `area` once it holds no copies and nobody holds it (its lock file and folder).
|
||||
/// Tidy away area `area` once it holds no copies (its lock file and folder). The caller holds
|
||||
/// the area until this returns.
|
||||
fn remove_area(&self, _area: &str) {}
|
||||
/// Remove area `area`'s folder if it is empty, after [`RecoveryStore::remove_area`] and after the
|
||||
/// caller let the area go. On some file systems a file that is open is removed only when it is
|
||||
/// closed, so `remove_area` leaves the folder there while the area is held.
|
||||
fn remove_empty_area(&self, _area: &str) {}
|
||||
/// The clock heartbeats are judged by (Unix seconds; `None`: none, so no area counts as gone).
|
||||
fn now(&self) -> Option<i64> {
|
||||
vectorcraft_doc::metadata::now_unix()
|
||||
@@ -295,6 +300,73 @@ impl FolderStore {
|
||||
.filter(|n| Self::plain(n))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Lock area folder `dir`, which was just made. Another app tidies an empty area away
|
||||
/// (`tidy`) by removing its lock file and folder while it holds the lock. So when the folder
|
||||
/// or the lock file is gone by now, or the lock taken is on a lock file the folder no longer
|
||||
/// has, that app had the area: it is [`Lock::Busy`], and the caller tries another one.
|
||||
pub(crate) fn lock_area(dir: &std::path::Path) -> std::result::Result<Lock, String> {
|
||||
if let Err(e) = Self::own_area(dir) {
|
||||
let gone = std::fs::symlink_metadata(dir).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound);
|
||||
return if gone { Ok(Lock::Busy) } else { Err(e) };
|
||||
}
|
||||
let path = dir.join(LOCK_FILE);
|
||||
match std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path) {
|
||||
Ok(file) => Self::take(file, &path),
|
||||
Err(e) => Self::open_failed(e, &path),
|
||||
}
|
||||
}
|
||||
|
||||
/// Opening lock file `path` failed with `e`. When the folder is gone by now, another app had the
|
||||
/// area: it is [`Lock::Busy`]. So it is when the lock file is there but can't be opened: some
|
||||
/// file systems keep a removed file that another app still has open until that app closes it,
|
||||
/// and refuse to open it meanwhile. A lock file that can't be made is an error.
|
||||
pub(crate) fn open_failed(e: std::io::Error, path: &std::path::Path) -> std::result::Result<Lock, String> {
|
||||
match e.kind() {
|
||||
std::io::ErrorKind::NotFound => Ok(Lock::Busy),
|
||||
std::io::ErrorKind::PermissionDenied if std::fs::symlink_metadata(path).is_ok() => Ok(Lock::Busy),
|
||||
_ => Err(format!("{}: {e}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lock `file`, opened as lock file `path`. The lock holds the area only while `path` still
|
||||
/// names that file.
|
||||
pub(crate) fn take(file: std::fs::File, path: &std::path::Path) -> std::result::Result<Lock, String> {
|
||||
match file.try_lock() {
|
||||
Ok(()) if Self::still_named(&file, path) => Ok(Lock::Held(Box::new(file))),
|
||||
Ok(()) | Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy),
|
||||
// The lock file was removed meanwhile, and locking it failed instead.
|
||||
Err(std::fs::TryLockError::Error(_)) if !Self::still_named(&file, path) => Ok(Lock::Busy),
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(format!("{}: {e}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `path` still name `file`? On Unix the two must be the same file (device and inode); on
|
||||
/// Windows they must be the same file (volume serial number and file index); elsewhere `path`
|
||||
/// must exist. When either file can't be read, it does not.
|
||||
fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
match (file.metadata(), std::fs::symlink_metadata(path)) {
|
||||
(Ok(a), Ok(b)) => a.dev() == b.dev() && a.ino() == b.ino(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let opened = file.try_clone().and_then(same_file::Handle::from_file);
|
||||
match (opened, same_file::Handle::from_path(path)) {
|
||||
(Ok(a), Ok(b)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
{
|
||||
let _ = file;
|
||||
std::fs::symlink_metadata(path).is_ok()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -342,29 +414,23 @@ impl RecoveryStore for FolderStore {
|
||||
fn lock(&self, area: &str) -> std::result::Result<Lock, String> {
|
||||
let dir = self.area(area)?;
|
||||
Self::create_area(&dir)?;
|
||||
Self::own_area(&dir)?;
|
||||
let path = dir.join(LOCK_FILE);
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(&path)
|
||||
.map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(Lock::Held(Box::new(file))),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy),
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(format!("{}: {e}", path.display())),
|
||||
}
|
||||
Self::lock_area(&dir)
|
||||
}
|
||||
fn remove_area(&self, area: &str) {
|
||||
// Best effort: whatever is left is tidied at a later launch. A folder that isn't empty
|
||||
// (copies came back meanwhile) stays.
|
||||
// (copies came back meanwhile) stays. The caller still holds the lock here.
|
||||
if let Ok(dir) = self.area(area) {
|
||||
let _ = std::fs::remove_file(dir.join(LOCK_FILE));
|
||||
let _ = std::fs::remove_dir(&dir);
|
||||
}
|
||||
}
|
||||
fn remove_empty_area(&self, area: &str) {
|
||||
// Best effort, as above. An app that made the folder again meanwhile and has not locked it
|
||||
// yet finds it gone and takes another area (`lock_area`); one that has keeps it.
|
||||
if let Ok(dir) = self.area(area) {
|
||||
let _ = std::fs::remove_dir(&dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The area this session keeps its copies in, while it holds it.
|
||||
@@ -527,8 +593,10 @@ pub fn release(s: &mut Session) {
|
||||
for name in store.list().unwrap_or_default().iter().filter(|n| mine(n)) {
|
||||
let _ = store.remove(name);
|
||||
}
|
||||
drop(hold);
|
||||
// Held until it is gone, as in `tidy`.
|
||||
store.remove_area(&area);
|
||||
drop(hold);
|
||||
store.remove_empty_area(&area);
|
||||
}
|
||||
|
||||
/// Let go of this session's area but leave its copies, as a crash would, so the next app started
|
||||
@@ -967,7 +1035,9 @@ fn owner(s: &mut Session, store: &dyn RecoveryStore, area: &str, hold: &mut Vec<
|
||||
}
|
||||
}
|
||||
|
||||
/// Tidy away a gone app's area `area` once no copies are left in it, then let it go (`hold`).
|
||||
/// Tidy away a gone app's area `area` once no copies are left in it, then let it go (`hold`). The
|
||||
/// area is removed while it is still held, so an app taking a new area of that name meanwhile
|
||||
/// finds it held or gone and takes the next name.
|
||||
fn tidy(store: &dyn RecoveryStore, area: &str, hold: Vec<Hold>) {
|
||||
let names = store.list().unwrap_or_default();
|
||||
let mine: Vec<&String> = names.iter().filter(|n| n.split_once('/').is_some_and(|(a, _)| a == area)).collect();
|
||||
@@ -977,8 +1047,9 @@ fn tidy(store: &dyn RecoveryStore, area: &str, hold: Vec<Hold>) {
|
||||
for n in mine {
|
||||
let _ = store.remove(n);
|
||||
}
|
||||
drop(hold);
|
||||
store.remove_area(area);
|
||||
drop(hold);
|
||||
store.remove_empty_area(area);
|
||||
}
|
||||
|
||||
/// The copies of documents open now in this session.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -7,6 +7,7 @@ use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
|
||||
use vectorcraft_tools::builder::is_live_paint;
|
||||
|
||||
use super::object::can_align;
|
||||
use super::wand::{fill_of, stroke_of};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index, ok, str_param,
|
||||
@@ -178,6 +179,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("select.object.openPaths", "Open Paths", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n
|
||||
.path_data()
|
||||
.is_some_and(|p| !p.is_closed()))),
|
||||
cmd!(
|
||||
"select.object.notAlignedToPixelGrid",
|
||||
"Not Aligned to Pixel Grid",
|
||||
["Select", "Object"],
|
||||
None,
|
||||
"{} the paths (not guides) and compound paths whose pixel-aligned property (object.setPixelAligned) is off, looking into groups but not into compound paths → {count}",
|
||||
has_doc,
|
||||
not_pixel_aligned
|
||||
),
|
||||
cmd!(
|
||||
"select.same.graphicStyle",
|
||||
"Graphic Style",
|
||||
@@ -865,3 +875,19 @@ fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result<Value> {
|
||||
// The objects selected, after Lock Guides has left out guide paths.
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
|
||||
/// Select › Object › Not Aligned to Pixel Grid: the objects that can take the pixel-aligned
|
||||
/// property ([`can_align`]) and do not have it. A compound path counts as one object, so the walk
|
||||
/// does not look at the paths inside it.
|
||||
fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let mut ids = vec![];
|
||||
walk_selectable(&st.doc, st.isolation, |n| {
|
||||
if can_align(n) && !n.extras().pixel_aligned {
|
||||
ids.push(n.id);
|
||||
}
|
||||
!matches!(n.kind, NodeKind::Compound { .. })
|
||||
});
|
||||
s.select(|_, sel| sel.set(ids))?;
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@ use vectorcraft_doc::{Appearance, CellAlign, CellVAlign, Document, Node, NodeKin
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::{
|
||||
CommandSpec, EngineError, NodeId, Result, Session, bad, bool_or, cmd, f64_or, f64_req, has_doc, has_selection, id_param, ids_param, index,
|
||||
switch_or, targets,
|
||||
CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, f64_req, has_doc, has_selection, id_param, ids_param, index, number_or, switch_or,
|
||||
targets,
|
||||
};
|
||||
|
||||
/// The most slices one Divide Slices makes.
|
||||
@@ -380,7 +380,8 @@ fn from_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let targets = selected(s)?;
|
||||
let (dx, dy) = (f64_or(p, "dx", 10.0), f64_or(p, "dy", 10.0));
|
||||
let dx = number_or(p, "dx", 10.0, "object.slice.duplicate")?;
|
||||
let dy = number_or(p, "dy", 10.0, "object.slice.duplicate")?;
|
||||
let ids = s.edit("Duplicate Slice", |d, sel| {
|
||||
let mut out = vec![];
|
||||
for id in &targets {
|
||||
@@ -737,7 +738,7 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let slices = p.get("slices").filter(|v| !v.is_null()).cloned().unwrap_or(json!([]));
|
||||
let ids = slice_targets(s, &json!({ "slices": slices }), "object.slice.select")?;
|
||||
let toggle = bool_or(p, "toggle", false);
|
||||
let toggle = switch_or(p, "toggle", false, "object.slice.select")?;
|
||||
s.select(|_, sel| {
|
||||
let mut now = if toggle { sel.slices.clone() } else { vec![] };
|
||||
for id in ids {
|
||||
|
||||
@@ -13,11 +13,12 @@
|
||||
//! to loses its characters' own fill (stroke) when the style has fills (strokes), so the style's
|
||||
//! paint shows instead of the character colour under it.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Appearance, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Appearance, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, Node, NodeId, NodeKind, Shared};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index, object_param, ok, str_param, unique_name};
|
||||
@@ -260,9 +261,14 @@ fn override_chars(n: &mut Node, ap: &Appearance) {
|
||||
}
|
||||
|
||||
/// Give `n` style `g`: its appearance (a group or layer too: its own, above its contents; type its
|
||||
/// characters' colour too with `chars`, Override Character Color) and transparency.
|
||||
fn style_node(n: &mut Node, g: &GraphicStyle, chars: bool) {
|
||||
n.appearance = g.appearance_on(n).into_owned().into();
|
||||
/// characters' colour too with `chars`, Override Character Color) and transparency. Objects that
|
||||
/// take `g`'s appearance as it is share one copy of it, made in `shared` the first time; an object
|
||||
/// whose placed gradients land on its own bounds gets its own.
|
||||
fn style_node(n: &mut Node, g: &GraphicStyle, shared: &mut Option<Shared<Appearance>>, chars: bool) {
|
||||
n.appearance = match g.appearance_on(n) {
|
||||
Cow::Borrowed(ap) => shared.get_or_insert_with(|| Shared::new(ap.clone())).clone(),
|
||||
Cow::Owned(ap) => ap.into(),
|
||||
};
|
||||
if chars {
|
||||
override_chars(n, &g.appearance);
|
||||
}
|
||||
@@ -270,9 +276,9 @@ fn style_node(n: &mut Node, g: &GraphicStyle, chars: bool) {
|
||||
}
|
||||
|
||||
/// Give `id` style `g` ([`style_node`]) and link it.
|
||||
fn apply_style(d: &mut Document, id: NodeId, g: &GraphicStyle, chars: bool) {
|
||||
fn apply_style(d: &mut Document, id: NodeId, g: &GraphicStyle, shared: &mut Option<Shared<Appearance>>, chars: bool) {
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
style_node(n, g, chars);
|
||||
style_node(n, g, shared, chars);
|
||||
n.extras_mut().graphic_style = Some(g.id);
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
@@ -313,7 +319,7 @@ impl Session {
|
||||
/// Color as set): the Graphic Styles panel's previews.
|
||||
pub fn styled(&self, n: &Node, g: &GraphicStyle) -> Node {
|
||||
let mut n = n.clone();
|
||||
style_node(&mut n, g, self.prefs.override_char_color);
|
||||
style_node(&mut n, g, &mut None, self.prefs.override_char_color);
|
||||
n
|
||||
}
|
||||
}
|
||||
@@ -354,8 +360,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
d.graphic_style_id(i);
|
||||
let g = d.graphic_styles[i].clone();
|
||||
let mut shared = None;
|
||||
for id in &ids {
|
||||
apply_style(d, *id, &g, chars);
|
||||
apply_style(d, *id, &g, &mut shared, chars);
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true);
|
||||
}
|
||||
@@ -474,8 +481,9 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) = linked.into_iter().partition(|nid| d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
set_link(d, &edited, None);
|
||||
let g = d.graphic_styles[i].clone();
|
||||
let mut shared = None;
|
||||
for nid in &follow {
|
||||
apply_style(d, *nid, &g, chars);
|
||||
apply_style(d, *nid, &g, &mut shared, chars);
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &follow, (true, true), (true, true), false, true);
|
||||
set_link(d, &[src], Some(id));
|
||||
|
||||
@@ -14,7 +14,9 @@ use vectorcraft_doc::style_libs::{self, STYLE_LIBRARIES, STYLES_EXT, builtin_sty
|
||||
use vectorcraft_doc::{Document, GraphicStyle, PatternDef, StyleLibrary};
|
||||
|
||||
use super::menucmds::squash;
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, names_param, stem};
|
||||
use super::swatchlib::{
|
||||
FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, names_param, shown_id, shown_library_id, stem,
|
||||
};
|
||||
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param, switch_or, text_param, unique_name};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -94,6 +96,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<StyleLibrary>
|
||||
if let Some(found) = s.style_libraries.get(key) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(found) = concealed_library_id(s, key).and_then(|id| s.style_libraries.get(&id)) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(b) = STYLE_LIBRARIES.iter().find(|b| b.id == key) {
|
||||
return Some((builtin_info(b), builtin_style_library(key)?));
|
||||
}
|
||||
@@ -108,20 +113,22 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.style_libraries.rescan();
|
||||
let concealed = concealed_library_ids(s, []);
|
||||
let libs: Vec<Value> = libraries(s)
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len());
|
||||
json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.style_libraries.path(&l.id)})
|
||||
let (id, path) = (shown_id(&concealed, &l.id), s.style_libraries.shown_path(&l.id));
|
||||
json!({"id": id, "name": l.name, "category": l.category, "count": count, "path": path})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.style_libraries.user_dir() }))
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.style_libraries.shown_user_dir() }))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (info, lib) = library_param(s, p, "graphicStyle.library")?;
|
||||
let styles: Vec<Value> = lib.styles.iter().map(super::style::style_json).collect();
|
||||
Ok(json!({"id": info.id, "name": info.name, "category": info.category, "styles": styles}))
|
||||
Ok(json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "styles": styles}))
|
||||
}
|
||||
|
||||
/// Pattern `name` of `lib` in `d`: the document's own when it has the same pattern (under any
|
||||
@@ -192,7 +199,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let doc_name = |lib_name: &str| added.iter().find(|(l, _)| l == lib_name).map_or_else(|| lib_name.to_string(), |(_, n)| n.clone());
|
||||
let mut out = json!({
|
||||
"library": info.id,
|
||||
"library": shown_library_id(s, &info.id),
|
||||
"added": added.iter().map(|(_, n)| n).collect::<Vec<_>>(),
|
||||
"existing": existing.iter().map(|g| &g.name).collect::<Vec<_>>(),
|
||||
});
|
||||
@@ -238,5 +245,5 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The Swatches panel: new, delete and duplicate swatches, colour groups and sorting.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientMethod, GradientStop, Paint, Swatch, SwatchGroup, tint_percent};
|
||||
@@ -222,9 +222,10 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// The `names` list and `name` parameters, without repeats; at least one is required.
|
||||
pub(super) fn names_param(p: &Value, cmd: &str) -> Result<Vec<String>> {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
let mut names: Vec<String> = vec![];
|
||||
for n in str_list(p, "names").into_iter().chain(str_param(p, "name").map(str::to_string)) {
|
||||
if !names.contains(&n) {
|
||||
if seen.insert(n.clone()) {
|
||||
names.push(n);
|
||||
}
|
||||
}
|
||||
@@ -234,17 +235,73 @@ pub(super) fn names_param(p: &Value, cmd: &str) -> Result<Vec<String>> {
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// Take swatches `names` out of the document in that order, as [`Document::remove_swatch`] for
|
||||
/// each name in turn would, in one pass over the swatches: a name takes the first swatch of that
|
||||
/// name still there (ungrouped first, then each colour group's) when `take` accepts it, and
|
||||
/// nothing when `take` refuses it or no swatch has the name.
|
||||
fn take_swatches(d: &mut Document, names: &[String], take: impl Fn(&Swatch) -> bool) -> Vec<Swatch> {
|
||||
let wanted: HashSet<&str> = names.iter().map(String::as_str).collect();
|
||||
// Each wanted name's swatches in lookup order: (list, index, accepted), where list 0 holds the
|
||||
// ungrouped swatches and list g + 1 colour group g's.
|
||||
let mut places: HashMap<&str, VecDeque<(usize, usize, bool)>> = HashMap::new();
|
||||
let lists = std::iter::once(&d.swatches[..]).chain(d.swatch_groups.iter().map(|g| &g.swatches[..]));
|
||||
for (l, list) in lists.enumerate() {
|
||||
for (i, w) in list.iter().enumerate() {
|
||||
if let Some(n) = wanted.get(w.name.as_str()) {
|
||||
places.entry(n).or_default().push_back((l, i, take(w)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut picked: Vec<(usize, usize)> = vec![];
|
||||
for n in names {
|
||||
if let Some(q) = places.get_mut(n.as_str())
|
||||
&& let Some(&(l, i, true)) = q.front()
|
||||
{
|
||||
q.pop_front();
|
||||
picked.push((l, i));
|
||||
}
|
||||
}
|
||||
if picked.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let hit: HashSet<(usize, usize)> = picked.iter().copied().collect();
|
||||
let hit_lists: HashSet<usize> = picked.iter().map(|&(l, _)| l).collect();
|
||||
let mut taken: HashMap<(usize, usize), Swatch> = HashMap::with_capacity(picked.len());
|
||||
let mut split = |l: usize, list: &mut Vec<Swatch>| {
|
||||
for (i, w) in std::mem::take(list).into_iter().enumerate() {
|
||||
if hit.contains(&(l, i)) {
|
||||
taken.insert((l, i), w);
|
||||
} else {
|
||||
list.push(w);
|
||||
}
|
||||
}
|
||||
};
|
||||
// Both lists are copied on write, so each is only written when a swatch leaves it.
|
||||
if hit_lists.contains(&0) {
|
||||
split(0, &mut d.swatches);
|
||||
}
|
||||
if hit_lists.iter().any(|&l| l > 0) {
|
||||
for (g, group) in d.swatch_groups.iter_mut().enumerate() {
|
||||
if hit_lists.contains(&(g + 1)) {
|
||||
split(g + 1, &mut group.swatches);
|
||||
}
|
||||
}
|
||||
}
|
||||
picked.iter().filter_map(|k| taken.remove(k)).collect()
|
||||
}
|
||||
|
||||
fn swatch_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.delete";
|
||||
let names = names_param(p, C)?;
|
||||
check_switches(p, &["unlink"], C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let by_name = swatches_by_name(d);
|
||||
// Global swatches going away (named ones and those in named groups): their links are dropped.
|
||||
let mut global: Vec<String> = vec![];
|
||||
let mut global: HashSet<String> = HashSet::new();
|
||||
for n in &names {
|
||||
let swatches: Vec<&Swatch> = match d.swatch_groups.iter().find(|g| g.name == *n) {
|
||||
Some(g) => g.swatches.iter().collect(),
|
||||
None => vec![d.swatch(n).ok_or_else(|| bad(C, format!("no swatch or colour group `{n}`")))?],
|
||||
None => vec![by_name.get(n.as_str()).copied().ok_or_else(|| bad(C, format!("no swatch or colour group `{n}`")))?],
|
||||
};
|
||||
if swatches.iter().any(|w| w.is_reserved()) {
|
||||
return Err(bad(C, format!("`{n}` can't be deleted")));
|
||||
@@ -258,10 +315,9 @@ fn swatch_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|_: &mut Color, link: &mut Option<String>, _: &mut f32| link.as_ref().is_some_and(|l| global.contains(l)) && link.take().is_some();
|
||||
let colorized_ok = super::paint::check_colorized(d).is_ok();
|
||||
let unlinked = s.edit("Delete Swatch", |d, _| {
|
||||
d.swatch_groups.retain(|g| !names.contains(&g.name));
|
||||
for n in &names {
|
||||
d.remove_swatch(n);
|
||||
}
|
||||
let named: HashSet<&str> = names.iter().map(String::as_str).collect();
|
||||
d.swatch_groups.retain(|g| !named.contains(g.name.as_str()));
|
||||
take_swatches(d, &names, |_| true);
|
||||
let unlinked = map_swatch_links(d, &mut unlink);
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok(unlinked)
|
||||
@@ -347,6 +403,8 @@ fn gradient_key(g: &Gradient) -> Option<GradientKey<'_>> {
|
||||
GradientKind::Linear => 0,
|
||||
GradientKind::Radial => 1,
|
||||
GradientKind::Freeform => 2,
|
||||
GradientKind::Conic => 3,
|
||||
GradientKind::Diamond => 4,
|
||||
};
|
||||
let method = match g.method {
|
||||
GradientMethod::Classic => 0,
|
||||
@@ -419,15 +477,9 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
new.extend(art.into_iter().map(|c| (c, to_global)));
|
||||
}
|
||||
let name = d.free_swatch_name(requested.as_deref().unwrap_or("Color Group"));
|
||||
let mut group = SwatchGroup { name: name.clone(), swatches: vec![] };
|
||||
// Colour groups hold solid colours only.
|
||||
for n in &names {
|
||||
if d.swatch(n).is_some_and(|sw| matches!(sw.paint, Paint::Solid { .. }))
|
||||
&& let Some(sw) = d.remove_swatch(n)
|
||||
{
|
||||
group.swatches.push(sw);
|
||||
}
|
||||
}
|
||||
let swatches = take_swatches(d, &names, |sw| matches!(sw.paint, Paint::Solid { .. }));
|
||||
let mut group = SwatchGroup { name: name.clone(), swatches };
|
||||
// The global swatches made from the art's colours, which its unlinked paints link to.
|
||||
let mut links: Vec<(Color, String)> = vec![];
|
||||
let mut free = d.free_swatch_names();
|
||||
@@ -483,8 +535,9 @@ fn swatch_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
insert_before(&mut d.swatch_groups, items, at.as_deref(), |g| &g.name);
|
||||
return Ok(());
|
||||
}
|
||||
let by_name = swatches_by_name(d);
|
||||
for n in &names {
|
||||
let sw = d.swatch(n).ok_or_else(|| bad(C, format!("no swatch `{n}` (swatches and colour groups move separately)")))?;
|
||||
let sw = by_name.get(n.as_str()).ok_or_else(|| bad(C, format!("no swatch `{n}` (swatches and colour groups move separately)")))?;
|
||||
if sw.is_reserved() {
|
||||
return Err(bad(C, format!("`{n}` can't be moved")));
|
||||
}
|
||||
@@ -503,7 +556,7 @@ fn swatch_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let at = anchor(list(d, dest), to, &names, |w| &w.name);
|
||||
let items: Vec<Swatch> = names.iter().filter_map(|n| d.remove_swatch(n)).collect();
|
||||
let items = take_swatches(d, &names, |_| true);
|
||||
insert_before(list(d, dest), items, at.as_deref(), |w| &w.name);
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -955,8 +1008,9 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.merge";
|
||||
let names = names_param(p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let by_name = swatches_by_name(d);
|
||||
for n in &names {
|
||||
let sw = d.swatch(n).ok_or_else(|| bad(C, format!("no swatch `{n}`")))?;
|
||||
let sw = by_name.get(n.as_str()).ok_or_else(|| bad(C, format!("no swatch `{n}`")))?;
|
||||
if sw.is_reserved() {
|
||||
return Err(bad(C, format!("`{n}` can't be merged")));
|
||||
}
|
||||
@@ -970,9 +1024,10 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let kept = d.swatch(keep).ok_or_else(|| bad(C, format!("no swatch `{keep}`")))?;
|
||||
let (color, link) = (d.linked_color(kept.paint.color().unwrap_or_default(), kept.spot), kept.global.then(|| keep.clone()));
|
||||
let merged_names: HashSet<&str> = merged.iter().map(String::as_str).collect();
|
||||
// Tints keep their tint (of the kept colour).
|
||||
let mut relink = |c: &mut Color, l: &mut Option<String>, t: &mut f32| {
|
||||
if !l.as_ref().is_some_and(|l| merged.contains(l)) {
|
||||
if !l.as_ref().is_some_and(|l| merged_names.contains(l.as_str())) {
|
||||
return false;
|
||||
}
|
||||
*c = color.tinted(*t);
|
||||
@@ -981,9 +1036,7 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let colorized_ok = super::paint::check_colorized(d).is_ok();
|
||||
let relinked = s.edit("Merge Swatches", |d, _| {
|
||||
for n in merged {
|
||||
d.remove_swatch(n);
|
||||
}
|
||||
take_swatches(d, merged, |_| true);
|
||||
let relinked = map_swatch_links(d, &mut relink);
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok(relinked)
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! pattern) into the document; `swatch.library.save` writes the document's ([`palette_io`]).
|
||||
//! `swatch.library.copyToUser` copies a loaded library into the user library folder.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -211,6 +211,22 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
self.extra.iter().find(|e| e.info.id == id).and_then(|e| e.path.as_deref())
|
||||
}
|
||||
|
||||
/// The ids [`Libraries::get`] finds: the User Defined and loaded libraries', and the loaded ids of
|
||||
/// libraries copied into the user library folder.
|
||||
fn ids(&self) -> impl Iterator<Item = String> + '_ {
|
||||
self.extra.iter().map(|e| e.info.id.clone()).chain(self.copied.iter().map(|(loaded, _)| loaded.clone()))
|
||||
}
|
||||
|
||||
/// The file library `id` was read from, when the request being served may read it.
|
||||
pub fn shown_path(&self, id: &str) -> Option<&str> {
|
||||
self.path(id).filter(|p| readable(p))
|
||||
}
|
||||
|
||||
/// The user library folder, when the request being served may read it.
|
||||
pub fn shown_user_dir(&self) -> Option<&str> {
|
||||
self.user_dir().filter(|d| readable(d))
|
||||
}
|
||||
|
||||
/// The User Defined library whose file has the extension of file name `file` and holds `bytes`.
|
||||
fn user_file(&self, file: &str, bytes: &[u8]) -> Option<&Extra<L>> {
|
||||
let ext = extension(file);
|
||||
@@ -281,7 +297,10 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
self.saved_as
|
||||
.insert(format!("user/{file}").to_lowercase(), SavedAs { name: name.to_string(), hash: vectorcraft_doc::links::hash_bytes(bytes) });
|
||||
self.rescan();
|
||||
out["path"] = json!(path);
|
||||
// The folder is the app's own: a confined request sees the file only inside its read roots.
|
||||
if readable(&path) {
|
||||
out["path"] = json!(path);
|
||||
}
|
||||
out["library"] = json!(format!("user/{file}"));
|
||||
} else if let Some(path) = path {
|
||||
write_file(path, bytes)?;
|
||||
@@ -349,6 +368,10 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
.ok_or_else(|| bad(cmd, format!("`{id}` isn't a loaded library")))?;
|
||||
let (file, bytes) = match source.filter(|p| L::EXTS.contains(&extension(p).as_str())) {
|
||||
Some(p) => {
|
||||
// Outside the request's read roots: the error names no path.
|
||||
if !readable(&p) {
|
||||
return Err(bad(cmd, "the library's file is outside the read roots"));
|
||||
}
|
||||
let ext = extension(&p);
|
||||
let base = file_name(&p);
|
||||
// A sandbox copy of an import often lands as tmp….tmp.acb (#2996): store it under the
|
||||
@@ -446,6 +469,72 @@ fn file_name(path: &str) -> String {
|
||||
std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// May the request being served read `path` ([`crate::file_access::check_read`])? Always, without
|
||||
/// roots in force.
|
||||
fn readable(path: &str) -> bool {
|
||||
crate::file_access::check_read(path).is_ok()
|
||||
}
|
||||
|
||||
/// The loaded library ids (`loaded/<path>`) whose file the request being served may not read, each
|
||||
/// with the id a reply shows instead: `loaded/<file name>`, as a library loaded without a path is
|
||||
/// named. The ids are those of the session's swatch, brush, symbol and graphic style libraries, then
|
||||
/// `others` (ids the UI state refers to). When another id already is or shows that id, the next free
|
||||
/// one of `loaded/<file name> (2)`, `(3)` and so on is shown, so that two libraries stay two. The
|
||||
/// session's libraries are numbered first, in the sorted order of their full ids, so a library shows
|
||||
/// the same id whatever `others` holds; then `others`, in the same order. Without roots in force, none.
|
||||
pub fn concealed_library_ids(s: &Session, others: impl IntoIterator<Item = String>) -> Vec<(String, String)> {
|
||||
if crate::file_access::current().is_none() {
|
||||
return vec![];
|
||||
}
|
||||
let session: BTreeSet<String> =
|
||||
s.swatch_libraries.ids().chain(s.brush_libraries.ids()).chain(s.symbol_libraries.ids()).chain(s.style_libraries.ids()).collect();
|
||||
let others: BTreeSet<String> = others.into_iter().filter(|id| !session.contains(id)).collect();
|
||||
let mut hidden = Vec::new();
|
||||
let mut taken = BTreeSet::new();
|
||||
for ids in [session, others] {
|
||||
for id in ids {
|
||||
let name = id.strip_prefix("loaded/").filter(|path| !path.is_empty()).map(|path| (file_name(path), path));
|
||||
match name {
|
||||
Some((name, path)) if name != path && !readable(path) => hidden.push((id, name)),
|
||||
_ => {
|
||||
taken.insert(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hidden
|
||||
.into_iter()
|
||||
.map(|(id, name)| {
|
||||
let mut shown = format!("loaded/{name}");
|
||||
let mut n = 2;
|
||||
while taken.contains(&shown) {
|
||||
shown = format!("loaded/{name} ({n})");
|
||||
n += 1;
|
||||
}
|
||||
taken.insert(shown.clone());
|
||||
(id, shown)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The id a reply shows for library `id`, given the [`concealed_library_ids`] in force.
|
||||
pub(crate) fn shown_id(concealed: &[(String, String)], id: &str) -> String {
|
||||
concealed.iter().find(|(own, _)| own == id).map_or_else(|| id.to_string(), |(_, shown)| shown.clone())
|
||||
}
|
||||
|
||||
/// The id a reply shows for library `id` ([`concealed_library_ids`]).
|
||||
pub(crate) fn shown_library_id(s: &Session, id: &str) -> String {
|
||||
shown_id(&concealed_library_ids(s, []), id)
|
||||
}
|
||||
|
||||
/// The library id behind `key` when `key` is the id a reply shows for a concealed loaded library.
|
||||
pub(crate) fn concealed_library_id(s: &Session, key: &str) -> Option<String> {
|
||||
if !key.starts_with("loaded/") {
|
||||
return None;
|
||||
}
|
||||
concealed_library_ids(s, []).into_iter().find(|(_, shown)| shown == key).map(|(own, _)| own)
|
||||
}
|
||||
|
||||
/// `name` without its extension.
|
||||
pub(crate) fn stem(name: &str) -> &str {
|
||||
name.rsplit_once('.').map_or(name, |(s, _)| s)
|
||||
@@ -479,6 +568,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<SwatchLibrary
|
||||
if let Some(found) = s.swatch_libraries.get(key) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(found) = concealed_library_id(s, key).and_then(|id| s.swatch_libraries.get(&id)) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(b) = builtins().find(|(_, b)| b.id == key) {
|
||||
return Some((builtin_info(b), builtin_library(key)?));
|
||||
}
|
||||
@@ -556,14 +648,16 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.swatch_libraries.rescan();
|
||||
let concealed = concealed_library_ids(s, []);
|
||||
let libs: Vec<Value> = libraries(s)
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len());
|
||||
json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.swatch_libraries.path(&l.id)})
|
||||
let (id, path) = (shown_id(&concealed, &l.id), s.swatch_libraries.shown_path(&l.id));
|
||||
json!({"id": id, "name": l.name, "category": l.category, "count": count, "path": path})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.swatch_libraries.user_dir() }))
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.swatch_libraries.shown_user_dir() }))
|
||||
}
|
||||
|
||||
/// The document's swatches `names` (swatches or colour groups; empty: all) as a library named
|
||||
@@ -619,7 +713,7 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
document_library(&loaded.doc, &[], stem(file).to_string(), C)
|
||||
}
|
||||
})?;
|
||||
Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -629,7 +723,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let groups: Vec<Value> =
|
||||
lib.groups.iter().map(|g| json!({"name": g.name, "swatches": g.swatches.iter().map(|w| &w.name).collect::<Vec<_>>()})).collect();
|
||||
Ok(
|
||||
json!({"id": info.id, "name": info.name, "category": info.category, "swatches": ungrouped.chain(grouped).collect::<Vec<_>>(), "groups": groups}),
|
||||
json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "swatches": ungrouped.chain(grouped).collect::<Vec<_>>(), "groups": groups}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -652,7 +746,7 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"user" => (info, lib, false),
|
||||
_ => return Err(bad(C, format!("`{}` is built in and always listed", info.name))),
|
||||
};
|
||||
let path = s.swatch_libraries.path(&info.id);
|
||||
let path = s.swatch_libraries.shown_path(&info.id);
|
||||
Ok(json!({"library": info.id, "name": info.name, "count": lib.len(), "path": path, "copied": copied}))
|
||||
}
|
||||
|
||||
@@ -792,7 +886,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?
|
||||
};
|
||||
let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::<Vec<_>>();
|
||||
let mut out = json!({"library": info.id, "added": names(&added), "existing": names(&existing)});
|
||||
let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)});
|
||||
if let (Some(cmd), Some((_, first))) = (apply, picked.first()) {
|
||||
let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone());
|
||||
s.execute(cmd, &json!({"swatch": name, "focus": focus}))?;
|
||||
|
||||
@@ -19,7 +19,7 @@ use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_nat
|
||||
use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::swatch::str_list;
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, stem};
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, shown_id, shown_library_id, stem};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param};
|
||||
|
||||
/// The extension of saved symbol libraries: native documents.
|
||||
@@ -386,6 +386,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<SymbolLibrary
|
||||
if let Some(found) = s.symbol_libraries.get(key) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(found) = concealed_library_id(s, key).and_then(|id| s.symbol_libraries.get(&id)) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(b) = BUILTIN.iter().find(|b| b.id == key) {
|
||||
return Some((builtin_info(b), builtin_library(key)?));
|
||||
}
|
||||
@@ -400,14 +403,16 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.symbol_libraries.rescan();
|
||||
let concealed = concealed_library_ids(s, []);
|
||||
let libs: Vec<Value> = libraries(s)
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len());
|
||||
json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.symbol_libraries.path(&l.id)})
|
||||
let (id, path) = (shown_id(&concealed, &l.id), s.symbol_libraries.shown_path(&l.id));
|
||||
json!({"id": id, "name": l.name, "category": l.category, "count": count, "path": path})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.symbol_libraries.user_dir() }))
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.symbol_libraries.shown_user_dir() }))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -421,7 +426,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
json!({"name": sym.name, "size": [w, h], "registration": d.symbol_registration(&sym.name).0, "exportType": d.symbol_export_type(&sym.name).id()})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"id": info.id, "name": info.name, "category": info.category, "symbols": symbols}))
|
||||
Ok(json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "symbols": symbols}))
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -456,7 +461,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
|
||||
let at = if place { Some(Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?)) } else { None };
|
||||
let parent = if place { st.target_parent()? } else { None };
|
||||
let mut out = json!({ "library": info.id });
|
||||
let mut out = json!({ "library": shown_library_id(s, &info.id) });
|
||||
if imported.added > 0 || place {
|
||||
let placed = s.edit("Add to Symbols", |d, sel| {
|
||||
let imported = clip.import_into(d, &choices, false)?;
|
||||
@@ -512,7 +517,7 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
SymbolLibrary::from_document(&loaded.doc, &[], stem(file).to_string()).map_err(|e| bad(C, e))
|
||||
})?;
|
||||
Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area / Path Type",
|
||||
[],
|
||||
None,
|
||||
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText, fitMinPercent? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}",
|
||||
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}",
|
||||
has_doc,
|
||||
create_in_path
|
||||
),
|
||||
@@ -1637,7 +1637,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
super::create::new_type_alignment(s, p, C, &mut t)?;
|
||||
if !on_path {
|
||||
t.area.fit = super::create::new_area_fit(s, p, C)?;
|
||||
super::create::new_area_fit(s, p, C, &mut t)?;
|
||||
}
|
||||
t.system_layout = s.doc()?.doc.setup.system_layout;
|
||||
if bool_or(p, "placeholder", false) {
|
||||
|
||||
@@ -143,7 +143,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|s, p| edit_style(s, p, Kind::Char),
|
||||
true,
|
||||
));
|
||||
v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph", ""));
|
||||
v.extend(style_cmds!(
|
||||
Kind::Para,
|
||||
"paraStyle",
|
||||
"Paragraph Styles",
|
||||
"Paragraph",
|
||||
"; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt"
|
||||
));
|
||||
v.push(spec(
|
||||
"paraStyle.edit",
|
||||
"Edit Paragraph Style",
|
||||
&[],
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt",
|
||||
|s, p| edit_style(s, p, Kind::Para),
|
||||
true,
|
||||
));
|
||||
v.push(spec("textStyle.loadAll", "Load All Styles…", &["Window", "Type"], LOAD_PARAMS, |s, p| load(s, p, &[Kind::Char, Kind::Para]), true));
|
||||
v
|
||||
}
|
||||
@@ -554,7 +568,11 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
char_attrs(&st)
|
||||
}
|
||||
Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), m, &c)?),
|
||||
Kind::Para => {
|
||||
let st = with_attrs(&ParaStyle::default(), m, &c)?;
|
||||
para_ranges(&st, m, kept, &c)?;
|
||||
para_attrs(&st)
|
||||
}
|
||||
};
|
||||
Ok(Some(m.keys().filter_map(|k| full.get(k).map(|v| (k.clone(), v.clone()))).collect()))
|
||||
}
|
||||
@@ -562,6 +580,82 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of a paragraph style's indents, space before and space after, and Hyphenation Zone (pt),
|
||||
/// as `text.setFormat` keeps them.
|
||||
const PARA_DISTANCE: f64 = 1296.0;
|
||||
|
||||
/// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the
|
||||
/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each
|
||||
/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as
|
||||
/// `attrs` gives them) and the position of each tab stop. A value `kept` has is not checked.
|
||||
fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
|
||||
let within = |key: &str, value: f64, lo: f64, hi: f64| {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
};
|
||||
let changed = |key: &str| attrs.contains_key(key) && kept.and_then(|k| k.get(key)) != attrs.get(key);
|
||||
let nested_changed = |key: &str, field: &str| {
|
||||
changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field))
|
||||
};
|
||||
for (key, value) in [
|
||||
("left_indent", st.left_indent),
|
||||
("right_indent", st.right_indent),
|
||||
("first_line_indent", st.first_line_indent),
|
||||
("space_before", st.space_before),
|
||||
("space_after", st.space_after),
|
||||
] {
|
||||
if changed(key) {
|
||||
within(key, value, -PARA_DISTANCE, PARA_DISTANCE)?;
|
||||
}
|
||||
}
|
||||
let h = &st.hyphenation;
|
||||
for (field, value, lo, hi) in [
|
||||
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
|
||||
("after_first", f64::from(h.after_first), 1.0, 15.0),
|
||||
("before_last", f64::from(h.before_last), 1.0, 15.0),
|
||||
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
|
||||
("zone", h.zone, 0.0, PARA_DISTANCE),
|
||||
] {
|
||||
if nested_changed("hyphenation", field) {
|
||||
within(&format!("hyphenation.{field}"), value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
// Read as given: a paragraph's attributes keep justification options in range as they load.
|
||||
if let Some(given) = attrs.get("justification").filter(|_| changed("justification")) {
|
||||
let j: vectorcraft_doc::JustificationOptions = serde_json::from_value(given.clone()).map_err(|e| bad(c, e.to_string()))?;
|
||||
for (field, values, (lo, hi)) in [
|
||||
("word_spacing", j.word_spacing, vectorcraft_doc::JustificationOptions::WORD_SPACING),
|
||||
("letter_spacing", j.letter_spacing, vectorcraft_doc::JustificationOptions::LETTER_SPACING),
|
||||
("glyph_scaling", j.glyph_scaling, vectorcraft_doc::JustificationOptions::GLYPH_SCALING),
|
||||
] {
|
||||
if !nested_changed("justification", field) {
|
||||
continue;
|
||||
}
|
||||
let name = format!("justification.{field}");
|
||||
for value in values {
|
||||
within(&name, value, lo, hi)?;
|
||||
}
|
||||
if !(values[0] <= values[1] && values[1] <= values[2]) {
|
||||
return Err(bad(c, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
|
||||
}
|
||||
}
|
||||
if nested_changed("justification", "auto_leading") {
|
||||
let (lo, hi) = vectorcraft_doc::JustificationOptions::AUTO_LEADING;
|
||||
within("justification.auto_leading", j.auto_leading, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if changed("tabs") {
|
||||
let kept_tabs: Vec<f64> = kept
|
||||
.and_then(|k| k.get("tabs"))
|
||||
.and_then(Value::as_array)
|
||||
.map(|stops| stops.iter().filter_map(|s| s.get("position").and_then(Value::as_f64)).collect())
|
||||
.unwrap_or_default();
|
||||
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(&stop.position)) {
|
||||
within("tabs.position", stop.position, 0.0, 100_000.0)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check a character style's `fill` or `stroke` (`key`): each solid color and gradient stop has a
|
||||
/// tint from 0 to 1, and a link to a global swatch of `d`, whose color at that tint it takes.
|
||||
fn style_paint(d: &Document, paint: &mut vectorcraft_color::Paint, key: &str, c: &str) -> Result<()> {
|
||||
|
||||
@@ -1585,3 +1585,147 @@ fn para_style_range_capture_samples_start_paragraph() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn paras(s: &Session, id: u64) -> Vec<ParaStyle> {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.paragraph_styles(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `paraStyle.edit` renames a paragraph style and replaces its attributes in one undo step: every
|
||||
/// paragraph using it takes the new values, a paragraph's local override stays, and the saved file
|
||||
/// keeps the sparse definition.
|
||||
#[test]
|
||||
fn paragraph_style_options_edit_applies_to_users_and_is_one_saved_undo_step() {
|
||||
use vectorcraft_doc::Composer;
|
||||
let (mut s, id) = session_with_text("One\nTwo\nThree");
|
||||
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"left_indent": 6.0, "composer": "everyLine", "tabs": [{"position": 36.0}]}}))
|
||||
.unwrap();
|
||||
s.execute("paraStyle.apply", &json!({"name": "Body", "id": id, "start": 0, "end": 7})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"id": id, "start": 4, "end": 4, "leftIndent": 20.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let attrs = json!({"left_indent": 12.0, "composer": "singleLine", "tabs": [{"position": 36.0}],
|
||||
"hyphenation": {"words_longer_than": 8}, "justification": {"word_spacing": [70.0, 90.0, 120.0]}});
|
||||
s.execute("paraStyle.edit", &json!({"name": "Body", "to": "Text", "attrs": attrs})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let p = paras(&s, id);
|
||||
assert_eq!(
|
||||
p.iter().map(|p| (p.style_name.as_deref(), p.left_indent, p.composer)).collect::<Vec<_>>(),
|
||||
[(Some("Text"), 12.0, Composer::SingleLine), (Some("Text"), 20.0, Composer::SingleLine), (None, 0.0, Composer::EveryLine)]
|
||||
);
|
||||
assert_eq!(p[0].hyphenation.words_longer_than, 8);
|
||||
assert_eq!(p[1].justification.word_spacing, [70.0, 90.0, 120.0]);
|
||||
let def = s.doc().unwrap().doc.para_styles.iter().find(|d| d.name == "Text").unwrap().attrs.clone();
|
||||
let mut keys: Vec<&str> = def.keys().map(String::as_str).collect();
|
||||
keys.sort_unstable();
|
||||
assert_eq!(keys, ["composer", "hyphenation", "justification", "left_indent", "tabs"]);
|
||||
let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
assert_eq!(saved.para_styles.iter().find(|d| d.name == "Text").unwrap().attrs, def);
|
||||
let changed = s.doc().unwrap().doc.clone();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, changed);
|
||||
// The Normal style, an empty or a taken name and an unknown style are errors.
|
||||
s.execute("paraStyle.new", &json!({"name": "Other"})).unwrap();
|
||||
for (params, why) in [
|
||||
(json!({"name": "Text", "to": " ", "attrs": {}}), "give the style a name"),
|
||||
(json!({"name": "Text", "to": "Other", "attrs": {}}), "already exists"),
|
||||
(json!({"name": "Missing", "to": "Missing", "attrs": {}}), "no style `Missing`"),
|
||||
(json!({"name": NORMAL_PARA, "to": NORMAL_PARA, "attrs": {}}), "can't be edited"),
|
||||
] {
|
||||
let error = s.execute("paraStyle.edit", ¶ms).unwrap_err().to_string();
|
||||
assert!(error.contains(why), "{params}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A changed paragraph attribute outside the range `text.setFormat` keeps it to is an error for
|
||||
/// `paraStyle.edit`, `paraStyle.setAttrs` and `paraStyle.new`, with no change to the document; the
|
||||
/// ends of each range are accepted, and an out-of-range value the style already has can be kept.
|
||||
#[test]
|
||||
fn paragraph_style_attributes_are_checked_before_a_definition_changes() {
|
||||
let (mut s, _) = session_with_text("Text");
|
||||
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"left_indent": 6.0}})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for (attrs, key) in [
|
||||
(json!({"left_indent": -1296.1}), "left_indent"),
|
||||
(json!({"right_indent": 1296.1}), "right_indent"),
|
||||
(json!({"first_line_indent": 1e300}), "first_line_indent"),
|
||||
(json!({"space_before": 1296.1}), "space_before"),
|
||||
(json!({"space_after": -1296.1}), "space_after"),
|
||||
(json!({"hyphenation": {"words_longer_than": 0}}), "hyphenation.words_longer_than"),
|
||||
(json!({"hyphenation": {"words_longer_than": 4000000000_u64}}), "hyphenation.words_longer_than"),
|
||||
(json!({"hyphenation": {"after_first": 16}}), "hyphenation.after_first"),
|
||||
(json!({"hyphenation": {"before_last": 0}}), "hyphenation.before_last"),
|
||||
(json!({"hyphenation": {"hyphen_limit": 26}}), "hyphenation.hyphen_limit"),
|
||||
(json!({"hyphenation": {"zone": -1.0}}), "hyphenation.zone"),
|
||||
(json!({"hyphenation": {"zone": 1296.1}}), "hyphenation.zone"),
|
||||
(json!({"justification": {"word_spacing": [80.0, 100.0, 1000.1]}}), "justification.word_spacing"),
|
||||
(json!({"justification": {"word_spacing": [120.0, 100.0, 133.0]}}), "justification.word_spacing"),
|
||||
(json!({"justification": {"letter_spacing": [-100.1, 0.0, 0.0]}}), "justification.letter_spacing"),
|
||||
(json!({"justification": {"letter_spacing": [0.0, 10.0, 5.0]}}), "justification.letter_spacing"),
|
||||
(json!({"justification": {"glyph_scaling": [49.0, 100.0, 100.0]}}), "justification.glyph_scaling"),
|
||||
(json!({"justification": {"auto_leading": 500.1}}), "justification.auto_leading"),
|
||||
(json!({"tabs": [{"position": 100000.1}]}), "tabs.position"),
|
||||
(json!({"tabs": [{"position": -1.0}]}), "tabs.position"),
|
||||
] {
|
||||
for cmd in ["paraStyle.edit", "paraStyle.setAttrs", "paraStyle.new"] {
|
||||
let params = match cmd {
|
||||
"paraStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": attrs}),
|
||||
"paraStyle.new" => json!({"name": "Other", "attrs": attrs}),
|
||||
_ => json!({"name": "Body", "attrs": attrs}),
|
||||
};
|
||||
let error = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
assert!(error.contains(&format!("`{key}`")), "{cmd} {attrs}: {error}");
|
||||
}
|
||||
}
|
||||
// Malformed values are errors too.
|
||||
for attrs in [json!({"hyphenation": {"words_longer_than": -1}}), json!({"justification": {"word_spacing": [1.0, 2.0]}}), json!({"tabs": 3})] {
|
||||
assert!(s.execute("paraStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": attrs})).is_err(), "{attrs}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
|
||||
let ends = json!({
|
||||
"left_indent": -1296.0, "right_indent": 1296.0, "first_line_indent": 0.0, "space_before": 1296.0, "space_after": -1296.0,
|
||||
"hyphenation": {"words_longer_than": 25, "after_first": 1, "before_last": 15, "hyphen_limit": 0, "zone": 1296.0},
|
||||
"justification": {"word_spacing": [0.0, 0.0, 1000.0], "letter_spacing": [-100.0, 0.0, 500.0], "glyph_scaling": [50.0, 100.0, 200.0], "auto_leading": 500.0},
|
||||
"tabs": [{"position": 0.0}, {"position": 100000.0}]
|
||||
});
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": ends})).unwrap();
|
||||
// A style that already holds a value out of range (one read from a file) can be renamed with it.
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.para_styles.iter_mut().find(|d| d.name == "Body").unwrap().attrs.insert("left_indent".into(), json!(2000.0));
|
||||
s.execute("paraStyle.edit", &json!({"name": "Body", "to": "Renamed", "attrs": {"left_indent": 2000.0}})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.para_styles.iter().any(|d| d.name == "Renamed"));
|
||||
// Such a Hyphenation, Justification or tab value is kept while another option of its group changes,
|
||||
// and a changed option is still checked.
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let held = json!({
|
||||
"hyphenation": {"words_longer_than": 40, "after_first": 2},
|
||||
"justification": {"letter_spacing": [0.0, 0.0, 600.0], "auto_leading": 120.0},
|
||||
"tabs": [{"position": 200000.0}]
|
||||
});
|
||||
let attrs = &mut doc.para_styles.iter_mut().find(|d| d.name == "Renamed").unwrap().attrs;
|
||||
attrs.extend(held.as_object().unwrap().clone());
|
||||
let edited = json!({
|
||||
"hyphenation": {"words_longer_than": 40, "after_first": 3},
|
||||
"justification": {"letter_spacing": [0.0, 0.0, 600.0], "auto_leading": 150.0},
|
||||
"tabs": [{"position": 200000.0}, {"position": 72.0}]
|
||||
});
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Renamed", "attrs": edited})).unwrap();
|
||||
let def = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|d| d.name == "Renamed").unwrap().attrs.clone();
|
||||
assert_eq!(def(&s)["hyphenation"]["after_first"], json!(3));
|
||||
assert_eq!(def(&s)["justification"]["auto_leading"], json!(150.0));
|
||||
for (attrs, key) in [
|
||||
(json!({"hyphenation": {"words_longer_than": 40, "after_first": 16}}), "hyphenation.after_first"),
|
||||
(json!({"justification": {"auto_leading": 501.0}}), "justification.auto_leading"),
|
||||
(json!({"tabs": [{"position": 200000.0}, {"position": 72.0}, {"position": 100001.0}]}), "tabs.position"),
|
||||
] {
|
||||
let error = s.execute("paraStyle.setAttrs", &json!({"name": "Renamed", "attrs": attrs})).unwrap_err().to_string();
|
||||
assert!(error.contains(&format!("`{key}`")), "{attrs}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area Type Options…",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
has_selection,
|
||||
area_options
|
||||
),
|
||||
@@ -304,11 +304,13 @@ fn ruby(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// Recompute the layout caches (bounds and baselines) after a text edit. Every engine text edit ends here (typing
|
||||
/// through `text.editRange` too), inside its `Session::edit`, so this is where Auto Size area type
|
||||
/// ([`vectorcraft_doc::AreaFit::AutoHeight`]) fits its frame to the text: part of the same undo
|
||||
/// step as the edit.
|
||||
/// ([`vectorcraft_doc::AreaFit::AutoHeight`]) fits its frame to the text, and Dynamic Text's Block
|
||||
/// (`dynamic_text` on area type, [`block::block_fit`]) sizes each line to the frame: part of the
|
||||
/// same undo step as the edit.
|
||||
pub(crate) fn refresh_bounds(t: &mut TextObject) {
|
||||
// Edits that changed the paragraph count keep one paragraph style per paragraph.
|
||||
t.normalize_paras();
|
||||
block::block_fit(t);
|
||||
auto_height(t);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
t.cached_bounds = Some(lay.bounds);
|
||||
@@ -320,6 +322,7 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) {
|
||||
/// ([`vectorcraft_text::take_kept_layout`]) instead of laying the object out again.
|
||||
pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) {
|
||||
t.normalize_paras();
|
||||
block::block_fit(t);
|
||||
auto_height(t);
|
||||
let stamp = vectorcraft_text::LayoutStamp::now();
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
@@ -1026,7 +1029,7 @@ pub(crate) fn reshape_area_with(t: &mut TextObject, f: impl FnOnce(&mut TextObje
|
||||
}
|
||||
|
||||
/// Area type's text, if `n` is area type.
|
||||
fn area_text(n: Option<&Node>) -> Option<&TextObject> {
|
||||
pub(crate) fn area_text(n: Option<&Node>) -> Option<&TextObject> {
|
||||
match n.map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) => Some(t),
|
||||
_ => None,
|
||||
@@ -1059,10 +1062,15 @@ fn size_area(t: &mut TextObject, w: Option<f64>, h: Option<f64>) -> bool {
|
||||
reshape_area_with(t, |t| t.transform_area(a))
|
||||
}
|
||||
|
||||
/// The fit `p` asks for (`fit`: none|autoHeight|shrinkText or `{"shrinkText": {"minPercent"}}`,
|
||||
/// `fitMinPercent`), starting from `cur`. None when `p` sets neither (or only `fitMinPercent`
|
||||
/// while the fit isn't Shrink Text).
|
||||
pub(crate) fn fit_param(p: &Value, cur: AreaFit, c: &str) -> Result<Option<AreaFit>> {
|
||||
/// A fit `p` asks for: the Area Type Options fit, and whether Dynamic Text's Block
|
||||
/// ([`TextObject::dynamic_text`]) is on. Block's fit is [`AreaFit::None`]: it replaces Auto Size
|
||||
/// and Shrink Text to Fit.
|
||||
pub(crate) type FitChoice = (AreaFit, bool);
|
||||
|
||||
/// The fit `p` asks for (`fit`: none|autoHeight|shrinkText|block or `{"shrinkText": {"minPercent"}}`,
|
||||
/// `fitMinPercent`), starting from `cur` (`block`: Block is on). None when `p` sets neither (or only
|
||||
/// `fitMinPercent` while the fit isn't Shrink Text).
|
||||
pub(crate) fn fit_param(p: &Value, cur: AreaFit, block: bool, c: &str) -> Result<Option<FitChoice>> {
|
||||
check_numbers(p, &["fitMinPercent"], c)?;
|
||||
let min = p.get("fitMinPercent").and_then(Value::as_f64);
|
||||
let cur_min = match cur {
|
||||
@@ -1071,21 +1079,48 @@ pub(crate) fn fit_param(p: &Value, cur: AreaFit, c: &str) -> Result<Option<AreaF
|
||||
};
|
||||
let fit = match p.get("fit") {
|
||||
None | Some(Value::Null) => match (cur, min) {
|
||||
(AreaFit::ShrinkText { .. }, Some(m)) => AreaFit::ShrinkText { min_percent: m },
|
||||
(AreaFit::ShrinkText { .. }, Some(m)) if !block => AreaFit::ShrinkText { min_percent: m },
|
||||
_ => return Ok(None),
|
||||
},
|
||||
Some(Value::String(id)) if is_block_id(id) => return Ok(Some((AreaFit::None, true))),
|
||||
Some(Value::String(id)) => {
|
||||
AreaFit::parse(id, min.or(cur_min)).ok_or_else(|| bad(c, format!("fit must be none|autoHeight|shrinkText, got {id}")))?
|
||||
AreaFit::parse(id, min.or(cur_min)).ok_or_else(|| bad(c, format!("fit must be none|autoHeight|shrinkText|block, got {id}")))?
|
||||
}
|
||||
Some(v) => match serde_json::from_value::<AreaFit>(v.clone()).map_err(|e| bad(c, format!("bad fit: {e}")))? {
|
||||
AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: min.unwrap_or(min_percent) },
|
||||
f => f,
|
||||
},
|
||||
};
|
||||
Ok(Some(match fit {
|
||||
AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: AreaFit::clamp_percent(min_percent) },
|
||||
f => f,
|
||||
}))
|
||||
Ok(Some((
|
||||
match fit {
|
||||
AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: AreaFit::clamp_percent(min_percent) },
|
||||
f => f,
|
||||
},
|
||||
false,
|
||||
)))
|
||||
}
|
||||
|
||||
/// Whether a `fit` id names Dynamic Text's Block (case, spaces, dashes and underscores ignored).
|
||||
fn is_block_id(id: &str) -> bool {
|
||||
matches!(id.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str(), "block" | "dynamictext")
|
||||
}
|
||||
|
||||
/// The `fit` id area type reports: `block` while Dynamic Text's Block is on, else its fit's.
|
||||
pub(crate) fn fit_id(t: &TextObject) -> &'static str {
|
||||
if t.dynamic_text { "block" } else { t.area.fit.id() }
|
||||
}
|
||||
|
||||
/// Dynamic Text's Block gaps `p` gives: `wordGap` (% of a word space, 0..1000) and `lineGap` (pt,
|
||||
/// -1296..1296). A value that is not a number, or is outside its range, is an error.
|
||||
pub(crate) fn block_gaps(p: &Value, c: &str) -> Result<(Option<f64>, Option<f64>)> {
|
||||
let gap = |key: &str, (lo, hi): (f64, f64)| -> Result<Option<f64>> {
|
||||
match number_given(p, key, c)? {
|
||||
Some(v) if !(v.is_finite() && (lo..=hi).contains(&v)) => Err(bad(c, format!("`{key}` must be from {lo} to {hi}, not {v}"))),
|
||||
v => Ok(v),
|
||||
}
|
||||
};
|
||||
use vectorcraft_doc::AreaOptions as O;
|
||||
Ok((gap("wordGap", O::WORD_GAP)?, gap("lineGap", O::LINE_GAP)?))
|
||||
}
|
||||
|
||||
/// Area type's options as `text.areaOptions` reports them: the Area Type Options with `fit` as
|
||||
@@ -1095,7 +1130,7 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> {
|
||||
let mut v = serde_json::to_value(&t.area).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("fit".into(), json!(t.area.fit.id()));
|
||||
o.insert("fit".into(), json!(fit_id(t)));
|
||||
o.insert("flow".into(), json!(t.area.flow));
|
||||
// The gutter between rows, the gutter's when the rows have none of their own.
|
||||
o.insert("rowGutter".into(), json!(t.area.row_gutter.unwrap_or(t.area.gutter)));
|
||||
@@ -1104,6 +1139,9 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> {
|
||||
_ => AreaFit::DEFAULT_MIN_PERCENT,
|
||||
};
|
||||
o.insert("fitMinPercent".into(), json!(min));
|
||||
let (word_gap, line_gap) = t.area.block_gaps();
|
||||
o.insert("wordGap".into(), json!(word_gap));
|
||||
o.insert("lineGap".into(), json!(line_gap));
|
||||
if let Some((w, h, _)) = area_size(t) {
|
||||
o.insert("width".into(), json!(w));
|
||||
o.insert("height".into(), json!(h));
|
||||
@@ -1132,8 +1170,9 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Checked once up front (its errors don't depend on the frame); each frame resolves `fit`
|
||||
// against its own setting below.
|
||||
let cur = area_text(s.doc()?.doc.node(first)).map(|t| t.area.clone()).unwrap_or_default();
|
||||
fit_param(p, cur.fit, C)?;
|
||||
let fit_given = p.get("fit").is_some_and(|v| !v.is_null()) || p.get("fitMinPercent").is_some_and(|v| !v.is_null());
|
||||
fit_param(p, cur.fit, false, C)?;
|
||||
let (word_gap, line_gap) = block_gaps(p, C)?;
|
||||
let fit_given = ["fit", "fitMinPercent", "wordGap", "lineGap"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
|
||||
let size = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).map(|x| x.clamp(1.0, 100_000.0));
|
||||
let (w, h) = (size("width"), size("height"));
|
||||
let given: Vec<(&String, &Value)> = p.as_object().into_iter().flatten().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())).collect();
|
||||
@@ -1142,7 +1181,7 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Each area type takes the options given over its own (#3759): setting one option on several
|
||||
// frames leaves their other options as they were.
|
||||
let merged = |own: &vectorcraft_doc::AreaOptions| -> Result<vectorcraft_doc::AreaOptions> {
|
||||
let merged = |own: &vectorcraft_doc::AreaOptions, block: bool| -> Result<(vectorcraft_doc::AreaOptions, bool)> {
|
||||
let mut v = serde_json::to_value(own).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
for (k, val) in &given {
|
||||
@@ -1162,17 +1201,29 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
opts.inset = finite(opts.inset).clamp(0.0, 10_000.0);
|
||||
opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0);
|
||||
// Each frame's fit from its own (`fitMinPercent` alone changes only Shrink Text frames).
|
||||
opts.fit = fit_param(p, own.fit, C)?.unwrap_or(own.fit);
|
||||
Ok(opts)
|
||||
let (fit, block) = fit_param(p, own.fit, block, C)?.unwrap_or((own.fit, block));
|
||||
opts.fit = fit;
|
||||
opts.word_gap = word_gap.unwrap_or(own.word_gap);
|
||||
opts.line_gap = line_gap.unwrap_or(own.line_gap);
|
||||
Ok((opts, block))
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let planned: Vec<(NodeId, vectorcraft_doc::AreaOptions)> = ids
|
||||
let planned: Vec<(NodeId, (vectorcraft_doc::AreaOptions, bool))> = ids
|
||||
.iter()
|
||||
.filter_map(|id| area_text(d.node(*id)).map(|t| (*id, &t.area)))
|
||||
.map(|(id, own)| merged(own).map(|o| (id, o)))
|
||||
.filter_map(|id| area_text(d.node(*id)).map(|t| (*id, t)))
|
||||
.map(|(id, t)| merged(&t.area, t.dynamic_text).map(|o| (id, o)))
|
||||
.collect::<Result<_>>()?;
|
||||
let apply = |t: &mut TextObject, opts: &vectorcraft_doc::AreaOptions| {
|
||||
// Dynamic Text's Block is refused for threaded frames, as `type.dynamicText` refuses it.
|
||||
let frames: Vec<String> =
|
||||
planned.iter().filter(|(id, (_, block))| *block && !super::threads::story_of(d, *id).is_empty()).map(|(id, _)| id.0.to_string()).collect();
|
||||
if !frames.is_empty() {
|
||||
let frames = frames.join(", ");
|
||||
return Err(bad(C, format!("area type in a thread cannot use Dynamic Text: {frames}")));
|
||||
}
|
||||
let apply = |t: &mut TextObject, (opts, block): &(vectorcraft_doc::AreaOptions, bool)| {
|
||||
t.area = opts.clone();
|
||||
// Block off keeps the sizes it wrote into the characters.
|
||||
t.dynamic_text = *block;
|
||||
// Auto Size sets the height (Illustrator's dialog turns the Height field off).
|
||||
let h = if opts.fit == AreaFit::AutoHeight { None } else { h };
|
||||
// A resized frame has laid its text out again; otherwise the new options do here.
|
||||
@@ -1313,6 +1364,9 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod area_tests;
|
||||
mod block;
|
||||
#[cfg(test)]
|
||||
mod block_tests;
|
||||
|
||||
/// Width of the first line and of the space it can fill, with `tracking` on the first paragraph.
|
||||
/// The third value is where the first line ends in the plain text.
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
//! Dynamic Text's Block for area type ([`TextObject::dynamic_text`] on area type): each line as
|
||||
//! typed is set to the frame's width by changing its font size, after every edit
|
||||
//! ([`super::refresh_bounds`]).
|
||||
|
||||
use vectorcraft_doc::{TextKind, TextObject, TextRun};
|
||||
|
||||
/// The font size range a line's first character is fitted within, in document points (the
|
||||
/// Character panel's).
|
||||
const SIZES: (f64, f64) = (0.1, 1296.0);
|
||||
|
||||
/// Most passes a refit runs to correct lines that still wrap after the first fit; each pass measures
|
||||
/// the lines and runs at most one more area layout.
|
||||
pub(crate) const BLOCK_PASSES: usize = 4;
|
||||
|
||||
/// One line as typed: `start..content` is its text, `content..end` the `\n` or U+2028 that ends it
|
||||
/// (empty for the last line). `para` is the index of its paragraph, and `para_start` whether it
|
||||
/// starts that paragraph.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct TypedLine {
|
||||
start: usize,
|
||||
content: usize,
|
||||
end: usize,
|
||||
para: usize,
|
||||
para_start: bool,
|
||||
}
|
||||
|
||||
/// The lines as typed: the text split after each `\n` and U+2028.
|
||||
fn typed_lines(text: &str) -> Vec<TypedLine> {
|
||||
let mut out = vec![];
|
||||
let (mut start, mut para, mut para_start) = (0, 0, true);
|
||||
for (i, c) in text.char_indices() {
|
||||
if c == '\n' || c == '\u{2028}' {
|
||||
let end = i + c.len_utf8();
|
||||
out.push(TypedLine { start, content: i, end, para, para_start });
|
||||
start = end;
|
||||
para_start = c == '\n';
|
||||
if c == '\n' {
|
||||
para += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(TypedLine { start, content: text.len(), end: text.len(), para, para_start });
|
||||
out
|
||||
}
|
||||
|
||||
/// The stored size of the character at `byte` (the run that holds it, not the one before it).
|
||||
pub(crate) fn size_at(runs: &[TextRun], byte: usize) -> f64 {
|
||||
let mut off = 0;
|
||||
for r in runs {
|
||||
let end = off + r.text.len();
|
||||
if (off..end).contains(&byte) {
|
||||
return r.style.size;
|
||||
}
|
||||
off = end;
|
||||
}
|
||||
vectorcraft_text::edit::style_at(runs, byte).size
|
||||
}
|
||||
|
||||
/// The stored size of each line's first character, in one pass over the runs.
|
||||
fn first_sizes(runs: &[TextRun], lines: &[TypedLine]) -> Vec<f64> {
|
||||
let mut out = Vec::with_capacity(lines.len());
|
||||
let (mut ri, mut off) = (0, 0);
|
||||
for l in lines {
|
||||
while let Some(r) = runs.get(ri) {
|
||||
if l.start < off + r.text.len() {
|
||||
break;
|
||||
}
|
||||
off += r.text.len();
|
||||
ri += 1;
|
||||
}
|
||||
out.push(runs.get(ri).map_or_else(|| size_at(runs, l.start), |r| r.style.size));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Each line's content width (trailing spaces left out) by its first byte, with `t` laid out as
|
||||
/// point type, where no line wraps, with the word spacing `t`'s layout uses.
|
||||
fn line_widths(db: &vectorcraft_text::FontDb, t: &TextObject) -> std::collections::HashMap<usize, f64> {
|
||||
let mut probe = t.clone();
|
||||
for p in probe.para_styles_mut() {
|
||||
p.justification = t.layout_justification(p);
|
||||
}
|
||||
probe.kind = TextKind::Point;
|
||||
let laid = vectorcraft_text::layout(db, &probe);
|
||||
let mut out = std::collections::HashMap::with_capacity(laid.lines.len());
|
||||
for m in &laid.lines {
|
||||
out.entry(m.start).or_insert(m.x1 - m.x0);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing
|
||||
/// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down
|
||||
/// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its
|
||||
/// size rounded down to tenths, and None when that is its size, so fitting again changes nothing.
|
||||
/// Room taken entirely by indents gives the smallest size.
|
||||
fn refit(size: f64, width: f64, avail: f64, slope: f64) -> Option<f64> {
|
||||
if width <= avail + 1e-6 && width + 0.1 * slope > avail {
|
||||
let rounded = tenths(size);
|
||||
return ((rounded - size).abs() > 1e-9).then_some(rounded);
|
||||
}
|
||||
Some(tenths(size + (avail.max(0.0) - width) / slope))
|
||||
}
|
||||
|
||||
/// A size in document points rounded down to a whole number of tenths and kept within [`SIZES`].
|
||||
fn tenths(points: f64) -> f64 {
|
||||
((points * 10.0 + 1e-6).floor() / 10.0).clamp(SIZES.0, SIZES.1)
|
||||
}
|
||||
|
||||
/// Fit area type with Dynamic Text (Block) on: with the word gap as every paragraph's Desired word
|
||||
/// spacing ([`TextObject::layout_justification`]; the paragraphs keep their own values), each line
|
||||
/// as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to
|
||||
/// 1,296 pt, the line's other characters keeping their proportions to it) at which its width
|
||||
/// equals the frame's width less the inset, the gutters and the paragraph's indents, and each
|
||||
/// character's leading is its size plus the line gap. An empty line or one of only spaces keeps
|
||||
/// its size. Nothing changes when the frame has no width along the lines or the type's transform
|
||||
/// has no size. A line that still wraps at its first fit is made smaller, in at most
|
||||
/// [`BLOCK_PASSES`] more passes. True when the text changed.
|
||||
pub(crate) fn block_fit(t: &mut TextObject) -> bool {
|
||||
if !t.dynamic_text {
|
||||
return false;
|
||||
}
|
||||
let TextKind::Area { frame } = &t.kind else { return false };
|
||||
let (_, line_gap) = t.area.block_gaps();
|
||||
let Some(b) = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return false };
|
||||
let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false };
|
||||
let before = t.runs.clone();
|
||||
|
||||
// The room along a line in one cell of the frame, before indents.
|
||||
let a = &t.area;
|
||||
let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) };
|
||||
let cells = cells.max(1) as f64;
|
||||
let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells;
|
||||
if !(cell.is_finite() && cell > 1e-9) {
|
||||
return t.runs != before;
|
||||
}
|
||||
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let text = t.plain_text();
|
||||
let lines = typed_lines(&text);
|
||||
let widths = line_widths(db, t);
|
||||
let sizes = first_sizes(&t.runs, &lines);
|
||||
// Per line: (factor applied to its sizes, the room it fills, the last size measured and its
|
||||
// width), or None to keep its size.
|
||||
let mut fits: Vec<Option<(f64, f64, f64, f64)>> = lines
|
||||
.iter()
|
||||
.zip(&sizes)
|
||||
.map(|(l, size)| {
|
||||
if l.content == l.start {
|
||||
return None;
|
||||
}
|
||||
let width = widths.get(&l.start).copied().filter(|w| w.is_finite() && *w > 1e-9)?;
|
||||
let para = t.para_at(l.para);
|
||||
let first = if l.para_start { para.first_line_indent } else { 0.0 };
|
||||
let avail = cell - para.left_indent - para.right_indent - first;
|
||||
let size = size * points;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return None;
|
||||
}
|
||||
Some((refit(size, width, avail, width / size).map_or(1.0, |n| n / size), avail, size, width))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let gap = line_gap / points;
|
||||
let min_leading = SIZES.0 / points;
|
||||
// Always from the sizes the refit started with, so each pass sets a line's size once: the runs
|
||||
// are split where the lines end and each piece scaled by its line's factor, in one pass.
|
||||
let apply = |t: &mut TextObject, from: &[TextRun], fits: &[Option<(f64, f64, f64, f64)>]| {
|
||||
let mut out = Vec::with_capacity(from.len() + lines.len());
|
||||
let (mut off, mut li) = (0, 0);
|
||||
for r in from {
|
||||
let end = off + r.text.len();
|
||||
let mut at = off;
|
||||
loop {
|
||||
while lines.get(li).is_some_and(|l| l.end <= at && li + 1 < lines.len()) {
|
||||
li += 1;
|
||||
}
|
||||
let stop = lines.get(li).map_or(end, |l| l.end.clamp(at, end));
|
||||
let stop = if stop == at { end } else { stop };
|
||||
let f = fits.get(li).copied().flatten().map_or(1.0, |(f, ..)| f);
|
||||
let mut piece = TextRun { text: r.text.get(at - off..stop - off).unwrap_or_default().to_string(), ..r.clone() };
|
||||
if at > off {
|
||||
piece.style.glyph_alternate = None;
|
||||
}
|
||||
let st = &mut piece.style;
|
||||
st.size *= f;
|
||||
st.baseline_shift *= f;
|
||||
st.tcy_up_down *= f;
|
||||
st.tcy_left_right *= f;
|
||||
st.leading = Some((st.size + gap).max(min_leading));
|
||||
if let Some(art) = &mut piece.inline {
|
||||
art.baseline_shift *= f;
|
||||
}
|
||||
out.push(piece);
|
||||
at = stop;
|
||||
if at >= end {
|
||||
break;
|
||||
}
|
||||
}
|
||||
off = end;
|
||||
}
|
||||
vectorcraft_text::edit::normalize(&mut out);
|
||||
t.runs = out;
|
||||
};
|
||||
let start = t.runs.clone();
|
||||
apply(t, &start, &fits);
|
||||
|
||||
// Each pass measures the lines again: a line whose width did not follow its size (a tab to a
|
||||
// fixed stop) is fitted again from its measured width, and when every line measures right, a
|
||||
// line the frame's shape or a list marker still wraps is made smaller, by what the line the
|
||||
// layout gave it holds.
|
||||
// Per line: the smallest size measured too wide, which a later pass never goes back to.
|
||||
let mut too_wide = vec![f64::INFINITY; lines.len()];
|
||||
for _ in 0..BLOCK_PASSES {
|
||||
let now_widths = line_widths(db, t);
|
||||
let mut again = false;
|
||||
for (((l, fit), size), wide) in lines.iter().zip(fits.iter_mut()).zip(&sizes).zip(too_wide.iter_mut()) {
|
||||
let Some((f, avail, last_size, last_width)) = fit else { continue };
|
||||
let size = size * points;
|
||||
let now = size * *f;
|
||||
let Some(width) = now_widths.get(&l.start).copied().filter(|w| w.is_finite() && *w > 1e-9) else { continue };
|
||||
if width > *avail + 1e-6 {
|
||||
*wide = wide.min(now);
|
||||
}
|
||||
// The slope between the last two sizes measured, where they differ: a line whose width
|
||||
// has a part that stays as the size changes is fitted in one step.
|
||||
let slope = Some((width - *last_width) / (now - *last_size))
|
||||
.filter(|s| (now - *last_size).abs() > 1e-9 && s.is_finite() && *s > 1e-9)
|
||||
.unwrap_or(width / now);
|
||||
(*last_size, *last_width) = (now, width);
|
||||
let next = refit(now, width, *avail, slope).map(|n| if n >= *wide - 1e-9 { tenths(*wide - 0.1) } else { n });
|
||||
if let Some(next) = next.filter(|n| (n - now).abs() > 1e-9) {
|
||||
*f = next / size;
|
||||
again = true;
|
||||
}
|
||||
}
|
||||
if !again {
|
||||
let laid = vectorcraft_text::layout(db, t);
|
||||
// Per typed line: how many laid-out lines it took, and the room of its first.
|
||||
let mut parts: Vec<(usize, f64)> = vec![(0, 0.0); lines.len()];
|
||||
for m in &laid.lines {
|
||||
let i = lines.partition_point(|l| l.start <= m.start).saturating_sub(1);
|
||||
if let Some(p) = parts.get_mut(i) {
|
||||
if p.0 == 0 {
|
||||
p.1 = m.avail.1 - m.avail.0;
|
||||
}
|
||||
p.0 += 1;
|
||||
}
|
||||
}
|
||||
for (((l, fit), (count, room)), size) in lines.iter().zip(fits.iter_mut()).zip(&parts).zip(&sizes) {
|
||||
let Some((f, ..)) = fit else { continue };
|
||||
if *count < 2 {
|
||||
continue;
|
||||
}
|
||||
let size = size * points;
|
||||
let now = size * *f;
|
||||
if now <= SIZES.0 + 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let width = now_widths.get(&l.start).copied().unwrap_or(f64::INFINITY);
|
||||
let smaller = if room.is_finite() && *room > 0.0 && *room < width { tenths(now * room / width) } else { now };
|
||||
*f = smaller.min(tenths(now - 0.1)) / size;
|
||||
again = true;
|
||||
}
|
||||
}
|
||||
if !again {
|
||||
break;
|
||||
}
|
||||
apply(t, &start, &fits);
|
||||
}
|
||||
t.runs != before
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn typed_lines_split_after_returns_and_forced_breaks() {
|
||||
let l = typed_lines("ab\ncd\u{2028}e\n");
|
||||
let spans: Vec<_> = l.iter().map(|l| (l.start, l.content, l.end, l.para, l.para_start)).collect();
|
||||
assert_eq!(spans, vec![(0, 2, 3, 0, true), (3, 5, 8, 1, true), (8, 9, 10, 1, false), (10, 10, 10, 2, true)]);
|
||||
assert_eq!(typed_lines("").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fitting_line_keeps_its_size_in_tenths() {
|
||||
// 100 pt wide at 12 pt, 100.5 pt of room: a tenth larger would not fit.
|
||||
assert_eq!(refit(12.0, 100.0, 100.5, 100.0 / 12.0), None);
|
||||
assert_eq!(refit(12.34, 100.0, 100.5, 100.0 / 12.34), Some(12.3), "a size between tenths is rounded down");
|
||||
// Room for twice the width: twice the size.
|
||||
assert_eq!(refit(12.0, 100.0, 200.0, 100.0 / 12.0), Some(24.0));
|
||||
// A part of the width that stays (a slope below width / size) needs more size.
|
||||
assert_eq!(refit(12.0, 100.0, 150.0, 5.0), Some(22.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_round_down_to_tenths_within_the_range() {
|
||||
assert_eq!(tenths(23.99), 23.9);
|
||||
assert_eq!(tenths(24.0 - 1e-9), 24.0);
|
||||
assert_eq!(tenths(0.01), 0.1);
|
||||
assert_eq!(tenths(5000.0), 1296.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
//! Dynamic Text's Block for area type: `type.dynamicText`, Area Type Options › Block and the refit
|
||||
//! after edits.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{AreaFit, NodeId, NodeKind, TextKind, TextObject};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn area(s: &mut Session, w: f64, h: f64, text: &str) -> u64 {
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 40, "size": 12, "area": {"width": w, "height": h}, "text": text})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
fn text(s: &Session, id: u64) -> TextObject {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
k => panic!("not text: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The size of the character at `byte`.
|
||||
fn size_at(t: &TextObject, byte: usize) -> f64 {
|
||||
super::block::size_at(&t.runs, byte)
|
||||
}
|
||||
|
||||
/// Each laid-out line's (start byte, content width, room): the room is the frame's span less the
|
||||
/// indents.
|
||||
fn lines(t: &TextObject) -> Vec<(usize, f64, f64)> {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
lay.lines.iter().map(|l| (l.start, l.x1 - l.x0, l.avail.1 - l.avail.0)).collect()
|
||||
}
|
||||
|
||||
/// Every typed line is one laid-out line whose width is within one 0.1 pt size step of its room.
|
||||
fn assert_block(t: &TextObject) {
|
||||
let typed: Vec<usize> = std::iter::once(0).chain(t.plain_text().match_indices(['\n', '\u{2028}']).map(|(i, c)| i + c.len())).collect();
|
||||
let laid = lines(t);
|
||||
assert_eq!(laid.iter().map(|l| l.0).collect::<Vec<_>>(), typed, "one laid-out line per typed line: {laid:?}");
|
||||
for &(start, width, room) in &laid {
|
||||
let size = size_at(t, start);
|
||||
if width <= 1e-9 || size >= 1296.0 - 1e-9 || size <= 0.1 + 1e-9 {
|
||||
continue;
|
||||
}
|
||||
assert!(width <= room + 0.01, "line at {start} is wider than its room: {width} > {room}");
|
||||
assert!(width >= room * (size - 0.1) / size - 0.01, "line at {start} at {size} pt is short of its room: {width} < {room}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_sets_each_typed_line_to_the_frame_width_by_its_size() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line\nmid one");
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("type.dynamicText", &json!({})).unwrap();
|
||||
assert_eq!(r, json!({"on": true, "ids": [id], "fitScale": 1.0, "wordGap": 100.0, "lineGap": 0.0}));
|
||||
assert_eq!(undo_len(&s), n + 1, "one undo step");
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text);
|
||||
assert_eq!(t.area.fit, AreaFit::None);
|
||||
assert_block(&t);
|
||||
let (big, long, mid) = (size_at(&t, 0), size_at(&t, 4), size_at(&t, 31));
|
||||
assert!(big > mid && mid > long, "a shorter line is set larger: {big} {mid} {long}");
|
||||
for size in [big, long, mid] {
|
||||
assert!(((size * 10.0).round() - size * 10.0).abs() < 1e-6, "{size} is a whole number of tenths");
|
||||
}
|
||||
// Each character's leading is its size (line gap 0).
|
||||
assert!(t.runs.iter().all(|r| r.style.leading == Some(r.style.size)), "{:?}", t.runs);
|
||||
// Inspect reports it.
|
||||
let doc = s.execute("document.inspect", &json!({})).unwrap();
|
||||
let node = doc["layers"][0]["children"].as_array().unwrap().iter().find(|k| k["id"] == id).unwrap().clone();
|
||||
assert_eq!((node["dynamicText"].as_bool(), node["fit"].as_str()), (Some(true), Some("block")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_keeps_the_proportions_inside_a_line_and_fits_again_after_edits() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "one two three\nfour");
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 3, "size": 24})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_block(&t);
|
||||
let ratio = size_at(&t, 0) / size_at(&t, 4);
|
||||
assert!((ratio - 2.0).abs() < 0.02, "the first word stays twice the size of the rest: {ratio}");
|
||||
let four = size_at(&t, 14);
|
||||
// Typing into the first line makes it smaller, in the edit's own undo step; the second line stays.
|
||||
let first = size_at(&t, 4);
|
||||
let n = undo_len(&s);
|
||||
s.execute("text.editRange", &json!({"id": id, "start": 13, "end": 13, "insert": " and more words"})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
let t = text(&s, id);
|
||||
assert_block(&t);
|
||||
assert!(size_at(&t, 4) < first, "{} < {first}", size_at(&t, 4));
|
||||
assert_eq!(size_at(&t, t.plain_text().find("four").unwrap()), four);
|
||||
// A narrower frame sets every line smaller.
|
||||
s.execute("text.areaOptions", &json!({"width": 150})).unwrap();
|
||||
let narrow = text(&s, id);
|
||||
assert_block(&narrow);
|
||||
let f = size_at(&narrow, narrow.plain_text().find("four").unwrap()) / four;
|
||||
assert!((f - 0.5).abs() < 0.02, "half the width, half the size: {f}");
|
||||
// Undo brings the wider frame's sizes back.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(text(&s, id).runs, t.runs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_turns_off_keeping_its_sizes_and_records_nothing_when_nothing_changes() {
|
||||
let mut s = session();
|
||||
// The tab goes to a stop that stays where it is as the size changes.
|
||||
let id = area(&mut s, 300.0, 400.0, "Fit me\nand\tme too");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let fitted = text(&s, id).runs;
|
||||
let laid = lines(&text(&s, id));
|
||||
assert_eq!(laid.iter().map(|l| l.0).collect::<Vec<_>>(), vec![0, 7], "{laid:?}");
|
||||
assert!(laid.iter().all(|l| l.1 <= l.2 + 0.01 && l.1 > l.2 * 0.95), "each line fills its room: {laid:?}");
|
||||
let n = undo_len(&s);
|
||||
assert_eq!(s.execute("type.dynamicText", &json!({"on": true})).unwrap()["on"], true);
|
||||
assert_eq!(undo_len(&s), n, "already on: no undo step");
|
||||
let r = s.execute("type.dynamicText", &json!({})).unwrap();
|
||||
assert_eq!(r["on"], false);
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
let t = text(&s, id);
|
||||
assert!(!t.dynamic_text);
|
||||
assert_eq!(t.runs, fitted, "off keeps the sizes it was drawn at");
|
||||
// Edits no longer fit the lines.
|
||||
s.execute("text.areaOptions", &json!({"width": 100})).unwrap();
|
||||
assert_eq!(text(&s, id).runs, fitted);
|
||||
assert_eq!(s.execute("type.dynamicText", &json!({"on": false})).unwrap()["on"], false);
|
||||
assert_eq!(undo_len(&s), n + 2, "already off: no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_and_other_type_are_refused() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "Fit me");
|
||||
for bad in [
|
||||
json!({"on": "yes"}),
|
||||
json!({"on": 1}),
|
||||
json!({"wordGap": "wide"}),
|
||||
json!({"wordGap": -1}),
|
||||
json!({"wordGap": 1001}),
|
||||
json!({"lineGap": 1297}),
|
||||
json!({"lineGap": -1297}),
|
||||
json!({"lineGap": true}),
|
||||
] {
|
||||
assert!(s.execute("type.dynamicText", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert!(!text(&s, id).dynamic_text);
|
||||
let point = s.execute("text.create", &json!({"x": 10, "y": 500, "text": "point"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [point]})).unwrap();
|
||||
let e = s.execute("type.dynamicText", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("select type on a path or area type"), "{e}");
|
||||
// With point type selected too, only the area type changes.
|
||||
s.execute("select.set", &json!({"ids": [id, point]})).unwrap();
|
||||
let r = s.execute("type.dynamicText", &json!({})).unwrap();
|
||||
assert_eq!(r["ids"], json!([id]));
|
||||
assert!(text(&s, id).dynamic_text && !text(&s, point).dynamic_text);
|
||||
// A gap with only type on a path selected is an error, and nothing changes.
|
||||
let path = s.execute("path.create", &json!({"d": "M60 550 L340 550"})).unwrap()["id"].as_u64().unwrap();
|
||||
let along = s.execute("text.createInPath", &json!({"path": path, "mode": "onPath", "text": "Along"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [along]})).unwrap();
|
||||
let n = undo_len(&s);
|
||||
for gap in [json!({"wordGap": 300}), json!({"on": false, "lineGap": 2})] {
|
||||
let e = s.execute("type.dynamicText", &gap).unwrap_err().to_string();
|
||||
assert!(e.contains("need area type"), "{e}");
|
||||
}
|
||||
assert_eq!(undo_len(&s), n);
|
||||
assert!(!text(&s, along).dynamic_text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gaps_set_word_spacing_and_leading() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "two words\nthree more words");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let plain = text(&s, id);
|
||||
let r = s.execute("type.dynamicText", &json!({"wordGap": 300, "lineGap": 6})).unwrap();
|
||||
assert_eq!((r["on"].as_bool(), r["wordGap"].as_f64(), r["lineGap"].as_f64()), (Some(true), Some(300.0), Some(6.0)));
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text);
|
||||
assert_eq!((t.area.word_gap, t.area.line_gap), (300.0, 6.0));
|
||||
// The layout uses the gap as the Desired word spacing; the paragraph keeps its own.
|
||||
assert_eq!(t.para_at(0).justification.word_spacing, [80.0, 100.0, 133.0]);
|
||||
assert_eq!(t.layout_justification(t.para_at(0)).word_spacing, [80.0, 300.0, 300.0]);
|
||||
assert!(t.runs.iter().all(|r| (r.style.leading.unwrap() - r.style.size - 6.0).abs() < 1e-9), "{:?}", t.runs);
|
||||
assert_block(&t);
|
||||
assert!(size_at(&t, 0) < size_at(&plain, 0), "wider word spaces leave the letters less room");
|
||||
// (own, used by the layout) word spacing of the first paragraph.
|
||||
let spacing = |s: &Session| {
|
||||
let t = text(s, id);
|
||||
(t.para_at(0).justification.word_spacing, t.layout_justification(t.para_at(0)).word_spacing)
|
||||
};
|
||||
// Minimum and Maximum move out only as far as the current gap needs, and the paragraph's own
|
||||
// values apply again when Block is off.
|
||||
s.execute("type.dynamicText", &json!({"wordGap": 1000})).unwrap();
|
||||
assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [80.0, 1000.0, 1000.0]));
|
||||
s.execute("type.dynamicText", &json!({"wordGap": 100})).unwrap();
|
||||
assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [80.0, 100.0, 133.0]));
|
||||
s.execute("type.dynamicText", &json!({"wordGap": 0})).unwrap();
|
||||
assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [0.0, 0.0, 133.0]));
|
||||
s.execute("type.dynamicText", &json!({"on": false})).unwrap();
|
||||
assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [80.0, 100.0, 133.0]));
|
||||
// A paragraph's own values, outside the default range and equal to Desired too, stay through
|
||||
// gap changes and refits after edits.
|
||||
s.execute("text.setFormat", &json!({"wordSpacing": [20, 20, 150]})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true, "wordGap": 20})).unwrap();
|
||||
assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 20.0, 150.0]));
|
||||
s.execute("type.dynamicText", &json!({"wordGap": 1000})).unwrap();
|
||||
assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 1000.0, 1000.0]));
|
||||
s.execute("type.dynamicText", &json!({"wordGap": 100})).unwrap();
|
||||
s.execute("text.editRange", &json!({"id": id, "start": 0, "end": 0, "insert": "a "})).unwrap();
|
||||
assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 100.0, 150.0]));
|
||||
s.execute("type.dynamicText", &json!({"on": false})).unwrap();
|
||||
assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 20.0, 150.0]));
|
||||
// A gap alone on a frame without Block turns it on.
|
||||
let other = area(&mut s, 200.0, 200.0, "x y");
|
||||
let r = s.execute("type.dynamicText", &json!({"lineGap": -2})).unwrap();
|
||||
assert_eq!(r["on"], true);
|
||||
let t = text(&s, other);
|
||||
assert!(t.dynamic_text);
|
||||
assert_eq!((t.area.word_gap, t.area.line_gap), (100.0, -2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_type_options_offer_block_with_its_gaps() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "Fit me\nand me too");
|
||||
let q = s.execute("text.areaOptions", &json!({})).unwrap();
|
||||
assert_eq!((q["wordGap"].as_f64(), q["lineGap"].as_f64()), (Some(100.0), Some(0.0)));
|
||||
// Gaps alone are kept for Block, without turning it on or changing the text.
|
||||
let (n, runs) = (undo_len(&s), text(&s, id).runs);
|
||||
s.execute("text.areaOptions", &json!({"wordGap": 200})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!((undo_len(&s), t.dynamic_text, t.area.word_gap), (n + 1, false, 200.0));
|
||||
assert_eq!(t.runs, runs);
|
||||
let r = s.execute("text.areaOptions", &json!({"fit": "block", "lineGap": 4})).unwrap();
|
||||
assert_eq!((r["fit"].as_str(), r["wordGap"].as_f64(), r["lineGap"].as_f64()), (Some("block"), Some(200.0), Some(4.0)));
|
||||
assert!(text(&s, id).dynamic_text);
|
||||
assert_block(&text(&s, id));
|
||||
// The reply passed back (as the dialog does) changes nothing; naming Block again keeps the gaps.
|
||||
let n = undo_len(&s);
|
||||
assert_eq!(s.execute("text.areaOptions", &r).unwrap(), r);
|
||||
s.execute("text.areaOptions", &json!({"fit": "block"})).unwrap();
|
||||
assert_eq!(undo_len(&s), n);
|
||||
s.execute("text.areaOptions", &json!({"lineGap": 2})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!((t.dynamic_text, t.area.word_gap, t.area.line_gap), (true, 200.0, 2.0));
|
||||
assert!(s.execute("text.areaOptions", &json!({"lineGap": 5000})).is_err());
|
||||
assert!(s.execute("text.areaOptions", &json!({"wordGap": 2000})).is_err());
|
||||
assert!(s.execute("text.areaOptions", &json!({"wordGap": "wide"})).is_err());
|
||||
assert!(s.execute("text.areaOptions", &json!({"fit": "squash"})).unwrap_err().to_string().contains("shrinkText|block"));
|
||||
// Shrink Text to Fit replaces Block, keeping the sizes.
|
||||
let runs = text(&s, id).runs;
|
||||
s.execute("text.areaOptions", &json!({"fit": "shrinkText"})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(!t.dynamic_text);
|
||||
assert_eq!(t.runs, runs);
|
||||
// Block replaces Shrink Text to Fit and Auto Size.
|
||||
s.execute("text.areaOptions", &json!({"fit": "block"})).unwrap();
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::None);
|
||||
// New area type can start with it.
|
||||
let made = s
|
||||
.execute(
|
||||
"text.create",
|
||||
&json!({"x": 10, "y": 300, "size": 12, "area": {"width": 200, "height": 200, "fit": "block", "wordGap": 150}, "text": "made"}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let t = text(&s, made);
|
||||
assert_eq!((t.dynamic_text, t.area.word_gap, t.area.line_gap), (true, 150.0, 0.0));
|
||||
assert_block(&t);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_round_trips_through_the_native_format() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "Fit me\nand me too");
|
||||
s.execute("type.dynamicText", &json!({"wordGap": 120, "lineGap": 3})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let bytes = vectorcraft_format::save(&doc, false);
|
||||
let back = vectorcraft_format::load(&bytes).unwrap();
|
||||
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
assert_eq!((t.dynamic_text, t.area.word_gap, t.area.line_gap), (true, 120.0, 3.0));
|
||||
assert_eq!(t.runs, text(&s, id).runs, "the fitted sizes are saved in the characters");
|
||||
// Saved as `dynamicText` with the gaps beside the area options; missing gaps read as their
|
||||
// defaults, which are left out when saved.
|
||||
let saved = serde_json::to_value(&**t).unwrap();
|
||||
assert_eq!((&saved["dynamicText"], &saved["area"]["wordGap"], &saved["area"]["lineGap"]), (&json!(true), &json!(120.0), &json!(3.0)));
|
||||
let plain = serde_json::from_value::<vectorcraft_doc::AreaOptions>(json!({})).unwrap();
|
||||
assert_eq!((plain.word_gap, plain.line_gap), (100.0, 0.0));
|
||||
let plain: Value = serde_json::to_value(&plain).unwrap();
|
||||
assert!(plain.get("wordGap").is_none() && plain.get("lineGap").is_none(), "{plain}");
|
||||
// Turned off, it opens off with the sizes it had.
|
||||
s.execute("type.dynamicText", &json!({"on": false})).unwrap();
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
assert!(!t.dynamic_text);
|
||||
assert_eq!(t.runs, text(&s, id).runs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edge_cases_fit_without_failing() {
|
||||
let mut s = session();
|
||||
// Empty text, an empty line and a line of spaces keep their sizes.
|
||||
let empty = area(&mut s, 300.0, 400.0, "");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_eq!(size_at(&text(&s, empty), 0), 12.0);
|
||||
let gaps = area(&mut s, 300.0, 400.0, "top\n\n \nbottom line");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, gaps);
|
||||
assert_eq!((size_at(&t, 4), size_at(&t, 5)), (12.0, 12.0));
|
||||
assert_block(&t);
|
||||
// One word.
|
||||
let word = area(&mut s, 300.0, 400.0, "Word");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_block(&text(&s, word));
|
||||
// A wide frame stops at 1,296 pt; a very long line in a narrow frame stops at 0.1 pt and wraps.
|
||||
let wide = area(&mut s, 100_000.0, 400.0, "i");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_eq!(size_at(&text(&s, wide), 0), 1296.0);
|
||||
let narrow = area(&mut s, 1.0, 400.0, &"long words ".repeat(40));
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, narrow);
|
||||
assert_eq!(size_at(&t, 0), 0.1);
|
||||
assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "at 0.1 pt the line still does not fit");
|
||||
// A frame inset so far that it has no width keeps the sizes.
|
||||
let inset = area(&mut s, 50.0, 400.0, "Inset");
|
||||
s.execute("text.areaOptions", &json!({"inset": 30})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_eq!(size_at(&text(&s, inset), 0), 12.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_fits_columns_lists_vertical_and_right_to_left_type() {
|
||||
let mut s = session();
|
||||
// Two columns: each line is set to a column's width.
|
||||
let cols = area(&mut s, 400.0, 600.0, "left column\nsecond");
|
||||
s.execute("text.areaOptions", &json!({"columns": 2, "gutter": 20})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, cols);
|
||||
assert_block(&t);
|
||||
assert!(lines(&t).iter().all(|l| (l.2 - 190.0).abs() < 1e-6), "{:?}", lines(&t));
|
||||
// A bulleted list: each item stays one line, the marker and its tab taking their room before
|
||||
// the text (the room the layout reports takes in the marker's too).
|
||||
let list = area(&mut s, 300.0, 400.0, "first item\nsecond item here");
|
||||
s.execute("text.setFormat", &json!({"list": "bullet"})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, list);
|
||||
let laid = lines(&t);
|
||||
assert_eq!(laid.iter().map(|l| l.0).collect::<Vec<_>>(), vec![0, 11], "{laid:?}");
|
||||
assert!(laid.iter().all(|l| l.1 <= l.2), "{laid:?}");
|
||||
assert!(size_at(&t, 0) > size_at(&t, 11), "the shorter item is larger");
|
||||
// Right-to-left text.
|
||||
let rtl = area(&mut s, 300.0, 400.0, "שלום עולם\nטקסט ארוך יותר בשורה");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_block(&text(&s, rtl));
|
||||
// Vertical type: each column of text is set to the frame's height.
|
||||
let v = s
|
||||
.execute(
|
||||
"text.create",
|
||||
&json!({"x": 40, "y": 40, "size": 12, "vertical": true, "area": {"width": 300, "height": 200}, "text": "縦書き\nもっと長い縦書きの行"}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [v]})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, v);
|
||||
assert!(t.vertical);
|
||||
assert_block(&t);
|
||||
assert!(lines(&t).iter().all(|l| (l.2 - 200.0).abs() < 1e-6), "{:?}", lines(&t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threaded_frames_are_refused_and_threading_turns_block_off() {
|
||||
let mut s = session();
|
||||
let a = area(&mut s, 200.0, 300.0, "Fit me\nand me too");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let fitted = text(&s, a).runs;
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 400, "y": 40, "width": 200, "height": 300})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let n = undo_len(&s);
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
let t = text(&s, a);
|
||||
assert!(!t.dynamic_text, "threading turns Block off");
|
||||
assert_eq!(t.runs, fitted, "the text keeps its sizes");
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let e = s.execute("type.dynamicText", &json!({"on": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("area type in a thread") && e.contains(&a.to_string()), "{e}");
|
||||
let runs = text(&s, a).runs;
|
||||
let e = s.execute("text.areaOptions", &json!({"fit": "block"})).unwrap_err().to_string();
|
||||
assert!(e.contains("area type in a thread") && e.contains(&a.to_string()), "{e}");
|
||||
assert_eq!(text(&s, a).runs, runs, "Area Type Options refuses it too, changing nothing");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(text(&s, a).dynamic_text, "undo brings it back with the thread gone");
|
||||
assert!(matches!(text(&s, a).kind, TextKind::Area { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_text_fits_in_a_bounded_number_of_layouts() {
|
||||
let mut s = session();
|
||||
let story: String = (0..300).map(|i| format!("line number {i} {}\n", "x".repeat(i % 17))).collect();
|
||||
let id = area(&mut s, 300.0, 100_000.0, &story);
|
||||
let before = vectorcraft_text::test_fonts::layouts_on_this_thread();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let used = vectorcraft_text::test_fonts::layouts_on_this_thread() - before;
|
||||
assert_block(&text(&s, id));
|
||||
// The command fits the object to compare and to apply (each a measure, at most two layouts a
|
||||
// pass and the caches), plus the reply's own.
|
||||
let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 4;
|
||||
assert!(used <= bound, "{used} layouts");
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
//! Type menu long tail (Change Case, Smart Punctuation, Convert To Area/Point Type, Type on a Path
|
||||
//! Options, Fill with Placeholder Text, Insert Special/Whitespace/Break characters) and the text
|
||||
//! commands of the Edit menu (Find and Replace, Find Next, Paste without Formatting).
|
||||
//! Options, Dynamic Text, Fill with Placeholder Text, Insert Special/Whitespace/Break characters)
|
||||
//! and the text commands of the Edit menu (Find and Replace, Find Next, Paste without Formatting).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Document, Justify, LockedArtboards, Node, NodeId, NodeKind, Quotes, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_doc::{AreaFit, CharStyle, Document, Justify, LockedArtboards, Node, NodeId, NodeKind, Quotes, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
|
||||
use super::object::choice;
|
||||
use super::typecmd::refresh_bounds;
|
||||
use super::typecmd::{area_text, block_gaps, refresh_bounds};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or,
|
||||
switch_or, targets, text_param,
|
||||
@@ -65,10 +65,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Dynamic Text",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, on?: bool} turn Dynamic Text on or off for the selected type on a path (on omitted: the opposite of the first object's setting). On, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. Off, the text keeps the sizes it was drawn at. Point type and area type in the selection are left as they are; a selection holding type on a path in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When every object already has the setting, nothing changes and no undo step is recorded → {on, ids, fitScale (the first object's factor, 1 when off)}",
|
||||
has_free_path_type,
|
||||
"{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type (on omitted: the opposite of the first object's setting, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Point type in the selection is left as it is; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}",
|
||||
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",
|
||||
@@ -520,26 +529,40 @@ fn path_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
options(s)
|
||||
}
|
||||
|
||||
/// Whether type on a path `id` is a frame of a thread.
|
||||
/// Whether type `id` is a frame of a thread.
|
||||
fn threaded(d: &Document, id: NodeId) -> bool {
|
||||
!super::threads::story_of(d, id).is_empty()
|
||||
}
|
||||
|
||||
/// `type.dynamicText` is enabled for a selection holding type on a path, none of it in a thread.
|
||||
fn has_free_path_type(s: &Session) -> std::result::Result<(), String> {
|
||||
/// Type on a path or area type: the type Dynamic Text works on.
|
||||
fn dynamic_type(n: Option<&Node>) -> Option<&TextObject> {
|
||||
path_text(n).or_else(|| area_text(n))
|
||||
}
|
||||
|
||||
/// `type.dynamicText` is enabled for a selection holding type on a path or area type, none of it
|
||||
/// in a thread.
|
||||
fn has_dynamic_type(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
let d = &st.doc;
|
||||
let selected: Vec<NodeId> = st.selection.objects.to_vec();
|
||||
let paths: Vec<NodeId> = text_ids(d, &selected).into_iter().filter(|id| path_text(d.node(*id)).is_some()).collect();
|
||||
if paths.is_empty() {
|
||||
return Err("select type on a path".into());
|
||||
let types: Vec<NodeId> = text_ids(d, &selected).into_iter().filter(|id| dynamic_type(d.node(*id)).is_some()).collect();
|
||||
if types.is_empty() {
|
||||
return Err("select type on a path or area type".into());
|
||||
}
|
||||
threaded_refusal(d, &types).map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
/// Why Dynamic Text is refused for `ids`: the frames among them that are in a thread, type on a
|
||||
/// path first; None when none is.
|
||||
fn threaded_refusal(d: &Document, ids: &[NodeId]) -> Option<String> {
|
||||
let (paths, areas): (Vec<NodeId>, Vec<NodeId>) = ids.iter().copied().partition(|id| path_text(d.node(*id)).is_some());
|
||||
let frames = threaded_ids(d, &paths);
|
||||
if !frames.is_empty() {
|
||||
return Err(format!("type on a path in a thread cannot use Dynamic Text: {frames}"));
|
||||
return Some(format!("type on a path in a thread cannot use Dynamic Text: {frames}"));
|
||||
}
|
||||
Ok(())
|
||||
let frames = threaded_ids(d, &areas);
|
||||
(!frames.is_empty()).then(|| format!("area type in a thread cannot use Dynamic Text: {frames}"))
|
||||
}
|
||||
|
||||
/// The ids among `ids` of frames of threads, as a list for a message; empty when there are none.
|
||||
@@ -547,32 +570,60 @@ fn threaded_ids(d: &Document, ids: &[NodeId]) -> String {
|
||||
ids.iter().filter(|id| threaded(d, **id)).map(|id| id.0.to_string()).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// Type › Dynamic Text: set `on` (without it, the opposite of the first object's setting) on the
|
||||
/// selected type on a path, in one undo step, and none when every object already has it. Turning
|
||||
/// it off keeps the sizes the text was drawn at ([`bake_dynamic_text`]).
|
||||
/// Type › Dynamic Text: set `on` (without it, the opposite of the first object's setting, or on
|
||||
/// when a gap is given) on the selected type on a path and area type (Block, with its gaps), in
|
||||
/// one undo step, and none when nothing changes. Turning it off keeps the sizes the text was drawn
|
||||
/// at ([`bake_dynamic_text`]).
|
||||
fn dynamic_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "type.dynamicText";
|
||||
let (ids, on, changing) = {
|
||||
let (word_gap, line_gap) = block_gaps(p, C)?;
|
||||
let (ids, on, planned) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let ids: Vec<NodeId> = texts(s, p, C)?.into_iter().filter(|i| path_text(d.node(*i)).is_some()).collect();
|
||||
let first = *ids.first().ok_or_else(|| bad(C, "select 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 ids: Vec<NodeId> = texts(s, p, C)?.into_iter().filter(|i| dynamic_type(d.node(*i)).is_some()).collect();
|
||||
let first = *ids.first().ok_or_else(|| bad(C, "select type on a path or area type"))?;
|
||||
if let Some(why) = threaded_refusal(d, &ids) {
|
||||
return Err(bad(C, why));
|
||||
}
|
||||
let on = switch_or(p, "on", !path_text(d.node(first)).is_some_and(|t| t.dynamic_text), C)?;
|
||||
let changing: Vec<NodeId> = ids.iter().copied().filter(|id| path_text(d.node(*id)).is_some_and(|t| t.dynamic_text != on)).collect();
|
||||
(ids, on, changing)
|
||||
let gap_given = word_gap.is_some() || line_gap.is_some();
|
||||
if gap_given && !ids.iter().any(|id| area_text(d.node(*id)).is_some()) {
|
||||
return Err(bad(C, "wordGap and lineGap need area type in the selection"));
|
||||
}
|
||||
let on = switch_or(p, "on", gap_given || !dynamic_type(d.node(first)).is_some_and(|t| t.dynamic_text), C)?;
|
||||
// Each object as the command leaves it, and only those it changes.
|
||||
let mut planned: Vec<(NodeId, TextObject)> = vec![];
|
||||
for id in &ids {
|
||||
let Some(t) = dynamic_type(d.node(*id)) else { continue };
|
||||
let mut after = t.clone();
|
||||
if matches!(t.kind, TextKind::Area { .. }) {
|
||||
after.area.word_gap = word_gap.unwrap_or(t.area.word_gap);
|
||||
after.area.line_gap = line_gap.unwrap_or(t.area.line_gap);
|
||||
}
|
||||
match (on, t.dynamic_text) {
|
||||
(true, true) => refresh_bounds(&mut after),
|
||||
(true, false) => {
|
||||
after.dynamic_text = true;
|
||||
// Block replaces Auto Size and Shrink Text to Fit.
|
||||
if matches!(t.kind, TextKind::Area { .. }) {
|
||||
after.area.fit = AreaFit::None;
|
||||
}
|
||||
refresh_bounds(&mut after);
|
||||
}
|
||||
(false, true) => {
|
||||
bake_dynamic_text(&mut after);
|
||||
}
|
||||
(false, false) => {}
|
||||
}
|
||||
if after != *t {
|
||||
planned.push((*id, after));
|
||||
}
|
||||
}
|
||||
(ids, on, planned)
|
||||
};
|
||||
if !changing.is_empty() {
|
||||
if !planned.is_empty() {
|
||||
s.edit("Dynamic Text", |d, _| {
|
||||
for id in &changing {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
if on {
|
||||
t.dynamic_text = true;
|
||||
refresh_bounds(t);
|
||||
} else {
|
||||
bake_dynamic_text(t);
|
||||
for (id, after) in &planned {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
**t = after.clone();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -581,7 +632,13 @@ fn dynamic_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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!({"on": on, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "fitScale": fit}))
|
||||
let mut reply = json!({"on": on, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "fitScale": fit});
|
||||
if let Some(t) = ids.iter().find_map(|id| area_text(d.node(*id))) {
|
||||
let (w, l) = t.area.block_gaps();
|
||||
reply["wordGap"] = json!(w);
|
||||
reply["lineGap"] = json!(l);
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
/// Turn Dynamic Text off on `t`, keeping the sizes its layout draws it at: every run's size,
|
||||
@@ -600,6 +657,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).
|
||||
|
||||
Reference in New Issue
Block a user