Merge main into fix/colorize-missing-link-fill

This commit is contained in:
dotCooCoo
2026-11-12 19:57:08 -08:00
103 changed files with 3987 additions and 469 deletions
+1 -1
View File
@@ -777,7 +777,7 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
/// The most presets one presets file imports: each is looked up among the saved ones.
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::DecodedImages;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
pub use docmenu::guide_indexes;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
+1 -1
View File
@@ -14,7 +14,7 @@ mod select;
mod shapes;
mod typetools;
pub(crate) use image::DecodedImages;
pub(crate) use image::{DecodedImages, refresh_color_masks};
use super::CommandSpec;
+112 -74
View File
@@ -2,12 +2,16 @@
//! 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.
//! on the pixels; nothing is sent anywhere. Color Mask ([`mask`]) hides colors matched the same
//! way while the image keeps its pixels. They are VectorCraft additions. Its submenu (Object ›
//! Plug-ins › Image Tools) and dialogs are the UI's.
mod mask;
#[cfg(test)]
mod tests;
pub(crate) use mask::refresh as refresh_color_masks;
use std::collections::{HashMap, HashSet};
use std::io::Cursor;
use std::sync::{Arc, Weak};
@@ -15,12 +19,12 @@ 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_doc::{ImageBlob, ImageObject, NodeId, NodeKind};
use vectorcraft_geom::Affine;
use super::super::fileio::{MAX_RASTER_ALLOC, ppi};
use super::super::menucmds::has_image;
use super::super::paint::{PROCESS_ON_TRANSPARENCY, gray_colorized_with_process};
use super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
use super::super::{CommandSpec, Result, Session, bad, checked_ids_param, cmd, hex_with_alpha, number_or, switch_or, text_param};
/// Remove Background's command.
@@ -35,7 +39,7 @@ const MAX_COLORS: usize = 16;
const WORK_BYTES: u64 = 10;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
let mut v = vec![cmd!(
"addon.image.removeBackground",
"Remove Background…",
["Object", "Plug-ins", "Image Tools"],
@@ -43,7 +47,9 @@ pub fn specs() -> Vec<CommandSpec> {
"{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, a result with no pixel left, and a grayscale image colorized with a process color (which can't colorize gray pixels with transparency) 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
)]
)];
v.extend(mask::specs());
v
}
/// Where the background's colors come from.
@@ -79,50 +85,50 @@ pub(crate) struct Settings {
}
impl Settings {
/// The settings `p` gives, each checked.
fn read(p: &Value) -> Result<Self> {
/// The settings `p` gives to command `cmd`, each checked.
fn read(p: &Value, cmd: &str) -> 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 v = number_or(p, key, 10.0, cmd)?;
if v.is_finite() && (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(cmd, 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)?),
Some(v) => Some(colors(v, cmd)?),
};
let background = match text_param(p, "background", C)? {
let background = match text_param(p, "background", cmd)? {
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")),
Some("colors") => Background::Colors(colors.ok_or_else(|| colors_error(cmd))?),
Some(_) => return Err(bad(cmd, "`background` must be edges, corners or colors")),
};
let measure = match text_param(p, "match", C)? {
let measure = match text_param(p, "match", cmd)? {
None | Some("distance") => Match::Distance,
Some("channels") => Match::Channels,
Some(_) => return Err(bad(C, "`match` must be distance or channels")),
Some(_) => return Err(bad(cmd, "`match` must be distance or channels")),
};
let contiguous = switch_or(p, "contiguous", true, C)?;
let contiguous = switch_or(p, "contiguous", true, cmd)?;
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")
fn colors_error(cmd: &str) -> crate::EngineError {
bad(cmd, "`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]>> {
/// The colors `v` lists to command `cmd`: 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, cmd: &str) -> 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()),
Value::Array(a) => a.iter().take(MAX_COLORS + 1).map(Value::as_str).collect::<Option<_>>().ok_or_else(|| colors_error(cmd))?,
_ => return Err(colors_error(cmd)),
};
if texts.is_empty() || texts.len() > MAX_COLORS {
return Err(colors_error());
return Err(colors_error(cmd));
}
texts.into_iter().map(|t| rgb8(t).ok_or_else(colors_error)).collect()
texts.into_iter().map(|t| rgb8(t).ok_or_else(|| colors_error(cmd))).collect()
}
/// The 8-bit RGB of the color `t` writes.
@@ -135,7 +141,7 @@ fn rgb8(t: &str) -> Option<[u8; 3]> {
}
fn remove_background(s: &mut Session, p: &Value) -> Result<Value> {
let settings = Settings::read(p)?;
let settings = Settings::read(p, C)?;
// 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;
@@ -165,40 +171,15 @@ fn remove_background(s: &mut Session, p: &Value) -> Result<Value> {
/// 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 images = images(s, p, C)?;
// The result has an alpha channel, which a grayscale image colorized with a process color
// can't take. The pixels that are cleared are checked, the image's own, not the ones a color
// mask shows.
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(n) = st.doc.node(id) else { continue };
let NodeKind::Image(im) = &n.kind else { continue };
let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image's pixels are missing"))?;
// The result has an alpha channel, which a grayscale image colorized with a process color
// can't take.
if gray_colorized_with_process(&st.doc, n).is_some() {
for (id, _, blob) in &images {
if blob.gray_source().is_some() && st.doc.node(*id).is_some_and(|n| colorized_with_process(&st.doc, n)) {
return Err(bad(C, PROCESS_ON_TRANSPARENCY));
}
// 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();
@@ -207,7 +188,7 @@ fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut De
let out = match cleared.get(im.key.as_str()) {
Some(out) => out.clone(),
None => {
let out = clear(blob, settings, kept.as_deref_mut())?;
let out = clear(blob, settings, kept.as_deref_mut(), C)?;
cleared.insert(&im.key, out.clone());
out
}
@@ -225,6 +206,58 @@ fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut De
Ok(changes)
}
/// The image objects command `cmd` acts on (`ids`, each once, or the selected images), each with
/// its pixels, all checked before any is decoded: an object that is not an image, missing pixels,
/// a linked image that shows its preview and a CMYK image are errors, as is no image at all.
fn images<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<Vec<(NodeId, &'a ImageObject, &'a ImageBlob)>> {
let st = s.doc()?;
let mut images = vec![];
for id in targets(s, p, cmd)? {
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(cmd, "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(cmd, "the linked image shows its preview: embed or relink it first"));
}
if blob.is_cmyk() {
return Err(cmyk_refusal(cmd));
}
images.push((id, &**im, blob));
}
Ok(images)
}
/// The image objects command `cmd` acts on: `ids`, each once, or the selected images. An object in
/// `ids` that is not an image is an error, as is no image at all.
fn targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
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", cmd)?.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(cmd, 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(cmd, "select an image"));
}
Ok(ids)
}
/// Whether `cmd` is one of Color Mask's commands, which hide pixels instead of clearing them.
fn masks(cmd: &str) -> bool {
matches!(cmd, mask::COLOR_MASK | mask::REMOVE_COLOR_MASK | mask::APPLY_COLOR_MASK)
}
/// Command `cmd`'s refusal of a CMYK image.
fn cmyk_refusal(cmd: &str) -> crate::EngineError {
if masks(cmd) { bad(cmd, "a CMYK image can't take a color mask") } else { bad(cmd, "a CMYK image has no transparency to set") }
}
/// 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)]
@@ -352,16 +385,16 @@ impl Pixels {
/// `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>> {
/// errors of command `cmd`. 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>, cmd: &str) -> Result<Option<Cleared>> {
if blob.is_cmyk() {
return Err(bad(C, "a CMYK image has no transparency to set"));
return Err(cmyk_refusal(cmd));
}
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)?,
None => decode(blob, kept, cmd)?,
};
// 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));
@@ -373,7 +406,11 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
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"));
return Err(if masks(cmd) {
bad(cmd, "the mask would hide every pixel")
} else {
bad(cmd, "every pixel matches the background: no image would be left")
});
}
let out = match (px, gray) {
(Pixels::Eight(img), false) => DynamicImage::ImageRgba8(img),
@@ -389,9 +426,9 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
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()))?;
encoder.set_icc_profile(icc).map_err(|e| bad(cmd, e.to_string()))?;
}
out.write_with_encoder(encoder).map_err(|e| bad(C, e.to_string()))?;
out.write_with_encoder(encoder).map_err(|e| bad(cmd, 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);
@@ -401,11 +438,12 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
/// `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}")))?;
/// is given, if a copy of them fits the decode allowance beside the work. Errors are command `cmd`'s.
fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<(Arc<Pixels>, bool, Option<Vec<u8>>)> {
let reader = || {
image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(cmd, "the image's pixels can't be read"))
};
let mut decoder = reader()?.into_decoder().map_err(|e| bad(cmd, 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 _;
@@ -418,13 +456,13 @@ fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>) -> Result<(Arc<Pix
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")));
return Err(bad(cmd, 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}")))?;
let img = reader.decode().map_err(|e| bad(cmd, 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);
+443
View File
@@ -0,0 +1,443 @@
//! Image Tools › Color Mask (`addon.image.colorMask`, `addon.image.removeColorMask`,
//! `addon.image.applyColorMask`): colors of the selected images are hidden while their pixels
//! stay as they are. The colors are matched as Remove Background matches them ([`super::clear`]);
//! the image keeps its own pixels, and the mask's settings and the masked pixels are kept with it
//! ([`vectorcraft_doc::color_mask`]), so the mask can be changed, removed, or applied to the
//! pixels later. When an image's own pixels are replaced (a link updated or relinked, the image
//! cropped or recolored), its mask is applied to the new pixels ([`refresh`]).
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch};
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
use vectorcraft_geom::Affine;
use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
use super::super::super::{CommandSpec, Result, Session, bad, cmd};
use super::{Background, DecodedImages, MAX_COLORS, Match, Settings, clear, images, targets};
/// Color Mask's command.
pub const COLOR_MASK: &str = "addon.image.colorMask";
/// Remove Color Mask's command.
pub const REMOVE_COLOR_MASK: &str = "addon.image.removeColorMask";
/// Apply Color Mask's command.
pub const APPLY_COLOR_MASK: &str = "addon.image.applyColorMask";
/// The params that set a mask; with none of them, Color Mask only reports.
const SETTINGS: [&str; 6] = ["background", "colors", "contiguous", "match", "tolerance", "softness"];
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"addon.image.colorMask",
"Color Mask…",
["Object", "Plug-ins", "Image Tools"],
None,
"{background?: \"edges\" (default: the most common color along the image's edges) | \"corners\" (the average of the image's four corner pixels that are not clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 hex colors or black, white, red, green and blue, as addon.image.removeBackground takes them; needed with background: colors), contiguous?: bool (true: only matching pixels that reach in from an edge are hidden; false: wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a hidden color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (% as addon.image.removeBackground measures it; a pixel this near a hidden color is hidden; 10), softness?: 0..100 (% past the tolerance over which pixels fade from hidden to shown; 10), ids?: [id…] (default: the selected images)} hide colors of each image without changing its pixels, as one undo step: the image keeps its own pixels, and the mask (these settings, and the image's pixels with the hidden colors made clear, made as Remove Background makes them) is kept with the image and saved with the document; the canvas, printing and separations, PDF, SVG, EPS, raster formats, DXF, EMF, WMF, the legacy .ai and the .ai editing data, copy and paste, and placing a document show the masked pixels, and a click on any part of the image's frame selects it (the Eyedropper, Object Mosaic, Create Gradient Mesh, Crop Image's trim and Image Trace read the image's own pixels); setting the mask again replaces it, and an image whose mask does not change is left as it is (no undo step when none changes); when the image's own pixels are replaced later (Update Link, Relink, Crop Image, a recolor, a linked file read again on open), the mask is made again for the new pixels; an object in `ids` that is not an image, a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, a mask that would hide every pixel, and a mask that would hide pixels of a grayscale image colorized with a process color (masked gray pixels have transparency, which only a spot color, black or white colorizes; each image is checked on the pixels its new mask shows) are refused. With none of background, colors, contiguous, match, tolerance and softness given, nothing changes and the mask settings of the first image (or the defaults when it has no mask) are returned → {changed: the images changed, ids, hidden: the pixels made fully clear in them} or {background, colors, contiguous, match, tolerance, softness, masked}",
super::has_image,
color_mask
),
cmd!(
"addon.image.removeColorMask",
"Remove Color Mask",
["Object", "Plug-ins", "Image Tools"],
None,
"{ids?: [id…] (default: the selected images)} take the color mask off each image, as one undo step: the image shows its own pixels again; images without a mask are left as they are (no undo step when none has one), and an object in `ids` that is not an image is refused → {changed, ids}",
has_color_mask,
remove_color_mask
),
cmd!(
"addon.image.applyColorMask",
"Apply Color Mask",
["Object", "Plug-ins", "Image Tools"],
None,
"{ids?: [id…] (default: the selected images)} make each image's color mask part of its pixels, as one undo step: the masked pixels become the image's own, embedded as a PNG with an alpha channel (a linked image is embedded), and the mask is taken off; a mask that hides nothing is only taken off (the image keeps its pixels and its link); images without a mask are left as they are (no undo step when none has one), and an object in `ids` that is not an image, and a mask made again for new pixels that would give a grayscale image colorized with a process color an alpha channel, are refused → {changed, ids}",
has_color_mask,
apply_color_mask
),
]
}
/// Enabled when a selected image has a color mask.
fn has_color_mask(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.selection.objects.iter().any(|id| st.doc.node(*id).and_then(Document::color_mask_of).is_some()) {
Ok(())
} else {
Err("select an image with a color mask".into())
}
}
impl Settings {
/// The settings a mask was made with, `None` when a file gave ones out of range.
fn of(m: &ColorMask) -> Option<Self> {
let percent = |v: f64| v.is_finite() && (0.0..=100.0).contains(&v);
if !percent(m.tolerance) || !percent(m.softness) {
return None;
}
let background = match m.background {
MaskBackground::Edges => Background::Edges,
MaskBackground::Corners => Background::Corners,
MaskBackground::Colors if (1..=MAX_COLORS).contains(&m.colors.len()) => Background::Colors(m.colors.clone()),
MaskBackground::Colors => return None,
};
let measure = match m.measure {
MaskMatch::Distance => Match::Distance,
MaskMatch::Channels => Match::Channels,
};
Some(Self { background, contiguous: m.contiguous, measure, tolerance: m.tolerance, softness: m.softness })
}
/// A mask with these settings whose masked pixels are `key`, made from the pixels `from`.
fn mask(&self, key: String, from: String) -> ColorMask {
let (background, colors) = match &self.background {
Background::Edges => (MaskBackground::Edges, vec![]),
Background::Corners => (MaskBackground::Corners, vec![]),
Background::Colors(c) => (MaskBackground::Colors, c.clone()),
};
let measure = match self.measure {
Match::Distance => MaskMatch::Distance,
Match::Channels => MaskMatch::Channels,
};
ColorMask { key, from, background, colors, contiguous: self.contiguous, measure, tolerance: self.tolerance, softness: self.softness }
}
}
/// The masked pixels of `blob` (`None`: no pixel is hidden, the image's own pixels show) as
/// `settings` say, with errors of command `cmd`.
fn masked(blob: &ImageBlob, settings: &Settings, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<Option<(String, ImageBlob, u64)>> {
Ok(clear(blob, settings, kept, cmd)?.map(|out| (out.blob.content_key(), out.blob, out.cleared)))
}
fn color_mask(s: &mut Session, p: &Value) -> Result<Value> {
if !SETTINGS.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return report(s, p);
}
let settings = Settings::read(p, COLOR_MASK)?;
// 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 = mask_changes(s, p, &settings, previewing.then_some(&mut kept));
s.decoded_images = kept;
let changes = found?;
let ids: Vec<u64> = changes.iter().map(|c| c.0.0).collect();
let hidden: u64 = changes.iter().map(|c| c.3).sum();
if !changes.is_empty() {
s.edit("Color Mask", |d, _| {
for (id, mask, blob, _) in changes {
if let Some(blob) = blob {
d.images.entry(mask.key.clone()).or_insert(blob);
}
if let Some(n) = d.node_mut(id) {
n.extras_mut().color_mask = Some(Box::new(mask));
}
}
Ok(())
})?;
}
Ok(json!({ "changed": ids.len(), "ids": ids, "hidden": hidden }))
}
/// The images `p` names whose mask changes, each with its new mask, the masked pixels to add (when
/// the document doesn't have them) and how many pixels they hide.
type MaskChange = (NodeId, ColorMask, Option<ImageBlob>, u64);
fn mask_changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Vec<MaskChange>> {
let st = s.doc()?;
// Each image's pixels once, however many objects show them.
let mut made: HashMap<&str, (String, Option<ImageBlob>, u64)> = HashMap::new();
let mut out = vec![];
for (id, im, blob) in images(s, p, COLOR_MASK)? {
let (key, pixels, hidden) = match made.get(im.key.as_str()) {
Some(m) => m.clone(),
None => {
let m = match masked(blob, settings, kept.as_deref_mut(), COLOR_MASK)? {
Some((key, blob, hidden)) => (key, Some(blob), hidden),
None => (im.key.clone(), None, 0),
};
made.insert(&im.key, m.clone());
m
}
};
let mask = settings.mask(key, im.key.clone());
if st.doc.node(id).and_then(Document::color_mask_of) == Some(&mask) {
continue;
}
// Masked pixels that hide something have an alpha channel, which a grayscale image
// colorized with a process color can't take. The pixels the new mask shows are checked,
// made from the image's own pixels, not the ones an earlier mask shows.
let shown = pixels.as_ref().or_else(|| st.doc.images.get(&mask.key));
if st.doc.node(id).is_some_and(|n| refused_colorize(&st.doc, n, shown)) {
return Err(bad(COLOR_MASK, PROCESS_ON_TRANSPARENCY));
}
let pixels = pixels.filter(|_| !st.doc.images.contains_key(&mask.key));
out.push((id, mask, pixels, hidden));
}
Ok(out)
}
/// Whether masked pixels `shown`, made for image node `n`, have transparency that `n`'s colorize
/// color can't take: gray pixels with an alpha channel and a process color
/// ([`colorized_with_process`]).
fn refused_colorize(doc: &Document, n: &Node, shown: Option<&ImageBlob>) -> bool {
shown.and_then(ImageBlob::gray_source).is_some_and(|g| g.alpha) && colorized_with_process(doc, n)
}
/// Color Mask without settings: the first image's mask settings, or the defaults. It reads them
/// for images a change would refuse too (CMYK, a linked image at its preview), so the dialog opens.
fn report(s: &Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let first = targets(s, p, COLOR_MASK)?.first().and_then(|id| st.doc.node(*id)).and_then(Document::color_mask_of).cloned();
let m = first.as_ref();
let hex = |c: &[u8; 3]| format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]);
let colors =
m.filter(|m| !m.colors.is_empty()).map_or_else(|| "#ffffff".to_string(), |m| m.colors.iter().map(hex).collect::<Vec<_>>().join(", "));
let name = |v: Value| v.as_str().map(str::to_string).unwrap_or_default();
Ok(json!({
"background": name(serde_json::to_value(m.map_or(MaskBackground::Edges, |m| m.background)).unwrap_or_default()),
"colors": colors,
"contiguous": m.is_none_or(|m| m.contiguous),
"match": name(serde_json::to_value(m.map_or(MaskMatch::Distance, |m| m.measure)).unwrap_or_default()),
"tolerance": m.map_or(10.0, |m| m.tolerance),
"softness": m.map_or(10.0, |m| m.softness),
"masked": m.is_some(),
}))
}
/// The image objects `p` names ([`targets`]: `ids`, or the selected images) that have a color mask.
fn masked_images(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
let st = s.doc()?;
Ok(targets(s, p, cmd)?.into_iter().filter(|id| st.doc.node(*id).and_then(Document::color_mask_of).is_some()).collect())
}
fn remove_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
let ids = masked_images(s, p, REMOVE_COLOR_MASK)?;
if !ids.is_empty() {
s.edit("Remove Color Mask", |d, _| {
for id in &ids {
if let Some(n) = d.node_mut(*id) {
n.extras_mut().color_mask = None;
}
}
Ok(())
})?;
}
Ok(json!({ "changed": ids.len(), "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>() }))
}
fn apply_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
let ids = masked_images(s, p, APPLY_COLOR_MASK)?;
// Each image's masked pixels, made again first when its own pixels changed since. A mask that
// hides nothing (its masked pixels are the image's own) is only taken off: the image keeps its
// pixels and its link.
let mut made = vec![];
{
let st = s.doc()?;
for id in &ids {
let Some(n) = st.doc.node(*id) else { continue };
let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { continue };
let mask = match fresh(&st.doc, n, APPLY_COLOR_MASK) {
Some(Ok(fresh)) => fresh,
Some(Err(e)) => return Err(e),
None => (m.clone(), None),
};
if mask.0.key == im.key {
made.push((*id, None));
continue;
}
let shown = st.doc.images.get(&mask.0.key).or(mask.1.as_ref());
if refused_colorize(&st.doc, n, shown) {
return Err(bad(APPLY_COLOR_MASK, PROCESS_ON_TRANSPARENCY));
}
let size = mask_size(shown, im.width, im.height);
made.push((*id, Some((mask, size))));
}
}
if !made.is_empty() {
s.edit("Apply Color Mask", |d, _| {
for (id, applied) in made {
let Some(n) = d.node_mut(id) else { continue };
n.extras_mut().color_mask = None;
let Some(((mask, blob), (w, h))) = applied else { continue };
if let Some(blob) = blob {
d.images.entry(mask.key.clone()).or_insert(blob);
}
let Some(n) = d.node_mut(id) else { continue };
if let NodeKind::Image(im) = &mut n.kind {
// Masked pixels of another size than the object's keep its place and size.
if (w, h) != (im.width, im.height) {
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(w), f64::from(im.height) / f64::from(h));
(im.width, im.height) = (w, h);
}
im.key = mask.key;
im.link = None;
}
}
Ok(())
})?;
}
Ok(json!({ "changed": ids.len(), "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>() }))
}
/// The size in pixels of masked pixels `blob` (from its header), or the object's when it can't be
/// read.
fn mask_size(blob: Option<&ImageBlob>, width: u32, height: u32) -> (u32, u32) {
blob.and_then(|b| image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok())
.filter(|(w, h)| *w > 0 && *h > 0)
.unwrap_or((width, height))
}
/// The mask of image node `n` made again for the image's own pixels, with the masked pixels when
/// `doc` doesn't have them: `None` when the mask is up to date (or `n` has none), an error when the
/// pixels can't be masked (missing, CMYK, a linked preview, too large, every pixel hidden, or
/// settings a file gave out of range).
fn fresh(doc: &Document, n: &Node, cmd: &str) -> Option<Result<(ColorMask, Option<ImageBlob>)>> {
let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { return None };
if !stale_mask(doc, n) {
return None;
}
let made = || -> Result<(ColorMask, Option<ImageBlob>)> {
let settings = Settings::of(m).ok_or_else(|| bad(cmd, "the color mask's settings are out of range"))?;
let blob = doc.images.get(&im.key).ok_or_else(|| bad(cmd, "the image's pixels are missing"))?;
if im.link.is_some() && blob.is_proxy() {
return Err(bad(cmd, "the linked image shows its preview: embed or relink it first"));
}
Ok(match masked(blob, &settings, None, cmd)? {
Some((key, blob, _)) => {
let blob = (!doc.images.contains_key(&key)).then_some(blob);
(settings.mask(key, im.key.clone()), blob)
}
None => (settings.mask(im.key.clone(), im.key.clone()), None),
})
};
Some(made())
}
/// After an edit from `before` (`None`: everything is new, as after a document's links are read):
/// the color masks of images in `doc`'s art ([`Document::art_roots`]: layers, symbols, graph
/// designs, patterns and the original of the pattern being edited, opacity mask art included)
/// whose own pixels were replaced are made again for the new pixels ([`Refresh::made`]). Only the
/// art that changed since `before` is looked at.
pub(crate) fn refresh(before: Option<&Document>, doc: &mut Document) {
let old: Vec<&Arc<Node>> = before.map(|b| b.art_roots().collect()).unwrap_or_default();
let mut pass = Refresh { doc: &*doc, made: HashMap::new(), blobs: vec![] };
let mut fixed = vec![];
for (i, root) in doc.art_roots().enumerate() {
let counterpart = old.get(i).copied().filter(|o| o.id == root.id);
if stale_in(doc, root, counterpart) {
let mut root = root.clone();
pass.fix(Arc::make_mut(&mut root));
fixed.push((i, root));
}
}
let blobs = pass.blobs;
if fixed.is_empty() {
return;
}
for (key, blob) in blobs {
doc.images.entry(key).or_insert(blob);
}
let mut fixed = fixed.into_iter().peekable();
for (i, root) in doc.art_roots_mut().enumerate() {
if fixed.peek().is_some_and(|(at, _)| *at == i)
&& let Some((_, new)) = fixed.next()
{
*root = new;
}
}
}
/// Whether `n`, or anything in it (opacity-mask art included), is an image whose mask is out of
/// date ([`stale_mask`]). What is the same as in `old`, `n`'s counterpart before an edit, is not
/// looked at.
fn stale_in(doc: &Document, n: &Arc<Node>, old: Option<&Arc<Node>>) -> bool {
if old.is_some_and(|o| Arc::ptr_eq(o, n)) {
return false;
}
if stale_mask(doc, n) {
return true;
}
let old_mask = old.and_then(|o| o.extras().mask.as_ref()).map(|m| &m.art);
if n.extras().mask.as_ref().is_some_and(|m| stale_in(doc, &m.art, old_mask)) {
return true;
}
let Some(children) = n.children() else { return false };
let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice);
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
children.iter().enumerate().any(|(i, c)| {
let b = match before.get(i) {
Some(b) if b.id == c.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
};
stale_in(doc, c, b)
})
}
/// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked
/// pixels `doc` doesn't have). A mask that hides nothing (its masked pixels are the image's own)
/// is up to date while the image's key stays the same, even when its pixels are missing.
fn stale_mask(doc: &Document, n: &Node) -> bool {
matches!((&n.kind, Document::color_mask_of(n)), (NodeKind::Image(im), Some(m))
if im.pixels.is_none() && !(m.made_for(im) && (m.key == im.key || doc.images.contains_key(&m.key))))
}
/// One [`refresh`] pass: the masks made so far, by the image's pixels, the mask's settings and
/// whether a process color colorizes the image (an image shown by many objects is decoded once),
/// and the masked pixels to add to the document.
struct Refresh<'a> {
doc: &'a Document,
made: HashMap<(String, String, bool), ColorMask>,
blobs: Vec<(String, ImageBlob)>,
}
impl Refresh<'_> {
/// Make the masks out of date in `n` (a copy of the document's art) again.
fn fix(&mut self, n: &mut Node) {
if let Some(mask) = self.made(n) {
n.extras_mut().color_mask = Some(Box::new(mask));
}
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& stale_in(self.doc, &m.art, None)
{
self.fix(Arc::make_mut(&mut m.art));
}
for c in n.children_mut().into_iter().flatten() {
if stale_in(self.doc, c, None) {
self.fix(Arc::make_mut(c));
}
}
}
/// The mask of image node `n` made again for the image's own pixels ([`fresh`]), `None` when
/// it is up to date. A mask that can't be made for them (every pixel hidden, CMYK pixels, a
/// linked preview, too large, gray pixels with transparency under a process color) keeps its
/// settings and hides nothing: the image shows its own pixels, and setting the mask again
/// reports why.
fn made(&mut self, n: &Node) -> Option<ColorMask> {
let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { return None };
if !stale_mask(self.doc, n) {
return None;
}
let settings = ColorMask { key: String::new(), from: String::new(), ..m.clone() };
let at = (im.key.clone(), format!("{settings:?}"), colorized_with_process(self.doc, n));
if let Some(made) = self.made.get(&at) {
return Some(made.clone());
}
let hides_nothing = || ColorMask { key: im.key.clone(), from: im.key.clone(), ..m.clone() };
let mask = match fresh(self.doc, n, COLOR_MASK)? {
Ok((mask, blob)) if refused_colorize(self.doc, n, blob.as_ref().or_else(|| self.doc.images.get(&mask.key))) => hides_nothing(),
Ok((mask, blob)) => {
self.blobs.extend(blob.map(|b| (mask.key.clone(), b)));
mask
}
Err(_) => hides_nothing(),
};
self.made.insert(at, mask.clone());
Some(mask)
}
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -392,7 +392,7 @@ fn the_color_profile_is_kept() {
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 out = super::clear(&blob, &settings(Background::Edges), None, super::C).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));
}
@@ -123,6 +123,10 @@ fn node_refs(n: &Node, f: Visit) {
if let Some(mask) = &m.extras().mask {
node_refs(&mask.art, f);
}
// A color-masked image's masked pixels go with it.
if let Some(cm) = Document::color_mask_of(m) {
f(Ref::Name(Res::Image, &cm.key));
}
match &m.kind {
NodeKind::Text(t) => {
for r in &t.runs {
@@ -663,6 +667,10 @@ impl Relink {
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
self.node(Arc::make_mut(&mut m.art));
}
if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) {
self.name(Res::Image, &mut cm.key);
self.name(Res::Image, &mut cm.from);
}
match &mut n.kind {
NodeKind::Text(t) => {
for r in &mut t.runs {
+5 -3
View File
@@ -884,8 +884,8 @@ fn blended(n: &Node) -> bool {
n.opacity < 1.0 || n.blend != BlendMode::Normal
}
/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`), a
/// colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in
/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`, a
/// color-masked image's masked pixels counted as its own), a colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in
/// `n`, or anywhere when `on`, also in the tile art of the pattern fills of the paths in `n`, down
/// to `levels` patterns. Hidden art doesn't count.
fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool, levels: u32) -> bool {
@@ -894,7 +894,9 @@ fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet<String>, colorize:
}
let on = on || blended(n);
match &n.kind {
NodeKind::Image(im) => on || keys.contains(&im.key) || (n.extras().colorize.is_some() && colorize(d, n)),
NodeKind::Image(im) => {
on || keys.contains(&im.key) || keys.contains(&d.shown_image(n, im).key) || (n.extras().colorize.is_some() && colorize(d, n))
}
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
n.appearance.items.iter().any(|i| pattern_fill_holds_transparent_image(d, i, keys, colorize, on, levels))
}
+4 -2
View File
@@ -185,7 +185,8 @@ fn expand_image_patterns(d: &mut Document) -> Result<()> {
}
/// The images of `d` a legacy `.ai` can't hold, in paint order with their places in it (as
/// [`Document::walk`] counts). These have see-through pixels or a colorize paint (except the
/// [`Document::walk`] counts). These have see-through pixels (a color-masked image's masked pixels
/// counted as its own) or a colorize paint (except the
/// colorized images the writer writes as image masks, clear pixels included,
/// [`vectorcraft_eps::writes_image_mask`]), or
/// have opacity or a blending mode of their own or, with `flatten`, of a group they are in.
@@ -197,7 +198,8 @@ fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> {
let mut at = 0;
d.walk(|n| {
if let NodeKind::Image(im) = &n.kind
&& (((keys.contains(&im.key) || n.extras().colorize.is_some()) && !vectorcraft_eps::writes_image_mask(d, n))
&& (((keys.contains(&im.key) || keys.contains(&d.shown_image(n, im).key) || n.extras().colorize.is_some())
&& !vectorcraft_eps::writes_image_mask(d, n))
|| n.opacity < 1.0
|| n.blend != BlendMode::Normal
|| (mode == SeeThrough::Flatten && transparent(d, n.id)))
+3 -2
View File
@@ -76,12 +76,13 @@ pub(crate) fn see_through_images(doc: &Document) -> BTreeSet<String> {
doc.images.iter().filter(|(_, b)| see_through(b)).map(|(k, _)| k.clone()).collect()
}
/// `n` shows an image of `keys` (itself or inside).
/// `n` shows an image of `keys` (itself or inside), a color-masked image's masked pixels counted as
/// what it shows.
pub(super) fn draws_image(n: &Node, keys: &BTreeSet<String>) -> bool {
!keys.is_empty()
&& n.visible
&& match &n.kind {
NodeKind::Image(im) => keys.contains(&im.key),
NodeKind::Image(im) => keys.contains(&im.key) || Document::color_mask_of(n).is_some_and(|m| m.made_for(im) && keys.contains(&m.key)),
_ => n.children().is_some_and(|ch| ch.iter().any(|c| draws_image(c, keys))),
}
}
+2 -1
View File
@@ -155,7 +155,8 @@ impl FlattenOptions {
/// the paint ([`vectorcraft_doc::ImageBlob::takes_colorize`]) never counts: it draws uncolorized.
pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool {
let NodeKind::Image(im) = &n.kind else { return true };
let blob = d.image_blob(im);
let shown = d.shown_image(n, im);
let blob = d.image_blob(&shown);
if blob.is_some_and(|b| !b.takes_colorize()) {
return false;
}
+2
View File
@@ -1060,6 +1060,8 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps
};
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
}
// Color masks of images whose files were read again are made for the new pixels.
super::refresh_color_masks(None, d);
out
}
+1 -1
View File
@@ -290,7 +290,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Mesh Line",
[],
None,
"{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}",
"{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y), inside or on the edge, to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge; at a point that is already a mesh point it adds no line, and records no undo step unless `color` changes a gradient mesh's point (a mesh envelope's points have no color) → {index}",
has_doc,
mesh_add_line
),
+39 -6
View File
@@ -122,9 +122,14 @@ fn with_mesh<T>(s: &mut Session, p: &Value, cmd: &str, label: &str, envelopes: b
/// Run `f` on the gradient mesh `id` of `d`; with `envelopes`, a mesh envelope's grid too (its
/// points and handles are written back: editing fills in the handles).
fn edit_grid<T>(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
match d.node_mut(id).map(|n| &mut n.kind) {
Some(NodeKind::Mesh(m)) => f(m),
Some(NodeKind::Envelope { kind, .. }) if envelopes && matches!(**kind, EnvelopeKind::Mesh { .. }) => {
edit_kind(&mut d.node_mut(id).ok_or(EngineError::NoNode(id))?.kind, cmd, envelopes, f)
}
/// [`edit_grid`] on a node's kind.
fn edit_kind<T>(k: &mut NodeKind, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
match k {
NodeKind::Mesh(m) => f(m),
NodeKind::Envelope { kind, .. } if envelopes && matches!(**kind, EnvelopeKind::Mesh { .. }) => {
let EnvelopeKind::Mesh { rows, cols, points, handles } = &mut **kind else {
return Err(bad(cmd, "not a gradient mesh or mesh envelope"));
};
@@ -135,8 +140,7 @@ fn edit_grid<T>(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: imp
*handles = m.points.iter().map(|q| q.handles).collect();
Ok(r)
}
Some(_) => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })),
None => Err(EngineError::NoNode(id)),
_ => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })),
}
}
@@ -281,12 +285,41 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["tolerance"], C)?;
let tol = f64_or(p, "tolerance", 0.0).max(0.0);
let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c));
let index = with_mesh(s, p, C, "Add Mesh Line", true, |m| {
let add = move |m: &mut GradientMesh| {
let i = m.add_lines_at(q, tol).ok_or_else(|| bad(C, "point is outside the mesh"))?;
if let Some(c) = color {
m.points[i].color = c;
}
Ok(i)
};
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
if s.script_running() {
return Err(EngineError::Busy);
}
// The lines are added to a copy of the object. A point that is already a mesh point adds none:
// when its color stays too, nothing changes and no undo step is recorded. The grid is compared,
// not the node: a mesh envelope stored without handles takes them in any edit, and keeps no
// colors, so only its points and handles count.
let orig = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind.clone();
let colored = matches!(orig, NodeKind::Mesh(_));
let mut kind = orig.clone();
let (i, same) = edit_kind(&mut kind, C, true, |m| {
let before = m.clone();
let i = add(m)?;
let shape = |g: &GradientMesh| (g.rows, g.cols, g.points.iter().map(|q| (q.p, q.handles)).collect::<Vec<_>>());
Ok((i, if colored { *m == before } else { shape(m) == shape(&before) }))
})?;
if same {
return Ok(json!({ "index": i }));
}
let index = s.edit("Add Mesh Line", move |d, _| {
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
// Settling typed values before the edit may have changed the object: add the lines again.
if n.kind != orig {
return edit_kind(&mut n.kind, C, true, add);
}
n.kind = kind;
Ok(i)
})?;
Ok(json!({ "index": index }))
}
+5
View File
@@ -1053,6 +1053,11 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
bare.blend = Default::default();
bare.appearance = Appearance::default().into();
bare.visible = true;
// The image's own pixels are cut, not the masked ones a color mask shows: the mask is made
// again for the cut pixels after the edit.
if let Some(e) = bare.extras_if_any() {
e.color_mask = None;
}
let tmp = isolated_doc(&st.doc, vec![bare]);
let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale);
let (png, w, h, warning) =
+13 -5
View File
@@ -716,7 +716,9 @@ fn colorized_images(d: &Document, ids: &[NodeId], paint: &Paint) -> std::result:
out.push(*id);
continue;
}
let Some(gray) = d.image_blob(im).and_then(|b| b.gray_source()) else { continue };
// A color-masked image is colorized as it shows: its masked pixels, which have an alpha
// channel.
let Some(gray) = d.image_blob(&d.shown_image(n, im)).and_then(|b| b.gray_source()) else { continue };
match paint {
// Without a color, `none` goes to the image's fill item.
Paint::None => continue,
@@ -773,11 +775,17 @@ pub(super) fn check_colorized_kept(was_ok: bool, d: &Document) -> std::result::R
if was_ok { check_colorized(d) } else { Ok(()) }
}
/// How the pixels of `n` are gray, when `n` is a grayscale or 1-bit image colorized with a color
/// that [`colorizes_transparency`] refuses. Such an image can't have an alpha channel.
/// Is `n` an image colorized with a color that [`colorizes_transparency`] refuses? When its pixels
/// are grayscale or 1-bit, they can't have an alpha channel.
pub(super) fn colorized_with_process(d: &Document, n: &Node) -> bool {
matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.as_deref().is_some_and(|paint| !colorizes_transparency(d, paint))
}
/// How the pixels `n` shows are gray, when `n` is a grayscale or 1-bit image colorized with a
/// color that [`colorizes_transparency`] refuses ([`colorized_with_process`]).
pub(super) fn gray_colorized_with_process(d: &Document, n: &Node) -> Option<GraySource> {
let (NodeKind::Image(im), Some(paint)) = (&n.kind, n.extras().colorize.as_deref()) else { return None };
if colorizes_transparency(d, paint) { None } else { d.image_blob(im).and_then(|b| b.gray_source()) }
let NodeKind::Image(im) = &n.kind else { return None };
if colorized_with_process(d, n) { d.image_blob(&d.shown_image(n, im)).and_then(|b| b.gray_source()) } else { None }
}
/// Is `e` the refusal of [`check_colorized`]?
+6
View File
@@ -78,6 +78,12 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
NodeKind::SymbolInstance { symbol, .. } => f(Ref::Symbol(symbol)),
_ => {}
}
// A color-masked image's masked pixels come along, and the key they were made from
// follows the image's.
if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) {
f(Ref::Image(&mut cm.key));
f(Ref::Image(&mut cm.from));
}
});
}
@@ -34,7 +34,10 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.contour.set",
"addon.cutting.bridges",
"addon.cutting.weed",
"addon.image.applyColorMask",
"addon.image.colorMask",
"addon.image.removeBackground",
"addon.image.removeColorMask",
"addon.pathtools.addPoints",
"addon.pathtools.close",
"addon.pathtools.corner",
+343 -44
View File
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Color Theme Picker",
[],
None,
"{picks: [{at: [x, y]} (a click: the object a Selection tool click there takes, with everything inside it) | {rect: [x0, y0, x1, y1]} (a marquee: every painted object it touches, and the part of each image inside it)] (1 to 256, in document points), colors?: 5 (1 to 64)} → {colors: [colour keys, the most used first], objects: the number of objects read} the colour palette of the art picked, for Recolor Artwork's Color Theme Picker: visible fills and strokes, gradient stops, text, mesh points, pattern tiles (with the patterns they use), the art of symbol instances (placed through their 9-slice guides), the colorize colour of an image it applies to and other images' pixels (at most 65,536 pixels of each pick of an image, spread evenly, and 1,048,576 pixels of at most 64 images in all; pixels less than half opaque and images that can't be decoded are left out). In a clip group, or under an opacity mask that clips, only what shows inside the clipping path or the mask art is read; a blend, envelope or repeat a marquee touches is read whole. Hidden or fully transparent objects and fill or stroke items are left out; locked objects are read. Each object read weighs the same, shared among its colours (an image's among its pixels; the vector art a symbol instance places counts as one object, each image it places on its own); similar colours merge (k-means in Lab) into at most `colors`, each shown by its most used colour in its own model. Picks that touch no art give no colours. Changes nothing",
"{picks: [{at: [x, y]} (a click: the object a Selection tool click there takes, with everything inside it) | {rect: [x0, y0, x1, y1]} (a marquee: every painted object it touches, and the part of each image inside it)] (1 to 256, in document points), colors?: 5 (1 to 64)} → {colors: [colour keys, the most used first], objects: the number of objects read} the colour palette of the art picked, for Recolor Artwork's Color Theme Picker: visible fills and strokes, gradient stops, text, mesh points, pattern tiles (with the patterns they use), the art of symbol instances (placed through their 9-slice guides), the colorize colour of an image it applies to and other images' pixels (at most 65,536 pixels of each pick of an image, spread evenly, and 1,048,576 pixels of at most 64 images in all; pixels less than half opaque and images that can't be decoded are left out). In a clip group, or under an opacity mask that clips, only what shows inside the clipping path or the mask art is read; a blend, envelope or repeat a marquee touches is read whole. The symbol instances read place at most 16,000,000 objects in all (an instance whose art would pass that is left out), and the pixels read inside clip groups are tested against at most 4,000,000 clipping-path elements in all (the picks of an image inside clip groups that would pass that are left out). Hidden or fully transparent objects and fill or stroke items are left out; locked objects are read. Each object read weighs the same, shared among its colours (an image's among its pixels; the vector art a symbol instance places counts as one object, each image it places on its own); similar colours merge (k-means in Lab) into at most `colors`, each shown by its most used colour in its own model. Picks that touch no art give no colours. Changes nothing",
has_doc,
pick_theme
),
@@ -75,8 +75,8 @@ const MAX_THEME_IMAGES: usize = 64;
const MAX_THEME_READS: usize = 4096;
/// The stroke segments the opacity masks one pick reads are outlined along, at most.
const MASK_OUTLINE_SEGMENTS: usize = 20_000;
/// The point-in-region tests one pick makes to find whether outlines show through clip groups,
/// and the clipping-path elements the pixels of one image are tested against, at most.
/// The point-in-region tests the picks make to find whether outlines show through clip groups,
/// and the clipping-path elements the pixels of their images are tested against, at most.
const THEME_WORK: usize = 4_000_000;
/// The picks one `recolor.pickTheme` takes, and the colours it gives, at most.
const MAX_PICKS: usize = 256;
@@ -126,6 +126,10 @@ struct ImageRead<'a> {
colorize: Option<Vec<Color>>,
}
/// A pattern's colours, the image reads of its tiles, and the depth its tiles were read at when
/// [`MAX_THEME_DEPTH`] cut them short.
type PatternRead<'a> = (Vec<Color>, Vec<ImageRead<'a>>, Option<usize>);
/// The colours the Color Theme Picker has read: each object weighs 1, shared among its colours.
struct Theme<'a> {
d: &'a Document,
@@ -138,11 +142,17 @@ struct Theme<'a> {
/// What the clip groups being read show, in document space: the union of these regions
/// (none: nothing shows); `None` outside clip groups.
clip: Option<Vec<Region>>,
/// The colours of the patterns read so far, and the patterns whose tiles are being read.
pattern_colors: HashMap<String, (Vec<Color>, Vec<ImageRead<'a>>)>,
/// The colours of the patterns read so far (with the depth their tiles were read at when
/// [`MAX_THEME_DEPTH`] cut them short), and the patterns whose tiles are being read.
pattern_colors: HashMap<String, PatternRead<'a>>,
pattern_stack: Vec<String>,
/// Whether art was left out for passing [`MAX_THEME_DEPTH`].
cut: bool,
/// The region tests [`Self::shows`] has made.
work: std::cell::Cell<usize>,
/// The objects the symbol instances read have placed, of [`vectorcraft_doc::MAX_SYMBOL_NODES`]
/// ([`vectorcraft_doc::charge_symbol_art`]).
symbol_nodes: u64,
/// The object isolated in isolation mode.
scope: Option<NodeId>,
/// The stroke segments opacity masks may still be outlined along ([`mask_regions`]).
@@ -170,8 +180,10 @@ impl<'a> Theme<'a> {
blobs: std::collections::HashSet::new(),
clip: None,
pattern_colors: HashMap::new(),
cut: false,
pattern_stack: vec![],
work: std::cell::Cell::new(0),
symbol_nodes: 0,
scope: None,
mask_budget: MASK_OUTLINE_SEGMENTS,
objects: 0,
@@ -192,8 +204,10 @@ impl<'a> Theme<'a> {
/// many there are, and the cells of all the reads add up, so the images give at most 16³
/// colours. Images that can't be decoded give none. The first [`MAX_THEME_IMAGES`] images
/// are read, and all the reads share [`THEME_TOTAL_PIXELS`] pixels (each read at least one, at
/// most [`THEME_PIXELS`]).
fn read_images(&mut self) {
/// most [`THEME_PIXELS`]). The pixels read inside clip groups are tested against
/// [`THEME_WORK`] clipping-path elements in all; the reads of an image inside clip groups
/// that would pass it are left out. Gives the clipping-path elements tested.
fn read_images(&mut self) -> usize {
let reads = std::mem::take(&mut self.images);
// The reads of each image, in the order its first read came.
let mut by_image: Vec<(*const vectorcraft_doc::ImageBlob, Vec<&ImageRead>)> = vec![];
@@ -208,15 +222,42 @@ impl<'a> Theme<'a> {
let count: usize = by_image.iter().map(|(_, g)| g.len()).sum();
let budget = (THEME_TOTAL_PIXELS / count.max(1)).clamp(1, THEME_PIXELS);
let mut pixels: HashMap<[u8; 3], ([f64; 3], f64)> = HashMap::new();
for (_, group) in by_image {
// The clipping-path elements the pixels read have been tested against.
let tested = std::cell::Cell::new(0usize);
let elements =
|r: &ImageRead| r.clip.as_ref().map_or(0, |rs| rs.iter().map(|(bp, _)| bp.elements().len().max(1)).fold(0, usize::saturating_add));
for (_, mut group) in by_image {
// Each pixel sampled for a read inside clip groups is tested against its clipping
// regions: the clipped reads of one image take at most `clipped` pixels each, so all
// of them keep within the work left, and the other reads take `budget`. When the work
// left can't test one pixel of each, the clipped reads are kept in order while their
// pixel fits, and the rest are left out.
let left = THEME_WORK.saturating_sub(tested.get());
if group.iter().map(|r| elements(r)).fold(0, usize::saturating_add) > left {
let mut room = left;
group.retain(|r| {
let c = elements(r);
let fits = c <= room;
room = room.saturating_sub(if fits { c } else { 0 });
fits
});
}
let cost = group.iter().map(|r| elements(r)).fold(0, usize::saturating_add);
let clipped = left.checked_div(cost).map_or(budget, |w| budget.min(w));
if group.is_empty() {
continue;
}
let keeps: Vec<Box<dyn Fn(f64, f64) -> bool + '_>> = group
.iter()
.map(|r| {
let (xf, (w, h), area, clip) = (r.xf, r.size, r.area, &r.clip);
let (xf, (w, h), area, clip, cost, tested) = (r.xf, r.size, r.area, &r.clip, elements(r), &tested);
Box::new(move |u: f64, v: f64| {
let p = xf * Point::new(u * w, v * h);
area.is_none_or(|a| a.contains(p))
&& clip.as_ref().is_none_or(|rs| rs.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p)))
&& clip.as_ref().is_none_or(|rs| {
tested.set(tested.get().saturating_add(cost));
rs.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p))
})
}) as Box<dyn Fn(f64, f64) -> bool + '_>
})
.collect();
@@ -241,15 +282,10 @@ impl<'a> Theme<'a> {
let high = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::NEG_INFINITY, f64::max);
[low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h]
});
(box_uv, keep.as_ref())
(box_uv, if r.clip.is_some() { clipped } else { budget }, keep.as_ref())
})
.collect();
// Each sampled pixel inside a clip group is tested against the clipping regions: the
// pixels one image gives keep that work within THEME_WORK path elements.
let elements =
group.iter().map(|r| r.clip.as_ref().map_or(0, |rs| rs.iter().map(|(bp, _)| bp.elements().len()).sum::<usize>())).max().unwrap_or(0);
let budget = THEME_WORK.checked_div(elements).map_or(budget, |w| budget.min(w.max(1)));
let Some(each) = group[0].blob.sample_pixels(&picks, budget) else { continue };
let Some(each) = group[0].blob.sample_pixels(&picks) else { continue };
for (px, read) in each.into_iter().zip(&group) {
if let Some(colors) = &read.colorize {
// Ink: an opaque pixel darker than white takes the colorize paint.
@@ -289,6 +325,7 @@ impl<'a> Theme<'a> {
let [r, g, b] = sum.map(|s| (s / w).round().clamp(0.0, 255.0) as u8);
self.samples.push((Color::rgb8(r, g, b), w as f32));
}
tested.get()
}
/// Read `n` and everything visible inside it: each image (its part inside `area` when given,
@@ -316,8 +353,12 @@ impl<'a> Theme<'a> {
/// [`Self::read`] without `n`'s opacity mask.
fn read_unmasked(&mut self, n: &Node, area: Option<Rect>, depth: usize) {
if depth > MAX_THEME_DEPTH {
self.cut = true;
return;
}
// Hidden and fully transparent objects show nothing.
if depth > MAX_THEME_DEPTH || !n.visible || n.opacity <= 0.0 || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
if !n.visible || n.opacity <= 0.0 || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
return;
}
let touches = area.is_none_or(|r| self.touches(n, r));
@@ -332,13 +373,13 @@ impl<'a> Theme<'a> {
// other paints its appearance has (with effects that draw them) count as well.
let colorized = n.extras().colorize.is_some() && blob.takes_colorize();
let own = if colorized || n.extras().colorize.is_none() {
self.own(n, true)
self.own(n, true, depth)
} else {
// A colorize paint the image does not take (a linked image's preview)
// shows nothing.
let mut plain = n.clone();
plain.extras_mut().colorize = None;
self.own(&plain, true)
self.own(&plain, true, depth)
};
let colorize = if colorized {
Some(own)
@@ -357,31 +398,43 @@ impl<'a> Theme<'a> {
&& self.shows(n, area)
&& let Some(s) = self.d.symbols.iter().find(|s| s.name == *symbol)
{
// The instance's own paints; its overrides show in its art.
let own = self.own(n, false);
self.add(own);
// The art as the instance places it: through the symbol's 9-slice guides when
// it has them, else by the instance's transform. Art that would place too many
// objects is left out, as the renderer leaves it out.
// it has them, else by the instance's transform. All the instances read share
// one limit on the objects they place, counted as the renderer counts them: an
// instance whose art would pass it shows nothing and is left out.
let dynamic = (!n.extras().symbol_overrides.is_empty()).then(|| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n));
if let Some(placed) = self.d.place_symbol_art(symbol, dynamic.as_ref().unwrap_or(&s.art), *xf) {
// The vector art counts as one object, each of its colours once, so an
// object the 9-slice guides cut into several copies does not count more.
// Each image placed is read on its own, as images are elsewhere.
let (samples, objects) = (self.samples.len(), self.objects);
self.read(&placed, None, depth + 1);
let added = self.samples.split_off(samples);
self.objects = objects;
let mut seen = std::collections::HashSet::new();
let colors: Vec<Color> = added.into_iter().map(|(c, _)| c).filter(|c| seen.insert(ColorKey::of(c))).collect();
self.add(colors);
}
let (d, art) = (self.d, dynamic.as_ref().unwrap_or(&s.art));
let placed = match d.symbol_slice_map(symbol, *xf) {
Some(m) => vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, m.most_placed(art, d), || {
let placed = d.place_symbol_art(symbol, art, *xf);
let n = placed.as_ref().map_or(0, |a| a.count_with_masks() as u64);
(placed, n)
}),
None => {
let count = art.count() as u64;
vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, count, || (d.place_symbol_art(symbol, art, *xf), count))
}
};
let Some(Some(placed)) = placed else { return };
// The instance's own paints; its overrides show in its art.
let own = self.own(n, false, depth);
self.add(own);
// The vector art counts as one object, each of its colours once, so an
// object the 9-slice guides cut into several copies does not count more.
// Each image placed is read on its own, as images are elsewhere.
let (samples, objects) = (self.samples.len(), self.objects);
self.read(&placed, None, depth + 1);
let added = self.samples.split_off(samples);
self.objects = objects;
let mut seen = std::collections::HashSet::new();
let colors: Vec<Color> = added.into_iter().map(|(c, _)| c).filter(|c| seen.insert(ColorKey::of(c))).collect();
self.add(colors);
}
return;
}
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) => {
if touches && self.shows(n, area) {
let own = self.own(n, true);
let own = self.own(n, true, depth);
self.add(own);
// The copies are drawn elsewhere than the objects lie: the clipping paths
// around the live object, tested above, do not apply to the objects.
@@ -396,7 +449,7 @@ impl<'a> Theme<'a> {
_ => {}
}
if touches && self.shows(n, area) {
let own = self.own(n, true);
let own = self.own(n, true, depth);
self.add(own);
}
// A compound path's members are its geometry: the compound paints them.
@@ -767,13 +820,16 @@ impl<'a> Theme<'a> {
/// document art is read (clip groups and symbols included; the tiles' images join this pick's
/// image reads). Each pattern's colours
/// are read once; a pattern whose tile uses itself, directly or through other patterns, adds
/// nothing more the second time.
fn own(&mut self, m: &Node, overrides: bool) -> Vec<Color> {
/// nothing more the second time. `depth` is `m`'s ([`Self::read`]): the tiles' art is read one
/// deeper, and a pattern whose tiles [`MAX_THEME_DEPTH`] cut short is read again when it is
/// used less deep.
fn own(&mut self, m: &Node, overrides: bool, depth: usize) -> Vec<Color> {
let mut out = vec![];
let mut patterns: Vec<String> = vec![];
paint_colors_of(m, overrides, &mut out, &mut patterns);
for name in patterns {
if let Some((colors, reads)) = self.pattern_colors.get(&name) {
if let Some((colors, reads, cut)) = self.pattern_colors.get(&name).filter(|e| e.2.is_none_or(|at| depth >= at)) {
self.cut |= cut.is_some();
out.extend(colors);
// The tiles' images count again for each use, within the pick's limits.
let reads = reads.clone();
@@ -795,10 +851,11 @@ impl<'a> Theme<'a> {
sub.blobs = std::mem::take(&mut self.blobs);
// The tiles share this pick's limits on work too.
sub.work.set(self.work.get());
sub.symbol_nodes = self.symbol_nodes;
sub.mask_budget = self.mask_budget;
let before = sub.images.len();
for a in &def.art {
sub.read(a, None, 0);
sub.read(a, None, depth + 1);
}
sub.pattern_stack.pop();
self.pattern_stack = std::mem::take(&mut sub.pattern_stack);
@@ -807,10 +864,12 @@ impl<'a> Theme<'a> {
self.images = std::mem::take(&mut sub.images);
self.blobs = std::mem::take(&mut sub.blobs);
self.work.set(sub.work.get());
self.symbol_nodes = sub.symbol_nodes;
self.mask_budget = sub.mask_budget;
self.cut |= sub.cut;
let colors: Vec<Color> = sub.samples.iter().map(|(c, _)| *c).collect();
out.extend(&colors);
self.pattern_colors.insert(name, (colors, reads));
self.pattern_colors.insert(name, (colors, reads, sub.cut.then_some(depth)));
}
out
}
@@ -1529,3 +1588,243 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
.collect();
Ok(json!({ "map": map }))
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use vectorcraft_doc::{Appearance, ImageBlob, MAX_SYMBOL_NODES, PatternDef, Symbol};
use vectorcraft_geom::{Affine, BezPath, FillRule, shapes};
use super::*;
const RED: Color = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 };
const BLUE: Color = Color::Rgb { r: 0.0, g: 0.0, b: 1.0 };
/// A 10 pt square from (`x`, 0) painted `fill`.
fn square(d: &mut Document, x: f64, fill: Paint) -> Arc<Node> {
let p = shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0));
Arc::new(Node::path(d.alloc_id(), p, Appearance::basic(fill, Paint::None, 0.0)))
}
/// Symbol `name` whose art is a group of `art`, and an instance of it.
fn symbol(d: &mut Document, name: &str, art: Vec<Arc<Node>>) -> Arc<Node> {
let group = Node::group(d.alloc_id(), art);
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(group) });
Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY }))
}
fn has(t: &Theme, c: Color) -> bool {
t.samples.iter().any(|(s, _)| ColorKey::of(s) == ColorKey::of(&c))
}
/// The symbol instances read share one limit on the objects they place: with room for one
/// instance's art (a group and a square, 2 objects), the first instance is read and the
/// second, of another symbol, is left out.
#[test]
fn symbol_instances_share_one_limit_on_placed_objects() {
let mut d = Document::new(100.0, 100.0);
let red = square(&mut d, 0.0, Paint::solid(RED));
let a = symbol(&mut d, "Red", vec![red]);
let blue = square(&mut d, 20.0, Paint::solid(BLUE));
let b = symbol(&mut d, "Blue", vec![blue]);
let mut t = Theme::new(&d);
t.symbol_nodes = MAX_SYMBOL_NODES - 3;
t.read(&a, None, 0);
t.read(&b, None, 0);
assert!(has(&t, RED), "the first instance fits");
assert!(!has(&t, BLUE), "the second does not");
assert_eq!(t.symbol_nodes, MAX_SYMBOL_NODES - 1);
}
/// An instance left out at the limit shows nothing, so its own paints are left out too.
#[test]
fn an_instance_past_the_limit_gives_none_of_its_own_paints() {
let mut d = Document::new(100.0, 100.0);
let red = square(&mut d, 0.0, Paint::solid(RED));
let mut inst = (*symbol(&mut d, "Red", vec![red])).clone();
inst.appearance = Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0).into();
let mut t = Theme::new(&d);
t.read(&inst, None, 0);
assert!(has(&t, BLUE), "the instance's own fill, with room for its art");
let mut t = Theme::new(&d);
t.symbol_nodes = MAX_SYMBOL_NODES - 1;
t.read(&inst, None, 0);
assert!(t.samples.is_empty() && t.objects == 0, "nothing past the limit: {:?}", t.samples);
}
/// An instance without 9-slice guides is counted as the renderer counts it, without the art of
/// its opacity masks: a square with a mask of 6 objects places 2.
#[test]
fn an_instance_is_counted_without_its_mask_art() {
let mut d = Document::new(100.0, 100.0);
let leaf = square(&mut d, 0.0, Paint::solid(BLUE));
let mut mask = vectorcraft_doc::OpacityMask::new(Node::group(d.alloc_id(), vec![leaf; 5]), true);
mask.disabled = true;
let mut red = (*square(&mut d, 0.0, Paint::solid(RED))).clone();
red.extras_mut().mask = Some(Box::new(mask));
let inst = symbol(&mut d, "Masked", vec![Arc::new(red)]);
let mut t = Theme::new(&d);
t.symbol_nodes = MAX_SYMBOL_NODES - 3;
t.read(&inst, None, 0);
assert!(has(&t, RED));
assert_eq!(t.symbol_nodes, MAX_SYMBOL_NODES - 1);
}
/// Nested instances charge the limit at every level: a tree of four leaf instances (5
/// objects) whose leaves place 2 objects each places 13 objects in all, and with 9 objects of
/// room it places the tree and two of its leaves.
#[test]
fn nested_symbol_instances_charge_every_level() {
let mut d = Document::new(100.0, 100.0);
let red = square(&mut d, 0.0, Paint::solid(RED));
let leaf = symbol(&mut d, "Leaf", vec![red]);
let tree = symbol(&mut d, "Tree", vec![leaf; 4]);
let mut t = Theme::new(&d);
t.read(&tree, None, 0);
assert_eq!(t.symbol_nodes, 13);
let mut t = Theme::new(&d);
t.symbol_nodes = MAX_SYMBOL_NODES - 9;
t.read(&tree, None, 0);
assert_eq!(t.symbol_nodes, MAX_SYMBOL_NODES, "the tree and two leaves");
assert!(has(&t, RED));
}
/// Patterns `P0` to `P{n}`: each tile a group holding a square filled with the next pattern,
/// the last a red square. Gives a square filled with `P0`.
fn pattern_chain(d: &mut Document, n: usize) -> Arc<Node> {
let fill = |i: usize| Paint::Pattern { pattern: format!("P{i}"), xf: Affine::IDENTITY };
for i in 0..=n {
let inner = if i == n { square(d, 0.0, Paint::solid(RED)) } else { square(d, 0.0, fill(i + 1)) };
let tile = Arc::new(Node::group(d.alloc_id(), vec![inner]));
d.patterns.push(PatternDef::new(&format!("P{i}"), vec![tile]));
}
square(d, 0.0, fill(0))
}
/// Pattern tiles are read one level deeper than the object their pattern fills, so a chain of
/// patterns shares one limit on depth with the art around it: the end of a chain of 50 is
/// read, the end of a chain of 200 (two levels for each tile) is not.
#[test]
fn pattern_tiles_share_one_depth_limit() {
let mut d = Document::new(100.0, 100.0);
let short = pattern_chain(&mut d, 50);
let mut t = Theme::new(&d);
t.read(&short, None, 0);
assert!(has(&t, RED), "a chain of 50");
let mut d = Document::new(100.0, 100.0);
let long = pattern_chain(&mut d, 200);
let p100 = square(&mut d, 0.0, Paint::Pattern { pattern: "P100".into(), xf: Affine::IDENTITY });
let mut t = Theme::new(&d);
t.read(&long, None, 0);
assert!(!has(&t, RED), "a chain of 200 passes {MAX_THEME_DEPTH} levels");
// The patterns cut short there are read again when used less deep: from P100 the end is
// 100 patterns away.
t.read(&p100, None, 0);
assert!(has(&t, RED), "P100 read again at the top");
}
/// A pattern tile's symbol instances charge the same limit as the art around it.
#[test]
fn pattern_tiles_charge_the_symbol_limit() {
let mut d = Document::new(100.0, 100.0);
let red = square(&mut d, 0.0, Paint::solid(RED));
let inst = symbol(&mut d, "Red", vec![red]);
d.patterns.push(PatternDef::new("Dots", vec![inst]));
let art = square(&mut d, 0.0, Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY });
let mut t = Theme::new(&d);
t.read(&art, None, 0);
assert!(has(&t, RED));
assert_eq!(t.symbol_nodes, 2, "the tile's instance placed a group and a square");
let mut t = Theme::new(&d);
t.symbol_nodes = MAX_SYMBOL_NODES - 1;
t.read(&art, None, 0);
assert!(!has(&t, RED), "no room for the tile's instance");
}
/// A `size` px image of one color `rgba`.
fn blob(rgba: [u8; 4], size: u32) -> ImageBlob {
let mut png = Vec::new();
image::RgbaImage::from_pixel(size, size, image::Rgba(rgba)).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
ImageBlob::png(png)
}
/// A read of all of `blob`, placed at the origin 1 pt a pixel, inside a clipping path over
/// it of `elements` path elements.
fn clipped(blob: &ImageBlob, size: f64, elements: usize) -> ImageRead<'_> {
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
let steps = elements.saturating_sub(4).max(1);
for i in 1..=steps {
bp.line_to((size * i as f64 / steps as f64, 0.0));
}
bp.line_to((size, size));
bp.line_to((0.0, size));
bp.close_path();
ImageRead { blob, xf: Affine::IDENTITY, size: (size, size), area: None, clip: Some(vec![(bp, FillRule::NonZero)]), colorize: None }
}
/// The reads of one image inside clip groups share the work limit: three reads of a 64 px
/// image, each inside a clipping path of 3,000 elements, test at most [`THEME_WORK`] elements
/// in all and still read the image.
#[test]
fn reads_of_one_image_share_the_clip_work_limit() {
let d = Document::new(100.0, 100.0);
let red = blob([255, 0, 0, 255], 64);
let mut t = Theme::new(&d);
t.images = (0..3).map(|_| clipped(&red, 64.0, 3000)).collect();
let tested = t.read_images();
assert!(tested > 0 && tested <= THEME_WORK, "{tested} elements tested");
assert!(has(&t, RED));
}
/// A read of an image outside clip groups keeps its own pixel budget when another read of the
/// same image inside a clip group gets only two pixels: the blue 8 px block in the corner of a
/// red 64 px image is still read.
#[test]
fn unclipped_reads_keep_their_budget_beside_clipped_reads() {
let d = Document::new(100.0, 100.0);
let red = blob([255, 0, 0, 255], 64);
let mut png = Vec::new();
image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba(if x >= 56 && y >= 56 { [0, 0, 255, 255] } else { [255, 0, 0, 255] }))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let corner = ImageBlob::png(png);
let mut t = Theme::new(&d);
let whole = ImageRead { clip: None, ..clipped(&corner, 64.0, 4) };
// The red read leaves 6,400 elements of work; 3,200 elements a pixel leave two pixels.
t.images = vec![clipped(&red, 64.0, 3900), whole, clipped(&corner, 64.0, 3200)];
let tested = t.read_images();
assert!(tested <= THEME_WORK, "{tested} elements tested");
assert!(has(&t, BLUE), "the read outside clip groups samples the whole image");
}
/// When the work left can't test a pixel of every clipped read of an image, the reads that fit
/// are still read: with 6,400 elements left, a read of a blue image inside a clipping path
/// of 5,000 elements is read beside one of 2,000 elements, which is left out.
#[test]
fn clipped_reads_that_fit_the_work_left_are_read() {
let d = Document::new(100.0, 100.0);
let (red, blue) = (blob([255, 0, 0, 255], 64), blob([0, 0, 255, 255], 64));
let mut t = Theme::new(&d);
t.images = vec![clipped(&red, 64.0, 3900), clipped(&blue, 64.0, 5000), clipped(&blue, 64.0, 2000)];
let tested = t.read_images();
assert!(tested <= THEME_WORK, "{tested} elements tested");
assert!(has(&t, BLUE), "the read that fits is read");
}
/// Past the work limit, the reads of an image inside clip groups are left out: a red image
/// inside a clipping path of 3,900 elements takes nearly all of it, and a blue image after it,
/// inside one of 100,000 elements, is not read.
#[test]
fn clipped_image_reads_past_the_work_limit_are_left_out() {
let d = Document::new(100.0, 100.0);
let (red, blue) = (blob([255, 0, 0, 255], 64), blob([0, 0, 255, 255], 64));
let mut t = Theme::new(&d);
t.images = vec![clipped(&red, 64.0, 3900), clipped(&blue, 64.0, 100_000)];
let tested = t.read_images();
assert!(tested <= THEME_WORK, "{tested} elements tested");
assert!(has(&t, RED));
assert!(!has(&t, BLUE), "the blue image is past the limit");
}
}
+2
View File
@@ -31,6 +31,8 @@ impl Session {
}
// Pixel-aligned objects the edit changed go back on the pixel grid.
cmd::refresh_pixel_aligned(&before, doc);
// Color masks of images whose own pixels the edit replaced are made for the new ones.
cmd::refresh_color_masks(Some(&*before), doc);
let placed = cmd::objects_on_path::refresh(&before, doc);
// Pixel-aligned members that placing moved go back on the pixel grid.
cmd::keep_aligned_in(doc, &placed);
+23
View File
@@ -123,6 +123,29 @@ fn reset_with_warp_and_mesh_switch_the_kind_and_keep_the_content() {
assert!(s.execute("object.envelope.resetWithMesh", &json!({})).is_err());
}
/// `object.mesh.addLine` at a point a mesh envelope already has (one stored without handles) adds
/// no line and records no undo step, with or without a `color`; a point between its lines adds
/// them as one step.
#[test]
fn mesh_envelope_add_line_at_a_mesh_point_records_no_undo_step() {
let mut s = session();
let (_, e) = enveloped(&mut s, "object.envelope.makeWithMesh", json!({"rows": 2, "cols": 2}));
let before = kind(&s, e);
assert!(matches!(&before, EnvelopeKind::Mesh { handles, .. } if handles.is_empty()), "{before:?}");
let undo_len = |s: &Session| s.doc().unwrap().history.undo.len();
let n = undo_len(&s);
for (x, y) in [(100.0, 100.0), (300.0, 200.0), (200.0, 150.0), (300.0, 150.0)] {
s.execute("object.mesh.addLine", &json!({"id": e.0, "x": x, "y": y})).unwrap();
assert_eq!((kind(&s, e), undo_len(&s)), (before.clone(), n), "({x}, {y}): nothing changed");
}
// An envelope's points carry no color, so a color there changes nothing either.
s.execute("object.mesh.addLine", &json!({"id": e.0, "x": 200, "y": 150, "color": "#00ff00"})).unwrap();
assert_eq!((kind(&s, e), undo_len(&s)), (before.clone(), n), "a color changes nothing");
s.execute("object.mesh.addLine", &json!({"id": e.0, "x": 150, "y": 125})).unwrap();
assert!(matches!(kind(&s, e), EnvelopeKind::Mesh { rows: 3, cols: 3, .. }), "{:?}", kind(&s, e));
assert_eq!(undo_len(&s), n + 1);
}
/// A new warp envelope bends with its style's Bézier net (`version` [`live::WARP_NET`]) and keeps
/// it through Reset with Warp. One saved before the version existed keeps the earlier map when its
/// warp or its options change.
+41
View File
@@ -1184,6 +1184,47 @@ fn mesh_add_line_on_the_edge_from_just_outside() {
assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 140, "y": 210, "tolerance": 3})).is_err(), "past the tolerance");
}
/// `object.mesh.addLine` and Create Gradient Mesh `at` a point exactly on the outline add their
/// lines there with no tolerance, on the bottom and right edges as on the top and left ones.
#[test]
fn mesh_add_line_exactly_on_the_edge_needs_no_tolerance() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
sel(&mut s, &[a]);
let r = s.execute("object.mesh.create", &json!({"at": [50, 100]})).unwrap();
let m = mesh_of(&s, a);
assert_eq!((m.rows, m.cols), (1, 2), "a column through the bottom edge");
assert!(m.points[r["index"].as_u64().unwrap() as usize].p.distance(Point::new(50.0, 100.0)) < 0.5);
for (x, y) in [(100.0, 30.0), (20.0, 0.0), (0.0, 80.0)] {
let r = s.execute("object.mesh.addLine", &json!({"id": a.0, "x": x, "y": y})).unwrap();
let p = mesh_of(&s, a).points[r["index"].as_u64().unwrap() as usize].p;
assert!(p.distance(Point::new(x, y)) < 0.5, "({x}, {y}): {p:?}");
}
assert_eq!((mesh_of(&s, a).rows, mesh_of(&s, a).cols), (3, 3));
let n = undo_len(&s);
assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 60, "y": 100.01})).is_err(), "just outside");
assert_eq!(undo_len(&s), n, "nothing changed");
}
/// `object.mesh.addLine` at a point that is already a mesh point (a corner, a point on an edge or
/// inside) adds no line and records no undo step; with a new `color` there it is one step.
#[test]
fn mesh_add_line_at_a_mesh_point_records_no_undo_step() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
sel(&mut s, &[a]);
s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap();
let (before, n) = (mesh_of(&s, a), undo_len(&s));
for (x, y) in [(0.0, 0.0), (100.0, 100.0), (50.0, 100.0), (100.0, 50.0), (50.0, 50.0)] {
let r = s.execute("object.mesh.addLine", &json!({"id": a.0, "x": x, "y": y})).unwrap();
let p = mesh_of(&s, a).points[r["index"].as_u64().unwrap() as usize].p;
assert!(p.distance(Point::new(x, y)) < 0.5, "({x}, {y}): {p:?}");
assert_eq!((mesh_of(&s, a), undo_len(&s)), (before.clone(), n), "({x}, {y}): nothing changed");
}
s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 100, "y": 100, "color": "#00ff00"})).unwrap();
assert_eq!(undo_len(&s), n + 1, "a new color is a step");
}
/// A mesh point `index`, and `rows`, `cols` or `columns` for Create Gradient Mesh, that is not a
/// whole number is an error that changes nothing; 4.0 names point 4.
#[test]