Merge main into fix/painted-type-used-as-a-clipping-path-loses-its

This commit is contained in:
dotCooCoo committed 2026-11-15 06:21:19 -08:00
commit a7cfe02b08
237 files changed
+14355 -1074

No files matched your search

Generated
+2
View File
@@ -6632,6 +6632,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"vectorcraft-brush",
"vectorcraft-doc",
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
@@ -6929,6 +6930,7 @@ name = "vectorcraft-ui-egui"
version = "0.24.1"
dependencies = [
"bytemuck",
"chrono",
"craft-keymap",
"craft-ui",
"craft-update",
+7
View File
@@ -120,6 +120,13 @@ impl StoredArt {
doc.number_mounted_art();
}
/// Sets the art on `doc` as [`Document::mounted_art`] with the ids it is stored with, the id
/// counter left as it is: what a save looks through, writing back only the brushes whose art it
/// changed ([`Self::write_back`]).
pub fn mount_as_stored(&self, doc: &mut Document) {
doc.mounted_art = self.entries.iter().flat_map(|e| e.art.iter().cloned()).collect();
}
/// Takes [`Document::mounted_art`] off `doc` and writes each brush whose art changed (new ids
/// included) back into its library entry: the entry at its index when that entry is as it was
/// read or reads as the brush as it was apart from its name, else the first entry that reads as
+155 -4
View File
@@ -618,13 +618,25 @@ pub fn icc_color_space(icc: &[u8]) -> Option<[u8; 4]> {
icc.get(16..20)?.try_into().ok()
}
/// The ICC profile of TIFF tag 34675 (ICCProfile) of the image `d` reads; `None` without one.
/// The most bytes of an ICC profile a TIFF's tag 34675 is read with (16 MiB).
const MAX_TIFF_ICC: u64 = 16 << 20;
/// The ICC profile of TIFF tag 34675 (ICCProfile, of type UNDEFINED or BYTE) of the image `d`
/// reads, as its bytes; `None` without one and for one over [`MAX_TIFF_ICC`] bytes.
fn tiff_icc(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> Option<Vec<u8>> {
d.get_tag_u8_vec(tiff::tags::Tag::IccProfile).ok().filter(|icc| !icc.is_empty())
use tiff::tags::{Tag, Type, ValueBuffer};
let mut ifd = d.image_ifd();
let entry = ifd.find_entry(Tag::IccProfile)?;
if !matches!(entry.field_type(), Type::UNDEFINED | Type::BYTE) || entry.count() == 0 || entry.count() > MAX_TIFF_ICC {
return None;
}
let mut buf = ValueBuffer::empty(Type::UNDEFINED);
ifd.find_tag_buf(Tag::IccProfile, &mut buf).ok()??;
Some(buf.as_bytes().to_vec())
}
/// The ICC profile of TIFF `bytes`' first image (tag 34675), read with the `tiff` decoder's own
/// limits, whatever the size of the image; `None` for other images and TIFFs without one.
/// The ICC profile of TIFF `bytes`' first image (tag 34675), up to [`MAX_TIFF_ICC`] bytes whatever
/// the size of the image; `None` for other images, TIFFs without one and a longer one.
pub fn tiff_icc_profile(bytes: &[u8]) -> Option<Vec<u8>> {
let (_, mut d) = tiff(bytes)?;
tiff_icc(&mut d)
@@ -638,6 +650,61 @@ fn jpeg_icc(bytes: &[u8]) -> Option<Vec<u8>> {
d.icc_profile().filter(|icc| !icc.is_empty())
}
/// The bytes after an `ICC_PROFILE` APP2 segment's length: its name, then the segment's number and
/// the count of segments.
const ICC_SEGMENT: &[u8; 12] = b"ICC_PROFILE\0";
/// JPEG `bytes` carrying `icc` in place of the ICC profile they carry, if any: every
/// `ICC_PROFILE` APP2 segment before the scan taken out, `icc` written as numbered APP2 segments
/// after the leading application segments, and the other segments and the scan as they are. `None`
/// for bytes whose segments before the scan can't be read, an empty `icc`, and one longer than 255
/// segments hold.
pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option<Vec<u8>> {
// A segment's length counts itself (2 bytes) and the name, number and count (14).
const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2;
let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect();
let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?;
if !bytes.starts_with(&[0xFF, 0xD8]) {
return None;
}
let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len());
for (i, chunk) in chunks.iter().enumerate() {
let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?;
segments.extend_from_slice(&[0xFF, 0xE2]);
segments.extend_from_slice(&len.to_be_bytes());
segments.extend_from_slice(ICC_SEGMENT);
segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]);
segments.extend_from_slice(chunk);
}
let mut out = Vec::with_capacity(bytes.len() + segments.len());
out.extend_from_slice(&[0xFF, 0xD8]);
let mut icc_segments = Some(segments);
let mut at = 2;
// The segments before the scan (SOS), each with its length; a marker without one ends them.
// Fill bytes (0xFF) before a marker are left out.
loop {
while bytes.get(at..at + 2) == Some(&[0xFF, 0xFF]) {
at += 1;
}
let (Some(&0xFF), Some(&marker)) = (bytes.get(at), bytes.get(at + 1)) else { return None };
let app = (0xE0..=0xEF).contains(&marker);
if !app && let Some(s) = icc_segments.take() {
out.extend_from_slice(&s);
}
if matches!(marker, 0xDA | 0xD8 | 0xD9 | 0x01 | 0xD0..=0xD7) {
break;
}
let len = usize::from(u16::from_be_bytes(bytes.get(at + 2..at + 4)?.try_into().ok()?));
let segment = bytes.get(at..(at + 2).checked_add(len)?).filter(|_| len >= 2)?;
if !(marker == 0xE2 && segment.get(4..16) == Some(ICC_SEGMENT.as_slice())) {
out.extend_from_slice(segment);
}
at += segment.len();
}
out.extend_from_slice(bytes.get(at..)?);
Some(out)
}
/// `icc` when it is a profile of CMYK colors, which the samples of a CMYK image are in.
fn cmyk_icc(icc: Option<Vec<u8>>) -> Option<Vec<u8>> {
icc.filter(|icc| icc_color_space(icc) == Some(*b"CMYK"))
@@ -746,6 +813,14 @@ impl ImageBlob {
Some(Self::new("image/tiff", tiff))
}
/// [`ImageBlob::cmyk_tiff`], carrying `icc` as tag 34675 (ICCProfile) when it is a profile of
/// CMYK colors; any other profile is left out. The caller checks the rest of the profile.
pub fn cmyk_tiff_with_icc(inks: &Inks, icc: Option<&[u8]>) -> Option<Self> {
let icc = icc.filter(|icc| icc_color_space(icc) == Some(*b"CMYK"));
let tiff = write_cmyk_tiff(inks.width, inks.height, SampleSlice::Eight(&inks.data), None, icc)?;
Some(Self::new("image/tiff", tiff))
}
/// Does the image hold CMYK samples (a four-component JPEG or a CMYK TIFF)? Reads only its
/// header.
pub fn is_cmyk(&self) -> bool {
@@ -1968,6 +2043,35 @@ mod tests {
assert_eq!(rgb.get_pixel(1, 0).0, [0, 255, 255]);
}
/// A CMYK TIFF written with a CMYK profile carries it byte for byte as tag 34675; a profile of
/// other colors, and none, leave the TIFF untagged. The inks are the same either way.
#[test]
fn a_cmyk_tiff_carries_the_cmyk_profile_it_is_given() {
let profile = |space: &[u8; 4]| {
let mut icc = vec![0u8; 128];
icc[0..4].copy_from_slice(&128u32.to_be_bytes());
icc[16..20].copy_from_slice(space);
icc[36..40].copy_from_slice(b"acsp");
icc
};
let cmyk = profile(b"CMYK");
let b = ImageBlob::cmyk_tiff_with_icc(&inks(), Some(&cmyk)).unwrap();
assert_eq!(b.cmyk_icc_profile(), Some(cmyk), "the profile, byte for byte");
assert_eq!(b.cmyk(), Some(inks()));
// Read back up to 16 MiB; a longer one isn't read.
for (len, read) in [(16 << 20, true), ((16 << 20) + 1, false)] {
let mut big = profile(b"CMYK");
big.resize(len, 0);
let b = ImageBlob::cmyk_tiff_with_icc(&inks(), Some(&big)).unwrap();
assert_eq!(b.cmyk_icc_profile().is_some_and(|p| p == big), read, "{len} bytes");
}
for icc in [Some(profile(b"RGB ")), None] {
let b = ImageBlob::cmyk_tiff_with_icc(&inks(), icc.as_deref()).unwrap();
assert_eq!(tiff_icc_profile(&b.bytes), None, "{icc:?}");
assert_eq!(b.cmyk(), Some(inks()));
}
}
#[test]
fn a_header_gives_the_size_without_the_samples() {
assert_eq!(ImageBlob::cmyk_tiff(&inks()).unwrap().header_size(), Some((3, 2)));
@@ -2031,6 +2135,53 @@ mod tests {
}
}
/// A CMYK JPEG given a profile carries it in place of its own, its samples as they were; a
/// profile longer than 255 segments hold, an empty one and bytes that aren't a JPEG give none.
#[test]
fn a_cmyk_jpeg_carries_the_profile_it_is_given() {
let profile = |len: usize, mark: u8| {
let mut icc = vec![mark; len];
icc[16..20].copy_from_slice(b"CMYK");
icc
};
let px: Vec<u8> = (0..16 * 16).flat_map(|_| [10u8, 40, 100, 20]).collect();
let mut jpg = Vec::new();
let mut e = jpeg_encoder::Encoder::new(&mut jpg, 100);
e.add_icc_profile(&profile(300_000, 1)).unwrap();
e.encode(&px, 16, 16, jpeg_encoder::ColorType::Cmyk).unwrap();
let inks = ImageBlob::new("image/jpeg", jpg.clone()).cmyk().unwrap();
// One segment holds 65,519 bytes of a profile.
for len in [128, 65_519, 65_520, 300_000, 1 << 20] {
let icc = profile(len, 2);
let b = ImageBlob::new("image/jpeg", jpeg_with_icc(&jpg, &icc).unwrap());
assert!(b.cmyk_icc_profile() == Some(icc), "{len} bytes");
assert!(b.cmyk() == Some(inks.clone()), "{len} bytes: the samples as they were");
}
// A profile segment after the quantization table is taken out too.
let dqt = jpg.windows(2).position(|w| w == [0xFF, 0xDB]).unwrap();
let after = dqt + 2 + usize::from(u16::from_be_bytes([jpg[dqt + 2], jpg[dqt + 3]]));
let mut late = jpg.clone();
let stale = profile(128, 3);
let segment = [&[0xFF, 0xE2, 0, 144][..], ICC_SEGMENT, &[1, 1], &stale].concat();
late.splice(after..after, segment);
let icc = profile(128, 2);
let b = jpeg_with_icc(&late, &icc).unwrap();
assert_eq!(b.windows(ICC_SEGMENT.len()).filter(|w| *w == ICC_SEGMENT).count(), 1, "one profile segment");
assert!(ImageBlob::new("image/jpeg", b).cmyk_icc_profile() == Some(icc));
// Fill bytes before the quantization table's marker are passed over.
let mut filled = jpg.clone();
filled.splice(dqt..dqt, [0xFF; 3]);
assert!(ImageBlob::new("image/jpeg", filled.clone()).cmyk() == Some(inks.clone()), "the decoder reads it");
let icc = profile(128, 2);
let b = ImageBlob::new("image/jpeg", jpeg_with_icc(&filled, &icc).unwrap());
assert!(b.cmyk_icc_profile() == Some(icc), "fill bytes");
assert!(b.cmyk() == Some(inks.clone()), "fill bytes: the samples as they were");
assert!(jpeg_with_icc(&jpg, &profile(255 * 65_519, 2)).is_some(), "255 segments");
assert!(jpeg_with_icc(&jpg, &profile(255 * 65_519 + 1, 2)).is_none(), "256 segments");
assert!(jpeg_with_icc(&jpg, &[]).is_none(), "empty");
assert!(jpeg_with_icc(&ImageBlob::cmyk_tiff(&inks).unwrap().bytes, &profile(128, 2)).is_none(), "a TIFF");
}
#[test]
fn other_images_are_not_cmyk() {
let mut png = Vec::new();
+145 -11
View File
@@ -266,6 +266,7 @@ pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip
/// (`opt.scope`) or on a locked artboard. On a layer whose Preview is off it counts by its
/// outline, as a click there hits it.
pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &[NodeId]) -> Option<NodeId> {
let _walk = ArtWalk::open();
let symbols = doc.symbol_boxes();
let locks = doc.locked_artboards();
selected.iter().rev().copied().find(|&id| {
@@ -322,6 +323,7 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option<Hi
/// The objects under `p` that [`Hit::top_object`] picks in `scope` (isolation mode), topmost
/// first: what clicks there select, one below the other (Cmd/Ctrl-click selects behind).
pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>) -> Vec<NodeId> {
let walk = ArtWalk::open();
let opt = HitOptions { scope: scope.or(opt.scope), ..opt };
// Normally one hit test per *object* suffices: layers and sublayers aren't selectable,
// while a group (including a clipping group) is selected as one object. Repeatedly
@@ -337,6 +339,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
for layer in doc.layers.iter().rev() {
// Malformed files may contain non-layer roots; let the general traversal handle them.
if !layer.is_layer() {
walk.restart();
return objects_at_repeated(doc, p, opt, scope);
}
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
@@ -344,7 +347,9 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
}
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
// An envelope in Edit Contents may expose objects *within* a top-level group.
// The repeated traversal handles that mixed hierarchy precisely.
// The repeated traversal handles that mixed hierarchy precisely, with the whole
// limit of symbol art to walk.
walk.restart();
return objects_at_repeated(doc, p, opt, scope);
}
}
@@ -429,6 +434,7 @@ pub const MAX_LOCKED_AT: usize = 20;
/// out. While a pattern is edited only its tile layer is searched, and in isolation mode
/// (`opt.scope`) only what is inside the isolated group or object.
pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeId> {
let _walk = ArtWalk::open();
let symbols = doc.symbol_boxes();
let mut out = Vec::new();
if let Some(scope) = opt.scope
@@ -506,6 +512,7 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
let _walk = ArtWalk::open();
let finish = |mut h: Hit| {
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
@@ -1059,9 +1066,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
}
// A symbol instance is hit within its bounds, and outside them where its art paints
// ([`instance_art_hit`]).
// ([`instance_art_hit`]). In the art of another instance walked outside that instance's
// bounds, it is hit only where its own art paints ([`ArtOnly`]).
NodeKind::SymbolInstance { .. } => {
if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
return Some(HitKind::Bounds);
}
instance_art_hit(n, p, opt, symbols)
@@ -1172,6 +1180,15 @@ impl<'a> InstanceArt<'a> {
whole.or_else(|| self.map.as_ref()?.one_cell_with(n, &self.boxes))
}
/// How many objects placing the whole art makes: the objects of the art with their opacity
/// masks' art ([`Node::count_with_masks`]), or, through the guides, the most that
/// [`crate::NineSliceMap::most_placed_with`] counts.
fn size(&self) -> u64 {
self.map
.as_ref()
.map_or_else(|| u64::try_from(self.art.count_with_masks()).unwrap_or(u64::MAX), |m| m.most_placed_with(&self.art, &self.boxes))
}
/// Object `n` of the art placed on the canvas as it is drawn, clip groups included: moved by
/// `whole` when an object around it is moved as one piece ([`Self::whole`]). `None` when
/// placing it through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects, as
@@ -1219,6 +1236,7 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or
/// no editable object of its art is under `p`.
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
let _walk = ArtWalk::open();
let art = InstanceArt::of(doc, inst)?;
let symbols = doc.symbol_boxes();
let mut path = vec![];
@@ -1250,7 +1268,7 @@ impl FindPart<'_> {
/// What a click at `p` hits on object `n` of the art, with `path` the child indices that lead
/// to what it hits. `outline`: the view is in Outline, or a layer around `n` has Preview off.
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> Option<HitKind> {
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) {
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || !ArtWalk::take(1) {
return None;
}
let outline = outline || previews_off(n);
@@ -1298,17 +1316,120 @@ impl FindPart<'_> {
/// Outline, [`HitOptions::outline`]): its strokes, and the art that the live geometry effects of a
/// clipping path in it show past the art's box. `None` for an instance of a missing symbol, of a
/// symbol that holds an instance of itself or nests too deep ([`SymbolBoxes::art`]), and of art past
/// the 9-slice object limit ([`InstanceArt::of`]).
/// the 9-slice object limit ([`InstanceArt::of`]), when `p` is outside the instance's reach
/// ([`Node::reach_bounds_with`]), and once the click has visited as many objects of symbol art as
/// [`ArtWalk`] allows.
fn instance_art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return None };
if opt.outline || symbols.art(symbol).is_none() {
if opt.outline || symbols.art(symbol).is_none() || !n.reach_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
return None;
}
let _walk = ArtWalk::open();
if ArtWalk::used_up() {
return None;
}
let art = InstanceArt::of(symbols.document(), n)?;
#[cfg(test)]
ARTS_WALKED.with(|c| c.set(c.get() + 1));
let opt = HitOptions { clip_outlines: false, ..opt };
let _art_only = ArtOnly::set();
FindPart { art: &art, p, opt, symbols, whole_instance: true }.find(&art.art, &mut vec![], None, false)
}
thread_local! {
/// Whether a symbol instance's art is being walked outside the instance's box ([`ArtOnly`]).
static ART_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// While a guard lives, a symbol instance is hit ([`hit_leaf`]) and touched by a marquee
/// ([`marquee_with`]) only where its own art is, by the same rule at every level, and not anywhere
/// in its box. [`instance_art_hit`] and the marquee's walk of an instance's art hold one: they walk
/// the art outside the instance's box, where the box of an instance nested in the art can reach
/// past it over empty space.
struct ArtOnly {
was: bool,
}
impl ArtOnly {
fn set() -> Self {
Self { was: ART_ONLY.replace(true) }
}
fn on() -> bool {
ART_ONLY.get()
}
}
impl Drop for ArtOnly {
fn drop(&mut self) {
ART_ONLY.set(self.was);
}
}
thread_local! {
/// How many more objects of symbol art the click or marquee under way may visit ([`ArtWalk`]),
/// `None` outside one.
static ART_WALK_LEFT: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
}
#[cfg(test)]
thread_local! {
/// The number of objects [`ArtWalk::open`] allows on this thread in place of
/// [`crate::MAX_SYMBOL_NODES`].
static ART_WALK_LIMIT: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
/// How many symbol instances' art clicks and marquees walked on this thread.
static ARTS_WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The objects of symbol art that one click or one marquee may visit: [`crate::MAX_SYMBOL_NODES`]
/// in all, the art of the instances nested in that art included, at every level. The first
/// [`ArtWalk::open`] of a click or a marquee sets the limit, and the walks opened while its guard
/// lives share it. Once the limit is used up, an instance is no longer hit or touched outside its
/// box; inside its box it still is.
struct ArtWalk {
outermost: bool,
}
impl ArtWalk {
fn open() -> Self {
let walk = Self { outermost: ART_WALK_LEFT.get().is_none() };
walk.restart();
walk
}
/// For the outermost guard, sets what is left back to the whole limit.
fn restart(&self) {
if self.outermost {
#[cfg(test)]
let limit = ART_WALK_LIMIT.get().unwrap_or(crate::MAX_SYMBOL_NODES);
#[cfg(not(test))]
let limit = crate::MAX_SYMBOL_NODES;
ART_WALK_LEFT.set(Some(limit));
}
}
/// Is nothing left?
fn used_up() -> bool {
ART_WALK_LEFT.get() == Some(0)
}
/// Takes `n` objects from what is left. `false` when fewer are left, and nothing is left after.
fn take(n: u64) -> bool {
let Some(left) = ART_WALK_LEFT.get() else { return true };
let rest = left.checked_sub(n);
ART_WALK_LEFT.set(Some(rest.unwrap_or(0)));
rest.is_some()
}
}
impl Drop for ArtWalk {
fn drop(&mut self) {
if self.outermost {
ART_WALK_LEFT.set(None);
}
}
}
/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks
/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it
/// does not count.
@@ -1502,6 +1623,7 @@ fn previews_off(n: &Node) -> bool {
}
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
let _walk = ArtWalk::open();
let mut out = Vec::new();
// The objects the marquee may touch ([`Top`]).
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
@@ -1613,8 +1735,9 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
// A symbol instance is touched by its box, and outside it where the live geometry
// effects of a clipping path in its art show the art.
NodeKind::SymbolInstance { .. } => box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds),
// effects of a clipping path in its art show the art. In the art of another instance
// walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]).
NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds),
_ => box_touches(n, s, r),
}
}
@@ -1628,15 +1751,26 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
}
/// Does the marquee `r` touch the art of symbol instance `n` placed as the canvas draws it, as
/// it touches a group of that art? Only for art whose clipping paths have live geometry effects
/// ([`SymbolBoxes::art`]), and only when `r` meets the instance's reach
/// ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's box.
/// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the
/// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's
/// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows.
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false };
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
if s.art(symbol).is_none_or(|a| a.reshaped.is_none()) || !n.reach_bounds_with(s).is_some_and(meets) {
if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) {
return false;
}
let _walk = ArtWalk::open();
if ArtWalk::used_up() {
return false;
}
let Some(art) = InstanceArt::of(s.document(), n) else { return false };
if !ArtWalk::take(art.size()) {
return false;
}
#[cfg(test)]
ARTS_WALKED.with(|c| c.set(c.get() + 1));
let _art_only = ArtOnly::set();
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false))
}
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
+179
View File
@@ -1961,6 +1961,185 @@ fn a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box() {
assert_eq!(at(108.0, HitOptions { outline: true, ..HitOptions::default() }), None, "Outline view");
}
/// Outside a symbol instance's box, an instance nested in its art counts where its own art is, not
/// anywhere in its box: a click or a marquee on empty space in the nested box, where a moved
/// clipping path shows the art past the outer box, selects nothing, and on art drawn there it
/// selects the outer instance.
#[test]
fn a_nested_symbol_instances_box_past_the_outer_box_is_not_a_hit() {
set_clip_region(moved_clip_region);
// `Two` draws squares at the corners of 0..200 × 0..100, and with `middle` one at 140..160 ×
// 40..60. The outer symbol clips an instance of it to 0..100 × 0..100, which `test.move` moves
// to 100..200: the outer box is 0..100, the nested box 0..200.
let build = |middle: bool| {
let mut d = Document::new(600.0, 400.0);
let l = d.layers[0].id;
let square = |d: &mut Document, r: Rect| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()));
let mut squares = vec![square(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)), square(&mut d, Rect::new(190.0, 90.0, 200.0, 100.0))];
if middle {
squares.push(square(&mut d, Rect::new(140.0, 40.0, 160.0, 60.0)));
}
group_symbol(&mut d, "Two", squares);
let (mut mask, _) = half_clipped(&mut d);
mask.appearance.effects.push(test_move());
let nested = instance_of(&mut d, "Two");
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), nested]);
clip.set_clips(true);
group_symbol(&mut d, "Outer", vec![Arc::new(clip)]);
let inst = d.alloc_id();
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Outer".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
(d, inst)
};
let at = |d: &Document, x: f64, y: f64| hit_test(d, Point::new(x, y), HitOptions::default()).map(|h| h.leaf);
let inside = Rect::new(145.0, 45.0, 155.0, 55.0);
let (d, inst) = build(false);
assert_eq!(at(&d, 150.0, 50.0), None, "empty space in the nested box");
assert!(marquee(&d, inside, None, false).is_empty(), "marquee on empty space in the nested box");
assert_eq!(at(&d, 195.0, 95.0), Some(inst), "on the nested art past the outer box");
assert_eq!(at(&d, 50.0, 50.0), Some(inst), "in the outer box");
let (d, inst) = build(true);
assert_eq!(at(&d, 150.0, 50.0), Some(inst), "on the nested art");
// Across the middle square's left edge.
assert_eq!(marquee(&d, Rect::new(135.0, 45.0, 145.0, 55.0), None, false), [inst], "marquee on the nested art");
}
/// Adds the symbol `Clipped`: a clip group whose clipping path's region `test.move` moves to
/// 100..200 × 0..100, past the 0..100 box, over a 0..200 × 0..100 rectangle shown when `shown`.
/// A click at (150, 50) hits an instance of it on the rectangle, or, with the rectangle hidden,
/// walks its art and finds nothing.
fn clipped_symbol(d: &mut Document, shown: bool) {
set_clip_region(moved_clip_region);
let (mut mask, mut art) = half_clipped(d);
mask.appearance.effects.push(test_move());
art.visible = shown;
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
let root = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
d.symbols.push(crate::Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(root) });
}
/// A symbol named `name` whose art is a group of `members`.
fn group_symbol(d: &mut Document, name: &str, members: Vec<Arc<Node>>) {
let root = Node::group(d.alloc_id(), members);
d.symbols.push(crate::Symbol { dynamic: false, name: name.into(), art: Arc::new(root) });
}
/// An instance of the symbol named `symbol`, not moved.
fn instance_of(d: &mut Document, symbol: &str) -> Arc<Node> {
Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }))
}
/// 30 small squares at the origin, which a click at (150, 50) passes by.
fn far_squares(d: &mut Document) -> Vec<Arc<Node>> {
(0..30).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()))).collect()
}
/// Runs `f` with [`ArtWalk`] allowing `limit` objects, and returns its result with how many
/// leaves [`hit_leaf`] tested and how many instances' art was walked meanwhile.
fn with_art_limit<R>(limit: u64, f: impl FnOnce() -> R) -> (R, usize, usize) {
ART_WALK_LIMIT.with(|c| c.set(Some(limit)));
LEAVES_TESTED.with(|c| c.set(0));
ARTS_WALKED.with(|c| c.set(0));
let r = f();
ART_WALK_LIMIT.with(|c| c.set(None));
(r, LEAVES_TESTED.with(std::cell::Cell::get), ARTS_WALKED.with(std::cell::Cell::get))
}
/// One click visits at most the art walk's limit of objects in a chain of nested symbol
/// instances, though each level's art alone is well within it. A click on the art of an
/// instance nested in another is still found.
#[test]
fn a_click_walks_a_chain_of_nested_symbol_instances_within_one_limit() {
// Level 0 is `Clipped`; each level above holds an instance of the level below and 30 squares:
// 32 objects to visit at each level.
let chain = |shown: bool| {
let mut d = Document::new(600.0, 400.0);
let l = d.layers[0].id;
clipped_symbol(&mut d, shown);
for level in 1..12 {
let below = if level == 1 { "Clipped".to_string() } else { format!("Level {}", level - 1) };
let mut members = vec![instance_of(&mut d, &below)];
members.extend(far_squares(&mut d));
group_symbol(&mut d, &format!("Level {level}"), members);
}
let inst = instance_of(&mut d, "Level 11");
let id = inst.id;
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
(d, id)
};
let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf);
// Without one limit for the click, the miss walks the art of all 12 levels.
let (d, inst) = chain(false);
let (hit, _, arts) = with_art_limit(100, || at(&d, 150.0));
assert_eq!(hit, None);
assert!(arts <= 4, "{arts} levels walked");
assert_eq!(with_art_limit(100, || at(&d, 50.0)).0, Some(inst), "in the box");
// Past the limit, a click that the art would take finds only the box.
let (d, inst) = chain(true);
assert_eq!(with_art_limit(100, || at(&d, 150.0)).0, None, "past the limit");
assert_eq!(at(&d, 150.0), Some(inst), "within the limit");
// Two levels: a click on the inner instance's art is found within the limit.
let mut d = Document::new(600.0, 400.0);
let l = d.layers[0].id;
clipped_symbol(&mut d, true);
let inner = instance_of(&mut d, "Clipped");
group_symbol(&mut d, "Outer", vec![inner]);
let inst = instance_of(&mut d, "Outer");
let id = inst.id;
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
assert_eq!(with_art_limit(100, || at(&d, 150.0)).0, Some(id), "nested");
}
/// One click, and one marquee, visit at most the art walk's limit of objects in art that repeats
/// one nested instance many times, though the art of each instance alone is well within it. A
/// click on one of the nested instances' art is still found.
#[test]
fn a_click_and_a_marquee_walk_repeated_nested_symbol_instances_within_one_limit() {
// 50 instances of `Clipped` in one symbol's art, its rectangle shown when `shown`.
let repeated = |shown: bool| {
let mut d = Document::new(600.0, 400.0);
let l = d.layers[0].id;
clipped_symbol(&mut d, shown);
let members = (0..50).map(|_| instance_of(&mut d, "Clipped")).collect();
group_symbol(&mut d, "Repeated", members);
let inst = instance_of(&mut d, "Repeated");
let id = inst.id;
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
(d, id)
};
let (d, inst) = repeated(false);
// Without one limit for the click, the miss walks the art of all 51 instances. The outer art
// takes 1 object of the 100, and each nested instance with its art 4.
let (hit, _, arts) = with_art_limit(100, || hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).map(|h| h.leaf));
assert_eq!(hit, None);
assert!(arts <= 26, "{arts} instances' art walked");
// Select Behind over 60 instances of `Clipped` on the layer shares one limit too: each walk
// takes 3 objects of the 100.
let mut stack = Document::new(600.0, 400.0);
let l = stack.layers[0].id;
clipped_symbol(&mut stack, false);
for _ in 0..60 {
let inst = instance_of(&mut stack, "Clipped");
stack.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
}
let (behind, _, arts) = with_art_limit(100, || objects_at(&stack, Point::new(150.0, 50.0), HitOptions::default(), None));
assert!(behind.is_empty());
assert!(arts <= 34, "Select Behind: {arts} instances' art walked");
// Without one limit for the marquee, it places the art of all 51 instances, inside the moved
// region (within each instance's reach and outside its box). Placing the outer art takes 51
// objects of the 100, and each nested art 4.
let inside = Rect::new(140.0, 40.0, 160.0, 60.0);
let (touched, _, arts) = with_art_limit(100, || marquee(&d, inside, None, false));
assert!(touched.is_empty());
assert!(arts <= 14, "{arts} instances' art placed");
assert_eq!(with_art_limit(100, || marquee(&d, Rect::new(40.0, 40.0, 60.0, 60.0), None, false)).0, [inst], "in the box");
// A click and a marquee on the nested instances' art are found within the limit.
let (d, inst) = repeated(true);
assert_eq!(with_art_limit(100, || hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).map(|h| h.leaf)).0, Some(inst), "click");
let edge = Rect::new(140.0, -5.0, 160.0, 5.0);
assert_eq!(with_art_limit(100, || marquee(&d, edge, None, false)).0, [inst], "marquee across the art's edge");
}
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
/// canvas draws nothing of it. At the art's natural size the same art is picked.
+31 -3
View File
@@ -281,7 +281,13 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
});
}
b += match &n.kind {
NodeKind::Path { path, live, .. } => path_bytes(path) + boxed(live),
NodeKind::Path { path, live, .. } => {
let was = other.and_then(|o| match &o.kind {
NodeKind::Path { path, .. } => Some(path),
_ => None,
});
path_bytes_besides(path, was) + boxed(live)
}
NodeKind::Layer { children, .. }
| NodeKind::Group { children, .. }
| NodeKind::Compound { children, .. }
@@ -298,8 +304,30 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
}
fn path_bytes(p: &PathData) -> usize {
let anchors: usize =
p.subpaths.iter().map(|s| if s.anchors.capacity() == 0 { 0 } else { ALLOC + s.anchors.capacity() * size_of::<Anchor>() }).sum();
path_bytes_besides(p, None)
}
/// [`path_bytes`] without the anchor chunks that `other` (another version of the path) holds too:
/// a version made by changing one anchor shares every chunk but the one it changed.
fn path_bytes_besides(p: &PathData, other: Option<&PathData>) -> usize {
let mut shared: Vec<usize> =
other.map(|o| o.subpaths.iter().flat_map(|s| s.anchors.chunk_allocations()).map(|(id, _)| id).collect()).unwrap_or_default();
shared.sort_unstable();
let chunk = ALLOC + ARC + size_of::<Vec<Anchor>>() + ALLOC;
let anchors: usize = p
.subpaths
.iter()
.map(|s| {
let table = s.anchors.table_bytes();
let own: usize = s
.anchors
.chunk_allocations()
.filter(|(id, _)| shared.binary_search(id).is_err())
.map(|(_, capacity)| chunk + capacity * size_of::<Anchor>())
.sum();
if table == 0 { own } else { ALLOC + table + own }
})
.sum();
anchors + if p.subpaths.capacity() == 0 { 0 } else { ALLOC + p.subpaths.capacity() * size_of::<SubPath>() }
}
+34 -4
View File
@@ -17,22 +17,52 @@ pub enum Justify {
JustifyAll,
}
/// Paragraph composer (Paragraph panel menu): how lines are broken.
/// Paragraph composer (Paragraph panel menu): how lines are broken, and whether complex scripts
/// (Indic, Arabic, Hebrew) are shaped. `SingleLine` and `EveryLine` are the Middle Eastern & South
/// Asian composers: they shape complex scripts with the font's layout tables, as all type is set
/// here, and are what documents saved before the four composers existed use. The `Standard`
/// composers break lines the same way but set a complex script glyph by glyph as the font maps its
/// characters, with no conjuncts, marks placed or joining forms: what fonts that keep a script's
/// glyphs on Latin character codes (legacy ANSI Indic fonts) need.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Composer {
/// Break each line as soon as it is full.
/// Middle Eastern & South Asian Single-line Composer: break each line as soon as it is full.
SingleLine,
/// Total fit over the whole paragraph (Illustrator's default): justified lines get even word
/// spacing, ragged lines an even rag.
/// Middle Eastern & South Asian Every-line Composer: total fit over the whole paragraph
/// (Illustrator's default): justified lines get even word spacing, ragged lines an even rag.
#[default]
EveryLine,
/// Standard Single-line Composer: [`Composer::SingleLine`]'s breaks, complex scripts not shaped.
StandardSingleLine,
/// Standard Every-line Composer: [`Composer::EveryLine`]'s breaks, complex scripts not shaped.
StandardEveryLine,
}
impl Composer {
fn is_default(&self) -> bool {
*self == Self::default()
}
/// Does this composer break lines one at a time (as opposed to a total fit)?
pub fn is_single_line(self) -> bool {
matches!(self, Self::SingleLine | Self::StandardSingleLine)
}
/// Does this composer shape complex scripts ([`Composer::SingleLine`], [`Composer::EveryLine`])?
pub fn shapes_complex_scripts(self) -> bool {
matches!(self, Self::SingleLine | Self::EveryLine)
}
/// The same shaping with the other line breaking (`single_line`: one line at a time).
pub fn with_breaking(self, single_line: bool) -> Self {
match (single_line, self.shapes_complex_scripts()) {
(true, true) => Self::SingleLine,
(true, false) => Self::StandardSingleLine,
(false, true) => Self::EveryLine,
(false, false) => Self::StandardEveryLine,
}
}
}
/// A paragraph's hyphenation options (Paragraph panel menu › Hyphenation…): which words automatic
+1 -1
View File
@@ -859,7 +859,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
crate::SVG_FILTER,
"SVG Filter",
&["Effect", "SVG Filters"],
"{name: string (the filter's id), xml: string (one SVG <filter> element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)",
"{name: string (the filter's id), xml: string (one SVG <filter> element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document), axes?: [a, b, c, d] (absent or [1, 0, 0, 1]: the document's axes, and not null; the document directions of one unit along the filter's x axis [a, b] and y axis [c, d] before scale, each -1000..1000, with a·d - b·c at least 0.001 from 0; a turned, skewed or unevenly scaled user space, as SVG import gives a filtered element under a rotate, skew or uneven scale; the filter's offsets, blurs and region run along these axes; moving, turning or skewing the object moves origin and leaves axes)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)",
json!({"scale": 1.0, "origin": [0.0, 0.0]}),
));
v
+4 -1
View File
@@ -81,7 +81,10 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry};
pub use raster::{
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_map, staged_effects,
without_geometry,
};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
+54 -1
View File
@@ -606,9 +606,62 @@ fn transform_step(e: &Effect) -> Option<Affine> {
(copies == 0 && !flag(&p, "random", false)).then(|| map.with_translation(Vec2::ZERO))
}
/// The Transform effects of `effects` that move the image of its last visible Rasterize effect
/// instead of the art it is made from: the indices of the visible Transform effects listed after
/// it that move the art, when from the first visible Transform effect after it on every visible
/// effect is a Transform effect that moves the art once (no copies, not at random). Effects apply
/// in the order they are listed, so the image is made of the art before those Transform effects
/// and moves with them, its pixel grid and room around the art included. `None` when there is no
/// such Transform effect, or the effects after the Rasterize effect hold anything else from there
/// on.
pub fn rasterize_stage(effects: &[Effect]) -> Option<Vec<usize>> {
let r = effects.iter().rposition(|e| e.visible && e.id == RASTERIZE)?;
let first = r + 1 + effects.get(r + 1..)?.iter().position(|e| e.visible && e.id == "distort.transform")?;
let mut at = vec![];
for (i, e) in effects.iter().enumerate().skip(first).filter(|(_, e)| e.visible) {
if e.id != "distort.transform" || transform_step(e).is_none() {
return None;
}
if crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).0 != Affine::IDENTITY {
at.push(i);
}
}
(!at.is_empty()).then_some(at)
}
/// `effects` with the Transform effects at `at` hidden ([`rasterize_stage`]): what the image of
/// the Rasterize effect before them is made from.
pub fn staged_effects(effects: &[Effect], at: &[usize]) -> Vec<Effect> {
let mut out = effects.to_vec();
for &i in at {
if let Some(e) = out.get_mut(i) {
e.visible = false;
}
}
out
}
/// The map the Transform effects at `at` of `effects` ([`rasterize_stage`]) move the Rasterize
/// image by, for `staged`, the geometry the effects before them make: each one's map about its
/// reference point on the bounds of the geometry it takes, as the geometry pass applies it, the
/// last one outermost. `None` when `staged` is empty or the map is not a number.
pub fn stage_map(effects: &[Effect], at: &[usize], staged: &vectorcraft_geom::PathData) -> Option<Affine> {
let mut cur = staged.clone();
let mut b = staged.bounds()?;
let mut map = Affine::IDENTITY;
for &i in at {
let e = effects.get(i)?;
let (m, _) = crate::distort::transform_map(b, &merged_params(&e.id, &e.params), 0);
map = m * map;
cur = cur.transformed(m);
b = cur.bounds().unwrap_or(b);
}
map.is_finite().then_some(map)
}
/// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG
/// filter does not, and neither does Rasterize, whose image keeps its own pixel grid and room
/// around the art.
/// around the art: the image moves with those Transform effects instead ([`rasterize_stage`]).
pub(crate) fn follows(id: &str) -> bool {
crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE
}
+56 -7
View File
@@ -171,7 +171,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
}
}
}
let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0));
let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| crate::solids::shadow::casts(paint_of(i).1 * s.opacity)));
return check_shadow(p, casting.map(|s| &s.path), b, options);
}
let (path, _) = object_profile(n, "Revolve")?;
@@ -350,8 +350,8 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
/// The shadow of Revolve `fx` cast by the surface of `path` in `item`'s paint about the axis of
/// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with
/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when
/// the surface it is cast from is past the limits.
/// the shadow off, when `item` is fully transparent or its opacity is not a finite number, or when
/// it casts nothing, and an error when the surface it is cast from is past the limits.
///
/// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the
/// surface is swept again for its shadow alone.
@@ -366,7 +366,7 @@ fn shadow_of(
) -> Result<Option<Node>, String> {
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) };
let (_, opacity, blend) = paint_of(item);
if opacity <= 0.0 {
if !crate::solids::shadow::casts(opacity) {
return Ok(None);
}
let mut caster = vectorcraft_three_d::ShadowCaster::new();
@@ -377,7 +377,7 @@ fn shadow_of(
/// Does Revolve `fx` cast a shadow, so a surface in paint as opaque as `opacity` keeps the faces
/// its shadow is cast from ([`surface`])?
fn casts(fx: &Effect, opacity: f32) -> bool {
opacity > 0.0 && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some()
crate::solids::shadow::casts(opacity) && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some()
}
/// Add the surface of `path` about the axis of `b` to `caster`: the faces it kept when it was
@@ -420,9 +420,9 @@ fn group_shadow(
for s in shapes {
let kept = kept.next().flatten();
let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue };
// A member whose surface is fully transparent casts nothing.
// A member whose surface is fully transparent, or whose opacity is not a finite number, casts nothing.
let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend };
if ink.opacity <= 0.0 {
if !ink.casts() {
continue;
}
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
@@ -1861,6 +1861,55 @@ mod tests {
}
}
}
/// A surface whose fill, or whose member, is at NaN or infinite opacity casts no shadow, as one
/// at 0 % does, whether the shadow is cast from the surface drawn or swept for it alone; the
/// member beside it still casts its part.
#[test]
fn a_surface_whose_opacity_is_not_a_finite_number_casts_no_shadow() {
let fx = crate::new_effect(REVOLVE, &json!({"shadow": true})).unwrap();
let group = |opacity: f32| {
let mut other = profile_node();
other.id = NodeId(2);
other.transform(Affine::translate((120.0, 0.0)), false);
other.opacity = opacity;
let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]);
g.appearance.effects.push(fx.clone());
g
};
let group_shadows = |g: &Node| {
let shapes = members(g, "").unwrap();
let b = union_bounds(&shapes).unwrap();
let options = shared_options(&shapes, fx_options(&fx)).unwrap();
let kept: Vec<Option<SolidFaces>> = shapes
.iter()
.map(|s| {
let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap());
let cast = casts(&fx, opacity * s.opacity);
surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2
})
.collect();
[group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(), group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap()]
.map(|art| format!("{art:?}"))
};
let expected = group_shadows(&group(0.0));
for bad in [f32::NAN, f32::INFINITY] {
let mut n = profile_node();
if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] {
f.opacity = bad;
}
let (path, _) = profile(&n).unwrap();
let b = path.bounds().unwrap();
let item = surface_item(&n.appearance.items).unwrap();
assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow");
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn");
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone");
let shadows = group_shadows(&group(bad));
assert!(!expected[0].is_empty() && expected[0] != "[]", "the opaque member casts");
assert_eq!(shadows, expected, "{bad}: only the opaque member casts");
}
}
}
#[cfg(test)]
+10 -10
View File
@@ -1474,8 +1474,8 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
let view = view_options(p);
let mut caster = vectorcraft_three_d::ShadowCaster::new();
// The faces each solid of visible art added, with its member's scopes and its ink (opacity
// and blending mode), in order. A fully transparent fill or stroke (or member) casts nothing
// and does not place the plane.
// and blending mode), in order. A fill or stroke (or member) that is fully transparent, or whose
// opacity is not a finite number, casts nothing and does not place the plane ([`shadow::Ink::casts`]).
let mut cast: Vec<shadow::Cast> = vec![];
let ink = |item: &AppearanceItem, member: f32| {
let (_, opacity, blend) = paint_of(item, member);
@@ -1483,7 +1483,7 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
};
if id == ROTATE {
for s in shapes {
for item in s.items.iter().filter(|i| ink(i, s.opacity).opacity > 0.0) {
for item in s.items.iter().filter(|i| ink(i, s.opacity).casts()) {
let (area, rule) = region(&s.path, s.rule, item);
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
@@ -1497,7 +1497,7 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
// Inflate's eye is placed for every shape together, as the solids are.
let added: Vec<Result<std::ops::Range<usize>, String>> = if id == INFLATE {
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
let casts: Vec<bool> = inks.iter().map(|i| i.opacity > 0.0).collect();
let casts: Vec<bool> = inks.iter().map(|i| i.casts()).collect();
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len()));
caster.inflate(&shapes, &casts, bounds, inflate_options(p), view)
@@ -1505,13 +1505,13 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
let mut added = vec![];
for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) {
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.opacity > 0.0)));
added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts())));
added.push(if ink.casts() { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
}
added
};
for (((item, _, _, _, scopes, _), ink), faces) in parts.iter().zip(inks).zip(added) {
if ink.opacity <= 0.0 {
if !ink.casts() {
continue;
}
// A stroke whose own solid is past the limits is left out; past the shadow's limit for
@@ -1552,7 +1552,7 @@ fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<
}
for ((s, item), kept) in items.into_iter().zip(built) {
let ink = ink(item, s.opacity);
if ink.opacity <= 0.0 {
if !ink.casts() {
continue;
}
let faces = match kept {
@@ -1570,11 +1570,11 @@ fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<
}
let (parts, bounds) = solid_parts(shapes, b);
let inks: Vec<shadow::Ink> = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect();
if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.opacity > 0.0 && kept.is_none())) {
if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.casts() && kept.is_none())) {
return cast_shadow(id, p, shapes);
}
for (((item, _, area, rule, scopes, _), ink), kept) in parts.iter().zip(inks).zip(built) {
if ink.opacity <= 0.0 {
if !ink.casts() {
continue;
}
let faces = match kept {
+13
View File
@@ -50,6 +50,19 @@ pub(crate) struct Ink {
pub(crate) blend: BlendMode,
}
impl Ink {
/// Whether art in this ink casts part of a shadow ([`casts`]).
pub(crate) fn casts(self) -> bool {
casts(self.opacity)
}
}
/// Whether art at `opacity` casts part of a shadow: its opacity is a finite number above zero.
/// Art at zero, negative, NaN or infinite opacity casts nothing.
pub(crate) fn casts(opacity: f32) -> bool {
opacity.is_finite() && opacity > 0.0
}
/// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule;
/// `None` when it casts nothing.
+60
View File
@@ -312,3 +312,63 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it()
}
}
}
/// The opacity of each part of the shadow of `n` (its 3D effect's shadow on) and the shadow's art,
/// as [`cast_shadow`] casts it from solids built for the shadow alone and as [`cast_built`] casts
/// it from the faces the solids drawn kept.
fn cast_parts(n: &Node) -> [(Vec<f32>, String); 2] {
let (_, fx) = solid(&n.appearance.effects).unwrap();
let shapes = if is_container(n) {
members(n, "").unwrap()
} else {
let (path, rule) = profile(n).unwrap();
vec![Profile { path, rule, items: solid_paint_sources(n).1, opacity: 1.0, scopes: vec![] }]
};
let p = crate::merged_params(&fx.id, &fx.params);
let (_, built) = surfaces_for(None, n, fx, &shapes, true).unwrap();
[cast_shadow(&fx.id, &p, &shapes), cast_built(&fx.id, &p, &shapes, built)].map(|c| {
let (caster, settings, cast) = c.unwrap().unwrap();
let inks = cast.iter().map(|(_, ink, _)| ink.opacity).collect();
(inks, format!("{:?}", shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes))))
})
}
/// A fill, a stroke or a member whose opacity is NaN or infinite casts no part of the shadow, as one
/// at 0 % does, whether the shadow is cast from solids built for it or from the solids drawn; the
/// art beside it still casts its part.
#[test]
fn art_whose_opacity_is_not_a_finite_number_casts_no_shadow() {
// The art with opacity `opacity` in one place: a square's stroke, the fill of a group's second
// member, and a group's second member.
let objects = |opacity: f32| {
let mut fill = square_node(2, 200.0);
for item in &mut fill.appearance.items {
if let AppearanceItem::Fill(f) = item {
f.opacity = opacity;
}
}
let mut member = square_node(2, 200.0);
member.opacity = opacity;
[
stroked_square(1, 0.0, opacity),
Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(fill)]),
Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(member)]),
]
};
for id in [EXTRUDE, INFLATE, ROTATE] {
for bad in [f32::NAN, f32::INFINITY] {
for (i, (mut n, mut clear)) in objects(bad).into_iter().zip(objects(0.0)).enumerate() {
n.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap());
clear.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap());
let expected = cast_parts(&clear);
for (k, (inks, shadow)) in cast_parts(&n).into_iter().enumerate() {
assert_eq!(inks, vec![1.0], "{id} {bad} object {i} cast {k}: only the opaque art casts");
assert_eq!(shadow, expected[k].1, "{id} {bad} object {i} cast {k}");
}
let mut opacities = vec![];
art(&n, id).unwrap().walk(&mut |c| opacities.extend(shadow_opacity(c)));
assert_eq!(opacities, vec![0.5], "{id} {bad} object {i}");
}
}
}
}
+218 -34
View File
@@ -1,7 +1,8 @@
//! Effect › SVG Filters (`svg.filter`): an SVG `<filter>` element applied as a live raster effect.
//! The filter runs on the object's pixels as SVG 1.1 describes it
//! (<https://www.w3.org/TR/SVG11/filters.html>), drawn by resvg. Its lengths are in points times
//! the effect's `scale`, its user space starts at the effect's `origin`, its object bounding box is the box of the drawn pixels, and it runs at the
//! the effect's `scale`, its user space starts at the effect's `origin`, its axes point as the effect's `axes` say (a turned or
//! skewed user space), its object bounding box is the box of the drawn pixels, and it runs at the
//! Document Raster Effects resolution when the view shows the object at a finer one.
use std::sync::Arc;
@@ -1224,13 +1225,16 @@ fn region_length(v: Option<&str>, default: f64, user: bool) -> Length {
}
/// An SVG filter effect: the filter's XML, how many points one of its units is, where its user
/// space's origin lies in the document, and its region.
/// space's origin lies in the document, which way its axes point, and its region.
#[derive(Clone, Debug, PartialEq)]
pub struct SvgFilterFx {
/// The filter as it is drawn and written ([`rebuilt`]).
xml: Arc<str>,
scale: f64,
origin: Vec2,
/// The directions of the user space's axes in the document, before `scale` ([`axes_param`]):
/// the identity unless the user space is turned, skewed or scaled unevenly.
axes: Affine,
/// Its region (filter effects region): x, y, width, height.
region: [Length; 4],
/// Is the region in user space with a length measured against the object's box? It is then
@@ -1250,11 +1254,92 @@ fn origin_param(p: &Value) -> Vec2 {
Vec2::new(at(0), at(1))
}
/// The largest magnitude of an entry of an SVG filter effect's `axes`.
pub const MAX_AXIS: f64 = 1000.0;
/// The smallest magnitude of the determinant of an SVG filter effect's `axes`.
pub const MIN_AXES_DET: f64 = 0.001;
/// The `axes` of an SVG filter effect's parameters `p`: `[a, b, c, d]`, the document directions
/// of one unit along the filter's x axis (`[a, b]`) and its y axis (`[c, d]`), before `scale`.
/// The identity when absent; `None` when it isn't four numbers from -[`MAX_AXIS`] to [`MAX_AXIS`]
/// whose determinant is at least [`MIN_AXES_DET`] across ([`valid_axes`]).
fn axes_param(p: &Value) -> Option<Affine> {
match p.get("axes") {
None | Some(Value::Null) => Some(Affine::IDENTITY),
Some(v) => valid_axes(v),
}
}
/// `v` as the linear map of an SVG filter effect's `axes` ([`axes_param`]), when it is one.
pub fn valid_axes(v: &Value) -> Option<Affine> {
let n: Vec<f64> = v.as_array()?.iter().map(Value::as_f64).collect::<Option<_>>()?;
axes_of(<[f64; 4]>::try_from(n).ok()?)
}
/// `[a, b, c, d]` as the linear map of an SVG filter effect's `axes`, when the effect takes it ([`valid_axes`]).
fn axes_of([a, b, c, d]: [f64; 4]) -> Option<Affine> {
let det = a * d - b * c;
([a, b, c, d].iter().all(|v| v.is_finite() && v.abs() <= MAX_AXIS) && det.abs() >= MIN_AXES_DET).then(|| Affine::new([a, b, c, d, 0.0, 0.0]))
}
/// A filter's user space as the SVG filter effect stores it ([`user_space`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct UserSpace {
/// The effect's `scale`.
pub scale: f64,
/// The effect's `origin`.
pub origin: [f64; 2],
/// The effect's `axes`; `None` when the axes are the document's.
pub axes: Option<[f64; 4]>,
}
/// `ts`, a user space mapped to the document, as the SVG filter effect's `scale` (the square root
/// of its area scale), `origin` and, when it turns, skews or scales unevenly, `axes`. `None` when
/// it can't be stored: not finite, `scale` outside 0.001..1000, or `axes` the effect refuses
/// ([`valid_axes`]).
pub fn user_space(ts: Affine) -> Option<UserSpace> {
let [a, b, c, d, e, f] = ts.as_coeffs();
if ![a, b, c, d, e, f].iter().all(|v| v.is_finite()) {
return None;
}
let scale = ts.determinant().abs().sqrt();
if !(0.001..=1000.0).contains(&scale) {
return None;
}
let even = b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= 1e-9 * a.max(1.0);
if even {
return Some(UserSpace { scale: a, origin: [e, f], axes: None });
}
let axes = [a, b, c, d].map(|v| v / scale);
axes_of(axes)?;
Some(UserSpace { scale, origin: [e, f], axes: Some(axes) })
}
/// The longest a unit vector becomes under the linear part of `a` (its largest singular value).
fn stretch(a: Affine) -> f64 {
let [a, b, c, d, _, _] = a.as_coeffs();
let sum = a * a + b * b + c * c + d * d;
let det = a * d - b * c;
(0.5 * (sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt())).sqrt()
}
/// The share of a raster pixel, `space.px` points wide, that a pixel of the Document Raster Effects
/// resolution is (at most 1).
fn raster_resolution(space: &PixelSpace) -> f64 {
if space.line.is_finite() && space.line > 0.0 && space.px.is_finite() && space.px > 0.0 { (space.px / space.line).min(1.0) } else { 1.0 }
}
/// How many times the raster's pixels a turned filter's canvas may hold ([`SvgFilterFx::turned_canvas`]).
const TURNED_ROOM: f64 = 4.0;
impl SvgFilterFx {
/// The effect's parameters `p` (defaults merged in): `xml`, the `<filter>` element, `scale`
/// and `origin`. `None` when `xml` isn't a filter [`check`] takes, however the effect came to
/// hold it (an opened file, a script): the object is then drawn, printed and exported without it.
/// The effect's parameters `p` (defaults merged in): `xml`, the `<filter>` element, `scale`,
/// `origin` and `axes`. `None` when `xml` isn't a filter [`check`] takes, or `axes` isn't
/// valid ([`axes_param`]), however the effect came to hold it (an opened file, a script): the
/// object is then drawn, printed and exported without it.
pub(crate) fn parse(p: &Value) -> Option<Self> {
let axes = axes_param(p)?;
let xml = checked(text(p, "xml", ""))?;
let (wrapped, _) = wrap(&xml);
let doc = roxmltree::Document::parse(&wrapped).ok()?;
@@ -1273,7 +1358,17 @@ impl SvgFilterFx {
let (window, blur) = (largest(&["radius", "kernelUnitLength"]), largest(&["stdDeviation"]));
let box_units = f.attribute("primitiveUnits").is_some_and(|u| u.trim() == "objectBoundingBox");
let scale = num(p, "scale", 1.0).clamp(1e-3, 1e3);
Some(Self { xml, scale, origin: origin_param(p), region, measured, window, blur, box_units })
Some(Self { xml, scale, origin: origin_param(p), axes, region, measured, window, blur, box_units })
}
/// The filter's user space → the document: moved to `origin`, scaled by `scale`, along `axes`.
pub fn to_doc(&self) -> Affine {
Affine::translate(self.origin) * Affine::scale(self.scale) * self.axes
}
/// The box of `bounds` (document units) in the filter's user space.
fn user_box(&self, bounds: Rect) -> Rect {
self.to_doc().inverse().transform_rect_bbox(bounds)
}
/// The filter's region in its user space for an object whose box there is `b`: lengths in user
@@ -1308,11 +1403,11 @@ impl SvgFilterFx {
with_attributes(xml, &[("x", r.x0), ("y", r.y0), ("width", r.width()), ("height", r.height())])
}
/// The filter as SVG output writes it (one unit a point, [`Self::in_points`]) for an object
/// whose box in the document is `bounds`: in its SVG 1.1 form ([`svg11`]), `None` when SVG 1.1
/// can't hold it ([`Self::writes_as_svg11`]).
pub fn written_xml(&self, bounds: Rect) -> Option<String> {
let out = self.with_region(&self.svg11_form()?, (bounds - self.origin).scale_from_origin(1.0 / self.scale))?;
/// The filter as SVG output writes it, in its user space ([`Self::to_doc`]), for an object
/// whose box in that user space is `user_box`: in its SVG 1.1 form ([`svg11`]), `None` when SVG
/// 1.1 can't hold it ([`Self::writes_as_svg11`]).
pub fn written_xml(&self, user_box: Rect) -> Option<String> {
let out = self.with_region(&self.svg11_form()?, user_box)?;
(written_len(&out) <= MAX_WRITTEN_XML).then_some(out)
}
@@ -1345,10 +1440,11 @@ impl SvgFilterFx {
if !(space.px.is_finite() && space.px > 0.0) {
return 1.0;
}
let mut s: f64 = if space.line.is_finite() && space.line > 0.0 { (space.px / space.line).min(1.0) } else { 1.0 };
// A length spans length × scale / px raster pixels, or a fraction of the box.
let mut s = raster_resolution(space);
// A length spans at most length × scale × the axes' stretch / px raster pixels, or a fraction of the box.
let reach = self.scale * stretch(self.axes);
for (length, most) in [(self.window, MAX_WINDOW_PX), (self.blur, MAX_BLUR_PX)] {
let px = if self.box_units { length * box_px.max(0.0) } else { length * self.scale / space.px };
let px = if self.box_units { length * box_px.max(0.0) } else { length * reach / space.px };
if px * s > most {
s = most / px;
}
@@ -1374,15 +1470,21 @@ impl SvgFilterFx {
self.measured
}
/// Does one unit of the filter's user space measure one point (its `scale` is 1)?
pub fn in_points(&self) -> bool {
self.scale == 1.0
/// Is the filter's user space the document's, only moved: one unit a point, its axes the
/// document's (`scale` 1, no `axes`)?
pub fn moves_only(&self) -> bool {
self.scale == 1.0 && self.axes == Affine::IDENTITY
}
/// Can SVG import store the filter's user space ([`Self::to_doc`]) again ([`user_space`])? Its
/// `scale` and `axes` together can scale it past what one of them holds alone.
pub fn opens_again(&self) -> bool {
user_space(self.to_doc()).is_some()
}
/// How far beyond `bounds` (document units) the filter can draw: its region's reach past them.
pub fn outset(&self, bounds: Rect) -> f64 {
let b = (bounds - self.origin).scale_from_origin(1.0 / self.scale);
let region = self.region_in(b).scale_from_origin(self.scale) + self.origin;
let region = self.to_doc().transform_rect_bbox(self.region_in(self.user_box(bounds)));
let reach = [bounds.x0 - region.x0, bounds.y0 - region.y0, region.x1 - bounds.x1, region.y1 - bounds.y1].into_iter().fold(0.0, f64::max);
if reach.is_finite() { reach.min(MAX_OUTSET) } else { 0.0 }
}
@@ -1397,20 +1499,40 @@ impl SvgFilterFx {
}
// Art that draws no pixels still has a box: the whole raster stands for it.
let (x0, y0, x1, y1) = drawn_box(data, w, h).unwrap_or((0, 0, w, h));
let s = self.resolution(space, (x1 - x0).max(y1 - y0) as f64);
let (sw, sh) = ((w as f64 * s).ceil().max(1.0) as u32, (h as f64 * s).ceil().max(1.0) as u32);
let Some(png) = png_of(data, w, x0, y0, x1, y1).map(Arc::new) else { return };
let k = self.scale;
// Filter user space → the small canvas, and the image's pixels → filter user space.
let outer = Affine::scale(s) * space.to_doc.inverse() * Affine::translate(self.origin) * Affine::scale(k);
let place = Affine::scale(1.0 / k) * Affine::translate(-self.origin) * space.to_doc * Affine::translate(Vec2::new(x0 as f64, y0 as f64));
let b = place.transform_rect_bbox(Rect::new(0.0, 0.0, (x1 - x0) as f64, (y1 - y0) as f64));
let user = self.to_doc();
// Filter user space → the small canvas, and the small canvas → the raster's pixels.
let (sw, sh, outer, back) = if self.axes == Affine::IDENTITY {
let s = self.resolution(space, (x1 - x0).max(y1 - y0) as f64);
let (sw, sh) = ((w as f64 * s).ceil().max(1.0) as u32, (h as f64 * s).ceil().max(1.0) as u32);
(sw, sh, Affine::scale(s) * space.to_doc.inverse() * user, Affine::scale(1.0 / s))
} else {
// The canvas measures the costly lengths in its own pixels.
let drawn = Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64);
let Some(canvas) = self.turned_canvas(w, h, raster_resolution(space), drawn, space) else { return };
canvas
};
// The source as an image, its size, and the map from its pixels to filter user space. The
// object's box in user space is the image's box there, which resvg measures the region and
// a primitive's lengths in the object's box against. In a turned or skewed user space the
// source is first drawn onto the canvas's pixels, whose rows and columns run along the user
// space's axes, and cut to the pixels it draws there: the image then lies along those axes,
// and its box is the box of the art in the user space, not of the raster's box turned into it.
let source = if self.axes == Affine::IDENTITY {
let place = user.inverse() * space.to_doc * Affine::translate(Vec2::new(x0 as f64, y0 as f64));
png_of(data, w, x0, y0, x1, y1).map(|png| (png, x1 - x0, y1 - y0, place))
} else {
on_canvas(data, w, h, sw, sh, outer * user.inverse() * space.to_doc)
.map(|(png, cx, cy, iw, ih)| (png, iw, ih, outer.inverse() * Affine::translate(Vec2::new(cx as f64, cy as f64))))
};
let Some((png, iw, ih, place)) = source else { return };
let png = Arc::new(png);
let b = place.transform_rect_bbox(Rect::new(0.0, 0.0, iw as f64, ih as f64));
let Some(drawn) = self.drawn_xml(b).and_then(|xml| with_id(&xml, DRAWN_ID)) else { return };
let svg = format!(
"<svg xmlns=\"{SVG_NS}\" xmlns:xlink=\"{XLINK_NS}\" width=\"{sw}\" height=\"{sh}\" viewBox=\"0 0 {sw} {sh}\"><defs>{drawn}</defs><g transform=\"{}\"><g filter=\"url(#{DRAWN_ID})\"><image width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" transform=\"{}\" xlink:href=\"data:image/png;base64,{}\"/></g></g></svg>",
matrix(outer),
x1 - x0,
y1 - y0,
iw,
ih,
matrix(place),
base64(&png)
);
@@ -1420,19 +1542,65 @@ impl SvgFilterFx {
}
let Some(mut small) = tiny_skia::Pixmap::new(sw, sh) else { return };
resvg::render(&tree, tiny_skia::Transform::identity(), &mut small.as_mut());
let out = if s < 1.0 {
let out = if back == Affine::IDENTITY {
small
} else {
let Some(mut full) = tiny_skia::Pixmap::new(w as u32, h as u32) else { return };
let paint = tiny_skia::PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..Default::default() };
let up = (1.0 / s) as f32;
full.draw_pixmap(0, 0, small.as_ref(), &paint, tiny_skia::Transform::from_scale(up, up), None);
let [a, b, c, d, e, f] = back.as_coeffs().map(|v| v as f32);
full.draw_pixmap(0, 0, small.as_ref(), &paint, tiny_skia::Transform::from_row(a, b, c, d, e, f), None);
full
} else {
small
};
if out.data().len() == data.len() {
data.copy_from_slice(out.data());
}
}
/// The canvas a filter whose user space is turned, skewed or scaled unevenly runs on, for a
/// `w` × `h` raster lying in the document as `space` says, at resolution `s`
/// ([`raster_resolution`]), whose art draws within `drawn` (raster pixels): its axes are the user
/// space's, so the filter's offsets, blurs and other lengths run along them as SVG 1.1 measures
/// them, and it covers what the raster shows. Along each of its axes its pixels are about as
/// large as the raster's at `s`, and coarser when it would hold more than [`TURNED_ROOM`] times
/// as many pixels as the raster does at `s`, and when a morphology radius or kernel unit would
/// span more than 32 of its pixels or a blur's standard deviation more than 512 (a length in the
/// object's box measured against the art's box on the canvas). Returns its size, the map from
/// user space to it, and the map from it to the raster's pixels; `None` when the spaces can't
/// be measured.
fn turned_canvas(&self, w: usize, h: usize, s: f64, drawn: Rect, space: &PixelSpace) -> Option<(u32, u32, Affine, Affine)> {
let to_px = space.to_doc.inverse() * self.to_doc();
let from_px = to_px.inverse();
let ub = from_px.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64));
let most = ((w as f64 * s).ceil().max(1.0) * (h as f64 * s).ceil().max(1.0) * TURNED_ROOM).max(1.0);
// Canvas pixels a unit along each axis of the user space: as many as the raster's at `s`.
let [a, b, c, d, _, _] = to_px.as_coeffs();
let (mut qx, mut qy) = (s * a.hypot(b), s * c.hypot(d));
let pixels = ub.width() * qx * ub.height() * qy;
if pixels > most {
let k = (most / pixels).sqrt();
(qx, qy) = (qx * k, qy * k);
}
// A length along an axis spans length × q canvas pixels, or length × the art's box on the
// canvas along that axis: both shrink with q.
let art = from_px.transform_rect_bbox(drawn);
for (length, cap) in [(self.window, MAX_WINDOW_PX), (self.blur, MAX_BLUR_PX)] {
let px = if self.box_units { length * (art.width() * qx).max(art.height() * qy) } else { length * qx.max(qy) };
if px > cap {
let k = cap / px;
(qx, qy) = (qx * k, qy * k);
}
}
if !(qx.is_finite() && qx > 0.0 && qy.is_finite() && qy > 0.0 && ub.is_finite()) {
return None;
}
let (cw, ch) = ((ub.width() * qx).ceil().max(1.0), (ub.height() * qy).ceil().max(1.0));
// Rounding up adds at most a row and a column.
if cw * ch > most + cw + ch + 1.0 {
return None;
}
let outer = Affine::scale_non_uniform(qx, qy) * Affine::translate(Vec2::new(-ub.x0, -ub.y0));
Some((cw as u32, ch as u32, outer, to_px * outer.inverse()))
}
}
/// The farthest a filter's region reaches beyond the object, in points.
@@ -1450,6 +1618,22 @@ fn drawn_box(data: &[u8], w: usize, h: usize) -> Option<(usize, usize, usize, us
(x1 > x0 && y1 > y0).then_some((x0, y0, x1, y1))
}
/// The pixels of `data` (premultiplied RGBA8, `w` × `h`) drawn onto a `cw` × `ch` canvas through
/// `to_canvas` (the raster's pixels → the canvas's), cut to the box of the canvas pixels that aren't
/// transparent (the whole canvas when all are): a PNG of them, the box's corner on the canvas, and
/// its size.
fn on_canvas(data: &[u8], w: usize, h: usize, cw: u32, ch: u32, to_canvas: Affine) -> Option<(Vec<u8>, usize, usize, usize, usize)> {
let size = tiny_skia::IntSize::from_wh(u32::try_from(w).ok()?, u32::try_from(h).ok()?)?;
let raster = tiny_skia::Pixmap::from_vec(data.to_vec(), size)?;
let mut canvas = tiny_skia::Pixmap::new(cw, ch)?;
let paint = tiny_skia::PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..Default::default() };
let [a, b, c, d, e, f] = to_canvas.as_coeffs().map(|v| v as f32);
canvas.draw_pixmap(0, 0, raster.as_ref(), &paint, tiny_skia::Transform::from_row(a, b, c, d, e, f), None);
let (cw, ch) = (cw as usize, ch as usize);
let (x0, y0, x1, y1) = drawn_box(canvas.data(), cw, ch).unwrap_or((0, 0, cw, ch));
Some((png_of(canvas.data(), cw, x0, y0, x1, y1)?, x0, y0, x1 - x0, y1 - y0))
}
/// The pixels of `data` (premultiplied RGBA8, `w` wide) in columns x0..x1 and rows y0..y1, as a PNG.
fn png_of(data: &[u8], w: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> Option<Vec<u8>> {
use image::ImageEncoder;
+150 -1
View File
@@ -222,6 +222,154 @@ fn user_space_starts_at_the_origin() {
assert!((filter(json!({ "xml": half, "origin": [-10.0, 0.0] })).outset(b) - 10.0).abs() < 1e-9);
}
/// The opacity of `data` (`w` wide) after the filter `xml` with `params` runs on a blue square
/// over 10..20 pt of a 40 pt raster one point a pixel, at each of `points`.
fn turned_run(xml: &str, params: serde_json::Value, points: &[(usize, usize)]) -> Vec<u8> {
let w = 40;
let mut data = image(w, w, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { [0, 0, 255, 255] } else { [0; 4] });
let mut p = params;
p["xml"] = json!(xml);
filter(p).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
points.iter().map(|&(x, y)| at(&data, w, x, y)[3]).collect()
}
const SHIFT_X: &str = r#"<filter id="Shift" x="-1" y="-1" width="3" height="3"><feOffset dx="4"/></filter>"#;
/// With `axes`, the filter runs in its turned or skewed user space: an offset along its x axis
/// moves the art along that axis in the document (SVG 1.1 measures a primitive's lengths in the
/// user space of the element the filter is on).
#[test]
fn a_turned_user_space_moves_the_art_along_its_own_axes() {
// The square spans 10..20 pt; moved 4 pt along x it covers 14..24 across.
let points = [(22, 15), (15, 22), (12, 11)];
assert_eq!(turned_run(SHIFT_X, json!({}), &points), [255, 0, 0], "the document's axes: to the right");
// Turned a quarter turn: the filter's x axis points down the page.
let down = turned_run(SHIFT_X, json!({ "axes": [0.0, 1.0, -1.0, 0.0] }), &points);
assert_eq!(down, [0, 255, 0], "moved down, not to the right");
// Skewed: one unit along y is one across and one down, so dy 4 moves the art 4 pt each way.
let shift_y = r#"<filter id="Shift" x="-1" y="-1" width="3" height="3"><feOffset dy="4"/></filter>"#;
let skewed = turned_run(shift_y, json!({ "axes": [1.0, 0.0, 1.0, 1.0] }), &[(22, 22), (11, 22), (11, 11)]);
assert!(skewed[0] > 200 && skewed[1] < 60 && skewed[2] < 60, "moved across and down: {skewed:?}");
}
#[test]
fn axes_the_effect_cannot_measure_are_not_drawn() {
for axes in [json!([0, 0, 0, 0]), json!([1, 2]), json!([1, 0, 0, "1"]), json!([2000, 0, 0, 1]), json!([0.01, 0, 0, 0.01]), json!("turned")] {
let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": SHIFT_X, "axes": axes }), visible: true };
assert!(raster_effects(&[e]).is_empty(), "{axes}: drawn without it");
assert!(valid_axes(&axes).is_none(), "{axes}");
}
assert_eq!(valid_axes(&json!([0, 1, -1, 0])), Some(Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0])));
}
/// A region measured against the object's box is measured against its box in the turned user
/// space: a diamond turned an eighth of a turn is a square there, and a flood over 0..100% of it
/// covers the diamond alone.
#[test]
fn a_turned_region_is_measured_against_the_box_in_its_user_space() {
let w = 40;
let diamond = |x: usize, y: usize| (x as f64 - 19.5).abs() + (y as f64 - 19.5).abs() <= 10.0;
let mut data = image(w, w, |x, y| if diamond(x, y) { [0, 0, 255, 255] } else { [0; 4] });
let flood = r##"<filter id="F" filterUnits="userSpaceOnUse" x="0%" y="0%" width="100%" height="100%"><feFlood flood-color="#ff0000"/></filter>"##;
let h = std::f64::consts::FRAC_1_SQRT_2;
filter(json!({ "xml": flood, "axes": [h, h, -h, h] })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
assert_eq!(at(&data, w, 20, 20), [255, 0, 0, 255], "inside the diamond");
assert!(at(&data, w, 12, 12)[3] < 40, "outside the diamond, inside its box on the page: {:?}", at(&data, w, 12, 12));
}
/// In a turned user space, a region in the object's bounding box (the default `filterUnits`) and a
/// primitive's lengths in it (`primitiveUnits="objectBoundingBox"`) are measured against the
/// object's box there: on a diamond turned an eighth of a turn, a flood over 0..100% of the box
/// covers the diamond alone.
#[test]
fn a_turned_filter_measures_box_units_against_the_box_in_its_user_space() {
let w = 40;
let h = std::f64::consts::FRAC_1_SQRT_2;
let region = r##"<filter id="F" x="0" y="0" width="1" height="1"><feFlood flood-color="#ff0000"/></filter>"##;
let primitive = r##"<filter id="F" filterUnits="userSpaceOnUse" x="-1000" y="-1000" width="2000" height="2000" primitiveUnits="objectBoundingBox"><feFlood flood-color="#ff0000" x="0" y="0" width="1" height="1"/></filter>"##;
for xml in [region, primitive] {
let diamond = |x: usize, y: usize| (x as f64 - 19.5).abs() + (y as f64 - 19.5).abs() <= 10.0;
let mut data = image(w, w, |x, y| if diamond(x, y) { [0, 0, 255, 255] } else { [0; 4] });
filter(json!({ "xml": xml, "axes": [h, h, -h, h] })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
assert_eq!(at(&data, w, 20, 20), [255, 0, 0, 255], "{xml}: inside the diamond");
assert!(at(&data, w, 12, 12)[3] < 40, "{xml}: outside the diamond, inside its box on the page: {:?}", at(&data, w, 12, 12));
}
}
/// SVG import stores a filter's user space again only when `scale` and `axes` together stay within
/// what it holds: each alone can be valid while their product is not.
#[test]
fn a_user_space_opens_again_only_within_what_import_stores() {
let opens = |scale: f64, axes: serde_json::Value| filter(json!({ "xml": SHIFT_X, "scale": scale, "axes": axes })).opens_again();
assert!(opens(1000.0, json!(null)));
assert!(opens(2.0, json!([0.0, 1.0, -1.0, 0.0])));
assert!(!opens(1000.0, json!([2.0, 0.0, 0.0, 2.0])), "scale 2000 across");
assert!(!opens(0.001, json!([0.5, 0.0, 0.0, 0.5])), "scale 0.0005 across");
let space = user_space(Affine::new([0.0, 2.0, -2.0, 0.0, 5.0, 6.0])).unwrap();
assert_eq!((space.scale, space.origin, space.axes), (2.0, [5.0, 6.0], Some([0.0, 1.0, -1.0, 0.0])));
}
/// The region of a turned filter reaches as far as its turned box does.
#[test]
fn a_turned_region_reaches_along_the_turned_axes() {
let b = Rect::new(0.0, 0.0, 50.0, 50.0);
let user = r#"<filter id="u" filterUnits="userSpaceOnUse" x="-30" y="-5" width="100" height="100"><feOffset/></filter>"#;
assert!((filter(json!({ "xml": user })).outset(b) - 45.0).abs() < 1e-9, "45 pt below the box");
// A quarter turn: user y runs to the left of the page, so -5..95 of it lies 95 pt left of the box.
assert!((filter(json!({ "xml": user, "axes": [0.0, 1.0, -1.0, 0.0] })).outset(b) - 95.0).abs() < 1e-9);
}
/// A filter skewed as far as `axes` allows runs on a canvas no larger than four times the raster's
/// pixels, however far the skew spreads the raster's box in its user space.
#[test]
fn a_skewed_filter_runs_within_its_pixel_budget() {
let (w, h) = (64, 48);
let f = filter(json!({ "xml": SHIFT_X, "axes": [1.0, 0.0, 999.0, 1.0] }));
let all = Rect::new(0.0, 0.0, w as f64, h as f64);
let (cw, ch, ..) = f.turned_canvas(w, h, 1.0, all, &space(w, h, 1.0, 1.0)).unwrap();
let (cw, ch) = (f64::from(cw), f64::from(ch));
assert!(cw * ch <= TURNED_ROOM * (w * h) as f64 + cw + ch + 1.0, "{cw} × {ch}");
// It still draws.
let mut data = image(w, h, |x, y| if (20..40).contains(&x) && (10..30).contains(&y) { [0, 0, 255, 255] } else { [0; 4] });
f.apply(&mut data, w, h, &space(w, h, 1.0, 1.0));
// A plain quarter turn keeps the raster's own pixel size.
let turned = filter(json!({ "xml": SHIFT_X, "axes": [0.0, 1.0, -1.0, 0.0] }));
let (cw, ch, outer, _) = turned.turned_canvas(w, h, 1.0, all, &space(w, h, 1.0, 1.0)).unwrap();
assert_eq!((cw, ch), (48, 64));
assert!((outer.determinant() - 1.0).abs() < 1e-9);
// Stretched 100 times across and squeezed 100 times down: each canvas axis keeps the raster's
// detail along it, not one column of it.
let stretched = filter(json!({ "xml": SHIFT_X, "axes": [100.0, 0.0, 0.0, 0.01] }));
let (cw, ch, ..) = stretched.turned_canvas(100, 100, 1.0, Rect::new(0.0, 0.0, 100.0, 100.0), &space(100, 100, 1.0, 1.0)).unwrap();
assert_eq!((cw, ch), (100, 100));
}
/// On a far skewed canvas, a radius or a standard deviation in the object's box spans no more
/// canvas pixels than the caps allow: it is measured against the art's box on the canvas, which the
/// skew spreads far wider than the art's box in the raster.
#[test]
fn a_skewed_filter_keeps_box_lengths_within_the_caps_on_its_canvas() {
let (w, h) = (64, 48);
let sp = space(w, h, 1.0, 1.0);
let drawn = Rect::new(20.0, 10.0, 40.0, 30.0);
for (xml, length, cap) in [
("<filter id=\"m\" primitiveUnits=\"objectBoundingBox\"><feMorphology radius=\"1.5\"/></filter>", 1.5, MAX_WINDOW_PX),
("<filter id=\"b\" primitiveUnits=\"objectBoundingBox\"><feGaussianBlur stdDeviation=\"20\"/></filter>", 20.0, MAX_BLUR_PX),
] {
let f = filter(json!({ "xml": xml, "axes": [1.0, 0.0, 999.0, 1.0] }));
let (_, _, outer, _) = f.turned_canvas(w, h, 1.0, drawn, &sp).unwrap();
// The art's box on the canvas: the drawn pixels taken into user space, then onto the canvas.
let art = (outer * f.to_doc().inverse() * sp.to_doc).transform_rect_bbox(drawn);
let px = length * art.width().max(art.height());
assert!(px <= cap + 1e-6, "{xml}: {px} canvas pixels");
}
// A user-space radius spans no more than 32 canvas pixels along either axis.
let f = filter(json!({ "xml": "<filter id=\"u\"><feMorphology radius=\"100\"/></filter>", "scale": 1000.0, "axes": [1.0, 0.0, 999.0, 1.0] }));
let (_, _, outer, _) = f.turned_canvas(w, h, 1.0, drawn, &sp).unwrap();
let [qx, _, _, qy, _, _] = outer.as_coeffs();
assert!(100.0 * qx.max(qy) <= MAX_WINDOW_PX + 1e-6, "{qx} {qy}");
}
#[test]
fn runs_no_finer_than_the_raster_effects_resolution() {
let w = 16;
@@ -448,7 +596,8 @@ fn a_region_measured_against_the_box_is_written_out() {
let far = r#"<filter id="r" filterUnits="userSpaceOnUse" x="-50%" y="0" width="200%" height="10"><feOffset/></filter>"#;
let f = filter(json!({ "xml": far, "origin": [10.0, 0.0] }));
assert_eq!(
f.written_xml(Rect::new(10.0, 0.0, 30.0, 10.0)).as_deref(),
// The object over 10..30 pt of the page: 0..20 of the user space that starts at the origin.
f.written_xml(Rect::new(0.0, 0.0, 20.0, 10.0)).as_deref(),
Some(r#"<filter id="r" filterUnits="userSpaceOnUse" x="-10" y="0" width="40" height="10"><feOffset/></filter>"#)
);
let plain = filter(json!({ "xml": RED_FLOOD }));
+59 -1
View File
@@ -117,13 +117,71 @@ fn a_hidden_shadow_follows_the_transform_it_loses() {
assert!(close(drawn_shadow(&[shown]), (20.0, 20.0, 8.0)));
}
/// Rasterize keeps its room around the art: its image keeps its own pixel grid.
/// Rasterize keeps its room around the art: its image keeps its own pixel grid, and the Transform
/// effect moves the image instead ([`crate::rasterize_stage`]).
#[test]
fn rasterize_before_a_transform_keeps_its_options() {
let rasterize = fx(crate::RASTERIZE, json!({"addAround": 6}));
let effects = [rasterize.clone(), transform(json!({"scaleH": 200, "scaleV": 200}))];
assert_eq!(crate::raster::followed(&effects)[0], rasterize);
assert_eq!(crate::raster::without_geometry(&effects), vec![rasterize]);
assert_eq!(crate::rasterize_stage(&effects), Some(vec![1]));
}
/// The Transform effects after the last Rasterize effect move its image when, from the first of
/// them on, every visible effect is a Transform effect that moves the art once. Hidden ones, and
/// ones with Transform Objects off, leave the image where it is.
#[test]
fn rasterize_following_ignores_hidden_and_objects_off() {
let rasterize = || fx(crate::RASTERIZE, json!({}));
let scale = || transform(json!({"scaleH": 200, "scaleV": 200}));
let mut hidden = scale();
hidden.visible = false;
let off = transform(json!({"scaleH": 200, "objects": false}));
let roughen = fx("distort.roughen", json!({}));
let shadow = shadow(5.0, 5.0, 2.0);
let cases: Vec<(Vec<Effect>, Option<Vec<usize>>)> = vec![
(vec![rasterize(), hidden.clone()], None),
(vec![rasterize(), off.clone()], None),
(vec![rasterize(), hidden, off, scale()], Some(vec![3])),
(vec![rasterize(), transform(json!({"moveH": 10})), scale()], Some(vec![1, 2])),
// Effects before the first Transform effect go into the image; anything after it holds
// the image back.
(vec![rasterize(), roughen.clone(), shadow.clone(), scale()], Some(vec![3])),
(vec![rasterize(), scale(), roughen], None),
(vec![rasterize(), scale(), shadow], None),
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2}))], None),
(vec![rasterize(), transform(json!({"scaleH": 200, "random": true}))], None),
// The Transform effect before the Rasterize effect moves the art.
(vec![scale(), rasterize()], None),
(vec![scale(), rasterize(), rasterize(), scale()], Some(vec![3])),
];
for (effects, want) in cases {
let ids: Vec<&str> = effects.iter().map(|e| e.id.as_str()).collect();
assert_eq!(crate::rasterize_stage(&effects), want, "{ids:?}");
}
// What the image is made from hides those Transform effects; the rest stay as they are.
let effects = [rasterize(), scale()];
let staged = crate::staged_effects(&effects, &[1]);
assert_eq!((staged[0].visible, staged[1].visible), (true, false));
}
/// The map that moves the image is each Transform effect's map about its reference point on the
/// bounds of the geometry it takes, in order.
#[test]
fn the_image_moves_by_each_transform_about_the_art_it_takes() {
let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0));
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"moveH": 5}))];
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
// Twice the size about the center (20, 20), then 5 pt to the right.
let want = Affine::translate((5.0, 0.0)) * Affine::translate((20.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-20.0, -20.0));
assert!(map.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{map:?}");
// The second Transform effect turns about the center of what the first one made.
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"moveH": 100})), transform(json!({"rotate": 90}))];
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
let c = map * Point::new(20.0, 20.0);
assert!((c.x - 120.0).abs() < 1e-9 && (c.y - 20.0).abs() < 1e-9, "{c:?}");
assert_eq!(crate::stage_map(&effects, &[1, 2], &PathData::default()), None);
}
/// An SVG filter keeps its options: it paints in its own user space.
+77 -17
View File
@@ -9,8 +9,9 @@
//! text. Each action is an `/action-N` block with a hexadecimal `/name`; each step is an `/event-N`
//! block inside one, with its `/internalName` in parentheses, the `/localizedName` it is shown with
//! as hexadecimal text, and `/isOn` 0 when it is left out of playback; each value a step was
//! recorded with is a `/parameter-N` block inside it, which is counted, and whose hexadecimal
//! `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount`
//! recorded with is a `/parameter-N` block inside it, which is counted, whose `/key` (a number),
//! `/type` (text in parentheses) and `/value` (a number, text in parentheses or hexadecimal text) are
//! kept, and whose hexadecimal `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount`
//! and a step's `/parameterCount` give how many actions, steps and recorded values follow.
//! The layout follows the README of Inventsable's Redesigning-Illustrator-Actions-in-Scripting
//! (https://github.com/Inventsable/Redesigning-Illustrator-Actions-in-Scripting), the forum post
@@ -40,6 +41,8 @@ const MAX_STEPS: usize = 10_000;
/// The most steps read in the set: a small text can hold hundreds of thousands of empty steps, and
/// the answer holds an object for each.
const MAX_SET_STEPS: usize = 100_000;
/// The most recorded values kept in the set; the others are counted but not kept.
const MAX_VALUES: usize = 100_000;
/// The longest name kept (bytes).
const MAX_NAME: usize = 1024;
/// The most tokens listed as unread.
@@ -56,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Read Action Set File",
[],
None,
"{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error",
"{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, values: [{key: the block's /key, or null, type: its /type, or null, value: its /value when it is a number, or text that is UTF-8 (else null), bytes?: the text's length in bytes}] (the first 100,000 recorded values in the set), line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error",
always,
read
)]
@@ -73,12 +76,33 @@ pub struct AiaStep {
pub on: Option<i64>,
/// How many `/parameter-N` blocks it has.
pub params: usize,
/// Its `/parameter-N` blocks, in order, while the set keeps at most [`MAX_VALUES`].
pub values: Vec<AiaValue>,
/// Its `/parameterCount`, if it has one.
pub declared: Option<i64>,
/// The line its block opens on (from 1).
pub line: usize,
}
/// A value a step was recorded with: a `/parameter-N` block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AiaValue {
/// Its `/key`, if it has one that fits an `i64`.
pub key: Option<i64>,
/// Its `/type`, read as UTF-8 with replacement characters, if it has one.
pub kind: Option<String>,
/// Its `/value`, if it is a number that fits an `i64` or text.
pub value: Option<AiaData>,
}
/// A recorded `/value` that is kept.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AiaData {
Int(i64),
/// The bytes of text in parentheses or of hexadecimal text.
Text(Vec<u8>),
}
/// An action: an `/action-N` block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AiaAction {
@@ -106,6 +130,8 @@ pub struct AiaSet {
pub truncated: bool,
/// How many steps were read in all the actions.
steps: usize,
/// How many recorded values were kept in all the steps.
values: usize,
}
/// A token of the text.
@@ -252,7 +278,8 @@ fn hex_bytes(digits: &[u8]) -> Option<Vec<u8>> {
enum Kind {
Action,
Step,
Param,
/// A recorded value, and whether it is kept.
Param(bool),
/// A block that isn't read, or one past a cap.
Other,
}
@@ -315,12 +342,18 @@ fn open_block(set: &mut AiaSet, stack: &[Kind], name: &[u8], line: usize) -> Kin
}
},
Some(Kind::Step) if numbered(name, b"parameter-") => {
let mut kept = false;
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
s.params += 1;
if set.values < MAX_VALUES {
s.values.push(AiaValue::default());
set.values += 1;
kept = true;
}
}
Kind::Param
Kind::Param(kept)
}
Some(Kind::Param | Kind::Other) => Kind::Other,
Some(Kind::Param(_) | Kind::Other) => Kind::Other,
_ => {
unread(set, line, format!("/{} {{", String::from_utf8_lossy(name)));
Kind::Other
@@ -355,12 +388,23 @@ fn set_hex(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, bytes: Op
}
}
/// Mark `set` truncated when the hexadecimal `/value` on `line` isn't as many bytes as its count
/// says.
fn check_value(set: &mut AiaSet, bytes: Option<Vec<u8>>, line: usize) {
if bytes.is_none() {
/// Set the field `name` of the recorded value open on `line` to `token`: its `/key`, `/type` or
/// `/value`, when the value is `kept`. A hexadecimal `/value` that isn't as many bytes as its count
/// says marks `set` truncated, kept or not.
fn set_param(set: &mut AiaSet, kept: bool, name: Option<&[u8]>, token: Token, line: usize) {
if name == Some(b"value".as_slice()) && matches!(token, Token::Hex(None)) {
set.truncated = true;
unread(set, line, BAD_HEX);
return;
}
let value = set.actions.last_mut().and_then(|a| a.steps.last_mut()).and_then(|s| s.values.last_mut());
let Some(v) = value.filter(|_| kept) else { return };
match (name, token) {
(Some(b"key"), Token::Int(key)) => v.key = key,
(Some(b"type"), Token::Text(t)) => v.kind = Some(String::from_utf8_lossy(&t).into_owned()),
(Some(b"value"), Token::Int(Some(n))) => v.value = Some(AiaData::Int(n)),
(Some(b"value"), Token::Text(t) | Token::Hex(Some(t))) => v.value = Some(AiaData::Text(t)),
_ => {}
}
}
@@ -448,13 +492,13 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
unread(&mut set, line, "}");
}
}
Token::Hex(bytes) if matches!(stack.last(), Some(Kind::Param)) => {
if field(&mut pending).as_deref() == Some(b"value".as_slice()) {
check_value(&mut set, bytes, line);
}
_ if matches!(stack.last(), Some(Kind::Param(_))) => {
let kept = matches!(stack.last(), Some(Kind::Param(true)));
let name = field(&mut pending);
set_param(&mut set, kept, name.as_deref(), token, line);
}
// The other values inside a recorded value, or a block that isn't read.
_ if matches!(stack.last(), Some(Kind::Param | Kind::Other)) => {
// The values inside a block that isn't read.
_ if matches!(stack.last(), Some(Kind::Other)) => {
pending = None;
}
Token::Hex(bytes) => {
@@ -521,6 +565,21 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
Ok(set)
}
/// A recorded value in `actionSet.read`'s answer: `{key, type, value, bytes?}`, the value a number,
/// text that is UTF-8 (else null) with its length in bytes, or null.
fn value_json(v: &AiaValue) -> Value {
let mut out = json!({ "key": v.key, "type": v.kind, "value": null });
match &v.value {
Some(AiaData::Int(n)) => out["value"] = json!(n),
Some(AiaData::Text(t)) => {
out["value"] = json!(std::str::from_utf8(t).ok());
out["bytes"] = json!(t.len());
}
None => {}
}
out
}
fn read(_: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "actionSet.read";
let (path, data, b64) = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?);
@@ -544,7 +603,8 @@ fn read(_: &mut Session, p: &Value) -> Result<Value> {
.iter()
.map(|s| {
let label = s.label.clone().filter(|l| !l.trim().is_empty());
json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "line": s.line })
let values: Vec<Value> = s.values.iter().map(value_json).collect();
json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "values": values, "line": s.line })
})
.collect();
json!({ "name": a.name, "steps": steps })
@@ -1225,7 +1225,7 @@ fn expand_dashes_keeps_the_fill_below_and_follows_aligned_corners() {
let mut centred = 0;
for id in ids(&r) {
let sp = path(&s, id).subpaths[0].clone();
if let [a, b, c] = sp.anchors.as_slice()
if let [a, b, c] = &*sp.anchors.to_vec()
&& corners.iter().any(|k| b.p.distance(*k) < 1e-6)
{
assert!((a.p.distance(b.p) - 5.0).abs() < 1e-6 && (c.p.distance(b.p) - 5.0).abs() < 1e-6, "{sp:?}");
+6 -6
View File
@@ -14,8 +14,9 @@ use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_geom::Point;
use super::super::links::{Status, statuses};
use super::super::panelcmds::listed_artboards;
use super::super::select::{is_selectable, on_artboard, selectable};
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param};
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, switch_or, text_param};
use crate::{DocState, Result, Session};
/// How Select by Artboards relates an object to the chosen artboards (`relation`).
@@ -33,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select by Artboards",
["Object", "Plug-ins", "Selection Tools"],
None,
"{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
"{artboards: [index…] (0-based whole numbers, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
has_doc,
by_artboards
),
@@ -58,13 +59,12 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "`relation` must be overlap, inside or outside"));
}
let listed = p.get("artboards").ok_or_else(|| bad(C, "missing `artboards`"))?;
let indices = point_indices(listed).ok_or_else(|| bad(C, "`artboards` must be a list of artboard indices"))?;
if indices.is_empty() {
if listed.as_array().is_some_and(Vec::is_empty) {
return Err(bad(C, "choose at least one artboard"));
}
let st = s.doc()?;
let rects =
indices.iter().map(|i| st.doc.artboards.get(*i).map(|a| a.rect)).collect::<Option<Vec<_>>>().ok_or_else(|| bad(C, "no such artboard"))?;
let rects: Vec<_> =
listed_artboards(&st.doc, listed, "artboards", C)?.into_iter().filter_map(|i| st.doc.artboards.get(i)).map(|a| a.rect).collect();
let symbols = st.doc.symbol_boxes();
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation)
.into_iter()
@@ -108,6 +108,35 @@ fn bad_params_are_errors_and_leave_the_selection() {
}
}
/// A malformed `artboards` entry is refused as one, naming the parameter, before any entry is
/// looked up; a value that is not a list, an empty list, a left-out list and a whole number past
/// the last artboard each have their own error.
#[test]
fn artboard_errors_say_what_is_wrong() {
let mut s = three_boards();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
let entries = "invalid parameters for `addon.select.byArtboards`: `artboards` must contain whole numbers";
let not_a_list = "invalid parameters for `addon.select.byArtboards`: `artboards` must be a list of artboard indices";
for (p, want) in [
(json!({"artboards": ["1"]}), entries),
(json!({"artboards": [-1]}), entries),
(json!({"artboards": [1.5]}), entries),
(json!({"artboards": [true]}), entries),
(json!({"artboards": [9, "1"]}), entries),
(json!({"artboards": "0"}), not_a_list),
(json!({"artboards": null}), not_a_list),
(json!({"artboards": []}), "invalid parameters for `addon.select.byArtboards`: choose at least one artboard"),
(json!({}), "invalid parameters for `addon.select.byArtboards`: missing `artboards`"),
(json!({"artboards": [9]}), "no such artboard"),
(json!({"artboards": [0, 9]}), "no such artboard"),
] {
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
assert_eq!(s.execute(C, &p).unwrap_err().to_string(), want, "{p}");
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{p}");
}
assert_eq!(pick(&mut s, json!({"artboards": [0, 0]})), vec![a]);
}
#[test]
fn a_symbol_instance_is_measured_by_its_art() {
// The symbol's art, (100, 60) to (140, 80), drawn 50 pt up and left: (50, 10) to (90, 30), on
+3 -3
View File
@@ -19,8 +19,8 @@ use super::edit::{outermost, selected_roots};
use super::pathops::{remove_each, separate};
use super::swatch::{anchor, names_param};
use super::{
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok,
str_param, switch_or,
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, named_ids, number_or, ok, str_param,
switch_or,
};
use crate::EngineError;
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paintbrush",
[],
None,
"{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, or a `style` other than \"pencil\" or \"brush\", is an error and nothing is drawn → {id}",
"{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, a `style` other than \"pencil\" or \"brush\", a `brush` for a path with no stroke (a continued or redrawn path without one, or a new filled \"pencil\" path while the stroke is None) and an unknown key are errors and nothing is drawn; the path and its brush are one undo step → {id}",
has_doc,
brush_freehand
),
+7 -14
View File
@@ -1,7 +1,6 @@
use super::{
AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value,
anchor, bad, brush, check_numbers, find_command, id_param, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown,
str_param,
anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param,
};
// ---------- brushes ----------
@@ -729,9 +728,10 @@ pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "ids": ids_json(&out) }))
}
/// Paints a `path.freehand` stroke with the brush `brush` names. A `brush` left out or null draws
/// the plain path; a `brush` that is not a string or names no brush in the document, and a `style`
/// other than "pencil" or "brush", is an error before anything is drawn.
/// Paints a `path.freehand` stroke with the brush `brush` names, in one undo step with the path.
/// A `brush` left out or null draws the plain path; a `brush` that is not a string or names no
/// brush in the document, a `style` other than "pencil" or "brush", and a `brush` for a path with
/// no stroke are errors before anything is drawn.
pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "brush.freehand";
let name = match crate::cmd::text_param(p, "brush", C)? {
@@ -745,13 +745,6 @@ pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
Some(v) => return Err(bad(C, format!("`style` must be \"pencil\" or \"brush\", not {v}"))),
}
let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?;
let r = crate::cmd::run_checked(s, spec, p)?;
let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) };
s.edit("Paintbrush", |d, _| {
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
st.brush = Some(name.clone());
}
Ok(())
})?;
Ok(r)
let checked = crate::schemas::check(spec, p, s.replaying())?;
crate::cmd::draw2::freehand_brushed(s, checked.as_ref().unwrap_or(p), name.as_deref())
}
+2 -2
View File
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket",
[],
None,
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face, count (faces reached)}",
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces: each face reached has its fills replaced by one fill with the paint, shown, fully opaque and blending normally, in the place of its topmost fill (none leaves one fill of none), and its strokes and its own opacity stay as they are; when every face it reaches already has only that one fill, nothing changes (no undo step, and the recent colors stay as they are) → {group, face, count (faces reached)}",
has_doc,
lp_fill
),
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket (Stroke)",
[],
None,
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached takes the paint and width in its topmost stroke that is shown, or in a new stroke above the others when it has none; when every edge it reaches already has the paint and the width there, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
has_doc,
lp_stroke_edge
),
+79 -39
View File
@@ -525,16 +525,17 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
Some(gid) => {
let (fid, targets) = targets_in(&s.doc()?.doc, gid)?;
let count = targets.len();
// Faces that already have the paint stay as they are: when every face has it, nothing
// changes and no undo step is recorded.
// Faces that already have only the fill the bucket would leave ([`bucket_keeps`]) stay as
// they are: when every face does, nothing changes and no undo step is recorded.
let d = &s.doc()?.doc;
let unpainted: Vec<NodeId> = targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| f.appearance.fill_paint() != paint)).collect();
let unpainted: Vec<NodeId> =
targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| !bucket_keeps(&f.appearance, true, &paint, 0.0))).collect();
if unpainted.is_empty() {
return Ok(json!({ "group": gid.0, "face": fid.0, "count": count }));
}
s.edit("Live Paint Bucket", |d, _| {
for target in unpainted {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
bucket_paint(&mut d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance, true, &paint, 0.0);
}
Ok((gid, fid, count))
})?
@@ -544,7 +545,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
let (fid, targets) = targets_in(d, gid)?;
let count = targets.len();
for target in targets {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
bucket_paint(&mut d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance, true, &paint, 0.0);
}
Ok((gid, fid, count))
})?,
@@ -580,18 +581,10 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
.collect(),
};
let count = targets.len();
// An edge whose shown stroke already has the paint and the width (or that has no shown stroke
// and gets none) stays as it is; when every edge does, nothing changes and no undo step is
// recorded.
let changed: Vec<NodeId> = targets
.into_iter()
.filter(|t| {
d.node(*t).is_none_or(|e| match shown_stroke(e) {
Some(st) => !(st.paint == paint && st.width == width),
None => !paint.is_none(),
})
})
.collect();
// An edge that already has only the stroke the bucket would leave ([`bucket_keeps`]) stays
// as it is; when every edge does, nothing changes and no undo step is recorded.
let changed: Vec<NodeId> =
targets.into_iter().filter(|t| d.node(*t).is_none_or(|e| !bucket_keeps(&e.appearance, false, &paint, width))).collect();
(eid, count, changed)
};
if changed.is_empty() {
@@ -599,14 +592,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
}
s.edit("Live Paint Bucket", |d, _| {
for target in &changed {
let e = d.node_mut(*target).ok_or(EngineError::NoNode(*target))?;
match shown_stroke_mut(e) {
Some(st) => {
st.paint = paint.clone();
st.width = width;
}
None => e.appearance.items.push(super::AppearanceItem::Stroke(super::StrokeLayer::new(paint.clone(), width))),
}
bucket_paint(&mut d.node_mut(*target).ok_or(EngineError::NoNode(*target))?.appearance, false, &paint, width);
}
Ok(())
})?;
@@ -614,22 +600,76 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "group": g.0, "edge": eid.0, "count": count }))
}
/// The stroke `livePaint.strokeEdge` paints on Live Paint edge `e`: its topmost stroke that is
/// shown. None when it has no stroke or every stroke is hidden; the command then adds a stroke
/// above the others.
fn shown_stroke(e: &Node) -> Option<&super::StrokeLayer> {
e.appearance.items.iter().rev().find_map(|i| match i {
super::AppearanceItem::Stroke(s) if s.visible => Some(s),
_ => None,
})
/// Whether the Live Paint Bucket leaves appearance `a` as it is when it paints its fills (`fill`)
/// or strokes with `paint` (a stroke at `width`): it has exactly one row of that kind, shown, fully
/// opaque, blending normally and with the paint (a stroke also with the width, unless the paint is
/// none), or it has no row of that kind and the paint is none.
fn bucket_keeps(a: &Appearance, fill: bool, paint: &super::Paint, width: f64) -> bool {
let mut rows = a.items.iter().filter(|i| i.is_fill() == fill);
match (rows.next(), rows.next()) {
(None, _) => paint.is_none(),
(Some(row), None) => {
row.visible()
&& row.opacity() == 1.0
&& row.blend() == vectorcraft_color::BlendMode::Normal
&& row.paint() == paint
&& match row {
AppearanceItem::Fill(_) => true,
AppearanceItem::Stroke(st) => paint.is_none() || st.width == width,
}
}
(Some(_), Some(_)) => false,
}
}
/// [`shown_stroke`], to change.
fn shown_stroke_mut(e: &mut Node) -> Option<&mut super::StrokeLayer> {
e.appearance.items.iter_mut().rev().find_map(|i| match i {
super::AppearanceItem::Stroke(s) if s.visible => Some(s),
_ => None,
})
/// Paint the fills (`fill`) or strokes of appearance `a` with `paint` (a stroke at `width`), as the
/// Live Paint Bucket does: every row of that kind is replaced by one row, shown, fully opaque and
/// blending normally, in the place of the topmost row of that kind. The new row keeps the other
/// settings (a stroke's dashes, caps and arrowheads, a row's effects) of the topmost row of that
/// kind that is shown, or of the topmost one when every row is hidden. Rows of the other kind stay
/// as they are. With no row of that kind, a fill is added below the strokes and a stroke above the
/// fills.
fn bucket_paint(a: &mut Appearance, fill: bool, paint: &super::Paint, width: f64) {
let of_kind = |i: &AppearanceItem| i.is_fill() == fill;
let Some(top) = a.items.iter().rposition(of_kind) else {
if fill {
a.set_fill(paint.clone());
} else {
a.items.push(AppearanceItem::Stroke(super::StrokeLayer::new(paint.clone(), width)));
}
return;
};
let base = a.items.iter().rposition(|i| of_kind(i) && i.visible()).unwrap_or(top);
let Some(mut row) = a.items.get(base).cloned() else { return };
match &mut row {
AppearanceItem::Fill(f) => {
f.paint = paint.clone();
f.opacity = 1.0;
f.blend = vectorcraft_color::BlendMode::Normal;
f.visible = true;
}
AppearanceItem::Stroke(st) => {
st.paint = paint.clone();
st.width = width;
st.opacity = 1.0;
st.blend = vectorcraft_color::BlendMode::Normal;
st.visible = true;
}
}
let mut row = Some(row);
a.items = std::mem::take(&mut a.items)
.into_iter()
.enumerate()
.filter_map(|(i, item)| {
if i == top {
row.take()
} else if of_kind(&item) {
None
} else {
Some(item)
}
})
.collect();
}
/// Every fill and stroke row of face or edge `n`, bottom first, as `livePaint.info` lists them. A
+30 -7
View File
@@ -12,6 +12,7 @@ use super::{
thread_local! {
static BOX_TESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static CANDIDATE_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static TRACES_ON_THIS_THREAD: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
// ---------- Image Trace ----------
@@ -548,15 +549,20 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
Ok(seams.into_iter().chain(groups).collect())
}
/// What a trace depends on: the document it is made in, the object traced (an image, or an Image
/// Trace object traced again), its image, the image's encoded bytes, and the settings it is traced
/// with. The tracer makes the same paths of the same inputs, so a trace made away from the command
/// ([`TraceRun`]) stands in for the command's own in the same document.
/// What a trace depends on: the document it is made in and the content it was reverted to, the
/// object traced (an image, or an Image Trace object traced again), its image, the image's encoded
/// bytes, and the settings it is traced with. The tracer makes the same paths of the same inputs,
/// so a trace made away from the command ([`TraceRun`]) stands in for the command's own in the same
/// document until File › Revert replaces its content.
#[derive(Clone, Debug, PartialEq)]
struct TraceInputs {
/// The [`DocState::uid`](crate::DocState::uid) of the document traced in. A trace made in one
/// document never stands in for one in another, however alike their images and settings.
doc: u64,
/// The document's [`DocState::reverts`](crate::DocState::reverts) when the trace was prepared.
/// A trace prepared before File › Revert never stands in for one after it, even when the
/// restored image, pixels, object and settings are the same.
reverts: u64,
target: NodeId,
image: Box<ImageObject>,
/// The settings traced with, as JSON.
@@ -625,7 +631,8 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
let bytes = Arc::clone(&blob.bytes);
let library = trace_library(c, s, &mut params)?;
let traced_with = serde_json::to_value(&params).map_err(|e| EngineError::Other(e.to_string()))?;
let inputs = TraceInputs { doc: s.doc()?.uid, target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
let st = s.doc()?;
let inputs = TraceInputs { doc: st.uid, reverts: st.reverts, target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
}
@@ -641,7 +648,8 @@ pub struct Traced {
impl Traced {
/// Hand it to the next run of its command with the same inputs ([`TraceRun::params`]) in the
/// document it was made in, which applies it as one undo step instead of tracing again. Any
/// other trace drops it, a trace in another document included.
/// other trace drops it and traces again, a trace in another document included, and so does
/// the command after File › Revert replaced the document's content.
pub fn hand_in(self, s: &mut Session) {
s.trace_hand_off = Some(self);
}
@@ -650,6 +658,8 @@ impl Traced {
/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has
/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
#[cfg(test)]
TRACES_ON_THIS_THREAD.with(|n| n.set(n.get() + 1));
// An image over the tracer's size is traced scaled down (the paths are scaled back).
let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
if !steps(0, 0) {
@@ -725,17 +735,30 @@ impl TraceRun {
}
/// Does it still apply: would the command trace the same object, image, pixels and settings
/// now, in the document it was prepared in?
/// now, in the document it was prepared in, with no File › Revert since?
pub fn current(&self, s: &Session) -> bool {
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
}
/// Has File › Revert replaced the content of the document it was prepared in since then? False
/// when that document is no longer open.
pub fn reverted(&self, s: &Session) -> bool {
let TraceInputs { doc, reverts, .. } = self.prepared.inputs;
s.documents().iter().any(|st| st.uid == doc && st.reverts != reverts)
}
/// Decode and trace the image, telling `steps` how far it has got → what it traced, or why it
/// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no
/// document, so it can run on any thread.
pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
trace_now(&self.prepared.inputs, &self.prepared.trace, steps)
}
/// How many images this thread has decoded and traced so far.
#[cfg(test)]
pub(crate) fn traces_on_this_thread() -> usize {
TRACES_ON_THIS_THREAD.with(std::cell::Cell::get)
}
}
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
+24 -8
View File
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Flare",
[],
None,
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?} → {id}",
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: places the rings along the path anew, keeping their count and sizes)} → {id}",
has_doc,
flare
),
@@ -429,6 +429,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
"direction",
"pathLength",
"seed",
"ringSeed",
];
check_numbers(p, &numbers, "shape.flare")?;
let pct = |k: &str, d: f64| (f64_or(p, k, d) / 100.0).clamp(0.0, 10.0);
@@ -450,14 +451,28 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
c + vectorcraft_geom::Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0)
}
};
// Deterministic pseudo-random sizes (same parameters → same flare).
let mut seed = p.get("seed").and_then(Value::as_u64).unwrap_or(0x2545_f491_4f6c_dd1d) | 1;
let mut rnd = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed >> 11) as f64 / (1u64 << 53) as f64
// Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings
// along the path from a sequence of its own; their count and sizes and the other parts stay.
let seed_of = |key: &str| match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))),
};
// The generator's state is odd (never 0).
let random = |mut state: u64| {
move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state >> 11) as f64 / (1u64 << 53) as f64
}
};
let mut rnd = random(seed_of("seed")?.unwrap_or(0x2545_f491_4f6c_dd1d) | 1);
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own.
let ring_seed = match seed_of("ringSeed")? {
Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))),
r => r,
};
let mut ring_at = ring_seed.map(|r| random((r << 1) | 1));
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
@@ -495,6 +510,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
// Rings along the path to the end point (Largest = % of the average ring size).
for _ in 0..rings {
let t = rnd();
let t = ring_at.as_mut().map_or(t, |next| next());
let at = c + (end - c) * t;
let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5);
let solid = rnd() < 0.5;
+2 -1
View File
@@ -356,7 +356,8 @@ fn mirror_open(sp: &SubPath, axis: &Axis, m: Affine) -> Vec<SubPath> {
if !end_on {
run.reverse();
}
let Some((last, body)) = run.anchors.split_last() else { return vec![] };
let run = run.anchors.into_vec();
let Some((last, body)) = run.split_last() else { return vec![] };
let q = axis.project(last.p);
let mut anchors = body.to_vec();
anchors.push(Anchor::with_handles(q, last.h_in, m * last.h_in));
+3 -9
View File
@@ -10,6 +10,7 @@ use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection,
use vectorcraft_geom::Vec2;
use super::edit::selected_roots;
use super::panelcmds::artboard_at;
use super::pathops::Beside;
use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable};
use super::{
@@ -201,7 +202,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Guide",
[],
None,
"{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}",
"{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (0-based whole number; an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default, or null, a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}",
has_doc,
guide_add
),
@@ -767,15 +768,8 @@ 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 = 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;
let ab = v.as_u64().and_then(|i| boards.get(usize::try_from(i).ok()?)).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
Some(ab.id)
}
None => None,
};
let st = s.doc()?;
let artboard = artboard_at(&st.doc, p, "artboard", "guide.add")?.and_then(|i| st.doc.artboards.get(i)).map(|a| a.id);
let layer = match id_param(p, "layer") {
Some(l) if st.doc.node(l).is_some_and(Node::is_layer) => Some(l),
Some(_) => return Err(bad("guide.add", "layer must name a layer or sublayer")),
+1
View File
@@ -33,3 +33,4 @@ mod smooth;
pub use commands::specs;
pub(super) use common::{ids_json, replace_with_pieces, usize_opt};
pub(super) use cut::{components, erase_outline};
pub(super) use freehand::freehand_brushed;
+76 -12
View File
@@ -46,7 +46,7 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
let sp = vectorcraft_tools::draw2::catmull_rom(&marked, false);
if sp.anchors.len() < 3 {
// Two anchors closed would run back over the line itself.
return SubPath::new(sp.anchors, closed && n > 2);
return SubPath::of(sp.anchors, closed && n > 2);
}
let fitted = po::simplify_with(
&PathData::single(sp.clone()),
@@ -62,7 +62,7 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
f.h_in = f.p;
}
}
SubPath::new(anchors, closed)
SubPath::of(anchors, closed)
}
/// The path of a freehand stroke: fitted at `tol` ([`fit_freehand`]), or with no `tol` the points
@@ -133,13 +133,13 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
*s0 = s1.p;
let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None };
*e0 = e1.p;
let fit = stroke_subpath(&stroke, tol, false).anchors;
let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec();
let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None };
let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default();
let (before, after): (Vec<Anchor>, Vec<Anchor>) = if sp.closed {
((0..=(start + n - end) % n).filter_map(|k| sp.anchors.get((end + k) % n).copied()).collect(), vec![])
} else {
(sp.anchors.get(..=start)?.to_vec(), sp.anchors.get(end..)?.to_vec())
(sp.anchors.get_range(..=start)?, sp.anchors.get_range(end..)?)
};
let mut anchors = before;
if let Some(a) = anchors.last_mut() {
@@ -157,6 +157,34 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
}
pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
freehand_brushed(s, p, None)
}
/// The object a brush on path `id` paints: the compound path a member path is in, else the path.
fn brush_target(d: &Document, id: NodeId) -> NodeId {
d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id)
}
/// Whether `ap` has a stroke a brush can paint: a stroke whose paint is not None.
fn can_brush(ap: &Appearance) -> bool {
ap.stroke().is_some_and(|st| !st.paint.is_none())
}
fn no_stroke(name: &str) -> EngineError {
bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke"))
}
/// Sets brush `name` on the stroke of object `id` of `d`.
fn set_brush(d: &mut Document, id: NodeId, name: &str) {
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
st.brush = Some(name.to_string());
}
}
/// `path.freehand`, with the stroke painted with brush `brush_name` (one `brush.freehand` has
/// checked) in the same undo step as the path. A path without a stroke is an error before
/// anything changes.
pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&str>) -> Result<Value> {
const C: &str = "path.freehand";
let samples = samples_param(p, "points", C)?;
if samples.iter().any(|q| !within_input_bound(q.pt)) {
@@ -173,6 +201,8 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
let closed = switch_or(p, "closed", false, C)?;
let brush = str_param(p, "style") == Some("brush");
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
let keep_selected = switch_or(p, "keepSelected", true, C)?;
let filled = switch_or(p, "fill", false, C)?;
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
@@ -180,6 +210,12 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
let at_start = str_param(ext, "end") == Some("start");
let (pd, _) = path_of(&s.doc()?.doc, id)?;
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
let target = brush_target(&s.doc()?.doc, id);
if let Some(name) = brush_name
&& !s.doc()?.doc.node(target).is_some_and(|n| can_brush(&n.appearance))
{
return Err(no_stroke(name));
}
let mut sp = pd.subpaths[si].clone();
let old_len = subpath_len(&sp);
if at_start {
@@ -191,6 +227,15 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) };
*p0 = end;
if pts.len() < 2 {
// No stroke to add: the brush alone changes, when it is not the path's already.
if let Some(name) = brush_name
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
{
s.edit("Paintbrush", |d, _| {
set_brush(d, target, name);
Ok(())
})?;
}
return Ok(json!({ "id": id.0 }));
}
// A stroke that ends on an open end of another path connects the two: (that path, its last
@@ -271,12 +316,12 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
// outgoing handle.
let mut other_len = 0.0;
if let Some((_, _, y, _)) = &connect
&& let Some((y0, rest)) = y.anchors.split_first()
&& let Some(y0) = y.anchors.first()
{
if let Some(last) = sp.anchors.last_mut() {
*last = Anchor::with_handles(y0.p, last.h_in + (y0.p - last.p), y0.h_out);
}
sp.anchors.extend_from_slice(rest);
sp.anchors.extend(y.anchors.iter().skip(1));
other_len = subpath_len(y);
}
// What the pen recorded along the path (in the direction it is continued in), followed by
@@ -290,7 +335,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
let drawn = old.extended(old_len, &pen, drawn_len - old_len);
if connect.is_some() { drawn.extended(drawn_len, &other, other_len) } else { drawn }
});
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
s.edit(label, |d, sel| {
let reverse = at_start && !sp.closed;
if reverse {
sp.reverse();
@@ -326,6 +371,9 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
{
if reverse { joined.reversed() } else { joined }.write(st);
}
if let Some(name) = brush_name {
set_brush(d, target, name);
}
if keep_selected {
sel.set([id]);
} else {
@@ -346,11 +394,19 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
// were, measured along the old path; fit them to the new length if strokes drawn with a
// pen get redrawn.
if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) {
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
// A member path of a compound path is redrawn in it: the compound path is what is
// selected, and what a brush paints.
let whole = brush_target(&s.doc()?.doc, id);
if let Some(name) = brush_name
&& !s.doc()?.doc.node(whole).is_some_and(|n| can_brush(&n.appearance))
{
return Err(no_stroke(name));
}
s.edit(label, |d, sel| {
*path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| bad(C, "no such subpath"))? = sp;
// A member path of a compound path is redrawn in it: the compound path is what is
// selected.
let whole = d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id);
if let Some(name) = brush_name {
set_brush(d, whole, name);
}
if keep_selected {
sel.set([whole]);
} else {
@@ -373,7 +429,15 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(st) = look.appearance.stroke_mut() {
pen.write(st);
}
let out = insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)?;
if let Some(name) = brush_name {
if !can_brush(&look.appearance) {
return Err(no_stroke(name));
}
if let Some(st) = look.appearance.stroke_mut() {
st.brush = Some(name.to_string());
}
}
let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?;
if !keep_selected {
// A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke
// by dropping the earlier selection, it does not keep it (#5752).
+11 -11
View File
@@ -274,7 +274,7 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
for a in &mut out {
*a = Anchor::with_handles(a.p, a.h_in, a.h_out);
}
out
out.into_vec()
}
/// Distance (points) from an anchor within which a smoothed closed path starts at that anchor
@@ -549,7 +549,7 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
if sp.closed {
let start = sp.anchors[0].p;
let Some(k) = marked.iter().position(|m| !m) else {
let corners = smooth_corners(&sp.anchors, true, radius);
let corners = smooth_corners(&sp.anchors.contiguous(), true, radius);
let Some(c) = corners.iter().position(|c| *c) else {
// Everything is in range and nothing is a corner: smooth the whole closed path,
// across its start too.
@@ -557,7 +557,7 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
return f.subpaths.into_iter().next().map(|r| start_nearest(r, start, sp));
};
// Cut the path open at a corner, which then ends the last part as well as starting the first.
let mut open = sp.anchors.clone();
let mut open = sp.anchors.to_vec();
open.rotate_left(c);
let mut cut = corners;
cut.rotate_left(c);
@@ -576,15 +576,14 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
return Some(start_nearest(SubPath::new(res, true), start, sp));
};
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
let mut open = sp.clone();
open.anchors.rotate_left(k);
let mut open = sp.anchors.to_vec();
open.rotate_left(k);
let mut m = marked.clone();
m.rotate_left(k);
open.anchors.push(open.anchors[0]);
open.push(open[0]);
m.push(false);
open.closed = false;
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, radius, false);
if same_anchors(&res, &open.anchors) {
let mut res = smooth_open(&open, &m, near, tol, sigma, radius, false);
if same_anchors(&res, &open) {
return None;
}
let l = res.pop()?;
@@ -595,8 +594,9 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
let res = SubPath::new(res, true);
return Some(if k == 0 { res } else { start_nearest(res, start, sp) });
}
let res = smooth_open(&sp.anchors, &marked, near, tol, sigma, radius, true);
(!same_anchors(&res, &sp.anchors)).then(|| SubPath::new(res, false))
let anchors = sp.anchors.contiguous();
let res = smooth_open(&anchors, &marked, near, tol, sigma, radius, true);
(!same_anchors(&res, &anchors)).then(|| SubPath::new(res, false))
}
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
+5 -1
View File
@@ -146,7 +146,11 @@ fn text(k: &str, v: &Value, multiline: bool) -> Result<String> {
return Err(bad(C, format!("{k} is too long (at most {MAX_TEXT} characters)")));
}
if s.chars().any(|c| c.is_control() && !(multiline && matches!(c, '\n' | '\r' | '\t'))) {
return Err(bad(C, format!("{k} has control characters{}", if multiline { "" } else { " or line breaks" })));
return Err(if multiline {
bad(C, format!("{k} has control characters"))
} else {
bad(C, format!("{k} has control characters or line breaks"))
});
}
Ok(s.to_string())
}
+6
View File
@@ -54,6 +54,7 @@ pub mod ppi;
pub mod progress;
mod psdlayers;
pub mod psdread;
mod psdslices;
mod pxrread;
mod save;
mod screens;
@@ -93,6 +94,9 @@ pub(crate) use native::preview_png;
pub use native::with_compression_pref;
pub(crate) use pdfimport::opened_page_document;
pub use pdfimport::{LoadOptions, page_document};
pub(crate) use psdlayers::import_active as psd_layers;
pub use psdlayers::{PsdInfo, info as psd_info};
pub(crate) use psdslices::over as psd_slices;
pub(crate) use save::job_for;
pub(crate) use save::save as save_document;
pub use save::{
@@ -240,6 +244,8 @@ mod tests_psd;
mod tests_psdlayers;
#[cfg(test)]
mod tests_psdread;
#[cfg(test)]
mod tests_psdslices;
#[cfg(test)]
mod tests_heifread;
+11 -2
View File
@@ -1,6 +1,6 @@
use super::access::file_list;
use super::formats::formats;
use super::{CommandSpec, action_batch, always, batch, cmd, export, has_doc, has_selection, load, pdfimport, save, screens};
use super::{CommandSpec, action_batch, always, batch, cmd, export, has_doc, has_selection, load, pdfimport, psdlayers, save, screens};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.p Line truncated
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size Line truncated
always,
load::open
),
@@ -139,6 +139,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
pdfimport::pdf_info
),
cmd!(
query "document.psdInfo",
"PSD Info",
[],
None,
"{path} or {name?, dataBase64} what a PSD or PSB file holds, read from its header, slices and layer records without decoding pixels → {format: psd|psb, width, height (the canvas, px), layers (group markers not counted), hiddenLayers (the hidden ones among them), groups, slices (those importSlices brings in; 0 when the file has none or they can't be read)}; a file without layer records, or whose layer records can't be read, has layers: 0 and opens and places as its merged image; a file that is not a PSD or PSB file is an error",
always,
psdlayers::psd_info
),
cmd!(
"document.exportForOffice",
"Save for Office Documents…",
+17 -8
View File
@@ -528,17 +528,26 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
}
// 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),
}
}
"psd" | "psb" if opts.layers => match super::psdlayers::import_active(bytes, opts.hidden_layers) {
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))),
};
// A PSD or PSB file's slices become user slices over its canvas (`importSlices`, default on),
// whether its layers or its merged image came in.
if matches!(format.id, "psd" | "psb")
&& opts.import_slices
&& let Some(canvas) = doc.artboards.first().map(|a| a.rect)
{
let (slices, notes) = super::psd_slices(bytes, canvas);
for (rect, options) in slices {
crate::cmd::slices::add_slice(&mut doc, rect, options);
}
warnings.extend(notes);
}
// A PDF, `.ai` or `.ait` read from its pages or its editing copy, not restored from the document
// it carries, opens with the File Info it gives (a PostScript `.ai` gives none).
if matches!(format.id, "pdf" | "ai" | "ait")
+6 -8
View File
@@ -236,15 +236,13 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
}
/// `doc` with its path geometry rounded to `decimals` places, as [`vectorcraft_format::save_to`]
/// writes it for `version`: placed documents become groups of their art for older versions.
/// writes it for `version`: placed documents, those in the stored brushes' art included, become
/// groups of their art for older versions.
fn rounded(doc: &Document, version: u32, decimals: u8) -> Document {
let mut d = if version < vectorcraft_format::VERSION && doc.has_placed() {
let mut d = doc.with_placed_art().into_owned();
d.placed_as_groups();
d
} else {
doc.clone()
};
let mut d = doc.clone();
if version < vectorcraft_format::VERSION {
vectorcraft_format::placed_as_groups(&mut d);
}
d.round_geometry(decimals.min(vectorcraft_format::MAX_PRECISION));
d
}
+9 -1
View File
@@ -36,6 +36,8 @@ pub struct LoadOptions {
pub layers: bool,
/// A PSD or PSB file's hidden layers come in, hidden (`hiddenLayers`; else they are left out).
pub hidden_layers: bool,
/// A PSD or PSB file's slices become user slices (`importSlices`; else they are left out).
pub import_slices: 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
@@ -67,6 +69,7 @@ impl Default for LoadOptions {
text_as: TextAs::default(),
layers: true,
hidden_layers: false,
import_slices: true,
dxf: Default::default(),
editing_data: true,
trust_editing_data: false,
@@ -81,7 +84,7 @@ 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), `hiddenLayers` (true | false),
/// `editingData` (true | false | `always`),
/// `importSlices` (true | false), `editingData` (true | false | `always`),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
/// false) and `dxf` (the DXF import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
@@ -111,6 +114,10 @@ impl LoadOptions {
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "hiddenLayers must be true or false"))?,
};
let import_slices = match p.get("importSlices").filter(|v| !v.is_null()) {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "importSlices 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),
@@ -137,6 +144,7 @@ impl LoadOptions {
text_as,
layers,
hidden_layers,
import_slices,
dxf,
editing_data,
trust_editing_data,
+64
View File
@@ -43,6 +43,7 @@ use std::cell::Cell;
use std::sync::Arc;
use image::RgbaImage;
use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
use vectorcraft_color::blend::{blend_rgb, composite};
use vectorcraft_color::cms::{Lab, lab::lab_to_srgb};
@@ -51,6 +52,7 @@ use vectorcraft_geom::Affine;
use super::load::{RasterImage, as_png};
use super::psdread::{Header, Reader, byte, header, layer_channel, layer_info, long_key, row_bytes, sample, to_rgb};
use crate::cmd::Session;
use crate::cmd::place::text::mac_roman;
/// Most layer groups inside one another.
@@ -1527,3 +1529,65 @@ pub(super) fn import(
doc.limit_depth_noting(&mut warnings);
Ok(Some((doc, warnings)))
}
/// [`import`] within the memory allowed for one image, CMYK converted with the active color
/// settings: what `document.open` and `file.place` read a PSD or PSB file's layers with.
pub(crate) fn import_active(bytes: &[u8], hidden: bool) -> Result<Option<(Document, Vec<String>)>, String> {
let cms = vectorcraft_color::cms::active();
import(bytes, hidden, super::MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false))
}
/// What a PSD or PSB file holds (`document.psdInfo`, the PSD Import Options dialog).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PsdInfo {
/// The large document format.
pub psb: bool,
/// The canvas, in pixels.
pub width: u32,
pub height: u32,
/// The layers, group markers left out.
pub layers: usize,
/// The layers among them that are hidden.
pub hidden: usize,
/// The layer groups.
pub groups: usize,
/// The slices that come in with `importSlices` (those generated automatically, and those
/// outside the canvas, left out).
pub slices: usize,
}
/// What PSD or PSB file `bytes` holds, read from its header, its slices and its layer records
/// without decoding any pixels. A file without layer records, or whose layer records can't be read, has no layers: it
/// opens and places as its merged image.
pub fn info(bytes: &[u8]) -> Result<PsdInfo, String> {
let mut r = Reader::new(bytes);
let h = header(&mut r)?;
let records = layer_info(h.layers, h.psb).filter(|info| info.len() > 2).and_then(|info| records(info, h.psb).ok()).unwrap_or_default();
let layers = records.iter().filter(|r| r.divider == 0);
Ok(PsdInfo {
psb: h.psb,
width: h.width,
height: h.height,
layers: layers.clone().count(),
hidden: layers.filter(|r| r.hidden).count(),
groups: records.iter().filter(|r| matches!(r.divider, 1 | 2)).count(),
slices: super::psdslices::count(bytes),
})
}
const INFO: &str = "document.psdInfo";
/// `document.psdInfo`.
pub(super) fn psd_info(_: &mut Session, p: &Value) -> crate::cmd::Result<Value> {
let bytes = super::source(p, INFO)?.bytes;
let i = info(&bytes).map_err(super::load::err)?;
Ok(json!({
"format": if i.psb { "psb" } else { "psd" },
"width": i.width,
"height": i.height,
"layers": i.layers,
"hiddenLayers": i.hidden,
"groups": i.groups,
"slices": i.slices,
}))
}
+2 -2
View File
@@ -105,7 +105,7 @@ pub(super) struct Header<'a> {
/// Colour mode data: an indexed image's palette (256 reds, then greens, then blues).
palette: &'a [u8],
/// The image resources.
resources: &'a [u8],
pub(super) resources: &'a [u8],
/// The layer and mask information.
pub(super) layers: &'a [u8],
}
@@ -172,7 +172,7 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
/// The image resource blocks of `resources`, in file order: each one's id, name (the bytes of its
/// Pascal string) and data. Stops at the first block that is cut short. With `signed`, only the
/// blocks whose signature is `8BIM` are given.
fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
pub(super) fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
let mut r = Reader::new(resources);
std::iter::from_fn(move || {
if r.rest().is_empty() {
+408
View File
@@ -0,0 +1,408 @@
//! The slices a Photoshop document (PSD or PSB) stores, for `document.open` and `file.place`
//! with `importSlices`: image resource 1050, read from the "Slices resource format" of Adobe's
//! public Photoshop File Formats Specification
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). Version 6 stores the slices
//! as records; versions 7 and 8 store them in a descriptor. The descriptor's keys, and the meaning
//! of the origin, type and background values, are read as the MIT-licensed ag-psd reads them
//! (<https://github.com/Agamnentzar/ag-psd>, `src/imageResources.ts` and `src/descriptor.ts`),
//! which agrees with psd.rb (<https://github.com/layervault/psd.rb>,
//! `lib/psd/resources/slices.rb`) on the keys both read.
//!
//! A slice the file marks as generated automatically is left out: the document lays out its own
//! auto slices around the others. A slice that follows a layer comes in as a user slice over the
//! rectangle the file stores for it. Each slice keeps its name, its type (Image or No Image), its
//! link, target, message, alternative text, cell text and background color; text alignment isn't
//! read. The file is untrusted: every read is checked, and the slice count, the strings and the
//! descriptor's nesting and item count are capped.
use vectorcraft_doc::{SliceKind, SliceOptions};
use vectorcraft_geom::Rect;
use super::psdread::{Reader, TRUNCATED, header, resources};
/// The image resource that holds the slices.
const SLICES: u16 = 1050;
/// The most slices one file brings in.
const MAX_SLICES: usize = 10_000;
/// The deepest descriptor objects and lists nest.
const MAX_DEPTH: usize = 16;
/// The most values the descriptors of one slices resource hold together, nested ones included.
const MAX_VALUES: usize = 200_000;
/// The error of descriptors that hold more than [`MAX_VALUES`].
const TOO_MANY_VALUES: &str = "the slices' descriptor holds too many values";
/// One slice as the file stores it.
#[derive(Clone, Debug, PartialEq)]
struct PsdSlice {
/// Left, top, right and bottom, in the canvas's pixels.
rect: [i64; 4],
options: SliceOptions,
}
/// The slices a file stores, those generated automatically left out, and its canvas.
struct Stored {
slices: Vec<PsdSlice>,
/// The canvas's width and height, in pixels.
size: (u32, u32),
}
/// The slices PSD or PSB file `bytes` stores. `None` when it stores none (no `8BIM` resource 1050
/// before the image resources end or are cut short). An error when the file isn't a PSD or PSB
/// file, or its slices can't be read.
fn read(bytes: &[u8]) -> Result<Option<Stored>, String> {
let mut r = Reader::new(bytes);
let h = header(&mut r)?;
let Some((_, _, data)) = resources(h.resources, true).find(|(id, _, _)| *id == SLICES) else { return Ok(None) };
Ok(Some(Stored { slices: decode(data)?, size: (h.width, h.height) }))
}
/// The slices of resource 1050's `data`.
fn decode(data: &[u8]) -> Result<Vec<PsdSlice>, String> {
let mut r = Reader::new(data);
// The values every descriptor of the resource may hold together.
let mut budget = MAX_VALUES;
match r.u32()? {
6 => version_6(&mut r, &mut budget),
7 | 8 => {
if r.u32()? != 16 {
return Err("the slices' descriptor has a version other than 16".into());
}
let d = descriptor(&mut r, 0, &mut budget)?;
from_descriptor(&d)
}
v => Err(format!("the slices are stored in version {v}, which isn't read")),
}
}
/// Version 6: the bounds of all the slices, the group's name, the count, then each slice's record.
/// The descriptors that follow the records spend one `budget` of values between them.
fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, String> {
r.take(16)?;
unicode(r)?;
let count = r.u32()? as usize;
if count > MAX_SLICES {
return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read"));
}
let mut out = vec![];
for _ in 0..count {
// The ID and group ID.
r.take(8)?;
let origin = r.u32()?;
// A slice that follows a layer gives the layer's ID.
if origin == 1 {
r.take(4)?;
}
let name = unicode(r)?;
let kind = if r.u32()? == 0 { SliceKind::NoImage } else { SliceKind::Image };
let mut rect = [0i64; 4];
for v in &mut rect {
*v = i64::from(r.u32()? as i32);
}
let (url, target, message, alt) = (unicode(r)?, unicode(r)?, unicode(r)?, unicode(r)?);
let html = r.u8()? != 0;
let cell = unicode(r)?;
// The horizontal and vertical alignment.
r.take(8)?;
let [a, red, green, blue] = r.array::<4>()?;
let background = if a == 0 && red == 0 && green == 0 && blue == 0 {
String::new()
} else if a == 0 {
"matte".into()
} else {
format!("#{red:02x}{green:02x}{blue:02x}")
};
// Photoshop 7 and later may follow a record with a descriptor (version 16); a record that
// doesn't start one is the next slice. A descriptor read that uses up the budget is an
// error.
if r.rest().starts_with(&16u32.to_be_bytes()) {
let mut ahead = Reader::new(r.rest());
ahead.u32()?;
match descriptor(&mut ahead, 0, budget) {
Ok(_) => {
let used = r.rest().len() - ahead.rest().len();
r.take(used)?;
}
Err(e) if e == TOO_MANY_VALUES => return Err(e),
Err(_) => {}
}
}
// Origin 0 is a slice generated automatically.
if origin != 0 {
let options = SliceOptions { kind, name, url, target, message, alt, text: cell_text(cell, html), background, ..Default::default() };
out.push(PsdSlice { rect, options: for_kind(options) });
}
}
Ok(out)
}
/// Versions 7 and 8: the descriptor's `slices` list, each slice an object.
fn from_descriptor(d: &[(String, Value)]) -> Result<Vec<PsdSlice>, String> {
let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) };
if list.len() > MAX_SLICES {
return Err(format!("the file has {} slices, more than the {MAX_SLICES} read", list.len()));
}
let mut out = vec![];
for s in list {
let Value::Object(s) = s else { return Err("the slices' descriptor lists something other than a slice".into()) };
if matches!(field(s, "origin"), Some(Value::Enum(_, v)) if v == "autoGenerated") {
continue;
}
let Some(Value::Object(b)) = field(s, "bounds") else { return Err("a slice in the slices' descriptor has no bounds".into()) };
let edge = |k: &str| number(field(b, k)).ok_or_else(|| "a slice's bounds in the slices' descriptor aren't numbers".to_string());
let rect = [edge("Left")?, edge("Top ")?, edge("Rght")?, edge("Btom")?];
let text = |k: &str| match field(s, k) {
Some(Value::Text(t)) => t.clone(),
_ => String::new(),
};
let kind = if matches!(field(s, "Type"), Some(Value::Enum(_, v)) if v == "noImage") { SliceKind::NoImage } else { SliceKind::Image };
let html = matches!(field(s, "cellTextIsHTML"), Some(Value::Bool(true)));
let background = match field(s, "bgColorType") {
Some(Value::Enum(_, v)) if v == "matte" => "matte".into(),
Some(Value::Enum(_, v)) if v == "Clr " => match field(s, "bgColor") {
Some(Value::Object(c)) => {
let channel = |k: &str| number(field(c, k)).map(|v| v.clamp(0, 255));
match (channel("Rd "), channel("Grn "), channel("Bl ")) {
(Some(r), Some(g), Some(b)) => format!("#{r:02x}{g:02x}{b:02x}"),
_ => String::new(),
}
}
_ => String::new(),
},
_ => String::new(),
};
let options = SliceOptions {
kind,
name: text("Nm "),
url: text("url"),
target: text("null"),
message: text("Msge"),
alt: text("altTag"),
text: cell_text(text("cellText"), html),
background,
..Default::default()
};
out.push(PsdSlice { rect, options: for_kind(options) });
}
Ok(out)
}
/// `o` with only the options of its slice type: an Image slice's cell text isn't shown, and a No
/// Image slice has no link, target, message or alternative text.
fn for_kind(mut o: SliceOptions) -> SliceOptions {
if o.kind == SliceKind::Image {
o.text.clear();
} else {
for s in [&mut o.url, &mut o.target, &mut o.message, &mut o.alt] {
s.clear();
}
}
o
}
/// A cell's text as the HTML a No Image slice shows: plain text has `&`, `<` and `>` escaped.
fn cell_text(text: String, html: bool) -> String {
if html { text } else { text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;") }
}
/// The longest text one string, key or class ID holds (UTF-16 units or bytes).
const MAX_TEXT: usize = 65_536;
/// An error unless `n`, the length a string or ID declares, is at most [`MAX_TEXT`].
fn text_len(n: usize) -> Result<usize, String> {
if n > MAX_TEXT {
return Err(format!("a text in the slices has more than the {MAX_TEXT} characters read"));
}
Ok(n)
}
/// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped.
fn unicode(r: &mut Reader<'_>) -> Result<String, String> {
let n = text_len(r.u32()? as usize)?;
let bytes = r.take(n.checked_mul(2).ok_or(TRUNCATED)?)?;
let units: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect();
Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string())
}
/// A descriptor's value, as far as the slices need it.
#[derive(Clone, Debug, PartialEq)]
enum Value {
Long(i32),
Double(f64),
Bool(bool),
Text(String),
/// An enumeration's type and value.
Enum(String, String),
Object(Vec<(String, Value)>),
List(Vec<Value>),
/// A value of another type, read past.
Other,
}
/// The value with key `key`.
fn field<'a>(d: &'a [(String, Value)], key: &str) -> Option<&'a Value> {
d.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
/// A whole number: a long, or a finite double rounded.
fn number(v: Option<&Value>) -> Option<i64> {
match v? {
Value::Long(n) => Some(i64::from(*n)),
Value::Double(d) if d.is_finite() && d.abs() < 1e12 => Some(d.round() as i64),
_ => None,
}
}
/// A key or class ID: a length, then that many characters, or four when the length is 0.
fn id(r: &mut Reader<'_>) -> Result<String, String> {
let n = text_len(r.u32()? as usize)?;
let b = r.take(if n == 0 { 4 } else { n })?;
Ok(String::from_utf8_lossy(b).into_owned())
}
/// A class: its Unicode name, then its ID.
fn class(r: &mut Reader<'_>) -> Result<(), String> {
unicode(r)?;
id(r)?;
Ok(())
}
/// A descriptor: its class, the count of its items, then each item's key, type and value.
fn descriptor(r: &mut Reader<'_>, depth: usize, budget: &mut usize) -> Result<Vec<(String, Value)>, String> {
if depth > MAX_DEPTH {
return Err("the slices' descriptor nests too deep".into());
}
class(r)?;
let count = r.u32()? as usize;
let mut out = vec![];
for _ in 0..count {
let key = id(r)?;
let kind = r.array::<4>()?;
out.push((key, value(r, &kind, depth, budget)?));
}
Ok(out)
}
/// A value of type `kind`.
fn value(r: &mut Reader<'_>, kind: &[u8; 4], depth: usize, budget: &mut usize) -> Result<Value, String> {
*budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?;
Ok(match kind {
b"long" => Value::Long(r.u32()? as i32),
b"doub" => Value::Double(f64::from_be_bytes(r.array()?)),
b"UntF" => {
r.take(4)?;
Value::Double(f64::from_be_bytes(r.array()?))
}
b"UnFl" => {
r.take(4)?;
Value::Double(f64::from(f32::from_be_bytes(r.array()?)))
}
b"bool" => Value::Bool(r.u8()? != 0),
b"TEXT" => Value::Text(unicode(r)?),
b"enum" => Value::Enum(id(r)?, id(r)?),
b"Objc" | b"GlbO" => Value::Object(descriptor(r, depth + 1, budget)?),
b"VlLs" => {
if depth >= MAX_DEPTH {
return Err("the slices' descriptor nests too deep".into());
}
let count = r.u32()? as usize;
let mut items = vec![];
for _ in 0..count {
let kind = r.array::<4>()?;
items.push(value(r, &kind, depth + 1, budget)?);
}
Value::List(items)
}
b"comp" => {
r.take(8)?;
Value::Other
}
b"type" | b"GlbC" => {
class(r)?;
Value::Other
}
b"tdta" | b"alis" => {
let n = r.u32()? as usize;
r.take(n)?;
Value::Other
}
b"obj " => {
let count = r.u32()? as usize;
for _ in 0..count {
*budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?;
match &r.array::<4>()? {
b"prop" => {
class(r)?;
id(r)?;
}
b"Clss" => class(r)?,
b"Enmr" => {
class(r)?;
id(r)?;
id(r)?;
}
b"rele" => {
class(r)?;
r.take(4)?;
}
b"Idnt" | b"indx" => {
r.take(4)?;
}
b"name" => {
class(r)?;
unicode(r)?;
}
k => return Err(format!("the slices' descriptor has a reference of an unknown kind ({})", String::from_utf8_lossy(k))),
}
}
Value::Other
}
k => return Err(format!("the slices' descriptor has a value of an unknown type ({})", String::from_utf8_lossy(k))),
})
}
/// The slices of PSD or PSB file `bytes` laid over `canvas`, the box its canvas takes (points),
/// each clipped to the canvas, with warnings: for slices that lie wholly outside it or have no
/// size, and for slices that can't be read (the file comes in without them). Empty, without a
/// warning, when the file stores no slices.
pub(crate) fn over(bytes: &[u8], canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec<String>) {
match read(bytes) {
Ok(None) => (vec![], vec![]),
Ok(Some(s)) => laid_over(&s.slices, s.size, canvas),
Err(e) => (vec![], vec![format!("the slices can't be read ({e}) and were left out")]),
}
}
/// `slices` of a canvas of `size` pixels laid over `canvas` (points).
fn laid_over(slices: &[PsdSlice], (w, h): (u32, u32), canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec<String>) {
let (sx, sy) = (canvas.width() / f64::from(w.max(1)), canvas.height() / f64::from(h.max(1)));
let mut out = vec![];
for s in slices {
let [l, t, r, b] = s.rect;
let (l, r) = (l.clamp(0, i64::from(w)), r.clamp(0, i64::from(w)));
let (t, b) = (t.clamp(0, i64::from(h)), b.clamp(0, i64::from(h)));
if l < r && t < b {
let x = |v: i64| canvas.x0 + v as f64 * sx;
let y = |v: i64| canvas.y0 + v as f64 * sy;
out.push((Rect::new(x(l), y(t), x(r), y(b)), s.options.clone()));
}
}
let warnings = match slices.len() - out.len() {
0 => vec![],
1 => vec!["1 slice lies outside the canvas or has no size and was left out".to_string()],
n => vec![format!("{n} slices lie outside the canvas or have no size and were left out")],
};
(out, warnings)
}
/// How many slices of PSD or PSB file `bytes` come in (`document.psdInfo`): 0 when it stores none
/// or they can't be read.
pub(crate) fn count(bytes: &[u8]) -> usize {
match read(bytes) {
Ok(Some(Stored { slices, size: (w, h) })) => laid_over(&slices, (w, h), Rect::new(0.0, 0.0, f64::from(w), f64::from(h))).0.len(),
_ => 0,
}
}
+187 -1
View File
@@ -1,7 +1,8 @@
//! Opening PSD and PSB files with their layers as layers (`document.open`'s `layers` and
//! `hiddenLayers`): names, visibility, opacity, blend modes, groups, layer masks, clipped layers
//! and blend modes VectorCraft lacks merged, 16-bit and PSB files, VectorCraft's own PSD export
//! read back, and damaged files read without a panic.
//! read back, and damaged files read without a panic. Placing them with their layers as objects
//! (`file.place`'s `layers` and `hiddenLayers`), and `document.psdInfo`.
use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
@@ -967,10 +968,12 @@ fn damaged_layers_never_panic() {
let mut f = good.clone();
f[i] = v;
let _ = psdlayers::import(&f, true, 1 << 30, cms);
let _ = psdlayers::info(&f);
}
}
for n in 0..good.len() {
let _ = psdlayers::import(&good[..n], true, 1 << 30, cms);
let _ = psdlayers::info(&good[..n]);
}
// A layer past the memory allowed is refused, not read.
assert!(psdlayers::import(&good, true, 64, cms).unwrap_err().contains("too large"));
@@ -1015,3 +1018,186 @@ fn merges_keep_pass_through_groups_blending_with_what_is_below() {
assert!(px.iter().zip([75, 150, 38, 255]).all(|(&a, b)| a.abs_diff(b) <= 1), "{px:?}");
}
}
/// `file.place` of `f` with `p` into a new 100 × 100 pt document, centred on (50, 50).
fn place(f: &[u8], p: Value) -> (Session, crate::cmd::Result<Value>) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("file.place", &merge(json!({"name": "layers.psd", "dataBase64": vectorcraft_format::base64_encode(f), "at": [50, 50]}), p));
(s, r)
}
/// The one object `file.place` placed.
fn placed(s: &Session, r: &Value) -> Node {
let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap());
s.doc().unwrap().doc.node(id).unwrap().clone()
}
#[test]
fn placing_with_layers_embeds_the_layers_as_one_group() {
let f = file(8, 8, &stack(), 8, false, false);
let (mut s, r) = place(&f, json!({"layers": true}));
let r = r.unwrap();
assert_eq!((&r["format"], &r["linked"], &r["warnings"]), (&json!("psd"), &json!(false), &json!([HIDDEN_1])), "{r}");
let g = placed(&s, &r);
assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "one group, unclipped: its layers lie on the canvas");
assert_eq!(name(&g), "layers.psd");
let kids = g.children().unwrap();
assert_eq!(kids.iter().map(|c| name(c)).collect::<Vec<_>>(), ["Bottom", "Folder", "Screens", "Faded"], "bottom first");
// A layer is its image, where the merged image would put it: the 8 pt canvas centred on (50, 50).
let ((x, y), px) = pixels_of(&s, &kids[0]);
assert_eq!(((x, y), px.dimensions(), px.get_pixel(3, 3).0), ((46.0, 46.0), (8, 8), [255, 0, 0, 255]));
// A group is a group of its layers; a pass-through group isn't isolated, another mode's is.
let folder = &kids[1];
assert!(matches!(folder.kind, NodeKind::Group { .. }) && !folder.isolate && folder.blend == BlendMode::Normal);
let inner = folder.children().unwrap();
assert_eq!(inner.iter().map(|c| name(c)).collect::<Vec<_>>(), ["Inner A"], "the hidden layer is left out");
assert!(matches!(inner[0].kind, NodeKind::Image(_)) && inner[0].blend == BlendMode::Multiply && (inner[0].opacity - 128.0 / 255.0).abs() < 1e-6);
let screens = &kids[2];
assert!(screens.isolate && screens.blend == BlendMode::Screen);
let ((x, y), px) = pixels_of(&s, &screens.children().unwrap()[0]);
assert_eq!(((x, y), px.get_pixel(0, 0).0), ((48.0, 48.0), [10, 20, 30, 128]));
assert!((kids[3].opacity - 102.0 / 255.0).abs() < 1e-6, "fill opacity: {}", kids[3].opacity);
// One undo step.
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)));
// Hidden layers come in hidden when asked for.
let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true}));
let r = r.unwrap();
assert_eq!(r["warnings"], json!([]), "{r}");
let g = placed(&s, &r);
let inner: Vec<(&str, bool)> = g.children().unwrap()[1].children().unwrap().iter().map(|c| (name(c), c.visible)).collect();
assert_eq!(inner, [("Inner A", true), ("Inner B", false)]);
// Without `layers`, the merged image, in the same box.
let (s, r) = place(&f, json!({}));
let r = r.unwrap();
let flat = placed(&s, &r);
let ((x, y), px) = pixels_of(&s, &flat);
assert_eq!(((x, y), px.dimensions(), px.get_pixel(0, 0).0), ((46.0, 46.0), (8, 8), [128, 128, 128, 255]), "{r}");
}
#[test]
fn placed_layers_keep_their_masks_and_are_clipped_to_the_canvas() {
let mut masked = layer("Masked", [0, 0, 8, 8], [255, 255, 255, 255]);
masked.mask = Some(([2, 2, 4, 4], 0, 0, vec![255, 128, 0, 255]));
let (s, r) = place(&file(8, 8, &[masked], 8, false, false), json!({"layers": true}));
let g = placed(&s, &r.unwrap());
let kids = g.children().unwrap();
assert!(matches!(kids[0].kind, NodeKind::Image(_)), "the layer is its image");
let m = kids[0].extras().mask.as_deref().expect("the layer mask as the image's opacity mask");
let ((x, y), px) = pixels_of(&s, &m.art);
assert_eq!(((x, y), px.dimensions(), m.clip), ((48.0, 48.0), (2, 2), true), "the mask moves with its layer");
// A layer that reaches past the canvas: the group is clipped to the canvas, as the merged
// image shows only the canvas.
let over = layer("Over", [-2, -2, 6, 6], [0, 255, 0, 255]);
let (s, r) = place(&file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), over], 8, false, false), json!({"layers": true}));
let r = r.unwrap();
let g = placed(&s, &r);
assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}");
let kids = g.children().unwrap();
let b = kids[0].geometric_bounds_with(&s.doc().unwrap().doc.symbol_boxes()).unwrap();
assert!(matches!(kids[0].kind, NodeKind::Path { clipping: true, .. }));
assert_eq!((b.x0, b.y0, b.x1, b.y1), (46.0, 46.0, 54.0, 54.0), "the clipping path is the canvas");
assert_eq!(kids[1..].iter().map(|c| name(c)).collect::<Vec<_>>(), ["Bottom", "Over"]);
assert_eq!(pixels_of(&s, &kids[2]).0, (44.0, 44.0));
// A hidden layer that reaches past the canvas clips the group too, so showing it later draws
// only the canvas. Left out, it doesn't.
let mut hidden = layer("Hidden", [-2, -2, 6, 6], [0, 255, 0, 255]);
hidden.hidden = true;
let f = file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), hidden], 8, false, false);
let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true}));
let r = r.unwrap();
let g = placed(&s, &r);
assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}");
assert_eq!(g.children().unwrap()[1..].iter().map(|c| (name(c), c.visible)).collect::<Vec<_>>(), [("Bottom", true), ("Hidden", false)]);
let (s, r) = place(&f, json!({"layers": true}));
assert!(matches!(placed(&s, &r.unwrap()).kind, NodeKind::Group { clip: false, .. }));
}
#[test]
fn placing_with_layers_never_links_and_refuses_values_it_cant_use() {
let f = file(8, 8, &stack(), 8, false, false);
let dir = std::env::temp_dir().join(format!("vc-psd-place-layers-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("layers.psd");
std::fs::write(&path, &f).unwrap();
let from_path = |p: Value| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("file.place", &merge(json!({"path": path.to_str().unwrap()}), p));
(s, r)
};
// From a path, `layers` embeds: `link` is then false unless given, and `link: true` is refused.
let (s, r) = from_path(json!({"layers": true}));
let r = r.unwrap();
assert_eq!(r["linked"], json!(false), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Group { .. }));
let (s, r) = from_path(json!({"layers": true, "link": true}));
assert!(r.unwrap_err().to_string().contains("a linked PSD file is placed as its flat image"));
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "nothing is placed");
// Without `layers` the file is linked as before.
let (s, r) = from_path(json!({}));
let r = r.unwrap();
assert_eq!(r["linked"], json!(true), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// A file without layers is embedded as its merged image, without a warning.
let flat = {
let mut f = file(2, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 8, false, false);
let at = 26 + 8;
let len = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) as usize;
f.splice(at..at + 4 + len, 0u32.to_be_bytes());
f
};
std::fs::write(&path, &flat).unwrap();
let (s, r) = from_path(json!({"layers": true}));
let r = r.unwrap();
assert_eq!((&r["linked"], &r["warnings"]), (&json!(false), &json!([])), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// Layers that are all left out: the merged image, with the importer's warnings.
let mut gone = layer("Gone", [0, 0, 2, 2], [9, 9, 9, 255]);
gone.hidden = true;
let (s, r) = place(&file(2, 2, &[gone], 8, false, false), json!({"layers": true}));
let r = r.unwrap();
assert_eq!((&r["linked"], r["warnings"].as_array().map(Vec::len)), (&json!(false), Some(1)), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// Layers that can't be read: the merged image, with a warning.
let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false);
let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap();
cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes());
let (s, r) = place(&cut, json!({"layers": true}));
let r = r.unwrap();
assert!(r["warnings"][0].as_str().unwrap().starts_with("the layers can't be read"), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// Values the command can't use are errors, and nothing is placed.
for (p, why) in [
(json!({"hiddenLayers": true}), "hiddenLayers applies to a PSD file placed with layers: true"),
(json!({"layers": true, "link": true}), "a linked PSD file is placed as its flat image"),
(json!({"layers": "yes"}), "layers must be true or false"),
(json!({"layers": true, "hiddenLayers": 1}), "hiddenLayers must be true or false"),
] {
let (s, r) = place(&f, p.clone());
assert!(r.unwrap_err().to_string().contains(why), "{p}");
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "{p}");
}
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let q = s.execute("file.place.queue", &json!({"paths": [path.to_str().unwrap()], "layers": "yes"}));
assert!(q.unwrap_err().to_string().contains("`layers` must be true or false"));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn psd_info_counts_the_layers_without_opening_the_file() {
let mut s = Session::new();
let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": vectorcraft_format::base64_encode(f)}));
let r = info(&mut s, &file(8, 8, &stack(), 8, false, false)).unwrap();
assert_eq!(r, json!({"format": "psd", "width": 8, "height": 8, "layers": 5, "hiddenLayers": 1, "groups": 2, "slices": 0}));
let r = info(&mut s, &file(4, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 16, true, true)).unwrap();
assert_eq!((&r["format"], &r["width"], &r["height"], &r["layers"]), (&json!("psb"), &json!(4), &json!(2), &json!(1)), "{r}");
// Layer records that can't be read count as no layers: the file opens as its merged image.
let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false);
let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap();
cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes());
assert_eq!(info(&mut s, &cut).unwrap()["layers"], json!(0));
assert!(info(&mut s, b"not a psd").unwrap_err().to_string().contains("not a PSD file"));
}
@@ -0,0 +1,459 @@
//! A PSD or PSB file's slices (image resource 1050) opened and placed as user slices
//! (`document.open`'s and `file.place`'s `importSlices`): version 6 records and version 7 and 8
//! descriptors, built from the Photoshop File Formats Specification's "Slices resource format";
//! their options, slices outside the canvas, damaged or unknown slice data, placing scaled and
//! moved in one undo step, linked files, and `document.psdInfo`'s count.
use serde_json::{Value, json};
use vectorcraft_doc::{SliceKind, SliceOptions};
use vectorcraft_geom::Rect;
use crate::Session;
/// A Unicode string: a count of UTF-16 units, then the units.
fn ustr(s: &str) -> Vec<u8> {
let units: Vec<u16> = s.encode_utf16().collect();
let mut b = (units.len() as u32).to_be_bytes().to_vec();
b.extend(units.iter().flat_map(|u| u.to_be_bytes()));
b
}
/// One version 6 slice record.
#[derive(Clone)]
struct S {
/// 0: generated automatically, 1: follows a layer, 2: made by the user.
origin: u32,
name: &'static str,
/// 0: No Image, 1: Image.
kind: u32,
/// Left, top, right, bottom (px).
rect: [i32; 4],
url: &'static str,
target: &'static str,
message: &'static str,
alt: &'static str,
html: bool,
cell: &'static str,
/// Alpha, red, green, blue.
argb: [u8; 4],
}
fn user(name: &'static str, rect: [i32; 4]) -> S {
S { origin: 2, name, kind: 1, rect, url: "", target: "", message: "", alt: "", html: false, cell: "", argb: [0; 4] }
}
/// Resource 1050 in version 6, each record followed by `trailing` (a Photoshop 7 descriptor, or
/// nothing).
fn v6(slices: &[S], trailing: &[u8]) -> Vec<u8> {
let mut b = 6u32.to_be_bytes().to_vec();
b.extend([0u8; 16]);
b.extend(ustr("group"));
b.extend((slices.len() as u32).to_be_bytes());
for (i, s) in slices.iter().enumerate() {
b.extend((i as u32 + 1).to_be_bytes());
b.extend(0u32.to_be_bytes());
b.extend(s.origin.to_be_bytes());
if s.origin == 1 {
b.extend(7u32.to_be_bytes());
}
b.extend(ustr(s.name));
b.extend(s.kind.to_be_bytes());
for v in s.rect {
b.extend(v.to_be_bytes());
}
for t in [s.url, s.target, s.message, s.alt] {
b.extend(ustr(t));
}
b.push(u8::from(s.html));
b.extend(ustr(s.cell));
b.extend([0u8; 8]);
b.extend(s.argb);
b.extend(trailing);
}
b
}
/// A descriptor value.
enum D {
Long(i32),
Doub(f64),
Bool(bool),
Text(&'static str),
Enum(&'static str, &'static str),
Obj(Vec<(&'static str, D)>),
List(Vec<D>),
}
/// A key or class ID: a four-character one with length 0, else its length and characters.
fn key(k: &str) -> Vec<u8> {
let mut b = if k.len() == 4 { 0u32 } else { k.len() as u32 }.to_be_bytes().to_vec();
b.extend(k.as_bytes());
b
}
/// A descriptor: an empty class name, the class ID, the count, then each item.
fn descriptor(items: &[(&str, D)]) -> Vec<u8> {
let mut b = ustr("");
b.extend(key("null"));
b.extend((items.len() as u32).to_be_bytes());
for (k, v) in items {
b.extend(key(k));
b.extend(value(v));
}
b
}
/// A value's type, then the value.
fn value(v: &D) -> Vec<u8> {
let mut b = vec![];
match v {
D::Long(n) => {
b.extend(b"long");
b.extend(n.to_be_bytes());
}
D::Doub(d) => {
b.extend(b"doub");
b.extend(d.to_be_bytes());
}
D::Bool(on) => {
b.extend(b"bool");
b.push(u8::from(*on));
}
D::Text(t) => {
b.extend(b"TEXT");
b.extend(ustr(t));
}
D::Enum(t, e) => {
b.extend(b"enum");
b.extend(key(t));
b.extend(key(e));
}
D::Obj(items) => {
b.extend(b"Objc");
b.extend(descriptor(items));
}
D::List(items) => {
b.extend(b"VlLs");
b.extend((items.len() as u32).to_be_bytes());
for i in items {
b.extend(value(i));
}
}
}
b
}
/// A bounds object: top, left, bottom and right.
fn bounds(l: i32, t: i32, r: i32, b: i32) -> D {
D::Obj(vec![("Top ", D::Long(t)), ("Left", D::Long(l)), ("Btom", D::Long(b)), ("Rght", D::Long(r))])
}
/// Resource 1050 in `version` 7 or 8 holding `slices`.
fn v7(version: u32, slices: Vec<D>) -> Vec<u8> {
let mut b = version.to_be_bytes().to_vec();
b.extend(16u32.to_be_bytes());
b.extend(descriptor(&[("bounds", bounds(0, 0, 20, 20)), ("baseName", D::Text("poster")), ("slices", D::List(slices))]));
b
}
/// A 20 × 20 px PSD file written by `document.export`, with its layers (two) or flat.
fn psd(layers: bool) -> Vec<u8> {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
s.execute("paint.setFill", &json!({ "color": "#ff0000" })).unwrap();
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
s.execute("layer.new", &json!({ "name": "Top" })).unwrap();
s.execute("shape.rectangle", &json!({"x": 8, "y": 8, "width": 10, "height": 10})).unwrap();
let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap();
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
}
/// `psd` with image resource `id` holding `data` added to its image resources.
fn with_resource(psd: &[u8], id: u16, data: &[u8]) -> Vec<u8> {
let u32_at = |at: usize| u32::from_be_bytes(psd[at..at + 4].try_into().unwrap()) as usize;
let colors = 26 + 4 + u32_at(26);
let len = u32_at(colors);
let mut block = b"8BIM".to_vec();
block.extend(id.to_be_bytes());
block.extend([0, 0]);
block.extend((data.len() as u32).to_be_bytes());
block.extend(data);
block.resize(block.len().next_multiple_of(2), 0);
let mut out = psd[..colors].to_vec();
out.extend(((len + block.len()) as u32).to_be_bytes());
out.extend(&psd[colors + 4..colors + 4 + len]);
out.extend(block);
out.extend(&psd[colors + 4 + len..]);
out
}
fn b64(f: &[u8]) -> String {
vectorcraft_format::base64_encode(f)
}
fn open(f: &[u8], extra: Value) -> (Session, Value) {
let mut s = Session::new();
let mut p = json!({"name": "poster.psd", "dataBase64": b64(f)});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
let r = s.execute("document.open", &p).unwrap();
(s, r)
}
/// The document's user slices: rectangle and options.
fn slices(s: &Session) -> Vec<(Rect, SliceOptions)> {
s.doc().unwrap().doc.slices.iter().map(|x| (x.rect, x.options.clone())).collect()
}
fn warnings(r: &Value) -> Vec<String> {
r["warnings"].as_array().map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default()
}
#[test]
fn version_6_slices_open_as_user_slices_with_their_options() {
let linked = S { origin: 1, url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", ..user("logo", [2, 4, 10, 8]) };
let plain = S { kind: 0, cell: "a < b & c", argb: [0, 0, 0, 0], ..user("note", [10, 10, 20, 20]) };
let html = S { kind: 0, html: true, cell: "<b>Hi</b>", argb: [255, 0x12, 0x34, 0x56], ..user("", [0, 12, 6, 18]) };
let matte = S { argb: [0, 1, 2, 3], cell: "ignored", ..user("matte", [12, 0, 18, 6]) };
let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) };
let data = v6(&[linked, plain, html, matte, auto], &[]);
for layers in [true, false] {
let f = with_resource(&psd(layers), 1050, &data);
// Either conversion brings the slices in; the automatic one stays out.
for p in [json!({}), json!({"layers": false})] {
let (s, r) = open(&f, p);
assert!(warnings(&r).is_empty(), "{r}");
let got = slices(&s);
assert_eq!(got.len(), 4, "{got:?}");
assert_eq!(got[0].0, Rect::new(2.0, 4.0, 10.0, 8.0));
assert_eq!(
got[0].1,
SliceOptions {
kind: SliceKind::Image,
name: "logo".into(),
url: "https://example.com/".into(),
target: "_blank".into(),
message: "Go".into(),
alt: "Logo".into(),
..Default::default()
}
);
// Plain cell text is escaped as the HTML a No Image cell shows; HTML stays as it is.
assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.background.as_str()), (SliceKind::NoImage, "a &lt; b &amp; c", ""));
assert_eq!((got[2].1.text.as_str(), got[2].1.background.as_str(), got[2].1.name.as_str()), ("<b>Hi</b>", "#123456", ""));
// An Image slice's cell text isn't kept; a background with no alpha is the matte.
assert_eq!((got[3].1.text.as_str(), got[3].1.background.as_str()), ("", "matte"));
// Web output lays them out with auto slices around them.
let layout = s.doc().unwrap().doc.slice_layout();
assert_eq!(layout.iter().filter(|a| a.source == vectorcraft_doc::SliceSource::User).count(), 4);
assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto));
}
}
}
#[test]
fn photoshop_7_descriptors_after_version_6_records_are_read_past() {
let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat();
let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5]), user("b", [5, 5, 10, 10])], &trailing));
let (s, r) = open(&f, json!({}));
assert!(warnings(&r).is_empty(), "{r}");
let names: Vec<String> = slices(&s).into_iter().map(|(_, o)| o.name).collect();
assert_eq!(names, ["a", "b"]);
}
#[test]
fn version_6_descriptors_share_one_budget_of_values() {
// Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold;
// 100 of them hold 250,100 together.
let list = D::List((0..2_500).map(D::Long).collect());
let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("many", list)])].concat();
let records: Vec<S> = (0..100).map(|_| user("a", [0, 0, 5, 5])).collect();
// Alone, one such descriptor is read past.
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records[..1], &trailing)), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
assert_eq!(slices(&s).len(), 1);
// Together they are refused, and the file opens without slices.
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({}));
let w = warnings(&r);
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("too many values")), "{w:?}");
assert!(slices(&s).is_empty());
}
#[test]
fn version_7_and_8_descriptors_open_as_user_slices() {
let slice = |origin: &'static str, kind: &'static str, l: i32, t: i32, r: i32, b: i32| {
D::Obj(vec![
("sliceID", D::Long(1)),
("groupID", D::Long(0)),
("origin", D::Enum("ESliceOrigin", origin)),
("Type", D::Enum("ESliceType", kind)),
("bounds", bounds(l, t, r, b)),
("Nm ", D::Text("cell")),
("url", D::Text("https://example.com/")),
("null", D::Text("_top")),
("Msge", D::Text("msg")),
("altTag", D::Text("alt")),
("cellTextIsHTML", D::Bool(false)),
("cellText", D::Text("x>y")),
("bgColorType", D::Enum("ESliceBGColorType", "Clr ")),
("bgColor", D::Obj(vec![("Rd ", D::Doub(255.0)), ("Grn ", D::Doub(128.0)), ("Bl ", D::Long(0))])),
])
};
for version in [7, 8] {
let data = v7(
version,
vec![slice("userGenerated", "Img ", 1, 2, 9, 10), slice("autoGenerated", "Img ", 0, 0, 20, 1), slice("layer", "noImage", 10, 10, 15, 15)],
);
let (s, r) = open(&with_resource(&psd(true), 1050, &data), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
let got = slices(&s);
assert_eq!(got.len(), 2, "{got:?}");
assert_eq!(got[0].0, Rect::new(1.0, 2.0, 9.0, 10.0));
assert_eq!(
got[0].1,
SliceOptions {
name: "cell".into(),
url: "https://example.com/".into(),
target: "_top".into(),
message: "msg".into(),
alt: "alt".into(),
background: "#ff8000".into(),
..Default::default()
}
);
assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.url.as_str()), (SliceKind::NoImage, "x&gt;y", ""));
}
}
#[test]
fn import_slices_false_leaves_them_out_and_must_be_a_switch() {
let f = with_resource(&psd(true), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[]));
let (s, _) = open(&f, json!({"importSlices": false}));
assert!(slices(&s).is_empty());
let mut s = Session::new();
let e = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": "yes"})).unwrap_err();
assert!(e.to_string().contains("importSlices must be true or false"), "{e}");
}
#[test]
fn slices_that_cant_be_read_warn_and_the_file_still_opens() {
let good = v6(&[user("a", [0, 0, 5, 5])], &[]);
let mut bad_descriptor = v7(7, vec![]);
bad_descriptor[4..8].copy_from_slice(&15u32.to_be_bytes());
let cases: Vec<(Vec<u8>, &str)> = vec![
(good[..good.len() - 3].to_vec(), "cut short"),
([9u32.to_be_bytes().to_vec(), good[4..].to_vec()].concat(), "version 9"),
(bad_descriptor, "version other than 16"),
// The count follows the version, the bounds and the group's name.
([&good[..34], &u32::MAX.to_be_bytes()[..], &good[38..]].concat(), "more than the 10000 read"),
(v7(8, vec![D::Long(3)]), "other than a slice"),
// A whole record whose name is longer than a slice's text may be.
(v6(&[user("a".repeat(65_537).leak(), [0, 0, 5, 5])], &[]), "more than the 65536 characters read"),
];
for (data, why) in cases {
for layers in [true, false] {
let (s, r) = open(&with_resource(&psd(layers), 1050, &data), json!({}));
let w = warnings(&r);
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains(why)), "{why}: {w:?}");
assert!(slices(&s).is_empty());
// The art still came in.
assert!(s.doc().unwrap().doc.art_bounds().is_some(), "{why}");
}
}
// A name of the longest length read comes in.
let longest = v6(&[user("a".repeat(65_536).leak(), [0, 0, 5, 5])], &[]);
let (s, r) = open(&with_resource(&psd(false), 1050, &longest), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
assert_eq!(slices(&s).first().map(|(_, o)| o.name.len()), Some(65_536));
// A file without slices opens without a word about them.
let (s, r) = open(&psd(true), json!({}));
assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}");
}
#[test]
fn slices_are_clipped_to_the_canvas_and_those_outside_it_are_left_out() {
let data = v6(&[user("over", [-5, -5, 5, 30]), user("out", [25, 0, 30, 5]), user("empty", [4, 4, 4, 9]), user("in", [1, 1, 2, 2])], &[]);
let (s, r) = open(&with_resource(&psd(false), 1050, &data), json!({}));
assert_eq!(warnings(&r), ["2 slices lie outside the canvas or have no size and were left out"]);
let got: Vec<(Rect, String)> = slices(&s).into_iter().map(|(r, o)| (r, o.name)).collect();
assert_eq!(got, [(Rect::new(0.0, 0.0, 5.0, 20.0), "over".to_string()), (Rect::new(1.0, 1.0, 2.0, 2.0), "in".to_string())]);
}
#[test]
fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() {
let data = v6(&[user("a", [0, 0, 10, 10]), user("b", [10, 10, 20, 20])], &[]);
for layers in [false, true] {
let f = with_resource(&psd(layers), 1050, &data);
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
// Fitted into a 40 pt square at (100, 60): twice the size.
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "rect": [100, 60, 40, 40], "layers": layers})).unwrap();
assert_eq!(r["slices"].as_array().map(Vec::len), Some(2), "{r}");
let got: Vec<Rect> = slices(&s).into_iter().map(|(r, _)| r).collect();
assert_eq!(got, [Rect::new(100.0, 60.0, 120.0, 80.0), Rect::new(120.0, 80.0, 140.0, 100.0)]);
// The placed art stays selected, and one undo takes the art and the slices away.
assert_eq!(s.doc().unwrap().selection.objects.len(), 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(slices(&s).is_empty());
assert!(s.doc().unwrap().doc.art_bounds().is_none());
// Centered on `at` at 100%.
s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "at": [100, 100], "layers": layers})).unwrap();
assert_eq!(slices(&s)[0].0, Rect::new(90.0, 90.0, 100.0, 100.0));
// `importSlices: false` places the art alone.
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": false, "layers": layers})).unwrap();
assert!(r.get("slices").is_none());
assert_eq!(slices(&s).len(), 2);
}
}
#[test]
fn linked_files_are_placed_without_their_slices() {
let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("poster.psd");
std::fs::write(&path, with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[]))).unwrap();
let path = path.to_string_lossy().into_owned();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("file.place", &json!({ "path": path })).unwrap();
assert_eq!((&r["linked"], r.get("slices")), (&json!(true), None));
assert!(slices(&s).is_empty());
let e = s.execute("file.place", &json!({ "path": path, "importSlices": true })).unwrap_err();
assert!(e.to_string().contains("importSlices: a linked PSD file is placed as its flat image"), "{e}");
// Embedded from its path, they come in.
let r = s.execute("file.place", &json!({ "path": path, "link": false })).unwrap();
assert_eq!((&r["linked"], r["slices"].as_array().map(Vec::len)), (&json!(false), Some(1)));
// file.place.info counts what a place would bring in.
let info = s.execute("file.place.info", &json!({ "path": path, "link": false })).unwrap();
assert_eq!(info["slices"], json!(1));
let info = s.execute("file.place.info", &json!({ "path": path })).unwrap();
assert_eq!(info["slices"], json!(0));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn psd_info_counts_the_slices_that_come_in() {
let mut s = Session::new();
let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": b64(f)})).unwrap();
let data = v6(&[user("a", [0, 0, 5, 5]), S { origin: 0, ..user("auto", [5, 5, 20, 20]) }, user("out", [30, 30, 40, 40])], &[]);
assert_eq!(info(&mut s, &with_resource(&psd(false), 1050, &data))["slices"], json!(1));
assert_eq!(info(&mut s, &with_resource(&psd(true), 1050, &data[..data.len() - 4]))["slices"], json!(0));
assert_eq!(info(&mut s, &psd(true))["slices"], json!(0));
}
#[test]
fn damaged_slices_never_panic() {
let data = v7(8, vec![D::Obj(vec![("origin", D::Enum("ESliceOrigin", "userGenerated")), ("bounds", bounds(0, 0, 5, 5))])]);
let base = with_resource(&psd(false), 1050, &data);
let start = base.windows(data.len()).position(|w| w == data).unwrap();
for at in (start - 12..start + data.len()).step_by(3) {
for v in [0u8, 0x7f, 0xff] {
let mut f = base.clone();
f[at] = v;
let mut s = Session::new();
let _ = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)}));
let _ = s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)}));
}
}
}
+1 -1
View File
@@ -51,7 +51,7 @@ mod options;
mod presets;
mod report;
pub(crate) use analysis::{outlined_text, see_through_images};
pub(crate) use analysis::{carry, outlined_text, see_through_images};
pub(crate) use apply::{expand_transparent_tile_images, flatten_document, flatten_expanded, has_transparent_tile_images};
#[cfg(test)]
pub(crate) use apply::{with_clips_ignored, with_every_region};
+1 -1
View File
@@ -56,7 +56,7 @@ pub(crate) fn outlined_text(n: &Node) -> Option<Node> {
}
/// `to` (art made from `from`) with `from`'s name, transparency, opacity mask and effects.
fn carry(from: &Node, mut to: Node) -> Node {
pub(crate) fn carry(from: &Node, mut to: Node) -> Node {
to.name = from.name.clone();
to.opacity = from.opacity;
to.blend = from.blend;
+40 -5
View File
@@ -10,9 +10,10 @@ use vectorcraft_color::Paint;
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
use vectorcraft_geom::Rect;
use super::panelcmds::listed_artboards;
use super::select::on_artboard;
use super::typecmd::refresh_bounds;
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index, str_param};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -39,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Text by Font",
[],
None,
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based whole numbers)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
has_doc,
select_font
),
@@ -1080,9 +1081,9 @@ impl FontScope {
Some(_) => Err(bad(C, format!("`scope.{key}` must be a non-empty array"))),
}
};
if let Some(a) = list("artboards")? {
let rect = |v: &Value| v.as_u64().and_then(|i| d.artboards.get(index(i))).map(|b| b.rect);
return a.iter().map(|v| rect(v).ok_or_else(|| bad(C, format!("no such artboard {v}")))).collect::<Result<_>>().map(Self::Artboards);
if let (Some(v), Some(_)) = (scope.get("artboards"), list("artboards")?) {
let indices = listed_artboards(d, v, "scope.artboards", C)?;
return Ok(Self::Artboards(indices.into_iter().filter_map(|i| d.artboards.get(i)).map(|b| b.rect).collect()));
}
if let Some(a) = list("layers")? {
let layer = |v: &Value| v.as_u64().map(NodeId).filter(|id| d.node(*id).is_some_and(Node::is_layer));
@@ -1292,6 +1293,40 @@ mod tests {
}
}
/// Select Text by Font refuses a `scope.artboards` entry that is not a whole number, naming the
/// parameter, before it looks at the artboards, and leaves the selection as it was; a whole
/// number past the last artboard is `no such artboard`.
#[test]
fn select_font_refuses_artboards_that_are_not_whole_numbers() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 200, "height": 200})).unwrap();
let text = |s: &mut Session, x: i32| {
NodeId(s.execute("text.create", &json!({"x": x, "y": 50, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap())
};
let first = text(&mut s, 10);
let second = text(&mut s, 350);
let run =
|s: &mut Session, artboards: Value| s.execute("select.font", &json!({"family": "Source Serif 4", "scope": {"artboards": artboards}}));
let malformed = "invalid parameters for `select.font`: `scope.artboards` must contain whole numbers";
for (artboards, want) in [
(json!(["1"]), malformed),
(json!([-1]), malformed),
(json!([1.5]), malformed),
(json!([true]), malformed),
(json!([null]), malformed),
(json!([9, "1"]), malformed),
(json!([9]), "no such artboard"),
(json!([1, 9]), "no such artboard"),
] {
s.execute("select.set", &json!({"ids": [first.0]})).unwrap();
assert_eq!(run(&mut s, artboards.clone()).unwrap_err().to_string(), want, "{artboards}");
assert_eq!(s.doc().unwrap().selection.objects, [first], "{artboards}");
}
run(&mut s, json!([1, 1])).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [second]);
}
/// Select Text by Font with a layer scope takes the text in the layers, their sublayers
/// included, and still leaves out hidden and locked text.
#[test]
+3 -3
View File
@@ -41,7 +41,7 @@ pub(crate) use data::{apply_csv, parse_csv};
#[cfg(test)]
use data::{fmt_value, to_csv};
pub use edit::{GraphTypeSubject, graph_type_subject};
pub(crate) use edit::{graphs_holding, keep_placed};
pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed};
pub use generate::calculated_axes;
#[cfg(test)]
use generate::generate;
@@ -50,8 +50,8 @@ use series::default_series_color;
pub(crate) use series::{
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in,
series_object_opacity_differs, shown_paint,
label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among,
series_marks_in, series_object_opacity_differs, shown_paint,
};
#[cfg(test)]
+17
View File
@@ -88,6 +88,23 @@ pub(crate) fn keep_placed(d: &mut Document, graphs: &[(NodeId, Option<Rect>, Opt
}
}
/// Let `edit` change the art of graph node `n` (a copy outside any document) without the next redraw reading the
/// change as a move or scale: the plot rect first takes any move or scale of the art since it was generated, as a
/// redraw measures it, and the bounds the graph keeps become those of the changed art (also for a graph that had none,
/// so a later move is followed).
pub(crate) fn edit_graph_art(n: &mut Node, edit: impl FnOnce(&mut Node)) {
let moved = measured(n).and_then(|(placed, now)| n.extras().graph.as_deref().and_then(|g| carried(g.rect, placed, now)));
if let (Some(rect), Some(g)) = (moved, n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) {
g.rect = rect;
}
edit(n);
let children = n.children();
let (whole, art) = (children.and_then(|c| children_bounds(c)), children.and_then(|c| art_bounds(c)));
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
(g.placed, g.placed_art) = (whole, art);
}
}
/// 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_art` bounds, or `placed` in graphs saved without them).
pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> {
+1 -1
View File
@@ -293,7 +293,7 @@ fn bar_rect(horizontal: bool, a: f64, w: f64, v0: f64, v1: f64) -> Rect {
}
/// White text on a dark wedge.
fn is_dark(fill: &Paint) -> bool {
pub(super) fn is_dark(fill: &Paint) -> bool {
fill.color().is_some_and(|c| {
let [r, g, b] = c.to_rgb();
0.2126 * r + 0.7152 * g + 0.0722 * b < 0.5
+456 -26
View File
@@ -1,8 +1,13 @@
use vectorcraft_color::BlendMode;
use vectorcraft_geom::Shape;
use super::axis::radar_axis;
use super::labels::{Role, filled_lines_on, label_para, label_style};
use super::{Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Rect, Result, Session, Value, bad};
use super::generate::is_dark;
use super::labels::{Role, filled_lines_on, label_para, label_size, label_style};
use super::{
Affine, Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Rect, Result, Session, Value, bad,
refresh_bounds,
};
// ---------- generation ----------
@@ -639,35 +644,460 @@ fn graph_labels(doc: &Document) -> HashMap<NodeId, (NodeId, Role)> {
let mut out = HashMap::new();
doc.walk(|n| {
let Some(g) = n.extras().graph.as_deref() else { return };
for c in n.children().into_iter().flatten() {
match (&c.kind, c.name.as_deref(), c.extras().series_index) {
(NodeKind::Text(_), _, _) if g.kind == GraphKind::Pie => {
out.insert(c.id, (n.id, Role::Category));
}
(NodeKind::Group { .. }, Some("Legend"), None) => {
for t in c.children().into_iter().flatten().filter(|t| matches!(t.kind, NodeKind::Text(_))) {
out.insert(t.id, (n.id, Role::Legend));
}
}
(NodeKind::Group { .. }, Some("Axes"), None) => {
let texts: Vec<NodeId> =
c.children().into_iter().flatten().filter(|t| matches!(t.kind, NodeKind::Text(_))).map(|t| t.id).collect();
let cats = match g.kind {
GraphKind::Scatter => 0,
GraphKind::Radar => texts.len(),
_ => g.categories.iter().take(g.rows.len().max(1)).filter(|c| !c.is_empty()).count().min(texts.len()),
};
for (i, t) in texts.iter().enumerate() {
out.insert(*t, (n.id, if i + cats >= texts.len() { Role::Category } else { Role::Value }));
}
}
_ => {}
}
for (id, role) in own_labels(n, g) {
out.insert(id, (n.id, role));
}
});
out
}
/// The generated labels of graph `n` (with spec `g`) and what each shows, as [`graph_labels`] finds them.
fn own_labels(n: &Node, g: &GraphSpec) -> Vec<(NodeId, Role)> {
let mut out = vec![];
for c in n.children().into_iter().flatten() {
match (&c.kind, c.name.as_deref(), c.extras().series_index) {
(NodeKind::Text(_), _, _) if g.kind == GraphKind::Pie => {
out.push((c.id, Role::Category));
}
(NodeKind::Group { .. }, Some("Legend"), None) => {
for t in c.children().into_iter().flatten().filter(|t| matches!(t.kind, NodeKind::Text(_))) {
out.push((t.id, Role::Legend));
}
}
(NodeKind::Group { .. }, Some("Axes"), None) => {
let texts: Vec<NodeId> = c.children().into_iter().flatten().filter(|t| matches!(t.kind, NodeKind::Text(_))).map(|t| t.id).collect();
let cats = match g.kind {
GraphKind::Scatter => 0,
GraphKind::Radar => texts.len(),
_ => g.categories.iter().take(g.rows.len().max(1)).filter(|c| !c.is_empty()).count().min(texts.len()),
};
for (i, t) in texts.iter().enumerate() {
out.push((*t, if i + cats >= texts.len() { Role::Category } else { Role::Value }));
}
}
_ => {}
}
}
out
}
/// Set the labels of graph node `n` (a copy outside any document) in a new graph's label formats: the character and
/// paragraph formats the graph keeps for them are dropped, with the mark that its legend labels' fill is their own, and
/// each label takes its kind's default character style, unscaled (keeping its rotation), and default paragraph
/// attributes, keeping its alignment and where it starts. A pie's legend label on a dark wedge is white, as a redraw
/// sets it. Every other object in the graph goes to `other`. The rest of the graph's art, and what its labels say, stay
/// as they are.
pub(crate) fn plain_labels(n: &mut Node, other: &dyn Fn(&mut Node)) {
fn plain(l: &mut vectorcraft_doc::LabelStyles) {
(l.values, l.categories, l.legend) = (None, None, None);
(l.values_para, l.categories_para, l.legend_para) = (None, None, None);
l.legend_fill_set = false;
}
// Which legend labels a redraw sets on a dark wedge, read while the labels are as the graph drew them.
let on_dark = match n.extras().graph.as_deref() {
Some(g) if g.kind == GraphKind::Pie && g.legend && g.pie_legend_in_wedges => {
let mut redraw = g.clone();
plain(&mut redraw.label_styles);
redrawn_on_dark(n, &redraw).unwrap_or_else(|| legend_on_dark(n, g))
}
_ => HashMap::new(),
};
let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) else { return };
plain(&mut g.label_styles);
let Some(g) = n.extras().graph.as_deref() else { return };
let roles: HashMap<NodeId, Role> = own_labels(n, g).into_iter().collect();
struct Plain<'a> {
roles: HashMap<NodeId, Role>,
other: &'a dyn Fn(&mut Node),
}
fn visit(c: &mut Node, p: &Plain) {
let role = p.roles.get(&c.id).copied();
if let (Some(role), NodeKind::Text(t)) = (role, &mut c.kind) {
let plain = vectorcraft_doc::LabelStyles::default();
let justify = t.para_at(0).justify;
let text = t.plain_text();
t.runs = vec![vectorcraft_doc::TextRun { text, style: label_style(&plain, role), inline: None }];
let mut para = label_para(&plain, role);
para.justify = justify;
t.set_all_paras(para);
// The label loses its scale and keeps its rotation (and a reflection), so it stays turned with the
// rest of a rotated graph's art.
let [a, b, c, d, _, _] = t.xf.as_coeffs();
let flip = if a * d - b * c < 0.0 { Affine::scale_non_uniform(1.0, -1.0) } else { Affine::IDENTITY };
t.xf = Affine::translate(t.xf.translation()) * Affine::rotate(b.atan2(a)) * flip;
refresh_bounds(t);
return;
}
// The Axes and Legend groups, and any other group of the graph's own, are looked through.
if role.is_none() && matches!(c.kind, NodeKind::Group { .. }) && c.extras().graph.is_none() {
for k in c.children_mut().into_iter().flatten() {
visit(Arc::make_mut(k), p);
}
return;
}
(p.other)(c);
}
let p = Plain { roles, other };
for c in n.children_mut().into_iter().flatten() {
visit(Arc::make_mut(c), &p);
}
set_legend_fills(n, &on_dark);
}
/// Give each legend label of graph `n` in `on_dark` white characters (`true`) or black ones.
fn set_legend_fills(n: &mut Node, on_dark: &HashMap<NodeId, bool>) {
if on_dark.is_empty() {
return;
}
// The legend labels are in the graph's Legend group.
for c in n.children_mut().into_iter().flatten() {
if !c.children().into_iter().flatten().any(|t| on_dark.contains_key(&t.id)) {
continue;
}
for t in Arc::make_mut(c).children_mut().into_iter().flatten() {
let Some(dark) = on_dark.get(&t.id) else { continue };
let fill = Paint::solid(if *dark { Color::WHITE } else { Color::BLACK });
if matches!(&t.kind, NodeKind::Text(text) if text.runs.iter().all(|r| r.style.fill == fill)) {
continue;
}
if let NodeKind::Text(text) = &mut Arc::make_mut(t).kind {
text.runs.iter_mut().for_each(|r| r.style.fill = fill.clone());
}
}
}
}
/// The legend labels of graph `n`: the type in its Legend group, as [`own_labels`] finds them.
fn legend_labels(n: &Node) -> Vec<&Node> {
legend_in(n.children().map_or(&[], |c| c.as_slice()))
}
/// The type in the Legend group among a graph's `children`.
fn legend_in(children: &[Arc<Node>]) -> Vec<&Node> {
children
.iter()
.filter(|c| matches!(c.kind, NodeKind::Group { .. }) && c.name.as_deref() == Some("Legend") && c.extras().series_index.is_none())
.flat_map(|c| c.children().into_iter().flatten())
.map(|t| t.as_ref())
.filter(|t| matches!(t.kind, NodeKind::Text(_)))
.collect()
}
/// A pie wedge: its series, its outline and whether the fill it shows is dark.
struct Wedge {
series: u32,
bounds: vectorcraft_geom::Rect,
path: vectorcraft_geom::BezPath,
dark: bool,
}
/// The wedges of pie `n` (the paths of its series groups), in paint order.
fn pie_wedges(n: &Node) -> Vec<Wedge> {
wedges_in(n.children().map_or(&[], |c| c.as_slice()))
}
/// The wedges among a pie's `children`, as [`pie_wedges`] finds them.
fn wedges_in(children: &[Arc<Node>]) -> Vec<Wedge> {
let mut wedges = vec![];
for c in children {
let Some(series) = c.extras().series_index else { continue };
c.walk(&mut |m| {
if let NodeKind::Path { path, .. } = &m.kind {
let path = path.to_bezpath();
wedges.push(Wedge { series, bounds: path.bounding_box(), path, dark: is_dark(&shown_paint(m, true).0) });
}
});
}
wedges
}
/// The text of the label of each series of graph `g` in its wedges, with the series that show it (several when series
/// share a name).
fn series_by_label(g: &GraphSpec) -> HashMap<String, Vec<u32>> {
let mut names: HashMap<String, Vec<u32>> = HashMap::new();
for (s, name) in g.series.iter().enumerate() {
if let Ok(s) = u32::try_from(s) {
names.entry(name.replace('|', "\n")).or_default().push(s);
}
}
names
}
/// The legend labels of pie `n`, each with whether a redraw from spec `g` sets it on a dark wedge, by the fill each wedge
/// of `n` shows now. The pie is drawn again apart from any document, which places each label in its wedge as `g` sets
/// it and tells each label's series. Each redrawn wedge takes the fill of the wedge of `n` of its series with the same
/// bounds, and each legend label of `n` is the nearest redrawn one with the same text, places measured in the bounds of
/// all the wedges. `None` when a wedge or a label has no counterpart of its own, or a wedge out of its place in paint
/// order has several (art or labels added, removed, edited or restyled since the pie was drawn).
fn redrawn_on_dark(n: &Node, g: &GraphSpec) -> Option<HashMap<NodeId, bool>> {
use vectorcraft_geom::kurbo::ParamCurveNearest;
// Each series name that shows a label is drawn with a mark and its index after it, which moves no line, so each
// redrawn label tells its series.
const MARK: char = '\u{1f}';
let mut marked = g.clone();
for (s, name) in marked.series.iter_mut().enumerate() {
if !super::labels::blank_label(name) {
name.push(MARK);
name.push_str(&s.to_string());
}
}
let legend = legend_labels(n);
let mut scratch = Document::new(1.0, 1.0);
let art = super::generate::generate(&mut scratch, &marked);
let redrawn = legend_in(&art);
let now = pie_wedges(n);
let mut wedges = wedges_in(&art);
if redrawn.len() != legend.len() || wedges.len() != now.len() {
return None;
}
// Places are measured in the bounds of all the wedges, since the pie may have been moved or resized since it was drawn.
let frame = |ws: &[Wedge]| ws.iter().map(|w| w.bounds).reduce(|a, b| a.union(b));
let (Some(was), Some(is)) = (frame(&wedges), frame(&now)) else { return None };
let at = |f: vectorcraft_geom::Rect, p: vectorcraft_geom::Point| ((p.x - f.x0) / f.width().max(1e-9), (p.y - f.y0) / f.height().max(1e-9));
let corners = |f: vectorcraft_geom::Rect, w: &Wedge| {
let (a, b) = (at(f, vectorcraft_geom::Point::new(w.bounds.x0, w.bounds.y0)), at(f, vectorcraft_geom::Point::new(w.bounds.x1, w.bounds.y1)));
[a.0, a.1, b.0, b.1]
};
// A wedge and a redrawn one are the same wedge when they show the same series with the same bounds. Wedges are
// compared this many times in all, labels included; past it, nothing is matched.
let mut budget: usize = 1 << 20;
let mut copied_wedges: HashMap<u32, Vec<(usize, [f64; 4])>> = HashMap::new();
for (k, w) in now.iter().enumerate() {
copied_wedges.entry(w.series).or_default().push((k, corners(is, w)));
}
// The wedge in the same place in paint order when its bounds are the same, else the one of the series whose bounds
// are nearest, when they are the same to within 0.001 of the whole; each copied wedge is matched once.
let off = |c: &[f64; 4], d: &[f64; 4]| c.iter().zip(d).map(|(p, q)| (p - q).abs()).fold(0.0, f64::max);
let mut used = vec![false; now.len()];
let mut fills = Vec::with_capacity(wedges.len());
for (i, r) in wedges.iter().enumerate() {
let c = corners(was, r);
let k = match now.get(i) {
Some(w) if w.series == r.series && off(&c, &corners(is, w)) <= 1e-7 => i,
_ => {
let group = copied_wedges.get(&r.series)?;
if budget < group.len() {
return None;
}
budget -= group.len();
let (k, d) = group.iter().map(|(k, d)| (*k, off(&c, d))).min_by(|a, b| a.1.total_cmp(&b.1))?;
if d > 1e-3 {
return None;
}
k
}
};
if std::mem::replace(used.get_mut(k)?, true) {
return None;
}
fills.push(now.get(k)?.dark);
}
for (r, dark) in wedges.iter_mut().zip(fills) {
r.dark = dark;
}
// Each label's words and origin, in the frame of its pie's wedges.
let place = |labels: &[&Node], f| {
labels
.iter()
.map(|t| match &t.kind {
NodeKind::Text(text) => Some((text.plain_text(), at(f, text.xf * vectorcraft_geom::Point::ORIGIN))),
_ => None,
})
.collect::<Option<Vec<_>>>()
};
let (Some(copied), Some(mut drawn)) = (place(&legend, is), place(&redrawn, was)) else { return None };
// The series of each redrawn label, and its words without the mark.
let mut series = Vec::with_capacity(drawn.len());
for (words, _) in &mut drawn {
let (said, s) = words.rsplit_once(MARK)?;
let s: usize = s.parse().ok()?;
let name = g.series.get(s)?;
if *said != name.replace('|', "\n") {
return None;
}
series.push((s, name.as_str()));
words.truncate(said.len());
}
// Each label is the nearest redrawn label that says the same, and no two labels are the same redrawn one.
let mut same: HashMap<&str, Vec<usize>> = HashMap::new();
for (j, (words, _)) in drawn.iter().enumerate() {
same.entry(words.as_str()).or_default().push(j);
}
let mut taken = vec![false; drawn.len()];
let mut matched = Vec::with_capacity(copied.len());
for (words, p) in &copied {
let group = same.get(words.as_str())?;
if budget < group.len() {
return None;
}
budget -= group.len();
let away = |j: &usize| drawn.get(*j).map_or(f64::INFINITY, |(_, q)| (p.0 - q.0).powi(2) + (p.1 - q.1).powi(2));
let j = *group.iter().min_by(|a, b| away(a).total_cmp(&away(b)))?;
if std::mem::replace(taken.get_mut(j)?, true) {
return None;
}
matched.push(j);
}
let mut by_series: HashMap<u32, Vec<&Wedge>> = HashMap::new();
for w in &wedges {
by_series.entry(w.series).or_default().push(w);
}
// A redraw puts the middle of a label's lines (its series name split at `|` and line breaks, at the default leading)
// 0.35 of the label size below a point inside its wedge, at the label's origin across. The label is on the nearest
// wedge of its series to that point, the one holding it. When the wedges of the series are all dark or all light, the
// place does not matter.
let uniform: HashMap<u32, Option<bool>> =
by_series.iter().map(|(s, ws)| (*s, ws.first().map(|w| w.dark).filter(|d| ws.iter().all(|w| w.dark == *d)))).collect();
let ls = label_size(&g.label_styles, Role::Legend);
let mut out = HashMap::new();
for (t, j) in legend.iter().zip(matched) {
let (Some(r), Some((s, name))) = (redrawn.get(j), series.get(j).copied()) else { return None };
let s = u32::try_from(s).ok()?;
if let Some(Some(dark)) = uniform.get(&s) {
out.insert(t.id, *dark);
continue;
}
let NodeKind::Text(text) = &r.kind else { return None };
let middle = name.split(['|', '\n']).count().saturating_sub(1) as f64 * ls * 1.2 / 2.0;
let point = text.xf * vectorcraft_geom::Point::new(0.0, middle - ls * 0.35);
let named = by_series.get(&s)?;
if budget < named.len() {
return None;
}
budget -= named.len();
// The nearest wedge, measured exactly only while its bounds are nearer than the nearest one found so far.
let to_box = |b: vectorcraft_geom::Rect| {
let (dx, dy) = ((b.x0 - point.x).max(point.x - b.x1).max(0.0), (b.y0 - point.y).max(point.y - b.y1).max(0.0));
dx * dx + dy * dy
};
let away = |w: &Wedge| {
if w.path.contains(point) { 0.0 } else { w.path.segments().map(|seg| seg.nearest(point, 1e-3).distance_sq).fold(f64::INFINITY, f64::min) }
};
let mut by_box: Vec<(f64, &Wedge)> = named.iter().map(|w| (to_box(w.bounds), *w)).collect();
by_box.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut best: Option<(f64, bool)> = None;
for (near, w) in by_box {
if best.is_some_and(|b| near >= b.0) {
break;
}
let d = away(w);
if best.is_none_or(|b| d < b.0) {
best = Some((d, w.dark));
}
}
out.insert(t.id, best?.1);
}
Some(out)
}
/// The legend labels of graph `n` (a pie with Legends in Wedges, its labels where it drew them), each with whether a
/// redraw sets it on a dark wedge, by the fill each wedge shows now. A label is placed by the point a redraw centers it
/// on, which lies inside its wedge: the wedge holding it of the series the label names (the nearest one when none holds
/// it), or of any series when the label names none. When the wedges of the series a label names are all dark or all
/// light, the label's place does not matter.
fn legend_on_dark(n: &Node, g: &GraphSpec) -> HashMap<NodeId, bool> {
wedge_contrast(&legend_labels(n), &pie_wedges(n), g)
}
/// The point a redraw centers legend label `text` of series `name` on, in a pie of spec `g` whose legend labels are
/// `ls` points: 0.35 of the label size above where a redraw (`label` in `labels.rs`) puts the middle of the label's
/// lines, at the label's origin across. The lines are those of the series name, split at `|` and line breaks, at the
/// default leading; with kept paragraph attributes, a redraw puts the middle of the first and last baselines there
/// instead, when each of those lines that holds characters has one baseline and the first and last hold characters.
fn label_anchor(text: &vectorcraft_doc::TextObject, name: &str, g: &GraphSpec, ls: f64) -> vectorcraft_geom::Point {
let lines: Vec<&str> = name.split(['|', '\n']).collect();
let ys: Vec<f64> = text.baselines().map(|(a, _)| a.y).collect();
let set = lines.iter().filter(|l| !l.is_empty()).count();
let ends_set = lines.first().is_some_and(|l| !l.is_empty()) && lines.last().is_some_and(|l| !l.is_empty());
let middle = match (ys.first(), ys.last()) {
(Some(first), Some(last)) if g.label_styles.legend_para.is_some() && ends_set && ys.len() == set => (first + last) / 2.0,
_ => lines.len().saturating_sub(1) as f64 * ls * 1.2 / 2.0,
};
text.xf * vectorcraft_geom::Point::new(0.0, middle - ls * 0.35)
}
/// [`legend_on_dark`] for legend labels `legend` of a pie of spec `g` with wedges `wedges`.
fn wedge_contrast(legend: &[&Node], wedges: &[Wedge], g: &GraphSpec) -> HashMap<NodeId, bool> {
use vectorcraft_geom::kurbo::ParamCurveNearest;
let mut out = HashMap::new();
if legend.is_empty() {
return out;
}
let mut by_series: HashMap<u32, Vec<&Wedge>> = HashMap::new();
for w in wedges {
by_series.entry(w.series).or_default().push(w);
}
// For each label text, the wedges of the series that show it, and how many of them are dark.
let named_wedges: HashMap<String, (Vec<&Wedge>, usize)> = series_by_label(g)
.into_iter()
.map(|(name, series)| {
let named: Vec<&Wedge> = series.iter().filter_map(|s| by_series.get(s)).flatten().copied().collect();
let darks = named.iter().filter(|w| w.dark).count();
(name, (named, darks))
})
.collect();
let none = (vec![], 0);
// For each label text, the first series name that shows it (names that differ only in `|` against a line break of
// their own show the same text, and nothing in the label tells them apart).
let mut series_names: HashMap<String, &str> = HashMap::new();
for name in &g.series {
series_names.entry(name.replace('|', "\n")).or_insert(name.as_str());
}
let ls = label_size(&g.label_styles, Role::Legend);
// The search for the nearest wedge looks at this many wedges in all; past it, a label takes the contrast most of the
// wedges of its series show.
let mut budget: usize = 1 << 20;
for t in legend {
let NodeKind::Text(text) = &t.kind else { continue };
let id = t.id;
let words = text.plain_text();
let (named, darks) = named_wedges.get(&words).unwrap_or(&none);
let darks = *darks;
if (darks == 0 || darks == named.len())
&& let Some(w) = named.first()
{
out.insert(id, w.dark);
continue;
}
let name = series_names.get(&words).map_or_else(|| words.replace('\n', "|"), |s| (*s).to_owned());
let at = label_anchor(text, &name, g, ls);
if named.is_empty() {
let cost = wedges.len();
let dark = budget >= cost && wedges.iter().any(|w| w.dark && w.bounds.contains(at) && w.path.contains(at));
budget = budget.saturating_sub(cost);
out.insert(id, dark);
continue;
}
if budget < named.len() {
out.insert(id, darks * 2 > named.len());
continue;
}
budget -= named.len();
// The nearest wedge, measured exactly only while its bounds are nearer than the nearest one found so far.
let to_box = |r: vectorcraft_geom::Rect| {
let (dx, dy) = ((r.x0 - at.x).max(at.x - r.x1).max(0.0), (r.y0 - at.y).max(at.y - r.y1).max(0.0));
dx * dx + dy * dy
};
let away = |w: &Wedge| {
if w.path.contains(at) { 0.0 } else { w.path.segments().map(|s| s.nearest(at, 1e-3).distance_sq).fold(f64::INFINITY, f64::min) }
};
let mut by_box: Vec<(f64, &Wedge)> = named.iter().map(|w| (to_box(w.bounds), *w)).collect();
by_box.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut best = (f64::INFINITY, darks * 2 > named.len());
for (near, w) in by_box {
if near >= best.0 {
break;
}
let d = away(w);
if d < best.0 {
best = (d, w.dark);
}
}
out.insert(id, best.1);
}
out
}
/// Keep the anti-aliasing method `method` given to graph labels `ids` for every label of their kind, as
/// [`capture_label_styles`] keeps a formatting change. Returns whether a kept method changed.
pub(crate) fn capture_label_anti_alias(doc: &mut Document, ids: &[NodeId], method: vectorcraft_doc::text::TypeAntiAlias) -> bool {
+5 -3
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character / Paragraph",
[],
None,
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tent Line truncated
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tent Line truncated
has_doc,
set_format
),
@@ -255,7 +255,7 @@ pub(crate) fn artboard_indices(d: &vectorcraft_doc::Document, p: &Value, cmd: &s
/// list of artboard indices", and a list with an entry that is not a whole number is "`{key}` must
/// contain whole numbers"; a whole number past the last artboard is `no such artboard`. Every entry
/// is checked for its form before any is checked against the artboards.
fn listed_artboards(d: &vectorcraft_doc::Document, v: &Value, key: &str, cmd: &str) -> Result<Vec<usize>> {
pub(crate) fn listed_artboards(d: &vectorcraft_doc::Document, v: &Value, key: &str, cmd: &str) -> Result<Vec<usize>> {
let entries = v.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be a list of artboard indices")))?;
if entries.is_empty() {
return Err(bad(cmd, format!("`{key}` must be a non-empty list of artboard indices")));
@@ -645,7 +645,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
Some(v) => Some(match v.as_str() {
Some("singleLine") => Composer::SingleLine,
Some("everyLine") => Composer::EveryLine,
_ => return Err(bad(C, "composer must be \"singleLine\" or \"everyLine\"")),
Some("standardSingleLine") => Composer::StandardSingleLine,
Some("standardEveryLine") => Composer::StandardEveryLine,
_ => return Err(bad(C, "composer must be \"singleLine\", \"everyLine\", \"standardSingleLine\" or \"standardEveryLine\"")),
}),
};
let (position, small_caps) = super::docsetup::script_params(p, &s.doc()?.doc.setup, C)?;
+6 -1
View File
@@ -369,6 +369,12 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
{
return Err(bad(id, "`origin` must be [x, y] in points"));
}
if effect == vectorcraft_render::effects::SVG_FILTER
&& let Some(axes) = given.get("axes")
&& vectorcraft_render::effects::svg_filter::valid_axes(axes).is_none()
{
return Err(bad(id, "`axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0"));
}
// Its name is the filter's id.
if effect == vectorcraft_render::effects::SVG_FILTER && given.contains_key("name") && !given.contains_key("xml") {
return Err(bad(id, "an SVG filter is named by its id: give `xml` with `name`"));
@@ -529,7 +535,6 @@ pub const UNCHECKED: &[&str] = &[
"assets.settings.set",
"attributes.info",
"attributes.set",
"brush.freehand",
"css.export",
"css.generate",
"css.selection",
+19 -15
View File
@@ -5,7 +5,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection};
use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath, Vec2};
use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2};
use super::create::anchor_from_json;
use super::draw2::usize_opt;
@@ -544,10 +544,12 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
&& before > 2
&& picked(0)
&& picked(before - 1)
&& let [first, .., last] = sp.anchors.as_mut_slice()
&& same(first, last)
&& let (Some(&first), Some(&last)) = (sp.anchors.first(), sp.anchors.last())
&& same(&first, &last)
{
first.h_in = last.h_in;
if let Some(first) = sp.anchors.first_mut() {
first.h_in = last.h_in;
}
sp.anchors.pop();
if let Some(smooth) = join_kind {
join_point(sp, 0, smooth);
@@ -565,10 +567,12 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
for i in (1..len).rev() {
if picked(i - 1)
&& picked(i)
&& let Some([a, b]) = anchors.get_mut(i - 1..=i)
&& same(a, b)
&& let (Some(&a), Some(&b)) = (anchors.get(i - 1), anchors.get(i))
&& same(&a, &b)
{
a.h_out = b.h_out;
if let Some(a) = anchors.get_mut(i - 1) {
a.h_out = b.h_out;
}
if let Some(slot) = gone.get_mut(i) {
*slot = true;
}
@@ -603,7 +607,7 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
}
/// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index.
fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
fn join_point_between(anchors: &mut Anchors, ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
let at = |j: Option<usize>| j.and_then(|j| anchors.get(j)).map(|a| a.p);
let (prev, next) = (at(prev), at(next));
if let Some(a) = anchors.get_mut(ai) {
@@ -1565,7 +1569,7 @@ enum Stretch {
/// anchor, so the two handles of a smooth anchor stay in line with it. That share is below 0 or
/// above 1 for a handle long enough beside the span. A closed subpath with no anchor that stays
/// moves whole when it has a focal point.
fn stretch_weights(anchors: &[Anchor], closed: bool, roles: &[Stretch]) -> Vec<[f64; 3]> {
fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f64; 3]> {
let n = anchors.len();
let mut shares = vec![[0.0; 3]; n];
let role = |i: usize| match roles.get(i) {
@@ -1891,10 +1895,10 @@ mod tests {
&& before > 2
&& picked(0)
&& picked(before - 1)
&& let [first, .., last] = sp.anchors.as_mut_slice()
&& same(first, last)
&& let (Some(&first), Some(&last)) = (sp.anchors.first(), sp.anchors.last())
&& same(&first, &last)
{
first.h_in = last.h_in;
sp.anchors[0].h_in = last.h_in;
sp.anchors.pop();
if let Some(smooth) = join_kind {
join_point(sp, 0, smooth);
@@ -1903,10 +1907,10 @@ mod tests {
for i in (1..sp.anchors.len()).rev() {
if picked(i - 1)
&& picked(i)
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
&& same(a, b)
&& let (Some(&a), Some(&b)) = (sp.anchors.get(i - 1), sp.anchors.get(i))
&& same(&a, &b)
{
a.h_out = b.h_out;
sp.anchors[i - 1].h_out = b.h_out;
sp.anchors.remove(i);
if let Some(smooth) = join_kind {
join_point(sp, i - 1, smooth);
+150 -16
View File
@@ -4,6 +4,10 @@
//! - A raster image becomes one image at 100% of its physical size: its pixels at the resolution
//! the file declares ([`fileio::ppi`]; 72 ppi when it declares none), linked to its file with
//! `link` ([`super::links`]).
//! - A PSD or PSB file placed with `layers` becomes one group of its layers as objects, embedded
//! ([`fileio::psd_layers`]); otherwise it is an image like any other, its merged image. An
//! embedded one brings its slices in as user slices, placed with its art (`importSlices`,
//! [`fileio::psd_slices`]).
//! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options
//! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`).
//! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or
@@ -45,7 +49,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SymbolBoxes};
use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes};
use vectorcraft_geom::{Affine, Point, Rect, shapes};
use vectorcraft_pdf::CropTo;
@@ -75,7 +79,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, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; 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), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf and a PDF with several pages or a password and no page ask for those options first; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. 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 and PICT (.pct, .pic, .pict; 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. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. 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, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; 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), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), 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), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. 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 and PICT (.pct, .pic, .pict; 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. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives Line truncated
has_doc,
place
),
@@ -84,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Placed File Info",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…} (both as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
always,
info
),
@@ -102,7 +106,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Load Place Cursor",
[],
None,
"{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}",
"{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, layers?, hiddenLayers?, importSlices?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}",
has_doc,
queue
),
@@ -148,16 +152,33 @@ struct Loaded {
board: Option<Rect>,
}
/// A PSD or PSB file's slices, embedded with `importSlices`: their rectangles over the natural box
/// of its art, and their options.
type Slices = Vec<(Rect, SliceOptions)>;
/// Points per pixel of a raster image at the resolution it declares (72 ppi when none).
pub(crate) fn pt_per_px(ppi: Option<(f64, f64)>) -> (f64, f64) {
let (x, y) = ppi.unwrap_or((72.0, 72.0));
(72.0 / x, 72.0 / y)
}
/// [`load_sliced`] without the slices.
fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loaded> {
load_into(p, cmd, board, link_pdf, &mut vec![])
}
/// [`load_into`], with the slices of a PSD or PSB file that `importSlices` brings in.
fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<(Loaded, Slices)> {
let mut slices = vec![];
let l = load_into(p, cmd, board, link_pdf, &mut slices)?;
Ok((l, slices))
}
/// The file `p` names, read into placeable art; a DXF drawing's Fit to Artboard fills `board`
/// (unless the params name their own box). A PDF/.ai page read from a path is placed linked with
/// Link when `link_pdf` (false for the queries, which read it embedded).
fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loaded> {
/// Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB file's slices
/// go to `slices`.
fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_out: &mut Slices) -> Result<Loaded> {
let src = fileio::source(p, cmd)?;
let name = fileio::file_name(src.name);
// An Affinity file is recognised by its signature, whatever its name says.
@@ -237,12 +258,52 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
let art = Art::Vector { src: Box::new(a.doc), nodes: a.nodes, clip: a.clip };
return Ok(Loaded { name, format, art, natural: a.frame, warnings: a.warnings, link: None, board: None });
}
// A PSD or PSB file placed with `layers`: its layers as objects, never linked. One without
// layers, or whose layers can't be read, is embedded as its merged image.
let (mut embed, mut unread) = (false, vec![]);
let mut slices_from = None;
if matches!(format.id, "psd" | "psb") {
let layers = switch_or(p, "layers", false, cmd)?;
if switch_or(p, "hiddenLayers", false, cmd)? && !layers {
return Err(bad(cmd, "hiddenLayers applies to a PSD file placed with layers: true"));
}
// Slices come in with an embedded file (default on); a linked file shows its flat image.
let linked = !layers && src.path.is_some() && bool_or(p, "link", true);
let slices = switch_or(p, "importSlices", !linked, cmd)?;
if slices && linked {
return Err(bad(cmd, "importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices"));
}
if slices {
slices_from = Some(&src.bytes[..]);
}
if layers {
// Layers are embedded: a link shows the file's flat image.
if switch_or(p, "link", false, cmd)? {
return Err(bad(cmd, "layers: a linked PSD file is placed as its flat image; leave link out or give link: false"));
}
embed = true;
match fileio::psd_layers(&src.bytes, opts.hidden_layers) {
Ok(Some((doc, mut warnings))) => match psd_groups(doc) {
Some((art, natural)) => {
*slices_out = psd_slices(slices_from, natural, &mut warnings);
return Ok(Loaded { name, format, art, natural, warnings, link: None, board: None });
}
// No layer has art: the merged image, embedded.
None => unread = warnings,
},
// No layers: the merged image, embedded.
Ok(None) => {}
Err(e) => unread.push(format!("the layers can't be read ({e}): the file was placed as its merged image")),
}
}
}
if format.raster {
let img = fileio::raster_image(&src.bytes)?;
let (sx, sy) = pt_per_px(img.ppi);
let natural = Rect::new(0.0, 0.0, img.width as f64 * sx, img.height as f64 * sy);
let link = src.path.map(|path| super::links::link_info(path, &src.bytes));
let warnings = fileio::size_note(&img.blob.bytes).into_iter().collect();
let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes));
let mut warnings: Vec<String> = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect();
*slices_out = psd_slices(slices_from, natural, &mut warnings);
let clip = fileio::psdread::clipping_path(&src.bytes);
return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None });
}
@@ -303,6 +364,56 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip }, natural, warnings, link: None, board })
}
/// A PSD or PSB file's layers, read as `document.open` reads them into `doc`, as art to place: an
/// image for each layer and a group for each layer group, bottom first, with the layer's name,
/// visibility, opacity, blend mode and opacity mask. The art's natural box is the file's canvas,
/// where the merged image would lie, and the art is clipped to the canvas when layers reach past it.
/// None when no layer brought any art in.
fn psd_groups(mut doc: Document) -> Option<(Art, Rect)> {
let canvas = doc.artboards.first()?.rect;
let nodes = psd_objects(&std::mem::take(&mut doc.layers));
// Hidden layers count too: showing one later must not draw past the canvas.
let symbols = doc.symbol_boxes();
let reached = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, reach(&symbols, n)))?;
let past = reached.union(canvas) != canvas;
Some((Art::Vector { src: Box::new(doc), nodes, clip: past.then_some(canvas) }, canvas))
}
/// The slices of the PSD or PSB file `bytes` (none without it) laid over `canvas`, the natural box
/// of its art; their warnings go to `warnings`.
fn psd_slices(bytes: Option<&[u8]>, canvas: Rect, warnings: &mut Vec<String>) -> Slices {
let Some(bytes) = bytes else { return vec![] };
let (slices, notes) = fileio::psd_slices(bytes, canvas);
warnings.extend(notes);
slices
}
/// The bounds of `n` and every object inside it, hidden ones included.
fn reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
match n.children() {
Some(kids) => kids.iter().fold(None, |acc, k| vectorcraft_geom::union_opt(acc, reach(symbols, k))),
None => n.geometric_bounds_with(symbols),
}
}
/// The layers a PSD import made as objects: a layer of sublayers as a group of them, and a layer
/// holding one image as that image, each with the layer's name, visibility, opacity, blend mode,
/// isolation and opacity mask.
fn psd_objects(layers: &[Arc<Node>]) -> Vec<Node> {
layers
.iter()
.map(|l| {
let mut n = (**l).clone();
let NodeKind::Layer { children, .. } = &l.kind else { return n };
n.kind = match &children[..] {
[c] if matches!(c.kind, NodeKind::Image(_)) => c.kind.clone(),
_ => NodeKind::Group { children: psd_objects(children).into_iter().map(Arc::new).collect(), clip: false },
};
n
})
.collect()
}
/// Page `page` (1-based) of the PDF/.ai/.ait file `src` (`bytes`, read from `path` when there is
/// one) as art to place: clipped to the box `opts.crop` names, or (`bounding`) the bounds of its
/// art; read with `opts.password`. Only the page placed is read. A .ai saved without PDF
@@ -548,6 +659,7 @@ pub struct PlaceJob {
pub struct PlaceRead {
job: PlaceJob,
loaded: Loaded,
slices: Slices,
}
impl PlaceJob {
@@ -562,7 +674,7 @@ impl PlaceJob {
/// the renderers' image store for the first frame that draws them
/// ([`super::links::readable_and_kept`]).
pub fn read(self) -> Result<PlaceRead> {
let mut loaded = load(&self.params, PLACE, self.target, true)?;
let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true)?;
let linked = loaded.link.is_some() && bool_or(&self.params, "link", true);
match &mut loaded.art {
Art::Image(img, _) => {
@@ -572,7 +684,7 @@ impl PlaceJob {
Art::Dcs(a) => a.img.blob = super::links::readable(a.img.blob.clone(), false, true)?,
_ => {}
}
Ok(PlaceRead { job: self, loaded })
Ok(PlaceRead { job: self, loaded, slices })
}
}
@@ -653,7 +765,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
/// Place the file `read` holds in the active document.
fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded } = read;
let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded, slices: read_slices } = read;
let p = &params;
let template = bool_or(p, "template", false);
let at = at_param(p)?;
@@ -699,7 +811,22 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
if let Art::Dcs(a) = &loaded.art {
warnings.extend(dcs::swatch_notes(&st.doc, &a.spots));
}
let (id, size) = s.edit("Place", |d, sel| {
// A PSD file's slices move and scale with its art; one that would leave the canvas is left out.
let read_count = read_slices.len();
let slices: Slices = read_slices
.into_iter()
.filter_map(|(r, o)| {
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c));
super::slices::slice_rect_ok(placed).then_some((placed, o))
})
.collect();
match read_count - slices.len() {
0 => {}
1 => warnings.push("1 slice would lie outside the canvas and was left out".into()),
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
}
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
let node = transformed(build(d, loaded, link), m);
let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default();
let (into, index) = match old {
@@ -712,15 +839,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
None => (parent, usize::MAX),
};
let id = d.insert(into, index, node)?;
let slice_ids: Vec<u64> = slices.into_iter().map(|(r, o)| super::slices::add_slice(d, r, o).0).collect();
// Template art is locked: nothing to select.
if template {
sel.clear()
} else {
sel.set([id])
}
Ok((id, size))
Ok((id, size, slice_ids))
})?;
let mut out = json!({ "ids": [id.0], "name": name, "format": format, "linked": linked, "width": size.width(), "height": size.height(), "warnings": warnings });
if !slice_ids.is_empty() {
out["slices"] = json!(slice_ids);
}
// A DCS, PSD or PSB file clipped by its clipping path: its image, which the Links commands
// take.
if file_clipped {
@@ -824,7 +955,7 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> {
let thumbnail = p.get("thumbnail").and_then(Value::as_f64);
let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]);
for mut q in queued {
for k in ["link", "template", "page", "crop", "text", "dxf"] {
for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices"] {
if let Some(v) = p.get(k) {
q[k] = v.clone();
}
@@ -870,7 +1001,7 @@ 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_switches(params, &["link", "template", "layers", "hiddenLayers", "importSlices"], QUEUE)?;
check_numbers(params, &["thumbnail"], QUEUE)?;
let files = queued_files(params)?;
Ok(QueueJob { doc: self.doc()?.uid, params: params.clone(), files })
@@ -948,7 +1079,7 @@ 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 (mut l, slices) = load_sliced(p, "file.place.info", None, false)?;
let natural = l.natural;
let mut out = json!({
"name": l.name,
@@ -957,6 +1088,9 @@ pub fn read_info(p: &Value) -> Result<Value> {
"height": natural.height(),
"warnings": std::mem::take(&mut l.warnings),
});
if matches!(l.format.id, "psd" | "psb") {
out["slices"] = json!(slices.len());
}
if let Art::Image(img, _) = &l.art {
let (x, y) = img.ppi.unwrap_or((72.0, 72.0));
out["pixelWidth"] = json!(img.width);
+128 -4
View File
@@ -334,10 +334,19 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
/// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when
/// that is its only visible raster effect and is its own (not a fill's or a stroke's): made of `n`
/// without that effect and without its transparency, which stays on the object. `None` otherwise,
/// or when the image can't be made.
/// without that effect and without its transparency, which stays on the object. When Transform
/// effects after the Rasterize effect move its image ([`vectorcraft_render::rasterize_stage`]),
/// the image is made of the art before them and moved by them, as the canvas draws it. `None`
/// otherwise, when those Transform effects flatten the image, or when the image can't be made.
fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
let staged = vectorcraft_render::rasterize_stage(d, n);
if let Some((_, map)) = &staged
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
{
return None;
}
let n = staged.as_ref().map_or(n, |(stage, _)| stage);
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
let p = json!({
"ppi": r.ppi.unwrap_or(d.raster_effects_ppi),
@@ -354,7 +363,11 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
// shortcut: expanded Rasterize effects stay RGB, as the object keeps its own opacity mask and the
// image's transparency would need one too; upgrade when CMYK images carry alpha.
let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?;
Some(image.into_node(d))
let mut image = image.into_node(d);
if let Some((_, map)) = staged {
image.transform(map, false);
}
Some(image)
}
/// `v` (an object without its raster effects) replaced by `image` of the object with them: the
@@ -473,7 +486,9 @@ fn imaged(n: &Node, which: Which) -> bool {
let live = filters
&& pixels == 1
&& effects::svg_filter::writes_live(&n.appearance.effects)
&& fx.iter().any(|f| matches!(f, RasterFx::Pixel(effects::PixelFx::Svg(s)) if s.in_points() && (!s.measured() || fx.len() == 1) && s.writes_as_svg11()));
&& fx
.iter()
.any(|f| matches!(f, RasterFx::Pixel(effects::PixelFx::Svg(s)) if (!s.measured() || fx.len() == 1) && s.writes_as_svg11() && s.opens_again()));
(pixels > 0 && !live)
|| (fx.iter().any(|f| matches!(f, RasterFx::DropShadow { darkness: Some(_), .. })) && (cmyk || !simple_rgb_shadow_source(n, &fx)))
}
@@ -589,6 +604,112 @@ fn walk_all(out: &mut Document, nodes: &[Arc<Node>], report: &mut FlattenReport)
.then(|| nodes.iter().map(|n| walk(out, n, report).map(Arc::new).unwrap_or_else(|| n.clone())).collect())
}
/// `n` as an image when its Rasterize image moves with the Transform effects after it
/// ([`vectorcraft_render::rasterize_stage`]): the image is made of the art before those Transform
/// effects and moved by them, as the canvas draws it, which baking the geometry effects first would
/// lose. A map that flattens the image leaves an empty group, as the canvas draws nothing. Inside
/// groups, layers and opacity masks, the members are looked at the same way. `None` when nothing in
/// `n` changes; hidden objects and template layers stay as they are.
fn staged(out: &mut Document, n: &Node, report: &mut FlattenReport) -> Option<Node> {
if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) {
return None;
}
if let Some((_, map)) = vectorcraft_render::rasterize_stage(out, n) {
let mut v = n.clone();
strip_raster(&mut v, false);
let det = map.determinant();
if !(det.is_finite() && det.abs() > 1e-12) {
v.appearance = Default::default();
v.kind = NodeKind::Group { children: vec![], clip: false };
return Some(v);
}
let image = raster_image(out, n, false, false)?;
report.record(n, &image);
let mut m = replace_with_image(v, image);
staged_mask(out, &mut m, report);
return Some(m);
}
let mut m = n.clone();
let mut changed = staged_mask(out, &mut m, report);
if is_container(n)
&& let Some(ch) = staged_all(out, n.children()?, report)
&& let Some(slot) = m.children_mut()
{
*slot = ch;
changed = true;
}
changed.then_some(m)
}
/// The art of `n`'s opacity mask with [`staged`] applied; `true` when it changed.
fn staged_mask(out: &mut Document, n: &mut Node, report: &mut FlattenReport) -> bool {
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& let Some(art) = staged(out, &m.art, report)
{
m.art = Arc::new(art);
return true;
}
false
}
/// Does `n`, or anything inside it or its opacity mask, list a Rasterize effect whose image the
/// Transform effects after it move ([`effects::rasterize_stage`])?
fn holds_stage(n: &Node) -> bool {
effects::rasterize_stage(&n.appearance.effects).is_some()
|| n.extras().mask.as_ref().is_some_and(|m| holds_stage(&m.art))
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_stage(c)))
}
/// A copy of `doc` with [`staged`] applied in its layers, symbol definitions and pattern tiles,
/// `None` when nothing changes.
fn staged_document(doc: &Document, report: &mut FlattenReport) -> Option<Document> {
let holds = doc.layers.iter().any(|n| holds_stage(n))
|| doc.symbols.iter().any(|s| holds_stage(&s.art))
|| doc.patterns.iter().any(|p| p.art.iter().any(|n| holds_stage(n)));
if !holds {
return None;
}
let mut out = doc.clone();
let mut changed = false;
if let Some(layers) = staged_all(&mut out, &doc.layers, report) {
out.layers = layers;
changed = true;
}
for i in 0..out.symbols.len() {
if let Some(art) = out.symbols.get(i).map(|s| s.art.clone()).and_then(|a| staged(&mut out, &a, report))
&& let Some(s) = out.symbols.get_mut(i)
{
s.art = Arc::new(art);
changed = true;
}
}
for i in 0..out.patterns.len() {
if let Some(art) = out.patterns.get(i).map(|p| p.art.clone()).and_then(|a| staged_all(&mut out, &a, report))
&& let Some(p) = out.patterns.get_mut(i)
{
p.art = art;
changed = true;
}
}
changed.then_some(out)
}
/// `nodes` with [`staged`] applied, `None` when none changes.
fn staged_all(out: &mut Document, nodes: &[Arc<Node>], report: &mut FlattenReport) -> Option<Vec<Arc<Node>>> {
let mut changed = false;
let all = nodes
.iter()
.map(|n| match staged(out, n, report) {
Some(m) => {
changed = true;
Arc::new(m)
}
None => n.clone(),
})
.collect();
changed.then_some(all)
}
/// A copy of `doc` with raster effects turned into images at the document's raster effects
/// resolution, or `None` when there are none: on every kind of object (paths, groups and layers,
/// type, images, symbol instances, live objects) and on single fills and strokes, in the layers,
@@ -616,6 +737,9 @@ fn flatten(doc: &Document, report: &mut FlattenReport) -> Option<Document> {
if !any(&doc.layers) && !doc.symbols.iter().any(|s| needs(&s.art, which)) && !doc.patterns.iter().any(|p| any(&p.art)) {
return None;
}
// Rasterize images that Transform effects after them move, before those effects are baked.
let pre = staged_document(doc, report);
let doc = pre.as_ref().unwrap_or(doc);
// Geometry effects first, so the vector objects kept above shadows are final.
let baked = effects::bake_document(doc);
let src = baked.as_ref().unwrap_or(doc);
+3 -2
View File
@@ -999,8 +999,9 @@ impl RecoveryJob {
pub fn write(&self) -> std::result::Result<Value, String> {
let store = self.store.as_ref();
let doc = self.save.doc();
// A linked image keeps its preview, as a save writes it.
let linked = doc.linked_only_images();
// A linked image keeps its preview, as a save writes it (the images in the stored brushes'
// art counted too).
let linked = super::links::with_brush_art(doc).linked_only_images();
let mut lean = Document::clone(doc);
let blobs = std::mem::take(&mut lean.images);
let enc = self.save.encode_doc(&lean).map_err(|e| e.to_string())?;
+6 -5
View File
@@ -8,9 +8,10 @@ use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_tools::builder::is_live_paint;
use super::object::can_align;
use super::panelcmds::artboard_at;
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,
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param,
switch_or, text_param,
};
use crate::DocState;
@@ -31,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"All on Active Artboard",
["Select"],
Some("Cmd+Alt+A"),
"{artboard?: index (0-based; the app passes the active one; default: the first)}",
"{artboard?: index (0-based whole number; the app passes the active one; default, or null: the first)}",
has_doc,
all_on_artboard
),
@@ -229,7 +230,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Appearance Attribute",
["Select", "Same"],
None,
"{item?: appearance item index} the objects sharing an appearance attribute of the first selected object: its fill or stroke `item` (default: the Appearance panel's active item), else its first effect, else its topmost fill (compound paths as select.same.fillColor)",
"{item?: appearance item index (0-based whole number; default, or null: the Appearance panel's active item)} the objects sharing an appearance attribute of the first selected object: its fill or stroke `item` (default: the Appearance panel's active item), else its first effect, else its topmost fill (compound paths as select.same.fillColor)",
has_selection,
same_attribute
),
@@ -428,7 +429,7 @@ fn all(s: &mut Session, _: &Value) -> Result<Value> {
fn all_on_artboard(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let i = p.get("artboard").and_then(Value::as_u64).map_or(0, index);
let i = artboard_at(&st.doc, p, "artboard", "select.allOnArtboard")?.unwrap_or(0);
let r = st.doc.artboards.get(i).map(|a| a.rect).ok_or_else(|| bad("select.allOnArtboard", "no such artboard"))?;
let symbols = st.doc.symbol_boxes();
let ids: Vec<NodeId> =
@@ -1217,10 +1218,10 @@ enum Attribute {
fn same_attribute(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "select.same.appearanceAttribute";
let item = index_opt(p, "item", cmd)?.or(s.appearance_item());
let st = s.doc()?;
let (refn, _) = same_reference(st, cmd)?;
let ap = &refn.appearance;
let item = p.get("item").and_then(Value::as_u64).map(index).or(s.appearance_item());
let attr = match (item.and_then(|i| ap.items.get(i)), ap.effects.first()) {
(Some(it), _) => Attribute::Item(it.clone()),
(None, Some(e)) => Attribute::Effect(e.clone()),
+28 -3
View File
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Merge Swatches",
["Window", "Swatches"],
None,
"{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), as one undo step → {name, merged: [deleted names], relinked}",
"{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), and gradient stops linked to them drop their process plates, as one undo step → {name, merged: [deleted names], relinked}",
has_doc,
swatch_merge
),
@@ -688,6 +688,11 @@ impl Relink {
/// batch, and a canceled batch preview, put back the paints the batch started with. A change is
/// recorded with the step just made, so Undo and Redo put these paints back with the document.
pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) -> Result<()> {
map_default_paints_by(s, &mut |p| p.map_links(f))
}
/// [`map_default_paints`] with `f` applied to each whole paint; `f` returns true when it changed it.
fn map_default_paints_by(s: &mut Session, f: &mut dyn FnMut(&mut Paint) -> bool) -> Result<()> {
if s.in_interaction() && s.batch_stash.is_none() {
return Ok(());
}
@@ -699,7 +704,7 @@ pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) -> Result<()>
});
let mut changed = false;
for p in [&mut pd.fill, &mut pd.stroke].into_iter().chain(template) {
changed |= p.map_links(f);
changed |= f(p);
}
if changed {
super::colormgmt::record_new_art_colors(s, start)?;
@@ -1124,17 +1129,37 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> {
*l = link.clone();
true
};
// A stop linked to a merged swatch loses its process plates, which printed with that ink.
let mut unplate = |p: &Paint| {
let mut q = p.clone();
drop_stop_plates(&mut q, &merged_names).then_some(q)
};
let colorized_ok = super::paint::check_colorized(d).is_ok();
let relinked = s.edit("Merge Swatches", |d, _| {
take_swatches(d, merged, |_| true);
map_all_paints(d, &mut unplate);
let relinked = map_swatch_links(d, &mut relink);
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
Ok(relinked)
})?;
map_default_paints(s, &mut relink)?;
map_default_paints_by(s, &mut |p| {
let unplated = drop_stop_plates(p, &merged_names);
p.map_links(&mut relink) | unplated
})?;
Ok(json!({"name": keep, "merged": merged, "relinked": relinked}))
}
/// Clear the process plates of `p`'s gradient stops linked to a swatch in `names`. True when any
/// stop had plates.
fn drop_stop_plates(p: &mut Paint, names: &HashSet<&str>) -> bool {
let Paint::Gradient(g) = p else { return false };
g.gradient
.stops
.iter_mut()
.filter(|st| st.swatch.as_deref().is_some_and(|l| names.contains(l)))
.fold(false, |ch, st| st.plates.take().is_some() | ch)
}
fn swatch_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.ungroup";
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?.to_string();
+1 -1
View File
@@ -384,7 +384,7 @@ fn weather_icons() -> SymbolLibrary {
Anchor { p: Point::new(5.0, 16.0), h_in: Point::new(-6.0, 16.0), h_out: Point::new(0.0, 8.0), kind: AnchorKind::Corner },
Anchor { p: Point::new(-4.0, -1.0), h_in: Point::new(-4.0, 6.0), h_out: Point::new(-4.0, -8.0), kind: AnchorKind::Smooth },
];
let moon = PathData::single(SubPath { anchors: moon_anchors, closed: true });
let moon = PathData::single(SubPath::new(moon_anchors, true));
// Helper for cloud contour
let cloud_subpath = |offset_y: f64, scale: f64| -> SubPath {
+24
View File
@@ -1652,6 +1652,30 @@ fn paragraph_style_options_edit_applies_to_users_and_is_one_saved_undo_step() {
}
}
/// A paragraph style can hold a Standard composer: it applies to its paragraphs, redefining and
/// resetting treat it like any attribute, and the style and the paragraphs keep it through a save.
#[test]
fn paragraph_styles_keep_a_standard_composer_through_a_save() {
use vectorcraft_doc::Composer;
let (mut s, id) = session_with_text("One\nTwo");
s.execute("paraStyle.new", &json!({"name": "Legacy", "attrs": {"composer": "standardSingleLine"}})).unwrap();
s.execute("paraStyle.apply", &json!({"name": "Legacy", "id": id, "start": 0, "end": 0})).unwrap();
assert_eq!(paras(&s, id).iter().map(|p| p.composer).collect::<Vec<_>>(), [Composer::StandardSingleLine, Composer::EveryLine]);
let doc = s.doc().unwrap().doc.clone();
let saved = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
let style = saved.para_styles.iter().find(|d| d.name == "Legacy").unwrap();
assert_eq!(style.attrs["composer"], json!("standardSingleLine"));
let mut composers = vec![];
saved.walk(|n| {
if let vectorcraft_doc::NodeKind::Text(t) = &n.kind {
composers.extend(t.paragraph_styles().iter().map(|p| p.composer));
}
});
assert_eq!(composers, [Composer::StandardSingleLine, Composer::EveryLine]);
s.execute("paraStyle.setAttrs", &json!({"name": "Legacy", "attrs": {"composer": "standardEveryLine"}})).unwrap();
assert_eq!(paras(&s, id)[0].composer, Composer::StandardEveryLine, "an edited style reaches its paragraphs");
}
/// 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.
+7 -5
View File
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Outlines",
["Type"],
Some("Cmd+Shift+O"),
"{} convert the selected text to groups of compound paths (one per glyph); the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
"{} convert the selected text to groups of compound paths (one per glyph); the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; the group keeps the object's transparency, opacity mask and effects, once; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
has_selection,
create_outlines
),
@@ -739,11 +739,13 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
if children.is_empty() {
continue;
}
// The group takes the object's name, transparency, opacity mask and effects, which
// apply to the type as a whole: once, not to each glyph. It is marked as type's
// outlines, so geometry effects move its placed gradients with the whole outline, as
// they do on the type.
let gid = d.alloc_id();
let mut g = Node::group(gid, children);
g.opacity = n.opacity;
g.blend = n.blend;
g.name = n.name.clone();
let mut g = super::flatten::carry(&n, Node::group(gid, children));
g.extras_mut().type_outlines = true;
d.insert(par, idx, g)?;
out.push(gid);
if roots.contains(&tid) {
+7 -10
View File
@@ -138,7 +138,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paste without Formatting",
["Edit"],
Some("Cmd+Alt+V"),
"{center?, dx?, dy?, swatchConflict?} paste as edit.paste; pasted text takes the default character style (one run) and leaves its character and paragraph styles behind, as do the labels of pasted graphs → {ids, added, merged, renamed}",
"{center?, dx?, dy?, swatchConflict?} paste as edit.paste; pasted text takes the default character style (one run) and leaves its character and paragraph styles behind, as do the labels of pasted graphs, which take a new graph's label character style and paragraph attributes (keeping their alignment); a pasted graph no longer keeps its labels' character and paragraph formats, so a later redraw sets them the same way → {ids, added, merged, renamed}",
has_clipboard,
paste_plain
),
@@ -1767,15 +1767,12 @@ fn strip_formatting(n: &mut vectorcraft_doc::Node) {
t.set_all_paras(Default::default());
refresh_bounds(t);
}
// A graph keeps the names of its labels' character and paragraph styles for each redraw.
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
let l = &mut g.label_styles;
for st in [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten() {
st.style_name = None;
}
for pa in [&mut l.values_para, &mut l.categories_para, &mut l.legend_para].into_iter().flatten() {
pa.style_name = None;
}
// A graph keeps its labels' character and paragraph formats for each redraw: they go with the
// labels' own formatting, and the labels are set in a new graph's label formats. The graph's generated
// bounds follow its changed labels, so the next redraw does not read them as a move.
if n.extras().graph.is_some() {
super::graph::edit_graph_art(n, |n| super::graph::plain_labels(n, &strip_formatting));
return;
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
+17 -2
View File
@@ -59,8 +59,23 @@ fn rect_in_range(r: vectorcraft_geom::Rect) -> bool {
/// margin passes without being measured: its curves stay inside their control points. Any other
/// object, and a path with a point outside that margin, is measured.
pub(crate) fn objects_in_range(d: &Document, ids: &[NodeId]) -> bool {
let paths = d.index_paths(ids.iter().copied());
ids.iter().all(|id| paths.get(id).and_then(|p| d.node_at(p)).is_none_or(|n| points_in_range(n) || n.geometric_bounds().is_none_or(rect_in_range)))
if ids.is_empty() {
return true;
}
let node_ok = |n: &vectorcraft_doc::Node| points_in_range(n) || n.geometric_bounds().is_none_or(rect_in_range);
// A cached document or a few ids: look each one up. Otherwise one walk of the tree, with no
// path vectors allocated.
if d.has_lookup_cache() || ids.len() <= 16 {
return ids.iter().all(|id| d.node(*id).is_none_or(node_ok));
}
let want: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let mut ok = true;
d.walk(|n| {
if ok && want.contains(&n.id) && !node_ok(n) {
ok = false;
}
});
ok
}
/// Coordinates at most this far from 0 keep a curve's measured bounds within [`MAX_COORD`]
+69 -4
View File
@@ -1545,6 +1545,7 @@ fn shape_commands_refuse_a_number_or_boolean_given_as_text() {
("shape.flare", json!({"cx": 100, "cy": 100, "x2": "300", "y2": 300}), "x2"),
("shape.flare", with(&flare, "direction", json!("45")), "direction"),
("shape.flare", with(&flare, "seed", json!("7")), "seed"),
("shape.flare", with(&flare, "ringSeed", json!("7")), "ringSeed"),
("shape.spiral", with(&spiral, "decay", json!("80")), "decay"),
("shape.spiral", with(&spiral, "segments", json!("10")), "segments"),
]
@@ -2132,7 +2133,7 @@ mod pen_interactions {
gesture(&mut s, &[(400.0, 500.0)], Mods::default(), v);
let extended = path(&s, id);
assert_eq!(extended.anchor_count(), 3);
assert_eq!(extended.subpaths[0].anchors[..2], reversed.subpaths[0].anchors);
assert_eq!(extended.subpaths[0].anchors.to_vec()[..2], reversed.subpaths[0].anchors);
assert!(!s.in_interaction() && !s.tool_busy());
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 1);
}
@@ -2167,7 +2168,7 @@ mod pen_interactions {
gesture(&mut s, &[(300.0, 400.0)], Mods::default(), v);
let extended = path(&s, id);
assert_eq!(extended.anchor_count(), 3);
assert_eq!(extended.subpaths[0].anchors[..2], converted.subpaths[0].anchors);
assert_eq!(extended.subpaths[0].anchors.to_vec()[..2], converted.subpaths[0].anchors);
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 1);
}
@@ -2226,7 +2227,7 @@ mod pen_interactions {
}
let extended = path(&s, id);
assert_eq!(extended.anchor_count(), 3);
assert_eq!(extended.subpaths[0].anchors[..2], before.subpaths[0].anchors);
assert_eq!(extended.subpaths[0].anchors.to_vec()[..2], before.subpaths[0].anchors);
let a = extended.subpaths[0].anchors[2];
assert_eq!(a.p, Point::new(320.0, 450.0));
assert_eq!(a.h_in, Point::new(290.0, 430.0), "Alt freezes the incoming handle and Space translates it");
@@ -3269,6 +3270,70 @@ fn flare_rotation_turns_only_the_rays() {
}
}
/// `shape.flare`'s `ringSeed` places the rings along the path anew and keeps their count and
/// sizes and the other parts; the same `ringSeed` draws the same flare, neighboring ones differ,
/// and a seed that is not a whole number of at least 0 (for `ringSeed`, below 2^53) is refused.
#[test]
fn flare_ring_seed_moves_only_the_rings() {
let mut s = session();
let parts = |s: &mut Session, ring_seed: Option<u64>| {
let mut p = json!({"cx": 200, "cy": 200, "diameter": 60, "rays": 9, "rings": 6, "x2": 400, "y2": 300, "seed": 3});
if let Some(r) = ring_seed {
p["ringSeed"] = json!(r);
}
let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap());
let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("flare is a group") };
children.iter().map(|c| (c.name.clone(), c.geometric_bounds().unwrap())).collect::<Vec<_>>()
};
let plain = parts(&mut s, None);
let placed = parts(&mut s, Some(11));
assert_eq!(placed, parts(&mut s, Some(11)));
assert_eq!(plain.len(), placed.len());
let mut moved = 0;
for ((name, a), (_, b)) in plain.iter().zip(&placed) {
if name.as_deref() == Some("Ring") {
assert!((a.width() - b.width()).abs() < 1e-9, "a ring keeps its size");
moved += usize::from(a.center().distance(b.center()) > 1e-6);
} else {
assert_eq!(a, b, "{name:?}");
}
}
assert_eq!(moved, 6, "every ring moves");
assert_ne!(parts(&mut s, Some(0)), parts(&mut s, Some(1)), "neighboring seeds place the rings differently");
let undo = s.doc().unwrap().history.undo.len();
for bad in [json!(-1), json!(2.5), json!(true), json!(1u64 << 53)] {
assert!(s.execute("shape.flare", &json!({"cx": 0, "cy": 0, "ringSeed": bad})).is_err(), "{bad}");
}
for bad in [json!(-1), json!(2.5), json!(true)] {
assert!(s.execute("shape.flare", &json!({"cx": 0, "cy": 0, "seed": bad})).is_err(), "{bad}");
}
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
/// Through the session, Ctrl/Cmd in the Flare tool's center drag keeps the center's size while the
/// drag sizes the halo, and the flare drawn keeps both.
#[test]
fn flare_tool_ctrl_keeps_the_center_while_the_drag_sizes_the_halo() {
let mut s = session();
let v = ViewInfo::default();
let cmd = vectorcraft_tools::Mods { cmd: true, ..Default::default() };
s.select_tool("flare", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 240.0, 200.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 200.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 200.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 500.0, 400.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 500.0, 400.0), v).unwrap();
let st = s.doc().unwrap();
let g = st.doc.node(st.selection.objects[0]).unwrap();
let NodeKind::Group { children, .. } = &g.kind else { panic!("flare is a group") };
let width = |name: &str| children.iter().find(|c| c.name.as_deref() == Some(name)).unwrap().geometric_bounds().unwrap().width();
// The center as the key found it (80); the halo as a 160-point center with 20 % growth would
// have it: 80 × 1.2 × 1.6 = 153.6 radius.
assert!((width("Center") - 80.0).abs() < 0.5, "{}", width("Center"));
assert!((width("Halo") - 2.0 * 153.6).abs() < 0.5, "{}", width("Halo"));
}
#[test]
fn reshape_moves_the_grabbed_point_and_its_neighbourhood() {
let mut s = session();
@@ -3316,7 +3381,7 @@ fn reshape_open_path(s: &mut Session, anchors: Value) -> NodeId {
/// The anchors of the path's first subpath.
fn reshape_anchors(s: &Session, id: NodeId) -> Vec<vectorcraft_geom::Anchor> {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.clone()
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.to_vec()
}
/// The share of the drag an anchor takes at `u` of the way from an end to the grabbed point.
+57 -3
View File
@@ -3,7 +3,7 @@
use serde_json::json;
use crate::cmd::actionset::{AiaStep, read_aia};
use crate::cmd::actionset::{AiaData, AiaStep, AiaValue, read_aia};
use crate::*;
/// `text` as a bracketed hexadecimal value.
@@ -37,7 +37,12 @@ fn a_set_reads_its_actions_and_steps() {
let names: Vec<&str> = set.actions.iter().map(|a| a.name.as_str()).collect();
assert_eq!(names, ["First", "二番目"]);
let step = |a: usize, s: usize| set.actions[a].steps[s].clone();
let join = AiaStep { name: "sample_join".into(), label: Some("Join".into()), on: Some(1), params: 3, declared: Some(3), line: 9 };
let values = vec![
AiaValue { key: Some(1), kind: Some("unit real".into()), value: None },
AiaValue { key: None, kind: Some("ustring".into()), value: Some(AiaData::Text(b"a } brace".to_vec())) },
AiaValue { key: None, kind: Some("raw".into()), value: None },
];
let join = AiaStep { name: "sample_join".into(), label: Some("Join".into()), on: Some(1), params: 3, values, declared: Some(3), line: 9 };
assert_eq!(step(0, 0), join);
assert_eq!((step(1, 0).name.as_str(), step(1, 0).label.clone(), step(1, 0).on), ("sample)one", None, Some(0)));
assert_eq!((step(1, 1).label.as_deref(), step(1, 1).on, step(1, 1).line), (Some("Second Step"), None, 39));
@@ -60,6 +65,55 @@ fn recorded_values_are_counted_and_checked() {
assert!(set(&[value("one"), "/value [ 1 zz ]".to_string()]).truncated, "a second value that isn't hexadecimal");
}
/// `actionSet.read` answers with each recorded value's key, type and value: a number, text in
/// parentheses or hexadecimal text that is UTF-8 with its length in bytes, and null for text that
/// isn't UTF-8 and for other values. Fields may come in any order, and a value with the wrong byte
/// count still marks the set truncated.
#[test]
fn recorded_values_come_back_with_their_keys_and_types() {
let mut s = Session::new();
let text = format!(
"/version 3 /action-1 {{ /event-1 {{ /internalName (sample_values) /parameterCount 6 \
/parameter-1 {{ /key 1952807028 /type (ustring) /value {note} }} \
/parameter-2 {{ /value 1 /type (boolean) /key 2003792484 }} \
/parameter-3 {{ /type (ustring) /value [ 2 c328 ] /key 7 }} \
/parameter-4 {{ /key 99999999999999999999 /type (real) /value 4.5 }} \
/parameter-5 {{ /key 3 /type (text) /value (plain) }} \
/parameter-6 {{ }} }} }}",
note = hex("Größe ✓")
);
let r = s.execute("actionSet.read", &json!({ "data": text })).unwrap();
assert_eq!(r["truncated"], false);
assert_eq!(
r["actions"][0]["steps"][0]["values"],
json!([
{"key": 1952807028, "type": "ustring", "value": "Größe ✓", "bytes": 11},
{"key": 2003792484, "type": "boolean", "value": 1},
{"key": 7, "type": "ustring", "value": null, "bytes": 2},
{"key": null, "type": "real", "value": null},
{"key": 3, "type": "text", "value": "plain", "bytes": 5},
{"key": null, "type": null, "value": null},
])
);
let bad = "/version 3 /action-1 { /event-1 { /parameter-1 { /key 1 /type (ustring) /value [ 3 4142 ] } } }";
assert_eq!(s.execute("actionSet.read", &json!({ "data": bad })).unwrap()["truncated"], true);
}
/// At most 100,000 recorded values are kept in a set: the others are still counted, so a step's
/// `values` can be shorter than its `params`.
#[test]
fn recorded_values_past_the_cap_are_counted_but_not_kept() {
let step = format!("/event-1 {{ {} }} ", "/parameter-1 { /key 1 /value 0 } ".repeat(1000));
let action = format!("/action-1 {{ {} }} ", step.repeat(50));
let set = read_aia(format!("/version 3 {}", action.repeat(3)).as_bytes()).unwrap();
assert!(!set.truncated);
let steps = || set.actions.iter().flat_map(|a| &a.steps);
assert_eq!(steps().map(|s| s.params).sum::<usize>(), 150_000);
assert_eq!(steps().map(|s| s.values.len()).sum::<usize>(), 100_000);
assert_eq!(set.actions[2].steps[0].values.len(), 0);
assert_eq!(set.actions[1].steps[49].values[999], AiaValue { key: Some(1), kind: None, value: Some(AiaData::Int(0)) });
}
/// `actionSet.read` takes exactly one of `path`, `data` and `dataBase64`, and text for the text
/// params; any other value is an error.
#[test]
@@ -97,7 +151,7 @@ fn read_command_answers_with_the_set() {
let text = sample().replacen(&format!("/name {}", hex("Prep Sätze")), "", 1);
let r = s.execute("actionSet.read", &json!({ "data": text, "name": "/sets/Mine.aia" })).unwrap();
assert_eq!(r["set"], "Mine");
assert_eq!(r["actions"][1]["steps"][0], json!({"name": "sample)one", "label": null, "on": false, "params": 0, "line": 34}));
assert_eq!(r["actions"][1]["steps"][0], json!({"name": "sample)one", "label": null, "on": false, "params": 0, "values": [], "line": 34}));
assert_eq!(r["actions"][0]["steps"][0]["on"], true);
assert_eq!(r["actions"][0]["steps"][0]["label"], "Join");
let blank = format!("/version 3 /action-1 {{ /event-1 {{ /internalName (x) /localizedName {} }} }}", hex(" "));
+43 -2
View File
@@ -1,6 +1,7 @@
//! An edit of one anchor of a long selected path does not measure the path's segments
//! ([`vectorcraft_geom::path::measured_segments`]) to check that it stays within the canvas, and
//! an edit that leaves the anchor as it was records no undo step.
//! ([`vectorcraft_geom::path::measured_segments`]) to check that it stays within the canvas, its
//! undo step keeps the chunk of anchors it changed rather than a copy of every anchor, and an edit
//! that leaves the anchor as it was records no undo step.
use std::collections::BTreeSet;
use std::sync::Arc;
@@ -74,6 +75,46 @@ fn one_anchor_edit_of_a_long_path_measures_few_segments() {
}
}
/// Most bytes the undo step of one anchor edit may keep, however many anchors the path has: about
/// one chunk of anchors and the node, with room for the chunk tables of 200,000 anchors.
const MOST_STEP_BYTES: usize = 48 * 1024;
#[test]
fn one_anchor_edit_of_a_long_path_keeps_one_chunk_in_its_undo_step() {
for n in [10_000, 200_000] {
let (mut s, id) = long_path(n);
let original = s.doc().unwrap().doc.clone();
let edits = [
("path.moveAnchor", json!({"id": id.0, "anchor": 5, "x": 3, "y": 50})),
("path.setHandle", json!({"id": id.0, "anchor": 5, "which": "out", "x": 4, "y": 40})),
("path.moveAnchors", json!({"dx": 1, "dy": 0})),
("object.nudge", json!({"dx": 1, "dy": 0})),
];
let mut docs = vec![];
for (cmd, p) in &edits {
s.execute(cmd, p).unwrap();
let step = s.doc().unwrap().history.undo.last().unwrap().bytes;
assert!(step <= MOST_STEP_BYTES, "{cmd} on {n} anchors kept {step} bytes in its undo step");
docs.push(s.doc().unwrap().doc.clone());
}
assert_eq!(anchor(&s, id, 5).p, Point::new(5.0, 50.0));
assert_eq!(anchor(&s, id, 5).h_out, Point::new(6.0, 40.0));
assert_eq!(anchor(&s, id, n - 1), original.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[n - 1]);
// Undo gives back each version exactly, and redo the edits, each step as small.
for k in (0..edits.len()).rev() {
s.execute("edit.undo", &json!({})).unwrap();
let expected = if k == 0 { &original } else { &docs[k - 1] };
assert!(s.doc().unwrap().doc == *expected, "undo of {} on {n} anchors", edits[k].0);
let redo = s.doc().unwrap().history.redo.last().unwrap().bytes;
assert!(redo <= MOST_STEP_BYTES, "redo of {} on {n} anchors keeps {redo} bytes", edits[k].0);
}
for (k, doc) in docs.iter().enumerate() {
s.execute("edit.redo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == *doc, "redo of {} on {n} anchors", edits[k].0);
}
}
}
/// A handle past the canvas is measured: the edit stands while the curve stays within the canvas,
/// and is refused once the curve leaves it.
#[test]
+99
View File
@@ -1002,6 +1002,105 @@ fn brush_freehand_refuses_a_brush_or_style_it_cannot_use() {
}
}
/// A `brush.freehand` call outside an interaction draws the path and paints it with the brush in
/// one undo step: one Undo removes the path and gives back the earlier selection, and one Redo
/// brings back the brushed path. Continuing a path with a brush is one step too.
#[test]
fn brush_freehand_direct_call_has_one_undo_step() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
select(&mut s, &[a]);
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"));
s.execute("edit.undo", &json!({})).unwrap();
assert!(*s.doc().unwrap().doc == *before, "one Undo removes the brushed path");
assert_eq!(selected(&s), [a], "Undo gives back the earlier selection");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"), "Redo brings back the brush");
assert_eq!(selected(&s), [id]);
let undo = s.doc().unwrap().history.undo.len();
let p = json!({"points": [[120, 10], [160, 60], [200, 10]], "extend": {"id": id.0, "end": "end"}, "brush": "Dots"});
assert_eq!(s.execute("brush.freehand", &p).unwrap()["id"], json!(id.0));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "continuing is one undo step");
assert_eq!(brush_of(&s, id).as_deref(), Some("Dots"));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"), "one Undo takes back the stroke and its brush");
let undo = s.doc().unwrap().history.undo.len();
s.execute("brush.freehand", &json!({"points": [[10, 100], [60, 140], [120, 100]], "style": "pencil", "brush": "Charcoal"})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Paintbrush"), "a stroke with a brush is a Paintbrush step");
}
/// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one
/// and a new filled pencil path while the stroke is None) instead of reporting it painted: the
/// document, the selection and the undo history stay as they were. Without a brush the path is
/// drawn as `path.freehand` draws it.
#[test]
fn brush_freehand_refuses_a_brush_on_a_path_without_a_stroke() {
let mut s = session();
s.execute("select.none", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
let drawn = json!([[10, 10], [60, 20], [90, 80], [20, 90]]);
let p = NodeId(s.execute("path.freehand", &json!({"points": drawn, "fill": true})).unwrap()["id"].as_u64().unwrap());
assert!(node(&s, p).appearance.stroke_paint().is_none(), "the path has no stroke");
// The redraw below replaces a section of the path rather than drawing a new one.
let redraw = json!({"points": [[10, 10], [40, 30], [60, 20]], "redraw": {"id": p.0}});
assert_eq!(s.execute("path.freehand", &redraw).unwrap()["id"], json!(p.0));
s.execute("edit.undo", &json!({})).unwrap();
select(&mut s, &[p]);
let extend = json!({"id": p.0, "end": "end"});
for (what, mut params) in [
("continued", json!({"points": [[20, 90], [0, 120], [-10, 150]], "extend": extend})),
("continued by one point", json!({"points": [[20, 90]], "extend": extend})),
("redrawn", redraw.clone()),
("new filled pencil", json!({"points": [[100, 100], [150, 120], [180, 180]], "style": "pencil", "fill": true})),
] {
params["brush"] = json!("Charcoal");
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let e = s.execute("brush.freehand", &params).expect_err(&format!("{what}: refused"));
assert_eq!(e.to_string(), "invalid parameters for `brush.freehand`: cannot apply brush `Charcoal`: path has no stroke", "{what}");
assert!(*s.doc().unwrap().doc == *before, "{what}: the document stays");
assert_eq!(selected(&s), [p], "{what}: the selection stays");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{what}: no undo step");
}
let r = s.execute("brush.freehand", &json!({"points": [[20, 90], [0, 120], [-10, 150]], "extend": extend, "brush": null})).unwrap();
assert_eq!(r["id"], json!(p.0));
assert_eq!(brush_of(&s, p), None, "without a brush the path is continued as it is");
}
/// `brush.freehand` takes the keys of `path.freehand` and `brush`, and refuses any other key with
/// the nearest key it takes, before it draws.
#[test]
fn brush_freehand_refuses_unknown_keys() {
let spec = crate::cmd::find_command("brush.freehand").unwrap();
let mut keys = crate::cmd::params::accepted_keys(spec.params).expect("the description names every key");
keys.sort_unstable();
assert_eq!(keys, ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "points", "redraw", "style"]);
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
select(&mut s, &[a]);
let points = json!([[10, 10], [60, 40], [120, 10]]);
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let e = s.execute("brush.freehand", &json!({"points": points, "brsuh": "Charcoal"})).expect_err("a misspelled key is refused");
assert!(e.to_string().contains("unknown parameter `brsuh`; did you mean `brush`?"), "{e}");
assert!(*s.doc().unwrap().doc == *before, "the document stays");
assert_eq!(selected(&s), [a], "the selection stays");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
let every = json!({
"points": points, "fidelity": 2.0, "fit": true, "closed": false, "style": "brush", "fill": false, "keepSelected": true,
"extend": null, "connect": null, "redraw": null, "brush": "Charcoal"
});
let id = NodeId(s.execute("brush.freehand", &every).unwrap()["id"].as_u64().unwrap());
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"));
}
/// The Paintbrush skips a brush deleted after it was chosen: a deleted tool brush gives way to
/// the document's current brush, and with neither the stroke is drawn without a brush.
#[test]
+155 -5
View File
@@ -3576,9 +3576,9 @@ fn live_paint_bucket_scopes_follow_the_stroke_an_edge_draws() {
assert_eq!(r["count"], json!(clear.len() + top.len() + hidden.len()));
}
/// `livePaint.strokeEdge` paints an edge's topmost stroke that is shown, so the edge then draws
/// with the paint; an edge whose strokes are all hidden takes a new stroke above them. Painting
/// again changes nothing.
/// `livePaint.strokeEdge` leaves an edge one stroke, shown, with the paint, so the edge then draws
/// with it, whether its topmost shown stroke sat under a hidden one or every stroke was hidden.
/// Painting again changes nothing.
#[test]
fn live_paint_stroke_edge_paints_the_shown_stroke() {
let mut s = session();
@@ -3613,8 +3613,107 @@ fn live_paint_stroke_edge_paints_the_shown_stroke() {
paint(&mut s, at);
assert_eq!(history_state(&s).0, depth, "painting {id} again");
}
assert_eq!(node(&s, m).appearance.items.len(), 2, "the hidden stroke stays as it was");
assert_eq!(node(&s, l).appearance.items.len(), 2, "a new stroke above the hidden one");
assert_eq!(node(&s, m).appearance.items.len(), 1, "one stroke in place of the hidden and the shown one");
assert_eq!(node(&s, l).appearance.items.len(), 1, "one shown stroke in place of the hidden one");
}
/// A face with two fills that draw, under a hidden top fill: the Bucket replaces every fill with
/// one shown, fully opaque fill of the paint, keeps the face's strokes, opacity and their order,
/// and a click with the paint the face then has records nothing. A fill of none leaves no fill
/// that draws. The route that makes the objects into a group first paints the same way.
#[test]
fn live_paint_bucket_replaces_every_fill_row() {
use vectorcraft_doc::appearance::{FillLayer, StrokeLayer};
let mut s = session();
let g = live_squares(&mut s, &[0.0]);
let [f] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let stroke = StrokeLayer::new(blue.clone(), 3.0);
s.edit("t", |d, _| {
let n = d.node_mut(f).unwrap();
n.opacity = 0.5;
let mut half = FillLayer::new(blue.clone());
half.opacity = 0.5;
let mut hidden = FillLayer::new(green.clone());
hidden.visible = false;
n.appearance.items = vec![
AppearanceItem::Fill(FillLayer::new(red.clone())),
AppearanceItem::Stroke(stroke.clone()),
AppearanceItem::Fill(half),
AppearanceItem::Fill(hidden),
];
Ok(())
})
.unwrap();
let depth = history_state(&s).0;
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00"})).unwrap();
assert_eq!(history_state(&s).0, depth + 1, "a hidden top fill with the paint does not stop the fill");
let n = node(&s, f);
assert_eq!(n.appearance.items, vec![AppearanceItem::Stroke(stroke.clone()), AppearanceItem::Fill(FillLayer::new(green.clone()))]);
assert_eq!(n.opacity, 0.5, "the face keeps its own opacity");
s.recent_colors.clear();
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00"})).unwrap();
assert_eq!((history_state(&s).0, s.recent_colors.len()), (depth + 1, 0), "painting again records nothing");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "none": true})).unwrap();
let n = node(&s, f);
assert!(!n.appearance.has_drawn_fill(), "no fill draws after a fill of none");
assert_eq!(n.appearance.items, vec![AppearanceItem::Stroke(stroke), AppearanceItem::Fill(FillLayer::new(Paint::None))]);
// Objects made into a Live Paint group by the click: each object's two fills become one.
let mut s = session();
let id = rect(&mut s, 0.0, 0.0, 50.0, 50.0);
s.edit("t", |d, _| {
d.node_mut(id).unwrap().appearance.items.insert(0, AppearanceItem::Fill(FillLayer::new(red.clone())));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let r = s.execute("livePaint.fill", &json!({"point": [25, 25], "color": "#00ff00"})).unwrap();
let face = NodeId(r["face"].as_u64().unwrap());
let fills: Vec<Paint> = node(&s, face).appearance.items.iter().filter(|i| i.is_fill()).map(|i| i.paint().clone()).collect();
assert_eq!(fills, vec![green]);
}
/// An edge with two strokes that draw: `livePaint.strokeEdge` replaces them with one stroke of the
/// paint and width, keeping the topmost one's dashes; a stroke of none leaves no stroke that
/// draws, and `livePaint.info` then lists that one row.
#[test]
fn live_paint_stroke_edge_replaces_every_stroke_row() {
use vectorcraft_doc::appearance::{Dash, StrokeLayer};
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0]);
let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0));
let [m] = middle[..] else { panic!("one middle edge") };
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let dash = Dash { pattern: vec![4.0, 2.0], offset: 0.0, align_corners: false };
s.edit("t", |d, _| {
let mut top = StrokeLayer::new(green.clone(), 2.0);
top.opacity = 0.5;
top.dash = Some(dash.clone());
d.node_mut(m).unwrap().appearance.items = vec![AppearanceItem::Stroke(StrokeLayer::new(red.clone(), 6.0)), AppearanceItem::Stroke(top)];
Ok(())
})
.unwrap();
let depth = history_state(&s).0;
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [50, 25], "color": "#00ff00", "width": 2})).unwrap();
assert_eq!(history_state(&s).0, depth + 1, "a half-transparent top stroke with the paint does not stop the stroke");
let mut want = StrokeLayer::new(green.clone(), 2.0);
want.dash = Some(dash);
assert_eq!(node(&s, m).appearance.items, vec![AppearanceItem::Stroke(want)]);
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [50, 25], "color": "#00ff00", "width": 2})).unwrap();
assert_eq!(history_state(&s).0, depth + 1, "painting again records nothing");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [50, 25], "none": true, "width": 2})).unwrap();
assert!(!node(&s, m).appearance.has_drawn_stroke(), "no stroke draws after a stroke of none");
let info = s.execute("livePaint.info", &json!({"group": g.0})).unwrap();
let edge = info["edges"].as_array().unwrap().iter().find(|e| e["id"] == json!(m.0)).unwrap().clone();
let rows = edge["appearance"].as_array().unwrap();
assert_eq!(rows.len(), 1);
assert_eq!((&rows[0]["kind"], &rows[0]["drawn"], &edge["stroke"]), (&json!("stroke"), &json!(false), &json!(Paint::None.label())));
}
/// With Cmd held, the Live Paint Bucket's presses go to the selection tool Cmd lends, and the
@@ -5589,6 +5688,57 @@ fn a_trace_run_applies_only_in_its_own_document() {
}
}
/// A trace prepared before File › Revert doesn't apply after it, even when the document keeps its
/// uid and the restored image, object and settings are the same: both trace commands drop the
/// trace handed in and trace the restored image again, as one undo step. Reverting another
/// document, or a revert that fails, leaves the run current, and a trace prepared after the revert
/// applies as usual.
#[test]
fn a_trace_run_prepared_before_a_revert_does_not_apply_after_it() {
let p = json!({"params": {"ignoreWhite": true}});
for command in ["imageTrace.make", "imageTrace.makeAndExpand"] {
let mut direct = session();
image_doc(&mut direct);
let want = direct.execute(command, &p).unwrap();
let mut s = session();
let img = image_doc(&mut s);
let a = s.active_index().unwrap();
let copy = (*s.doc().unwrap().doc).clone();
let run = cmd::TraceRun::prepare(&s, command, &p).unwrap();
let traced = run.run(&|_, _| true).unwrap();
let b = s.add_document(copy.clone(), None);
assert!(s.replace_document(b, copy.clone()));
assert!(s.set_active(a));
assert!(run.current(&s) && !run.reverted(&s), "{command}: another document reverted");
assert!(!s.replace_document(s.documents().len(), copy.clone()));
assert!(run.current(&s) && !run.reverted(&s), "{command}: a revert that failed");
let (uid, reverts) = (s.doc().unwrap().uid, s.doc().unwrap().reverts);
assert!(s.replace_document(a, copy));
assert_eq!(s.doc().unwrap().uid, uid, "{command}: the tab keeps its uid");
assert_eq!(s.doc().unwrap().reverts, reverts + 1, "{command}");
assert!(!run.current(&s), "{command}: reverted");
assert!(run.reverted(&s), "{command}");
traced.hand_in(&mut s);
let traces = cmd::TraceRun::traces_on_this_thread();
let got = s.execute(run.command(), run.params()).unwrap();
assert_eq!(cmd::TraceRun::traces_on_this_thread(), traces + 1, "{command}: traced again");
assert!(s.trace_hand_off.is_none(), "{command}: dropped");
assert_eq!(got, want, "{command}");
let g = NodeId(got["id"].as_u64().unwrap());
assert_eq!(node(&s, g), node(&direct, g), "{command}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(matches!(node(&s, img).kind, NodeKind::Image(_)), "{command}: one undo step");
// A trace prepared after the revert is handed in and applied without tracing again.
let after = cmd::TraceRun::prepare(&s, command, run.params()).unwrap();
let traced = after.run(&|_, _| true).unwrap();
assert!(after.current(&s) && !after.reverted(&s), "{command}: prepared after the revert");
traced.hand_in(&mut s);
let traces = cmd::TraceRun::traces_on_this_thread();
s.execute(after.command(), after.params()).unwrap();
assert_eq!(cmd::TraceRun::traces_on_this_thread(), traces, "{command}: the trace handed in applied");
}
}
/// A plug-in run that calls Image Trace and then fails leaves a trace handed in for the command in
/// place, as it leaves the document.
#[test]
+720 -1
View File
@@ -531,7 +531,726 @@ fn a_pasted_graph_brings_and_follows_its_label_styles_and_paints() {
new_doc(&mut s);
let v = s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap();
assert!(doc(&s).char_styles.is_empty() && doc(&s).para_styles.is_empty(), "{v}");
assert_eq!(graph_links(&s, ids_of(&v)[0]), (brand, None, None));
// The value labels' red characters stay behind too; the series fill and the legend rows keep Brand.
assert_eq!(graph_links(&s, ids_of(&v)[0]), (vec!["Brand".to_string(); 2], None, None));
}
/// Each label of graph `id` (the text of its Axes and Legend groups) with its size and its first paragraph's format.
fn graph_label_looks(s: &Session, id: NodeId) -> Vec<(String, f64, vectorcraft_doc::ParaStyle)> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind {
out.push((t.plain_text(), t.first_style().size, t.para_at(0).clone()));
}
});
out
}
/// Paste without Formatting sets a pasted graph's labels in a new graph's label size and paragraph attributes, and the
/// graph keeps them when it is drawn again: the character and paragraph formats its labels keep stay behind with their
/// text formatting.
#[test]
fn a_graph_pasted_without_formatting_keeps_plain_labels_when_drawn_again() {
let mut s = session();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
let g = id_of(&s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 120, "height": 80, "csv": csv})).unwrap());
let fresh = graph_label_looks(&s, g);
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"size": 14})).unwrap();
s.execute("text.setFormat", &json!({"spaceAfter": 6})).unwrap();
assert!(graph_label_looks(&s, g).iter().all(|(_, size, para)| *size == 14.0 && para.space_after == 6.0));
// The labels as drawn are also set in a character style.
s.execute("charStyle.new", &json!({"name": "Emphasis", "attrs": {"size": 14.0}})).unwrap();
let mut labels = vec![];
node(&s, g).walk(&mut |n| {
if matches!(n.kind, NodeKind::Text(_)) {
labels.push(n.id);
}
});
for id in labels {
if let Some(NodeKind::Text(t)) = doc_mut(&mut s).node_mut(id).map(|n| &mut n.kind) {
t.runs.iter_mut().for_each(|r| r.style.style_name = Some("Emphasis".into()));
}
}
copy(&mut s, &[g]);
assert_eq!(s.clipboard.char_styles.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["Emphasis"]);
// Where a redraw of the copied graph puts its plot.
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
let plot = node(&s, g).extras().graph.as_deref().unwrap().rect;
new_doc(&mut s);
let steps = s.doc().unwrap().history.undo.len();
let v = s.execute("edit.pasteWithoutFormatting", &json!({"dx": 10, "dy": 20})).unwrap();
let p = ids_of(&v)[0];
assert!(doc(&s).char_styles.is_empty(), "the labels' character style stays behind: {v}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Paste without Formatting"));
let l = node(&s, p).extras().graph.as_deref().unwrap().label_styles.clone();
assert_eq!((l.values, l.categories, l.legend), (None, None, None));
assert_eq!((l.values_para, l.categories_para, l.legend_para), (None, None, None));
let pasted = graph_label_looks(&s, p);
assert_eq!(pasted, fresh, "the labels are set as a new graph's are");
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(graph_label_looks(&s, p), pasted, "and stay so when the graph is drawn again");
let r = node(&s, p).extras().graph.as_deref().unwrap().rect;
let off = [r.x0 - plot.x0 - 10.0, r.y0 - plot.y0 - 20.0, r.x1 - plot.x1 - 10.0, r.y1 - plot.y1 - 20.0];
assert!(off.iter().all(|d| d.abs() < 1e-6), "the plot moves by the offset and keeps its size: {plot:?} → {r:?}");
s.execute("graph.setType", &json!({"id": p.0, "type": "column"})).unwrap();
assert_eq!(graph_label_looks(&s, p), pasted, "a change of type draws them the same way");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(doc(&s).node(p).is_none(), "one undo takes the paste back");
}
/// Paste without Formatting leaves the rest of a pasted graph's art as it was copied: a column painted by hand keeps its
/// paint, and nothing is drawn again.
#[test]
fn a_graph_pasted_without_formatting_keeps_its_art() {
let mut s = session();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
let g = id_of(&s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 120, "height": 80, "csv": csv})).unwrap());
let red = Paint::solid(hex("ff0000"));
let mut column = None;
node(&s, g).walk(&mut |n| {
if column.is_none() && matches!(n.kind, NodeKind::Path { .. }) && n.appearance.fill_paint() != Paint::None {
column = Some(n.id);
}
});
let column = column.unwrap();
let n = doc_mut(&mut s).node_mut(column).unwrap();
n.appearance = vectorcraft_doc::Appearance::basic(red.clone(), Paint::None, 0.0).into();
/// Every object of graph `id` that is not type: its kind's name, its fill and its bounds.
fn art(s: &Session, id: NodeId) -> Vec<(String, Paint, Option<Rect>)> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if !matches!(n.kind, NodeKind::Text(_)) {
out.push((format!("{:?}", std::mem::discriminant(&n.kind)), n.appearance.fill_paint(), n.geometric_bounds()));
}
});
out
}
let copied = art(&s, g);
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({"dx": 15, "dy": 25})).unwrap())[0];
let pasted = art(&s, p);
let dx = pasted[0].2.unwrap().x0 - copied[0].2.unwrap().x0;
let dy = pasted[0].2.unwrap().y0 - copied[0].2.unwrap().y0;
let moved: Vec<_> = copied.into_iter().map(|(k, f, b)| (k, f, b.map(|b| b + vectorcraft_geom::Vec2::new(dx, dy)))).collect();
assert_eq!(pasted.len(), moved.len());
for (a, b) in pasted.iter().zip(&moved) {
assert_eq!((&a.0, &a.1), (&b.0, &b.1));
let (a, b) = (a.2.unwrap(), b.2.unwrap());
assert!((a.x0 - b.x0).abs() + (a.y0 - b.y0).abs() + (a.x1 - b.x1).abs() + (a.y1 - b.y1).abs() < 1e-6, "{a:?} {b:?}");
}
assert!(pasted.iter().any(|(_, f, _)| *f == red), "the column keeps the paint it was given");
}
/// The labels of a scaled graph pasted without formatting are set at a new graph's label size, unscaled, as a redraw
/// sets them.
#[test]
fn a_scaled_graph_pasted_without_formatting_gets_unscaled_labels() {
let mut s = session();
let csv = ",2024\nQ1,3\nQ2,5";
let g = id_of(&s.execute("graph.create", &json!({"type": "column", "x": 50, "y": 50, "width": 120, "height": 80, "csv": csv})).unwrap());
let fresh = graph_label_looks(&s, g)[0].1;
sel(&mut s, &[g]);
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
/// Each label's size as drawn: its character size times the scale of its transform.
fn drawn_sizes(s: &Session, id: NodeId) -> Vec<f64> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind {
out.push(t.first_style().size * t.xf.determinant().abs().sqrt());
}
});
out
}
assert!(drawn_sizes(&s, g).iter().all(|z| (z - fresh * 2.0).abs() < 1e-6), "{:?}", drawn_sizes(&s, g));
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert!(drawn_sizes(&s, p).iter().all(|z| (z - fresh).abs() < 1e-6), "{:?}", drawn_sizes(&s, p));
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert!(drawn_sizes(&s, p).iter().all(|z| (z - fresh).abs() < 1e-6), "{:?}", drawn_sizes(&s, p));
// A rotated graph's labels keep their rotation, so they stay turned with the rest of its art.
/// Each label's rotation in degrees: the angle of its transform's x axis.
fn angles(s: &Session, id: NodeId) -> Vec<f64> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind {
let [a, b, ..] = t.xf.as_coeffs();
out.push(b.atan2(a).to_degrees());
}
});
out
}
let r = id_of(&s.execute("graph.create", &json!({"type": "column", "x": 300, "y": 50, "width": 120, "height": 80, "csv": csv})).unwrap());
sel(&mut s, &[r]);
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let turned = angles(&s, r);
assert!(turned.iter().all(|a| (a.abs() - 30.0).abs() < 1e-6), "{turned:?}");
copy(&mut s, &[r]);
new_doc(&mut s);
let q = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(angles(&s, q).len(), turned.len());
assert!(angles(&s, q).iter().zip(&turned).all(|(a, b)| (a - b).abs() < 1e-6), "{:?} against {turned:?}", angles(&s, q));
assert!(drawn_sizes(&s, q).iter().all(|z| (z - fresh).abs() < 1e-6), "{:?}", drawn_sizes(&s, q));
}
/// A pie's legend labels in their wedges keep a redraw's contrast when pasted without formatting: white on a dark
/// wedge, black on a light one.
#[test]
fn pie_labels_in_wedges_pasted_without_formatting_stay_readable() {
let mut s = session();
let csv = ",North,South\nP,1,1";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
/// Each text of graph `id` with its characters' fill.
fn fills(s: &Session, id: NodeId) -> Vec<(String, Paint)> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind {
out.push((t.plain_text(), t.first_style().fill.clone()));
}
});
out
}
let drawn = fills(&s, g);
assert!(drawn.contains(&("North".into(), Paint::solid(Color::WHITE))), "the first wedge is black: {drawn:?}");
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"size": 14})).unwrap();
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(fills(&s, p), drawn);
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(fills(&s, p), drawn);
}
/// A pie whose legend labels were given a black fill of their own loses that mark when pasted without formatting, so a
/// later change to a legend label's size does not bring the black fill back on the dark wedge.
#[test]
fn a_legend_fill_of_its_own_stays_behind_when_pasted_without_formatting() {
let mut s = session();
let csv = ",North,South\nP,1,1";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
/// The legend label of graph `id` that says `name`.
fn label(s: &Session, id: NodeId, name: &str) -> (NodeId, Paint) {
let mut out = None;
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == name
{
out = Some((n.id, t.first_style().fill.clone()));
}
});
out.unwrap()
}
let (north, fill) = label(&s, g, "North");
assert_eq!(fill, Paint::solid(Color::WHITE), "white on the black wedge");
s.execute("text.setStyle", &json!({"ids": [north.0], "fill": "#000000"})).unwrap();
assert!(node(&s, g).extras().graph.as_deref().unwrap().label_styles.legend_fill_set);
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert!(!node(&s, p).extras().graph.as_deref().unwrap().label_styles.legend_fill_set);
assert_eq!(label(&s, p, "North").1, Paint::solid(Color::WHITE), "pasted as a redraw sets it");
let (north, _) = label(&s, p, "North");
s.execute("text.setStyle", &json!({"ids": [north.0], "size": 11})).unwrap();
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(label(&s, p, "North").1, Paint::solid(Color::WHITE), "still white when the pie is drawn again");
}
/// A two-line legend label in a narrow dark wedge, whose text sits off the wedge's middle line, stays white when its graph
/// is pasted without formatting.
#[test]
fn a_legend_label_in_a_narrow_wedge_pasted_without_formatting_stays_readable() {
let mut s = session();
// The first wedge fills a quarter from the top; the dark fourth series ("Narrow", series 3) follows it for 0.2 degrees,
// narrower than the label's distance from the wedge's middle line.
let csv = ",A,B,C,Narrow|,E\nP,9,0,0,0.02,26.98";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
fn narrow(s: &Session, id: NodeId) -> Paint {
let mut out = None;
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text().starts_with("Narrow")
{
out = Some(t.first_style().fill.clone());
}
});
out.unwrap()
}
assert_eq!(narrow(&s, g), Paint::solid(Color::WHITE));
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(narrow(&s, p), Paint::solid(Color::WHITE));
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(narrow(&s, p), Paint::solid(Color::WHITE));
// A standard legend beside the pie stays black.
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "standard"})).unwrap();
assert_eq!(narrow(&s, g), Paint::solid(Color::BLACK));
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(narrow(&s, p), Paint::solid(Color::BLACK));
// Two series with one name: each label keeps its own wedge's contrast, though the second label lies nearer the
// middle of the first (dark) wedge's bounds than of its own.
fn xs(s: &Session, id: NodeId) -> Vec<Paint> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == "X"
{
out.push(t.first_style().fill.clone());
}
});
out
}
let csv = ",X,X,Y\nP,8,1,89";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 0, "y": 0, "width": 2000, "height": 2000, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
let drawn = xs(&s, g);
assert_eq!(drawn, vec![Paint::solid(Color::WHITE), Paint::solid(Color::BLACK)]);
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(xs(&s, p), drawn);
}
/// Two-line legend labels of a light and a dark series with one name keep a redraw's colors when pasted without
/// formatting, though the narrow light wedge's label reaches into the dark wedge after it.
#[test]
fn shared_name_labels_in_a_narrow_wedge_pasted_without_formatting_keep_their_colors() {
let mut s = session();
let csv = ",A,B,Q|,Q|\nP,9,0,0.02,26.98";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
fn qs(s: &Session, id: NodeId) -> Vec<Paint> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text().starts_with('Q')
{
out.push(t.first_style().fill.clone());
}
});
out
}
let drawn = qs(&s, g);
assert_eq!(drawn.len(), 2);
assert_ne!(drawn[0], drawn[1], "one light and one dark series");
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(qs(&s, p), drawn);
// Names that hold a line break of their own (a redraw sets them on lines centered on the point, as it sets `|`) keep
// them too.
for name in ["Q\nQ", "Q\nQ\nQ\nQ\nQ\nQ\nQ\nQ\nQ"] {
new_doc(&mut s);
let named = json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "series": ["A", "B", name, name], "categories": ["P"], "rows": [[9, 0, 0.02, 26.98]]});
let g = id_of(&s.execute("graph.create", &named).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
let broken = qs(&s, g);
assert_eq!(broken.len(), 2);
assert_ne!(broken[0], broken[1], "names with line breaks");
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(qs(&s, p), broken, "names with {} line breaks", name.matches('\n').count());
}
// So do labels whose names show the same text, one with a line break of its own and one with `|`.
new_doc(&mut s);
let named = json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "series": ["Q\n", "B", "Q|", "Q|"], "categories": ["P"], "rows": [[9, 0, 0.02, 26.98]]});
let g = id_of(&s.execute("graph.create", &named).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
// The fills of the Q labels by their place from left to right and top to bottom.
fn placed(s: &Session, id: NodeId) -> Vec<Paint> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text().starts_with('Q')
{
let o = t.xf.translation();
out.push((o.x, o.y, t.first_style().fill.clone()));
}
});
out.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)));
out.into_iter().map(|(_, _, f)| f).collect()
}
let alike = placed(&s, g);
assert_eq!(alike.len(), 3);
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(placed(&s, p), alike, "names that show the same text");
// The narrow light wedge's label (the second) brought to the front keeps them too.
new_doc(&mut s);
let g = id_of(&s.execute("graph.create", &named).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
let legend = node(&s, g).children().unwrap().iter().find(|c| c.name.as_deref() == Some("Legend")).unwrap().clone();
let labels = legend.children().unwrap();
assert_eq!(labels.len(), 3);
s.execute("object.arrange.bringToFront", &json!({"ids": [labels[1].id.0]})).unwrap();
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(placed(&s, p), alike, "names that show the same text, labels reordered");
// Labels given another size, which leaves them where they were drawn, keep them too.
new_doc(&mut s);
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"size": 14})).unwrap();
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(qs(&s, p), drawn, "resized labels");
// Large labels of four series of one name, drawn again at that size, keep the colors that drawing gave them.
new_doc(&mut s);
let four = ",Q|,Q|,Q|,Q|\nP,1,1,1,1";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": four})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"size": 200})).unwrap();
s.execute("graph.setData", &json!({"id": g.0, "csv": four})).unwrap();
let large = placed(&s, g);
assert_eq!(large.len(), 4);
assert!(large.contains(&Paint::solid(Color::WHITE)) && large.contains(&Paint::solid(Color::BLACK)), "{large:?}");
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(placed(&s, p), large, "large labels drawn again");
// A scaled and rotated pie keeps them too.
new_doc(&mut s);
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
sel(&mut s, &[g]);
s.execute("object.scale", &json!({"sx": 400, "sy": 400})).unwrap();
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let drawn = qs(&s, g);
assert_ne!(drawn[0], drawn[1]);
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(qs(&s, p), drawn);
}
/// The legend labels of a pie that kept a fill of their own (red, or black on every wedge), scaled, with two series of
/// one name, are pasted without formatting in the colors a redraw gives them.
#[test]
fn recolored_wedge_labels_pasted_without_formatting_match_a_redraw() {
for fill in ["#ff0000", "#000000"] {
recolored_wedge_labels_match_a_redraw(fill);
}
}
fn recolored_wedge_labels_match_a_redraw(fill: &str) {
let mut s = session();
let csv = ",A,B,Q|,Q|\nP,9,0,0.02,26.98";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"fill": fill})).unwrap();
s.execute("object.scale", &json!({"sx": 400, "sy": 400})).unwrap();
fn legend(s: &Session, id: NodeId) -> Vec<(String, Paint)> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& ["A", "Q"].iter().any(|p| t.plain_text().starts_with(p))
{
out.push((t.plain_text(), t.first_style().fill.clone()));
}
});
out
}
assert!(legend(&s, g).iter().all(|(_, f)| *f == Paint::solid(hex(fill))), "{fill}: {:?}", legend(&s, g));
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
let pasted = legend(&s, p);
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
let redrawn = legend(&s, p);
assert_eq!(pasted, redrawn, "{fill}");
assert!(
redrawn.iter().any(|(_, f)| *f == Paint::solid(Color::WHITE)) && redrawn.iter().any(|(_, f)| *f == Paint::solid(Color::BLACK)),
"{fill}: {redrawn:?}"
);
}
/// A wedge whose fill was changed after its label was drawn gives the label, pasted without formatting, the color a
/// redraw gives it.
#[test]
fn a_repainted_wedge_sets_its_label_color_when_pasted_without_formatting() {
let mut s = session();
let csv = ",North,South\nP,1,1";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
fn labels(s: &Session, id: NodeId) -> Vec<(String, Paint)> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& ["North", "South"].contains(&t.plain_text().as_str())
{
out.push((t.plain_text(), t.first_style().fill.clone()));
}
});
out
}
// Each wedge takes the other's contrast: the dark one (its label white) white, the light one black.
let drawn = labels(&s, g);
let white = |name: &str| drawn.iter().any(|(t, f)| t == name && *f == Paint::solid(Color::WHITE));
let mut wedges = vec![];
for c in node(&s, g).children().unwrap().iter() {
let Some(series) = c.extras().series_index else { continue };
let dark = white(["North", "South"][series as usize]);
c.walk(&mut |m| {
if let NodeKind::Path { .. } = m.kind {
wedges.push((m.id, dark));
}
});
}
assert!(wedges.iter().any(|w| w.1) && wedges.iter().any(|w| !w.1), "{drawn:?}");
for (id, dark) in &wedges {
s.execute("paint.setFill", &json!({"ids": [id.0], "color": if *dark { "#ffffff" } else { "#000000" }})).unwrap();
}
let before = labels(&s, g);
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
let pasted = labels(&s, p);
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(pasted, labels(&s, p), "copied as {before:?}");
}
/// When one pie's wedge of a series is repainted and another pie's wedge of that series is not, each pasted legend label
/// takes the contrast of the wedge it is in.
#[test]
fn wedges_of_one_series_painted_apart_keep_their_label_colors_when_pasted_without_formatting() {
let mut s = session();
fn north(s: &Session, id: NodeId) -> Vec<Paint> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == "North"
{
out.push(t.first_style().fill.clone());
}
});
out
}
// Two pies side by side, and two stacked pies of one series (a disk on a larger one, and on one nearly its size).
for (csv, position) in [(",North,South\nP,1,1\nQ,1,1", "even"), (",North\nP,1\nQ,3", "stacked"), (",North\nP,1000\nQ,999", "stacked")] {
// The second time, the repainted wedge is brought to the front of its series first.
let mut pasted = vec![];
for reorder in [false, true] {
pasted.push(paste_painted_apart(&mut s, csv, position, reorder, north));
}
assert_eq!(pasted[0], pasted[1], "{csv}");
}
// A series name of nine lines, from line breaks a quoted CSV cell keeps, on two stacked pies: each label is centered
// on its own ring, as a redraw centers it.
fn tall(s: &Session, id: NodeId) -> Vec<Paint> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == ["N"; 9].join("\n")
{
out.push(t.first_style().fill.clone());
}
});
out
}
let csv = format!(",\"{}\"\nP,1\nQ,3", ["N"; 9].join("\n"));
paste_painted_apart(&mut s, &csv, "stacked", false, tall);
}
/// Paste without Formatting a pie graph made from `csv` with pies at `position` and Legends in Wedges, after its first
/// wedge of the first series takes the other contrast and, with `reorder`, comes to the front of its series. Returns
/// what `north` reads from the pasted graph, after checking the two values differ.
fn paste_painted_apart(s: &mut Session, csv: &str, position: &str, reorder: bool, north: fn(&Session, NodeId) -> Vec<Paint>) -> Vec<Paint> {
new_doc(s);
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 400, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges", "piePosition": position})).unwrap();
let drawn = north(s, g);
assert_eq!(drawn.len(), 2);
assert_eq!(drawn[0], drawn[1]);
// Repaint the first North wedge with the contrast its label shows, so it takes the other contrast.
let mut first = None;
for c in node(s, g).children().unwrap().iter() {
if c.extras().series_index == Some(0) && first.is_none() {
c.walk(&mut |m| {
if first.is_none() && matches!(m.kind, NodeKind::Path { .. }) {
first = Some(m.id);
}
});
}
}
let first = first.unwrap();
let color = if drawn[0] == Paint::solid(Color::WHITE) { "#ffffff" } else { "#000000" };
s.execute("paint.setFill", &json!({"ids": [first.0], "color": color})).unwrap();
if reorder {
s.execute("object.arrange.bringToFront", &json!({"ids": [first.0]})).unwrap();
}
copy(s, &[g]);
new_doc(s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
let labels = north(s, p);
assert_ne!(labels[0], labels[1], "drawn as {drawn:?}, {position}, reorder {reorder}");
labels
}
/// Legend labels of series that share a name, brought into another order, each keep the contrast of the wedge they are
/// in when the pie is pasted without formatting.
#[test]
fn reordered_shared_name_labels_keep_their_colors_when_pasted_without_formatting() {
let mut s = session();
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": ",X,X\nP,1,1"})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
// Each label's fill, by its place from left to right and top to bottom.
fn labels(s: &Session, id: NodeId) -> (Vec<NodeId>, Vec<Paint>) {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == "X"
{
let o = t.xf.translation();
out.push((o.x, o.y, n.id, t.first_style().fill.clone()));
}
});
out.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)));
out.into_iter().map(|(_, _, id, f)| (id, f)).unzip()
}
let (ids, drawn) = labels(&s, g);
assert_eq!(drawn.len(), 2);
assert_ne!(drawn[0], drawn[1]);
let first = node(&s, g).children().unwrap().iter().find(|c| c.name.as_deref() == Some("Legend")).unwrap().children().unwrap()[0].id;
assert!(ids.contains(&first));
s.execute("object.arrange.bringToFront", &json!({"ids": [first.0]})).unwrap();
copy(&mut s, &[g]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
assert_eq!(labels(&s, p).1, drawn);
}
/// A wedge's hidden fill does not set its legend label's color: the fill it shows does.
#[test]
fn a_hidden_wedge_fill_does_not_color_its_label() {
let mut s = session();
let csv = ",North,South\nP,1,1";
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
let mut n = node(&s, g).clone();
// A hidden black fill above the light South wedge's fill.
for c in n.children_mut().unwrap().iter_mut().filter(|c| c.extras().series_index == Some(1)) {
for w in std::sync::Arc::make_mut(c).children_mut().unwrap().iter_mut() {
let w = std::sync::Arc::make_mut(w);
if let Some(vectorcraft_doc::AppearanceItem::Fill(f)) = w.appearance.items.iter().find(|it| it.is_fill()).cloned() {
let hidden = vectorcraft_doc::FillLayer { paint: Paint::solid(Color::BLACK), visible: false, ..f };
w.appearance.items.push(vectorcraft_doc::AppearanceItem::Fill(hidden));
}
}
}
crate::cmd::graph::plain_labels(&mut n, &|_| {});
let mut south = None;
n.walk(&mut |m| {
if let NodeKind::Text(t) = &m.kind
&& t.plain_text() == "South"
{
south = Some(t.first_style().fill.clone());
}
});
assert_eq!(south, Some(Paint::solid(Color::BLACK)));
}
/// A graph inside a group, and a graph inside a graph, get plain labels too.
#[test]
fn graphs_in_groups_pasted_without_formatting_get_plain_labels() {
let mut s = session();
let csv = ",2024\nQ1,3\nQ2,5";
let g = id_of(&s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 120, "height": 80, "csv": csv})).unwrap());
let fresh = graph_label_looks(&s, g);
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"size": 14})).unwrap();
let r = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
sel(&mut s, &[g, r]);
let group = id_of(&s.execute("object.group", &json!({})).unwrap());
// A copy of the graph placed inside it, as a file may hold one.
let inner = {
let d = doc_mut(&mut s);
let mut copy = d.node(g).unwrap().clone();
copy = d.reid(&copy);
let id = copy.id;
d.node_mut(g).unwrap().children_mut().unwrap().push(std::sync::Arc::new(copy));
id
};
copy(&mut s, &[group]);
new_doc(&mut s);
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap())[0];
let mut graphs = vec![];
node(&s, p).walk(&mut |n| {
if let Some(spec) = n.extras().graph.as_deref() {
graphs.push((n.id, spec.label_styles.clone()));
}
});
assert_eq!(graphs.len(), 2, "{inner:?}");
for (id, l) in graphs {
assert_eq!((l.values, l.categories, l.legend, l.values_para, l.categories_para, l.legend_para), (None, None, None, None, None, None));
let looks = graph_label_looks(&s, id);
assert!(looks.iter().all(|(_, size, _)| *size == fresh[0].1), "{looks:?}");
}
}
/// A graph without its generated bounds (as a file may hold it) is drawn again where Paste without Formatting put it.
#[test]
fn a_graph_without_generated_bounds_pasted_without_formatting_follows_the_offset() {
let mut s = session();
let csv = ",2024\nQ1,3\nQ2,5";
let g = id_of(&s.execute("graph.create", &json!({"type": "bar", "x": 50, "y": 60, "width": 100, "height": 80, "csv": csv})).unwrap());
let plot = {
let mut extras = doc_mut(&mut s).node_mut(g).unwrap().extras_mut();
let spec = extras.graph.as_mut().unwrap();
spec.placed = None;
spec.rect
};
copy(&mut s, &[g]);
let v = s.execute("edit.pasteWithoutFormatting", &json!({"dx": 30, "dy": -5})).unwrap();
let p = ids_of(&v)[0];
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
let r = node(&s, p).extras().graph.as_deref().unwrap().rect;
let off = [r.x0 - plot.x0 - 30.0, r.y0 - plot.y0 + 5.0, r.x1 - plot.x1 - 30.0, r.y1 - plot.y1 + 5.0];
assert!(off.iter().all(|d| d.abs() < 1e-6), "{plot:?} → {r:?}");
// A graph saved with the bounds of all its art but not those of its art without type, drawn with 30 pt labels: the
// labels set at 9 pt do not read as a move or scale when it is drawn again.
let g = id_of(&s.execute("graph.create", &json!({"type": "bar", "x": 300, "y": 60, "width": 100, "height": 80, "csv": csv})).unwrap());
sel(&mut s, &[g]);
s.execute("text.setStyle", &json!({"size": 30})).unwrap();
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
let plot = {
let mut extras = doc_mut(&mut s).node_mut(g).unwrap().extras_mut();
let spec = extras.graph.as_mut().unwrap();
spec.placed_art = None;
spec.rect
};
copy(&mut s, &[g]);
let v = s.execute("edit.pasteWithoutFormatting", &json!({"dx": 30, "dy": -5})).unwrap();
let p = ids_of(&v)[0];
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
let r = node(&s, p).extras().graph.as_deref().unwrap().rect;
let off = [r.x0 - plot.x0 - 30.0, r.y0 - plot.y0 + 5.0, r.x1 - plot.x1 - 30.0, r.y1 - plot.y1 + 5.0];
assert!(off.iter().all(|d| d.abs() < 1e-6), "without the bounds of the art without type: {plot:?} → {r:?}");
}
#[test]
+1 -1
View File
@@ -40,7 +40,7 @@ fn close(a: f64, b: f64) -> bool {
fn segment_angles(p: &PathData) -> Vec<f64> {
p.subpaths
.iter()
.flat_map(|sp| sp.anchors.windows(2).map(|w| w[1].p - w[0].p))
.flat_map(|sp| sp.anchors.iter().zip(sp.anchors.iter().skip(1)).map(|(a, b)| b.p - a.p))
.filter(|v| v.hypot() > 1e-9)
.map(|v| (-v.y).atan2(v.x).to_degrees().rem_euclid(90.0))
.collect()
+5 -5
View File
@@ -890,7 +890,7 @@ fn curvature_rubber_band_is_the_path_the_click_makes() {
s.pointer(&PointerEvent::new(PointerKind::Up, 450.0, 400.0), v).unwrap();
let made = path(&s, id).subpaths[0].clone();
assert_eq!(made.anchors.len(), 4);
let tail = vectorcraft_geom::SubPath::new(made.anchors[1..].to_vec(), false);
let tail = vectorcraft_geom::SubPath::new(made.anchors.to_vec()[1..].to_vec(), false);
assert_eq!(preview, bez(&tail));
}
@@ -1218,7 +1218,7 @@ fn scissors_cut_ellipse_end_drags_alone() {
s.pointer(&PointerEvent::new(PointerKind::Up, cut.x + 8.0, cut.y + 8.0).with_mods(m), v).unwrap();
assert_eq!(undo_steps(&s), undo + 1);
let after = path(&s, id);
let (old, new) = (&sp.anchors, &after.subpaths[0].anchors);
let (old, new) = (&sp.anchors.to_vec(), &after.subpaths[0].anchors.to_vec());
assert_eq!(new.len(), old.len());
assert_eq!(new[1..], old[1..], "only the dragged end moves (at anchor: {at_anchor}, {m:?})");
let d = Point::new(cut.x + 8.0, cut.y + 8.0) - cut;
@@ -1572,7 +1572,7 @@ fn a_short_smooth_drag_leaves_the_rest_of_long_segments_alone() {
drag(&mut s, "smooth", &[(195.0, 194.0), (205.0, 194.0)], Mods::default());
let p = path(&s, id);
assert_ne!(p, before, "the bump is smoothed");
let a = &p.subpaths[0].anchors;
let a = &p.subpaths[0].anchors.to_vec();
let (first, second, last) = (a[0], a[1], a[a.len() - 1]);
assert!(first.p == Point::new(50.0, 200.0) && !first.has_out() && !second.has_in(), "the left side is a line still: {first:?} {second:?}");
assert!(last.p == Point::new(350.0, 200.0) && !last.has_in() && !a[a.len() - 2].has_out(), "and the right one: {last:?}");
@@ -1783,7 +1783,7 @@ fn smoothing_over_a_closed_paths_first_anchor_keeps_its_start() {
assert_ne!(after, before, "the bump is smoothed");
assert_starts_nearest(&after, old, 12.0);
let kept = &after.subpaths[0].anchors;
for a in &before.subpaths[0].anchors[2..=10] {
for a in &before.subpaths[0].anchors.to_vec()[2..=10] {
assert!(kept.iter().any(|k| k.p == a.p), "{:?} is out of reach and stays: {kept:?}", a.p);
}
s.execute("edit.undo", &json!({})).unwrap();
@@ -3885,7 +3885,7 @@ fn pen_cmd_selected_anchors_are_what_copy_and_cut_take() {
assert!(left.is_empty());
assert!(s.doc().unwrap().selection.objects.is_empty());
assert_eq!(s.clipboard.nodes.len(), 1);
assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors[1..3]);
assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors.to_vec()[1..3]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(paths(&s), vec![(id, original.clone())]);
assert_eq!(s.doc().unwrap().selection, picked);
+23
View File
@@ -81,6 +81,29 @@ fn junk_is_rejected() {
assert_eq!(s.doc().unwrap().doc.metadata, DocMetadata { created: s.doc().unwrap().doc.metadata.created, ..Default::default() });
}
/// A control character inside a value is refused with the field's rule: Description and Copyright
/// Notice take line breaks and tabs, the other text fields and each keyword in a list take none.
#[test]
fn control_characters_are_refused_with_the_field_rule() {
let mut s = session();
for (params, msg) in [
(json!({"description": "a\u{7}b"}), "description has control characters"),
(json!({"copyrightNotice": "a\u{0}b"}), "copyrightNotice has control characters"),
(json!({"title": "a\nb"}), "title has control characters or line breaks"),
(json!({"author": "a\rb"}), "author has control characters or line breaks"),
(json!({"authorTitle": "a\tb"}), "authorTitle has control characters or line breaks"),
(json!({"copyrightUrl": "a\u{7}b"}), "copyrightUrl has control characters or line breaks"),
(json!({"keywords": ["ok", "a\nb"]}), "keywords has control characters or line breaks"),
] {
match s.execute("file.info", &params) {
Err(EngineError::BadParams { cmd, msg: got }) => assert_eq!((cmd.as_str(), got.as_str()), ("file.info", msg), "{params}"),
other => panic!("{params}: {other:?}"),
}
}
s.execute("file.info", &json!({"description": "two\nlines\tand a tab", "copyrightNotice": "a\r\nb"})).unwrap();
assert_eq!(s.doc().unwrap().doc.metadata.description, "two\nlines\tand a tab");
}
#[test]
fn file_info_round_trips_and_old_files_load() {
let mut s = session();
+69
View File
@@ -231,6 +231,75 @@ fn deleting_a_spot_swatch_takes_the_process_plates_of_the_stops_it_unlinks() {
assert_eq!(gradient(&s, id).gradient.stops[1], linked, "undo brings back the link and the plates");
}
/// The stops of the gradients the merge test puts in place: the art's fill, gradient swatch "Glow",
/// graphic style "Style", the art of brush "Brush" and the fill new art takes.
fn merge_test_stops(s: &Session, id: NodeId) -> Vec<(&'static str, Vec<GradientStop>)> {
let d = doc(s);
let stops = |p: Paint| match p {
Paint::Gradient(g) => g.gradient.stops,
p => panic!("not a gradient: {p:?}"),
};
let style = d.graphic_style("Style").unwrap().appearance.items.iter().find_map(|it| match it {
vectorcraft_doc::AppearanceItem::Fill(f) => Some(f.paint.clone()),
vectorcraft_doc::AppearanceItem::Stroke(_) => None,
});
let mut brush = None;
for n in vectorcraft_brush::find(d, "Brush").unwrap().art() {
n.walk(&mut |m| {
if brush.is_none() && matches!(m.appearance.fill_paint(), Paint::Gradient(_)) {
brush = Some(m.appearance.fill_paint());
}
});
}
vec![
("art", stops(d.node(id).unwrap().appearance.fill_paint())),
("gradient swatch", stops(d.swatch("Glow").unwrap().paint.clone())),
("graphic style", stops(style.unwrap())),
("brush art", stops(brush.unwrap())),
("new art", stops(s.paint.fill.clone())),
]
}
#[test]
fn merging_swatches_takes_the_process_plates_of_the_stops_it_relinks() {
// Kept swatch "Keep": spot, global process, and process that isn't global.
for (spot, global) in [(true, true), (false, true), (false, false)] {
let (mut s, id) = setup();
run(&mut s, "swatch.new", json!({"name": "Keep", "color": "#00ff00", "spot": spot, "global": global}));
run(&mut s, "swatch.new", json!({"name": "Other", "color": {"c": 1, "m": 0, "y": 0, "k": 0}, "spot": true}));
// Ink at 50 % over a 30 % cyan plate, and Other over its own 20 % magenta plate, which the
// merge leaves alone.
let plated = json!({"stops": [
{"offset": 0, "swatch": "Ink", "tint": 50, "plates": [0.3, 0, 0, 0]},
{"offset": 1, "swatch": "Other", "plates": [0, 0.2, 0, 0]},
]});
run(&mut s, "paint.editGradient", plated.clone());
run(&mut s, "swatch.new", json!({"name": "Glow", "gradient": plated}));
run(&mut s, "graphicStyle.new", json!({"name": "Style"}));
run(&mut s, "brush.new", json!({"type": "art", "name": "Brush"}));
s.paint.fill = doc(&s).node(id).unwrap().appearance.fill_paint();
let before = merge_test_stops(&s, id);
let kept = doc(&s).linked_color(doc(&s).swatch("Keep").unwrap().paint.color().unwrap(), spot);
assert!(before.iter().all(|(_, st)| st[0].plates == Some([0.3, 0.0, 0.0, 0.0])), "{before:?}");
run(&mut s, "swatch.merge", json!({"names": ["Keep", "Ink"]}));
let after = merge_test_stops(&s, id);
// The stop shows its tint of the kept color, unlinked when the kept swatch isn't global.
let (link, tint, color) = if global { (Some("Keep"), 0.5, kept.tinted(0.5)) } else { (None, 1.0, kept.tinted(0.5)) };
for (place, st) in &after {
let what = format!("spot {spot}, global {global}, {place}: {st:?}");
assert_eq!((st[0].swatch.as_deref(), st[0].tint, st[0].plates), (link, tint, None), "{what}");
assert_eq!(st[0].color, color, "{what}");
assert_eq!((st[1].swatch.as_deref(), st[1].plates), (Some("Other"), Some([0.0, 0.2, 0.0, 0.0])), "{what}");
}
run(&mut s, "edit.undo", json!({}));
assert_eq!(merge_test_stops(&s, id), before, "undo brings back the links and the plates");
run(&mut s, "edit.redo", json!({}));
assert_eq!(merge_test_stops(&s, id), after, "redo merges again");
}
}
#[test]
fn radial_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() {
let (mut s, _) = setup();
+47
View File
@@ -3299,6 +3299,32 @@ fn select_all_on_artboard_refuses_an_artboard_past_u32() {
assert!(selected(&s).is_empty());
}
/// All on Active Artboard refuses an `artboard` that is not a whole number, naming the parameter,
/// and leaves the selection as it was; a whole number past the last artboard is `no such
/// artboard`. Left out or null, it takes the first artboard.
#[test]
fn select_all_on_artboard_refuses_an_artboard_that_is_not_a_whole_number() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2, "artboardLayout": {"layout": "row", "spacing": 0}})).unwrap();
let (first, second) = (rect(&mut s, 10.0, 10.0, 20.0, 20.0), rect(&mut s, 110.0, 10.0, 20.0, 20.0));
for bad in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1]), json!({})] {
s.execute("select.none", &json!({})).unwrap();
let err = s.execute("select.allOnArtboard", &json!({"artboard": bad})).unwrap_err().to_string();
assert_eq!(err, "invalid parameters for `select.allOnArtboard`: `artboard` must be a whole number", "{bad}");
assert!(selected(&s).is_empty(), "{bad}");
}
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute("select.allOnArtboard", &json!({"artboard": 9})).unwrap_err().to_string(), "no such artboard");
assert!(selected(&s).is_empty());
for p in [json!({}), json!({"artboard": null}), json!({"artboard": 0})] {
s.execute("select.none", &json!({})).unwrap();
s.execute("select.allOnArtboard", &p).unwrap();
assert_eq!(selected(&s), vec![first], "{p}");
}
s.execute("select.allOnArtboard", &json!({"artboard": 1})).unwrap();
assert_eq!(selected(&s), vec![second]);
}
#[test]
fn save_and_recall_selection() {
let mut s = session();
@@ -4605,6 +4631,27 @@ fn artboard_guides_go_with_their_artboard() {
assert_eq!((guides(&s).len(), selected_guides(&s)), (3, vec![0, 1]));
}
/// `guide.add` refuses an `artboard` that is not a whole number, naming the parameter, and adds no
/// guide; a whole number past the last artboard is `no such artboard`. Null makes a canvas guide,
/// and a whole number an artboard guide.
#[test]
fn guide_add_refuses_an_artboard_that_is_not_a_whole_number() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 900, "y": 0, "width": 400, "height": 300})).unwrap();
let add = |s: &mut Session, artboard: Value| s.execute("guide.add", &json!({"vertical": true, "pos": 10, "artboard": artboard}));
for bad in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1]), json!({})] {
let err = add(&mut s, bad.clone()).unwrap_err().to_string();
assert_eq!(err, "invalid parameters for `guide.add`: `artboard` must be a whole number", "{bad}");
}
assert_eq!(add(&mut s, json!(9)).unwrap_err().to_string(), "no such artboard");
assert!(s.doc().unwrap().doc.ruler_guides().is_empty());
add(&mut s, Value::Null).unwrap();
add(&mut s, json!(1)).unwrap();
let d = &s.doc().unwrap().doc;
let boards: Vec<_> = d.ruler_guides().iter().map(|g| g.artboard).collect();
assert_eq!(boards, [None, Some(d.artboards[1].id)]);
}
/// #451: a guide dragged out of a ruler snaps (to the art's corners, side midpoints and anchors,
/// the artboards' edges and centres) and is made in one undo step where it is released over the
/// canvas; with the Artboard tool it is an artboard guide of the active artboard.
+38
View File
@@ -775,6 +775,44 @@ fn create_outlines_draws_the_type_objects_own_paint() {
assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something");
}
/// Create Outlines draws what the type drew with effects of its own: a drop shadow of the whole
/// type and a Transform effect that scales and turns it, over fills and strokes of the object's
/// own around its Characters row.
#[test]
fn create_outlines_draws_the_type_objects_own_effects() {
let mut s = session();
type_with_own_paint(&mut s, &[red_blue(), blue_stroke()], 1);
let plain = render(&s);
let shadow = json!({"x": 6, "y": 6, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow, "item": null}));
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 80, "scaleV": 80, "rotate": 10}, "item": null}));
let before = render(&s);
assert!(differing(&plain, &before, 24) > 500, "the effects change what the type draws");
run(&mut s, "type.createOutlines", json!({}));
let after = render(&s);
let n = differing(&before, &after, 24);
assert!(n < 40, "{n} pixels differ");
}
/// A Warp effect of the type object's own bends one gradient across the whole type on the canvas,
/// and the group Create Outlines makes keeps it across the whole outline rather than one per
/// glyph, so the outlines draw what the type drew.
#[test]
fn create_outlines_keeps_a_warped_character_gradient_across_the_type() {
let mut s = session();
let t = run(&mut s, "text.create", json!({"x": 20, "y": 110, "text": "HIH", "size": 60}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [t]}));
let down = json!({"kind": "linear", "angle": 90, "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]});
run(&mut s, "paint.setFill", json!({"gradient": down}));
run(&mut s, "paint.setStroke", json!({"none": true}));
run(&mut s, "effect.apply", json!({"effect": "warp.arc", "params": {"bend": 50}, "item": null}));
let before = render(&s);
run(&mut s, "type.createOutlines", json!({}));
let after = render(&s);
let n = differing(&before, &after, 24);
assert!(n < 40, "{n} pixels differ");
}
/// Selected type "HIH" at 40 pt with ruby, underlined and struck through, its characters filled
/// with `fill` (a `paint.setFill` param) and stroked 2 pt wide, then scaled to 150% and rotated 20
/// degrees (the stroke keeps its 2 pt, which is 4/3 pt in text space).
+29
View File
@@ -1722,6 +1722,35 @@ fn text_set_format() {
assert_eq!(t.para.composer, vectorcraft_doc::Composer::EveryLine);
}
/// `text.setFormat {composer}` takes the two Middle Eastern & South Asian and the two Standard
/// composers, each per paragraph and one undo step; any other value is refused and names them all.
#[test]
fn text_set_format_takes_the_four_composers() {
use vectorcraft_doc::Composer;
let mut s = session();
let r = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "One\nTwo"})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
let composers = |s: &Session| {
let NodeKind::Text(t) = node(s, id).kind else { panic!() };
[t.para_at(0).composer, t.para_at(1).composer]
};
assert_eq!(composers(&s), [Composer::EveryLine; 2], "new type is ME&SA Every-line");
for (value, want) in [
("singleLine", Composer::SingleLine),
("standardSingleLine", Composer::StandardSingleLine),
("standardEveryLine", Composer::StandardEveryLine),
("everyLine", Composer::EveryLine),
] {
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": value, "start": 4, "end": 4})).unwrap();
assert_eq!(composers(&s), [Composer::EveryLine, want], "{value}: only the second paragraph");
}
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "standardEveryLine"})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(composers(&s), [Composer::EveryLine; 2], "one undo step");
let e = s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "standard"})).unwrap_err().to_string();
assert!(e.contains("standardSingleLine") && e.contains("standardEveryLine"), "{e}");
}
#[test]
fn stroke_advanced_scale_swap_flip() {
let mut s = session();
+2 -1
View File
@@ -704,10 +704,11 @@ fn effect_params_are_the_effects_own() {
fn an_effect_parameter_without_a_default_is_held_to_its_type() {
use crate::cmd::params::undefaulted_type;
use vectorcraft_render::effects::effect_catalog;
// Read by checks of their own: a stored texture or a texture to load, an SVG filter, a Warp's
// Read by checks of their own: a stored texture or a texture to load, an SVG filter and its axes, a Warp's
// map and the style of Crop Marks.
let own_check = |effect: &str, key: &str| match key {
"textureImage" | "name" | "xml" => true,
"axes" => effect == "svg.filter",
"version" => effect.starts_with("warp."),
"style" => effect == "cropMarks",
_ => false,
+56
View File
@@ -1088,6 +1088,62 @@ fn create_outlines_keeps_the_objects_own_fills_and_strokes() {
assert_eq!(node(&s, t).appearance.items, own, "one undo step brings the type back");
}
/// The type object's own effects go on the group once, in their order, with their settings and a
/// hidden one still hidden; a fill's own effect stays on its path of the whole outline, and no
/// glyph or whole-outline path takes the object's effects. Undo brings the type back with them.
#[test]
fn create_outlines_keeps_the_objects_own_effects_on_the_group() {
let mut s = session();
let t = text(&mut s, "Hi", 64.0);
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
for (cmd, p) in [
("appearance.addFill", json!({"target": "object"})),
("appearance.setItem", json!({"index": 0, "color": "#ff0000"})),
("effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 2}, "item": 0})),
("effect.apply", json!({"effect": "stylize.dropShadow", "params": {"x": 7, "y": 3, "blur": 0, "opacity": 60}, "item": null})),
("effect.apply", json!({"effect": "distort.transform", "params": {"rotate": 15}, "item": null})),
("effect.setParams", json!({"index": 1, "visible": false, "item": null})),
] {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
}
let own: Appearance = (*node(&s, t).appearance).clone();
let ids_of = |fx: &[vectorcraft_doc::Effect]| fx.iter().map(|e| (e.id.clone(), e.visible)).collect::<Vec<_>>();
assert_eq!(ids_of(&own.effects), [("stylize.dropShadow".to_string(), true), ("distort.transform".to_string(), false)]);
assert_eq!(ids_of(own.items[0].effects()), [("path.offsetPath".to_string(), true)]);
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
let g = node(&s, r[0]);
assert_eq!(g.appearance.effects, own.effects, "the group holds the object's effects as they were");
let ch = g.children().unwrap();
assert!(ch.iter().all(|c| c.appearance.effects.is_empty()), "no piece takes the object's effects");
let rows: Vec<_> = ch.iter().filter(|c| c.appearance.items == own.items).collect();
assert_eq!(rows.len(), 1, "one path of the whole outline paints the object's fill");
assert_eq!(rows[0].appearance.items[0].effects(), own.items[0].effects(), "the fill keeps its own effect");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(*node(&s, t).appearance, own, "one undo step brings the type back with its effects");
}
/// The group takes the type object's opacity, blend mode, Isolate Blending, Opacity & Mask Define
/// Knockout Shape and opacity mask.
#[test]
fn create_outlines_keeps_the_objects_transparency_and_opacity_mask() {
let mut s = session();
let t = text(&mut s, "Hi", 64.0);
let m = rect(&mut s, 0.0, 0.0, 40.0, 80.0);
s.execute("select.set", &json!({"ids": [t.0, m.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let p = json!({"ids": [t.0], "opacity": 70, "blend": "multiply", "isolate": true, "knockoutShape": true});
s.execute("transparency.set", &p).unwrap();
let before = node(&s, t);
assert!(before.extras().mask.is_some(), "the type has a mask");
let look = |n: &vectorcraft_doc::Node| (n.opacity, n.blend, n.isolate, n.knockout_shape);
assert_eq!(look(&before), (0.7, vectorcraft_color::BlendMode::Multiply, true, true));
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
let g = node(&s, r[0]);
assert_eq!(look(&g), look(&before));
assert_eq!(g.extras().mask, before.extras().mask, "the group keeps the type's opacity mask");
}
/// Colour bitmap glyphs (emoji) become embedded images where they sat; glyphs showing one image
/// share its pixels.
#[test]
@@ -1023,6 +1023,78 @@ fn saved_for_older_apps_with_a_precision_the_placed_art_is_rounded_too() {
assert_ne!(preview, crate::cmd::fileio::preview_png(&s.doc().unwrap().doc).unwrap());
}
/// Saved for an older version, a placed document held only in stored brushes' art (a scatter
/// brush's art and a pattern brush's tile) is saved as the art it shows, with the resources that art
/// uses, and a precision save's preview shows that art as the file holds it, rounded. The current
/// version keeps it placed.
#[test]
fn saved_for_older_apps_placed_documents_in_brush_art_become_their_art() {
let dir = Folder::new("placed-brush-older");
let src = dir.file("badge.vectorcraft");
// A symbol `Star` and a triangle off the whole-point grid.
let mut d = Document::new(100.0, 100.0);
let layer = d.layers[0].id;
let star = Node::path(vectorcraft_doc::NodeId(900), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), look(BLUE));
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Star".into(), art: std::sync::Arc::new(star) });
let id = d.alloc_id();
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Star".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
let points = [(3.4876474632797176, 10.5), (96.5, 2.4876), (40.4876, 97.5)].map(|(x, y)| vectorcraft_geom::Point::new(x, y));
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::path::SubPath::polyline(&points, true));
let id = d.alloc_id();
d.insert(Some(layer), 1, Node::path(id, path, look(RED))).unwrap();
write(&src, &vectorcraft_format::save_file(&d));
let mut s = session();
let id = place(&mut s, &src);
let art = s.doc().unwrap().doc.node(id).unwrap().clone();
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let scatter = vectorcraft_brush::Scatter { art: art.clone(), ..Default::default() };
let pattern = vectorcraft_brush::PatternBrush { side: art, ..Default::default() };
vectorcraft_brush::store(
d,
&[
vectorcraft_brush::Brush { name: "Badge Dots".into(), kind: vectorcraft_brush::BrushKind::Scatter(scatter) },
vectorcraft_brush::Brush { name: "Badge Band".into(), kind: vectorcraft_brush::BrushKind::Pattern(pattern) },
],
);
assert!(!d.has_placed(), "only the brushes hold it");
}
let line = s.execute("shape.line", &json!({"x1": 20, "y1": 150, "x2": 380, "y2": 150})).unwrap()["id"].clone();
s.execute("brush.apply", &json!({"name": "Badge Dots", "ids": [line]})).unwrap();
// The placed documents in each brush's art.
let placed_in_brushes = |d: &Document| {
let mut n = 0;
for b in vectorcraft_brush::library(d) {
for art in b.art() {
art.walk(&mut |c| n += usize::from(matches!(c.kind, NodeKind::PlacedDocument(_))));
}
}
n
};
let prefix = vectorcraft_doc::placed_document::RESOURCE_PREFIX;
let older = vectorcraft_format::VERSION - 1;
let old =
vectorcraft_format::load(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft", "version": older})).unwrap())).unwrap();
assert_eq!(placed_in_brushes(&old), 0, "{}", old.unknown[vectorcraft_brush::DOC_KEY]);
assert_eq!(vectorcraft_brush::library(&old).len(), 2);
for b in vectorcraft_brush::library(&old) {
assert!(matches!(b.art()[0].kind, NodeKind::Group { .. }), "{}: {}", b.name, b.art()[0].kind_label());
}
assert!(old.symbols.iter().any(|s| s.name.starts_with(prefix)), "the art's symbol is saved with it");
let current = vectorcraft_format::load(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap())).unwrap();
assert_eq!(placed_in_brushes(&current), 2, "the current version keeps them placed");
assert!(current.symbols.iter().all(|s| !s.name.starts_with(prefix)));
// With a precision, the preview shows the brushes' art as the file holds it, rounded.
let file = decode(&s.execute("file.saveCopy", &json!({"version": older, "precision": 0, "preview": true})).unwrap());
let saved = vectorcraft_format::load(&file).unwrap();
assert_eq!(placed_in_brushes(&saved), 0);
let preview = vectorcraft_format::preview(&file);
assert!(preview.is_some());
assert_eq!(preview, crate::cmd::fileio::preview_png(&saved).unwrap());
assert_ne!(preview, crate::cmd::fileio::preview_png(&s.doc().unwrap().doc).unwrap());
}
#[test]
fn break_link_gives_the_editable_copy_placing_without_link_gives() {
let dir = Folder::new("placed-break");
+52
View File
@@ -292,6 +292,58 @@ fn rasterize_measures_the_art_its_geometry_effects_draw() {
assert_eq!((xf.translation().x, width), (150.0, 41));
}
/// A Transform effect after Rasterize moves the image the Rasterize effect makes: Expand Appearance
/// and PDF export make the image of the art before the Transform effect, as Object › Rasterize
/// makes it, and place it through the effect's map, as the canvas draws it.
#[test]
fn expand_rasterize_then_transform_matches_canvas() {
let mut o = session();
red_rectangle(&mut o);
let made = id(&o.execute("object.rasterize", &json!({"ppi": 72, "background": "white", "addAround": 2})).unwrap());
let od = &o.doc().unwrap().doc;
let (w, h, xf, png, _) = rasterized(od, od.node(made).unwrap());
// About the center of the rectangle's path.
let about =
|m: vectorcraft_geom::Affine| vectorcraft_geom::Affine::translate((70.5, 65.25)) * m * vectorcraft_geom::Affine::translate((-70.5, -65.25));
let cases = [
(json!({"scaleH": 200, "scaleV": 200}), about(vectorcraft_geom::Affine::scale(2.0))),
(json!({"rotate": 30}), about(vectorcraft_geom::Affine::rotate(-30f64.to_radians()))),
(
json!({"rotate": 30, "moveH": 10, "strokes": true}),
vectorcraft_geom::Affine::translate((10.0, 0.0)) * about(vectorcraft_geom::Affine::rotate(-30f64.to_radians())),
),
];
for (params, map) in cases {
let mut s = session();
let r = red_rectangle(&mut s);
let raster = json!({"useDocumentResolution": false, "resolution": 72, "background": "white", "addAround": 2});
s.execute("effect.apply", &json!({"effect": "rasterize", "params": raster, "ids": [r.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": params.clone(), "ids": [r.0]})).unwrap();
let check = |d: &Document, n: &vectorcraft_doc::Node, what: &str| {
let (w2, h2, xf2, png2, _) = rasterized(d, n);
assert_eq!((w2, h2), (w, h), "{what} {params}");
assert!(png2 == png, "{what} {params}: the same pixels");
let want = map * xf;
assert!(xf2.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{what} {params}: {xf2:?} {want:?}");
};
let flat = crate::flatten_raster_effects(&s.doc().unwrap().doc).unwrap();
check(&flat, &flat.layers[0].children().unwrap()[0], "PDF export");
s.execute("effect.expandAppearance", &json!({"ids": [r.0]})).unwrap();
let d = &s.doc().unwrap().doc;
check(d, d.node(r).unwrap(), "Expand Appearance");
}
// A Transform effect that scales the image to nothing leaves nothing in PDF export, as the
// canvas draws nothing.
let mut s = session();
let r = red_rectangle(&mut s);
let raster = json!({"useDocumentResolution": false, "resolution": 72, "background": "white", "addAround": 2});
s.execute("effect.apply", &json!({"effect": "rasterize", "params": raster, "ids": [r.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleH": 0}, "ids": [r.0]})).unwrap();
let flat = crate::flatten_raster_effects(&s.doc().unwrap().doc).unwrap();
let n = &flat.layers[0].children().unwrap()[0];
assert!(matches!(&n.kind, vectorcraft_doc::NodeKind::Group { children, .. } if children.is_empty()), "{:?}", n.kind);
}
#[test]
fn the_clipping_mask_follows_the_art_its_geometry_effects_draw() {
let clip = |s: &Session, n: NodeId| match &s.doc().unwrap().doc.node(n).unwrap().kind {
+41
View File
@@ -1532,6 +1532,47 @@ fn images_sharing_an_entry_are_written_once() {
assert_eq!(store.images_written().len(), 1, "restored into this session's area once");
}
/// A linked image shown only in a stored brush's art is kept as its preview, as a save writes it;
/// an image key that a brush's art embeds keeps its full bytes though the layers show it linked.
#[test]
fn recovery_brush_links_keep_proxy_and_embedded_full_bytes() {
let (full, proxy) = (vec![1u8; 40], vec![2u8; 10]);
for brush_linked in [true, false] {
let store = Arc::new(MemoryStore::default());
let mut s = session_in(&store);
{
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let blob =
vectorcraft_doc::ImageBlob { proxy: Some(Arc::new(proxy.clone())), ..vectorcraft_doc::ImageBlob::new("image/jpeg", full.clone()) };
d.images.insert("k".into(), blob);
let image = |link: Option<vectorcraft_doc::LinkInfo>| {
let im = vectorcraft_doc::ImageObject {
key: "k".into(),
width: 4,
height: 4,
xf: vectorcraft_geom::Affine::IDENTITY,
link,
placement: Default::default(),
pixels: None,
};
vectorcraft_doc::Node::new(NodeId(0), vectorcraft_doc::NodeKind::Image(Box::new(im)))
};
let link = Some(vectorcraft_doc::LinkInfo::new("/work/k.jpg"));
if !brush_linked {
let (mut n, layer) = (image(link.clone()), d.layers[0].id);
n.id = d.alloc_id();
d.insert(Some(layer), 0, n).unwrap();
}
let art = image(if brush_linked { link } else { None });
let scatter = vectorcraft_brush::Scatter { art, ..Default::default() };
vectorcraft_brush::store(d, &[vectorcraft_brush::Brush { name: "Dots".into(), kind: vectorcraft_brush::BrushKind::Scatter(scatter) }]);
}
let r = s.execute("file.recovery.save", &json!({})).unwrap();
let want = if brush_linked { proxy.len() } else { full.len() };
assert_eq!(r["saved"][0]["imageBytes"], want, "linked in the brush: {brush_linked}: {r}");
}
}
#[test]
fn copies_from_before_images_were_kept_apart_still_restore() {
let store = Arc::new(MemoryStore::default());
+10 -10
View File
@@ -73,8 +73,8 @@ fn simplify_refits_only_the_run_between_direct_selected_anchors() {
assert_eq!(out["after"].as_u64(), Some(len as u64));
assert!(len < 101 - 30, "{len}");
let end = len - 41;
assert_eq!(sp.anchors[..20], original.anchors[..20], "the anchors before the run");
assert_eq!(sp.anchors[end + 1..], original.anchors[61..], "the anchors after the run");
assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20], "the anchors before the run");
assert_eq!(sp.anchors.to_vec()[end + 1..], original.anchors.to_vec()[61..], "the anchors after the run");
assert_eq!((sp.anchors[20].p, sp.anchors[20].h_in), (original.anchors[20].p, original.anchors[20].h_in));
assert_eq!((sp.anchors[end].p, sp.anchors[end].h_out), (original.anchors[60].p, original.anchors[60].h_out));
for i in 0..20 {
@@ -100,7 +100,7 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() {
let id = wave(&mut s);
select_anchors(&mut s, id, ranges);
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
path_of(&s, id).subpaths[0].anchors.clone()
path_of(&s, id).subpaths[0].anchors.to_vec()
};
let (first, second) = (alone(&[(10, 30)]), alone(&[(60, 80)]));
let mut s = session();
@@ -110,13 +110,13 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() {
let undo = undo_len(&s);
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
assert_eq!(undo_len(&s), undo + 1, "one undo step");
let both = path_of(&s, id).subpaths[0].anchors.clone();
let both = path_of(&s, id).subpaths[0].anchors.to_vec();
// Where old anchor 30 is in the first result, and old anchor 80 in the second.
let (a30, a80) = (first.len() - 71, second.len() - 21);
assert!(a30 < 30 && a80 < 80, "both runs lose anchors");
let mid = a30 + 30;
assert_eq!(both[..=a30], first[..=a30]);
assert_eq!(both[a30 + 1..mid], original.anchors[31..60], "the anchors between the runs");
assert_eq!(both[a30 + 1..mid], original.anchors.to_vec()[31..60], "the anchors between the runs");
assert_eq!(both[mid..], second[60..]);
let sel: BTreeSet<_> = (10..=a30).chain(mid..=mid + a80 - 60).map(|i| (0, i)).collect();
assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel));
@@ -138,7 +138,7 @@ fn a_run_across_the_start_of_a_closed_path_simplifies_as_one() {
assert!(sp.closed);
assert!(sp.anchors.len() < 80 - 10, "{}", sp.anchors.len());
assert!(!sp.anchors.iter().any(|a| a.p == original.anchors[0].p), "anchor 0 was inside the run");
assert_eq!(sp.anchors[1..60], original.anchors[11..70]);
assert_eq!(sp.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]);
assert_eq!((sp.anchors[0].p, sp.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out));
assert_eq!((sp.anchors[60].p, sp.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in));
for i in 0..60 {
@@ -162,8 +162,8 @@ fn picked_segments_simplify_and_stay_picked() {
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
let sp = path_of(&s, id).subpaths[0].clone();
let end = sp.anchors.len() - 41;
assert_eq!(sp.anchors[..20], original.anchors[..20]);
assert_eq!(sp.anchors[end + 1..], original.anchors[61..]);
assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20]);
assert_eq!(sp.anchors.to_vec()[end + 1..], original.anchors.to_vec()[61..]);
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.segments.get(&id), Some(&(20..end).map(|i| (0, i)).collect()));
assert_eq!(sel.anchors.get(&id), Some(&(20..=end).map(|i| (0, i)).collect()));
@@ -200,8 +200,8 @@ fn slider_preview_and_auto_simplify_only_the_run() {
let previewed = path_of(&s, id);
let sp = &previewed.subpaths[0];
assert!(sp.anchors.len() < 101, "{p}");
assert_eq!(sp.anchors[..20], original.anchors[..20], "{p}");
assert_eq!(sp.anchors[sp.anchors.len() - 40..], original.anchors[61..], "{p}");
assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20], "{p}");
assert_eq!(sp.anchors.to_vec()[sp.anchors.len() - 40..], original.anchors.to_vec()[61..], "{p}");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("object.path.simplify", &p).unwrap();
assert_eq!(path_of(&s, id), previewed, "{p}");
+2 -2
View File
@@ -93,7 +93,7 @@ fn more_smoothing_removes_the_jags_and_keeps_the_shape() {
// Within the tolerance (2.5 % of 300 pt at most) plus the jag the refit smooths away.
assert!(farthest(&before, &after) <= 7.5 + 1.5, "level {level}: {}", farthest(&before, &after));
// The end points of an open path stay put.
let (a, b) = (&before.subpaths[0].anchors, &after.subpaths[0].anchors);
let (a, b) = (&before.subpaths[0].anchors.to_vec(), &after.subpaths[0].anchors.to_vec());
assert_eq!((a[0].p, a[a.len() - 1].p), (b[0].p, b[b.len() - 1].p));
assert!(!after.subpaths[0].closed);
s.execute("edit.undo", &json!({})).unwrap();
@@ -206,7 +206,7 @@ fn direct_selected_anchors_smooth_only_their_section() {
s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors})).unwrap();
s.execute("object.path.smooth", &json!({"level": 100})).unwrap();
let after = path_of(&s, id);
let (a, b) = (&before.subpaths[0].anchors, &after.subpaths[0].anchors);
let (a, b) = (&before.subpaths[0].anchors.to_vec(), &after.subpaths[0].anchors.to_vec());
assert!(b.len() < a.len(), "{} → {}", a.len(), b.len());
// Anchors 0..=10 and 30..=40 are untouched, the section between them refitted.
assert_eq!(a[..=10].iter().map(|x| x.p).collect::<Vec<_>>(), b[..=10].iter().map(|x| x.p).collect::<Vec<_>>());
+20
View File
@@ -325,6 +325,26 @@ fn select_same_appearance_attribute() {
run(&mut s, "select.set", json!({"ids": [a.0]}));
run(&mut s, "select.same.appearanceAttribute", json!({"item": (1u64 << 32) + 1}));
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]);
// Null is the default: the shared effect.
run(&mut s, "select.set", json!({"ids": [a.0]}));
run(&mut s, "select.same.appearanceAttribute", json!({"item": null}));
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]);
}
/// Select > Same > Appearance Attribute refuses an `item` that is not a whole number and leaves
/// the selection as it was.
#[test]
fn select_same_appearance_attribute_refuses_an_item_that_is_not_a_whole_number() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "effect.apply", json!({"effect": "distort.roughen"}));
rect(&mut s, 100.0);
run(&mut s, "select.set", json!({"ids": [a.0]}));
for item in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1])] {
let e = s.execute("select.same.appearanceAttribute", &json!({"item": item})).unwrap_err().to_string();
assert_eq!(e, "invalid parameters for `select.same.appearanceAttribute`: `item` must be a whole number", "{item}");
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{item}");
}
}
/// With a member path of a compound path selected first, Select > Same > Graphic Style and
+37
View File
@@ -551,6 +551,26 @@ fn svg_export_keeps_a_measured_region_only_on_the_object_alone() {
assert!(after.contains("<image") && !after.contains("<feOffset dx=\"3\""), "{after}");
}
/// SVG export keeps a filter live only in a user space SVG import stores again: `scale` 1000 with
/// `axes` that double it scales the user space 2000 times, past what import holds, so the object is
/// written as an image instead of a filter that would be left out when the file is opened.
#[test]
fn svg_export_writes_an_image_for_a_user_space_import_cannot_store() {
let hue = r#"<filter id="Hue"><feColorMatrix type="hueRotate" values="90"/></filter>"#;
for (scale, axes, live) in [(2.0, json!([2, 0, 0, 2]), true), (1000.0, json!([2, 0, 0, 2]), false)] {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": hue, "scale": scale, "axes": axes}}));
let out = svg(&mut s);
assert_eq!((out.contains("<feColorMatrix"), out.contains("<image")), (live, !live), "scale {scale}: {out}");
let (back, warnings) = vectorcraft_svg::import_with_report(&out).unwrap();
assert!(warnings.is_empty(), "scale {scale}: {warnings:?}");
let mut kept = 0;
back.walk(|n| kept += n.appearance.effects.iter().filter(|e| e.id == "svg.filter").count());
assert_eq!(kept, usize::from(live), "scale {scale}: {out}");
}
}
/// SVG export writes a filter rebuilt from its filter elements and filter attributes, not the XML
/// the effect holds.
#[test]
@@ -575,6 +595,23 @@ fn moving_the_object_moves_the_filters_origin() {
assert_eq!(p["origin"], json!([8.0, 2.0]));
}
/// `axes` turns or skews the filter's user space; a move moves only its origin. Axes the effect
/// can't measure are refused.
#[test]
fn axes_turn_the_filters_user_space_and_bad_axes_are_refused() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": SHIFT, "axes": [0, 1, -1, 0]}}));
run(&mut s, "object.move", json!({"ids": [a.0], "dx": 5, "dy": -2}));
let p = &s.doc().unwrap().doc.node(a).unwrap().appearance.effects[0].params;
assert_eq!((&p["axes"], &p["origin"]), (&json!([0, 1, -1, 0]), &json!([5.0, -2.0])));
for axes in [json!([0, 0, 0, 0]), json!([1, 0, 0]), json!([1, 0, 0, "1"]), json!([1001, 0, 0, 1]), json!(null), json!("x")] {
let e = err(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": SHIFT, "axes": axes}}));
assert!(e.contains("`axes` must be [a, b, c, d]"), "{axes}: {e}");
}
assert!(err(&mut s, "effect.setParams", json!({"ids": [a.0], "index": 0, "params": {"axes": [0.01, 0, 0, 0.01]}})).contains("`axes` must be"));
}
#[test]
fn filters_survive_a_native_round_trip() {
let mut s = session();
+1 -1
View File
@@ -286,7 +286,7 @@ fn legacy_spiral_decay_preferences_report_the_ratio_drawn_after_reopening() {
assert_eq!(d.selection.objects.len(), 1);
let id = d.selection.objects[0];
let path = d.doc.node(id).unwrap().path_data().unwrap().clone();
let anchors = &path.subpaths[0].anchors;
let anchors = &path.subpaths[0].anchors.to_vec();
assert_eq!(anchors.len(), 5);
assert!(!path.is_closed());
let center = Point::new(200.0, 200.0);
+11
View File
@@ -1672,6 +1672,9 @@ fn action_set(bytes: &[u8]) -> Result<(), TestCaseError> {
prop_assert!(actions.iter().all(|a| a["steps"].as_array().map_or(0, Vec::len) <= 10_000));
prop_assert!(actions.iter().map(|a| a["steps"].as_array().map_or(0, Vec::len)).sum::<usize>() <= 100_000);
prop_assert!(r["unread"].as_array().map_or(0, Vec::len) <= 1000);
let steps = || actions.iter().flat_map(|a| a["steps"].as_array().cloned().unwrap_or_default());
prop_assert!(steps().all(|s| s["values"].as_array().map_or(0, Vec::len) as u64 <= s["params"].as_u64().unwrap_or(0)));
prop_assert!(steps().map(|s| s["values"].as_array().map_or(0, Vec::len)).sum::<usize>() <= 100_000);
}
Ok(())
}
@@ -1690,6 +1693,8 @@ fn arb_aia_token() -> impl Strategy<Value = Vec<u8>> {
"/localizedName",
"/isOn",
"/value",
"/key",
"/type",
"/x",
"/version",
])
@@ -1699,6 +1704,7 @@ fn arb_aia_token() -> impl Strategy<Value = Vec<u8>> {
"[a-z ()\\\\]{0,12}".prop_map(|t| format!("({t})").into_bytes()),
prop::sample::select(vec!["(", ")", "\\", "[ 2 4142 ]", "[ 3 41 4", "[ 1 zz ]", "[", "]", "< 2 0a0b >", "<", ">", "2.5"])
.prop_map(|t| t.as_bytes().to_vec()),
prop::sample::select(vec!["[ 2 c328 ]", "(ustring)", "(boolean)"]).prop_map(|t| t.as_bytes().to_vec()),
prop::sample::select(vec!["{", "}", "\r\n", "\r", "\n"]).prop_map(|t| t.as_bytes().to_vec()),
prop::sample::select(vec![vec![0u8], vec![0xFF, 0xFE], vec![0xC3]]),
]
@@ -1835,6 +1841,7 @@ proptest! {
/// Mutated copies of the PSD and PSB samples never crash opening them with their layers, hidden
/// ones too: the PSD's layer records, channel lengths and data, and the PSB's layer count.
/// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`.)
/// Neither does `document.psdInfo`, nor placing them with their layers as objects.
#[test]
fn mutated_layered_psds_open_without_panics(which in 6usize..8, cut in 0usize..1_000_000, edits in prop::collection::vec((0usize..1_000_000, any::<u8>()), 0..12)) {
let (name, mut bytes) = raster_samples().swap_remove(which);
@@ -1849,6 +1856,10 @@ proptest! {
let mut s = vectorcraft_engine::Session::new();
let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "hiddenLayers": true});
let _ = no_panic(s.execute("document.open", &p));
let _ = no_panic(s.execute("document.psdInfo", &p));
let _ = no_panic(s.execute("file.new", &json!({})));
let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "layers": true, "hiddenLayers": true});
let _ = no_panic(s.execute("file.place", &p));
});
prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err());
}
+327 -1
View File
@@ -1038,7 +1038,8 @@ fn nested_symbol_instances_stop_at_the_symbol_art_limit() {
/// The documents [`the_writer_counts_objects_as_the_reader_reads_them`] writes: groups, compound
/// paths, guides, sublayers, clipping groups and layers, painted clipping paths, opacity masks,
/// gradients, pattern definitions and tiles, images, type, symbol definitions and instances,
/// objects with art styles, objects bound to variables and live envelopes.
/// objects with art styles, objects bound to variables, live envelopes, and the rectangles of the
/// bounds of wrapped objects written as their art.
fn counted() -> Vec<(&'static str, Document)> {
vec![
("sample", sample()),
@@ -1054,9 +1055,28 @@ fn counted() -> Vec<(&'static str, Document)> {
("blend", blend_doc()),
("brushes", brushes_document()),
("envelopes", envelopes_document()),
("wrap bounds", wrap_bounds_doc()),
]
}
/// Area type below a wrapped symbol instance written as its art and wrapped type written as its
/// outlines, each with the rectangle of its bounds.
fn wrap_bounds_doc() -> Document {
let mut doc = over_area_type(|doc| {
two_leaves(doc);
let mut n = instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0]));
n.isolate = true;
wrapped(n, 4.5, false)
});
let mut label = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "Ill", style(60.0, Color::BLACK));
// Mirrored, so written as its outlines.
label.xf = Affine::new([-1.0, 0.0, 0.0, 1.0, 150.0, 120.0]);
let label = wrapped(text_node(&mut doc, label), -2.0, true);
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, label).unwrap();
doc
}
/// A blend of two squares 20 pt apart with a step every 10 pt, written as its steps.
fn blend_doc() -> Document {
let mut doc = Document::new(200.0, 100.0);
@@ -11374,6 +11394,42 @@ fn text_wrap_options_of_type_and_envelopes_are_read_back() {
same_wraps(&wraps(top), &[(Some("Bent".into()), 2.5, true)]);
}
/// The wrap shapes that `doc`'s first area type on its first layer takes from the objects above it,
/// in the type's own space: the bounds of each one's subpaths, and its options.
fn area_wrap_region(doc: &Document) -> Vec<(Vec<[f64; 4]>, f64, bool)> {
use vectorcraft_doc::TextKind;
let mut doc = doc.clone();
vectorcraft_doc::text::resolve_wrap(None, &mut doc);
let top = doc.layers[0].children().unwrap();
let Some(NodeKind::Text(t)) = top.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(t) if matches!(t.kind, TextKind::Area { .. })))
else {
panic!("no area type");
};
t.wrap
.iter()
.map(|s| {
let parts = s
.path
.subpaths
.iter()
.map(|sp| {
let b = PathData::new(vec![sp.clone()]).bounds().unwrap_or_default();
[b.x0, b.y0, b.x1, b.y1]
})
.collect();
(parts, s.wrap.offset, s.wrap.invert)
})
.collect()
}
/// `before` and `after` hold as many wrap shapes, each with as many subpaths, with bounds within
/// `1e-3`, and the same options.
fn same_region(before: &[(Vec<[f64; 4]>, f64, bool)], after: &[(Vec<[f64; 4]>, f64, bool)]) -> bool {
let close =
|b: &[[f64; 4]], a: &[[f64; 4]]| b.len() == a.len() && b.iter().zip(a).all(|(b, a)| b.iter().zip(a).all(|(x, y)| (x - y).abs() < 1e-3));
before.len() == after.len() && before.iter().zip(after).all(|(b, a)| close(&b.0, &a.0) && (b.1 - a.1).abs() < 1e-6 && b.2 == a.2)
}
/// Type written as its outlines wraps area type below it by its bounds, as it did before saving,
/// not by its glyphs: its text wrap options go on an unpainted rectangle of its bounds, the last
/// member of the outlines' group, which keeps the type's name and has no options of its own.
@@ -11464,6 +11520,276 @@ fn type_written_as_outlines_keeps_wrapping_by_its_bounds() {
assert_eq!(top[1].name.as_deref(), Some("Label"), "{text_out}");
}
/// A 300 × 200 document of area type "Body" filling the page, with `top` above it.
fn over_area_type(make: impl FnOnce(&mut Document) -> Node) -> Document {
use vectorcraft_doc::{TextKind, TextObject, TextRun};
let mut doc = Document::new(300.0, 200.0);
let layer = doc.layers[0].id;
let mut body = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(10.0, Color::BLACK));
body.runs = vec![TextRun::new("one two three four five six seven eight nine ten eleven twelve", style(10.0, Color::BLACK))];
body.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 290.0, 190.0)) };
body.xf = Affine::IDENTITY;
let body = named(text_node(&mut doc, body), "Body");
let top = make(&mut doc);
for n in [body, top] {
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
doc
}
/// Symbol "Leaf": two squares in opposite corners of the 20 × 20 square around the origin, apart.
fn two_leaves(doc: &mut Document) {
let a = square(doc, Rect::new(-10.0, -10.0, -6.0, -6.0), LEAF);
let b = square(doc, Rect::new(6.0, 6.0, 10.0, 10.0), LEAF);
let art = group(doc, vec![a, b], false);
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) });
}
/// A symbol instance written as its art (its isolation is a group's), a blend and an intertwine,
/// each written as a group of its art, wrap area type below them by their bounds after reopening,
/// as they did before saving, not by the members of that art: the text wrap options go on an
/// unpainted rectangle of the bounds, the group's first member, and the group, which keeps the
/// object's name, isolation, lock and visibility, has none. A positive offset, a negative offset
/// with Invert Wrap, and hidden and locked.
#[test]
fn live_art_written_as_a_group_keeps_wrapping_by_its_bounds() {
let instance_of = |offset: f64, invert: bool, visible: bool, locked: bool| {
move |doc: &mut Document| {
two_leaves(doc);
let mut n = instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0]));
n.isolate = true;
(n.visible, n.locked) = (visible, locked);
wrapped(named(n, "Thing"), offset, invert)
}
};
let blend = |doc: &mut Document| {
let keys = vec![
Arc::new(square(doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))),
Arc::new(square(doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))),
];
let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() };
wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), 4.5, false)
};
let intertwine = |doc: &mut Document| {
let a = Arc::new(square(doc, Rect::new(60.0, 60.0, 80.0, 80.0), Color::gray(0.5)));
let b = Arc::new(square(doc, Rect::new(200.0, 120.0, 220.0, 140.0), Color::gray(0.5)));
wrapped(named(Node::new(doc.alloc_id(), NodeKind::Intertwine { children: vec![a, b] }), "Thing"), 2.0, true)
};
let repeat = |doc: &mut Document| {
let a = Arc::new(square(doc, Rect::new(100.0, 80.0, 110.0, 90.0), Color::gray(0.5)));
let spec = vectorcraft_doc::RepeatSpec::grid(vec![a], 8.0, 12.0);
wrapped(named(Node::new(doc.alloc_id(), NodeKind::Repeat(spec)), "Thing"), 1.5, false)
};
// A Fidelity that isn't a whole number: written as its distorted art.
let envelope = |doc: &mut Document| {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
wrapped(named(envelope_node(doc, kind, 50.5, false, EnvelopeOptions::NEW), "Thing"), -3.0, true)
};
let docs = [
("instance", over_area_type(instance_of(4.5, false, true, false)), 4.5, false, true, false),
("instance, inverted", over_area_type(instance_of(-2.0, true, true, false)), -2.0, true, true, false),
("instance, hidden and locked", over_area_type(instance_of(3.0, false, false, true)), 3.0, false, false, true),
("blend", over_area_type(blend), 4.5, false, true, false),
("intertwine", over_area_type(intertwine), 2.0, true, true, false),
("repeat", over_area_type(repeat), 1.5, false, true, false),
("envelope", over_area_type(envelope), -3.0, true, true, false),
];
for (name, doc, offset, invert, visible, locked) in docs {
let thing = &doc.layers[0].children().unwrap()[1];
let want = thing.geometric_bounds().unwrap();
let text_out = program(&doc);
let back = read_back(&doc);
let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back));
assert_eq!(before.len(), usize::from(visible), "{name}");
assert!(same_region(&before, &after), "{name}\n{before:?}\n{after:?}\n{text_out}");
assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{name}: {text_out}");
let top = back.layers[0].children().unwrap();
same_wraps(&wraps(top), &[(None, offset, invert)]);
let g = &top[1];
assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "{name}: {text_out}");
assert_eq!(
(g.name.as_deref(), g.extras().wrap, g.visible, g.locked, g.isolate),
(Some("Thing"), None, visible, locked, thing.isolate),
"{name}"
);
let first = &g.children().unwrap()[0];
assert!(matches!(first.kind, NodeKind::Path { guide: false, .. }) && first.appearance.items.is_empty(), "{name}: {text_out}");
assert_eq!((first.visible, first.locked), (visible, locked), "{name}");
let b = first.geometric_bounds().unwrap();
assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 1e-3), "{name}: {b:?} {want:?}");
}
// An envelope written live opens live and wraps by its bounds, its options its own.
let live = |doc: &mut Document| {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
wrapped(named(envelope_node(doc, kind, 50.0, false, EnvelopeOptions::NEW), "Thing"), -3.0, true)
};
let doc = over_area_type(live);
let text_out = program(&doc);
let back = read_back(&doc);
let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back));
assert_eq!(before.len(), 1);
assert!(same_region(&before, &after), "{before:?}\n{after:?}\n{text_out}");
let top = back.layers[0].children().unwrap();
assert!(matches!(top[1].kind, NodeKind::Envelope { .. }), "{text_out}");
same_wraps(&wraps(top), &[(Some("Thing".into()), -3.0, true)]);
}
/// The rectangle that keeps a blend written as its art wrapping by its bounds counts toward the
/// object limit, ahead of the art: one object short, the last step is left out with the limit's
/// warning; without room for the rectangle, the options are left out with the warning, and the
/// group does not take them. In an instance whose art holds area type, shown, hidden, in a hidden
/// group or written as its outlines, the rectangle is the group's first member, below that type:
/// area type below the instance wraps by its bounds after reopening, and the type in its art is not
/// wrapped by them.
#[test]
fn wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped() {
use vectorcraft_doc::{TextKind, TextObject, TextRun};
// A blend alone, without a symbol definition, so the objects are the group, the rectangle and
// the steps.
let mut doc = Document::new(300.0, 200.0);
let keys = vec![
Arc::new(square(&mut doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))),
Arc::new(square(&mut doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))),
];
let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() };
let thing = wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), 4.5, false);
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, thing).unwrap();
let steps = export_ai_editing(&doc, &opts()).unwrap();
let steps = crate::ai_alone(&steps.program).unwrap().0.layers[0].children().unwrap()[0].children().unwrap().len() - 1;
let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap();
let all = export_within(&doc, &opts(), read).unwrap();
assert!(!all.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", all.warnings);
let out = export_within(&doc, &opts(), read - 1).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", out.warnings);
let text_out = String::from_utf8_lossy(&out.program).replace("\r\n", "\n");
assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{text_out}");
let (back, _) = crate::ai_alone(&out.program).unwrap();
let top = back.layers[0].children().unwrap();
same_wraps(&wraps(top), &[(None, 4.5, false)]);
assert_eq!((top[0].name.as_deref(), top[0].extras().wrap), (Some("Thing"), None), "{text_out}");
let members = top[0].children().unwrap();
assert_eq!(members.len(), steps, "the rectangle and all but the last step: {text_out}");
assert!(matches!(members[0].kind, NodeKind::Path { guide: false, .. }) && members[0].appearance.items.is_empty(), "{text_out}");
let out = export_within(&doc, &opts(), read - steps - 1).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", out.warnings);
let text_out = String::from_utf8_lossy(&out.program).replace("\r\n", "\n");
assert!(!text_out.contains("(AI11TextWrapOffset)"), "{text_out}");
let (back, _) = crate::ai_alone(&out.program).unwrap();
assert!(wraps(back.layers[0].children().unwrap()).is_empty(), "{text_out}");
// Area type in the symbol's art, shown or hidden, of `words`, in a hidden group with `in_hidden`.
let make = |shown: bool, words: &'static str, in_hidden: bool| {
move |doc: &mut Document| {
let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(2.0, Color::BLACK));
t.runs = vec![TextRun::new(words, style(2.0, Color::BLACK))];
t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(-10.0, -10.0, -6.0, -6.0)) };
t.xf = Affine::IDENTITY;
let mut t = text_node(doc, t);
t.visible = shown;
if in_hidden {
t = group(doc, vec![t], false);
t.visible = false;
}
let s = square(doc, Rect::new(6.0, 6.0, 10.0, 10.0), LEAF);
let art = group(doc, vec![t, s], false);
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) });
let mut n = instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0]));
n.isolate = true;
wrapped(named(n, "Thing"), 4.5, false)
}
};
// Type of spaces alone is written as its outlines, which are not type.
for (what, shown, words, in_hidden) in
[("shown", true, "leaf", false), ("hidden", false, "leaf", false), ("in a hidden group", true, "leaf", true), ("spaces", true, " ", false)]
{
let doc = over_area_type(make(shown, words, in_hidden));
let text_out = program(&doc);
assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{what}: {text_out}");
let back = read_back(&doc);
let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back));
assert_eq!(before.len(), 1, "{what}");
assert!(same_region(&before, &after), "{what}\n{before:?}\n{after:?}\n{text_out}");
let g = &back.layers[0].children().unwrap()[1];
assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "{what}: {text_out}");
assert_eq!(g.extras().wrap, None, "{what}: {text_out}");
let first = &g.children().unwrap()[0];
assert!(matches!(first.kind, NodeKind::Path { guide: false, .. }) && first.appearance.items.is_empty(), "{what}: {text_out}");
let mut resolved = back.clone();
vectorcraft_doc::text::resolve_wrap(None, &mut resolved);
let mut inner = vec![];
resolved.layers[0].children().unwrap()[1].walk(&mut |m| {
if let NodeKind::Text(t) = &m.kind {
inner.push((matches!(t.kind, TextKind::Area { .. }), m.visible, t.wrap.len()));
}
});
let want: &[(bool, bool, usize)] = match what {
"shown" | "in a hidden group" => &[(true, true, 0)],
"hidden" => &[(true, false, 0)],
_ => &[],
};
assert_eq!(inner, want, "{what}: {text_out}");
}
}
/// A blend with no keys, written as an empty group, has no bounds for a rectangle: its group keeps
/// the text wrap options, and they read back.
#[test]
fn live_art_without_bounds_keeps_its_text_wrap_on_the_group() {
let mut doc = Document::new(300.0, 200.0);
let spec = vectorcraft_doc::BlendSpec::default();
let thing = wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: vec![], spec: Box::new(spec) }), "Thing"), 4.5, true);
assert_eq!(thing.geometric_bounds(), None);
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, thing).unwrap();
let text_out = program(&doc);
assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{text_out}");
let back = read_back(&doc);
same_wraps(&wraps(back.layers[0].children().unwrap()), &[(Some("Thing".into()), 4.5, true)]);
}
/// A symbol instance written as its art, whose art holds an envelope of area type beside a square,
/// wraps area type below it by its bounds after reopening. The envelope there is written as its art,
/// after the type written for it as a live envelope is taken back: the group has no text wrap
/// options, and its first member is the rectangle of the bounds.
#[test]
fn an_envelope_of_area_type_in_written_art_leaves_the_wrap_on_the_bounds() {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
use vectorcraft_doc::{TextKind, TextObject, TextRun};
let doc = over_area_type(|doc| {
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
let mut envelope = envelope_node(doc, kind, 50.0, false, EnvelopeOptions::NEW);
let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(10.0, Color::BLACK));
t.runs = vec![TextRun::new("bent", style(10.0, Color::BLACK))];
t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(60.0, 30.0, 140.0, 70.0)) };
t.xf = Affine::IDENTITY;
let t = text_node(doc, t);
let NodeKind::Envelope { content, .. } = &mut envelope.kind else { unreachable_envelope() };
content.push(Arc::new(t));
let s = square(doc, Rect::new(250.0, 150.0, 260.0, 160.0), LEAF);
let art = group(doc, vec![envelope, s], false);
doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) });
let mut n = instance(doc, "Bent", Affine::IDENTITY);
n.isolate = true;
wrapped(named(n, "Thing"), 4.5, false)
});
let text_out = program(&doc);
let back = read_back(&doc);
let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back));
assert_eq!(before.len(), 1);
assert!(same_region(&before, &after), "{before:?}\n{after:?}\n{text_out}");
let g = &back.layers[0].children().unwrap()[1];
assert_eq!(g.extras().wrap, None, "{text_out}");
let mut live = 0;
g.walk(&mut |m| live += usize::from(matches!(m.kind, NodeKind::Envelope { .. })));
assert_eq!(live, 0, "{text_out}");
let first = &g.children().unwrap()[0];
assert!(matches!(first.kind, NodeKind::Path { guide: false, .. }) && first.appearance.items.is_empty(), "{text_out}");
}
/// A clipping path inside art cut to a clipping object is written as its fills and its strokes,
/// two objects: its text wrap options are written once, whether it has both or only strokes, and
/// with its strokes when the region outside leaves nothing of its fills.
+43 -13
View File
@@ -289,7 +289,8 @@ pub(super) struct Writer<'a> {
/// brushed stroke's pieces) the art being written is in. Text wrap options are written only
/// outside them, since only the document's own objects wrap type.
drawn: u32,
/// The type just written as outlines has its text wrap options on the rectangle of its bounds
/// The type just written as outlines, or the symbol instance or live object just written as a
/// group of its art, has its text wrap options on the rectangle of its bounds
/// ([`Self::wrap_bounds`]), not in the group's dictionary.
wrap_moved: bool,
/// The brushes written ([`brushes`]).
@@ -773,6 +774,8 @@ impl<'a> Writer<'a> {
if !self.open_group("u") {
return;
}
let state = self.state;
let moved = self.wrap_on_bounds(n, state);
// The canvas places an instance inside a symbol's art where the outer instance puts
// it (9-slice guides, stains and patterns included), and this art doesn't move with it.
self.wrote_fixed |= self.in_symbol;
@@ -817,12 +820,13 @@ impl<'a> Writer<'a> {
self.warn(SYMBOL_LIMIT);
}
}
self.wrap_moved = moved;
self.end_group("U", xy);
}
NodeKind::Envelope { .. } if self.envelope(n, xy) => {}
NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES)),
NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES), true),
NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
self.drawn_art(n, xy, Some(LIVE));
self.drawn_art(n, xy, Some(LIVE), true);
}
// Ruler guides are kept in the document's native copy only.
NodeKind::RulerGuide { .. } => {}
@@ -889,13 +893,17 @@ impl<'a> Writer<'a> {
}
/// Live object `n`, of transparency `xy`, as a group of its art, with `warning` when it is given.
fn drawn_art(&mut self, n: &Node, xy: Xy, warning: Option<&str>) {
/// With `bounds`, `n`'s text wrap options go on the rectangle of its bounds, the group's first
/// member ([`Self::wrap_on_bounds`]); without it, in the group's dictionary.
fn drawn_art(&mut self, n: &Node, xy: Xy, warning: Option<&str>, bounds: bool) {
if !self.open_group("u") {
return;
}
let state = self.state;
if let Some(w) = warning {
self.warn(w);
}
let moved = bounds && self.wrap_on_bounds(n, state);
if self.nest < MAX_NEST {
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
self.nest += 1;
@@ -906,9 +914,29 @@ impl<'a> Writer<'a> {
self.drawn -= 1;
self.nest -= 1;
}
self.wrap_moved = moved;
self.end_group("U", xy);
}
/// In the group that object `n` is written as, when the group's dictionary would hold `n`'s text
/// wrap options: the rectangle of `n`'s bounds with them ([`Self::wrap_bounds`]), then lock and
/// hidden state `state` again. True when the group's dictionary is to leave the options out
/// ([`Self::wrap_moved`]), so the group wraps type by `n`'s bounds, as `n` does
/// ([`vectorcraft_doc::text::resolve_wrap`]), not by its members. Written before the group's
/// members, the rectangle is below any area type among them and does not wrap it. False,
/// writing nothing, when `n` has no finite bounds, and the group's dictionary keeps the options.
fn wrap_on_bounds(&mut self, n: &Node, state: Option<(bool, bool)>) -> bool {
let Some(w) = n.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) else { return false };
if finite_bounds(n).is_none() {
return false;
}
self.wrap_bounds(n, w);
if let Some((locked, hidden)) = state {
self.state(locked, hidden);
}
true
}
/// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]),
/// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an
/// empty `AIArtName`), has text wrap options ([`Self::text_wrap`]), has an opacity mask
@@ -1555,23 +1583,20 @@ impl<'a> Writer<'a> {
for c in over {
self.node(c);
}
// Type wraps by its bounds: its text wrap options go on a rectangle of its bounds, the
// group's last member, and the group's dictionary leaves them out.
if let Some(w) = n.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) {
self.wrap_bounds(n, w);
self.wrap_moved = true;
}
// Type wraps by its bounds.
self.wrap_moved = self.wrap_on_bounds(n, state);
if let Some((locked, hidden)) = state {
self.state(locked, hidden);
}
self.end_group("U", xy);
}
/// An unpainted closed rectangle at the geometric bounds of type `n`, the region its text wraps
/// around, with `n`'s lock and hidden state and text wrap options `w` in its dictionary. Nothing
/// An unpainted closed rectangle at the geometric bounds of type, a symbol instance or a live
/// object `n`, the region its text wraps around ([`vectorcraft_doc::text::resolve_wrap`]), with
/// `n`'s lock and hidden state and text wrap options `w` in its dictionary. Nothing
/// when `n` has no finite bounds, or without room for it ([`Self::take_objects`]).
fn wrap_bounds(&mut self, n: &Node, w: TextWrap) {
let Some(b) = n.geometric_bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return };
let Some(b) = finite_bounds(n) else { return };
self.state(n.locked, !n.visible);
let objects = self.objects;
self.plain_object(&shapes::rectangle(b), FillRule::NonZero, None, None, Xy::PLAIN);
@@ -1760,6 +1785,11 @@ impl<'a> Writer<'a> {
}
}
/// `n`'s geometric bounds, when they are finite.
fn finite_bounds(n: &Node) -> Option<vectorcraft_geom::Rect> {
n.geometric_bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))
}
/// The gradient of paint `p`, when it has one.
fn gradient(p: Option<&Paint>) -> Option<&vectorcraft_color::GradientPaint> {
match p {
@@ -411,9 +411,10 @@ impl Writer<'_> {
self.hidden -= 1;
self.nest -= 1;
// The distorted art, which takes the envelope's lock, visibility, transparency, name and
// opacity mask.
// opacity mask. The reader opens the envelope live, wrapping type by its bounds, so its text
// wrap options stay in the art's dictionary.
self.state(n.locked, !n.visible);
self.drawn_art(n, xy, None);
self.drawn_art(n, xy, None, false);
if !opened || outlines || self.left_out_since(charges) {
let lines = self.body.split_off(start);
self.give_back(charges, &lines);
+2 -4
View File
@@ -36,10 +36,8 @@ pub(crate) fn subpath(s: &mut String, xf: Affine, sp: &SubPath) {
s.push_str(if smooth { "c\n" } else { "C\n" });
}
};
for pair in sp.anchors.windows(2) {
if let [a, b] = pair {
segment(s, a, b);
}
for (a, b) in sp.anchors.iter().zip(sp.anchors.iter().skip(1)) {
segment(s, a, b);
}
if sp.closed
&& sp.anchors.len() > 1
+95 -20
View File
@@ -266,6 +266,14 @@ pub(crate) struct Scene<'a> {
images: HashMap<String, Option<usize>>,
/// The source key and solid paint together identify a colorized encoding.
colorized_images: HashMap<(String, String), Option<usize>>,
/// Image keys whose encoding didn't fit under the page limit → how much its first placement
/// adds to the body. The image is encoded again only once the page has room for that.
too_large_images: HashMap<String, usize>,
/// The same for colorized encodings, by `colorized_images`' keys.
too_large_colorized: HashMap<(String, String), usize>,
/// How many times an image or a colorized image was encoded.
#[cfg(test)]
encodes: usize,
/// Freeform gradients' images by [`ImageCode::content_key`] → their indices in `codes`: a field
/// encoded the same as one already kept draws from it.
fields: HashMap<u64, Vec<usize>>,
@@ -297,6 +305,10 @@ impl<'a> Scene<'a> {
brushes: None,
images: HashMap::new(),
colorized_images: HashMap::new(),
too_large_images: HashMap::new(),
too_large_colorized: HashMap::new(),
#[cfg(test)]
encodes: 0,
fields: HashMap::new(),
codes: vec![],
placements: vec![],
@@ -313,6 +325,30 @@ impl<'a> Scene<'a> {
self
}
/// [`Self::run`], with how many placements draw each encoded image the scene kept, and the
/// indices in `codes` that its image, colorized-image and field caches name.
#[cfg(test)]
pub fn run_with_codes(mut self) -> (Page, Vec<usize>, Vec<usize>) {
let doc = self.doc;
for l in &doc.layers {
self.node(l, false);
}
let uses = self.codes.iter().map(|c| c.uses).collect();
let cached = self.images.values().chain(self.colorized_images.values()).flatten().chain(self.fields.values().flatten()).copied().collect();
(self.page(), uses, cached)
}
/// [`Self::run`], with how many times the scene encoded an image or a colorized image.
#[cfg(test)]
pub fn run_counting_encodes(mut self) -> (Page, usize) {
let doc = self.doc;
for l in &doc.layers {
self.node(l, false);
}
let encodes = self.encodes;
(self.page(), encodes)
}
pub fn run(mut self) -> Page {
let doc = self.doc;
for l in &doc.layers {
@@ -556,7 +592,7 @@ impl<'a> Scene<'a> {
if self.size() > self.max_body {
self.body.truncate(was);
self.unplace(placed);
self.forget_fields(codes);
self.forget_codes(codes);
self.warn(TOO_LARGE);
}
}
@@ -1439,24 +1475,21 @@ impl<'a> Scene<'a> {
self.place_image(i, place);
}
/// Forget the field images after the first `n` codes that no placement draws any longer, last
/// first, up to the first code that is drawn or isn't a field image.
fn forget_fields(&mut self, n: usize) {
while self.codes.len() > n {
let i = self.codes.len() - 1;
let Some(code) = self.codes.get(i) else { break };
if code.uses > 0 {
break;
}
let key = code.content_key();
let Some(bucket) = self.fields.get_mut(&key) else { break };
let Some(at) = bucket.iter().position(|&j| j == i) else { break };
bucket.swap_remove(at);
if bucket.is_empty() {
self.fields.remove(&key);
}
self.codes.pop();
/// Forget the encoded images after the first `n` codes that no placement draws any longer, and
/// the cache entries that name them: placed images, colorized images and fields. A code that a
/// placement still draws keeps itself and every code before it.
fn forget_codes(&mut self, n: usize) {
let keep = self.codes.iter().rposition(|c| c.uses > 0).map_or(n, |last| n.max(last + 1));
if keep >= self.codes.len() {
return;
}
self.codes.truncate(keep);
self.images.retain(|_, e| e.is_none_or(|i| i < keep));
self.colorized_images.retain(|_, e| e.is_none_or(|i| i < keep));
self.fields.retain(|_, bucket| {
bucket.retain(|&i| i < keep);
!bucket.is_empty()
});
}
/// A placed image (`blob`, cached under `key`): its pixel grid of `width` × `height` placed
@@ -1469,7 +1502,28 @@ impl<'a> Scene<'a> {
let encoded = match self.images.get(key) {
Some(e) => *e,
None => {
let e = self.decode_image(blob).and_then(|img| self.encode_image(img.as_raw(), img.width(), img.height())).map(|c| self.add_code(c));
// An image turned away at the page limit is encoded again only once it fits.
if let Some(&len) = self.too_large_images.get(key) {
if self.size().saturating_add(len).saturating_add(64) > self.max_body {
self.warn(TOO_LARGE);
return;
}
self.too_large_images.remove(key);
}
#[cfg(test)]
{
self.encodes += 1;
}
let code = self.decode_image(blob).and_then(|img| self.encode_image(img.as_raw(), img.width(), img.height()));
// An image that can't be placed isn't kept.
if let Some(c) = &code
&& self.size().saturating_add(c.inline_len).saturating_add(64) > self.max_body
{
self.too_large_images.insert(key.to_string(), c.inline_len);
self.warn(TOO_LARGE);
return;
}
let e = code.map(|c| self.add_code(c));
self.images.insert(key.to_string(), e);
e
}
@@ -1501,7 +1555,28 @@ impl<'a> Scene<'a> {
let encoded = match self.colorized_images.get(&cache) {
Some(e) => *e,
None => {
let e = self.encode_colorized(blob, paint).map(|c| self.add_code(c));
// An image turned away at the page limit is encoded again only once it fits.
if let Some(&len) = self.too_large_colorized.get(&cache) {
if self.size().saturating_add(len).saturating_add(64) > self.max_body {
self.warn(TOO_LARGE);
return;
}
self.too_large_colorized.remove(&cache);
}
#[cfg(test)]
{
self.encodes += 1;
}
let code = self.encode_colorized(blob, paint);
// An image that can't be placed isn't kept.
if let Some(c) = &code
&& self.size().saturating_add(c.inline_len).saturating_add(64) > self.max_body
{
self.too_large_colorized.insert(cache, c.inline_len);
self.warn(TOO_LARGE);
return;
}
let e = code.map(|c| self.add_code(c));
self.colorized_images.insert(cache, e);
e
}
+222
View File
@@ -1495,6 +1495,228 @@ fn a_field_taken_back_at_the_page_limit_leaves_no_image_behind() {
assert!(page.setup.contains("/VCim0 VCsrc") && !page.setup.contains("VCim1"), "{}", page.setup);
}
/// A 200 × 200 pt document holding 8 × 8 pixels of noise as image `pic` and a three-pixel gray ramp
/// as image `gray`, its first layer holding what `nodes` makes.
fn image_doc_with(nodes: impl FnOnce(&mut Document) -> Vec<Node>) -> Document {
let mut d = Document::new(200.0, 200.0);
let mut png = vec![];
noise(8, 8).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
d.images.insert("pic".into(), ImageBlob::new("image/png", png));
let mut gray = vec![];
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(3, 1, vec![0, 128, 255]).unwrap())
.write_to(&mut std::io::Cursor::new(&mut gray), image::ImageFormat::Png)
.unwrap();
d.images.insert("gray".into(), ImageBlob::png(gray));
let nodes = nodes(&mut d);
let layer = d.layers[0].id;
for n in nodes {
d.insert(Some(layer), usize::MAX, n).unwrap();
}
d
}
/// One of [`image_doc_with`]'s images: `pic`, or `gray` colorized in process red.
#[derive(Clone, Copy, Debug)]
enum Pic {
Placed,
Colorized,
}
/// An image of `pic` at (`x`, `y`), its pixels `scale` points wide.
fn pic_node(d: &mut Document, pic: Pic, x: f64, y: f64, scale: f64) -> Node {
let (key, width, height) = match pic {
Pic::Placed => ("pic", 8, 8),
Pic::Colorized => ("gray", 3, 1),
};
let im = ImageObject {
key: key.into(),
width,
height,
xf: Affine::translate((x, y)) * Affine::scale(scale),
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
if let Pic::Colorized = pic {
n.extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0))));
}
n
}
/// A pattern whose tile is an image of `pic` about 60 points wide.
fn pic_pattern(d: &mut Document, pic: Pic) -> Paint {
let scale = match pic {
Pic::Placed => 8.0,
Pic::Colorized => 20.0,
};
let tile = pic_node(d, pic, 0.0, 0.0, scale);
d.patterns.push(vectorcraft_doc::PatternDef::new("tile", vec![Arc::new(tile)]));
Paint::Pattern { pattern: "tile".into(), xf: Affine::IDENTITY }
}
/// A 2000-sided shape filled with each of `fills` in turn, and stroked in black when `stroked`.
fn many_sided(d: &mut Document, fills: &[Paint], stroked: bool) -> Node {
let stroke = if stroked { Paint::solid(Color::rgb(0.0, 0.0, 0.0)) } else { Paint::None };
let mut n = path(d, shapes::polygon(Point::new(100.0, 100.0), 90.0, 2000, 0.0), fills[0].clone(), stroke, 1.0);
let Some(AppearanceItem::Fill(first)) = n.appearance.items.first().cloned() else { panic!("a filled shape") };
for (k, paint) in fills.iter().enumerate().skip(1) {
let mut fill = first.clone();
fill.paint = paint.clone();
n.appearance.items.insert(k, AppearanceItem::Fill(fill));
}
n
}
/// A page limit that the many-sided shape of `build` (`true`: stroked) passes with its stroke and
/// not without it.
fn stroke_passes_the_limit(build: impl Fn(bool) -> Document, o: &EpsOptions) -> usize {
let fill = crate::scene::Scene::new(&build(false), o).run().body.len();
let both = crate::scene::Scene::new(&build(true), o).run().body.len();
assert!(both > fill + 20_000, "{fill} {both}");
fill + (both - fill) / 2
}
/// Art taken back for passing the page limit after it placed an image (a placed or a colorized
/// one) keeps no encoding of that image, and no cache entry names one. A later placement of the
/// image is encoded again and written where it is drawn, at both levels.
#[test]
fn a_rolled_back_node_frees_its_image_codes() {
for pic in [Pic::Placed, Pic::Colorized] {
for level in Level::ALL {
let case = format!("{pic:?}, {level:?}");
let build = |stroked: bool, after: bool| {
image_doc_with(|d| {
let fill = pic_pattern(d, pic);
let mut nodes = vec![many_sided(d, &[fill], stroked)];
if after {
nodes.push(pic_node(d, pic, 20.0, 20.0, 4.0));
}
nodes
})
};
let o = EpsOptions { level, ..opts(&build(false, false)) };
let limit = stroke_passes_the_limit(|stroked| build(stroked, false), &o);
let (page, uses, cached) = crate::scene::Scene::new(&build(true, false), &o).with_max_body(limit).run_with_codes();
assert!(page.warnings.iter().any(|w| w.contains("too large")), "{case}: {:?}", page.warnings);
assert_eq!((uses, cached), (vec![], vec![]), "{case}");
assert!(page.body.is_empty() && page.setup.is_empty(), "{case}: {} {}", page.setup, page.body);
let (page, uses, cached) = crate::scene::Scene::new(&build(true, true), &o).with_max_body(limit).run_with_codes();
assert_eq!((uses, cached), (vec![1], vec![0]), "{case}");
let alone = crate::scene::Scene::new(&image_doc_with(|d| vec![pic_node(d, pic, 20.0, 20.0, 4.0)]), &o).run();
assert_eq!(alone.body.matches("} exec\n").count(), 1, "{case}: {}", alone.body);
assert_eq!((&page.setup, &page.body), (&alone.setup, &alone.body), "{case}");
}
}
}
/// A field encoded before an image in art taken back for passing the page limit is forgotten with
/// it. Two later fields sampled the same share one image, the first one the page keeps.
#[test]
fn a_rolled_back_image_does_not_pin_an_earlier_field_code() {
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
for pic in [Pic::Placed, Pic::Colorized] {
for level in Level::ALL {
let case = format!("{pic:?}, {level:?}");
let build = |stroked: bool, after: bool| {
image_doc_with(|d| {
let field = freeform(&[(60.0, 100.0, Color::rgb(0.0, 1.0, 0.0)), (140.0, 100.0, red)]);
let fills = [field, pic_pattern(d, pic)];
let mut nodes = vec![many_sided(d, &fills, stroked)];
if after {
nodes.extend([freeform_square(d, 0.0, 0.0, 64.0, red, blue), freeform_square(d, 0.0, 0.0, 64.0, red, blue)]);
}
nodes
})
};
let o = EpsOptions { level, ..opts(&build(false, false)) };
let limit = stroke_passes_the_limit(|stroked| build(stroked, false), &o);
let (page, uses, cached) = crate::scene::Scene::new(&build(true, false), &o).with_max_body(limit).run_with_codes();
assert!(page.warnings.iter().any(|w| w.contains("too large")), "{case}: {:?}", page.warnings);
assert_eq!((uses, cached), (vec![], vec![]), "{case}");
let (page, uses, cached) = crate::scene::Scene::new(&build(true, true), &o).with_max_body(limit).run_with_codes();
assert_eq!((uses, cached), (vec![2], vec![0]), "{case}");
assert_eq!(reuses(&page.body, 0, level), 2, "{case}: {}", page.body);
let alone = doc_with(|d| vec![freeform_square(d, 0.0, 0.0, 64.0, red, blue), freeform_square(d, 0.0, 0.0, 64.0, red, blue)]);
let alone = crate::scene::Scene::new(&alone, &o).run();
assert_eq!((&page.setup, &page.body), (&alone.setup, &alone.body), "{case}");
}
}
}
/// An image whose first placement doesn't fit under the page limit is left out with a warning and
/// keeps no encoding, though the object that draws it fits. The art before it is written.
#[test]
fn an_image_rejected_by_the_page_limit_keeps_no_unused_code() {
for pic in [Pic::Placed, Pic::Colorized] {
for level in Level::ALL {
let case = format!("{pic:?}, {level:?}");
let d = image_doc_with(|d| vec![red_rect(d), pic_node(d, pic, 20.0, 20.0, 4.0)]);
let o = EpsOptions { level, ..opts(&d) };
let rect = crate::scene::Scene::new(&image_doc_with(|d| vec![red_rect(d)]), &o).run();
let full = crate::scene::Scene::new(&d, &o).run().body.len();
let (page, uses, cached) = crate::scene::Scene::new(&d, &o).with_max_body(full - 1).run_with_codes();
assert!(page.warnings.iter().any(|w| w.contains("too large")), "{case}: {:?}", page.warnings);
assert_eq!((uses, cached), (vec![], vec![]), "{case}");
assert_eq!((&page.setup, &page.body), (&rect.setup, &rect.body), "{case}");
}
}
}
/// An image turned away at the page limit is encoded once, not again at each later placement
/// that doesn't fit either.
#[test]
fn an_image_rejected_by_the_page_limit_is_encoded_once() {
for pic in [Pic::Placed, Pic::Colorized] {
for level in Level::ALL {
let case = format!("{pic:?}, {level:?}");
let d = image_doc_with(|d| {
let mut nodes = vec![red_rect(d)];
nodes.extend((0..50).map(|k| pic_node(d, pic, f64::from(k), 20.0, 4.0)));
nodes
});
let o = EpsOptions { level, ..opts(&d) };
let rect = crate::scene::Scene::new(&image_doc_with(|d| vec![red_rect(d)]), &o).run();
let (page, encodes) = crate::scene::Scene::new(&d, &o).with_max_body(rect.body.len() + 64).run_counting_encodes();
assert!(page.warnings.iter().any(|w| w.contains("too large")), "{case}: {:?}", page.warnings);
assert_eq!(encodes, 1, "{case}");
assert_eq!((&page.setup, &page.body), (&rect.setup, &rect.body), "{case}");
}
}
}
/// An image turned away at the page limit inside art that is then taken back is encoded again
/// once the page has room for it, and written where it is drawn.
#[test]
fn an_image_rejected_in_art_taken_back_is_encoded_again_when_it_fits() {
for pic in [Pic::Placed, Pic::Colorized] {
for level in Level::ALL {
let case = format!("{pic:?}, {level:?}");
let build = |stroked: bool, after: bool| {
image_doc_with(|d| {
let fill = pic_pattern(d, pic);
let mut nodes = vec![many_sided(d, &[fill], stroked)];
if after {
nodes.push(pic_node(d, pic, 20.0, 20.0, 4.0));
}
nodes
})
};
let o = EpsOptions { level, ..opts(&build(false, false)) };
let solid = image_doc_with(|d| vec![many_sided(d, &[Paint::solid(Color::rgb(1.0, 0.0, 0.0))], false)]);
// The shape's outline fits under this limit, and its first tile of the image doesn't.
let limit = crate::scene::Scene::new(&solid, &o).run().body.len() + 64;
let (page, encodes) = crate::scene::Scene::new(&build(false, false), &o).with_max_body(limit).run_counting_encodes();
assert!(page.warnings.iter().any(|w| w.contains("too large")), "{case}: {:?}", page.warnings);
assert_eq!((encodes, page.body.matches("} exec\n").count()), (1, 0), "{case}: {}", page.body);
let (page, encodes) = crate::scene::Scene::new(&build(true, true), &o).with_max_body(limit).run_counting_encodes();
assert_eq!(encodes, 2, "{case}");
let alone = crate::scene::Scene::new(&image_doc_with(|d| vec![pic_node(d, pic, 20.0, 20.0, 4.0)]), &o).run();
assert_eq!((&page.setup, &page.body), (&alone.setup, &alone.body), "{case}");
}
}
}
#[test]
fn run_length_and_ascii85_round_trip() {
let cycle: Vec<u8> = (0..=255u8).cycle().take(1000).collect();
+1
View File
@@ -10,6 +10,7 @@ workspace = true
[dependencies]
vectorcraft-doc = { workspace = true }
vectorcraft-brush = { workspace = true }
craft-vectorcraft-format = { workspace = true }
serde ={ workspace = true }
serde_json = { workspace = true }
+44 -8
View File
@@ -52,6 +52,7 @@ use std::sync::Arc;
use craft_vectorcraft_format::{Contents, Head, Image, ReadError, Tail};
use serde::de::{DeserializeSeed, IgnoredAny, MapAccess, SeqAccess, Visitor};
use serde::{Deserializer, Serialize};
use vectorcraft_brush::stored_art::StoredArt;
use vectorcraft_doc::{Document, ImageBlob};
#[cfg(not(target_arch = "wasm32"))]
@@ -243,18 +244,20 @@ fn body(doc: &Document, o: &SaveOptions) -> Result<Body, FormatError> {
// version reads them.
d.guides_to_saved();
// Older apps don't know placed documents: they get the art the objects show, with its
// resources. Otherwise resources only exporting adds are never saved.
if version < VERSION && d.has_placed() {
d = d.with_placed_art().into_owned();
d.placed_as_groups();
} else {
d.drop_placed_resources();
}
// resources. Otherwise resources only exporting adds are never saved. The images and placed
// documents in the stored brushes' art count as those in the layers do.
let linked = with_brush_art(&mut d, |d| {
if version < VERSION {
placed_as_groups(d);
} else {
d.drop_placed_resources();
}
d.linked_only_images()
});
// The art placed documents became for older versions is rounded too.
if let Some(decimals) = o.precision {
d.round_geometry(decimals.min(MAX_PRECISION));
}
let linked = d.linked_only_images();
// The blobs go in the file's `images` (only those the document uses).
let blobs = std::mem::take(&mut d.images);
if version < 3 {
@@ -277,6 +280,39 @@ fn body(doc: &Document, o: &SaveOptions) -> Result<Body, FormatError> {
Ok(Body { d, v1, blobs, linked })
}
/// `f` run on `d` with the art of its stored brushes set on it with the ids it is stored with
/// ([`StoredArt::mount_as_stored`]); the brushes whose art `f` changed are then written back into
/// the library, and the art is taken off `d` again. `f` runs on `d` as it is when no stored brush's
/// art holds an image or a placed document, or when art is set on `d` already.
pub fn with_brush_art<T>(d: &mut Document, f: impl FnOnce(&mut Document) -> T) -> T {
if !d.mounted_art.is_empty() {
return f(d);
}
let art = StoredArt::read(d);
if art.is_empty() {
return f(d);
}
art.mount_as_stored(d);
let out = f(d);
art.write_back(d);
out
}
/// Every placed document in `d`'s art, the art of its stored brushes included, replaced by a group
/// of the art it shows, with the resources that art uses, as a save for a version older than
/// [`VERSION`] writes it. Without a placed document, the resources only exporting adds are dropped
/// ([`Document::drop_placed_resources`]).
pub fn placed_as_groups(d: &mut Document) {
with_brush_art(d, |d| {
if d.has_placed() {
*d = d.with_placed_art().into_owned();
d.placed_as_groups();
} else {
d.drop_placed_resources();
}
});
}
/// Serialize a document (pretty = human-diffable) in the current version. Editing-mode working
/// copies are left out ([`Document::without_edit_modes`]).
pub fn save(doc: &Document, pretty: bool) -> Vec<u8> {
+94 -2
View File
@@ -4,8 +4,9 @@
use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::{Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind};
use vectorcraft_format::{base64_decode, load, save};
use vectorcraft_brush::{Brush, BrushKind, PatternBrush, Scatter};
use vectorcraft_doc::{Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind};
use vectorcraft_format::{SaveOptions, base64_decode, load, save, save_with};
use vectorcraft_geom::Affine;
fn image(d: &mut Document, key: &str, link: Option<LinkInfo>) {
@@ -59,3 +60,94 @@ fn link_details_round_trip_and_linked_only_images_save_their_preview() {
let again: Value = serde_json::from_slice(&save(&back, false)).unwrap();
assert_eq!(again["images"]["linked"], v["images"]["linked"]);
}
/// An image object for a stored brush's art.
fn brush_image(key: &str, link: Option<LinkInfo>) -> Node {
let im = ImageObject { key: key.into(), width: 600, height: 300, xf: Affine::IDENTITY, link, placement: Default::default(), pixels: None };
Node::new(NodeId(0), NodeKind::Image(Box::new(im)))
}
/// Stores a scatter brush with `scatter` as its art and a pattern brush with `tile` as its side tile.
fn brushes(d: &mut Document, scatter: Node, tile: Node) {
vectorcraft_brush::store(
d,
&[
Brush { name: "Dots".into(), kind: BrushKind::Scatter(Scatter { art: scatter, ..Default::default() }) },
Brush { name: "Frame".into(), kind: BrushKind::Pattern(PatternBrush { side: tile, ..Default::default() }) },
],
);
}
/// `key`'s entry in the saved file `v`: its bytes and its `proxy` flag.
fn saved_image(v: &Value, key: &str) -> (Vec<u8>, Value) {
(base64_decode(v["images"][key]["data"].as_str().unwrap()).unwrap(), v["images"][key]["proxy"].clone())
}
/// A linked image shown only in a stored brush's art (a scatter brush's art, a pattern brush's tile)
/// is saved as its preview, as one in the layers is, and with Include Linked Files as its file's
/// bytes; the brushes are saved as they were, their links kept.
#[test]
fn brush_only_link_saves_preview_unless_included() {
let mut d = Document::new(100.0, 100.0);
d.images.insert("dot".into(), blob(&[1, 2, 3], Some(&[9])));
d.images.insert("tile".into(), blob(&[4, 5, 6], Some(&[8])));
brushes(&mut d, brush_image("dot", Some(LinkInfo::new("/work/dot.jpg"))), brush_image("tile", Some(LinkInfo::new("/work/tile.jpg"))));
let stored = d.unknown[vectorcraft_brush::DOC_KEY].clone();
let bytes = save(&d, false);
let v: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(saved_image(&v, "dot"), (vec![9], Value::Bool(true)));
assert_eq!(saved_image(&v, "tile"), (vec![8], Value::Bool(true)));
let back = load(&bytes).unwrap();
assert_eq!(back.unknown[vectorcraft_brush::DOC_KEY], stored, "the brushes are saved as they were");
assert!(back.mounted_art.is_empty());
let mut links = vec![];
for b in vectorcraft_brush::library(&back) {
for art in b.art() {
art.walk(&mut |n| {
if let NodeKind::Image(im) = &n.kind {
links.extend(im.link.as_ref().map(|l| l.path.clone()));
}
});
}
}
links.sort();
assert_eq!(links, ["/work/dot.jpg", "/work/tile.jpg"]);
let included = save_with(&d, &SaveOptions { include_linked: true, ..SaveOptions::default() }).unwrap();
let v: Value = serde_json::from_slice(&included).unwrap();
assert_eq!(saved_image(&v, "dot"), (vec![1, 2, 3], Value::Null));
assert_eq!(saved_image(&v, "tile"), (vec![4, 5, 6], Value::Null));
}
/// An image key shown linked in one place and embedded in another keeps its full bytes, whichever
/// of the layers and a stored brush's art embeds it; the links stay as they were.
#[test]
fn shared_brush_image_key_keeps_full_bytes_for_embedded_use() {
for layer_linked in [true, false] {
let mut d = Document::new(100.0, 100.0);
d.images.insert("k".into(), blob(&[1, 2, 3], Some(&[9])));
let link = Some(LinkInfo::new("/work/k.jpg"));
let (in_layer, in_brush) = if layer_linked { (link, None) } else { (None, link) };
image(&mut d, "k", in_layer.clone());
brushes(&mut d, brush_image("k", in_brush.clone()), brush_image("k", in_brush.clone()));
let bytes = save(&d, false);
let v: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(saved_image(&v, "k"), (vec![1, 2, 3], Value::Null), "linked in the layer: {layer_linked}");
let back = load(&bytes).unwrap();
let mut layer_links = vec![];
for l in &back.layers {
l.walk(&mut |n| {
if let NodeKind::Image(im) = &n.kind {
layer_links.push(im.link.clone());
}
});
}
assert_eq!(layer_links, [in_layer]);
let brush_links: Vec<Option<LinkInfo>> = vectorcraft_brush::library(&back)
.iter()
.flat_map(|b| b.art().into_iter().map(|n| if let NodeKind::Image(im) = &n.kind { im.link.clone() } else { None }).collect::<Vec<_>>())
.collect();
assert_eq!(brush_links, [in_brush.clone(), in_brush]);
}
}
+38
View File
@@ -212,6 +212,44 @@ fn text_composer_round_trips() {
assert!(!String::from_utf8_lossy(&save(&d2, false)).contains("composer"));
}
/// Every composer reads back as it was saved (the two Standard ones as their own values), and the
/// ME&SA names are the ones files have always used: `everyLine` stays the unwritten default and
/// `singleLine` keeps its spelling, so a document that never picks a Standard composer is unchanged.
#[test]
fn all_four_composers_round_trip() {
use vectorcraft_doc::{TextKind, TextObject};
let one = |c: Composer| {
let mut d = Document::new(200.0, 200.0);
let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "ક\u{ACD}ક", Default::default());
t.para.composer = c;
t.kind = TextKind::Point;
let id = d.alloc_id();
d.insert(None, usize::MAX, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
d
};
for (c, written) in [
(Composer::SingleLine, Some("singleLine")),
(Composer::EveryLine, None),
(Composer::StandardSingleLine, Some("standardSingleLine")),
(Composer::StandardEveryLine, Some("standardEveryLine")),
] {
let bytes = save(&one(c), false);
let text = String::from_utf8_lossy(&bytes);
match written {
Some(w) => assert!(text.contains(&format!("\"composer\":\"{w}\"")), "{c:?}"),
None => assert!(!text.contains("\"composer\""), "{c:?}"),
}
let back = load(&bytes).unwrap();
let mut got = None;
back.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
got = Some(t.para.composer);
}
});
assert_eq!(got, Some(c));
}
}
/// A document as the first version wrote it (format name `drawcraft`, anchors as maps).
const V1_FILE: &str = r#"{"format":"drawcraft","version":1,"generator":"DrawCraft 0.1.0","document":{"version":1,"title":"Old","artboards":[{"id":1,"name":"Artboard 1","rect":{"x0":0.0,"y0":0.0,"x1":100.0,"y1":80.0}}],
"layers":[{"id":1,"name":"Layer 1","visible":true,"locked":false,"opacity":1.0,"kind":{"type":"layer","children":[
+790
View File
@@ -0,0 +1,790 @@
//! The anchors of a subpath, held in shared chunks.
//!
//! [`Anchors`] keeps its anchors in chunks of at most [`CHUNK`] anchors, each behind an `Arc`.
//! Copying the list copies the table of chunks and shares the chunks themselves; changing an
//! anchor copies only the chunk that holds it when another copy still shares that chunk. An undo
//! step that keeps the version of a path before a one-anchor edit then keeps one chunk of its
//! own, however many anchors the path has. Inserting or removing an anchor copies the chunk it is
//! in and rebuilds the table, which has one entry per chunk.
//!
//! The list reads and writes as one flat sequence of anchors, as a `Vec<Anchor>` does.
use std::borrow::Cow;
use std::fmt;
use std::ops::{Index, IndexMut, RangeBounds};
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use crate::path::Anchor;
/// An [`Anchors`] list of the anchors given, as `vec!` makes a `Vec`.
#[macro_export]
macro_rules! anchors {
($($t:tt)*) => {
$crate::Anchors::from(vec![$($t)*])
};
}
/// Most anchors one chunk holds.
pub const CHUNK: usize = 256;
/// The anchors of a subpath: a sequence with the reads of a slice and the edits of a `Vec`, whose
/// copies share the chunks they have not changed.
#[derive(Clone, Default)]
pub struct Anchors {
/// The chunks in order, none of them empty.
chunks: Vec<Arc<Vec<Anchor>>>,
/// Empty while every chunk but the last holds [`CHUNK`] anchors (anchor `i` is then in chunk
/// `i / CHUNK`). Otherwise `ends[c]` is the number of anchors in chunks `0..=c`.
ends: Vec<usize>,
/// The number of anchors.
len: usize,
}
impl Anchors {
/// An empty list.
pub const fn new() -> Self {
Self { chunks: Vec::new(), ends: Vec::new(), len: 0 }
}
/// The number of anchors.
pub fn len(&self) -> usize {
self.len
}
/// Whether the list has no anchors.
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// The chunk that holds anchor `i` and its place in that chunk. For `i` at or past the end the
/// chunk or the place is out of range.
fn locate(&self, i: usize) -> (usize, usize) {
if self.ends.is_empty() {
(i / CHUNK, i % CHUNK)
} else {
let c = self.ends.partition_point(|&e| e <= i);
let start = c.checked_sub(1).and_then(|p| self.ends.get(p)).copied().unwrap_or(0);
(c, i.saturating_sub(start))
}
}
/// Anchor `i`, or `None` past the end.
pub fn get(&self, i: usize) -> Option<&Anchor> {
if i >= self.len {
return None;
}
let (c, o) = self.locate(i);
self.chunks.get(c)?.get(o)
}
/// Anchor `i` to change, or `None` past the end. Copies the chunk that holds it when another
/// list shares that chunk.
pub fn get_mut(&mut self, i: usize) -> Option<&mut Anchor> {
if i >= self.len {
return None;
}
let (c, o) = self.locate(i);
Arc::make_mut(self.chunks.get_mut(c)?).get_mut(o)
}
/// The first anchor.
pub fn first(&self) -> Option<&Anchor> {
self.chunks.first()?.first()
}
/// The last anchor.
pub fn last(&self) -> Option<&Anchor> {
self.chunks.last()?.last()
}
/// The first anchor to change.
pub fn first_mut(&mut self) -> Option<&mut Anchor> {
Arc::make_mut(self.chunks.first_mut()?).first_mut()
}
/// The last anchor to change.
pub fn last_mut(&mut self) -> Option<&mut Anchor> {
Arc::make_mut(self.chunks.last_mut()?).last_mut()
}
/// The anchors in order.
pub fn iter(&self) -> Iter<'_> {
let (front, back): (&[Anchor], &[Anchor]) = (&[], &[]);
Iter { chunks: self.chunks.iter(), front: front.iter(), back: back.iter(), left: self.len }
}
/// The anchors in order, to change. Each chunk is copied, when another list shares it, as the
/// iterator reaches it.
pub fn iter_mut(&mut self) -> IterMut<'_> {
let chunk: fn(&mut Arc<Vec<Anchor>>) -> std::slice::IterMut<'_, Anchor> = |c| Arc::make_mut(c).iter_mut();
self.chunks.iter_mut().flat_map(chunk)
}
/// The anchors as one slice: borrowed when they are in one chunk, copied otherwise.
pub fn contiguous(&self) -> Cow<'_, [Anchor]> {
match self.chunks.as_slice() {
[] => Cow::Borrowed(&[]),
[one] => Cow::Borrowed(one.as_slice()),
_ => Cow::Owned(self.to_vec()),
}
}
/// The anchors in `range` copied into a `Vec`, or `None` when the range is out of bounds or
/// starts after it ends (as `slice::get` with a range).
pub fn get_range(&self, range: impl RangeBounds<usize>) -> Option<Vec<Anchor>> {
use std::ops::Bound;
let start = match range.start_bound() {
Bound::Included(&s) => s,
Bound::Excluded(&s) => s.checked_add(1)?,
Bound::Unbounded => 0,
};
let end = match range.end_bound() {
Bound::Included(&e) => e.checked_add(1)?,
Bound::Excluded(&e) => e,
Bound::Unbounded => self.len,
};
(start <= end && end <= self.len).then(|| self.iter().skip(start).take(end - start).copied().collect())
}
/// The anchors copied into a `Vec`.
pub fn to_vec(&self) -> Vec<Anchor> {
let mut v = Vec::with_capacity(self.len);
for c in &self.chunks {
v.extend_from_slice(c);
}
v
}
/// The anchors as a `Vec`, without a copy when they are in one chunk no other list shares.
pub fn into_vec(mut self) -> Vec<Anchor> {
if self.chunks.len() == 1
&& let Some(one) = self.chunks.pop()
{
return Arc::try_unwrap(one).unwrap_or_else(|shared| (*shared).clone());
}
self.to_vec()
}
/// Change the anchors as a `Vec` (for edits that move many of them, such as reversing).
pub fn with_vec<R>(&mut self, f: impl FnOnce(&mut Vec<Anchor>) -> R) -> R {
let mut v = std::mem::take(self).into_vec();
let r = f(&mut v);
*self = Self::from(v);
r
}
/// Rebuild `ends` and `len` after the chunks changed, dropping empty chunks.
fn reindex(&mut self) {
self.chunks.retain(|c| !c.is_empty());
self.len = self.chunks.iter().map(|c| c.len()).sum();
let n = self.chunks.len();
let uniform = self.chunks.iter().enumerate().all(|(k, c)| if k + 1 == n { c.len() <= CHUNK } else { c.len() == CHUNK });
self.ends.clear();
if !uniform {
let mut total = 0;
self.ends.extend(self.chunks.iter().map(|c| {
total += c.len();
total
}));
}
}
/// Add `a` at the end.
pub fn push(&mut self, a: Anchor) {
match self.chunks.last_mut() {
Some(last) if last.len() < CHUNK => Arc::make_mut(last).push(a),
_ => {
self.chunks.push(Arc::new(vec![a]));
if !self.ends.is_empty() {
self.ends.push(self.len);
}
}
}
self.len += 1;
if let Some(end) = self.ends.last_mut() {
*end = self.len;
}
}
/// Remove the last anchor.
pub fn pop(&mut self) -> Option<Anchor> {
let last = self.chunks.last_mut()?;
let a = Arc::make_mut(last).pop();
if last.is_empty() {
self.chunks.pop();
self.ends.pop();
}
self.len = self.len.saturating_sub(1);
if let Some(end) = self.ends.last_mut() {
*end = self.len;
}
a
}
/// Insert `a` before anchor `i`, or at the end when `i` is the length or more.
pub fn insert(&mut self, i: usize, a: Anchor) {
if i >= self.len {
self.push(a);
return;
}
let (c, o) = self.locate(i);
let Some(chunk) = self.chunks.get_mut(c) else { return };
let chunk = Arc::make_mut(chunk);
chunk.insert(o.min(chunk.len()), a);
if chunk.len() > CHUNK {
let tail = chunk.split_off(chunk.len() / 2);
self.chunks.insert(c + 1, Arc::new(tail));
}
self.reindex();
}
/// Remove anchor `i`, or `None` past the end.
pub fn try_remove(&mut self, i: usize) -> Option<Anchor> {
if i >= self.len {
return None;
}
let (c, o) = self.locate(i);
let chunk = Arc::make_mut(self.chunks.get_mut(c)?);
let a = (o < chunk.len()).then(|| chunk.remove(o));
// A chunk left small joins the next one when the two fit in one chunk.
if chunk.len() < CHUNK / 4
&& let Some(next) = self.chunks.get(c + 1)
&& self.chunks.get(c).map_or(0, |c| c.len()) + next.len() <= CHUNK
{
let next = self.chunks.remove(c + 1);
if let Some(chunk) = self.chunks.get_mut(c) {
Arc::make_mut(chunk).extend_from_slice(&next);
}
}
self.reindex();
a
}
/// Remove anchor `i`. Panics past the end, as `Vec::remove` does.
pub fn remove(&mut self, i: usize) -> Anchor {
match self.try_remove(i) {
Some(a) => a,
None => {
let none: &[Anchor] = &[];
none[i]
}
}
}
/// Keep the first `n` anchors.
pub fn truncate(&mut self, n: usize) {
if n >= self.len {
return;
}
let (c, o) = self.locate(n);
self.chunks.truncate(c + 1);
if let Some(last) = self.chunks.last_mut() {
Arc::make_mut(last).truncate(o);
}
self.reindex();
}
/// Remove every anchor.
pub fn clear(&mut self) {
*self = Self::new();
}
/// Add the anchors of `s` at the end.
pub fn extend_from_slice(&mut self, s: &[Anchor]) {
self.extend(s.iter().copied());
}
/// Keep the anchors for which `f` is true.
pub fn retain(&mut self, f: impl FnMut(&Anchor) -> bool) {
self.with_vec(|v| v.retain(f));
}
/// Keep the anchors for which `f` is true, letting `f` change them.
pub fn retain_mut(&mut self, f: impl FnMut(&mut Anchor) -> bool) {
self.with_vec(|v| v.retain_mut(f));
}
/// Reverse the order of the anchors.
pub fn reverse(&mut self) {
self.with_vec(|v| v.reverse());
}
/// Rotate the anchors `k` places towards the start.
pub fn rotate_left(&mut self, k: usize) {
self.with_vec(|v| v.rotate_left(k));
}
/// Rotate the anchors `k` places towards the end.
pub fn rotate_right(&mut self, k: usize) {
self.with_vec(|v| v.rotate_right(k));
}
/// Remove the anchors in `range` and return them.
pub fn drain(&mut self, range: impl RangeBounds<usize>) -> std::vec::IntoIter<Anchor> {
self.with_vec(|v| v.drain(range).collect::<Vec<_>>()).into_iter()
}
/// Replace the anchors in `range` with those of `with`, and return the anchors replaced.
pub fn splice(&mut self, range: impl RangeBounds<usize>, with: impl IntoIterator<Item = Anchor>) -> std::vec::IntoIter<Anchor> {
self.with_vec(|v| v.splice(range, with).collect::<Vec<_>>()).into_iter()
}
/// The pairs of anchors in the same place in `self` and `other`, with that place, in order.
/// When the two are chunked alike, the chunks they share in the same place are skipped (their
/// anchors are the same); otherwise every pair is visited. Stops at the end of the shorter list.
pub fn pairs_not_shared<'a>(&'a self, other: &'a Self) -> impl Iterator<Item = (usize, &'a Anchor, &'a Anchor)> + 'a {
let alike = self.len == other.len && self.chunks.len() == other.chunks.len() && self.ends == other.ends;
let chunked = alike.then(|| {
let starts = self.chunks.iter().scan(0, |start, c| {
let at = *start;
*start += c.len();
Some(at)
});
starts
.zip(self.chunks.iter().zip(&other.chunks))
.filter(|(_, (a, b))| !Arc::ptr_eq(a, b))
.flat_map(|(at, (a, b))| a.iter().zip(b.iter()).enumerate().map(move |(o, (x, y))| (at + o, x, y)))
});
let flat = (!alike).then(|| self.iter().zip(other.iter()).enumerate().map(|(i, (a, b))| (i, a, b)));
chunked.into_iter().flatten().chain(flat.into_iter().flatten())
}
/// Each chunk's address and capacity (in anchors): two lists hold a chunk in common when they
/// give the same address. For memory estimates.
pub fn chunk_allocations(&self) -> impl Iterator<Item = (usize, usize)> + '_ {
self.chunks.iter().map(|c| (Arc::as_ptr(c) as usize, c.capacity()))
}
/// The bytes the list's own tables hold on the heap (the chunk table and the running totals),
/// without the chunks.
pub fn table_bytes(&self) -> usize {
self.chunks.capacity() * size_of::<Arc<Vec<Anchor>>>() + self.ends.capacity() * size_of::<usize>()
}
}
/// [`Anchors::iter_mut`]'s iterator.
pub type IterMut<'a> = std::iter::FlatMap<
std::slice::IterMut<'a, Arc<Vec<Anchor>>>,
std::slice::IterMut<'a, Anchor>,
fn(&mut Arc<Vec<Anchor>>) -> std::slice::IterMut<'_, Anchor>,
>;
/// [`Anchors::iter`]'s iterator.
#[derive(Clone)]
pub struct Iter<'a> {
/// The chunks neither end has reached.
chunks: std::slice::Iter<'a, Arc<Vec<Anchor>>>,
/// What is left of the chunk the front is in.
front: std::slice::Iter<'a, Anchor>,
/// What is left of the chunk the back is in.
back: std::slice::Iter<'a, Anchor>,
/// The anchors left.
left: usize,
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a Anchor;
fn next(&mut self) -> Option<&'a Anchor> {
loop {
if let Some(a) = self.front.next() {
self.left -= 1;
return Some(a);
}
match self.chunks.next() {
Some(c) => self.front = c.iter(),
None => {
let a = self.back.next()?;
self.left -= 1;
return Some(a);
}
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.left, Some(self.left))
}
fn nth(&mut self, mut n: usize) -> Option<&'a Anchor> {
// Whole chunks are skipped without visiting their anchors.
loop {
let f = self.front.len();
if n < f {
self.left -= n + 1;
return self.front.nth(n);
}
n -= f;
self.left -= f;
self.front = Default::default();
match self.chunks.as_slice().first() {
Some(c) if c.len() <= n => {
n -= c.len();
self.left -= c.len();
self.chunks.next();
}
Some(_) => {
if let Some(c) = self.chunks.next() {
self.front = c.iter();
}
}
None => {
let b = self.back.len();
if n < b {
self.left -= n + 1;
return self.back.nth(n);
}
self.left -= b;
self.back = Default::default();
return None;
}
}
}
}
fn count(self) -> usize {
self.left
}
fn last(mut self) -> Option<&'a Anchor> {
self.next_back()
}
}
impl<'a> DoubleEndedIterator for Iter<'a> {
fn next_back(&mut self) -> Option<&'a Anchor> {
loop {
if let Some(a) = self.back.next_back() {
self.left -= 1;
return Some(a);
}
match self.chunks.next_back() {
Some(c) => self.back = c.iter(),
None => {
let a = self.front.next_back()?;
self.left -= 1;
return Some(a);
}
}
}
}
}
impl ExactSizeIterator for Iter<'_> {}
impl std::iter::FusedIterator for Iter<'_> {}
impl Index<usize> for Anchors {
type Output = Anchor;
/// Anchor `i`. Panics past the end, as indexing a slice does.
fn index(&self, i: usize) -> &Anchor {
let (c, o) = self.locate(i);
&self.chunks[c][o]
}
}
impl IndexMut<usize> for Anchors {
/// Anchor `i` to change ([`Anchors::get_mut`]). Panics past the end, as indexing a slice does.
fn index_mut(&mut self, i: usize) -> &mut Anchor {
let (c, o) = self.locate(i);
&mut Arc::make_mut(&mut self.chunks[c])[o]
}
}
impl From<Vec<Anchor>> for Anchors {
fn from(v: Vec<Anchor>) -> Self {
if v.is_empty() {
return Self::new();
}
let len = v.len();
let chunks = if len <= CHUNK { vec![Arc::new(v)] } else { v.chunks(CHUNK).map(|c| Arc::new(c.to_vec())).collect() };
Self { chunks, ends: Vec::new(), len }
}
}
impl From<&[Anchor]> for Anchors {
fn from(s: &[Anchor]) -> Self {
Self::from(s.to_vec())
}
}
impl<const N: usize> From<[Anchor; N]> for Anchors {
fn from(s: [Anchor; N]) -> Self {
Self::from(Vec::from(s))
}
}
impl From<Anchors> for Vec<Anchor> {
fn from(a: Anchors) -> Self {
a.into_vec()
}
}
impl FromIterator<Anchor> for Anchors {
fn from_iter<I: IntoIterator<Item = Anchor>>(it: I) -> Self {
Self::from(it.into_iter().collect::<Vec<_>>())
}
}
impl Extend<Anchor> for Anchors {
fn extend<I: IntoIterator<Item = Anchor>>(&mut self, it: I) {
for a in it {
self.push(a);
}
}
}
impl<'a> Extend<&'a Anchor> for Anchors {
fn extend<I: IntoIterator<Item = &'a Anchor>>(&mut self, it: I) {
self.extend(it.into_iter().copied());
}
}
impl<'a> IntoIterator for &'a Anchors {
type Item = &'a Anchor;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Iter<'a> {
self.iter()
}
}
impl<'a> IntoIterator for &'a mut Anchors {
type Item = &'a mut Anchor;
type IntoIter = IterMut<'a>;
fn into_iter(self) -> IterMut<'a> {
self.iter_mut()
}
}
impl IntoIterator for Anchors {
type Item = Anchor;
type IntoIter = std::vec::IntoIter<Anchor>;
fn into_iter(self) -> std::vec::IntoIter<Anchor> {
self.into_vec().into_iter()
}
}
impl PartialEq for Anchors {
fn eq(&self, other: &Self) -> bool {
self.len == other.len && self.iter().eq(other.iter())
}
}
impl PartialEq<[Anchor]> for Anchors {
fn eq(&self, other: &[Anchor]) -> bool {
self.len == other.len() && self.iter().eq(other.iter())
}
}
impl PartialEq<&[Anchor]> for Anchors {
fn eq(&self, other: &&[Anchor]) -> bool {
*self == **other
}
}
impl PartialEq<Vec<Anchor>> for Anchors {
fn eq(&self, other: &Vec<Anchor>) -> bool {
*self == **other
}
}
impl<const N: usize> PartialEq<[Anchor; N]> for Anchors {
fn eq(&self, other: &[Anchor; N]) -> bool {
*self == other[..]
}
}
impl PartialEq<Anchors> for [Anchor] {
fn eq(&self, other: &Anchors) -> bool {
*other == *self
}
}
impl PartialEq<Anchors> for Vec<Anchor> {
fn eq(&self, other: &Anchors) -> bool {
*other == **self
}
}
impl fmt::Debug for Anchors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl Serialize for Anchors {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_seq(self.iter())
}
}
impl<'de> Deserialize<'de> for Anchors {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Vec::<Anchor>::deserialize(d).map(Self::from)
}
}
#[cfg(test)]
mod tests {
use kurbo::Point;
use super::*;
fn line(n: usize) -> Vec<Anchor> {
(0..n).map(|i| Anchor::corner(Point::new(i as f64, (i % 7) as f64))).collect()
}
/// Chunks of `a` that `b` does not hold, with their capacity in anchors.
fn own_chunks(a: &Anchors, b: &Anchors) -> Vec<usize> {
let theirs: Vec<usize> = b.chunk_allocations().map(|(id, _)| id).collect();
a.chunk_allocations().filter(|(id, _)| !theirs.contains(id)).map(|(_, cap)| cap).collect()
}
#[test]
fn editing_one_anchor_copies_one_chunk_whatever_the_length() {
for n in [10_000, 200_000] {
let before = Anchors::from(line(n));
let mut after = before.clone();
after[n / 2].p = Point::new(-1.0, -1.0);
if let Some(a) = after.get_mut(n / 2 + 1) {
a.h_out = Point::new(-2.0, -2.0);
}
let copied = own_chunks(&after, &before);
assert_eq!(copied.len(), 1, "{n} anchors: one chunk copied");
assert!(copied.iter().all(|&cap| cap <= CHUNK), "{n} anchors: {copied:?}");
assert_eq!(own_chunks(&before, &after).len(), 1, "{n} anchors: the old version keeps one chunk of its own");
// The old version is as it was; the new one differs only at the two anchors.
assert_eq!(before, line(n));
let mut expected = line(n);
expected[n / 2].p = Point::new(-1.0, -1.0);
expected[n / 2 + 1].h_out = Point::new(-2.0, -2.0);
assert_eq!(after, expected);
}
}
#[test]
fn inserting_and_removing_copy_only_the_chunk_touched() {
let n = 200_000;
let before = Anchors::from(line(n));
let mut after = before.clone();
let extra = Anchor::corner(Point::new(0.5, 0.5));
after.insert(n / 2, extra);
assert!(own_chunks(&after, &before).len() <= 2, "the chunk split in two");
assert_eq!(after.len(), n + 1);
assert_eq!(after[n / 2], extra);
assert_eq!(after[n / 2 + 1], line(n)[n / 2]);
assert_eq!(after.remove(n / 2), extra);
assert_eq!(after, line(n));
assert!(own_chunks(&after, &before).len() <= 2);
assert_eq!(before, line(n));
}
#[test]
fn acts_as_a_vec_through_edits() {
// A run of edits applied to an `Anchors` and to a `Vec` leaves the two the same, across
// chunk splits, joins and the uniform and non-uniform layouts.
let mut v = line(700);
let mut a = Anchors::from(v.clone());
let mut seed = 7u64;
let mut next = |m: usize| {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(seed >> 33) as usize % m.max(1)
};
for step in 0..3000 {
let x = Anchor::corner(Point::new(step as f64, 0.25));
match next(8) {
0 | 1 => {
let i = next(v.len() + 1);
v.insert(i, x);
a.insert(i, x);
}
2 | 3 if !v.is_empty() => {
let i = next(v.len());
assert_eq!(v.remove(i), a.remove(i));
}
4 => {
v.push(x);
a.push(x);
}
5 => assert_eq!(v.pop(), a.pop()),
6 if !v.is_empty() => {
let i = next(v.len());
v[i].h_in = x.p;
a[i].h_in = x.p;
}
_ => {
let keep = v.len().saturating_sub(next(3));
v.truncate(keep);
a.truncate(keep);
}
}
assert_eq!(a.len(), v.len(), "step {step}");
if step % 50 == 0 {
assert_eq!(a, v, "step {step}");
for i in 0..v.len() {
assert_eq!(a.get(i), v.get(i), "step {step}, anchor {i}");
}
}
}
assert_eq!(a, v);
assert_eq!(a.iter().rev().copied().collect::<Vec<_>>(), v.iter().rev().copied().collect::<Vec<_>>());
assert_eq!(a.get(v.len()), None);
}
#[test]
fn iterators_skip_and_count_as_a_slice_does() {
let v = line(1000);
let a = Anchors::from(v.clone());
for skip in [0, 1, 255, 256, 257, 999, 1000, 1001] {
assert_eq!(a.iter().nth(skip), v.get(skip), "nth {skip}");
assert_eq!(a.iter().skip(skip).count(), v.iter().skip(skip).count(), "skip {skip}");
assert_eq!(a.iter().skip(skip).len(), v.iter().skip(skip).len(), "len after {skip}");
}
let mut both = a.iter();
let mut vs = v.iter();
for k in 0..1000 {
let (x, y) = if k % 3 == 0 { (both.next_back(), vs.next_back()) } else { (both.next(), vs.next()) };
assert_eq!(x, y, "step {k}");
assert_eq!(both.len(), vs.len());
}
assert_eq!(both.next(), None);
assert_eq!(a.iter().last(), v.last());
let mut m = a.clone();
m.iter_mut().for_each(|x| x.p.x += 1.0);
assert!(m.iter().zip(&v).all(|(x, y)| x.p.x == y.p.x + 1.0));
assert_eq!(a, v, "changing a copy left the original alone");
}
#[test]
fn reads_and_writes_as_a_flat_list() {
let v = line(600);
let a = Anchors::from(v.clone());
assert_eq!(serde_json::to_string(&a).ok(), serde_json::to_string(&v).ok());
let back: Anchors = serde_json::from_str(&serde_json::to_string(&v).unwrap_or_default()).unwrap_or_default();
assert_eq!(back, v);
assert_eq!(format!("{a:?}"), format!("{v:?}"));
}
#[test]
fn pairs_not_shared_skip_the_chunks_both_hold() {
let before = Anchors::from(line(10_000));
let mut after = before.clone();
after[5000].p = Point::new(-3.0, 0.0);
let pairs: Vec<_> = before.pairs_not_shared(&after).collect();
assert!(pairs.len() <= CHUNK);
let changed: Vec<usize> = pairs.iter().filter(|(_, a, b)| a != b).map(|(i, _, _)| *i).collect();
assert_eq!(changed, [5000]);
assert!(pairs.iter().all(|&(i, a, b)| *a == before[i] && *b == after[i]));
// Chunked differently: every pair.
let mut moved = before.clone();
moved.insert(0, Anchor::corner(Point::ZERO));
moved.remove(0);
assert_eq!(before.pairs_not_shared(&moved).count(), 10_000);
}
}
+2
View File
@@ -7,6 +7,7 @@
//! Coordinates are document points (1/72 in), y pointing down.
#![forbid(unsafe_code)]
pub mod anchors;
pub mod arc;
pub mod bez;
pub mod corners;
@@ -17,6 +18,7 @@ pub mod recognize;
pub mod shapes;
pub mod snap;
pub use anchors::Anchors;
pub use arc::ArcPath;
pub use kurbo;
pub use kurbo::{Affine, BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, Rect, Shape, Size, Vec2};
+14 -9
View File
@@ -6,6 +6,7 @@ use kurbo::{Affine, BezPath, CubicBez, ParamCurve, ParamCurveExtrema, ParamCurve
use serde::{Deserialize, Serialize};
use crate::EPS;
use crate::anchors::Anchors;
/// Fill rule for paths and compound paths.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -224,15 +225,15 @@ pub fn with_anchor_budget<T>(max: usize, f: impl FnOnce() -> T) -> T {
}
/// A subpath's anchors read within [`with_anchor_budget`].
fn anchors_within<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<Anchor>, D::Error> {
fn anchors_within<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Anchors, D::Error> {
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = Vec<Anchor>;
type Value = Anchors;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a list of anchors")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut a: A) -> Result<Vec<Anchor>, A::Error> {
let mut out = Vec::new();
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut a: A) -> Result<Anchors, A::Error> {
let mut out = Anchors::new();
while let Some(anchor) = a.next_element::<Anchor>()? {
if let Some(left) = ANCHORS_LEFT.get() {
let left = left
@@ -262,13 +263,17 @@ pub fn measured_segments() -> u64 {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct SubPath {
#[serde(deserialize_with = "anchors_within")]
pub anchors: Vec<Anchor>,
pub anchors: Anchors,
#[serde(default)]
pub closed: bool,
}
impl SubPath {
pub fn new(anchors: Vec<Anchor>, closed: bool) -> Self {
Self { anchors: anchors.into(), closed }
}
/// A subpath of `anchors`, sharing their chunks.
pub fn of(anchors: Anchors, closed: bool) -> Self {
Self { anchors, closed }
}
/// Polyline from points.
@@ -442,7 +447,7 @@ impl SubPath {
let (run, cuts): (Vec<Anchor>, BTreeSet<usize>) = if self.closed {
(self.anchors.iter().cycle().skip(first).take(n + 1).copied().collect(), cuts.map(|c| (c + n - first) % n).chain([n]).collect())
} else {
(self.anchors.clone(), cuts.collect())
(self.anchors.to_vec(), cuts.collect())
};
let mut pieces = vec![];
let mut cur: Vec<Anchor> = vec![];
@@ -511,11 +516,11 @@ impl PathData {
{
subpaths.push(sp);
}
cur = Some(SubPath { anchors: vec![Anchor::corner(p)], closed: false });
cur = Some(SubPath::new(vec![Anchor::corner(p)], false));
last = p;
}
PathEl::LineTo(p) => {
let sp = cur.get_or_insert_with(|| SubPath { anchors: vec![Anchor::corner(last)], closed: false });
let sp = cur.get_or_insert_with(|| SubPath::new(vec![Anchor::corner(last)], false));
sp.anchors.push(Anchor::corner(p));
last = p;
}
@@ -752,7 +757,7 @@ pub fn segment_bounds(seg: PathSeg) -> Rect {
}
fn push_curve(cur: &mut Option<SubPath>, last: Point, c1: Point, c2: Point, p: Point) {
let sp = cur.get_or_insert_with(|| SubPath { anchors: vec![Anchor::corner(last)], closed: false });
let sp = cur.get_or_insert_with(|| SubPath::new(vec![Anchor::corner(last)], false));
if let Some(a) = sp.anchors.last_mut() {
a.h_out = c1;
}
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff. Show more