Merge main into fix/js-interp-errors-translated

This commit is contained in:
dotCooCoo committed 2026-11-14 16:00:59 -08:00
commit cff8f2a30d
97 files changed
+6912 -2028

No files matched your search

Generated
+12
View File
@@ -1043,6 +1043,17 @@ dependencies = [
"serde_json",
]
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
dependencies = [
"encoding_rs",
"image",
"kurbo 0.13.1",
"thiserror 2.0.21",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
@@ -6681,6 +6692,7 @@ dependencies = [
name = "vectorcraft-metafile"
version = "0.24.1"
dependencies = [
"craft-metafile",
"image",
"kurbo 0.13.1",
"vectorcraft-brush",
+2
View File
@@ -31,6 +31,8 @@ craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
+27
View File
@@ -1008,6 +1008,33 @@ pub fn has_brush(n: &Node) -> bool {
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible))
}
/// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest
/// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has
/// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and
/// the exports leave for brush art when they cull.
pub fn reach(n: &Node) -> f64 {
let paints = |i: &AppearanceItem| matches!(i, AppearanceItem::Stroke(s) if s.visible && s.brush.is_some() && !s.paint.is_none());
if !n.appearance.items.iter().any(paints) {
return 0.0;
}
let w = n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max);
16.0 * w + 8.0
}
/// The largest [`reach`] of `n` and of the objects in it: the members of its groups, layers and
/// live objects. Of a group or layer with a clipping path only the clipping path counts, as the
/// clip keeps its members' brush art inside it. A compound path counts its own strokes only, as
/// it is painted with its own appearance and not its paths'. Symbol art is not looked into
/// ([`vectorcraft_doc::SymbolBoxes::with_brush_art`] measures it).
pub fn reach_within(n: &Node) -> f64 {
let members = match &n.kind {
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => children.get(..1).unwrap_or_default(),
NodeKind::Compound { .. } => &[],
_ => n.children().map_or(&[][..], |c| &c[..]),
};
members.iter().map(|c| reach_within(c)).fold(reach(n), f64::max)
}
/// Expand a brushed path: a group of [the path with its fills and unbrushed strokes (if any
/// paint remains), the brush art…]. Ids are 0 (the caller re-ids). `None` if not brushed.
pub fn expand(doc: &Document, n: &Node) -> Option<Node> {
+466 -37
View File
@@ -56,19 +56,114 @@ fn is_tiff(bytes: &[u8]) -> bool {
bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*")
}
/// The width and height of the first image of TIFF `bytes` when it has more strips or tiles than
/// the `tiff` decoder can count: strips per plane times planes past `u32::MAX`, or tiles per plane
/// times planes past `usize::MAX`. A file that stores one plane per channel (PlanarConfiguration 2)
/// has a plane for each channel; other files have one. The decoder multiplies these counts without
/// a check, which panics where overflow checks are on. Such an image, when it is at least a pixel
/// wide, claims at least 2^32 samples.
/// Where a tag repeats, the value giving the most strips or tiles counts. `None` for other images
/// What [`jpeg_frames`] found in a JPEG's headers.
enum Frames {
/// Every frame header declares a size the check accepts, or there is none.
Fit,
/// The width and height of the first frame header the check refuses.
Misfit(u16, u16),
/// The steps ran past [`MAX_JPEG_HEADER_STEPS`].
OverBudget,
}
/// Checks the width and height each 8-bit baseline, extended or progressive frame header in the
/// headers of a JPEG declares with `fits`. The JPEG is the bytes after its start-of-image marker:
/// `parts[0]` followed by `parts[1]`. The headers are read as the decoder reads them, up to the
/// first start-of-scan or end-of-image marker: every other marker is followed by its segment's
/// length, and bytes between segments are passed over, as are fill bytes (0xFF, and 0x00 after
/// one) before a marker. `steps` counts each byte looked at and each segment passed over.
fn jpeg_frames(parts: [&[u8]; 2], steps: &mut u64, fits: impl Fn(u16, u16) -> bool) -> Frames {
let byte = |i: usize| match i.checked_sub(parts[0].len()) {
None => parts[0].get(i).copied(),
Some(j) => parts[1].get(j).copied(),
};
let u16_at = |i: usize| Some(u16::from_be_bytes([byte(i)?, byte(i.checked_add(1)?)?]));
let mut p = 0usize;
loop {
*steps += 1;
if *steps > MAX_JPEG_HEADER_STEPS {
return Frames::OverBudget;
}
let Some(b) = byte(p) else { return Frames::Fit };
p += 1;
if b != 0xFF {
continue;
}
while matches!(byte(p), Some(0xFF | 0)) {
p += 1;
*steps += 1;
if *steps > MAX_JPEG_HEADER_STEPS {
return Frames::OverBudget;
}
}
let Some(marker) = byte(p) else { return Frames::Fit };
p += 1;
if matches!(marker, 0xDA | 0xD9) {
return Frames::Fit;
}
// Length (2 bytes), then for a frame header its precision, height and width.
let Some(len) = u16_at(p) else { return Frames::Fit };
if matches!(marker, 0xC0..=0xC2)
&& byte(p.saturating_add(2)) == Some(8)
&& let (Some(h), Some(w)) = (u16_at(p.saturating_add(3)), u16_at(p.saturating_add(5)))
&& !fits(w, h)
{
return Frames::Misfit(w, h);
}
if len < 2 {
return Frames::Fit;
}
p = p.saturating_add(usize::from(len));
}
}
/// Most strips or tiles the first image of a TIFF may have: VectorCraft's own limit, 1/1024 of
/// [`crate::MAX_RASTER_ALLOC`] (524,288 in the web app, 2,097,152 on the desktop). The decoder
/// reads an offset and a byte count of 8 bytes each for every one into memory before anything else.
pub const MAX_TIFF_CHUNKS: u64 = crate::MAX_RASTER_ALLOC / 1024;
/// Most pixels the JPEG of a JPEG-compressed TIFF tile may declare when it declares more pixels
/// than the whole image has: VectorCraft's own limit (2048 × 2048, 16 MB as CMYK).
pub const MAX_JPEG_TILE_PIXELS: u64 = 1 << 22;
/// Most steps reading the JPEG headers of a TIFF's strips or tiles may take (a byte looked at, a
/// segment passed over or a strip offset read): VectorCraft's own limit.
const MAX_JPEG_HEADER_STEPS: u64 = 1 << 24;
/// The width and height of the first image of TIFF or BigTIFF `bytes` when it has more strips or
/// tiles than the `tiff` decoder can count: strips per plane times planes past `u32::MAX`, or tiles
/// per plane times planes past `usize::MAX`. A file that stores one plane per channel
/// (PlanarConfiguration 2) has a plane for each channel; other files have one. The decoder
/// multiplies these counts without a check, which panics where overflow checks are on. Such an
/// image, when it is at least a pixel wide, claims at least 2^32 samples.
/// It also gives them for an image with more than [`MAX_TIFF_CHUNKS`] strips or tiles, counted from
/// its size or from the number of values its StripOffsets and StripByteCounts tags hold, or its
/// TileOffsets and TileByteCounts tags for a tiled image. An image the decoder reads as strips (it
/// has both strip tables and neither tile table) counts strips, and one it reads as tiles counts
/// tiles; the decoder refuses an image with any other mix of these tags before it reads a table.
/// For a JPEG-compressed image (Compression 7) it gives the width and height a strip's or tile's
/// JPEG declares in a frame header (in the JPEGTables, or in the strip or tile before its first
/// scan) when they are wider or taller than the strip or tile, or, for a tile, when they make more
/// than [`MAX_JPEG_TILE_PIXELS`] pixels and more than the image has. The decoder allocates the
/// pixels the JPEG declares. It gives the image's width and height when reading those headers
/// takes more than 16,777,216 steps (a byte looked at, a segment passed over or a strip offset
/// read), when the strip or tile offsets are of a type other than BYTE, UNDEFINED, SHORT, LONG,
/// IFD, LONG8 or IFD8, and when the image's width and height, a striped image's RowsPerStrip or a
/// tiled image's tile size isn't a single value of one of those types.
/// Where a tag repeats, the value giving the most strips or tiles counts, and the JPEG check uses
/// the last entry of a field type the decoder knows, as the decoder does. `None` for other images
/// and for bytes that aren't a TIFF.
pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> {
let le = bytes.starts_with(b"II*\0");
if !le && !bytes.starts_with(b"MM\0*") {
let le = bytes.starts_with(b"II");
let head = bytes.get(..4)?;
// A BigTIFF counts and points with 8 bytes where a TIFF uses 4, so its entries are 20 bytes.
let big = if head == b"II*\0" || head == b"MM\0*" {
false
} else if head == b"II+\0" || head == b"MM\0+" {
true
} else {
return None;
}
};
let u16_at = |at: usize| -> Option<u16> {
let b: [u8; 2] = bytes.get(at..at.checked_add(2)?)?.try_into().ok()?;
Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) })
@@ -77,32 +172,71 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> {
let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?;
Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) })
};
let ifd = usize::try_from(u32_at(4)?).ok()?;
// (tag, the entry's single BYTE, SHORT, LONG or IFD value, which sits in the entry, or its
// single LONG8 or IFD8 value that fits in 32 bits, which sits where the entry points)
let entry = |i: usize| -> Option<(u16, Option<u32>)> {
let e = ifd.checked_add(i.checked_mul(12)?.checked_add(2)?)?;
let (ty, count, at) = (u16_at(e.checked_add(2)?)?, u32_at(e.checked_add(4)?)?, e.checked_add(8)?);
let value = match (ty, count) {
(1, 1) => bytes.get(at).map(|&b| u32::from(b)),
(3, 1) => u16_at(at).map(u32::from),
(4 | 13, 1) => u32_at(at),
(16 | 18, 1) => {
let at = usize::try_from(u32_at(at)?).ok()?;
let (lo, hi) = (u32_at(at)?, u32_at(at.checked_add(4)?)?);
let wide = if le { u64::from(hi) << 32 | u64::from(lo) } else { u64::from(lo) << 32 | u64::from(hi) };
u32::try_from(wide).ok()
}
let u64_at = |at: usize| -> Option<u64> {
let b: [u8; 8] = bytes.get(at..at.checked_add(8)?)?.try_into().ok()?;
Some(if le { u64::from_le_bytes(b) } else { u64::from_be_bytes(b) })
};
let word_len: usize = if big { 8 } else { 4 };
let word = |at: usize| if big { u64_at(at) } else { u32_at(at).map(u64::from) };
// The bytes one value of each field type takes; 0 for types the decoder doesn't know.
let width_of = |ty: u16| -> usize {
match ty {
1 | 2 | 6 | 7 => 1,
3 | 8 => 2,
4 | 9 | 11 | 13 => 4,
5 | 10 | 12 | 16..=18 => 8,
_ => 0,
}
};
let ifd = usize::try_from(word(if big { 8 } else { 4 })?).ok()?;
let entries = if big { u64_at(ifd)? } else { u64::from(u16_at(ifd)?) };
let first = ifd.checked_add(if big { 8 } else { 2 })?;
// (tag, field type, number of values, where the values are: in the entry when they fit in its
// last word, otherwise where that word points)
let entry = |i: usize| -> Option<(u16, u16, u64, Option<usize>)> {
let e = first.checked_add(i.checked_mul(4 + 2 * word_len)?)?;
let (tag, ty, count) = (u16_at(e)?, u16_at(e.checked_add(2)?)?, word(e.checked_add(4)?)?);
let at = e.checked_add(4 + word_len)?;
let fits = u64::try_from(width_of(ty)).ok()?.checked_mul(count).is_some_and(|n| n <= word_len as u64);
let values = if fits { Some(at) } else { word(at).and_then(|p| usize::try_from(p).ok()) };
Some((tag, ty, count, values))
};
// Value `i` of an entry's BYTE, UNDEFINED, SHORT, LONG, IFD, LONG8 or IFD8 values at `at`.
let nth = |ty: u16, at: usize, i: u64| -> Option<u64> {
let p = at.checked_add(usize::try_from(i).ok()?.checked_mul(width_of(ty))?)?;
match ty {
1 | 7 => bytes.get(p).map(|&b| u64::from(b)),
3 => u16_at(p).map(u64::from),
4 | 13 => u32_at(p).map(u64::from),
16 | 18 => u64_at(p),
_ => None,
};
Some((u16_at(e)?, value))
}
};
let (mut width, mut height, mut planes, mut planar) = (0u32, 0u32, 1u32, false);
let (mut rows, mut tile_w, mut tile_h) = (None::<u32>, None::<u32>, None::<u32>);
// The most values a strip table and a tile table hold.
let (mut strip_chunks, mut tile_chunks) = (0u64, 0u64);
// The decoder keeps the last entry of a tag whose field type it knows. These are the last such
// entries (type, count, where) of the tags `LAST` lists.
const LAST: [u16; 11] = [256, 257, 259, 278, 322, 323, 273, 279, 324, 325, 347];
let mut last = [None::<(u16, u64, Option<usize>)>; LAST.len()];
let least = |was: Option<u32>, v: u32| Some(was.map_or(v, |w| w.min(v)));
for i in 0..usize::from(u16_at(ifd)?) {
let Some((tag, value)) = entry(i) else { break };
let Some(v) = value else { continue };
// The entry's single BYTE, UNDEFINED, SHORT, LONG or IFD value, or its single LONG8 or IFD8
// value when that fits in 32 bits.
let single = |ty: u16, count: u64, at: Option<usize>| at.filter(|_| count == 1).and_then(|at| nth(ty, at, 0)).and_then(|v| u32::try_from(v).ok());
for i in 0..usize::try_from(entries).unwrap_or(usize::MAX) {
let Some((tag, ty, count, at)) = entry(i) else { break };
match tag {
273 | 279 => strip_chunks = strip_chunks.max(count),
324 | 325 => tile_chunks = tile_chunks.max(count),
_ => {}
}
if width_of(ty) > 0
&& let Some(slot) = LAST.iter().position(|&t| t == tag).and_then(|k| last.get_mut(k))
{
*slot = Some((ty, count, at));
}
let Some(v) = single(ty, count, at) else { continue };
match tag {
256 => width = width.max(v),
257 => height = height.max(v),
@@ -115,13 +249,87 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> {
}
}
let planes = if planar { u128::from(planes) } else { 1 };
let tiles = match (tile_w, tile_h) {
(Some(tw @ 1..), Some(th @ 1..)) => u128::from(width.div_ceil(tw)) * u128::from(height.div_ceil(th)) * planes > usize::MAX as u128,
_ => false,
let tiled = match (tile_w, tile_h) {
(Some(tw @ 1..), Some(th @ 1..)) => u128::from(width.div_ceil(tw)) * u128::from(height.div_ceil(th)) * planes,
_ => 0,
};
let tiles = tiled > usize::MAX as u128;
let rows = rows.unwrap_or(height);
let strips = rows > 0 && u128::from(height.saturating_sub(1) / rows + 1) * planes > u128::from(u32::MAX);
(tiles || strips).then_some((width, height))
let striped = height.saturating_sub(1).checked_div(rows).map_or(0, |n| u128::from(n + 1) * planes);
let strips = striped > u128::from(u32::MAX);
if tiles || strips {
return Some((width, height));
}
let last_of = |tag: u16| LAST.iter().position(|&t| t == tag).and_then(|k| last.get(k).copied().flatten());
// The single value the decoder reads from the last entry of `tag`: `None` without one, and
// `Some(None)` when that entry doesn't hold a single value read here.
let value_of = |tag: u16| last_of(tag).map(|(ty, count, at)| single(ty, count, at));
// The decoder reads strips when the image has both strip tables and neither tile table, tiles
// in the opposite case, and refuses every other image before it reads a table.
let layout = match [273, 279, 324, 325].map(|tag| last_of(tag).is_some()) {
[true, true, false, false] => Some((273, striped.max(u128::from(strip_chunks)))),
[false, false, true, true] => Some((324, tiled.max(u128::from(tile_chunks)))),
_ => None,
};
let (offsets_tag, chunks) = layout?;
if chunks > u128::from(MAX_TIFF_CHUNKS) {
return Some((width, height));
}
if value_of(259) != Some(Some(7)) {
return None;
}
// The JPEG check uses the sizes the decoder reads. A size it needs that isn't a single value
// read here refuses the image.
let (Some(Some(w_img)), Some(Some(h_img))) = (value_of(256), value_of(257)) else { return Some((width, height)) };
let tile = offsets_tag == 324;
// RowsPerStrip, which the decoder reads only for strips.
let rows = if tile { Some(h_img) } else { value_of(278).unwrap_or(Some(h_img)) };
let Some(rows) = rows else { return Some((width, height)) };
let (tw, th) = match (value_of(322).flatten(), value_of(323).flatten()) {
(Some(tw), Some(th)) => (tw, th),
_ if tile => return Some((width, height)),
_ => (0, 0),
};
// A strip is as wide as the image and RowsPerStrip tall (at most the image's height); a tile's
// JPEG may be as large as the tile, which the edge tiles of the image overhang.
let fits = |w: u16, h: u16| {
let (w, h) = (u32::from(w), u32::from(h));
if tile {
let pixels = u64::from(w) * u64::from(h);
w <= tw && h <= th && (pixels <= MAX_JPEG_TILE_PIXELS || pixels <= u64::from(w_img) * u64::from(h_img))
} else {
w <= w_img && h <= rows.min(h_img)
}
};
// The decoder reads the JPEGTables after their start-of-image marker and without their last two
// bytes, followed by each strip or tile after its first two bytes; without JPEGTables, each
// strip or tile after its start-of-image marker.
let tables = last_of(347)
.and_then(|(_, count, at)| {
let at = at?;
let end = at.checked_add(usize::try_from(count).ok()?)?.min(bytes.len());
bytes.get(at.checked_add(2)?..end.checked_sub(2)?)
})
.unwrap_or_default();
let (ty, count, at) = last_of(offsets_tag)?;
let at = at?;
// The decoder also takes offsets of other types (a RATIONAL or ASCII value), which aren't read
// here: such an image is refused.
if !matches!(ty, 1 | 3 | 4 | 7 | 13 | 16 | 18) {
return Some((width, height));
}
let mut steps = 0u64;
for i in 0..count {
steps += 1;
let Some(at) = nth(ty, at, i).and_then(|o| usize::try_from(o).ok()) else { break };
let part = bytes.get(at.saturating_add(2)..).unwrap_or_default();
match jpeg_frames([tables, part], &mut steps, fits) {
Frames::Fit => {}
Frames::Misfit(w, h) => return Some((u32::from(w), u32::from(h))),
Frames::OverBudget => return Some((width, height)),
}
}
None
}
/// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too.
@@ -891,7 +1099,7 @@ mod tests {
f
};
assert_eq!(oversized_tiff(&header(2)), Some((u32::MAX, u32::MAX)));
assert_eq!(oversized_tiff(&header(1)), None, "one plane: (2^32 − 1)² tiles can be counted in 64 bits");
assert_eq!(oversized_tiff(&header(1)), Some((u32::MAX, u32::MAX)), "one plane: countable, but past MAX_TIFF_CHUNKS");
assert!(tiff(&header(2)).is_none(), "not decoded");
}
@@ -933,6 +1141,227 @@ mod tests {
}
}
/// A little-endian TIFF, or BigTIFF when `big`, holding `data` right after its header (from
/// byte 8, or 16 in a BigTIFF), then one directory of `entries` (tag, field type, values). An
/// entry's values sit in the entry when they fit, otherwise after the directory.
fn tiff_file(big: bool, entries: &[(u16, u16, Vec<u64>)], data: &[u8]) -> Vec<u8> {
let (word, head) = if big { (8, 16) } else { (4, 8) };
let put = |f: &mut Vec<u8>, v: u64, n: usize| f.extend(&v.to_le_bytes()[..n]);
let mut f = if big { b"II+\0\x08\0\0\0".to_vec() } else { b"II*\0".to_vec() };
let ifd = head + data.len();
put(&mut f, ifd as u64, word);
f.extend(data);
put(&mut f, entries.len() as u64, if big { 8 } else { 2 });
let after = f.len() + entries.len() * (4 + 2 * word) + word;
let mut tail = vec![];
for (tag, ty, values) in entries {
let width = match ty {
1 | 7 => 1,
3 => 2,
4 => 4,
_ => 8,
};
f.extend([tag.to_le_bytes(), ty.to_le_bytes()].concat());
put(&mut f, values.len() as u64, word);
let mut v = vec![];
for &x in values {
put(&mut v, x, width);
}
if v.len() <= word {
v.resize(word, 0);
f.extend(v);
} else {
put(&mut f, (after + tail.len()) as u64, word);
tail.extend(v);
}
}
put(&mut f, 0, word);
f.extend(tail);
f
}
/// A JPEG of four components whose progressive frame header declares `w` × `h` pixels, with a
/// scan header and no scan data.
fn jpeg_header(w: u16, h: u16) -> Vec<u8> {
let mut j = vec![0xFF, 0xD8, 0xFF, 0xC2, 0, 20, 8];
j.extend(h.to_be_bytes());
j.extend(w.to_be_bytes());
j.push(4);
for id in 1..=4 {
j.extend([id, 0x11, 0]);
}
j.extend([0xFF, 0xDA, 0, 14, 4, 1, 0, 2, 0, 3, 0, 4, 0, 0, 63, 0, 0xFF, 0xD9]);
j
}
/// The directory of a 1 × 1 CMYK image with alpha, JPEG-compressed in one strip of `len` bytes
/// at byte `at`.
fn jpeg_strip_entries(at: u64, len: u64) -> Vec<(u16, u16, Vec<u64>)> {
vec![
(256, 4, vec![1]),
(257, 4, vec![1]),
(258, 3, vec![8; 5]),
(259, 3, vec![7]),
(262, 3, vec![5]),
(273, 4, vec![at]),
(277, 3, vec![5]),
(278, 4, vec![1]),
(279, 4, vec![len]),
(338, 3, vec![2]),
]
}
/// A strip's JPEG that declares more pixels than the strip holds would have the decoder
/// allocate them: a 1 × 1 image whose JPEG claims 16384 × 16384 is refused before any decoder
/// opens it, in a TIFF or a BigTIFF, with fill bytes or other bytes before the frame header,
/// and with the frame header in the JPEGTables.
#[test]
fn a_jpeg_strip_declaring_more_than_its_strip_is_refused() {
let big = jpeg_header(16384, 16384);
let file = tiff_file(false, &jpeg_strip_entries(8, big.len() as u64), &big);
assert_eq!(oversized_tiff(&file), Some((16384, 16384)));
assert!(tiff(&file).is_none(), "not decoded");
let bigtiff = tiff_file(true, &jpeg_strip_entries(16, big.len() as u64), &big);
assert_eq!(oversized_tiff(&bigtiff), Some((16384, 16384)), "BigTIFF");
// The decoder reads the last ImageWidth and ImageLength: 1 × 1 after 16384 × 16384, in one
// strip without RowsPerStrip.
let mut entries = jpeg_strip_entries(8, big.len() as u64);
entries.retain(|e| e.0 != 278);
entries.splice(0..0, [(256, 4, vec![16384]), (257, 4, vec![16384])]);
assert_eq!(oversized_tiff(&tiff_file(false, &entries, &big)), Some((16384, 16384)), "repeated sizes");
// StripOffsets as a BYTE, which the decoder reads, and as a RATIONAL, which it reads as two
// offsets.
for (ty, expected) in [(1, (16384, 16384)), (5, (1, 1))] {
let mut entries = jpeg_strip_entries(8, big.len() as u64);
for e in &mut entries {
if e.0 == 273 {
e.1 = ty;
}
}
assert_eq!(oversized_tiff(&tiff_file(false, &entries, &big)), Some(expected), "StripOffsets of type {ty}");
}
let one = jpeg_header(1, 1);
assert_eq!(oversized_tiff(&tiff_file(false, &jpeg_strip_entries(8, one.len() as u64), &one)), None, "a JPEG as large as its strip");
let wide = jpeg_header(2, 1);
assert_eq!(oversized_tiff(&tiff_file(false, &jpeg_strip_entries(8, wide.len() as u64), &wide)), Some((2, 1)), "one pixel too wide");
for (what, prefix) in [("fill bytes", &[0xFF, 0x00, 0xFF][..]), ("other bytes", &[0x12, 0x34][..])] {
let mut j = big[..2].to_vec();
j.extend(prefix);
j.extend(&big[2..]);
let file = tiff_file(false, &jpeg_strip_entries(8, j.len() as u64), &j);
assert_eq!(oversized_tiff(&file), Some((16384, 16384)), "{what} before the frame header");
}
// The JPEGTables hold the frame header; the strip holds only the scan.
let tables = [&big[..24], &[0xFF, 0xD9][..]].concat();
let scan = [&[0xFF, 0xD8][..], &big[24..]].concat();
let mut entries = jpeg_strip_entries(8 + tables.len() as u64, scan.len() as u64);
entries.push((347, 7, tables.iter().map(|&b| u64::from(b)).collect()));
let file = tiff_file(false, &entries, &[tables, scan].concat());
assert_eq!(oversized_tiff(&file), Some((16384, 16384)), "frame header in the JPEGTables");
// An encoder's 8 × 8 RGB JPEG, with its own segments before the frame header, in an
// 8 × 8 image of one strip, and of strips 4 rows tall.
let mut real = Vec::new();
image::codecs::jpeg::JpegEncoder::new(&mut real).encode(&[90; 8 * 8 * 3], 8, 8, image::ExtendedColorType::Rgb8).unwrap();
let rgb = |rows: u64| {
let entries = [
(256, 4, vec![8]),
(257, 4, vec![8]),
(258, 3, vec![8; 3]),
(259, 3, vec![7]),
(262, 3, vec![2]),
(273, 4, vec![8]),
(277, 3, vec![3]),
(278, 4, vec![rows]),
(279, 4, vec![real.len() as u64]),
];
oversized_tiff(&tiff_file(false, &entries, &real))
};
assert_eq!(rgb(8), None, "an encoder's JPEG as large as its strip");
assert_eq!(rgb(4), Some((8, 8)), "an encoder's JPEG taller than its strip");
}
/// A tile's JPEG may be as large as the tile, which overhangs the image, and when it is more
/// than MAX_JPEG_TILE_PIXELS, no larger than the image.
#[test]
fn a_jpeg_tile_declaring_more_than_its_tile_is_refused() {
let tiled_with = |tile: u64, j: &[u8], rows: Vec<u64>| {
let mut entries: Vec<_> = jpeg_strip_entries(0, 0).into_iter().filter(|e| !matches!(e.0, 273 | 278 | 279)).collect();
if !rows.is_empty() {
entries.push((278, 4, rows));
}
entries.extend([(322, 4, vec![tile]), (323, 4, vec![tile]), (324, 4, vec![8]), (325, 4, vec![j.len() as u64])]);
oversized_tiff(&tiff_file(false, &entries, j))
};
let tiled = |tile: u64, j: &[u8]| tiled_with(tile, j, vec![]);
assert_eq!(tiled_with(16, &jpeg_header(16, 16), vec![1, 1]), None, "RowsPerStrip, unread in a tiled image");
assert_eq!(tiled(16, &jpeg_header(16, 16)), None, "as large as the tile");
assert_eq!(tiled(16, &jpeg_header(17, 16)), Some((17, 16)), "wider than the tile");
assert_eq!(tiled(16, &jpeg_header(16, 17)), Some((16, 17)), "taller than the tile");
assert_eq!(tiled(4096, &jpeg_header(2048, 2048)), None, "MAX_JPEG_TILE_PIXELS");
assert_eq!(tiled(4096, &jpeg_header(2048, 2049)), Some((2048, 2049)), "past MAX_JPEG_TILE_PIXELS and the image");
}
/// The decoder reads every strip's offset and byte count before anything else: an image with
/// more than MAX_TIFF_CHUNKS strips, counted from its size or from its tables, is refused.
#[test]
fn tiffs_with_more_strips_than_their_tables_may_hold_are_refused() {
let file = |height: u64, count: u32| {
let entries = [
(256, 4, vec![1]),
(257, 4, vec![height]),
(258, 3, vec![8]),
(262, 3, vec![1]),
(273, 4, vec![8]),
(278, 4, vec![1]),
(279, 4, vec![1]),
];
let mut f = tiff_file(false, &entries, &[0]);
// StripOffsets' count, its values left out of the file.
let at = 8 + 1 + 2 + 4 * 12 + 4;
f[at..at + 4].copy_from_slice(&count.to_le_bytes());
f
};
let most = MAX_TIFF_CHUNKS;
assert_eq!(oversized_tiff(&file(most, 1)), None, "MAX_TIFF_CHUNKS rows of a strip each");
assert_eq!(oversized_tiff(&file(most + 1, 1)), Some((1, u32::try_from(most + 1).unwrap())), "one strip more");
assert_eq!(oversized_tiff(&file(1, u32::try_from(most).unwrap())), None, "MAX_TIFF_CHUNKS offsets");
assert_eq!(oversized_tiff(&file(1, u32::try_from(most + 1).unwrap())), Some((1, 1)), "one offset more");
assert!(tiff(&file(1, 1 << 25)).is_none(), "not decoded");
// Tile sizes without tile tables: the decoder reads the strips and never counts the
// 4,194,304 tiles of a pixel the sizes give.
let strips_with_tile_sizes = |offsets: Option<u16>| {
let mut entries = vec![
(256, 4, vec![2048]),
(257, 4, vec![2048]),
(258, 3, vec![8]),
(262, 3, vec![1]),
(273, 4, vec![8]),
(279, 4, vec![2048 * 2048]),
(322, 4, vec![1]),
(323, 4, vec![1]),
];
entries.extend(offsets.map(|tag| (tag, 4, vec![8])));
entries.sort_by_key(|e| e.0);
oversized_tiff(&tiff_file(false, &entries, &[0]))
};
assert_eq!(strips_with_tile_sizes(None), None, "a strip image with tile sizes of one pixel");
assert_eq!(strips_with_tile_sizes(Some(324)), None, "strip and tile tables: the decoder refuses it unread");
}
/// Strips whose JPEG headers take more than MAX_JPEG_HEADER_STEPS steps to read refuse the
/// file: here every strip points at the same 1 MB without a marker.
#[test]
fn jpeg_strips_that_take_too_long_to_read_are_refused() {
let file = |strips: u64| {
let mut entries = jpeg_strip_entries(0, 0);
entries.retain(|e| !matches!(e.0, 257 | 273 | 279));
entries.extend([(257, 4, vec![strips]), (273, 4, vec![8; strips as usize]), (279, 4, vec![1 << 20; strips as usize])]);
tiff_file(false, &entries, &std::iter::repeat_n(0, 1 << 20).collect::<Vec<u8>>())
};
assert_eq!(oversized_tiff(&file(8)), None, "about 8 million steps");
assert_eq!(oversized_tiff(&file(17)), Some((1, 17)), "about 17 million steps");
}
fn inks() -> Inks {
Inks::new(3, 2, vec![0, 40, 100, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 12, 34, 56, 78]).unwrap()
}
+38 -27
View File
@@ -543,7 +543,7 @@ pub struct GraphSpec {
/// Bounds of the art when it was last generated (detects moves/scales of the graph group).
#[serde(skip_serializing_if = "Option::is_none")]
pub placed: Option<Rect>,
/// Bounds of the art other than type when it was last generated ([`art_bounds`]). Moves and scales of the graph
/// Bounds of the art other than type when it was last generated ([`graph_art_without_type`]). Moves and scales of the graph
/// group are measured on these when present; graphs saved without them are measured on [`Self::placed`].
#[serde(skip_serializing_if = "Option::is_none")]
pub placed_art: Option<Rect>,
@@ -562,6 +562,43 @@ fn edge_to_edge_before_the_option() -> bool {
true
}
/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend
/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these.
pub fn graph_art_without_type(children: &[std::sync::Arc<crate::Node>]) -> Option<Rect> {
children.iter().filter_map(|c| without_type(c).0).reduce(|a, b| a.union(b))
}
/// The geometric bounds of `n` leaving out the type in it, and whether its own geometric bounds depend on that type. A
/// group without such type gives its own bounds, and a clipping group whose clip does not depend on type gives the
/// bounds of its clip. Objects other than groups, layers and compound paths, blends, envelopes and repeats among them,
/// give their own bounds.
fn without_type(n: &crate::Node) -> (Option<Rect>, bool) {
use crate::NodeKind::{Compound, Group, Layer, Text};
if matches!(n.kind, Text(_)) {
return (None, true);
}
let children: &[std::sync::Arc<crate::Node>] = match &n.kind {
Group { clip: true, children } | Layer { clip: true, children, .. } => children,
Group { .. } | Layer { .. } | Compound { .. } => n.editing_children(),
_ => return (n.geometric_bounds(), false),
};
let mut bounds: Option<Rect> = None;
let mut had_type = false;
let mut clip_has_type = false;
let hidden_layer_member = |c: &crate::Node| !c.visible && matches!(n.kind, Layer { clip: false, .. });
for (i, c) in children.iter().enumerate().filter(|(_, c)| !hidden_layer_member(c)) {
let (b, t) = without_type(c);
had_type |= t;
clip_has_type |= i == 0 && t;
bounds = match (bounds, b) {
(Some(a), Some(b)) => Some(a.union(b)),
(a, b) => a.or(b),
};
}
let clip = matches!(n.kind, Group { clip: true, .. } | Layer { clip: true, .. });
if had_type && (!clip || clip_has_type) { (bounds, true) } else { (n.geometric_bounds(), false) }
}
impl GraphSpec {
/// The type series `s` is drawn as: its own type when it combines with the graph's, else the graph's.
pub fn series_kind(&self, s: usize) -> GraphKind {
@@ -630,32 +667,6 @@ impl GraphSpec {
}
}
/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend
/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these.
pub fn art_bounds(children: &[std::sync::Arc<crate::Node>]) -> Option<Rect> {
children.iter().filter_map(|c| art_bounds_of(c).0).reduce(|a, b| a.union(b))
}
/// The geometric bounds of `n` leaving out the type in it, and whether there was type to leave out. A group without type
/// gives its own bounds, so a clipping group gives the bounds of its clip.
fn art_bounds_of(n: &crate::Node) -> (Option<Rect>, bool) {
if matches!(n.kind, crate::NodeKind::Text(_)) {
return (None, true);
}
let Some(children) = n.children() else { return (n.geometric_bounds(), false) };
let mut bounds: Option<Rect> = None;
let mut had_type = false;
for c in children {
let (b, t) = art_bounds_of(c);
had_type |= t;
bounds = match (bounds, b) {
(Some(a), Some(b)) => Some(a.union(b)),
(a, b) => a.or(b),
};
}
if had_type { (bounds, true) } else { (n.geometric_bounds(), false) }
}
impl Default for GraphSpec {
fn default() -> Self {
Self {
+376 -88
View File
@@ -1,7 +1,7 @@
//! Hit testing over the document tree.
use std::cell::RefCell;
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::{Arc, OnceLock};
@@ -279,13 +279,16 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &
return false;
}
// How a click reaches it, if one does.
let start = opt;
let Some(opt) = path_options(&nodes, &chain, opt) else { return false };
// Hidden by a mask: one of the containers around it clips, and not to `p`.
let masked = nodes
.iter()
.rev()
.skip(1)
.any(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p)));
// Hidden by a mask: one of the containers around it clips, and not to `p`. A container
// tests its clipping path in outline from the first layer with Preview off down to it, as
// a click going down to it does ([`path_options`]).
let below = start.scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1);
let masked = nodes.iter().enumerate().rev().skip(1).any(|(k, n)| {
let outline = start.outline || nodes.get(below..=k).is_some_and(|ns| ns.iter().any(|n| previews_off(n)));
n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p, outline))
});
// A click may reach it there ([`may_hit`]: not a guide while guides are locked or
// hidden, nor a Shaper group's hidden part), and its own art is what a click would hit
// in it: a group's hidden, locked or masked contents don't count.
@@ -359,6 +362,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
/// measured by their art ([`Node::geometric_bounds_with`]).
fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, tops: &mut Vec<NodeId>, seen: &mut HashSet<NodeId>) -> bool {
let Some(children) = layer.children() else { return true };
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
if layer.clips()
&& let Some(clip) = children.first()
{
@@ -366,11 +370,10 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
if clip_outline_hit(layer, clip, p, opt, symbols, true).is_some() && seen.insert(clip.id) {
tops.push(clip.id);
}
if !clip_contains(clip, p) {
if !clip_contains(clip, p, opt.outline) {
return true;
}
}
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
for (i, c) in children.iter().enumerate().rev() {
if !may_hit(layer, i, c, p, opt, symbols, true) || seen.contains(&c.id) {
continue;
@@ -452,7 +455,7 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeI
/// whole, and an unlocked layer, group, blend or envelope in Edit Contents is searched inside.
fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, out: &mut Vec<NodeId>) {
let Some(children) = parent.children() else { return };
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p)) {
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) {
return;
}
for i in hit_order(parent, children, p) {
@@ -561,14 +564,170 @@ fn edits_contents(n: &Node) -> bool {
matches!(n.kind, NodeKind::Envelope { editing: true, .. })
}
/// Is `p` inside the region `clip` clips to ([`Node::clip_shapes`])? Text counts by its frame:
/// glyph outlines need the font engine, above this crate.
fn clip_contains(clip: &Node, p: Point) -> bool {
clip_regions(clip).iter().any(|(bp, rule)| fill_contains(bp, *rule, p))
/// Is `p` inside the region `clip` clips to ([`clip_areas`])? In outline mode ([`HitOptions::outline`])
/// the canvas draws no effects, so the plain shapes of `clip` ([`clip_regions`]) count.
fn clip_contains(clip: &Node, p: Point, outline: bool) -> bool {
let areas = if outline { clip_regions(clip) } else { clip_areas(clip) };
areas.iter().any(|(bp, rule)| fill_contains(bp, *rule, p))
}
/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in
/// [`clip_contains`].
/// The region of a clip group's clipping path as the canvas clips by it, with the live geometry
/// effects of the clipping path and of what it clips by applied, as one path and fill rule
/// (`Some(None)` when nothing is left to clip by). `None` when nothing in the clipping path has a
/// live geometry effect: its plain shapes ([`clip_regions`]) count then. Effects are evaluated
/// above this crate, so the engine registers one with [`set_clip_region`].
pub type ClipRegion = fn(&Node) -> Option<Option<(BezPath, FillRule)>>;
static CLIP_REGION: OnceLock<ClipRegion> = OnceLock::new();
/// Register how the region of a clipping path with live effects is found (the first registration
/// stays).
pub fn set_clip_region(f: ClipRegion) {
// Already set: the same engine, registered by another session.
let _ = CLIP_REGION.set(f);
}
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
/// then can the registered [`ClipRegion`] find a geometry effect in it.
fn has_effects(clip: &Node) -> bool {
let mut found = false;
clip.walk(&mut |n| {
let visible = |e: &crate::Effect| e.visible;
found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible));
});
found
}
/// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the
/// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its
/// path elements.
struct EvaluatedClip {
clip: Node,
inputs: u64,
region: Option<Rc<Option<(BezPath, FillRule)>>>,
size: usize,
}
/// How many regions [`clip_region`] keeps on each thread: every click and every hover over a clip
/// group whose clipping path has live effects asks for its region, and clip groups can be nested.
const CLIPS_KEPT: usize = 16;
thread_local! {
/// The regions [`clip_region`] keeps, the latest first.
static CLIPS: RefCell<Vec<EvaluatedClip>> = const { RefCell::new(Vec::new()) };
}
#[cfg(test)]
thread_local! {
/// How many regions [`clip_region`] evaluated on this thread.
static CLIPS_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The region clipping path `clip` clips to with its live geometry effects applied
/// ([`set_clip_region`]), or `None` when it has none or nothing is registered; its plain shapes
/// ([`clip_regions`]) are the region then. The region is evaluated again when `clip` or the
/// [`LiveInputs`] have changed since.
fn clip_region(clip: &Node) -> Option<Rc<Option<(BezPath, FillRule)>>> {
let f = CLIP_REGION.get()?;
if !has_effects(clip) {
return None;
}
let inputs = live_inputs();
let kept = CLIPS.with_borrow_mut(|kept| {
let i = kept.iter().position(|e| e.inputs == inputs && e.clip == *clip)?;
let e = kept.remove(i);
let region = e.region.clone();
kept.insert(0, e);
Some(region)
});
if let Some(region) = kept {
return region;
}
#[cfg(test)]
CLIPS_EVALUATED.with(|c| c.set(c.get() + 1));
let region = f(clip).map(Rc::new);
let elements = region.as_deref().and_then(Option::as_ref).map_or(0, |(bp, _)| bp.elements().len());
let size = elements.saturating_add(art_size(std::slice::from_ref(clip)));
if size <= LIVE_KEPT_SIZE {
let e = EvaluatedClip { clip: clip.clone(), inputs, region: region.clone(), size };
CLIPS.with_borrow_mut(|kept| {
kept.insert(0, e);
kept.truncate(CLIPS_KEPT);
let mut total = 0usize;
kept.retain(|e| {
total = total.saturating_add(e.size);
total <= LIVE_KEPT_SIZE
});
});
}
region
}
/// The box of a clipping path's region found by [`reshaped_clip_box`]: the clipping path and the
/// [`LiveInputs`] as they were, the box and the [`art_size`] of the clipping path.
struct ClipBox {
clip: Node,
inputs: u64,
rect: Option<Rect>,
size: usize,
}
/// How many boxes [`reshaped_clip_box`] keeps on each thread. Every pointer move measures every clip
/// group it passes, so the boxes of all of a document's clip groups with live effects are kept, not
/// only the latest few as with the regions.
const CLIP_BOXES_KEPT: usize = 4096;
thread_local! {
/// The boxes [`reshaped_clip_box`] keeps, by clipping path, and the sum of their sizes.
static CLIP_BOXES: RefCell<(HashMap<NodeId, ClipBox>, usize)> = RefCell::new((HashMap::new(), 0));
}
/// The box of the region `clip` clips to with its live geometry effects applied ([`clip_region`]),
/// `None` when it has none or no region. The box is kept until `clip` or the [`LiveInputs`] change.
/// When the boxes kept are full, a new box replaces as many others as it needs room for, so the
/// pointer moving over more clip groups than fit still finds most of their boxes.
pub(crate) fn reshaped_clip_box(clip: &Node) -> Option<Rect> {
use vectorcraft_geom::kurbo::Shape;
CLIP_REGION.get()?;
if !has_effects(clip) {
return None;
}
let inputs = live_inputs();
let kept = CLIP_BOXES.with_borrow(|(boxes, _)| boxes.get(&clip.id).filter(|b| b.inputs == inputs && b.clip == *clip).map(|b| b.rect));
if let Some(rect) = kept {
return rect;
}
let rect = clip_region(clip).and_then(|r| r.as_ref().as_ref().filter(|(bp, _)| !bp.elements().is_empty()).map(|(bp, _)| bp.bounding_box()));
let size = art_size(std::slice::from_ref(clip));
if size <= LIVE_KEPT_SIZE {
CLIP_BOXES.with_borrow_mut(|(boxes, total)| {
if let Some(old) = boxes.remove(&clip.id) {
*total = total.saturating_sub(old.size);
}
while boxes.len() >= CLIP_BOXES_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE {
let Some(other) = boxes.keys().next().copied() else { break };
if let Some(old) = boxes.remove(&other) {
*total = total.saturating_sub(old.size);
}
}
boxes.insert(clip.id, ClipBox { clip: clip.clone(), inputs, rect, size });
*total = total.saturating_add(size);
});
}
rect
}
/// The regions a click inside a clip group must fall in: those `clip` clips to with its live
/// effects applied, as the canvas clips ([`clip_region`]), else its plain shapes ([`clip_regions`]).
fn clip_areas(clip: &Node) -> Vec<(BezPath, FillRule)> {
match clip_region(clip) {
Some(region) => region.as_ref().iter().cloned().collect(),
None => clip_regions(clip),
}
}
/// The regions `clip` clips to by its plain shapes ([`Node::clip_shapes`]), without its live
/// effects. Text counts by its frame: glyph outlines need the font engine, above this crate.
pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
let frame = |n: &Node| {
let b = n.geometric_bounds()?;
@@ -698,7 +857,7 @@ fn hit_children(
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for
// the selection tools in isolation mode within it.
let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope);
if !edited && !clip_contains(clip, p) {
if !edited && !clip_contains(clip, p, opt.outline) {
return None;
}
}
@@ -960,7 +1119,7 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option
match &n.kind {
// A clip group only hits inside its clipping path.
NodeKind::Group { children, clip } => {
if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) {
if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) {
return None;
}
children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols))
@@ -1048,7 +1207,9 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
/// group's original shapes, which the canvas does not draw, and guide paths with
/// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice
/// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not
/// draw. `None` when `inst` is not a symbol instance or no editable object of its art is under `p`.
/// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a
/// 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>> {
struct Find<'a> {
art: &'a InstanceArt<'a>,
@@ -1057,35 +1218,34 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
symbols: &'a SymbolBoxes<'a>,
}
impl Find<'_> {
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> bool {
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some())
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> bool {
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, opt, self.symbols).is_some())
}
fn skips_guide(&self, n: &Node) -> bool {
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
}
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>) -> bool {
/// `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) -> bool {
if !n.visible || n.locked || n.is_template() || self.skips_guide(n) {
return false;
}
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole) };
let outline = outline || previews_off(n);
let opt = HitOptions { outline, ..self.opt };
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) };
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
return self.hit(n, whole);
return self.hit(n, whole, opt);
}
let whole = self.art.whole(n, whole);
if n.clips()
&& let Some(first) = children.first()
{
let Some(clip) = self.art.place_unclipped(first, whole) else { return false };
if self.opt.clip_outlines
&& first.visible
&& !first.locked
&& !self.skips_guide(first)
&& clip_outline(&clip, self.p, self.opt).is_some()
if self.opt.clip_outlines && first.visible && !first.locked && !self.skips_guide(first) && clip_outline(&clip, self.p, opt).is_some()
{
path.push(0);
return true;
}
if !clip_contains(&clip, self.p) {
if !clip_contains(&clip, self.p, outline) {
return false;
}
}
@@ -1096,7 +1256,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
}
let Ok(i) = u32::try_from(i) else { continue };
path.push(i);
if self.find(c, path, whole) {
if self.find(c, path, whole, outline) {
return true;
}
path.pop();
@@ -1107,7 +1267,17 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
let art = InstanceArt::of(doc, inst)?;
let symbols = doc.symbol_boxes();
let mut path = vec![];
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path)
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, outline).then_some(path)
}
/// 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.
fn below_preview_off(doc: &Document, n: &Node, scope: Option<NodeId>) -> bool {
let Some(chain) = doc.ancestry(n.id) else { return false };
let below = scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1);
chain.iter().skip(below).any(|a| doc.node(*a).is_some_and(previews_off))
}
/// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]),
@@ -1116,11 +1286,23 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
/// group per cell) they are cut to the bounds of the group's clip path, which is not outlined. An
/// object inside a clip group or a clipping layer of the art, other than its clipping path, is cut
/// to the bounds of that clipping path as well, which contain the region where [`symbol_part_at`]
/// picks it.
/// picks it: the bounds of the region its live geometry effects give it ([`clip_region`]) when it
/// has any.
/// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies.
pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<BezPath> {
symbol_part_outline_in_view(doc, inst, path, HitOptions::default())
}
/// [`symbol_part_outline`] in the view the canvas shows, for the clicks of `opt`: in Outline view
/// ([`HitOptions::outline`]) and below a layer whose Preview is off, in the art or around the
/// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the
/// outlines are cut to the bounds of the plain clipping paths, without their live effects, as
/// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around
/// the object leave no region.
pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option<BezPath> {
let art = InstanceArt::of(doc, inst)?;
let part = crate::symbol_overrides::part(&art.art, path)?;
let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope);
let mut out = BezPath::new();
let mut limit = None;
let mut whole = None;
@@ -1128,24 +1310,40 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<
for &i in path {
let children = n.children()?;
whole = art.whole(n, whole);
outline = outline || previews_off(n);
if i != 0
&& n.clips()
&& let Some(first) = children.first()
&& let Some(clip) = art.place_unclipped(first, whole)?.geometric_bounds()
{
match meet(Some(clip), limit) {
Some(r) => limit = Some(r),
None => return Some(out),
}
let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) };
limit = within;
}
n = children.get(usize::try_from(i).ok()?)?;
}
outline_within(&art.place(part, whole)?, limit, &mut out);
outline_within(&art.place(part, whole)?, limit, outline, &mut out);
Some(out)
}
/// [`symbol_part_outline`] for placed object `n`, cut to `limit` when there is one.
fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
/// `limit` cut to the box that the art clipped by `clip` is drawn in: the bounds of the region the
/// live geometry effects of `clip` give it ([`clip_region`]), or the bounds of `clip` when it has no
/// such effects and with `outline`, where the canvas draws no effects. `None` when none of that art
/// is drawn: the effects leave no region, or the box is outside `limit`.
fn limit_within(clip: &Node, limit: Option<Rect>, outline: bool) -> Option<Option<Rect>> {
use vectorcraft_geom::kurbo::Shape;
let region = if outline { None } else { clip_region(clip) };
let bounds = match region.as_deref() {
Some(Some((bp, _))) if !bp.elements().is_empty() => Some(bp.bounding_box()),
Some(_) => return None,
None => clip.geometric_bounds(),
};
match bounds {
Some(b) => meet(Some(b), limit).map(Some),
None => Some(limit),
}
}
/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one.
fn outline_within(n: &Node, limit: Option<Rect>, outline: bool, out: &mut BezPath) {
use vectorcraft_geom::kurbo::Shape;
if let Some(pd) = n.path_data() {
match limit {
@@ -1159,20 +1357,15 @@ fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
out.extend(b.to_path(0.1));
}
let Some(children) = n.children() else { return };
let outline = outline || previews_off(n);
if n.clips()
&& let Some((first, rest)) = children.split_first()
{
let inner = match first.geometric_bounds() {
Some(c) => match meet(Some(c), limit) {
Some(r) => Some(r),
None => return,
},
None => limit,
};
rest.iter().for_each(|c| outline_within(c, inner, out));
let Some(inner) = limit_within(first, limit, outline) else { return };
rest.iter().for_each(|c| outline_within(c, inner, outline, out));
return;
}
children.iter().for_each(|c| outline_within(c, limit, out));
children.iter().for_each(|c| outline_within(c, limit, outline, out));
}
/// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap.
@@ -1248,31 +1441,48 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
/// the selection tools' clicks.
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, leaves, false)
marquee_with(doc, r, scope, leaves, false, false)
}
/// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer
/// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as
/// the clicks of [`HitOptions::outline`] do.
pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, outline: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, leaves, false, outline)
}
/// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group
/// traversal follow [`marquee`]; compounds contribute the complete path they paint.
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>) -> Vec<NodeId> {
marquee_with(doc, r, scope, true, true)
/// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint.
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>, outline: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, true, true, outline)
}
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool) -> Vec<NodeId> {
/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)?
fn previews_off(n: &Node) -> bool {
matches!(n.kind, NodeKind::Layer { preview: false, .. })
}
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
let mut out = Vec::new();
// `tops` pairs each object with the part of `r` in which the marquee can touch it.
let tops: Vec<(&std::sync::Arc<Node>, Rect)> = match scope.and_then(|s| doc.node(s)) {
// The objects the marquee may touch ([`Top`]).
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
// marquee touches none of it, as clicks don't (#5309).
Some(s) if !doc.is_editable(s.id) => vec![],
Some(s) => match s.children() {
Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
Some(c) => c
.iter()
.enumerate()
.filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
.map(|(_, c)| (c, Some(r), outline, None))
.collect(),
// A single object isolated: only it.
None => doc
.parent_of(s.id)
.and_then(|p| doc.node(p))
.and_then(|p| p.children())
.into_iter()
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, r)))
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None)))
.collect(),
},
// The objects of the layers, looking through sublayers (hidden, locked and template ones
@@ -1281,42 +1491,88 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
.layers
.iter()
.filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id))
.flat_map(|l| layer_objects(l, r))
.flat_map(|l| layer_objects(l, r, outline))
.collect(),
};
/// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of
/// the sublayers it is in leave.
fn layer_objects(l: &Node, r: Rect) -> Vec<(&std::sync::Arc<Node>, Rect)> {
/// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`,
/// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain
/// shapes ([`mask_marquee`]).
fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec<Top<'_>> {
let mut out = vec![];
let Some(r) = marquee_in(l, r) else { return out };
for c in l.children().into_iter().flatten() {
let outline = outline || previews_off(l);
let inner = marquee_in_parent(l, r, outline);
for (i, c) in l.children().into_iter().flatten().enumerate() {
if c.is_layer() {
if c.visible && !c.locked && !c.is_template() {
out.extend(layer_objects(c, r));
if let Some(inner) = inner
&& c.visible
&& !c.locked
&& !c.is_template()
{
out.extend(layer_objects(c, inner, outline));
}
} else if !c.is_ruler_guide() {
out.push((c, r));
if i == 0 && l.clips() {
out.push((c, mask_marquee(l, r), outline, Some(r)));
} else if inner.is_some() {
out.push((c, inner, outline, None));
}
}
}
out
}
/// The part of `r` in which the marquee can touch the clipping path of `parent` by its own
/// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its
/// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to.
fn mask_marquee(parent: &Node, r: Rect) -> Option<Rect> {
marquee_in_parent(parent, r, true)
}
/// Does the marquee `r` touch `clip`, the clipping path of a clip group or of a layer with a
/// clipping mask, on the edge of the region its live effects give it ([`clip_region`]), where
/// the clip shows? Never in outline, nor without live effects: its own geometry counts then.
fn clip_edge_touches(clip: &Node, r: Rect, outline: bool) -> bool {
if outline {
return false;
}
clip_region(clip).is_some_and(|region| {
region.as_ref().as_ref().is_some_and(|(bp, _)| {
// The edge of the region is its outline with each open subpath closed, as `fill_contains` fills it.
let mut edge = PathData::from_bezpath(bp);
edge.subpaths.iter_mut().for_each(|sp| sp.closed = true);
vectorcraft_geom::hit::intersects_rect(&edge, r)
})
})
}
/// Is `n` collected whole by [`collect_leaves`], not by its members?
fn is_leaf(n: &Node) -> bool {
!matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. })
}
/// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip
/// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched
/// by the copies it draws, as clicks hit them. Objects of every other kind except paths,
/// compound paths, layers and groups are touched by their box.
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool) -> bool {
/// compound paths, layers and groups are touched by their box. A clipping path is touched by
/// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]).
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool) -> bool {
match &n.kind {
NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r),
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
marquee_in(n, r).is_some_and(|r| {
children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope, whole_compounds))
let outline = outline || previews_off(n);
let inner = marquee_in_parent(n, r, outline);
children.iter().enumerate().any(|(i, c)| {
c.visible
&& !shaper_hides(n, i, scope)
&& if i == 0 && n.clips() {
mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline)
} else {
inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))
}
})
}
NodeKind::Compound { children, .. } if whole_compounds => {
children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r))
}
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds)),
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds)),
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 box with no width or no height (an instance of a symbol that draws a straight
// line) is touched where the marquee crosses it.
_ => n.geometric_bounds_with(s).is_some_and(|b| {
@@ -1325,18 +1581,30 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
}),
}
}
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, out: &mut Vec<NodeId>) {
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
let Some(r) = marquee_in(n, r) else { return };
let outline = outline || previews_off(n);
let inner = marquee_in_parent(n, r, outline);
for (i, c) in children.iter().enumerate() {
if c.visible && !c.locked && !shaper_hides(n, i, scope) {
collect_leaves(c, s, r, scope, whole_compounds, out);
if !c.visible || c.locked || shaper_hides(n, i, scope) {
continue;
}
if i == 0 && n.clips() {
let before = out.len();
if let Some(r) = mask_marquee(n, r) {
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
}
if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) {
out.push(c.id);
}
} else if let Some(r) = inner {
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
}
}
}
_ => {
if touches(n, s, r, scope, whole_compounds) {
if touches(n, s, r, scope, whole_compounds, outline) {
out.push(n.id);
}
}
@@ -1344,36 +1612,56 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
}
let symbols = doc.symbol_boxes();
let locks = doc.locked_artboards();
for (t, r) in tops {
for (t, r, outline, edge) in tops {
if !t.visible || t.locked || locks.holds_id(t.id) {
continue;
}
if leaves {
collect_leaves(t, &symbols, r, scope, whole_compounds, &mut out);
} else if touches(t, &symbols, r, scope, whole_compounds) {
let before = out.len();
if let Some(r) = r {
collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out);
}
if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) {
out.push(t.id);
}
} else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline))
|| edge.is_some_and(|e| clip_edge_touches(t, e, outline))
{
out.push(t.id);
}
}
out
}
/// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which
/// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a
/// layer, the marquee whose edge test it also takes (`clip_edge_touches`).
type Top<'a> = (&'a std::sync::Arc<Node>, Option<Rect>, bool, Option<Rect>);
/// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None
/// when the marquee misses it); otherwise it is all of `r`.
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its
/// clipping path ([`clip_regions`]; None when the marquee misses them); otherwise it is all of `r`.
pub fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
marquee_in_parent(parent, r, true)
}
/// The part of a marquee `r` in which it can touch the children of `parent`, by the region its
/// clipping path clips to ([`clip_areas`]), or by that path's plain shapes with `outline`
/// ([`marquee_in_view`]).
fn marquee_in_parent(parent: &Node, r: Rect, outline: bool) -> Option<Rect> {
match parent.children().and_then(|c| c.first()) {
Some(clip) if parent.clips() => marquee_in_clip(clip, r),
Some(clip) if parent.clips() => marquee_in_clip(clip, r, outline),
_ => Some(r),
}
}
/// The part of a marquee `r` in which it can touch the art that `clip` clips (the clipping path of
/// a clip group or of a layer with a clipping mask): `r` cut to the bounds of the regions `clip`
/// clips to ([`clip_regions`]), or `None` when `r` meets none of those regions. Within those
/// bounds, art outside a region that is not a rectangle still counts.
fn marquee_in_clip(clip: &Node, r: Rect) -> Option<Rect> {
/// clips to ([`clip_areas`], its plain shapes with `outline`), or `None` when `r` meets none of
/// those regions. Within those bounds, art outside a region that is not a rectangle still counts.
fn marquee_in_clip(clip: &Node, r: Rect, outline: bool) -> Option<Rect> {
use vectorcraft_geom::kurbo::Shape;
let regions = clip_regions(clip);
let regions = if outline { clip_regions(clip) } else { clip_areas(clip) };
// The edge of a region is its outline with each open subpath closed, as `fill_contains` fills it.
let meets = |(bp, rule): &(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)| {
let mut edge = vectorcraft_geom::PathData::from_bezpath(bp);
+303
View File
@@ -110,6 +110,252 @@ fn half_clipped(d: &mut Document) -> (Node, Node) {
(mask, art)
}
/// A stand-in for the engine's [`ClipRegion`]: with an effect named `test.move` in the clipping
/// path, its first shape moved 100 pt right; with one named `test.empty`, no region left to clip
/// by; without either, no geometry effect.
fn moved_clip_region(clip: &Node) -> Option<Option<(BezPath, FillRule)>> {
let (mut moves, mut empty) = (false, false);
clip.walk(&mut |n| {
moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move");
empty |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.empty");
});
if empty {
return Some(None);
}
if !moves {
return None;
}
Some(clip_regions(clip).into_iter().next().map(|(mut bp, rule)| {
bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0)));
(bp, rule)
}))
}
/// A visible effect named `test.move`, which [`moved_clip_region`] reads as moving the region.
fn test_move() -> crate::Effect {
crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }
}
/// Clicks inside a clip group whose clipping path has a live effect fall in the region the
/// registered [`ClipRegion`] gives it. The pointer moving over it evaluates the region once, and
/// again after the clipping path changes; a clipping path without effects is not evaluated.
#[test]
fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_changes() {
set_clip_region(moved_clip_region);
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
d.insert(Some(l), 0, clip).unwrap();
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
let before = evaluated();
let leaf = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf);
for x in [148.0, 150.0, 152.0] {
assert_eq!(leaf(&d, x), Some(art_id), "in the moved region");
}
assert_eq!(leaf(&d, 50.0), None, "the clipping path's own place");
assert_eq!(evaluated(), before + 1);
// Outline mode draws no effects: the art's edge shows within the clipping path's own shape.
let outline = HitOptions { outline: true, ..HitOptions::default() };
assert_eq!(hit_test(&d, Point::new(50.0, 0.5), outline).map(|h| h.leaf), Some(art_id), "outline mode");
// So with a marquee across the art's left edge: in the view, only in Outline view. The
// clipping path's own left edge lies there too, and counts in both.
let edge = Rect::new(-5.0, 40.0, 5.0, 60.0);
assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]);
assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]);
// `marquee_in` measures by the plain shapes, as its callers clip by them.
assert!(marquee_in(d.node(g).unwrap(), edge).is_some());
// Hidden, the effect no longer moves the region.
d.node_mut(mask_id).unwrap().appearance.effects[0].visible = false;
assert_eq!(leaf(&d, 50.0), Some(art_id));
assert_eq!(leaf(&d, 150.0), None);
assert_eq!(evaluated(), before + 1);
// Shown again and widened, the region is evaluated again.
let mask = d.node_mut(mask_id).unwrap();
mask.appearance.effects[0].visible = true;
if let NodeKind::Path { path, .. } = &mut mask.kind {
*path = shapes::rectangle(Rect::new(0.0, 0.0, 90.0, 100.0));
}
assert_eq!(leaf(&d, 180.0), Some(art_id));
assert_eq!(leaf(&d, 195.0), None);
assert_eq!(evaluated(), before + 2);
}
/// A marquee around a clipping path that an effect moved into the middle of large art touches the
/// clipping path on the edge of its moved region, in a clip group and in a clipping layer.
#[test]
fn a_marquee_touches_a_moved_clipping_path_on_its_region() {
set_clip_region(moved_clip_region);
let parts = |d: &mut Document| {
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default());
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 300.0)), Appearance::default_art());
(mask, art)
};
// Around the moved region (120..160) and the clipping path's own place, inside the art.
let around = Rect::new(10.0, 10.0, 170.0, 70.0);
let mut d = Document::new(400.0, 400.0);
let l = d.layers[0].id;
let (mask, art) = parts(&mut d);
let (g, mask_id) = (d.alloc_id(), mask.id);
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
d.insert(Some(l), 0, clip).unwrap();
assert_eq!(marquee(&d, around, None, false), [g]);
assert_eq!(marquee(&d, around, None, true), [mask_id]);
// Only over the clipping path's own place, the marquee misses the region but touches the
// clipping path's anchors, which a click on its outline also finds.
let own = Rect::new(10.0, 10.0, 70.0, 70.0);
assert_eq!(marquee(&d, own, None, false), [g]);
assert_eq!(marquee(&d, own, None, true), [mask_id]);
// Away from both, nothing.
assert!(marquee(&d, Rect::new(70.0, 10.0, 110.0, 70.0), None, true).is_empty());
let mut d = Document::new(400.0, 400.0);
let top = d.layers[0].id;
let (mask, art) = parts(&mut d);
let mask_id = mask.id;
let mut sublayer = (*d.layers[0]).clone();
sublayer.id = d.alloc_id();
if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind {
(*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true);
}
d.insert(Some(top), 0, sublayer).unwrap();
assert_eq!(marquee(&d, around, None, false), [mask_id]);
}
/// A clipping layer whose Preview is off draws its art in outline: clicks, the objects at a point
/// and marquees count its clipping path by its plain shape, without the effect that moves it.
#[test]
fn a_clipping_layer_with_preview_off_counts_its_plain_clipping_path() {
set_clip_region(moved_clip_region);
let mut d = Document::new(300.0, 200.0);
let top = d.layers[0].id;
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
let art_id = art.id;
let mut sublayer = (*d.layers[0]).clone();
sublayer.id = d.alloc_id();
if let NodeKind::Layer { children, clip, preview, .. } = &mut sublayer.kind {
(*children, *clip, *preview) = (vec![Arc::new(mask), Arc::new(art)], true, false);
}
d.insert(Some(top), 0, sublayer).unwrap();
// The art's top edge, within the clipping path's own shape.
let p = Point::new(50.0, 0.5);
assert_eq!(hit_test(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art_id));
assert_eq!(objects_at(&d, p, HitOptions::default(), None).first(), Some(&art_id));
assert!(marquee(&d, Rect::new(45.0, -5.0, 55.0, 5.0), None, true).contains(&art_id));
}
/// The pointer moving over empty canvas past more clip groups with live effects than the regions
/// kept measures each group's box once: the boxes are kept for every clip group.
#[test]
fn hovers_past_many_clip_groups_evaluate_each_clipping_path_once() {
set_clip_region(moved_clip_region);
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
for i in 0..(2 * CLIPS_KEPT) {
let x = 20.0 * i as f64;
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default());
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 10.0)), Appearance::default_art());
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
d.insert(Some(l), 0, clip).unwrap();
}
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
let empty = Point::new(500.0, 500.0);
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
let first = evaluated();
for _ in 0..3 {
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
}
assert_eq!(evaluated(), first);
}
/// With more clip groups with live effects than the boxes kept, a new box replaces only as many
/// others as it needs room for: the next hover finds most of the boxes and evaluates few regions.
#[test]
fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() {
set_clip_region(moved_clip_region);
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let groups = CLIP_BOXES_KEPT + 64;
let mut members = Vec::with_capacity(groups);
for i in 0..groups {
let x = (i % 100) as f64 * 5.0;
let y = (i / 100) as f64 * 5.0;
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 2.0, y + 2.0)), Appearance::default());
mask.appearance.effects.push(test_move());
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 2.0)), Appearance::default_art());
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
members.push(Arc::new(clip));
}
if let Some(children) = d.node_mut(l).and_then(|n| n.children_mut()) {
*children = members;
}
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
let empty = Point::new(900.0, 900.0);
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
let first = evaluated();
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
let again = evaluated() - first;
assert!(again < groups / 8, "{again} of {groups} regions evaluated again");
}
/// Every test of a clip group by its clipping path follows the region a live effect moved it to:
/// the selected art hidden by the mask, a click into a group holding the clip group, the locked
/// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer
/// whose Preview is off, which is clicked in outline while the layer above clips by its region.
#[test]
fn every_clip_test_follows_the_moved_region() {
set_clip_region(moved_clip_region);
let (moved, own) = (Point::new(150.0, 50.0), Point::new(50.0, 50.0));
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(test_move());
let (g, art_id) = (d.alloc_id(), art.id);
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
let outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
d.insert(Some(l), 0, outer.clone()).unwrap();
let opt = HitOptions::default();
assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id), "hidden at the clipping path's own place");
assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None, "shown in the moved region");
let symbols = d.symbol_boxes();
assert_eq!(hit_any(&outer, moved, opt, &symbols), Some(HitKind::Fill));
assert_eq!(hit_any(&outer, own, opt, &symbols), None);
d.node_mut(art_id).unwrap().locked = true;
assert_eq!(locked_objects_at(&d, moved, opt), [art_id]);
assert!(locked_objects_at(&d, own, opt).is_empty());
// A clipping layer holding the mask and a sublayer whose Preview is off, with the art.
let mut d = Document::new(300.0, 200.0);
let top = d.layers[0].id;
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(test_move());
let art_id = art.id;
let mut sublayer = (*d.layers[0]).clone();
sublayer.id = d.alloc_id();
if let NodeKind::Layer { children, preview, .. } = &mut sublayer.kind {
(*children, *preview) = (vec![Arc::new(art)], false);
}
d.insert(Some(top), 0, sublayer).unwrap();
d.insert(Some(top), 0, mask).unwrap();
d.node_mut(top).unwrap().set_clips(true);
// The art's top edge, at the clipping path's own place and in the moved region.
let (own, moved) = (Point::new(50.0, 0.5), Point::new(150.0, 0.5));
assert!(hit_test(&d, own, opt).is_none());
assert_eq!(hit_test(&d, moved, opt).map(|h| h.leaf), Some(art_id));
assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id));
assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None);
}
/// The art a mask hides counts only for a selected object: there a click hits nothing, and the
/// selection tools grab the selection by that art. Not where the art shows (the click hits it),
/// beyond the art, for the clip group selected as a whole, nor for art a click can't hit (locked,
@@ -1549,6 +1795,63 @@ fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() {
assert!((b.x1 - 100.0).abs() < 1e-6, "the layer's outline is cut to the mask: {b:?}");
}
/// In a dynamic symbol's art, an object in a clipping layer whose clipping path has a live effect
/// is picked and outlined in the region the effect gives the clipping path. In Outline view, and
/// when Preview is off for the layer in the art or for the layer the instance is on, the plain
/// clipping path counts, as the canvas draws it. An effect that leaves no region leaves no outline.
#[test]
fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() {
set_clip_region(moved_clip_region);
// The instance of a symbol whose art is a clipping layer; `preview` is the Preview of that
// layer and of the document layer the instance is on.
let instance = |effect: &str, preview: [bool; 2]| {
let mut d = Document::new(300.0, 200.0);
if let NodeKind::Layer { preview: p, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind {
*p = preview[1];
}
let l = d.layers[0].id;
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(crate::Effect { id: effect.into(), ..test_move() });
let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2));
if let NodeKind::Layer { children, preview: p, .. } = &mut layer.kind {
(*children, *p) = (vec![Arc::new(mask), Arc::new(art)], preview[0]);
}
layer.set_clips(true);
let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]);
d.symbols.push(crate::Symbol { dynamic: true, name: "Clipped".into(), art: Arc::new(root) });
let inst = d.alloc_id();
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
(d, inst)
};
let outline_box = |d: &Document, inst: NodeId, opt: HitOptions| {
let o = symbol_part_outline_in_view(d, d.node(inst).unwrap(), &[0, 1], opt).unwrap();
vectorcraft_geom::kurbo::Shape::bounding_box(&o)
};
let opt = HitOptions::default();
let (d, inst) = instance("test.move", [true, true]);
let n = d.node(inst).unwrap();
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), Some(vec![0, 1]), "in the moved region");
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None, "where the clipping path was");
let b = outline_box(&d, inst, opt);
assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 200.0).abs() < 1e-6, "the outline is cut to the moved region: {b:?}");
let b = outline_box(&d, inst, HitOptions { outline: true, ..opt });
assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "in Outline view, to the plain clipping path: {b:?}");
// With Preview off, the art's top edge counts within the plain clipping path.
for (preview, what) in [([false, true], "the layer in the art"), ([true, false], "the layer the instance is on")] {
let (d, inst) = instance("test.move", preview);
let n = d.node(inst).unwrap();
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 0.5), opt), Some(vec![0, 1]), "on the edge the canvas draws, Preview off for {what}");
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 0.5), opt), None, "past the plain clipping path, Preview off for {what}");
let b = outline_box(&d, inst, opt);
assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "Preview off for {what}: the plain clipping path: {b:?}");
}
// An effect that leaves the clipping path no region hides the art: no pick and no outline.
let (d, inst) = instance("test.empty", [true, true]);
let n = d.node(inst).unwrap();
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None);
assert!(symbol_part_outline(&d, n, &[0, 1]).unwrap().elements().is_empty(), "nothing is drawn, so nothing is outlined");
}
/// 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.
+1
View File
@@ -119,6 +119,7 @@ pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOption
pub use style_libs::StyleLibrary;
pub use text::FontHeightReference;
pub use text::GlyphChoice;
pub use text::GlyphForm;
pub use text::WarichuAlign;
pub use text::{
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
+8 -1
View File
@@ -211,7 +211,9 @@ impl Node {
/// A quick box round everything the object can paint, for culling clicks: paths and compound
/// paths grow their geometric bounds by the farthest their strokes can reach from any path
/// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in
/// ([`Appearance::outset`]) instead of measuring along their shape. A clip group's or a
/// clipping layer's box takes in the region that the live geometry effects of its clipping
/// path give it ([`crate::hit::set_clip_region`]). An image's box takes in
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
@@ -261,6 +263,11 @@ impl Node {
NodeKind::Blend { children, spec } => {
vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols))
}
// The live geometry effects of a clipping path can move or grow the region it clips to
// past its plain shape ([`crate::hit::set_clip_region`]).
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
}
_ => self.visual(symbols),
}
}
+2 -2
View File
@@ -18,8 +18,8 @@ mod wrap;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
use char_style::yes;
pub use char_style::{
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES,
WARICHU_SCALE, WarichuAlign,
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics,
WARICHU_LINES, WARICHU_SCALE, WarichuAlign,
};
pub use composite::{
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
+94
View File
@@ -205,6 +205,99 @@ pub struct CharStyle {
/// default glyph otherwise. Saved only when set.
#[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")]
pub glyph_alternate: Option<GlyphChoice>,
/// The East Asian glyph form these characters are drawn in (Glyphs panel menu, with Show East
/// Asian Options): one OpenType feature of the font, such as JIS 78 forms (`jp78`), or the
/// font's default glyphs. The text keeps its characters. Saved only when set.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, rename = "glyphForm", skip_serializing_if = "crate::skip::is_default")]
pub glyph_form: GlyphForm,
}
/// The East Asian glyph form characters are drawn in ([`CharStyle::glyph_form`]): the font's
/// default glyphs, or the glyphs one OpenType feature substitutes. One form at a time.
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist>
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum GlyphForm {
/// The font's default glyphs.
#[default]
Default,
/// Traditional forms (`trad`).
Traditional,
/// Expert forms (`expt`).
Expert,
/// JIS 2004 forms (`jp04`).
Jis04,
/// JIS 90 forms (`jp90`).
Jis90,
/// JIS 78 forms (`jp78`).
Jis78,
/// JIS 83 forms (`jp83`).
Jis83,
/// Monospaced full-width forms (`fwid`).
FullWidth,
/// Monospaced half-width forms (`hwid`).
HalfWidth,
/// Monospaced third-width forms (`twid`).
ThirdWidth,
/// Monospaced quarter-width forms (`qwid`).
QuarterWidth,
}
impl GlyphForm {
/// Every form, in menu order, the default last.
pub const ALL: [GlyphForm; 11] = [
GlyphForm::Traditional,
GlyphForm::Expert,
GlyphForm::Jis04,
GlyphForm::Jis90,
GlyphForm::Jis78,
GlyphForm::Jis83,
GlyphForm::FullWidth,
GlyphForm::HalfWidth,
GlyphForm::ThirdWidth,
GlyphForm::QuarterWidth,
GlyphForm::Default,
];
/// The name files and commands give this form (as it is saved).
pub fn id(self) -> &'static str {
match self {
GlyphForm::Default => "default",
GlyphForm::Traditional => "traditional",
GlyphForm::Expert => "expert",
GlyphForm::Jis04 => "jis04",
GlyphForm::Jis90 => "jis90",
GlyphForm::Jis78 => "jis78",
GlyphForm::Jis83 => "jis83",
GlyphForm::FullWidth => "fullWidth",
GlyphForm::HalfWidth => "halfWidth",
GlyphForm::ThirdWidth => "thirdWidth",
GlyphForm::QuarterWidth => "quarterWidth",
}
}
/// The form [`GlyphForm::id`] names; `None` for any other name.
pub fn from_id(id: &str) -> Option<GlyphForm> {
GlyphForm::ALL.into_iter().find(|f| f.id() == id)
}
/// The OpenType feature that draws this form; `None` for the default glyphs.
pub fn feature(self) -> Option<&'static [u8; 4]> {
Some(match self {
GlyphForm::Default => return None,
GlyphForm::Traditional => b"trad",
GlyphForm::Expert => b"expt",
GlyphForm::Jis04 => b"jp04",
GlyphForm::Jis90 => b"jp90",
GlyphForm::Jis78 => b"jp78",
GlyphForm::Jis83 => b"jp83",
GlyphForm::FullWidth => b"fwid",
GlyphForm::HalfWidth => b"hwid",
GlyphForm::ThirdWidth => b"twid",
GlyphForm::QuarterWidth => b"qwid",
})
}
}
/// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it
@@ -586,6 +679,7 @@ impl Default for CharStyle {
no_break: false,
language: None,
glyph_alternate: None,
glyph_form: GlyphForm::Default,
}
}
}
+7 -3
View File
@@ -476,14 +476,18 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
/// `m`, art evaluated from an object, with its children baked and then given ids of their own (the
/// pieces copied from the source keep the source's ids until then). The pieces are baked with the
/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id.
/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. When
/// `m` clips, its clipping path, unless it is type, first takes the geometry effects in it as the
/// canvas clips by it ([`crate::clip::with_clip_effects_applied`]).
fn bake_pieces(d: &mut Document, mut m: Node) -> Node {
let mut seen = std::collections::HashSet::from([m.id]);
let clip = usize::from(m.clips() && !m.children().and_then(|ch| ch.first()).is_some_and(|c| matches!(c.kind, NodeKind::Text(_))));
let children = m.children().cloned().unwrap_or_default();
let children = children
.into_iter()
.map(|c| {
let c = Arc::unwrap_or_clone(c);
.enumerate()
.map(|(i, c)| {
let c = (i < clip).then(|| crate::clip::with_clip_effects_applied(&c)).flatten().unwrap_or_else(|| Arc::unwrap_or_clone(c));
let mut c = one_deeper(|| bake_node(d, &c)).unwrap_or(c);
fresh_ids(d, &mut c, &mut seen);
Arc::new(c)
+8 -4
View File
@@ -12,10 +12,14 @@ use vectorcraft_geom::{BezPath, FillRule, PathData};
/// fills and strokes: the region is then the union of the paths they give, as an export bakes them.
/// `None` when there is nothing to clip by (the clipped art is then hidden).
pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> {
match clip_effects_applied(clip, true, || true) {
Some(m) => m.clip_outline(Some(&outline_text), &unite),
None => clip.clip_outline(Some(&outline_text), &unite),
}
reshaped_clip_outline(clip).unwrap_or_else(|| clip.clip_outline(Some(&outline_text), &unite))
}
/// [`clip_outline`] of a clipping path that a live geometry effect reshapes; `None` when nothing
/// `clip` clips by has a geometry effect of its own or on a fill or stroke. A hidden member of a
/// group or layer does not clip, so its effects are not counted.
pub fn reshaped_clip_outline(clip: &Node) -> Option<Option<(BezPath, FillRule)>> {
clip_effects_applied(clip, true, || true).map(|m| m.clip_outline(Some(&outline_text), &unite))
}
/// `n`, the clipping path of a clip group, with the live geometry effects of everything it clips by
+1 -1
View File
@@ -72,7 +72,7 @@ pub use bake::{
StrokeArt, WrittenLayers, bake_appearance, bake_document, bake_document_placing_symbols, bake_type_appearance, expand_art, expand_leaf,
fresh_ids, needs_bake,
};
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, warp_pieces_translucent};
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent};
pub use group::{
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art,
+1
View File
@@ -16,6 +16,7 @@ use vectorcraft_geom::{Affine, Rect, Vec2};
use crate::pixel::PixelSpace;
use crate::util::{num, text};
pub mod defaults;
#[cfg(test)]
mod tests;
+248
View File
@@ -0,0 +1,248 @@
//! The default SVG filters: the filters Effect › SVG Filters and Apply SVG Filter list in every
//! document. The set, the names and the values are VectorCraft's own, written with the filter
//! primitives of SVG 1.1 (<https://www.w3.org/TR/SVG11/filters.html>). A default is not part of a
//! document until it is applied or edited there: the document then holds a copy under the
//! default's name, and that copy stands in the default's place in the lists. Every default computes
//! in sRGB (`color-interpolation-filters="sRGB"`), so art a filter passes through keeps its colors.
use vectorcraft_doc::SvgFilter;
/// A default SVG filter: its name (the `<filter>` element's `id`) and the element's XML.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DefaultFilter {
pub name: &'static str,
pub xml: &'static str,
}
/// The default filters, in the order the lists show them.
pub const DEFAULT_FILTERS: [DefaultFilter; 14] = [
DefaultFilter {
name: "Soft Blur",
xml: r#"<filter id="Soft Blur" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="2"/></filter>"#,
},
DefaultFilter {
name: "Heavy Blur",
xml: r#"<filter id="Heavy Blur" x="-50%" y="-50%" width="200%" height="200%" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="6"/></filter>"#,
},
DefaultFilter {
name: "Soft Shadow",
xml: r#"<filter id="Soft Shadow" x="-30%" y="-30%" width="170%" height="170%" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceAlpha" stdDeviation="3"/><feOffset dx="4" dy="4"/><feComponentTransfer><feFuncA type="linear" slope="0.5"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>"#,
},
DefaultFilter {
name: "Hard Shadow",
xml: r#"<filter id="Hard Shadow" x="-20%" y="-20%" width="150%" height="150%" color-interpolation-filters="sRGB"><feOffset in="SourceAlpha" dx="3" dy="3"/><feComponentTransfer><feFuncA type="linear" slope="0.6"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>"#,
},
DefaultFilter {
name: "Glow",
xml: r##"<filter id="Glow" x="-40%" y="-40%" width="180%" height="180%" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceAlpha" stdDeviation="4" result="spread"/><feFlood flood-color="#ffd24a"/><feComposite in2="spread" operator="in"/><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>"##,
},
DefaultFilter {
name: "Bevel",
xml: r##"<filter id="Bevel" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceAlpha" stdDeviation="2" result="height"/><feSpecularLighting in="height" surfaceScale="4" specularConstant="0.8" specularExponent="16" lighting-color="#ffffff" result="light"><feDistantLight azimuth="225" elevation="45"/></feSpecularLighting><feComposite in="light" in2="SourceAlpha" operator="in" result="lit"/><feComposite in="SourceGraphic" in2="lit" operator="arithmetic" k1="0" k2="1" k3="1" k4="0"/></filter>"##,
},
DefaultFilter {
name: "Emboss",
xml: r#"<filter id="Emboss" color-interpolation-filters="sRGB"><feConvolveMatrix order="3" kernelMatrix="-2 -1 0 -1 1 1 0 1 2" preserveAlpha="true"/></filter>"#,
},
DefaultFilter {
name: "Thicken",
xml: r#"<filter id="Thicken" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB"><feMorphology operator="dilate" radius="1.5"/></filter>"#,
},
DefaultFilter {
name: "Thin",
xml: r#"<filter id="Thin" color-interpolation-filters="sRGB"><feMorphology operator="erode" radius="1.5"/></filter>"#,
},
DefaultFilter {
name: "Rough Edges",
xml: r#"<filter id="Rough Edges" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB"><feTurbulence type="turbulence" baseFrequency="0.05" numOctaves="2" result="waves"/><feDisplacementMap in="SourceGraphic" in2="waves" scale="6" xChannelSelector="R" yChannelSelector="G"/></filter>"#,
},
DefaultFilter {
name: "Grain",
xml: r#"<filter id="Grain" color-interpolation-filters="sRGB"><feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.35 0"/><feComposite in2="SourceAlpha" operator="in" result="specks"/><feMerge><feMergeNode in="SourceGraphic"/><feMergeNode in="specks"/></feMerge></filter>"#,
},
DefaultFilter {
name: "Grayscale",
xml: r#"<filter id="Grayscale" color-interpolation-filters="sRGB"><feColorMatrix type="saturate" values="0"/></filter>"#,
},
DefaultFilter {
name: "Invert",
xml: r#"<filter id="Invert" color-interpolation-filters="sRGB"><feComponentTransfer><feFuncR type="table" tableValues="1 0"/><feFuncG type="table" tableValues="1 0"/><feFuncB type="table" tableValues="1 0"/></feComponentTransfer></filter>"#,
},
DefaultFilter {
name: "Hue Shift",
xml: r#"<filter id="Hue Shift" color-interpolation-filters="sRGB"><feColorMatrix type="hueRotate" values="180"/></filter>"#,
},
];
/// The default filter named `name`.
pub fn default_filter(name: &str) -> Option<DefaultFilter> {
DEFAULT_FILTERS.iter().copied().find(|f| f.name == name)
}
impl DefaultFilter {
/// The filter as a document holds it once it is applied or edited there.
pub fn to_filter(self) -> SvgFilter {
SvgFilter { name: self.name.to_string(), xml: self.xml.to_string() }
}
}
/// A filter of the lists ([`listed`]), and whether it is a default the document does not hold.
#[derive(Clone, Debug, PartialEq)]
pub struct Listed {
pub filter: SvgFilter,
/// A default the document has no filter named for: applying or editing it adds a copy.
pub default: bool,
}
/// The filters Effect › SVG Filters and Apply SVG Filter list for a document that holds `held`,
/// and how many of them come first as the defaults: each default in [`DEFAULT_FILTERS`]' order (the
/// document's filter of that name in its place), then the document's other filters in their order.
pub fn listed(held: &[SvgFilter]) -> (Vec<Listed>, usize) {
let mut out: Vec<Listed> = DEFAULT_FILTERS
.iter()
.map(|d| match held.iter().find(|f| f.name == d.name) {
Some(f) => Listed { filter: f.clone(), default: false },
None => Listed { filter: d.to_filter(), default: true },
})
.collect();
let defaults = out.len();
out.extend(held.iter().filter(|f| default_filter(&f.name).is_none()).map(|f| Listed { filter: f.clone(), default: false }));
(out, defaults)
}
#[cfg(test)]
mod tests {
use serde_json::json;
use vectorcraft_doc::Effect;
use vectorcraft_geom::{Affine, Point};
use super::*;
use crate::pixel::{Channels, PixelSpace};
use crate::svg_filter::{SVG_FILTER, SvgFilterFx, check, with_id};
use crate::{PixelFx, RasterFx, raster_effects};
/// A `w` × `w` raster whose pixels are one point wide.
fn space(w: usize) -> PixelSpace {
let wd = w as f64;
PixelSpace {
to_doc: Affine::scale(1.0),
px: 1.0,
center: Point::new(wd / 2.0, wd / 2.0),
channels: Channels::Rgb,
line: 1.0,
extent: 0.5 * wd.hypot(wd),
}
}
/// The default named `name` as the renderer reads it.
fn fx(name: &str) -> SvgFilterFx {
let d = default_filter(name).unwrap_or_else(|| panic!("no default {name}"));
let e = Effect { id: SVG_FILTER.into(), params: json!({"name": d.name, "xml": d.xml}), visible: true };
match raster_effects(&[e]).first() {
Some(RasterFx::Pixel(PixelFx::Svg(f))) => f.clone(),
other => panic!("{name}: {other:?}"),
}
}
/// A 40 × 40 raster with an opaque square of `rgb` from 10 to 30, run through default `name`.
fn run(name: &str, rgb: [u8; 3]) -> Vec<u8> {
let mut data: Vec<u8> = (0..40usize)
.flat_map(|y| (0..40usize).map(move |x| (x, y)))
.flat_map(|(x, y)| if (10..30).contains(&x) && (10..30).contains(&y) { [rgb[0], rgb[1], rgb[2], 255] } else { [0; 4] })
.collect();
fx(name).apply(&mut data, 40, 40, &space(40));
data
}
fn at(d: &[u8], x: usize, y: usize) -> [u8; 4] {
let i = (y * 40 + x) * 4;
[d[i], d[i + 1], d[i + 2], d[i + 3]]
}
#[test]
fn every_default_is_a_filter_the_check_takes_under_its_own_name() {
let mut seen = std::collections::BTreeSet::new();
for d in DEFAULT_FILTERS {
assert_eq!(check(d.xml), Ok(d.name.to_string()), "{}", d.name);
assert!(seen.insert(d.name), "{} is listed twice", d.name);
assert_eq!(d.name, d.name.trim());
// Edit SVG Filter keeps the name by writing it as the id: a default's code comes back as it is.
assert_eq!(with_id(d.xml, d.name).as_deref(), Some(d.xml), "{}", d.name);
assert_eq!(default_filter(d.name), Some(d));
assert!(d.xml.contains(r#" color-interpolation-filters="sRGB""#), "{} computes in sRGB", d.name);
}
assert!(DEFAULT_FILTERS.len() <= SvgFilter::MAX);
assert_eq!(default_filter("soft blur"), None, "names match exactly");
}
#[test]
fn every_default_draws_and_is_written_to_svg_as_a_filter() {
let plain = {
let mut d = vec![0u8; 40 * 40 * 4];
for y in 10..30 {
for x in 10..30 {
d[(y * 40 + x) * 4..(y * 40 + x) * 4 + 4].copy_from_slice(&[200, 60, 20, 255]);
}
}
d
};
for d in DEFAULT_FILTERS {
assert_ne!(run(d.name, [200, 60, 20]), plain, "{} changes what is drawn", d.name);
assert!(fx(d.name).writes_as_svg11(), "{} is written as SVG 1.1", d.name);
}
}
/// The color defaults against SVG 1.1's own arithmetic, in sRGB as each filter asks.
#[test]
fn the_color_defaults_compute_what_svg_1_1_defines() {
let near = |got: [u8; 4], want: [u8; 4]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 1);
// feComponentTransfer, type="table" with values 1 0: C' = 1 - C (§15.11).
let inv = at(&run("Invert", [200, 60, 20]), 20, 20);
assert!(near(inv, [55, 195, 235, 255]), "{inv:?}");
// feColorMatrix type="saturate" values="0": every channel is 0.213 R + 0.715 G + 0.072 B (§15.10).
let grey = at(&run("Grayscale", [200, 60, 20]), 20, 20);
let l = (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64).round() as u8;
assert!(near(grey, [l, l, l, 255]), "{grey:?} for {l}");
// feColorMatrix type="hueRotate" values="180" (§15.10): cos = -1 and sin = 0 leave
// R' = (2·0.213 - 1) R + 2·0.715 G + 2·0.072 B, and likewise for G' and B'.
let hue = at(&run("Hue Shift", [200, 60, 20]), 20, 20);
let lum2 = 2.0 * (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64);
let turned = [lum2 - 200.0, lum2 - 60.0, lum2 - 20.0].map(|v| v.round().clamp(0.0, 255.0) as u8);
assert!(near(hue, [turned[0], turned[1], turned[2], 255]), "{hue:?} for {turned:?}");
}
/// The shape defaults against what their primitives define: an offset copy of the alpha behind
/// the art (feOffset, §15.21), and a shape grown or shrunk by its radius (feMorphology, §15.20).
#[test]
fn the_shape_defaults_move_and_resize_the_alpha() {
let shadow = run("Hard Shadow", [200, 60, 20]);
assert_eq!(at(&shadow, 20, 20), [200, 60, 20, 255], "the art is on top");
// Right of and below the art by up to 3: black at 60% alpha (premultiplied 153).
assert_eq!(at(&shadow, 31, 31), [0, 0, 0, 153]);
assert_eq!(at(&shadow, 34, 34)[3], 0, "past the offset");
assert_eq!(at(&shadow, 8, 8)[3], 0, "nothing up and left");
let thick = run("Thicken", [200, 60, 20]);
assert_eq!((at(&thick, 9, 20)[3], at(&thick, 7, 20)[3]), (255, 0), "grown by its radius");
let thin = run("Thin", [200, 60, 20]);
assert_eq!((at(&thin, 10, 20)[3], at(&thin, 13, 20)[3]), (0, 255), "shrunk by its radius");
let soft = run("Soft Shadow", [200, 60, 20]);
assert_eq!(at(&soft, 20, 20), [200, 60, 20, 255]);
let below = at(&soft, 33, 33);
assert!(below[3] > 0 && below[3] < 128 && below[0] == 0, "a blurred, half-strength shadow: {below:?}");
}
#[test]
fn the_lists_show_the_defaults_first_with_the_documents_copy_in_place() {
let (all, defaults) = listed(&[]);
assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len(), DEFAULT_FILTERS.len()));
assert!(all.iter().all(|l| l.default));
let mine = SvgFilter { name: "Mine".into(), xml: "<filter id=\"Mine\"><feOffset/></filter>".into() };
let glow = SvgFilter { name: "Glow".into(), xml: "<filter id=\"Glow\"><feOffset dx=\"1\"/></filter>".into() };
let (all, defaults) = listed(&[mine.clone(), glow.clone()]);
assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len() + 1, DEFAULT_FILTERS.len()));
let at = DEFAULT_FILTERS.iter().position(|d| d.name == "Glow").unwrap();
assert_eq!(all[at], Listed { filter: glow, default: false }, "the document's Glow where the default was");
assert_eq!(all.last(), Some(&Listed { filter: mine, default: false }));
assert_eq!(all.iter().filter(|l| l.default).count(), DEFAULT_FILTERS.len() - 1);
}
}
+42
View File
@@ -172,6 +172,48 @@ fn the_clipping_paths_effects_apply_before_the_clip_groups() {
assert!((b.x0 - want.x0).abs() < 0.5 && (b.x1 - want.x1).abs() < 0.5, "exported: {b:?} against {want:?}");
}
#[test]
fn a_clip_group_with_a_fill_or_stroke_of_its_own_clips_as_the_canvas_does() {
// A clip group with a fill or a stroke of its own and no effects: the export turns its paint
// into art and still clips by the outline the canvas clips by, Transform copies included.
let items = [
vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))),
vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 2.0)),
];
let copies = || fx("distort.transform", json!({"moveH": 60, "copies": 1}));
let roughen = fx("distort.roughen", json!({"size": 10, "detail": 10, "relative": false}));
// A ring: a compound path of two squares with effects `own`, its hole with effects `hole_fx`.
let ring = |hole_fx: Vec<Effect>, own: Vec<Effect>| {
let outer = Node::path(NodeId(3), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), Appearance::default());
let mut hole = Node::path(NodeId(4), shapes::rectangle(Rect::new(75.0, 75.0, 125.0, 125.0)), Appearance::default());
hole.appearance.effects = hole_fx;
let mut c =
Node::new(NodeId(2), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: vectorcraft_geom::FillRule::EvenOdd });
c.appearance.effects = own;
c
};
let clips = [
("copies", clipping_path(2, vec![copies()])),
("roughen", clipping_path(2, vec![roughen])),
("a compound path's copies", ring(vec![], vec![copies()])),
("a compound path member's copies", ring(vec![copies()], vec![])),
];
for item in &items {
for (what, clip) in &clips {
let mut d = Document::new(400.0, 400.0);
let layer = d.layers[0].id;
let live = clip_outline(clip).unwrap();
let mut group = clip_group(1, clip.clone());
group.appearance.items.push(item.clone());
d.insert(Some(layer), 0, group).unwrap();
let exported = clip_outline(&baked_clip(&d)).unwrap();
assert_eq!(live, exported, "{what} with {item:?}: the canvas clips by the outline the export writes");
}
}
let b = bounds(&clips[0].1);
assert!((b.x0 - 50.0).abs() < 1e-6 && (b.x1 - 210.0).abs() < 1e-6, "the clip covers both copies: {b:?}");
}
#[test]
fn nested_effects_apply_before_the_clip_groups() {
// The clip group grows its clipping path by 10 (Offset Path). Inside the clipping path a
+6 -5
View File
@@ -288,9 +288,10 @@ fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result<V
/// The most anchor points an Image Trace may make, a guard for memory: a trace past it is refused
/// with advice instead (#525). A trace keeps about 90 bytes an anchor in the document (measured on
/// code-drawn photos of 2000 × 2000 to 6000 × 4000 pixels), so 8,000,000 anchors are about
/// 0.7 GB, with a peak of about 1 GB while tracing: a 4000 × 3000 photo at High Fidelity Photo
/// makes about 1.9 million, and even at Paths 100, Noise 1 and every tone about 7.9 million. On the
/// web, where a page has at most 4 GB of memory, the limit stays at 2,000,000.
/// 0.7 GB, with a peak of about 1 GB while tracing: a 4000 × 3000 photo at Limited 64 colors,
/// Paths 90, Corners 25 and Noise 4 makes about 1.9 million, and even at Paths 100, Noise 1 and
/// every tone about 7.9 million. On the web, where a page has at most 4 GB of memory, the limit
/// stays at 2,000,000.
#[cfg(not(target_arch = "wasm32"))]
pub const MAX_TRACE_ANCHORS: usize = 8_000_000;
@@ -1139,7 +1140,7 @@ mod trace_limit_tests {
assert_eq!(w, ["Flat Logo traced the image at 946 × 710 pixels, averaged down from 16000 × 12000."]);
}
// A 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million anchors, which must fit;
// the limit still guards memory (about 90 bytes an anchor). Checked when the tests build.
// A 4000 × 3000 photo at Limited 64 colors, Paths 90, Corners 25 and Noise 4 makes about
// 1.9 million anchors, which must fit; the limit still guards memory (about 90 bytes an anchor). Checked when the tests build.
const _: () = assert!(MAX_TRACE_ANCHORS >= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000);
}
+1 -1
View File
@@ -718,7 +718,7 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
/// sets its Warp style (`warpStyle`), its 3D type (`threeDType`) or visibility (`visible`), as one
/// undo step. They are checked as `effect.apply` checks them, and a visible 3D effect must still
/// fit; a hidden one has its given values checked. → `{ids}`.
fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "effect.setParams";
let index = index_param(p, "index", C)?;
let mut params = p.get("params").cloned().unwrap_or(Value::Null);
+194 -29
View File
@@ -2,13 +2,13 @@
//! (unknown keys are ignored, so one params object can carry the options of several formats).
use std::borrow::Cow;
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use serde::Deserialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use vectorcraft_doc::{Artboard, Document, Node, NodeKind};
use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SymbolOverride};
use vectorcraft_geom::Rect;
use vectorcraft_render::AntiAlias;
use vectorcraft_render::encode::jpeg::{self, JpegOptions};
@@ -450,31 +450,85 @@ pub fn export_art_bounds(doc: &Document, format: &str) -> Option<Rect> {
/// The bounds of the visible art of `doc` with the objects that `left_out` picks hidden
/// ([`hidden_nodes`]) and the ones in the art of the symbols that instances show taken out
/// ([`without_nodes`]: symbol art is measured with its hidden objects). An instance of a symbol
/// whose art is all picked or hidden is hidden too. The art of a dynamic symbol is measured whole:
/// an instance can paint its objects, and finds them by their places in the art.
/// whose art is all picked or hidden is hidden too. The drawn instances of a dynamic symbol that
/// make the same appearance changes to its art are measured on a copy of the symbol of their own,
/// in which each object is judged with those changes ([`as_drawn`]); the objects taken out of
/// a dynamic symbol's art leave empty groups in their places, by which instances find the objects
/// they change.
fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Rect> {
// The symbols instances show (the first of each name) that aren't dynamic.
// The symbols instances show (the first of each name).
let mut names = HashSet::new();
let shown: Vec<(usize, &vectorcraft_doc::Symbol)> =
doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).filter(|(_, s)| !s.dynamic).collect();
let shown: Vec<usize> = doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).map(|(i, _)| i).collect();
// The sets of appearance changes the drawn instances of each dynamic symbol make to its art;
// `None` for a symbol with more than `MAX_ART_COPIES`, which is measured whole.
let mut sets: HashMap<&str, Option<Vec<Vec<&SymbolOverride>>>> =
shown.iter().filter_map(|i| doc.symbols.get(*i)).filter(|s| s.dynamic).map(|s| (s.name.as_str(), Some(Vec::new()))).collect();
if !sets.is_empty() {
let mut walked = HashSet::new();
for l in &doc.layers {
drawn_changes(doc, l, left_out, true, &mut walked, &mut sets);
}
}
// Each set of changes gets a copy of its symbol, appended after the symbols, which the instances
// that make those changes show instead.
let variant = |symbol: &str, n: &Node| -> Option<String> {
let k = sets.get(symbol)?.as_ref()?.iter().position(|c| *c == own_changes(n))?;
Some(format!("{symbol}\u{0}{k}"))
};
let mut copies: Vec<(usize, &[&SymbolOverride])> = Vec::new();
let remapped_doc = sets.values().flatten().any(|v| !v.is_empty()).then(|| {
let mut d = doc.clone();
for l in &mut d.layers {
if let Some(n) = remapped(l, &variant) {
*l = n;
}
}
for s in &mut d.symbols {
if let Some(n) = remapped(&s.art, &variant) {
s.art = n;
}
}
for i in &shown {
let Some(s) = d.symbols.get(*i).cloned() else { continue };
for (k, c) in sets.get(s.name.as_str()).into_iter().flatten().flatten().enumerate() {
copies.push((d.symbols.len(), c.as_slice()));
d.symbols.push(vectorcraft_doc::Symbol { name: format!("{}\u{0}{k}", s.name), ..s.clone() });
}
}
d
});
let src = remapped_doc.as_ref().unwrap_or(doc);
// The symbols to measure with the changes their instances make (`None` for a static symbol),
// without the dynamic symbols measured whole.
let entries: Vec<(usize, Option<&[&SymbolOverride]>)> = shown
.iter()
.filter_map(|i| src.symbols.get(*i).map(|s| (*i, s)))
.filter(|(_, s)| !s.dynamic || sets.get(s.name.as_str()).is_some_and(Option::is_some))
.map(|(i, s)| (i, s.dynamic.then_some(&[][..])))
.chain(copies.iter().map(|(i, c)| (*i, Some(*c))))
.collect();
// The symbols whose art `left_out` leaves nothing of, those that only hold instances of such
// symbols included.
let mut empty: HashSet<&str> = HashSet::new();
while let Some((_, s)) = shown.iter().find(|(_, s)| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty)) {
while let Some(s) = entries.iter().find_map(|(i, c)| {
src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty, *c, &mut Vec::new()))
}) {
empty.insert(&s.name);
}
let left_out =
&|n: &Node| left_out(n) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if empty.contains(symbol.as_str()) && !has_effects(n));
let layers = hidden_nodes(&doc.layers, left_out);
let symbols: Vec<(usize, Arc<Node>)> = shown
let layers = hidden_nodes(&src.layers, left_out);
let symbols: Vec<(usize, Arc<Node>)> = entries
.iter()
.filter(|(_, s)| !empty.contains(s.name.as_str()))
.filter_map(|(i, s)| without_nodes(&s.art, left_out).map(|art| (*i, art)))
.filter_map(|(i, c)| {
let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()))?;
without_nodes(&s.art, left_out, *c, &mut Vec::new()).map(|art| (*i, art))
})
.collect();
if layers.is_none() && symbols.is_empty() {
return vectorcraft_render::encode::art_bounds(doc);
return vectorcraft_render::encode::art_bounds(src);
}
let mut d = doc.clone();
let mut d = remapped_doc.unwrap_or_else(|| doc.clone());
if let Some(layers) = layers {
d.layers = layers;
}
@@ -486,22 +540,126 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
vectorcraft_render::encode::art_bounds(&d)
}
/// The appearance changes instance `n` makes to its symbol's art, without those that change nothing.
fn own_changes(n: &Node) -> Vec<&SymbolOverride> {
n.extras().symbol_overrides.iter().filter(|o| !o.is_empty()).collect()
}
/// `n` with each instance at any depth that `variant` gives another symbol (from the instance's
/// symbol and the instance) made an instance of that symbol; `None` when none is.
fn remapped(n: &Arc<Node>, variant: &dyn Fn(&str, &Node) -> Option<String>) -> Option<Arc<Node>> {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
let name = variant(symbol, n)?;
let mut m = (**n).clone();
if let NodeKind::SymbolInstance { symbol, .. } = &mut m.kind {
*symbol = name;
}
return Some(Arc::new(m));
}
let children = n.children()?;
let mut out: Option<Vec<Arc<Node>>> = None;
for (i, c) in children.iter().enumerate() {
if let Some(new) = remapped(c, variant)
&& let Some(slot) = out.get_or_insert_with(|| children.clone()).get_mut(i)
{
*slot = new;
}
}
out.map(|c| {
let mut m = (**n).clone();
if let Some(children) = m.children_mut() {
*children = c;
}
Arc::new(m)
})
}
/// Whether `n` is hidden, picked by `left_out`, an instance of one of the `empty` symbols, or a
/// layer or a group holding only such objects (its clipping path among them when it clips). A
/// Shaper group, or a layer, group or instance with effects, fills or strokes of its own, is none
/// of these unless it is hidden or picked.
fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>) -> bool {
/// of these unless it is hidden or picked. In the art of a dynamic symbol (`changed`, the changes
/// an instance makes to it; `n` is at place `at`), each object is judged with those changes
/// ([`as_drawn`]).
fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>, changed: Option<&[&SymbolOverride]>, at: &mut Vec<u32>) -> bool {
let m = as_drawn(n, changed, at);
!n.visible
|| left_out(n)
|| !has_effects(n)
|| left_out(&m)
|| !has_effects(&m)
&& n.extras().shaper.is_none()
&& match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().all(|c| all_left_out(c, left_out, empty)),
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().enumerate().all(|(i, c)| {
at.push(i as u32);
let out = all_left_out(c, left_out, empty, changed, at);
at.pop();
out
}),
NodeKind::SymbolInstance { symbol, .. } => empty.contains(symbol.as_str()),
_ => false,
}
}
/// Add the sets of appearance changes that the instances in `n` and its subtree make to the art of
/// the symbols `sets` names, each set once, and those of the instances in the art of the symbols the
/// instances show (`walked`, the symbols already looked in). The instances that `left_out` picks or
/// that are in an object it picks are left out, and with `hidden` (in a layer) the hidden ones and
/// those in a hidden object. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`.
fn drawn_changes<'a>(
doc: &'a Document,
n: &'a Node,
left_out: &dyn Fn(&Node) -> bool,
hidden: bool,
walked: &mut HashSet<&'a str>,
sets: &mut HashMap<&'a str, Option<Vec<Vec<&'a SymbolOverride>>>>,
) {
if hidden && !n.visible || left_out(n) {
return;
}
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
let changes = own_changes(n);
if let Some(entry) = sets.get_mut(symbol.as_str())
&& !changes.is_empty()
{
let full = match entry {
Some(list) if !list.contains(&changes) && list.len() < MAX_ART_COPIES => {
list.push(changes);
false
}
Some(list) => !list.contains(&changes),
None => false,
};
if full {
*entry = None;
}
}
if walked.insert(symbol.as_str())
&& let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol)
{
drawn_changes(doc, &s.art, left_out, false, walked, sets);
}
}
for c in n.children().into_iter().flatten() {
drawn_changes(doc, c, left_out, hidden, walked, sets);
}
}
/// The most copies of one dynamic symbol's art [`bounds_without`] measures, one for each set of
/// appearance changes its instances make; a symbol whose instances make more sets is measured whole.
const MAX_ART_COPIES: usize = 64;
/// `n`, the object at place `at` of a symbol's art, with the appearance changes `changed` that an
/// instance makes to it applied in their order; `n` itself for the art of a symbol that is not
/// dynamic (`changed` is `None`) and when no change names `at`.
fn as_drawn<'a>(n: &'a Node, changed: Option<&[&SymbolOverride]>, at: &[u32]) -> Cow<'a, Node> {
let here: Vec<SymbolOverride> =
changed.into_iter().flatten().filter(|o| o.path == at).map(|o| SymbolOverride { path: Vec::new(), ..(*o).clone() }).collect();
if here.is_empty() {
return Cow::Borrowed(n);
}
let mut m = n.clone();
vectorcraft_doc::symbol_overrides::apply(&mut m, &here);
Cow::Owned(m)
}
/// Whether `n` has a visible effect, fill or stroke of its own, which the objects it holds can
/// take part in.
fn has_effects(n: &Node) -> bool {
@@ -511,25 +669,32 @@ fn has_effects(n: &Node) -> bool {
/// `n` without the objects that `left_out` picks in it, when it is a layer or a group, and in the
/// layers and groups in it at any depth; `None` when it picks none of them. A clipping layer or
/// group keeps its clipping path, its first object, and a Shaper group and a layer or group with
/// effects, fills or strokes of its own keep all they hold.
fn without_nodes(n: &Arc<Node>, left_out: &dyn Fn(&Node) -> bool) -> Option<Arc<Node>> {
/// effects, fills or strokes of its own keep all they hold. In the art of a dynamic symbol
/// (`changed`, the changes an instance makes to it, as for [`all_left_out`]; `n` is at place
/// `at`), each object is judged with those changes ([`as_drawn`]), and an object taken out leaves
/// an empty group in its place.
fn without_nodes(n: &Arc<Node>, left_out: &dyn Fn(&Node) -> bool, changed: Option<&[&SymbolOverride]>, at: &mut Vec<u32>) -> Option<Arc<Node>> {
let (NodeKind::Layer { children, clip, .. } | NodeKind::Group { children, clip }) = &n.kind else { return None };
if has_effects(n) || n.extras().shaper.is_some() {
if has_effects(&as_drawn(n, changed, at)) || n.extras().shaper.is_some() {
return None;
}
let mut changed = false;
let mut taken = false;
let kept: Vec<Arc<Node>> = children
.iter()
.enumerate()
.filter_map(|(i, c)| {
if left_out(c) && !(*clip && i == 0) {
changed = true;
return None;
}
Some(without_nodes(c, left_out).inspect(|_| changed = true).unwrap_or_else(|| c.clone()))
at.push(i as u32);
let out = if left_out(&as_drawn(c, changed, at)) && !(*clip && i == 0) {
taken = true;
changed.map(|_| Arc::new(Node::group(c.id, Vec::new())))
} else {
Some(without_nodes(c, left_out, changed, at).inspect(|_| taken = true).unwrap_or_else(|| c.clone()))
};
at.pop();
out
})
.collect();
changed.then(|| {
taken.then(|| {
let mut new = (**n).clone();
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut new.kind {
*children = kept;
@@ -254,6 +254,90 @@ fn a_plot_of_the_arts_bounds_leaves_out_images_in_symbol_art() {
}
}
/// In the art of a dynamic symbol a placed image and a path that paints nothing are left out as
/// well, until an instance paints the path, and a document whose only other visible art is an
/// instance of a dynamic symbol of an image is refused.
#[test]
fn a_plot_of_the_arts_bounds_leaves_out_images_in_dynamic_symbol_art() {
let mut s = two_boards();
let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v));
let bounds = |s: &Session| super::export_art_bounds(&s.doc().unwrap().doc, "hpgl").unwrap();
let same = |a: vectorcraft_geom::Rect, b: vectorcraft_geom::Rect| {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-6)
};
let printing = s.doc().unwrap().doc.layers[0].id;
s.execute("layer.new", &json!({})).unwrap();
let mut png = vec![];
image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone();
let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].clone();
let bare = s.execute("shape.rectangle", &json!({"x": 500, "y": -400, "width": 20, "height": 20})).unwrap()["id"].clone();
s.execute("paint.setStroke", &json!({"ids": [bare], "none": true})).unwrap();
let before = bounds(&s);
let inst = s.execute("symbol.new", &json!({"name": "Mixed", "ids": [image, square, bare], "type": "dynamic"})).unwrap()["id"].clone();
let after = bounds(&s);
assert!(same(before, after), "{before:?} {after:?}");
// A change of the path's blending mode leaves it painting nothing; once the instance paints the
// path, the path is measured.
let art = s.doc().unwrap().doc.symbols[0].art.clone();
let x0 = |c: &std::sync::Arc<vectorcraft_doc::Node>| c.visual_bounds().map_or(f64::MIN, |b| b.x0);
let at = (0..art.children().unwrap().len()).max_by(|a, b| x0(&art.children().unwrap()[*a]).total_cmp(&x0(&art.children().unwrap()[*b]))).unwrap();
s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "blend": "multiply"})).unwrap();
let blended = bounds(&s);
assert!(same(before, blended), "{before:?} {blended:?}");
s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "stroke": "#000000"})).unwrap();
let painted = bounds(&s);
assert!(painted.x1 > 500.0 && painted.y0 < -390.0, "{painted:?}");
// A later change to the same object, as a file can hold, takes the paint off again.
{
let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap());
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let n = d.node_mut(id).unwrap();
let mut overrides = n.extras().symbol_overrides.clone();
overrides.push(vectorcraft_doc::SymbolOverride { path: vec![at as u32], opacity: Some(0.0), ..Default::default() });
n.extras_mut().symbol_overrides = overrides.clone();
let taken_off = bounds(&s);
assert!(same(before, taken_off), "{before:?} {taken_off:?}");
overrides.pop();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
d.node_mut(id).unwrap().extras_mut().symbol_overrides = overrides;
}
// Another instance, far above, that doesn't paint the path is measured without it, whether or
// not the first one paints it.
let other = s.execute("symbol.place", &json!({"name": "Mixed", "x": 0, "y": -5000})).unwrap()["id"].clone();
let with_paint = bounds(&s);
s.execute("symbol.instance.reset", &json!({"ids": [inst]})).unwrap();
let without_paint = bounds(&s);
assert!((with_paint.y0 - without_paint.y0).abs() < 1e-6, "{with_paint:?} {without_paint:?}");
s.execute("edit.undo", &json!({})).unwrap();
let undone = bounds(&s);
assert!(same(undone, with_paint), "{undone:?} {with_paint:?}");
s.execute("select.set", &json!({"ids": [other]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [inst]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone();
s.execute("symbol.new", &json!({"name": "Image", "ids": [image], "type": "dynamic"})).unwrap();
let e = plot(&mut s).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{e}");
// An instance that brings a group at 0% opacity back to full opacity still draws nothing when
// the group holds only an image.
let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone();
let group = s.execute("object.group", &json!({"ids": [image]})).unwrap()["id"].clone();
s.execute("transparency.set", &json!({"ids": [group], "opacity": 0})).unwrap();
let inst = s.execute("symbol.new", &json!({"name": "Clear", "ids": [group], "type": "dynamic"})).unwrap()["id"].clone();
let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap());
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
d.node_mut(id).unwrap().extras_mut().symbol_overrides =
[vec![], vec![0]].into_iter().map(|path| vectorcraft_doc::SymbolOverride { path, opacity: Some(1.0), ..Default::default() }).collect();
let e = plot(&mut s).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{e}");
}
/// A placed image with a Vector Halftone effect is measured when the effect makes dots, and left
/// out when it would take more cells than the effect makes.
#[test]
+27 -9
View File
@@ -1,4 +1,4 @@
use vectorcraft_doc::graph::art_bounds;
use vectorcraft_doc::graph::graph_art_without_type as art_bounds;
use super::axis::{MAX_TICK_MARKS, count_given, one_line};
use super::data::apply_data;
@@ -21,12 +21,16 @@ fn bound_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<f64>>> {
/// The bounds a redraw of graph `n` measures a move or scale on, as kept at the last generation and as they are now:
/// those of its art without type ([`GraphSpec::placed_art`]), or those of all its art when the graph keeps no such
/// bounds with a width and a height, or has no art without type now.
/// bounds with a width and a height. `None` when the art measured has no width or no height now, or the graph keeps
/// bounds of its art without type and has no such art now.
fn measured(n: &Node) -> Option<(Rect, Rect)> {
let kept = n.extras().graph.as_deref()?;
let c = n.children()?;
let art = kept.placed_art.filter(|p| p.width() > 1e-9 && p.height() > 1e-9).zip(art_bounds(c));
art.or_else(|| kept.placed.zip(children_bounds(c)))
let solid = |r: &Rect| r.width() > 1e-9 && r.height() > 1e-9;
match kept.placed_art.filter(solid) {
Some(placed) => art_bounds(c).filter(solid).map(|now| (placed, now)),
None => kept.placed.zip(children_bounds(c).filter(solid)),
}
}
/// `r` carried by the change from bounds `from` to bounds `to`: each edge stays at the same place relative to them.
@@ -39,14 +43,28 @@ fn carried(r: Rect, from: Rect, to: Rect) -> Option<Rect> {
Some(Rect::new(to.x0 + (r.x0 - from.x0) * sx, to.y0 + (r.y0 - from.y0) * sy, to.x0 + (r.x1 - from.x0) * sx, to.y0 + (r.y1 - from.y0) * sy))
}
/// The graphs holding objects `ids`, each with the bounds of its art without type and of all its art. Give them to
/// [`keep_placed`] after an edit that changes a graph's art without moving the graph.
/// The graphs holding objects `ids`, that are among them or that are inside them, each with the bounds of its art
/// without type and of all its art. Give them to [`keep_placed`] after an edit that changes a graph's art without
/// moving the graph.
pub(crate) fn graphs_holding(d: &Document, ids: &[NodeId]) -> Vec<(NodeId, Option<Rect>, Option<Rect>)> {
let mut out: Vec<(NodeId, Option<Rect>, Option<Rect>)> = vec![];
let is_graph = |n: &Node| n.extras().graph.is_some();
let mut found: Vec<NodeId> = vec![];
for id in ids {
let Some(chain) = d.ancestry(*id) else { continue };
let holder = chain.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(|n| n.extras().graph.is_some()));
let Some(gid) = holder.filter(|g| !out.iter().any(|(o, ..)| o == g)) else { continue };
found.extend(chain.iter().rev().copied().find(|a| d.node(*a).is_some_and(is_graph)));
if let Some(n) = d.node(*id) {
n.walk(&mut |c| {
if is_graph(c) {
found.push(c.id);
}
});
}
}
let mut out: Vec<(NodeId, Option<Rect>, Option<Rect>)> = vec![];
for gid in found {
if out.iter().any(|(o, ..)| *o == gid) {
continue;
}
let children = d.node(gid).and_then(Node::children);
out.push((gid, children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c))));
}
+145 -2
View File
@@ -5977,6 +5977,141 @@ fn outlining_a_graphs_labels_leaves_the_plot_in_place() {
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 15.0)).abs() < 1e-6, "{moved:?}");
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}");
// A scale of the graph made before outlining is still followed.
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.scale", &json!({"sx": 150, "sy": 50, "origin": [moved.x0, moved.y0]})).unwrap();
s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q3").0]})).unwrap();
s.execute("type.createOutlines", &json!({})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let scaled = spec(&s, id).rect;
assert!((scaled.x0 - moved.x0).abs() < 1e-6 && (scaled.y0 - moved.y0).abs() < 1e-6, "{scaled:?}");
assert!((scaled.width() - 1.5 * rect.width()).abs() < 1e-6 && (scaled.height() - 0.5 * rect.height()).abs() < 1e-6, "{scaled:?}");
}
/// Outline Stroke on a graph's strokes leaves the plot where it is when the graph is drawn again, and a move of the
/// graph made before it is still followed.
#[test]
fn outlining_a_graphs_strokes_leaves_the_plot_in_place() {
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 20, "dy": 10})).unwrap();
s.execute("object.path.outlineStroke", &json!({})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 20.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 10.0)).abs() < 1e-6, "{moved:?}");
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}");
}
/// A graph left with only its labels, or with its labels and one vertical line, leaves the plot where it is when it is
/// drawn again after a label edit.
#[test]
fn a_graph_left_with_only_its_labels_leaves_the_plot_in_place() {
for keep_a_line in [false, true] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
let (mut art, mut line) = (vec![], None);
s.doc().unwrap().doc.node(id).unwrap().walk(&mut |n| {
if n.children().is_none() && !matches!(n.kind, NodeKind::Text(_)) {
let vertical = n.geometric_bounds().is_some_and(|b| b.width() < 1e-9 && b.height() > 1.0);
if keep_a_line && vertical && line.is_none() {
line = n.geometric_bounds();
} else {
art.push(n.id.0);
}
}
});
assert!(!art.is_empty() && line.is_some() == keep_a_line);
s.execute("select.set", &json!({"ids": art})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let left = s.doc().unwrap().doc.node(id).unwrap().clone();
assert_eq!(vectorcraft_doc::graph::graph_art_without_type(left.children().unwrap()), line, "{:#?}", left.children());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("text.setStyle", &json!({"size": 20})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
assert_eq!(spec(&s, id).rect, rect, "keeping a line: {keep_a_line}");
}
}
/// A graph saved without the bounds of its art without type, left with one vertical line, keeps its plot's size when
/// it is drawn again.
#[test]
fn a_graph_saved_with_only_its_whole_bounds_and_left_with_a_line_keeps_its_plot() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
let mut old = spec(&s, id);
old.placed_art = None;
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(old));
let (mut art, mut line) = (vec![], None);
s.doc().unwrap().doc.node(id).unwrap().walk(&mut |n| {
if n.children().is_none() {
let vertical = !matches!(n.kind, NodeKind::Text(_)) && n.geometric_bounds().is_some_and(|b| b.width() < 1e-9 && b.height() > 1.0);
if vertical && line.is_none() {
line = Some(n.id);
} else {
art.push(n.id.0);
}
}
});
assert!(line.is_some());
s.execute("select.set", &json!({"ids": art})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
assert_eq!(spec(&s, id).rect, rect);
}
/// The bounds a graph measures moves on take a clipping group holding type at the bounds of its clip, so art outside the
/// clip does not change them; a clipping group whose clip is type is measured on its other art.
#[test]
fn a_clipping_group_holding_type_is_measured_on_its_clip() {
use std::sync::Arc;
use vectorcraft_doc::graph::graph_art_without_type as measure;
use vectorcraft_geom::Affine;
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let label: Arc<vectorcraft_doc::Node> =
group(&n, "Legend").children().unwrap().iter().find(|c| matches!(c.kind, NodeKind::Text(_))).unwrap().clone();
let mut paths = vec![];
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::Path { .. }) {
paths.push(c.clone());
}
});
let (clip, art) = (Arc::new(paths[0].clone()), paths[1].clone());
let clipped = |dx: f64, first: Arc<vectorcraft_doc::Node>, second: Arc<vectorcraft_doc::Node>| {
let mut far = art.clone();
far.transform(Affine::translate((dx, 0.0)), false);
let mut g = vectorcraft_doc::Node::group(NodeId(999_999), vec![first, second, Arc::new(far)]);
if let NodeKind::Group { clip, .. } = &mut g.kind {
*clip = true;
}
measure(&[Arc::new(g)])
};
assert_eq!(clipped(500.0, clip.clone(), label.clone()), clip.geometric_bounds());
assert_eq!(clipped(500.0, clip.clone(), label.clone()), clipped(900.0, clip.clone(), label.clone()));
// A clip that is type leaves the other art to measure.
assert_ne!(clipped(500.0, label.clone(), clip.clone()), clipped(900.0, label.clone(), clip.clone()));
// A clip that is a clipping group holding type in its clipped art is measured on its own clip.
let mut inner = vectorcraft_doc::Node::group(NodeId(999_998), vec![clip.clone(), label.clone()]);
if let NodeKind::Group { clip, .. } = &mut inner.kind {
*clip = true;
}
let inner = Arc::new(inner);
assert_eq!(clipped(500.0, inner.clone(), label.clone()), clip.geometric_bounds());
assert_eq!(clipped(500.0, inner.clone(), label.clone()), clipped(900.0, inner.clone(), label.clone()));
// A blend holding type is measured whole, as it is drawn.
let blend = vectorcraft_doc::Node::new(NodeId(999_997), NodeKind::Blend { children: vec![clip.clone(), label.clone()], spec: Box::default() });
assert_eq!(measure(&[Arc::new(blend.clone())]), blend.geometric_bounds());
}
/// A graph whose kept bounds of its art without type have no width follows a move with the bounds of all of its art.
@@ -7294,9 +7429,17 @@ fn a_graph_opened_from_ai_measures_moves_without_its_labels() {
assert_eq!((graphs.len(), labels.len()), (1, 1));
let (id, label) = (graphs[0], labels[0]);
let before = spec(&s, id);
assert!(before.placed_art.is_some());
s.execute("select.set", &json!({"ids": [label.0]})).unwrap();
s.execute("text.setStyle", &json!({"size": 30})).unwrap();
s.execute("object.move", &json!({"dx": 80, "dy": -40})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap();
assert_eq!(spec(&s, id).rect, before.rect);
let rect = spec(&s, id).rect;
assert_eq!(rect, before.rect, "after restyling and moving a label");
// A move of the whole opened graph is still followed.
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 15, "dy": 25})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap();
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 15.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 25.0)).abs() < 1e-6, "{moved:?}");
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}");
}
+6 -1
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
),
@@ -617,6 +617,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"standardVerticalRoman",
"noBreak",
"digits",
"glyphForm",
"fontHeightReference",
"language",
"fontAxes",
@@ -651,6 +652,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
let char_align = super::textedit::char_align_param(p, C)?;
let char_direction = super::textedit::char_direction_param(p, C)?;
let digits = super::textedit::digits_param(p, C)?;
let glyph_form = super::textedit::glyph_form_param(p, C)?;
let language = super::textedit::language_param(p, C)?;
let font_axes = super::textedit::font_axes_param(p, C)?;
let font_height_reference = super::textedit::font_height_reference_param(p, C)?;
@@ -821,6 +823,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = digits {
st.digits = v;
}
if let Some(v) = glyph_form {
st.glyph_form = v;
}
if let Some(v) = &language {
st.language.clone_from(v);
}
+3
View File
@@ -1188,6 +1188,8 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result<Value> {
let roots = selected_roots(s)?;
let ids = s.edit("Outline Stroke", |d, sel| {
let before = d.clone();
// Outlining the strokes in a graph does not move or scale its plot at the next redraw.
let graphs = super::graph::graphs_holding(d, &roots);
// A dimension selected with the art it measures keeps its own lines: it is out of the
// document while the art is outlined.
let lifted = super::dimension::lift(d, &roots);
@@ -1207,6 +1209,7 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result<Value> {
if changed == 0 || (kept && d.layers == before.layers) {
return Err(EngineError::Other("Outline Stroke: no stroked paths selected".into()));
}
super::graph::keep_placed(d, &graphs);
sel.set(new_sel.iter().copied());
Ok(new_sel)
})?;
+111 -26
View File
@@ -3,9 +3,14 @@
//! applied effect names the document's filter: editing the filter changes what every object that
//! uses it draws, and deleting it leaves their effects in place, drawing nothing, until a filter of
//! that name exists again. Each effect holds the definition it draws with, kept in step here.
//!
//! The default filters ([`svg_filter::defaults`]) are listed for every document. Applying or
//! editing one adds a copy to the document under the default's name, and from then on that copy is
//! the filter of that name. Deleting the copy lists the default again.
use serde_json::{Value, json};
use vectorcraft_doc::{Appearance, Document, SvgFilter};
use vectorcraft_render::effects::svg_filter::defaults::{DEFAULT_FILTERS, default_filter};
use vectorcraft_render::effects::{self, svg_filter};
use super::fileio::{absolute_path, read_file_head};
@@ -21,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
"SVG Filters",
[],
None,
"{} → {filters: [{name, xml}…]} the SVG filters the document holds, in the SVG Filters submenu's order",
"{} → {filters: [{name, xml}…], defaults: [{name, xml, inDocument}…]} filters: the SVG filters the document holds, in the order they were added; defaults: the default filters every document lists (VectorCraft's own set), with inDocument true when the document holds a filter of that name, which then stands in the default's place. The SVG Filters submenu and Apply SVG Filter list the defaults first, then the document's other filters",
has_doc,
list
),
@@ -30,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New SVG Filter",
[],
None,
"{xml: one SVG <filter> element (its id is its name; 1..64 primitives; at most 64 KB), replace?: the name of the filter it replaces and keeps (Edit SVG Filter)} add an SVG filter to the document, after the others, or replace one, as one undo step; every object whose svg.filter effect names it draws with the new definition; a name another filter has is refused and a document holds at most 64 filters → {name, filters}",
"{xml: one SVG <filter> element (its id is its name; 1..64 primitives; at most 64 KB), replace?: the name of the filter it replaces and keeps (Edit SVG Filter)} add an SVG filter to the document, after the others, or replace one, as one undo step; every object whose svg.filter effect names it draws with the new definition; a name another filter of the document has is refused and a document holds at most 64 filters; replace with the name of a default filter the document does not hold adds the edited copy to the document under that name, and code equal to the default's adds nothing; a new filter may take a default's name, and then stands in its place → {name, filters}",
has_doc,
define
),
@@ -39,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Delete SVG Filter",
[],
None,
"{name} remove an SVG filter from the document, as one undo step; objects whose svg.filter effect names it keep the effect, which draws nothing until a filter of that name is defined or imported again → {filters}",
"{name} remove an SVG filter from the document, as one undo step; objects whose svg.filter effect names it keep the effect, which draws nothing until a filter of that name is defined or imported again, or the default of that name is applied; a default filter the document holds no copy of is refused (the defaults are not deleted), and deleting the document's copy of one lists the default again → {filters}",
has_doc,
delete
),
@@ -57,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply SVG Filter",
[],
None,
"{name, ids?|id?, item?} apply the document's SVG filter `name` (svgFilter.list) to ids or the selection as a live svg.filter effect, as one undo step, like effect.apply → {ids, index, item}",
"{name, ids?|id?, item?, index?} apply the document's SVG filter `name`, or the default filter of that name when the document holds none (svgFilter.list), to ids or the selection as a live svg.filter effect, as one undo step, like effect.apply → {ids, index, item}; with index, the filter takes the place of the applied svg.filter effect at index of item, like effect.setParams → {ids}; a default is copied into the document in the same undo step, which is refused when the document already holds 64 filters",
has_doc,
apply
),
@@ -69,7 +74,10 @@ fn filters_json(d: &Document) -> Value {
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "filters": filters_json(&s.doc()?.doc) }))
let d = &s.doc()?.doc;
let held = |name: &str| d.svg_filters.iter().any(|f| f.name == name);
let defaults: Vec<Value> = DEFAULT_FILTERS.iter().map(|f| json!({ "name": f.name, "xml": f.xml, "inDocument": held(f.name) })).collect();
Ok(json!({ "filters": filters_json(d), "defaults": defaults }))
}
/// `p`'s `name`, trimmed and not empty.
@@ -132,10 +140,12 @@ fn define(s: &mut Session, p: &Value) -> Result<Value> {
};
svg_filter::check(&xml).map_err(|e| bad(C, e))?;
let filters = &s.doc()?.doc.svg_filters;
let at = match &replace {
Some(r) => Some(filters.iter().position(|f| f.name == *r).ok_or_else(|| bad(C, format!("the document has no SVG filter named {r:?}")))?),
None => None,
};
let at = replace.as_ref().and_then(|r| filters.iter().position(|f| f.name == *r));
// A default the document does not hold: its edited copy is added under the default's name.
let default = replace.as_ref().filter(|_| at.is_none()).and_then(|r| default_filter(r));
if let Some(r) = replace.as_ref().filter(|_| at.is_none() && default.is_none()) {
return Err(bad(C, format!("the document has no SVG filter named {r:?}")));
}
// An edited filter keeps its name, whatever id its new code gives it.
let xml = match &replace {
Some(r) => svg_filter::with_id(&xml, r).ok_or_else(|| bad(C, "give one <filter> element"))?,
@@ -145,22 +155,28 @@ fn define(s: &mut Session, p: &Value) -> Result<Value> {
if filters.iter().enumerate().any(|(i, f)| f.name == name && Some(i) != at) {
return Err(bad(C, format!("the document already has an SVG filter named {name:?}")));
}
let new = SvgFilter { name: name.clone(), xml };
// Nothing to record when the filter, and every object that uses it, is already as given: a
// default saved with its own code stays out of the document.
let as_given = match default {
Some(d) => d.to_filter() == new,
None => at.and_then(|i| filters.get(i)) == Some(&new),
};
if as_given && !out_of_step(&s.doc()?.doc, &new.name, &new.xml) {
return Ok(json!({ "name": name, "filters": filters_json(&s.doc()?.doc) }));
}
if at.is_none() && filters.len() >= SvgFilter::MAX {
return Err(bad(C, format!("a document holds at most {} SVG filters", SvgFilter::MAX)));
}
let new = SvgFilter { name: name.clone(), xml };
// Nothing to record when the filter, and every object that uses it, is already as given.
if at.and_then(|i| filters.get(i)) != Some(&new) || out_of_step(&s.doc()?.doc, &new.name, &new.xml) {
let label = if at.is_some() { "Edit SVG Filter" } else { "New SVG Filter" };
s.edit(label, |d, _| {
update_users(d, &new.name, &new.xml);
match at.and_then(|i| d.svg_filters.get_mut(i)) {
Some(f) => *f = new,
None => d.svg_filters.push(new),
}
Ok(())
})?;
}
let label = if replace.is_some() { "Edit SVG Filter" } else { "New SVG Filter" };
s.edit(label, |d, _| {
update_users(d, &new.name, &new.xml);
match at.and_then(|i| d.svg_filters.get_mut(i)) {
Some(f) => *f = new,
None => d.svg_filters.push(new),
}
Ok(())
})?;
Ok(json!({ "name": name, "filters": filters_json(&s.doc()?.doc) }))
}
@@ -168,6 +184,9 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "svgFilter.delete";
let name = name_param(p, C)?;
if !s.doc()?.doc.svg_filters.iter().any(|f| f.name == name) {
if default_filter(&name).is_some() {
return Err(bad(C, format!("{name:?} is a default SVG filter, and the document holds no copy of it to delete")));
}
return Err(bad(C, format!("the document has no SVG filter named {name:?}")));
}
s.edit("Delete SVG Filter", |d, _| {
@@ -222,13 +241,79 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
fn apply(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "svgFilter.apply";
let name = name_param(p, C)?;
let f = s.doc()?.doc.svg_filters.iter().find(|f| f.name == name).cloned();
let f = f.ok_or_else(|| bad(C, format!("the document has no SVG filter named {name:?}")))?;
let mut q = json!({ "effect": effects::SVG_FILTER, "params": { "name": f.name, "xml": f.xml } });
let filters = &s.doc()?.doc.svg_filters;
// The document's filter of that name, or the default of that name, which the document then takes.
let (f, copied) = match (filters.iter().find(|f| f.name == name), default_filter(&name)) {
(Some(f), _) => (f.clone(), false),
(None, Some(_)) if filters.len() >= SvgFilter::MAX => {
return Err(bad(C, format!("a document holds at most {} SVG filters, and applying a default filter adds it", SvgFilter::MAX)));
}
(None, Some(d)) => (d.to_filter(), true),
(None, None) => return Err(bad(C, format!("the document has no SVG filter named {name:?}"))),
};
// A given `index`, null included, is checked as an index: only a missing one adds an effect.
let replaces = p.get("index").is_some();
let mut q = match replaces {
true => json!({ "index": p["index"], "params": { "name": f.name, "xml": f.xml } }),
false => json!({ "effect": effects::SVG_FILTER, "params": { "name": f.name, "xml": f.xml } }),
};
for key in ["ids", "id", "item"] {
if let Some(v) = p.get(key) {
q[key] = v.clone();
}
}
super::effectcmd::apply(s, &q)
if !copied {
return apply_as_given(s, p, &q, replaces, None);
}
// The effect and the copy are two edits joined into one step. The history keeps room for both
// until they are joined, so the application lets one old step go at most, as any edit does.
let limit = s.doc()?.history.limit;
if let Some(st) = s.active_mut() {
st.history.limit = limit.saturating_add(2);
}
let out = apply_as_given(s, p, &q, replaces, Some(f));
if let Some(st) = s.active_mut() {
st.history.limit = limit;
st.history.trim();
}
out
}
/// [`apply`] once the filter is known: the effect added (`q`) or put in the applied filter's place
/// (`replaces`), and `copy`, a default's copy, added to the document in the same undo step.
fn apply_as_given(s: &mut Session, p: &Value, q: &Value, replaces: bool, copy: Option<SvgFilter>) -> Result<Value> {
const C: &str = "svgFilter.apply";
let newest = s.doc()?.history.step().0;
let out = if replaces {
super::appearance::index_param(p, "index", C)?;
// Only an applied SVG filter gives its place: another effect would take the filter's
// parameters as its own.
let edited = super::effectcmd::set_params_effects(s, q);
if edited.is_empty() || edited.iter().any(|e| e != effects::SVG_FILTER) {
return Err(bad(C, "`index` must be the index of an applied SVG filter"));
}
super::effectcmd::set_params(s, q)?
} else {
super::effectcmd::apply(s, q)?
};
if let Some(f) = copy {
// The copy joins the step that applied it, under that step's name. That step is found by
// its document, not its place: in an undo group both edits join the group's one step.
let h = &s.doc()?.history;
let applied = h.undo.last().filter(|_| h.step().0 != newest).map(|step| (step.label.clone(), step.doc.clone()));
let label = applied.as_ref().map_or_else(|| "SVG Filter".to_string(), |(l, _)| l.clone());
s.edit(&label, |d, _| {
update_users(d, &f.name, &f.xml);
d.svg_filters.push(f);
Ok(())
})?;
let undo = &s.doc()?.history.undo;
let below = undo.len().checked_sub(2);
if let (Some(at), Some((_, doc))) = (below, &applied)
&& undo.get(at).is_some_and(|e| std::sync::Arc::ptr_eq(&e.doc, doc))
{
super::menucmds::squash(s, at, &label);
}
}
Ok(out)
}
+21 -1
View File
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; vertical type keeps the characters' spacing; 0 by default; a value that is not a number or is outside t Line truncated
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; vertical type keeps the characters' spacing; 0 by default; a value that is not a number or is outside t Line truncated
has_doc,
set_range_style
),
@@ -473,6 +473,7 @@ pub(crate) struct CharChange {
standard_vertical_roman: Option<bool>,
no_break: Option<bool>,
digits: Option<vectorcraft_doc::Digits>,
glyph_form: Option<vectorcraft_doc::GlyphForm>,
/// The language to set: a tag, or `None` for the default.
language: Option<Option<String>>,
font_axes: Option<AxisChange>,
@@ -571,6 +572,20 @@ pub(crate) fn digits_param(p: &Value, cmd: &str) -> Result<Option<vectorcraft_do
Ok(Some(d))
}
/// `glyphForm: "traditional"|"expert"|"jis04"|…|"default"` ([`GlyphForm::id`]) → the East Asian
/// glyph form the characters are drawn in.
///
/// [`GlyphForm::id`]: vectorcraft_doc::GlyphForm::id
pub(crate) fn glyph_form_param(p: &Value, cmd: &str) -> Result<Option<vectorcraft_doc::GlyphForm>> {
use vectorcraft_doc::GlyphForm;
let Some(v) = p.get("glyphForm").filter(|v| !v.is_null()) else { return Ok(None) };
let Some(f) = v.as_str().and_then(GlyphForm::from_id) else {
let ids: Vec<String> = GlyphForm::ALL.iter().map(|f| format!("\"{}\"", f.id())).collect();
return Err(bad(cmd, format!("`glyphForm` must be one of {}", ids.join(", "))));
};
Ok(Some(f))
}
/// `language: name|tag` (one of Document Setup's languages, case-insensitive) → the language to
/// set ([`vectorcraft_doc::CharStyle::language`]: `None` inside for the default).
pub(crate) fn language_param(p: &Value, cmd: &str) -> Result<Option<Option<String>>> {
@@ -840,6 +855,7 @@ impl CharChange {
standard_vertical_roman: flag("standardVerticalRoman"),
no_break: flag("noBreak"),
digits: digits_param(p, cmd)?,
glyph_form: glyph_form_param(p, cmd)?,
language: language_param(p, cmd)?,
font_axes: font_axes_param(p, cmd)?,
font_height_reference: font_height_reference_param(p, cmd)?,
@@ -905,6 +921,7 @@ impl CharChange {
&& self.standard_vertical_roman.is_none()
&& self.no_break.is_none()
&& self.digits.is_none()
&& self.glyph_form.is_none()
&& self.language.is_none()
&& self.font_axes.is_none()
&& self.font_height_reference.is_none()
@@ -1070,6 +1087,9 @@ impl CharChange {
if let Some(v) = self.digits {
st.digits = v;
}
if let Some(v) = self.glyph_form {
st.glyph_form = v;
}
if let Some(v) = self.font_height_reference {
st.font_height_reference = v;
}
+1
View File
@@ -228,6 +228,7 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
("digits", json!(v.digits)),
("fontHeightReference", json!(v.font_height_reference)),
("language", json!(v.language)),
("glyphForm", json!(v.glyph_form)),
] {
m.insert(k.into(), x);
}
@@ -1925,6 +1925,55 @@ fn standard_vertical_roman_is_a_character_attribute_saved_only_when_on() {
assert!(runs(&s).iter().all(|r| !r.style.standard_vertical_roman));
}
/// The East Asian glyph form (Glyphs panel menu) is one character attribute, `glyphForm`: one
/// form replaces another, "default" (Revert To Default Forms) takes it away, and it is saved
/// only when set. A call that changes nothing records no undo step, an unknown form is refused,
/// and character styles carry it.
#[test]
fn glyph_form_is_one_character_attribute_saved_only_when_set() {
use vectorcraft_doc::GlyphForm;
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "亜唖芦"})).unwrap()["id"].as_u64().unwrap();
let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.runs.clone(),
_ => panic!("text"),
};
let forms = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::<Vec<_>>();
assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("glyphForm").is_none());
s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 6, "glyphForm": "jis78"})).unwrap();
assert_eq!(forms(&s), [("亜".into(), GlyphForm::Default), ("唖".into(), GlyphForm::Jis78), ("芦".into(), GlyphForm::Default)]);
assert_eq!(serde_json::to_value(&runs(&s)[1].style).unwrap()["glyphForm"], "jis78");
// Saved and reopened as it was.
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
assert_eq!(t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::<Vec<_>>(), forms(&s));
// Another form replaces it: one form at a time.
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("text.setFormat", &json!({"glyphForm": "fullWidth"})).unwrap();
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::FullWidth));
let n = s.doc().unwrap().history.undo.len();
s.execute("text.setFormat", &json!({"glyphForm": "fullWidth"})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), n, "nothing changed, no undo step");
for bad in [json!("jis2004"), json!(78), json!(true), json!("Traditional")] {
let e = s.execute("text.setFormat", &json!({"glyphForm": bad})).unwrap_err().to_string();
assert!(e.contains("`glyphForm` must be one of \"traditional\""), "{bad}: {e}");
assert!(s.execute("text.setRangeStyle", &json!({"id": id, "glyphForm": bad})).is_err(), "{bad}");
}
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::FullWidth), "a refused call changes nothing");
assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style)["glyphForm"], "fullWidth");
s.execute("text.setFormat", &json!({"glyphForm": "default"})).unwrap();
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default));
assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("glyphForm").is_none());
// A character style carries the form.
s.execute("charStyle.new", &json!({"name": "Old forms", "attrs": {"glyphForm": "jis83"}})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Old forms", "id": id})).unwrap();
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Jis83));
assert!(s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"glyphForm": "jis2004"}})).is_err());
s.execute("edit.undo", &json!({})).unwrap();
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default));
}
/// No Break is a character attribute, saved only when on.
#[test]
fn no_break_is_a_character_attribute_saved_only_when_on() {
+2
View File
@@ -24,6 +24,8 @@ impl Session {
});
// Clicks find an image's own fills and strokes where their effects draw them.
vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint);
// Clicks inside a clip group fall in the region its clipping path's effects give it.
vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline);
// Clicks find a blend's steps and an envelope's distorted art where the canvas draws them,
// evaluated again when the fonts, the hyphenation exceptions or the plug-ins change.
vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || {
+68
View File
@@ -119,12 +119,80 @@ fn text_on_top_clips_by_its_glyphs() {
assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art));
assert!(b.x1 < 95.0, "{b:?}");
assert_eq!(hit(&s, b.x1 + 3.0, (b.y0 + b.y1) / 2.0), None, "beside the text");
// An effect that does not reshape it, such as a drop shadow, leaves clicks on its frame.
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {}, "ids": [t.0], "item": null})).unwrap();
assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art), "in the counter, with a drop shadow");
// Release gives the text back.
select(&mut s, &[g]);
s.execute("object.clippingMask.release", &json!({})).unwrap();
assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_)));
}
#[test]
fn a_hidden_member_of_a_clipping_group_leaves_clicks_on_the_type_frame() {
// The clipping path is a group of an "O" and a hidden rectangle with a Transform effect. The
// hidden rectangle does not clip, so clicks inside the clip group still count the type by its
// frame, the counter of the "O" included.
let mut s = session();
let art = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap());
let t = id_of(&s.execute("text.create", &json!({"x": 5, "y": 80, "text": "O", "size": 90})).unwrap());
let b = s.doc().unwrap().doc.node(t).unwrap().geometric_bounds().unwrap();
let r = id_of(&s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap());
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 20}, "ids": [r.0], "item": null})).unwrap();
select(&mut s, &[art, t]);
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
// Make Clipping Mask takes no group on top, so the group goes in place of the type.
let mut d = (*s.doc().unwrap().doc).clone();
let mut rect = (*d.remove(r).unwrap()).clone();
rect.visible = false;
let text = d.remove(t).unwrap();
let group = vectorcraft_doc::Node::group(d.alloc_id(), vec![text, Arc::new(rect)]);
d.insert(Some(g), 0, group).unwrap();
let leaf = |x: f64, y: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, y), Default::default()).map(|h| h.leaf);
let middle = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
assert_eq!(leaf(middle.0, middle.1), Some(art), "in the counter, inside the frame");
assert_eq!(leaf(b.x1 + 3.0, middle.1), None, "beside the text");
}
#[test]
fn clicks_follow_the_region_a_clipping_paths_effects_give_it() {
// Art from 10 to 90 pt, clipped by the artboard's left half, which a Transform effect moves
// 50 pt right: the art shows on the right half, as clicks find it.
let mut s = session();
let art = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap());
let clip = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 100})).unwrap());
select(&mut s, &[art, clip]);
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 50}, "ids": [clip.0], "item": null})).unwrap();
let r = render(&s);
assert!(opaque(&r, 75, 50) && !opaque(&r, 25, 50), "the canvas clips by the moved region");
assert_eq!(hit(&s, 75.0, 50.0), Some(art), "where the effect moved the clipping path");
assert_eq!(hit(&s, 25.0, 50.0), None, "the clipping path's own place");
let d = &s.doc().unwrap().doc;
let at = |x: f64| vectorcraft_doc::hit::objects_at(d, vectorcraft_geom::Point::new(x, 50.0), Default::default(), None);
assert_eq!(at(75.0), [g]);
assert!(at(25.0).is_empty());
// A marquee across the art's edge reaches it within the moved region only.
let marquee = |x0: f64, x1: f64| vectorcraft_doc::hit::marquee(d, vectorcraft_geom::Rect::new(x0, 40.0, x1, 60.0), None, true);
assert_eq!(marquee(85.0, 95.0), [art], "the right edge, in the moved region");
assert!(marquee(5.0, 15.0).is_empty(), "the left edge, in the clipping path's own place");
// The same with a sublayer that clips by its first object.
let mut d = (**d).clone();
let members: Vec<_> = d.node(g).unwrap().children().unwrap().to_vec();
let top = d.layers[0].id;
d.remove(g).unwrap();
let mut sublayer = (*d.layers[0]).clone();
sublayer.id = d.alloc_id();
if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind {
(*children, *clip) = (members, true);
}
d.insert(Some(top), 0, sublayer).unwrap();
let leaf = |x: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, 50.0), Default::default()).map(|h| h.leaf);
assert_eq!(leaf(75.0), Some(art));
assert_eq!(leaf(25.0), None);
}
#[test]
fn make_refuses_a_top_object_that_cannot_clip() {
let mut s = session();
+176
View File
@@ -715,3 +715,179 @@ fn svg_export_draws_a_filter_svg_1_1_lacks_as_an_image() {
assert_eq!((out.contains("<image"), out.contains("<feBlend")), (image, !image), "{mode}: {out}");
}
}
/// The `defaults` of `svgFilter.list`: each one's name and whether the document holds it.
fn defaults(s: &mut Session) -> Vec<(String, bool)> {
let listed = run(s, "svgFilter.list", json!({}))["defaults"].as_array().cloned().unwrap_or_default();
listed.iter().map(|f| (f["name"].as_str().unwrap().to_string(), f["inDocument"].as_bool().unwrap())).collect()
}
/// Every document lists the default filters without holding them; applying one adds the effect and
/// the document's copy in one undo step.
#[test]
fn a_default_filter_is_listed_and_copied_into_the_document_when_applied() {
use vectorcraft_render::effects::svg_filter::defaults::DEFAULT_FILTERS;
let mut s = session();
let listed = defaults(&mut s);
assert_eq!(listed.len(), DEFAULT_FILTERS.len());
assert!(listed.iter().all(|(_, held)| !held), "a new document holds none of them");
assert!(names(&mut s).is_empty());
let soft = DEFAULT_FILTERS.iter().find(|f| f.name == "Soft Shadow").unwrap();
assert_eq!(run(&mut s, "svgFilter.list", json!({}))["defaults"][2], json!({"name": "Soft Shadow", "xml": soft.xml, "inDocument": false}));
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 50.0));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let before = steps(&s);
let r = run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow"}));
assert_eq!((r["ids"].as_array().unwrap().len(), &r["index"]), (2, &json!(0)));
assert_eq!(steps(&s), before + 1, "the effect and the copy are one step");
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter");
assert_eq!(names(&mut s), ["Soft Shadow"]);
assert_eq!(drawn(&s, a), json!(soft.xml));
assert!(defaults(&mut s).contains(&("Soft Shadow".to_string(), true)));
// Applied again, the document's copy is the filter: nothing more is added.
run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow", "ids": [a.0]}));
assert_eq!(names(&mut s), ["Soft Shadow"]);
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
assert!(names(&mut s).is_empty(), "undo takes the copy back with the effect");
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
run(&mut s, "edit.redo", json!({}));
assert_eq!((names(&mut s), drawn(&s, b)), (vec!["Soft Shadow".to_string()], json!(soft.xml)));
// Nothing to apply it to: no copy and no step.
let mut s = session();
assert!(s.execute("svgFilter.apply", &json!({"name": "Glow"})).is_err(), "nothing selected");
assert!(names(&mut s).is_empty());
assert_eq!(steps(&s), 0);
assert!(err(&mut s, "svgFilter.apply", json!({"name": "glow", "ids": []})).contains("no SVG filter named \"glow\""), "names match exactly");
}
/// With a full history, applying a default lets one old step go, as any edit does: the copy joins
/// the step that applied it, and one Undo takes both back.
#[test]
fn a_default_applied_with_a_full_history_is_still_one_step() {
let mut s = session();
s.active_mut().unwrap().history.limit = 3;
let a = rect(&mut s, 10.0);
rect(&mut s, 30.0);
rect(&mut s, 50.0);
assert_eq!(steps(&s), 3);
run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0]}));
// The application takes one place in the history: only the oldest step went.
assert_eq!(steps(&s), 3);
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter");
run(&mut s, "edit.undo", json!({}));
assert!(names(&mut s).is_empty(), "the copy is undone with the effect");
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
}
/// Edit SVG Filter on a default saves the edited copy in the document under the default's name;
/// the document's filter then stands in the default's place, and deleting it lists the default again.
#[test]
fn an_edited_default_is_saved_in_the_document_and_delete_restores_the_default() {
use vectorcraft_render::effects::svg_filter::defaults::default_filter;
let mut s = session();
let glow = default_filter("Glow").unwrap();
// Saved with its own code: nothing to keep, and no undo step.
run(&mut s, "svgFilter.define", json!({"xml": glow.xml, "replace": "Glow"}));
assert_eq!((names(&mut s).len(), steps(&s)), (0, 0));
let edited = r#"<filter id="Renamed"><feGaussianBlur stdDeviation="9"/></filter>"#;
assert_eq!(run(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"}))["name"], "Glow");
assert_eq!((names(&mut s), steps(&s)), (vec!["Glow".to_string()], 1));
assert_eq!(s.doc().unwrap().history.undo[0].label, "Edit SVG Filter");
let kept = r#"<filter id="Glow"><feGaussianBlur stdDeviation="9"/></filter>"#;
assert_eq!(run(&mut s, "svgFilter.list", json!({}))["filters"][0]["xml"], kept, "it keeps the default's name");
// Applying the name now applies the document's filter.
let a = rect(&mut s, 10.0);
run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]}));
assert_eq!(drawn(&s, a), json!(kept));
// Deleting the copy leaves the effect drawing nothing, as for any filter, and lists the default.
run(&mut s, "svgFilter.delete", json!({"name": "Glow"}));
assert_eq!(drawn(&s, a), json!(""));
assert!(defaults(&mut s).contains(&("Glow".to_string(), false)));
// The default itself is not deleted.
let before = steps(&s);
assert!(err(&mut s, "svgFilter.delete", json!({"name": "Glow"})).contains("is a default SVG filter"));
assert!(err(&mut s, "svgFilter.delete", json!({"name": "Nope"})).contains("no SVG filter named"));
assert_eq!(steps(&s), before);
// Applied again, the default is copied back, and the object that named it draws with it.
let b = rect(&mut s, 50.0);
run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [b.0]}));
assert_eq!((drawn(&s, a), drawn(&s, b)), (json!(glow.xml), json!(glow.xml)));
assert_eq!(steps(&s), before + 2, "the rectangle and one step for the application");
// A new filter may take a default's name the document does not hold.
let mut s = session();
run(&mut s, "svgFilter.define", json!({"xml": r#"<filter id="Invert"><feOffset dx="1"/></filter>"#}));
assert!(defaults(&mut s).contains(&("Invert".to_string(), true)));
// An unknown name is still refused.
assert!(err(&mut s, "svgFilter.define", json!({"xml": SHIFT, "replace": "Nope"})).contains("no SVG filter named \"Nope\""));
}
/// With `index`, the filter takes the place of an applied SVG filter, a default with its copy in
/// the same undo step; any other effect keeps its place.
#[test]
fn apply_with_an_index_replaces_an_applied_filter() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "svgFilter.define", json!({"xml": SHIFT}));
run(&mut s, "svgFilter.apply", json!({"name": "Shift", "ids": [a.0]}));
run(&mut s, "effect.apply", json!({"effect": "stylize.feather", "ids": [a.0]}));
let before = steps(&s);
let r = run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": 0, "item": null}));
assert_eq!(r["ids"], json!([a.0]));
assert_eq!(steps(&s), before + 1, "one step");
let fx = s.doc().unwrap().doc.node(a).unwrap().appearance.effects.clone();
assert_eq!((fx.len(), fx[0].params["name"].as_str(), fx[1].id.as_str()), (2, Some("Invert"), "stylize.feather"));
assert_eq!(names(&mut s), ["Shift", "Invert"]);
run(&mut s, "edit.undo", json!({}));
assert_eq!(names(&mut s), ["Shift"]);
assert_eq!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects[0].params["name"], "Shift");
// Not an SVG filter, no effect there, or not an index: refused, and the default is not copied.
let before = steps(&s);
for (index, why) in [
(json!(1), "applied SVG filter"),
(json!(7), "applied SVG filter"),
(json!("x"), "`index`"),
(json!(-1), "`index`"),
(json!(null), "`index`"),
] {
let e = err(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": index, "item": null}));
assert!(e.contains(why), "{index}: {e}");
}
assert_eq!((names(&mut s), steps(&s)), (vec!["Shift".to_string()], before));
}
/// A default needs room in the document: at 64 filters applying one is refused, and a filter the
/// document holds still applies.
#[test]
fn a_full_document_refuses_a_default_it_does_not_hold() {
let mut s = session();
let a = rect(&mut s, 10.0);
for i in 0..64 {
run(&mut s, "svgFilter.define", json!({"xml": format!("<filter id=\"f{i}\"><feOffset/></filter>")}));
}
let before = steps(&s);
assert!(err(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]})).contains("at most 64 SVG filters"));
let edited = r#"<filter id="Glow"><feOffset dx="2"/></filter>"#;
assert!(err(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"})).contains("at most 64 SVG filters"));
assert_eq!(steps(&s), before);
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
run(&mut s, "svgFilter.apply", json!({"name": "f3", "ids": [a.0]}));
}
/// A default applied in one document is written to SVG as a filter and read back from the native
/// format with the document's copy.
#[test]
fn an_applied_default_survives_svg_export_and_a_native_round_trip() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "svgFilter.apply", json!({"name": "Grayscale", "ids": [a.0]}));
let out = svg(&mut s);
assert!(out.contains("<feColorMatrix") && out.contains("saturate"), "{out}");
let (back, warnings) = vectorcraft_svg::import_with_report(&out).unwrap();
assert!(warnings.is_empty(), "{warnings:?}");
assert!(back.any_node(|n| n.appearance.effects.iter().any(|e| e.id == "svg.filter")), "SVG import reads the filter back");
let doc = s.doc().unwrap().doc.clone();
let again = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
assert_eq!(again.svg_filters, doc.svg_filters);
assert_eq!(again.svg_filters[0].name, "Grayscale");
}
+4
View File
@@ -752,6 +752,10 @@ fn structured_junk() {
)}),
),
("svgFilter.apply", json!({"name": "\u{0}", "ids": [u64::MAX]})),
("svgFilter.apply", json!({"name": "Glow", "index": u64::MAX, "item": -1})),
("svgFilter.apply", json!({"name": "Rough Edges", "index": [0], "ids": "x"})),
("svgFilter.define", json!({"xml": "<filter id=\"x\"/>", "replace": "Glow"})),
("svgFilter.delete", json!({"name": "Glow"})),
("svgFilter.delete", json!({"name": ["a"]})),
(
"effect.apply",
+26 -2
View File
@@ -2904,9 +2904,9 @@ fn arb_body() -> impl Strategy<Value = Vec<u8>> {
}
/// WMF record functions VectorCraft reads, and one it doesn't.
const WMF_FUNCTIONS: [u16; 33] = [
const WMF_FUNCTIONS: [u16; 35] = [
0x0324, 0x0325, 0x0538, 0x041B, 0x0418, 0x061C, 0x0817, 0x081A, 0x0830, 0x0416, 0x0415, 0x02FA, 0x02FC, 0x02FB, 0x012D, 0x01F0, 0x0521, 0x0A32,
0x0F43, 0x0B41, 0x0940, 0x061D, 0x0213, 0x0214, 0x001E, 0x0127, 0x0106, 0x0209, 0x012E, 0x00F7, 0x01F9, 0x0142, 0x0999,
0x0F43, 0x0B41, 0x0940, 0x061D, 0x0213, 0x0214, 0x001E, 0x0127, 0x0106, 0x0209, 0x012E, 0x00F7, 0x01F9, 0x0142, 0x0103, 0x0104, 0x0999,
];
proptest! {
@@ -2933,6 +2933,30 @@ proptest! {
survive_metafile("WMF records", "x.wmf", &wmf_of(&records))?;
}
#[test]
fn random_headerless_wmf_records_never_panic(records in prop::collection::vec((prop::sample::select(WMF_FUNCTIONS.to_vec()), arb_body()), 0..32)) {
// Without the placeable header, the map and mix modes the records set decide the scale.
survive_metafile("headerless WMF records", "x.wmf", &wmf_of(&records)[22..])?;
}
#[test]
fn random_emf_plus_records_never_panic(records in prop::collection::vec((0x4001u16..0x403B, any::<u16>(), arb_body()), 0..32)) {
// One comment of EMF+ records (type, flags, data) after an EmfPlusHeader.
let mut plus = vec![];
let header = (0x4001u16, 0u16, [0xDBC0_1002u32, 0, 96, 96].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
for (kind, flags, data) in std::iter::once(&header).chain(&records) {
plus.extend(kind.to_le_bytes());
plus.extend(flags.to_le_bytes());
plus.extend((12 + data.len() as u32).to_le_bytes());
plus.extend((data.len() as u32).to_le_bytes());
plus.extend(data);
}
let mut comment = (4 + plus.len() as u32).to_le_bytes().to_vec();
comment.extend(b"EMF+");
comment.extend(plus);
survive_metafile("EMF+ records", "x.emf", &emf_of(&[(70, comment)]))?;
}
#[test]
fn pasted_metafiles_never_panic(which in 0usize..2, cut in 0usize..200_000, edits in prop::collection::vec((0usize..200_000, any::<u8>()), 0..12)) {
paste_from_elsewhere("clipboard.importEmf", json!({"dataBase64": mutated_b64(metafile_samples()[which].clone(), cut, &edits)}))?;
+51
View File
@@ -4191,6 +4191,57 @@ fn standard_vertical_roman_alignment_comes_back() {
assert_eq!(flags(&texts(&read_back(&both))[0])[2], (false, true));
}
/// Insert Aki Left and Right come back on each run, in vertical and horizontal type: a run with
/// either writes it as key 49 or 50 in 1/1000 em, a run without writes neither, and nothing is
/// reported. Each object lays out as it did. A run that also has an attribute the text document
/// leaves out is still reported.
#[test]
fn insert_aki_comes_back() {
use vectorcraft_doc::{CharStyle, TextObject, TextRun};
let plain = style(14.0, Color::BLACK);
let left = CharStyle { aki_left: 250.0, ..plain.clone() };
let both = CharStyle { aki_left: 125.5, aki_right: 500.0, ..plain.clone() };
let mut doc = Document::new(200.0, 200.0);
let layer = doc.layers[0].id;
let mut down = TextObject::point(vectorcraft_geom::Point::new(150.0, 20.0), "", plain.clone());
down.runs = vec![TextRun::new("AB", left.clone()), TextRun::new("CD", plain.clone()), TextRun::new("EF", both.clone())];
down.vertical = true;
let mut across = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "", plain.clone());
across.runs = vec![TextRun::new("GH", both.clone()), TextRun::new("IJ", plain.clone())];
for t in [down, across] {
let n = text_node(&mut doc, t);
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
let back = read_back(&doc);
same_lines(&type_lines(&back), &type_lines(&doc));
let texts = |d: &Document| -> Vec<TextObject> {
d.layers[0].children().unwrap().iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect()
};
let aki = |t: &TextObject| t.runs.iter().map(|r| (r.style.aki_left, r.style.aki_right)).collect::<Vec<_>>();
let (written, read) = (texts(&doc), texts(&back));
assert_eq!(read.iter().map(aki).collect::<Vec<_>>(), [vec![(250.0, 0.0), (0.0, 0.0), (125.5, 500.0)], vec![(125.5, 500.0), (0.0, 0.0)]]);
let origins = |t: &TextObject| {
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.iter().map(|g| (r3(g.origin.x), r3(g.origin.y))).collect::<Vec<_>>()
};
for (w, r) in written.iter().zip(&read) {
assert_eq!(origins(r), origins(w), "vertical={}", w.vertical);
}
let decoded = text_document(&program(&doc));
for (key, count) in [("/49 250.0", 1), ("/49 125.5", 2), ("/50 500.0", 2)] {
assert_eq!(decoded.matches(key).count(), count, "{key}: {decoded}");
}
assert_eq!(decoded.matches("/49 ").count() + decoded.matches("/50 ").count(), 5, "{decoded}");
// Underline is still left out, and reported.
let mut lossy = doc.clone();
let id = lossy.layers[0].children().unwrap()[0].id;
if let Some(NodeKind::Text(t)) = lossy.node_mut(id).map(|n| &mut n.kind) {
t.runs[0].style.underline = true;
}
assert_eq!(export_ai_editing(&lossy, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]);
}
/// The text document of program `text` (LF line ends), decoded, with its UTF-16 strings' zero
/// bytes left out.
fn text_document(text: &str) -> String {
+18 -1
View File
@@ -20,6 +20,7 @@ use std::fmt::Write;
use kurbo::{ParamCurveArclen, PathSeg};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::text::MAX_AKI;
use vectorcraft_doc::{
AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, LineCap, LineJoin, Mojikumi, Node, NodeId, NodeKind, ParaDirection,
ParaStyle, PathAlign, PathEffect, TextKind, TextObject, VerticalAlign,
@@ -29,7 +30,7 @@ use vectorcraft_geom::{Affine, PathData, Point};
use crate::ps;
/// What the text document holds of type, and what it leaves out.
pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps";
pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps";
/// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it.
const STREAM_VERSION: u32 = 14;
@@ -326,6 +327,12 @@ fn end_read_as_none(t: &TextObject) -> bool {
!closed(&segs) && end < 1.0 - 1e-9 && place_on(&segs, end) >= segs.len() as f64 - 0.02
}
/// Insert Aki Left or Right `v` as the text document holds it: 0 to [`MAX_AKI`] in 1/1000 em, and 0
/// for a value that is not a number.
fn held_aki(v: f64) -> f64 {
if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) }
}
/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])?
pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool {
// Small capitals are read back at Document Setup's default size.
@@ -360,6 +367,8 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool {
tate_chu_yoko: s.tate_chu_yoko,
// Key 35 holds one of the two: a Tate-chu-yoko run is read back without the other.
standard_vertical_roman: s.standard_vertical_roman && !s.tate_chu_yoko,
aki_left: held_aki(s.aki_left),
aki_right: held_aki(s.aki_right),
..CharStyle::default()
}
};
@@ -677,6 +686,14 @@ impl TextDoc {
};
d.push((12, V::Int(caps)));
d.push((35, V::Int(baseline_direction(st))));
// Insert Aki Left and Right in 1/1000 em, as the reader reads keys 49 and 50. No key is no
// space added: neither the stories' character attributes nor `[Normal Character Style]` set one.
for (key, v) in [(49, st.aki_left), (50, st.aki_right)] {
let v = held_aki(v);
if v > 0.0 {
d.push((key, real(v)));
}
}
let fill = solid(&st.fill).flatten();
// A stroke of no width keeps its paint.
let stroke = solid(&st.stroke).flatten();
+1 -1
View File
@@ -631,7 +631,7 @@ impl<'a> Reader<'a> {
let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false };
spec.series_paints = paints;
spec.placed = Some(placed);
spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::art_bounds(c));
spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::graph_art_without_type(c));
tag_series(art, &tags);
art.extras_mut().graph = Some(Box::new(spec));
true
+61
View File
@@ -25,6 +25,7 @@ use std::collections::{BTreeMap, HashMap};
use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::text::MAX_AKI;
use vectorcraft_doc::{
Burasagari, CharStyle, HyphenationOptions, JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LineCap, LineJoin, Node, NodeId, NodeKind,
ParaDirection, ParaStyle, PathAlign, PathEffect, TabAlign, TabStop, TextKind, TextObject, TextRun,
@@ -525,6 +526,17 @@ struct Style {
/// Key 35 at 1 (Standard): Standard Vertical Roman Alignment, half-width characters upright in
/// a column. Any other value, or no key in the run, its character style or the defaults, is off.
standard_vertical_roman: bool,
/// Keys 49 and 50, Insert Aki Left and Right ([`CharStyle::aki_left`]), in 1/1000 em.
aki_left: f64,
aki_right: f64,
}
/// Insert Aki Left or Right as key `v` of a character style gives it, in 1/1000 em (the unit the
/// scripting reference gives `aki left` and `aki right`), 0 to [`MAX_AKI`]. A negative value, one
/// that is not a finite number, or no key is 0: no space added. A key the run itself carries wins
/// over its styles' even when it is not a number, so a bad value never shows a style's.
fn aki(v: Option<&Val>) -> f64 {
v.and_then(Val::num).filter(|v| v.is_finite() && *v > 0.0).map_or(0.0, |v| v.min(MAX_AKI))
}
/// The longest font version string read from a font record: name ID 5 strings are short (`Version
@@ -922,6 +934,8 @@ impl Texts {
caps: num("12").filter(|v| *v == 1.0 || *v == 2.0).map_or(0, |v| v as u8),
tate_chu_yoko: num("35") == Some(3.0),
standard_vertical_roman: num("35") == Some(1.0),
aki_left: aki(pick("49")),
aki_right: aki(pick("50")),
}
}
}
@@ -1549,6 +1563,9 @@ fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle {
small_caps: (s.caps == 1).then(|| vectorcraft_doc::DocSetup::default().small_caps_size),
tate_chu_yoko: s.tate_chu_yoko,
standard_vertical_roman: s.standard_vertical_roman,
// In ems of the type's own size, so the art's scale does not apply.
aki_left: s.aki_left,
aki_right: s.aki_right,
..CharStyle::default()
}
}
@@ -1922,6 +1939,48 @@ mod tests {
assert!(texts(b"/35 3").style(None).tate_chu_yoko && !texts(b"/35 3").style(None).standard_vertical_roman);
}
/// Keys 49 and 50 of a character style are Insert Aki Left and Right in 1/1000 em, each from the
/// run, its character style and the styles that is based on, `[Normal Character Style]`, then the
/// document's defaults. A run's own 0 wins over a style's value, a value past 1000 is 1000, and a
/// negative value, one that is not a number or no key at all is 0.
#[test]
fn a_run_keeps_its_insert_aki() {
let texts = |defaults: &[u8], normal: &[u8]| Texts {
stories: vec![],
fonts: vec![],
defaults: read(defaults).unwrap(),
para_defaults: Val::Dict(BTreeMap::new()),
char_sheets: vec![
read(&[&b"/0 ([Normal Character Style]) /6 << "[..], normal, b" >>"].concat()).unwrap(),
read(b"/0 (Base) /6 << /49 125.0 >>").unwrap(),
read(b"/0 (Spaced) /5 1 /6 << /50 500.0 >>").unwrap(),
],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
kinsoku_sets: vec![],
};
let aki = |defaults: &[u8], normal: &[u8], run: &[u8]| {
let s = texts(defaults, normal).style(Some(&read(run).unwrap()));
(s.aki_left, s.aki_right)
};
assert_eq!(aki(b"/0 0", b"", b"/6 << /49 250.0 /50 750.0 >>"), (250.0, 750.0), "the run's own");
assert_eq!(aki(b"/0 0", b"", b"/5 2 /6 << >>"), (125.0, 500.0), "its style's, and the style that is based on");
assert_eq!(aki(b"/0 0", b"", b"/5 2 /6 << /49 0.0 /50 0 >>"), (0.0, 0.0), "the run's own zero wins");
assert_eq!(aki(b"/49 10.0 /50 20.0", b"/49 30.0", b"/6 << >>"), (30.0, 20.0), "Normal, then the document's");
assert_eq!(aki(b"/49 10.0 /50 20.0", b"", b"/6 << >>"), (10.0, 20.0), "the document's");
assert_eq!(aki(b"/0 0", b"", b"/6 << >>"), (0.0, 0.0), "no key");
assert_eq!(aki(b"/0 0", b"", b"/6 << /49 1000.5 /50 1e300 >>"), (MAX_AKI, MAX_AKI), "clamped");
for bad in [&b"-1.0"[..], b"-250", b"(125)", b"true", b"[ 125 ]", b"1e400", b"-1e400"] {
let run = [&b"/5 2 /6 << /49 "[..], bad, b" /50 ", bad, b" >>"].concat();
assert_eq!(aki(b"/0 0", b"", &run), (0.0, 0.0), "{}", String::from_utf8_lossy(bad));
}
// In ems of the type's size: the art's scale leaves it as it is.
let s = texts(b"/0 0", b"").style(Some(&read(b"/6 << /49 250.0 /50 125.0 >>").unwrap()));
let c = char_style(&s, 10.0, Affine::IDENTITY);
assert_eq!((c.aki_left, c.aki_right), (250.0, 125.0));
}
/// Keys 61, 62 and 64 of a character style are its stroke's cap (0 butt, 1 round, 2
/// projecting), join (0 miter, 1 round, 2 bevel) and miter limit, from the run, its character
/// style or the document's defaults. A value that isn't one of theirs keeps the default, a miter
@@ -2397,6 +2456,8 @@ mod tests {
caps: 0,
tate_chu_yoko: false,
standard_vertical_roman: false,
aki_left: 0.0,
aki_right: 0.0,
},
)],
kerns: vec![],
+1 -1
View File
@@ -101,7 +101,7 @@ const HEX_LINE: usize = 60;
pub const SUBLAYERS: &str = "sublayers are written as groups in their top-level layer (legacy .ai files have no sublayers)";
pub const TYPE: &str = "type a legacy .ai can't hold as text (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is written as outlines";
pub const ROTATED_TYPE: &str = "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate characters)";
pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out";
pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, Insert Aki, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out";
pub const DYNAMIC_TEXT: &str = "Dynamic Text is written as the sizes the type is drawn at (legacy .ai files don't have it)";
pub const HIDDEN: &str = "hidden objects are left out (hidden layers are kept, hidden)";
pub const HIDDEN_LAYER: &str = "hidden objects are moved to a hidden layer above their own (legacy .ai files can hide only layers)";
+3
View File
@@ -123,6 +123,9 @@ pub(super) fn lost_attributes(t: &TextObject) -> bool {
|| s.optical_kerning
|| s.small_caps.is_some()
|| s.position != CharPosition::Normal
// Its text operators (§15.4) have no Insert Aki.
|| s.aki_left != 0.0
|| s.aki_right != 0.0
|| !s.features.is_empty()
|| !s.font_axes.is_empty()
};
+35
View File
@@ -1435,6 +1435,41 @@ fn variable_font_settings_are_warned_as_left_out() {
assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text");
}
/// A legacy `.ai` text object has no Insert Aki (§15.4): type with Insert Aki Left or Right is
/// written as text with the warning that it is left out. Written as outlines, the glyphs keep the
/// space it adds, and nothing is reported.
#[test]
fn insert_aki_is_warned_as_left_out_of_text() {
for (left, right) in [(250.0, 0.0), (0.0, 125.0)] {
let mut doc = typed();
let id = texts(&doc)[0].0.id;
if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) {
t.runs[0].style.aki_left = left;
t.runs[0].style.aki_right = right;
}
let out = write(&doc);
assert!(out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{left} {right}: {:?}", out.warnings);
assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text");
}
let width = |aki: f64| {
let mut st = style(20.0, red());
st.aki_left = aki;
st.aki_right = aki;
let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "HH", st);
let mut doc = Document::new(300.0, 200.0);
let layer = doc.layers[0].id;
let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = write_with(&doc, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() });
assert!(!out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{:?}", out.warnings);
let back = crate::import(&out.bytes).unwrap().document;
children(&children(&back.layers[0])[0])[0].visual_bounds().unwrap().width()
};
// Between the two H's: 0.5 em after the first and 0.5 em before the second, 20 pt.
let (plain, spaced) = (width(0.0), width(500.0));
assert!((spaced - plain - 20.0).abs() < 0.05, "{plain} {spaced}");
}
/// Standard Vertical Roman Alignment is written as `Tv` and Tate-chu-yoko in horizontal type as a
/// Kumi block recorded for later use, `TY` (§15.3.4), each where it changes: the marks read back
/// on the same characters, a block is closed before its text object ends, and type with neither
+4 -1
View File
@@ -489,8 +489,11 @@ impl<'a> Scene<'a> {
self.warn(TOO_LARGE);
return;
}
// Off the region, an object is still written when brush art painted along its brushed
// strokes, or those of the objects in it, can reach the region.
let off = |b: Rect, reach: f64| !overlaps(b.inflate(1.0 + reach, 1.0 + reach), self.o.region);
match n.visual_bounds_with(&self.symbols) {
Some(b) if !force && !overlaps(b.inflate(1.0, 1.0), self.o.region) => return,
Some(b) if !force && off(b, 0.0) && off(b, vectorcraft_brush::reach_within(n)) => return,
None if !n.is_container() => return,
_ => {}
}
+53
View File
@@ -1654,6 +1654,59 @@ fn an_instance_whose_brush_art_reaches_the_region_is_written() {
assert!(page.contains("1 0 0 rg"), "{page}");
}
#[test]
fn a_path_whose_brush_art_reaches_the_region_is_written() {
// A line from (-5, 40) to (-5, 60) with a 1 pt red stroke painted by a 20 pt round nib lies
// left of the artboard, and the nib paints 10 pt either side of it, onto the artboard: alone, in
// a group and as a compound path. Without its brush, or 100 pt left of the artboard, where the
// nib does not reach it, the line is left out.
let red = |x: f64, brushed: bool| {
let mut n = Node::path(
vectorcraft_doc::NodeId(0),
shapes::line((x, 40.0).into(), (x, 60.0).into()),
Appearance::basic(Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0),
);
if brushed {
n.appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into());
}
n
};
let cases: [(&str, f64, bool, bool); 5] = [
("path", -5.0, true, true),
("group", -5.0, true, true),
("compound path", -5.0, true, true),
("unbrushed path", -5.0, false, false),
("far path", -100.0, true, false),
];
for (what, x, brushed, written) in cases {
let mut d = Document::new(200.0, 200.0);
let mut lib = vectorcraft_brush::library(&d);
let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else {
panic!("the 3 pt. Round brush")
};
c.size = 20.0;
vectorcraft_brush::store(&mut d, &lib);
let line = red(x, brushed);
let mut n = match what {
"group" => Node::group(vectorcraft_doc::NodeId(0), vec![Arc::new(line)]),
"compound path" => {
let mut c = Node::new(
vectorcraft_doc::NodeId(0),
NodeKind::Compound { children: vec![Arc::new(red(x, false))], rule: vectorcraft_geom::FillRule::NonZero },
);
c.appearance = line.appearance;
c
}
_ => line,
};
n.id = d.alloc_id();
let layer = d.layers[0].id;
d.insert(Some(layer), usize::MAX, n).unwrap();
let page = page_of(&d, &opts(&d));
assert_eq!(page.contains("1 0 0 rg") || page.contains("1 0 0 RG"), written, "{what}: {page}");
}
}
#[test]
fn symbol_art_effects_are_written_where_they_draw() {
// The symbol's square at (10, 40), which a Transform effect moves 100 pt right, is drawn from
+5 -4
View File
@@ -166,10 +166,11 @@ fn create(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Va
/// `Object.defineProperty` (section 15.2.3.6).
fn define_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
let o = require_object(interp, &arg(args, 0), "defineProperty")?;
let k = interp.to_key(&arg(args, 1))?;
let desc = to_desc(interp, &arg(args, 2))?;
let roots = desc_values(&desc);
interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true))?;
interp.with_key(&arg(args, 1), |interp, k| {
let desc = to_desc(interp, &arg(args, 2))?;
let roots = desc_values(&desc);
interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true))
})?;
Ok(Value::Object(o))
}
+14 -4
View File
@@ -1791,8 +1791,7 @@ impl Interp {
return self.replace(2, v);
}
self.check_coercible(&base, Some(&k), false)?;
let name = self.to_key(&k)?;
let v = self.get_value(&base, &name)?;
let v = self.with_key(&k, |i, name| i.get_value(&base, &name))?;
self.replace(2, v)?;
if with_this { self.push(base) } else { Ok(()) }
}
@@ -1864,8 +1863,7 @@ impl Interp {
return self.replace(2, Value::Number(if prefix { new } else { old }));
}
self.check_coercible(&base, Some(&k), false)?;
let name = self.to_key(&k)?;
let r = self.inc_property(&base, name, prefix, dec)?;
let r = self.with_key(&k, |i, name| i.inc_property(&base, name, prefix, dec))?;
self.replace(2, r)
}
@@ -2682,6 +2680,18 @@ impl Interp {
}
}
/// Runs `f` with the property name [`Self::to_key`] makes from `v`. A name converted from a
/// value that is not a string is kept reachable while `f` runs, so a collection that a getter
/// or setter starts still counts its units.
pub(crate) fn with_key<T>(&mut self, v: &Value, f: impl FnOnce(&mut Self, Key) -> JsResult<T>) -> JsResult<T> {
let name = self.to_key(v)?;
if matches!(v, Value::String(_)) {
return f(self, name);
}
let root = Value::String(Str::from_rc(name.clone()));
self.rooted(&[root], |i| f(i, name))
}
/// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that
/// copy's bytes are reserved and added to the heap first, without taking fuel. The rope stays
/// rooted while the copy is reserved; everything else the caller still needs must be
+26
View File
@@ -434,6 +434,32 @@ fn a_call_keeps_its_operands_while_a_string_receiver_is_boxed() {
assert_eq!(realm.run(src), Ok(JsValue::Number(1.0)));
}
#[test]
fn a_computed_key_stays_counted_while_its_getter_or_setter_runs() {
// `o` has an accessor named by a flat string of 131,073 units. `key`'s toString returns a new
// rope with the same units, so using `key` as a name makes a second flat copy, which must stay
// counted while an accessor makes a third. The heap has room for one more copy, not two.
let build = "var s = 'x'; for (var i = 0; i < 17; i++) s = s + s; function f(c) { return s + c; } \
function copy() { var g = f('g'); g[0]; return 1; } var o = {}, name = f('k'); name[0]; \
Object.defineProperty(o, name, { get: copy, set: copy }); \
var key = { toString: function () { return f('k'); } }; 0";
let realm = || {
let mut realm = Realm::with_options(Options::default(), Limits::default());
assert_eq!(realm.run(build), Ok(JsValue::Number(0.0)));
let interp = realm.interp();
interp.collect_garbage();
let copy = crate::heap::string_bytes(131_073);
interp.limits.heap_bytes = interp.heap.bytes + copy + copy / 2;
interp.reset_gc_threshold();
realm
};
assert_eq!(realm().run("o[name]"), Ok(JsValue::Number(1.0)), "the accessor's own copy fits");
for read in ["o[key]", "o[key] = 1", "o[key]++", "Object.defineProperty({}, key, { get value() { return copy(); } })"] {
let result = realm().run(read);
assert!(matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)), "{read}: {result:?}");
}
}
#[test]
fn compiling_a_pattern_counts_against_the_heap() {
let src = "var s = '[\\\\s\\\\S]a*'; for (var i = 0; i < 14; i++) s = s + s; new RegExp(s).source.length";
+1 -1
View File
@@ -1252,7 +1252,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.svgFilterDialog",
"Apply SVG Filter…",
"",
"{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's filters; OK runs svgFilter.apply with selected, or effect.setParams on the applied effect; New and Edit open the code, Save runs svgFilter.define, Delete runs svgFilter.delete and Import… svgFilter.import with a picked SVG file",
"{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's defaults (the document's filter of a default's name in its place) and then the document's other filters; OK runs svgFilter.apply with selected, and with index and item for the applied effect; New and Edit open the code, Save runs svgFilter.define (replace: the filter edited, a default included), Delete runs svgFilter.delete (off for a default the document holds no copy of) and Import… svgFilter.import with a picked SVG file",
),
(
"ui.importSvgFilter",
+2 -1
View File
@@ -3,7 +3,7 @@ name = "vectorcraft-metafile"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "VectorCraft metafiles: hand-written EMF and WMF writers and readers, and a QuickDraw picture (PICT) reader"
description = "VectorCraft metafiles: hand-written EMF and WMF writers, EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader"
[lints]
workspace = true
@@ -15,6 +15,7 @@ vectorcraft-doc = { workspace = true }
vectorcraft-effects = { workspace = true }
vectorcraft-brush = { workspace = true }
vectorcraft-text = { workspace = true }
craft-metafile = { workspace = true }
kurbo = { workspace = true }
image = { workspace = true }
+1 -51
View File
@@ -1,5 +1,4 @@
//! Little-endian values: the buffer both writers build records in, and a reader that never reads
//! past its data (every read is an `Option`).
//! Little-endian values: the buffer both writers build records in.
/// Bytes being written.
#[derive(Default)]
@@ -45,52 +44,3 @@ impl Out {
}
}
}
/// Sequential little-endian reads from a slice.
#[derive(Clone, Copy)]
pub(crate) struct Reader<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> Reader<'a> {
pub fn new(data: &'a [u8]) -> Self {
Self { data, pos: 0 }
}
pub fn bytes(&mut self, n: usize) -> Option<&'a [u8]> {
let b = self.data.get(self.pos..self.pos.checked_add(n)?)?;
self.pos += n;
Some(b)
}
fn array<const N: usize>(&mut self) -> Option<[u8; N]> {
self.bytes(N)?.try_into().ok()
}
pub fn u16(&mut self) -> Option<u16> {
self.array().map(u16::from_le_bytes)
}
pub fn i16(&mut self) -> Option<i16> {
self.array().map(i16::from_le_bytes)
}
pub fn u32(&mut self) -> Option<u32> {
self.array().map(u32::from_le_bytes)
}
pub fn i32(&mut self) -> Option<i32> {
self.array().map(i32::from_le_bytes)
}
pub fn f32(&mut self) -> Option<f32> {
self.array().map(f32::from_le_bytes)
}
pub fn skip(&mut self, n: usize) -> Option<()> {
self.bytes(n).map(drop)
}
/// The bytes not read yet.
pub fn rest(&self) -> &'a [u8] {
self.data.get(self.pos..).unwrap_or_default()
}
}
/// `len` bytes of `data` from `offset` (record-relative offsets read from untrusted files).
pub(crate) fn slice(data: &[u8], offset: u32, len: u32) -> Option<&[u8]> {
let start = usize::try_from(offset).ok()?;
data.get(start..start.checked_add(usize::try_from(len).ok()?)?)
}
+5 -283
View File
@@ -1,30 +1,24 @@
//! Device-independent bitmaps (DIBs), the pixels inside image records: written bottom-up as 24-bit
//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source); read from 1,
//! 4, 8, 16, 24 and 32-bit uncompressed and bit-field bitmaps and from embedded JPEG and PNG.
//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source).
use std::io::Cursor;
use vectorcraft_doc::resample::{Resample, resized};
use crate::bytes::Reader;
/// Most pixels along a side of an image the writers store (larger ones are scaled down).
const MAX_SIDE: u32 = 8192;
/// Most pixels an image the writers store holds.
const MAX_PIXELS: u64 = 1 << 24;
/// Most pixels along a side, and in all, of a bitmap the reader decodes.
/// Most pixels along a side, and in all, of a bitmap the PICT reader decodes.
pub(crate) const MAX_READ_SIDE: u32 = 1 << 15;
pub(crate) const MAX_READ_PIXELS: u64 = 1 << 26;
/// Most pixels the bitmaps of one file may decode to together (four of the largest one), so a small
/// file of many image records can't cost minutes of decoding (#3600).
pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28;
/// What [`decode`] says of a bitmap past what is left of the file's budget.
/// What [`charge`] says of a bitmap past what is left of the file's budget.
pub(crate) const OVER_BUDGET: &str = "the bitmaps hold more pixels than one file may";
const BI_RGB: u32 = 0;
const BI_BITFIELDS: u32 = 3;
const BI_JPEG: u32 = 4;
const BI_PNG: u32 = 5;
/// Pixels with straight (not premultiplied) alpha, row by row from the top.
#[derive(Clone, Debug, PartialEq)]
@@ -124,48 +118,6 @@ pub(crate) fn bgra32(img: &Rgba, opacity: f32) -> (Vec<u8>, Vec<u8>) {
(header(img.width, img.height, 32, bits.len()), bits)
}
/// How the fourth byte of 32-bit pixels reads.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Alpha {
/// Unused (StretchDIBits and BitBlt ignore it): every pixel opaque.
Ignore,
/// Premultiplied alpha (AlphaBlend with per-pixel alpha).
Premultiplied,
}
/// A colour channel of `v` under `mask`, scaled to 0–255.
fn channel(v: u32, mask: u32) -> u8 {
if mask == 0 {
return 0;
}
let shift = mask.trailing_zeros();
let max = u64::from(mask >> shift);
let x = u64::from((v & mask) >> shift);
((x * 255 + max / 2) / max.max(1)).min(255) as u8
}
/// PNG `bytes` without its compressed or text ancillary chunks (`iCCP`, `zTXt`, `iTXt`, `tEXt`),
/// which the pixels don't need and which a decoder expands when it is made. Other bytes, and a PNG
/// whose chunks don't read to the end, are returned as they are.
fn png_without_metadata(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> {
const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
if !bytes.starts_with(SIGNATURE) {
return bytes.into();
}
let mut out = SIGNATURE.to_vec();
let mut at = SIGNATURE.len();
while at < bytes.len() {
let (Some(len), Some(kind)) = (bytes.get(at..at + 4), bytes.get(at + 4..at + 8)) else { return bytes.into() };
let len = u32::from_be_bytes([len[0], len[1], len[2], len[3]]) as usize;
let Some(end) = at.checked_add(12).and_then(|n| n.checked_add(len)).filter(|end| *end <= bytes.len()) else { return bytes.into() };
if !matches!(kind, b"iCCP" | b"zTXt" | b"iTXt" | b"tEXt") {
out.extend_from_slice(&bytes[at..end]);
}
at = end;
}
out.into()
}
/// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded.
pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> {
let n = u64::from(w) * u64::from(h);
@@ -173,215 +125,24 @@ pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> {
Ok(())
}
/// Read a DIB from its BITMAPINFO (`bmi`: the header and colour table) and pixel `bits`, taking its
/// pixels from what is `left` of the file's budget ([`MAX_FILE_PIXELS`]).
pub(crate) fn decode(bmi: &[u8], bits: &[u8], alpha: Alpha, left: &mut u64) -> Result<Rgba, String> {
let bad = || "a bitmap is damaged".to_string();
let mut r = Reader::new(bmi);
let size = r.u32().ok_or_else(bad)?;
let (width, height, bpp, compression, colors, palette_entry, masks_at) = if size == 12 {
// BITMAPCOREHEADER: 16-bit sizes, RGB triples.
let w = i32::from(r.u16().ok_or_else(bad)?);
let h = i32::from(r.u16().ok_or_else(bad)?);
r.skip(2).ok_or_else(bad)?;
let bpp = r.u16().ok_or_else(bad)?;
(w, h, bpp, BI_RGB, 0, 3, 0)
} else if size >= 40 {
let w = r.i32().ok_or_else(bad)?;
let h = r.i32().ok_or_else(bad)?;
r.skip(2).ok_or_else(bad)?;
let bpp = r.u16().ok_or_else(bad)?;
let c = r.u32().ok_or_else(bad)?;
r.skip(12).ok_or_else(bad)?;
let used = r.u32().ok_or_else(bad)?;
(w, h, bpp, c, used, 4, 40)
} else {
return Err(bad());
};
if compression == BI_JPEG || compression == BI_PNG {
// The size comes from the image header, so an over-limit bitmap is refused before any pixels are decoded.
// A PNG's compressed ICC profile and text chunks expand when its decoder is made, and
// nothing here uses them: they are left out before the size is read and the pixels decoded.
let bits = png_without_metadata(bits);
let (w, h) = image::ImageReader::new(Cursor::new(&*bits)).with_guessed_format().map_err(|_| bad())?.into_dimensions().map_err(|_| bad())?;
if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS {
return Err("a bitmap is too large to read".into());
}
charge(w, h, left)?;
let img = image::load_from_memory(&bits).map_err(|_| bad())?.to_rgba8();
return Ok(Rgba { width: w, height: h, pixels: img.into_raw() });
}
if compression != BI_RGB && compression != BI_BITFIELDS {
return Err("compressed (RLE) bitmaps can't be read yet".into());
}
let top_down = height < 0;
let (w, h) = (width.unsigned_abs(), height.unsigned_abs());
if w == 0 || h == 0 {
return Err("a bitmap is empty".into());
}
if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS {
return Err("a bitmap is too large to read".into());
}
let header_len = size as usize;
// Bit-field masks follow a plain 40-byte header, or sit inside the larger ones.
let fields = compression == BI_BITFIELDS;
let masks: Option<[u32; 4]> = fields.then(|| {
let mut m = Reader::new(bmi.get(masks_at..).unwrap_or_default());
let rgb = [m.u32().unwrap_or(0), m.u32().unwrap_or(0), m.u32().unwrap_or(0)];
// An alpha mask comes with BITMAPV3INFOHEADER and later.
let a = if header_len >= 56 { m.u32().unwrap_or(0) } else { 0 };
[rgb[0], rgb[1], rgb[2], a]
});
let palette_at = header_len + if fields && header_len == 40 { 12 } else { 0 };
let bpp_u = u32::from(bpp);
let palette: Vec<[u8; 3]> = if bpp_u <= 8 {
let n = if colors == 0 { 1usize << bpp_u } else { (colors as usize).min(256) };
bmi.get(palette_at..)
.unwrap_or_default()
.chunks_exact(palette_entry)
.take(n)
.map(|e| [e.get(2).copied().unwrap_or(0), e.get(1).copied().unwrap_or(0), e.first().copied().unwrap_or(0)])
.collect()
} else {
vec![]
};
if !matches!(bpp, 1 | 4 | 8 | 16 | 24 | 32) {
return Err(format!("{bpp}-bit bitmaps can't be read"));
}
let row = stride(w, bpp_u).ok_or_else(bad)?;
if bits.len() < row.checked_mul(h as usize).ok_or_else(bad)? {
return Err(bad());
}
charge(w, h, left)?;
let (mr, mg, mb, ma) = match (masks, bpp) {
(Some([r, g, b, a]), _) => (r, g, b, a),
(None, 16) => (0x7c00, 0x03e0, 0x001f, 0),
_ => (0x00ff_0000, 0x0000_ff00, 0x0000_00ff, 0xff00_0000),
};
let mut pixels = Vec::with_capacity(w as usize * h as usize * 4);
for y in 0..h as usize {
let src_row = if top_down { y } else { h as usize - 1 - y };
let line = bits.get(src_row * row..src_row * row + row).ok_or_else(bad)?;
for x in 0..w as usize {
let px: [u8; 4] = match bpp {
1 | 4 | 8 => {
let bit = x * bpp_u as usize;
let byte = line.get(bit / 8).copied().unwrap_or(0);
let idx = (byte >> (8 - bpp_u as usize - bit % 8)) & ((1u16 << bpp_u) - 1) as u8;
let [r, g, b] = palette.get(idx as usize).copied().unwrap_or([0, 0, 0]);
[r, g, b, 255]
}
16 => {
let v = u32::from(u16::from_le_bytes([line.get(x * 2).copied().unwrap_or(0), line.get(x * 2 + 1).copied().unwrap_or(0)]));
[channel(v, mr), channel(v, mg), channel(v, mb), 255]
}
24 => {
let p = line.get(x * 3..x * 3 + 3).unwrap_or(&[0, 0, 0]);
[p[2], p[1], p[0], 255]
}
_ => {
let p = line.get(x * 4..x * 4 + 4).unwrap_or(&[0, 0, 0, 0]);
let v = u32::from_le_bytes([p[0], p[1], p[2], p[3]]);
let a = if alpha == Alpha::Premultiplied && ma != 0 { channel(v, ma) } else { 255 };
let un =
|c: u8| if alpha == Alpha::Premultiplied && a < 255 { (u32::from(c) * 255 / u32::from(a.max(1))).min(255) as u8 } else { c };
[un(channel(v, mr)), un(channel(v, mg)), un(channel(v, mb)), if alpha == Alpha::Premultiplied { a } else { 255 }]
}
};
pixels.extend_from_slice(&px);
}
}
Ok(Rgba { width: w, height: h, pixels })
}
/// A packed DIB (a BITMAPINFO and its bits, one after the other, as WMF records hold them) split
/// into the two.
pub(crate) fn split(packed: &[u8]) -> Option<(&[u8], &[u8])> {
let mut r = Reader::new(packed);
let size = r.u32()? as usize;
let (bpp, compression, used, entry) = if size == 12 {
r.skip(6)?;
(r.u16()?, BI_RGB, 0, 3)
} else {
r.skip(10)?;
let bpp = r.u16()?;
let c = r.u32()?;
r.skip(12)?;
(bpp, c, r.u32()? as usize, 4)
};
let masks = if compression == BI_BITFIELDS && size == 40 { 12 } else { 0 };
let colors = if used > 0 {
used.min(256)
} else if bpp <= 8 {
1usize << bpp
} else {
0
};
let len = size.checked_add(masks)?.checked_add(colors * entry)?;
Some((packed.get(..len)?, packed.get(len..)?))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_pngs_compressed_metadata_is_left_out_before_it_is_decoded() {
use image::ImageEncoder;
let mut png = vec![];
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
encoder.set_icc_profile(vec![0; 1 << 20]).unwrap();
encoder.write_image(&[10, 20, 30], 1, 1, image::ExtendedColorType::Rgb8).unwrap();
assert!(png.windows(4).any(|w| w == b"iCCP"));
let stripped = png_without_metadata(&png);
assert!(!stripped.windows(4).any(|w| w == b"iCCP") && stripped.len() < png.len());
let img = image::load_from_memory(&stripped).unwrap().to_rgba8();
assert_eq!(img.get_pixel(0, 0).0, [10, 20, 30, 255]);
// Not a PNG, or a PNG cut short: unchanged.
assert_eq!(&*png_without_metadata(b"BM...."), b"BM....");
assert_eq!(&*png_without_metadata(&png[..png.len() - 3]), &png[..png.len() - 3]);
}
fn sample() -> Rgba {
// 3 × 2: red, green, blue / half-transparent black, transparent, white.
let pixels = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255];
Rgba { width: 3, height: 2, pixels }
}
/// A whole file's budget.
fn budget() -> u64 {
MAX_FILE_PIXELS
}
/// A BITMAPINFOHEADER of an embedded PNG.
fn png_header() -> Vec<u8> {
let mut bmi = vec![0u8; 40];
bmi[..4].copy_from_slice(&40u32.to_le_bytes());
bmi[16..20].copy_from_slice(&BI_PNG.to_le_bytes());
bmi
}
#[test]
fn oversized_png_is_refused_from_its_header() {
// A width over the limit in the IHDR chunk: decoding the pixels would fail with a different error.
let png = crate::tests::png_claiming(MAX_READ_SIDE + 1, 1);
let err = decode(&png_header(), &png, Alpha::Ignore, &mut budget()).unwrap_err();
assert_eq!(err, "a bitmap is too large to read");
}
#[test]
fn bitmaps_share_the_file_budget() {
// #3600: each bitmap is charged before it is decoded, and one past what is left is refused.
let (bmi, bits) = rgb24(&sample(), 1.0);
let mut left = 6 + 5;
assert!(decode(&bmi, &bits, Alpha::Ignore, &mut left).is_ok());
assert!(charge(3, 2, &mut left).is_ok());
assert_eq!(left, 5);
assert_eq!(decode(&bmi, &bits, Alpha::Ignore, &mut left).unwrap_err(), OVER_BUDGET);
assert_eq!(charge(3, 2, &mut left).unwrap_err(), OVER_BUDGET);
assert_eq!(left, 5, "a refused bitmap costs nothing");
// An embedded PNG is charged from its header, so one past the budget is never decoded.
let mut left = (1 << 20) - 1;
let png = crate::tests::png_claiming(1 << 10, 1 << 10);
assert_eq!(decode(&png_header(), &png, Alpha::Ignore, &mut left).unwrap_err(), OVER_BUDGET);
}
#[test]
@@ -405,45 +166,6 @@ mod tests {
assert_eq!(&half[12..16], &[0, 0, 128, 128]);
}
#[test]
fn rgb24_round_trips_over_white() {
let (bmi, bits) = rgb24(&sample(), 1.0);
assert_eq!(bmi.len(), 40);
// Rows of 9 bytes padded to 12.
assert_eq!(bits.len(), 24);
let back = decode(&bmi, &bits, Alpha::Ignore, &mut budget()).unwrap();
assert_eq!((back.width, back.height), (3, 2));
assert_eq!(&back.pixels[..12], &[255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]);
// Half-transparent black over white is mid grey; transparent is white.
assert_eq!(&back.pixels[12..16], &[127, 127, 127, 255]);
assert_eq!(&back.pixels[16..20], &[255, 255, 255, 255]);
}
#[test]
fn bgra32_round_trips_with_alpha() {
let (bmi, bits) = bgra32(&sample(), 1.0);
let back = decode(&bmi, &bits, Alpha::Premultiplied, &mut budget()).unwrap();
assert_eq!(&back.pixels[..12], &sample().pixels[..12]);
assert_eq!(back.pixels[15], 128);
assert_eq!(back.pixels[19], 0);
// Read as StretchDIBits does, alpha is ignored.
assert!(decode(&bmi, &bits, Alpha::Ignore, &mut budget()).unwrap().opaque());
}
#[test]
fn palette_bitmaps_and_damage() {
// A 1-bit 2 × 1 bitmap: black then white.
let mut bmi = header(2, 1, 1, 4);
bmi.extend_from_slice(&[0, 0, 0, 0, 255, 255, 255, 0]);
let back = decode(&bmi, &[0b0100_0000, 0, 0, 0], Alpha::Ignore, &mut budget()).unwrap();
assert_eq!(back.pixels, vec![0, 0, 0, 255, 255, 255, 255, 255]);
// Too few bits, a silly size, an unknown depth: errors, no panic.
assert!(decode(&bmi, &[0], Alpha::Ignore, &mut budget()).is_err());
assert!(decode(&header(1 << 20, 1 << 20, 24, 0), &[], Alpha::Ignore, &mut budget()).is_err());
assert!(decode(&header(1, 1, 7, 0), &[0; 4], Alpha::Ignore, &mut budget()).is_err());
assert!(decode(&[1, 2], &[], Alpha::Ignore, &mut budget()).is_err());
}
#[test]
fn large_images_are_scaled_to_fit() {
let img = image::RgbaImage::new(MAX_SIDE * 2, 4);
+82 -558
View File
@@ -1,16 +1,14 @@
//! The metafile reader: the format parsers (`emf`, `wmf`, and `pict` for QuickDraw pictures) play
//! their records on a [`Player`], a small model of the device context they draw into (objects,
//! transforms, the current position, the path bracket, the clip), which turns what they draw into
//! document objects.
//! The metafile readers. EMF (with its EMF+ records) and WMF files are read by `craft_metafile`,
//! and `picture` turns what they draw into document objects. QuickDraw pictures (`pict`) play their
//! opcodes on a [`Player`], a small model of the drawing state (pen, brush, font, the clip), which
//! turns what they draw into document objects.
//!
//! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the
//! same pen join into one path. Clips become clipping groups around what they clip. Images keep
//! their pixels (as PNG), text becomes point type in the font the file names. Records the reader
//! doesn't know are counted and skipped, with one warning.
//! their pixels (as PNG), text becomes point type in the font the file names.
mod emf;
pub(crate) mod pict;
mod wmf;
mod picture;
use std::sync::Arc;
@@ -20,7 +18,7 @@ use vectorcraft_doc::{
Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeKind,
StrokeLayer, TextObject,
};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, Vec2, shapes};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes};
use crate::dib::{self, Rgba};
use crate::{Imported, Kind};
@@ -30,24 +28,13 @@ const MAX_NODES: usize = 1 << 20;
/// Objects and clips reaching further than this from the origin (points, well inside the canvas)
/// are left out: they come from damaged or hostile coordinates.
const LIMIT: f64 = 1e6;
/// Most nested saved device contexts.
const MAX_SAVED: usize = 1024;
/// Width of a cosmetic pen (one pixel of a 96 ppi screen), points.
const HAIRLINE: f64 = 0.75;
/// Curves made for arcs and ellipses are this close to the true curve (logical units are
/// transformed after, so it is relative).
const ARC_TOLERANCE: f64 = 0.01;
/// Raster operations.
pub(crate) const SRCCOPY: u32 = 0x00CC_0020;
const PATCOPY: u32 = 0x00F0_0021;
const WHITENESS: u32 = 0x00FF_0062;
const BLACKNESS: u32 = 0x0000_0042;
const SKIPPED_ROPS: &str = "images drawn with raster operations other than a plain copy (masks, inversions) were left out";
const HATCHES: &str = "hatched brushes are filled with their colour";
const PATTERN_BRUSHES: &str = "pattern brushes are filled grey";
const EXCLUDED_CLIPS: &str = "clip areas cut out of the clip (excluded rectangles, differences) are ignored";
const BAD_IMAGE: &str = "an image that couldn't be read was left out";
const TOO_MANY_PIXELS: &str = "images past the most pixels one file may hold were left out";
const FAR_AWAY: &str = "objects far outside the picture were left out";
@@ -57,6 +44,58 @@ fn sane(r: Rect) -> bool {
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= LIMIT)
}
/// Is `path` one upright rectangle around the whole of `frame`? Writers clip to one first; it clips
/// nothing in the picture. A path of more than one figure is not one rectangle, even when its
/// figures run along the sides of a box. Nor is one figure that runs back over its own edges, so
/// that it encloses less than the whole box.
fn around(path: &BezPath, frame: Rect) -> bool {
if path.elements().len() > 6 {
return false;
}
let b = path.bounding_box();
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)];
let near = |p: Point, q: Point| (p - q).hypot() <= 1e-6 * (1.0 + b.width().max(b.height()));
// Each edge, the closing one included, runs along a side: from a corner to itself or to a
// neighbor (corners are in order around the box), never across it.
let along = |i: usize, j: usize| (i + 4 - j) % 4 != 2;
let mut seen = [false; 4];
let mut points = Vec::with_capacity(6);
let (mut first, mut last) = (None, None);
for e in path.elements() {
let (p, start) = match e {
PathEl::MoveTo(p) => (*p, true),
PathEl::LineTo(p) => (*p, false),
PathEl::ClosePath => continue,
PathEl::QuadTo(..) | PathEl::CurveTo(..) => return false,
};
let Some(i) = corners.iter().position(|c| near(*c, p)) else { return false };
if start {
if first.is_some() {
return false;
}
first = Some(i);
} else if last.is_some_and(|l| !along(l, i)) {
return false;
}
last = Some(i);
seen[i] = true;
points.push(corners[i]);
}
if let (Some(f), Some(l)) = (first, last)
&& !along(f, l)
{
return false;
}
// Every edge runs along a side, so the figure winds the same number of times around every
// point inside the box: once, when its area is the box's.
let twice_area: f64 = points.iter().zip(points.iter().cycle().skip(1)).map(|(p, q)| (*p - corners[0]).cross(*q - corners[0])).sum();
if (twice_area.abs() - 2.0 * b.area()).abs() > 1e-6 * (1.0 + 2.0 * b.area()) {
return false;
}
let b = b.inflate(0.5, 0.5);
seen.iter().all(|s| *s) && b.contains(frame.origin()) && b.contains(Point::new(frame.x1, frame.y1))
}
/// A pen: its style flags (`PS_*`), width in logical units, colour and dash entries.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct PenObj {
@@ -68,7 +107,6 @@ pub(crate) struct PenObj {
}
impl PenObj {
pub const NULL: PenObj = PenObj { style: PS_NULL, width: 0.0, color: [0; 3], entries: vec![] };
pub fn solid(color: [u8; 3]) -> Self {
Self { style: 0, width: 0.0, color, entries: vec![] }
}
@@ -77,28 +115,6 @@ impl PenObj {
pub(crate) const PS_NULL: u32 = 5;
const PS_GEOMETRIC: u32 = 0x0001_0000;
/// A brush.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum BrushObj {
Null,
Solid([u8; 3]),
Hatched([u8; 3]),
/// A bitmap pattern (written grey).
Pattern,
}
impl BrushObj {
/// From a LOGBRUSH's style and colour.
pub fn from_log(style: u32, color: [u8; 3]) -> Self {
match style {
0 => Self::Solid(color),
1 => Self::Null,
2 => Self::Hatched(color),
_ => Self::Pattern,
}
}
}
/// A font: its height in logical units (negative: the character height, positive: the cell
/// height), escapement (tenths of a degree), weight, italics and face.
#[derive(Clone, Debug, Default, PartialEq)]
@@ -110,35 +126,17 @@ pub(crate) struct FontObj {
pub face: String,
}
/// A GDI object.
#[derive(Clone, Debug)]
pub(crate) enum Obj {
Pen(PenObj),
Brush(BrushObj),
Font(FontObj),
/// Palettes, regions, colour spaces: they take a slot but don't change the drawing.
Other,
}
/// The state records change, saved and restored as a whole.
/// The drawing state.
#[derive(Clone, Debug)]
struct Dc {
pen: PenObj,
brush: BrushObj,
/// The brush's color.
brush: [u8; 3],
font: FontObj,
text_color: [u8; 3],
text_align: u32,
fill_rule: FillRule,
miter: f64,
/// Arcs run counterclockwise (the default).
arc_ccw: bool,
/// Logical → page (EMF world transform).
world: Affine,
map_mode: u32,
win_org: Vec2,
win_ext: Vec2,
vp_org: Vec2,
vp_ext: Vec2,
clips: Vec<Arc<Clip>>,
}
@@ -146,105 +144,38 @@ impl Default for Dc {
fn default() -> Self {
Self {
pen: PenObj::solid([0; 3]),
brush: BrushObj::Solid([255; 3]),
brush: [255; 3],
font: FontObj::default(),
text_color: [0; 3],
text_align: 0,
fill_rule: FillRule::EvenOdd,
miter: 10.0,
arc_ccw: true,
world: Affine::IDENTITY,
map_mode: 1,
win_org: Vec2::ZERO,
win_ext: Vec2::new(1.0, 1.0),
vp_org: Vec2::ZERO,
vp_ext: Vec2::new(1.0, 1.0),
clips: vec![],
}
}
}
/// How an arc closes.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ArcKind {
Open,
Chord,
Pie,
}
pub(crate) struct Player {
kind: Kind,
/// Device units (EMF) or logical units (WMF) → document points.
/// Picture units → document points.
dev_to_doc: Affine,
/// Millimetres per device pixel (EMF's fixed mapping modes).
mm_per_px: f64,
dc: Dc,
saved: Vec<Dc>,
objects: Vec<Option<Obj>>,
/// The lowest object slot that may be free (WMF numbering).
free_hint: usize,
/// The path being recorded (document space), whether a figure is open in it and where that
/// figure started (logical).
path: Option<BezPath>,
figure: bool,
figure_start: Point,
/// The artboard (document space): clips holding all of it clip nothing worth keeping.
frame: Rect,
/// The current position (logical).
pos: Point,
/// Lines drawn one after another outside a path bracket, not drawn yet.
/// Lines drawn one after another, not drawn yet.
pending: BezPath,
out: Drawn,
doc: Document,
warnings: Vec<String>,
skipped: usize,
next_clip: u32,
/// Pixels the file's bitmaps may still decode to ([`dib::MAX_FILE_PIXELS`]).
pub pixels_left: u64,
/// The file holds EMF+ records (which aren't read).
pub emf_plus: bool,
}
fn rgb(c: [u8; 3]) -> Paint {
Paint::solid(Color::rgb8(c[0], c[1], c[2]))
}
/// The arc of the ellipse in `r` from the ray through `start` to the ray through `end`.
pub(crate) fn arc_path(r: Rect, start: Point, end: Point, ccw: bool, kind: ArcKind) -> BezPath {
let r = r.abs();
let c = r.center();
let radii = Vec2::new(r.width() / 2.0, r.height() / 2.0);
let mut bp = BezPath::new();
if radii.x <= 0.0 || radii.y <= 0.0 {
return bp;
}
let angle = |p: Point| ((p.y - c.y) / radii.y).atan2((p.x - c.x) / radii.x);
let (a0, a1) = (angle(start), angle(end));
let tau = std::f64::consts::TAU;
// Counterclockwise on a y-down device is towards smaller angles.
let sweep = if ccw {
let s = (a0 - a1).rem_euclid(tau);
-(if s == 0.0 { tau } else { s })
} else {
let s = (a1 - a0).rem_euclid(tau);
if s == 0.0 { tau } else { s }
};
let arc = kurbo::Arc { center: c, radii, start_angle: a0, sweep_angle: sweep, x_rotation: 0.0 };
let tol = ARC_TOLERANCE * radii.x.max(radii.y).max(1e-9);
if kind == ArcKind::Pie {
bp.move_to(c);
let first = c + Vec2::new(radii.x * a0.cos(), radii.y * a0.sin());
bp.line_to(first);
arc.append_iter(tol).for_each(|el| bp.push(el));
} else {
kurbo::Shape::path_elements(&arc, tol).for_each(|el| bp.push(el));
}
if kind != ArcKind::Open {
bp.close_path();
}
bp
}
/// A rectangle with elliptical corners `rx` × `ry`.
pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath {
let r = r.abs();
@@ -261,7 +192,7 @@ pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath {
}
impl Player {
fn new(kind: Kind, dev_to_doc: Affine, mm_per_px: f64, artboard: Rect) -> Self {
fn new(kind: Kind, dev_to_doc: Affine, artboard: Rect) -> Self {
let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 };
let (w, h) = (side(artboard.width()), side(artboard.height()));
let mut doc = Document::new(w, h);
@@ -269,24 +200,14 @@ impl Player {
Self {
kind,
dev_to_doc,
mm_per_px,
dc: Dc::default(),
saved: vec![],
objects: vec![],
free_hint: 0,
path: None,
figure: false,
figure_start: Point::ZERO,
frame: artboard,
pos: Point::ZERO,
pending: BezPath::new(),
out: vec![],
doc,
warnings: vec![],
skipped: 0,
next_clip: 0,
pixels_left: dib::MAX_FILE_PIXELS,
emf_plus: false,
}
}
@@ -296,188 +217,19 @@ impl Player {
}
}
/// A record of a kind the reader doesn't know.
pub fn skip(&mut self) {
self.skipped += 1;
}
// ---------- mapping ----------
/// Logical → document.
/// Picture units → document.
fn xf(&self) -> Affine {
if self.kind == Kind::Wmf {
return self.dev_to_doc;
}
let d = &self.dc;
let page_to_dev = match d.map_mode {
// Fixed modes: millimetres a unit, y up.
2..=6 => {
let mm = [0.1, 0.01, 0.254, 0.0254, 25.4 / 1440.0][(d.map_mode - 2) as usize];
let s = mm / self.mm_per_px.max(1e-12);
Affine::translate(d.vp_org) * Affine::scale_non_uniform(s, -s) * Affine::translate(-d.win_org)
}
7 | 8 => {
let ratio = |v: f64, w: f64| if w.abs() > 1e-12 && v.is_finite() { v / w } else { 1.0 };
let (mut sx, mut sy) = (ratio(d.vp_ext.x, d.win_ext.x), ratio(d.vp_ext.y, d.win_ext.y));
if d.map_mode == 7 {
// Isotropic: the same scale both ways, the smaller one.
let s = sx.abs().min(sy.abs());
(sx, sy) = (s.copysign(sx), s.copysign(sy));
}
Affine::translate(d.vp_org) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-d.win_org)
}
_ => Affine::translate(d.vp_org - d.win_org),
};
self.dev_to_doc * page_to_dev * d.world
self.dev_to_doc
}
/// How much logical lengths grow in the document.
/// How much picture lengths grow in the document.
fn scale(&self) -> f64 {
let s = self.xf().determinant().abs().sqrt();
if s.is_finite() { s } else { 0.0 }
}
pub fn set_map_mode(&mut self, m: u32) {
self.dc.map_mode = m;
}
pub fn set_window_org(&mut self, x: f64, y: f64) {
self.dc.win_org = Vec2::new(x, y);
}
pub fn set_window_ext(&mut self, x: f64, y: f64) {
self.dc.win_ext = Vec2::new(x, y);
}
pub fn set_viewport_org(&mut self, x: f64, y: f64) {
self.dc.vp_org = Vec2::new(x, y);
}
pub fn set_viewport_ext(&mut self, x: f64, y: f64) {
self.dc.vp_ext = Vec2::new(x, y);
}
pub fn scale_ext(&mut self, window: bool, x: (f64, f64), y: (f64, f64)) {
let e = if window { &mut self.dc.win_ext } else { &mut self.dc.vp_ext };
if x.1 != 0.0 && y.1 != 0.0 {
*e = Vec2::new(e.x * x.0 / x.1, e.y * y.0 / y.1);
}
}
/// `SetWorldTransform` / `ModifyWorldTransform` (`mode`: 1 identity, 2 left, 3 right, 4 set).
pub fn world(&mut self, x: Affine, mode: u32) {
if !x.as_coeffs().iter().all(|v| v.is_finite()) {
return;
}
self.dc.world = match mode {
1 => Affine::IDENTITY,
2 => self.dc.world * x,
3 => x * self.dc.world,
_ => x,
};
}
// ---------- state ----------
pub fn set_fill_mode(&mut self, alternate: bool) {
self.dc.fill_rule = if alternate { FillRule::EvenOdd } else { FillRule::NonZero };
}
pub fn set_miter(&mut self, m: f64) {
if m.is_finite() && m >= 1.0 {
self.dc.miter = m;
}
}
pub fn set_arc_ccw(&mut self, ccw: bool) {
self.dc.arc_ccw = ccw;
}
pub fn set_text_color(&mut self, c: [u8; 3]) {
self.dc.text_color = c;
}
pub fn set_text_align(&mut self, a: u32) {
self.dc.text_align = a;
}
pub fn save(&mut self) {
if self.saved.len() < MAX_SAVED {
self.saved.push(self.dc.clone());
}
}
/// `RestoreDC(n)`: a negative `n` counts back from the latest save, a positive one is a save's
/// number.
pub fn restore(&mut self, n: i32) {
let len = self.saved.len();
let keep = if n < 0 { len.checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1).filter(|k| *k < len) };
if let Some(k) = keep {
self.saved.truncate(k + 1);
if let Some(dc) = self.saved.pop() {
self.dc = dc;
}
}
}
// ---------- objects ----------
/// Put `obj` in slot `index` (EMF numbers its objects).
pub fn create_at(&mut self, index: u32, obj: Obj) {
let i = index as usize;
if i == 0 || i > u16::MAX as usize {
return;
}
if self.objects.len() <= i {
self.objects.resize(i + 1, None);
}
if let Some(s) = self.objects.get_mut(i) {
*s = Some(obj);
}
}
/// Put `obj` in the lowest free slot (WMF).
pub fn create(&mut self, obj: Obj) {
let start = self.free_hint.min(self.objects.len());
let i = self.objects.iter().skip(start).position(Option::is_none).map_or(self.objects.len(), |p| p + start);
if i > u16::MAX as usize {
// The table is full past the hint: the next creation looks from the end, not again
// through every slot.
self.free_hint = i;
return;
}
if i == self.objects.len() {
self.objects.push(None);
}
if let Some(s) = self.objects.get_mut(i) {
*s = Some(obj);
}
self.free_hint = i + 1;
}
pub fn delete(&mut self, index: u32) {
if let Some(s) = self.objects.get_mut(index as usize) {
*s = None;
self.free_hint = self.free_hint.min(index as usize);
}
}
/// Select object `index`, or a stock object (EMF: the high bit set).
pub fn select(&mut self, index: u32) {
if self.kind == Kind::Emf && index & 0x8000_0000 != 0 {
match index & 0x7fff_ffff {
0 | 18 => self.dc.brush = BrushObj::Solid([255; 3]),
1 => self.dc.brush = BrushObj::Solid([0xc0; 3]),
2 => self.dc.brush = BrushObj::Solid([0x80; 3]),
3 => self.dc.brush = BrushObj::Solid([0x40; 3]),
4 => self.dc.brush = BrushObj::Solid([0; 3]),
5 => self.dc.brush = BrushObj::Null,
6 => self.dc.pen = PenObj::solid([255; 3]),
7 | 19 => self.dc.pen = PenObj::solid([0; 3]),
8 => self.dc.pen = PenObj::NULL,
10..=17 => self.dc.font = FontObj::default(),
_ => {}
}
return;
}
match self.objects.get(index as usize).cloned().flatten() {
Some(Obj::Pen(p)) => self.dc.pen = p,
Some(Obj::Brush(b)) => self.dc.brush = b,
Some(Obj::Font(f)) => self.dc.font = f,
_ => {}
}
}
// ---------- output ----------
fn push(&mut self, mut node: Node) {
@@ -491,19 +243,8 @@ impl Player {
self.out.push((self.dc.clips.clone(), node));
}
fn fill_paint(&mut self) -> Option<Paint> {
match self.dc.brush.clone() {
BrushObj::Null => None,
BrushObj::Solid(c) => Some(rgb(c)),
BrushObj::Hatched(c) => {
self.warn(HATCHES);
Some(rgb(c))
}
BrushObj::Pattern => {
self.warn(PATTERN_BRUSHES);
Some(rgb([0x80; 3]))
}
}
fn fill_paint(&self) -> Paint {
rgb(self.dc.brush)
}
fn stroke_layer(&self) -> Option<StrokeLayer> {
@@ -549,8 +290,8 @@ impl Player {
return;
}
let mut items = vec![];
if fill && let Some(p) = self.fill_paint() {
items.push(AppearanceItem::Fill(FillLayer::new(p)));
if fill {
items.push(AppearanceItem::Fill(FillLayer::new(self.fill_paint())));
}
if stroke && let Some(st) = self.stroke_layer() {
items.push(AppearanceItem::Stroke(st));
@@ -573,124 +314,7 @@ impl Player {
}
}
/// A figure in logical units: added to the path being recorded, else drawn (filled when it is
/// an area).
pub fn figure(&mut self, mut bp: BezPath, area: bool) {
bp.apply_affine(self.xf());
match &mut self.path {
Some(path) => {
path.extend(bp);
self.figure = false;
}
None => self.draw(bp, area, true),
}
}
/// Polygon / Polyline (and Bézier ones): `pts` in logical units.
pub fn poly(&mut self, pts: &[Point], closed: bool, bezier: bool) {
let Some((first, rest)) = pts.split_first() else { return };
let mut bp = BezPath::new();
bp.move_to(*first);
if bezier {
for c in rest.as_chunks::<3>().0 {
bp.curve_to(c[0], c[1], c[2]);
}
} else {
rest.iter().for_each(|p| bp.line_to(*p));
}
if closed {
bp.close_path();
}
self.figure(bp, closed);
}
/// Several polygons (one area) or polylines.
pub fn poly_poly(&mut self, polys: &[Vec<Point>], closed: bool) {
let mut bp = BezPath::new();
for p in polys {
let Some((first, rest)) = p.split_first() else { continue };
bp.move_to(*first);
rest.iter().for_each(|q| bp.line_to(*q));
if closed {
bp.close_path();
}
}
self.figure(bp, closed);
}
pub fn move_to(&mut self, p: Point) {
self.pos = p;
self.figure = false;
}
/// LineTo / PolylineTo / PolyBezierTo: from the current position through `pts` (logical).
pub fn poly_to(&mut self, pts: &[Point], bezier: bool) {
let Some(last) = pts.last().copied() else { return };
let xf = self.xf();
let start = xf * self.pos;
let target = match &mut self.path {
Some(path) => {
if !self.figure {
path.move_to(start);
self.figure = true;
self.figure_start = self.pos;
}
path
}
None => {
if self.pending.elements().last().and_then(|e| e.end_point()) != Some(start) {
self.pending.move_to(start);
}
&mut self.pending
}
};
if bezier {
for c in pts.as_chunks::<3>().0 {
target.curve_to(xf * c[0], xf * c[1], xf * c[2]);
}
} else {
pts.iter().for_each(|p| target.line_to(xf * *p));
}
self.pos = last;
}
pub fn arc(&mut self, r: Rect, start: Point, end: Point, kind: ArcKind) {
let bp = arc_path(r, start, end, self.dc.arc_ccw, kind);
self.figure(bp, kind != ArcKind::Open);
}
// ---------- paths and clips ----------
pub fn begin_path(&mut self) {
self.path = Some(BezPath::new());
self.figure = false;
}
pub fn end_path(&mut self) {
// The path stays until it is filled, stroked or made the clip.
}
pub fn close_figure(&mut self) {
if let Some(p) = &mut self.path
&& self.figure
{
p.close_path();
self.figure = false;
self.pos = self.figure_start;
}
}
pub fn abort_path(&mut self) {
self.path = None;
}
/// FillPath / StrokePath / StrokeAndFillPath.
pub fn paint_path(&mut self, fill: bool, stroke: bool) {
if let Some(mut bp) = self.path.take() {
// Filling closes the open figure.
if fill && self.figure {
bp.close_path();
}
self.draw(bp, fill, stroke);
}
}
// ---------- clips ----------
fn push_clip(&mut self, path: BezPath, rule: FillRule, replace: bool) {
if replace {
@@ -699,10 +323,7 @@ impl Player {
if !sane(path.bounding_box()) {
return self.warn(FAR_AWAY);
}
// A rectangle around the whole picture (what writers clip to first) clips nothing in it.
let lines = path.elements().iter().all(|e| !matches!(e, PathEl::QuadTo(..) | PathEl::CurveTo(..)));
let around = path.bounding_box().inflate(0.5, 0.5);
if lines && path.elements().len() <= 6 && around.contains(self.frame.origin()) && around.contains(Point::new(self.frame.x1, self.frame.y1)) {
if around(&path, self.frame) {
return;
}
if self.dc.clips.len() >= MAX_NEST {
@@ -712,69 +333,10 @@ impl Player {
self.dc.clips.push(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) }));
}
/// SelectClipPath (`mode`: 1 and, 5 copy; the others cut out, which isn't read).
pub fn clip_path(&mut self, mode: u32) {
let Some(bp) = self.path.take() else { return };
match mode {
1 => self.push_clip(bp, self.dc.fill_rule, false),
5 => self.push_clip(bp, self.dc.fill_rule, true),
_ => self.warn(EXCLUDED_CLIPS),
}
}
/// IntersectClipRect (logical units).
pub fn clip_rect(&mut self, r: Rect) {
let mut bp = shapes::rectangle(r.abs()).to_bezpath();
bp.apply_affine(self.xf());
self.push_clip(bp, FillRule::NonZero, false);
}
/// A clip region of `rects` in device units (`mode` as [`Self::clip_path`]); none with mode
/// copy removes the clip.
pub fn clip_region(&mut self, rects: &[Rect], mode: u32) {
if rects.is_empty() {
if mode == 5 {
self.dc.clips.clear();
}
return;
}
let mut bp = BezPath::new();
for r in rects {
bp.extend(shapes::rectangle(r.abs()).to_bezpath());
}
bp.apply_affine(self.dev_to_doc);
match mode {
1 => self.push_clip(bp, FillRule::NonZero, false),
5 => self.push_clip(bp, FillRule::NonZero, true),
_ => self.warn(EXCLUDED_CLIPS),
}
}
pub fn exclude_clip(&mut self) {
self.warn(EXCLUDED_CLIPS);
}
// ---------- blits, images and text ----------
/// A raster operation without a source over `dest` (logical): the brush, white or black.
pub fn pattern_blit(&mut self, dest: Rect, rop: u32) {
let brush = match rop {
PATCOPY => self.dc.brush.clone(),
WHITENESS => BrushObj::Solid([255; 3]),
BLACKNESS => BrushObj::Solid([0; 3]),
_ => return self.skip(),
};
let pen = std::mem::replace(&mut self.dc.pen, PenObj::NULL);
let outer = std::mem::replace(&mut self.dc.brush, brush);
let mut bp = shapes::rectangle(dest.abs()).to_bezpath();
bp.apply_affine(self.xf());
self.draw(bp, true, false);
self.dc.pen = pen;
self.dc.brush = outer;
}
// ---------- images and text ----------
/// An image whose source rectangle `src` (pixels, from the top-left) is drawn into `dest`
/// (logical: origin and signed size) with raster operation `rop`, at `opacity`.
/// (picture units: origin and signed size) with raster operation `rop`, at `opacity`.
pub fn image(&mut self, img: Result<Rgba, String>, src: Rect, dest: Rect, rop: u32, opacity: f64) {
if rop != SRCCOPY {
self.warn(SKIPPED_ROPS);
@@ -793,8 +355,8 @@ impl Player {
self.image_xf(img, Affine::translate((dest.x0, dest.y0)) * Affine::scale_non_uniform(dest.width() / w, dest.height() / h), opacity);
}
/// An image placed by `xf` (its pixels, from the top-left, → logical), at `opacity`. An image
/// that `xf` flattens or sends past finite numbers is left out, and adds nothing to the
/// An image placed by `xf` (its pixels, from the top-left, → picture units), at `opacity`. An
/// image that `xf` flattens or sends past finite numbers is left out, and adds nothing to the
/// document's images.
pub(crate) fn image_xf(&mut self, img: Rgba, xf: Affine, opacity: f64) {
if img.width == 0 || img.height == 0 {
@@ -814,14 +376,13 @@ impl Player {
self.push(n);
}
/// Text at `at` (logical; the current position with TA_UPDATECP) in the current font.
/// Text at `at` (picture units) in the current font.
pub fn text(&mut self, at: Point, s: &str) {
let s: String = s.chars().filter(|c| *c != '\0').collect();
if s.trim().is_empty() {
return;
}
let align = self.dc.text_align;
let at = if align & 1 != 0 { self.pos } else { at };
let f = self.dc.font.clone();
let k = self.scale();
// A negative height is the em; a positive one the cell (the em and the internal leading).
@@ -863,18 +424,7 @@ impl Player {
/// The document: what was drawn on one layer, clipped art in clipping groups.
fn finish(mut self) -> Imported {
self.flush();
if self.skipped > 0 {
let n = self.skipped;
self.warnings.push(format!(
"{n} record{} of kinds VectorCraft doesn't read {} skipped",
if n == 1 { "" } else { "s" },
if n == 1 { "was" } else { "were" }
));
}
let out = std::mem::take(&mut self.out);
if out.is_empty() && self.emf_plus {
self.warnings.push("the picture is drawn with EMF+ records, which aren't read yet: nothing was imported".into());
}
let children = nest(&mut self.doc, out);
let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0));
if let Some(c) = layer.children_mut() {
@@ -904,33 +454,7 @@ fn crop(img: Rgba, src: Rect) -> Rgba {
Rgba { width: x1 - x0, height: y1 - y0, pixels }
}
/// Read a metafile.
/// Read an EMF or WMF file.
pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
match crate::sniff(bytes) {
Some(Kind::Emf) => emf::play(bytes),
Some(Kind::Wmf) => wmf::play(bytes),
None => Err("not an EMF or WMF file".into()),
}
}
#[cfg(test)]
mod table_tests {
use super::*;
/// Once the WMF table is full, a rejected creation leaves the hint at its end, so the next
/// ones don't scan every slot again; a freed slot is still found.
#[test]
fn a_full_object_table_is_not_rescanned() {
let mut p = Player::new(Kind::Wmf, Affine::IDENTITY, 1.0, Rect::new(0.0, 0.0, 10.0, 10.0));
for _ in 0..=u16::MAX as usize + 1 {
p.create(Obj::Other);
}
p.delete(5);
p.create(Obj::Other);
p.create(Obj::Other);
assert!(p.free_hint > u16::MAX as usize);
p.delete(7);
p.create(Obj::Other);
assert!(p.objects[7].is_some());
}
picture::import(bytes)
}
-392
View File
@@ -1,392 +0,0 @@
//! EMF records (MS-EMF) played on a [`Player`]: the header gives the frame (the artboard) and the
//! reference device (device pixels → millimetres), then every record in turn until EMR_EOF.
use vectorcraft_geom::{Affine, Point, Rect};
use super::{ArcKind, BrushObj, FontObj, Obj, PenObj, Player};
use crate::bytes::{Reader, slice};
use crate::dib::{self, Alpha};
use crate::{Imported, Kind};
/// Points per millimetre.
const PT_PER_MM: f64 = 72.0 / 25.4;
/// Most points one record may give (a hostile count can't make a huge allocation).
const MAX_POINTS: usize = 1 << 22;
/// Records that change nothing VectorCraft keeps (background mode and colour, raster modes,
/// palettes, colour management, comments…).
const IGNORED: &[u32] =
&[1, 13, 15, 16, 18, 20, 21, 23, 25, 28, 48, 50, 51, 52, 65, 66, 70, 98, 100, 101, 104, 110, 111, 112, 113, 115, 119, 120, 121];
fn rect(r: &mut Reader) -> Option<Rect> {
Some(Rect::new(f64::from(r.i32()?), f64::from(r.i32()?), f64::from(r.i32()?), f64::from(r.i32()?)))
}
fn point32(r: &mut Reader) -> Option<Point> {
Some(Point::new(f64::from(r.i32()?), f64::from(r.i32()?)))
}
fn point16(r: &mut Reader) -> Option<Point> {
Some(Point::new(f64::from(r.i16()?), f64::from(r.i16()?)))
}
fn color(r: &mut Reader) -> Option<[u8; 3]> {
let [red, g, b, _] = r.u32()?.to_le_bytes();
Some([red, g, b])
}
fn xform(r: &mut Reader) -> Option<Affine> {
let mut v = [0.0; 6];
for x in &mut v {
*x = f64::from(r.f32()?);
}
Some(Affine::new(v))
}
/// `n` points (32-bit or 16-bit), `None` when the record is shorter.
fn points(r: &mut Reader, n: u32, wide: bool) -> Option<Vec<Point>> {
let n = n as usize;
if n > MAX_POINTS || r.rest().len() < n * if wide { 8 } else { 4 } {
return None;
}
(0..n).map(|_| if wide { point32(r) } else { point16(r) }).collect()
}
/// The polygons of a PolyPolygon / PolyPolyline record.
fn polys(r: &mut Reader, wide: bool) -> Option<Vec<Vec<Point>>> {
r.skip(16)?;
let n = r.u32()? as usize;
let total = r.u32()?;
if n > MAX_POINTS || r.rest().len() < n * 4 {
return None;
}
let counts: Vec<u32> = (0..n).map(|_| r.u32()).collect::<Option<_>>()?;
let mut all = points(r, total, wide)?.into_iter();
Some(counts.iter().map(|c| all.by_ref().take(*c as usize).collect()).collect())
}
/// A LOGFONTW → the font.
fn font(r: &mut Reader) -> Option<FontObj> {
let height = f64::from(r.i32()?);
r.skip(4)?;
let escapement = f64::from(r.i32()?);
r.skip(4)?;
let weight = r.i32()?;
let italic = r.bytes(1)?.first().is_some_and(|b| *b != 0);
r.skip(7)?;
let units: Vec<u16> = (0..32).map_while(|_| r.u16()).take_while(|c| *c != 0).collect();
Some(FontObj { height, escapement, weight, italic, face: String::from_utf16_lossy(&units) })
}
/// The bitmap of an image record: its BITMAPINFO and bits at the offsets the record gives.
fn bitmap(rec: &[u8], off_bmi: u32, cb_bmi: u32, off_bits: u32, cb_bits: u32, alpha: Alpha, left: &mut u64) -> Result<dib::Rgba, String> {
let bmi = slice(rec, off_bmi, cb_bmi).ok_or("damaged")?;
let bits = slice(rec, off_bits, cb_bits).ok_or("damaged")?;
dib::decode(bmi, bits, alpha, left)
}
/// The rows a DIB's source rectangle counts from the bottom in (StretchDIBits on a bottom-up DIB).
fn bottom_up(rec: &[u8], off_bmi: u32) -> bool {
let at = off_bmi as usize;
let size = rec.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
let height = rec.get(at + 8..at + 12).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes);
size.is_some_and(|s| s >= 40) && height.is_some_and(|h| h > 0)
}
/// The source rectangle `(x, y, w, h)` of an image of `img`'s height, counted from the top.
fn source(x: i32, y: i32, w: i32, h: i32, img: &Result<dib::Rgba, String>, from_bottom: bool) -> Rect {
let ih = img.as_ref().map_or(0.0, |i| f64::from(i.height));
let (x, y, w, h) = (f64::from(x), f64::from(y), f64::from(w), f64::from(h));
let top = if from_bottom { ih - y - h } else { y };
Rect::new(x, top, x + w, top + h)
}
/// The size and placement of the picture: (device → document, millimetres a pixel, the artboard).
fn frame(bytes: &[u8]) -> Option<(Affine, f64, Rect)> {
let mut r = Reader::new(bytes);
r.skip(4)?;
let header_size = r.u32()?;
let bounds = rect(&mut r)?;
let frame = rect(&mut r)?;
// Signature, version, bytes, records, handles, description and palette size.
r.skip(32)?;
let device = (f64::from(r.i32()?), f64::from(r.i32()?));
let mm = (f64::from(r.i32()?), f64::from(r.i32()?));
// The device in micrometres (more precise), when the header has it.
let micro = if header_size >= 108 {
r.skip(12)?;
Some((f64::from(r.u32()?), f64::from(r.u32()?)))
} else {
None
};
let ok = |v: f64| v.is_finite() && v > 0.0;
let mm_per_px = match micro {
Some((mx, _)) if ok(mx) && ok(device.0) => mx / 1000.0 / device.0,
_ if ok(mm.0) && ok(device.0) => mm.0 / device.0,
_ => 25.4 / 96.0,
};
let mm_per_px = if mm_per_px.is_finite() && mm_per_px > 1e-9 { mm_per_px } else { 25.4 / 96.0 };
let k = mm_per_px * PT_PER_MM;
// The frame (0.01 mm) in device pixels; an empty frame falls back to the bounds.
let f = frame.abs();
let (origin, size) = if f.width() > 0.0 && f.height() > 0.0 {
(Point::new(f.x0 / 100.0 / mm_per_px, f.y0 / 100.0 / mm_per_px), (f.width() / 100.0 * PT_PER_MM, f.height() / 100.0 * PT_PER_MM))
} else {
let b = bounds.abs();
(b.origin(), ((b.width() + 1.0) * k, (b.height() + 1.0) * k))
};
let dev_to_doc = Affine::scale(k) * Affine::translate(-origin.to_vec2());
let side = |v: f64| if v.is_finite() { v.clamp(1.0, 1e6) } else { 1.0 };
Some((dev_to_doc, mm_per_px, Rect::new(0.0, 0.0, side(size.0), side(size.1))))
}
pub(super) fn play(bytes: &[u8]) -> Result<Imported, String> {
let (dev_to_doc, mm_per_px, artboard) = frame(bytes).ok_or("the EMF header is damaged")?;
let mut p = Player::new(Kind::Emf, dev_to_doc, mm_per_px, artboard);
let mut at = 0usize;
let mut ended = false;
while let Some(head) = bytes.get(at..at + 8) {
let kind = u32::from_le_bytes([head[0], head[1], head[2], head[3]]);
let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
let Some(rec) = bytes.get(at..at.saturating_add(size)).filter(|_| size >= 8) else { break };
if kind == 14 {
ended = true;
break;
}
if !matches!(kind, 27 | 54 | 5 | 6 | 88 | 89) {
p.flush();
}
if record(&mut p, kind, rec).is_none() {
p.skip();
}
at += size;
}
if !ended {
p.warn("the file ends early: what it held was imported");
}
Ok(p.finish())
}
/// PolyBezier, Polygon, Polyline, PolyBezierTo, PolylineTo and their 16-bit forms.
fn rec_poly(p: &mut Player, kind: u32, r: &mut Reader) -> Option<()> {
let wide = kind < 85;
r.skip(16)?;
let n = r.u32()?;
let pts = points(r, n, wide)?;
match if wide { kind } else { kind - 83 } {
2 => p.poly(&pts, false, true),
3 => p.poly(&pts, true, false),
4 => p.poly(&pts, false, false),
5 => p.poly_to(&pts, true),
_ => p.poly_to(&pts, false),
}
Some(())
}
/// CreatePen (38).
fn rec_create_pen(p: &mut Player, r: &mut Reader) -> Option<()> {
let ih = r.u32()?;
let style = r.u32()?;
let width = f64::from(r.i32()?);
r.skip(4)?;
p.create_at(ih, Obj::Pen(PenObj { style, width, color: color(r)?, entries: vec![] }));
Some(())
}
/// ExtCreatePen (95).
fn rec_ext_create_pen(p: &mut Player, r: &mut Reader) -> Option<()> {
let ih = r.u32()?;
r.skip(16)?;
let style = r.u32()?;
let width = f64::from(r.u32()?);
let brush = r.u32()?;
let c = color(r)?;
r.skip(4)?;
let n = (r.u32()? as usize).min(64);
let entries: Vec<f64> = (0..n).map_while(|_| r.u32()).map(f64::from).collect();
// A pen painted with the null brush draws nothing.
let style = if brush == 1 { super::PS_NULL } else { style };
p.create_at(ih, Obj::Pen(PenObj { style, width, color: c, entries }));
Some(())
}
/// GdiComment (70): EMF+ records ride in comments starting "EMF+".
fn rec_comment(p: &mut Player, r: &mut Reader) -> Option<()> {
r.skip(4)?;
p.emf_plus |= r.u32()? == 0x2B46_4D45;
Some(())
}
/// ExtSelectClipRgn (75).
fn rec_clip_region(p: &mut Player, r: &mut Reader) -> Option<()> {
let cb = r.u32()?;
let mode = r.u32()?;
let data = r.bytes(cb as usize)?;
let mut d = Reader::new(data);
let rects = if cb >= 32 {
d.skip(8)?;
let n = d.u32()? as usize;
d.skip(20)?;
if n > MAX_POINTS || d.rest().len() < n * 16 {
return None;
}
(0..n).map(|_| rect(&mut d)).collect::<Option<Vec<_>>>()?
} else {
vec![]
};
p.clip_region(&rects, mode);
Some(())
}
/// The rectangle at `(x, y)` of size `(w, h)`.
fn at_size(x: i32, y: i32, w: i32, h: i32) -> Rect {
Rect::new(f64::from(x), f64::from(y), f64::from(x) + f64::from(w), f64::from(y) + f64::from(h))
}
/// BitBlt (76) and StretchBlt (77).
fn rec_blt(p: &mut Player, kind: u32, rec: &[u8], r: &mut Reader) -> Option<()> {
r.skip(16)?;
let dest = (r.i32()?, r.i32()?, r.i32()?, r.i32()?);
let rop = r.u32()?;
let (xs, ys) = (r.i32()?, r.i32()?);
r.skip(24 + 4 + 4)?;
let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?);
let (ws, hs) = if kind == 77 { (r.i32()?, r.i32()?) } else { (dest.2, dest.3) };
let d = at_size(dest.0, dest.1, dest.2, dest.3);
if cb_bmi == 0 {
p.pattern_blit(d, rop);
} else {
let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, Alpha::Ignore, &mut p.pixels_left);
let src = source(xs, ys, ws, hs, &img, false);
p.image(img, src, d, rop, 1.0);
}
Some(())
}
/// StretchDIBits (81).
fn rec_stretch_dibits(p: &mut Player, rec: &[u8], r: &mut Reader) -> Option<()> {
r.skip(16)?;
let (xd, yd, xs, ys, ws, hs) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?, r.i32()?, r.i32()?);
let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?);
r.skip(4)?;
let rop = r.u32()?;
let (wd, hd) = (r.i32()?, r.i32()?);
let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, Alpha::Ignore, &mut p.pixels_left);
let src = source(xs, ys, ws, hs, &img, bottom_up(rec, off_bmi));
p.image(img, src, at_size(xd, yd, wd, hd), rop, 1.0);
Some(())
}
/// AlphaBlend (114).
fn rec_alpha_blend(p: &mut Player, rec: &[u8], r: &mut Reader) -> Option<()> {
r.skip(16)?;
let (xd, yd, wd, hd) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?);
let blend = r.bytes(4)?;
let (constant, per_pixel) = (blend.get(2).copied().unwrap_or(255), blend.get(3).is_some_and(|f| *f & 1 != 0));
let (xs, ys) = (r.i32()?, r.i32()?);
r.skip(24 + 4 + 4)?;
let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?);
let (ws, hs) = (r.i32()?, r.i32()?);
let alpha = if per_pixel { Alpha::Premultiplied } else { Alpha::Ignore };
let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, alpha, &mut p.pixels_left);
let src = source(xs, ys, ws, hs, &img, false);
p.image(img, src, at_size(xd, yd, wd, hd), crate::import::SRCCOPY, f64::from(constant) / 255.0);
Some(())
}
/// ExtTextOutA (83) and ExtTextOutW (84).
fn rec_text(p: &mut Player, kind: u32, rec: &[u8], r: &mut Reader) -> Option<()> {
r.skip(16 + 4 + 8)?;
let at = point32(r)?;
let n = r.u32()? as usize;
let off = r.u32()?;
let s = if kind == 84 {
let raw = slice(rec, off, u32::try_from(n.checked_mul(2)?).ok()?)?;
String::from_utf16_lossy(&raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect::<Vec<_>>())
} else {
slice(rec, off, u32::try_from(n).ok()?)?.iter().map(|b| char::from(*b)).collect()
};
p.text(at, &s);
Some(())
}
/// Play one record (`rec`: all of it, with its type and size). `None`: unknown or damaged.
fn record(p: &mut Player, kind: u32, rec: &[u8]) -> Option<()> {
let mut r = Reader::new(rec.get(8..)?);
match kind {
2..=6 | 85..=89 => rec_poly(p, kind, &mut r)?,
7 | 90 => p.poly_poly(&polys(&mut r, kind == 7)?, false),
8 | 91 => p.poly_poly(&polys(&mut r, kind == 8)?, true),
9 => p.set_window_ext(f64::from(r.i32()?), f64::from(r.i32()?)),
10 => p.set_window_org(f64::from(r.i32()?), f64::from(r.i32()?)),
11 => p.set_viewport_ext(f64::from(r.i32()?), f64::from(r.i32()?)),
12 => p.set_viewport_org(f64::from(r.i32()?), f64::from(r.i32()?)),
17 => p.set_map_mode(r.u32()?),
19 => p.set_fill_mode(r.u32()? == 1),
22 => p.set_text_align(r.u32()?),
24 => p.set_text_color(color(&mut r)?),
27 => p.move_to(point32(&mut r)?),
29 => p.exclude_clip(),
30 => p.clip_rect(rect(&mut r)?),
31 | 32 => {
let (xn, xd, yn, yd) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?);
p.scale_ext(kind == 32, (f64::from(xn), f64::from(xd)), (f64::from(yn), f64::from(yd)));
}
33 => p.save(),
34 => p.restore(r.i32()?),
35 => p.world(xform(&mut r)?, 4),
36 => {
let x = xform(&mut r)?;
p.world(x, r.u32()?);
}
37 => p.select(r.u32()?),
38 => rec_create_pen(p, &mut r)?,
39 => {
let ih = r.u32()?;
let style = r.u32()?;
p.create_at(ih, Obj::Brush(BrushObj::from_log(style, color(&mut r)?)));
}
40 => p.delete(r.u32()?),
42 => p.figure(vectorcraft_geom::shapes::ellipse(rect(&mut r)?.abs()).to_bezpath(), true),
43 => p.figure(vectorcraft_geom::shapes::rectangle(rect(&mut r)?.abs()).to_bezpath(), true),
44 => {
let b = rect(&mut r)?;
let (cx, cy) = (f64::from(r.i32()?), f64::from(r.i32()?));
p.figure(super::round_rect(b, cx, cy), true);
}
45..=47 => {
let b = rect(&mut r)?;
let (s, e) = (point32(&mut r)?, point32(&mut r)?);
p.arc(b, s, e, [ArcKind::Open, ArcKind::Chord, ArcKind::Pie][(kind - 45) as usize]);
}
49 | 99 | 122 => p.create_at(r.u32()?, Obj::Other),
54 => {
let pt = point32(&mut r)?;
p.poly_to(&[pt], false);
}
57 => p.set_arc_ccw(r.u32()? != 2),
58 => p.set_miter(f64::from(r.u32()?)),
59 => p.begin_path(),
60 => p.end_path(),
61 => p.close_figure(),
62 => p.paint_path(true, false),
63 => p.paint_path(true, true),
64 => p.paint_path(false, true),
67 => p.clip_path(r.u32()?),
68 => p.abort_path(),
70 => rec_comment(p, &mut r)?,
75 => rec_clip_region(p, &mut r)?,
76 | 77 => rec_blt(p, kind, rec, &mut r)?,
81 => rec_stretch_dibits(p, rec, &mut r)?,
82 => {
let ih = r.u32()?;
p.create_at(ih, Obj::Font(font(&mut r)?));
}
83 | 84 => rec_text(p, kind, rec, &mut r)?,
93 | 94 => p.create_at(r.u32()?, Obj::Brush(BrushObj::Pattern)),
95 => rec_ext_create_pen(p, &mut r)?,
114 => rec_alpha_blend(p, rec, &mut r)?,
k if IGNORED.contains(&k) => {}
_ => return None,
}
Some(())
}
+3 -3
View File
@@ -24,7 +24,7 @@ use std::io::Cursor;
use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect, Shape, Vec2, shapes};
use super::{BAD_IMAGE, BrushObj, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect};
use super::{BAD_IMAGE, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect};
use crate::dib::{self, Rgba};
use crate::{Imported, Kind};
@@ -600,7 +600,7 @@ impl Pict {
let base = Affine::translate(-frame.origin().to_vec2());
let artboard = Rect::new(0.0, 0.0, frame.width(), frame.height());
// A picture's coordinates map straight onto the document, as a WMF's do.
let p = Player::new(Kind::Wmf, base, 25.4 / 72.0, artboard);
let p = Player::new(Kind::Wmf, base, artboard);
Self {
p,
frame,
@@ -783,7 +783,7 @@ impl Pict {
/// Fill `bp` (picture space) with `color`.
fn fill(&mut self, mut bp: BezPath, color: [u8; 3], rule: FillRule) {
bp.apply_affine(self.p.xf());
self.p.dc.brush = BrushObj::Solid(color);
self.p.dc.brush = color;
self.p.dc.fill_rule = rule;
self.p.draw(bp, true, false);
}
+658
View File
@@ -0,0 +1,658 @@
//! EMF (with or without EMF+ records) and WMF files: `craft_metafile` plays the records into a
//! picture, and the picture's items become document objects here.
//!
//! - A filled or stroked path becomes a path with a fill and a stroke (caps, joins, miter limit
//! and dashes from the pen). Opaque solid strokes with round caps and round joins drawn one after
//! another, each starting where the last one ended, with the same pen and clip, join into one
//! path. Other strokes stay apart, each with its own caps and its own dashes.
//! - A path filled with a pattern or hatched brush is filled with the average color of the
//! brush's tile.
//! - A bitmap becomes an image (its pixels as PNG) placed where the picture draws it, turned or
//! skewed with it.
//! - Text becomes point type in the font the file names, underlined or struck through as the font
//! is, and clipped to its rectangle when the file clips it.
//! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around
//! the whole picture clips nothing and is left out.
//!
//! A WMF without a placeable header is read at 1440 units an inch, and one whose placeable box is
//! empty or inverted at the units an inch the header gives. Either one that draws in a metric map
//! mode (MM_LOMETRIC to MM_TWIPS) is read at 96 pixels an inch, as `craft_metafile` plays those
//! modes. An EMF without a usable frame is read at its device's pixels a millimetre (96
//! pixels an inch when the header doesn't say).
use std::collections::HashMap;
use std::sync::{Arc, Weak};
use craft_metafile::{Cap, ClipPath, HAlign, Item, Join, LineStyle, Seg, VAlign};
use vectorcraft_color::Paint;
use vectorcraft_doc::clipnest::{Clip, Drawn, MAX_NEST, deep_clips, nest};
use vectorcraft_doc::{
Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeId,
NodeKind, StrokeLayer, TextObject,
};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes};
use super::{BAD_IMAGE, FAR_AWAY, HAIRLINE, LIMIT, MAX_NODES, around, rgb, sane};
use crate::dib::Rgba;
use crate::wmf::PLACEABLE_KEY;
use crate::{Imported, Kind};
const PATTERNS: &str = "hatched and pattern brushes are filled with their average color";
const ENDS_EARLY: &str = "the file ends early: what it held was imported";
const TOO_MANY: &str = "objects past the most one file may hold were left out";
const AT_LIMIT: &str = "the file reached the most objects one file may hold: any after them were not read";
/// The most items `craft_metafile` keeps from one file (its `MAX_ITEMS`). It stops reading at the
/// limit and does not say whether more items followed, so a picture holding this many may have
/// been cut short.
const READER_ITEMS: usize = 200_000;
/// Points a unit of a WMF without a placeable header (1440 units an inch).
const WMF_UNIT: f64 = 72.0 / 1440.0;
/// The SAVEDC levels `craft_metafile` keeps; it stops reading at a SAVEDC past them.
const SAVED_LEVELS: usize = 1024;
/// Points a pixel at 96 pixels an inch.
const PT_PER_PX: f64 = 72.0 / 96.0;
/// Points a millimetre.
const PT_PER_MM: f64 = 72.0 / 25.4;
/// WMF records that draw lines and shapes, which `craft_metafile` plays only when the mix mode
/// lets them draw.
const WMF_SHAPES: [u16; 10] = [0x0213, 0x0324, 0x0325, 0x0418, 0x041B, 0x0538, 0x061C, 0x0817, 0x081A, 0x0830];
/// WMF records that draw text and bitmaps, which `craft_metafile` plays whatever the mix mode.
const WMF_DRAWS: [u16; 5] = [0x0521, 0x0940, 0x0A32, 0x0B41, 0x0F43];
/// SETROP2 mix modes under which `craft_metafile` draws no lines, shapes or brush fills: R2_XORPEN
/// and R2_NOP.
const WMF_MIX_SKIPS: [u16; 2] = [7, 11];
/// The mix mode a WMF starts in (R2_COPYPEN).
const WMF_MIX_START: u16 = 13;
/// PATBLT raster operations `craft_metafile` draws: PATCOPY (with the brush, as the mix mode
/// allows), BLACKNESS and WHITENESS.
const PATCOPY: u32 = 0x00F0_0021;
const BLACKNESS: u32 = 0x0000_0042;
const WHITENESS: u32 = 0x00FF_0062;
/// Does a WMF draw in a metric map mode (MM_LOMETRIC to MM_TWIPS)? `craft_metafile` plays those
/// at 96 pixels an inch, whatever the window. The mode that more drawing records are played in
/// decides, counting only records the reader draws (not lines and shapes under R2_NOP or
/// R2_XORPEN, nor a PATBLT it does not fill); a file that draws nothing goes by its last mode.
/// `start` is where the standard header begins.
fn wmf_metric(bytes: &[u8], start: usize) -> bool {
let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]]));
let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let Some(words) = start.checked_add(2).and_then(u16_at) else { return false };
let mut at = start.saturating_add(usize::from(words) * 2);
let mut mode = 1;
let mut mix = WMF_MIX_START;
let metric = |mode: u16| (2..=6).contains(&mode);
// Drawing records played in a metric mode, and in any other.
let (mut in_metric, mut in_other) = (0usize, 0usize);
// The map and mix modes SAVEDC kept, which RESTOREDC brings back as the reader does.
let mut saved: Vec<(u16, u16)> = Vec::new();
// The records as the reader walks them: it stops at the end record, a record shorter than its
// header, one that runs past the file and a SAVEDC past its 1,024 levels.
while let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) {
let size = (words as usize).saturating_mul(2);
let Some(next) = at.checked_add(size) else { break };
if function == 0 || size < 6 || next > bytes.len() {
break;
}
match function {
// SETMAPMODE, when the record holds its mode.
0x0103 if size >= 8 => mode = u16_at(at + 6).unwrap_or(mode),
// SETROP2, when the record holds its mix mode.
0x0104 if size >= 8 => mix = u16_at(at + 6).unwrap_or(mix),
// SAVEDC.
0x001E => {
if saved.len() >= SAVED_LEVELS {
break;
}
saved.push((mode, mix));
}
// RESTOREDC: a negative count pops that many levels, a positive one goes back to that
// level. One that names no saved level changes nothing.
0x0127 if size >= 8 => {
let n = u16_at(at + 6).map_or(0, |v| i32::from(i16::from_le_bytes(v.to_le_bytes())));
let level = if n < 0 { saved.len().checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1) };
if let Some(level) = level
&& let Some((m, x)) = saved.get(level).copied()
{
mode = m;
mix = x;
saved.truncate(level);
}
}
f => {
let draws = match f {
_ if WMF_DRAWS.contains(&f) => true,
_ if WMF_SHAPES.contains(&f) => !WMF_MIX_SKIPS.contains(&mix),
// PATBLT: its raster operation, when the record holds one.
0x061D => match u32_at(at + 6).filter(|_| size >= 10) {
Some(PATCOPY) => !WMF_MIX_SKIPS.contains(&mix),
Some(rop) => rop == BLACKNESS || rop == WHITENESS,
None => false,
},
_ => false,
};
if draws && metric(mode) {
in_metric += 1;
} else if draws {
in_other += 1;
}
}
}
at = next;
}
if in_metric == in_other { metric(mode) } else { in_metric > in_other }
}
/// Points a picture unit across and down. `craft_metafile` gives a placeable WMF with a box and an
/// EMF with a frame in points, and other files in their logical units (WMF; pixels in a metric map
/// mode) or device units (EMF).
fn unit(bytes: &[u8], kind: Kind) -> (f64, f64) {
let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]]));
let i16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| i16::from_le_bytes([b[0], b[1]]));
let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let i32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let positive = |v: Option<i32>| v.filter(|v| *v > 0).map(f64::from);
match kind {
Kind::Wmf => {
let placeable = bytes.get(..4) == Some(&PLACEABLE_KEY.to_le_bytes()[..]);
if placeable
&& let (Some(l), Some(t), Some(r), Some(b)) = (i16_at(6), i16_at(8), i16_at(10), i16_at(12))
&& r > l
&& b > t
{
return (1.0, 1.0);
}
if wmf_metric(bytes, if placeable { 22 } else { 0 }) {
return (PT_PER_PX, PT_PER_PX);
}
if !placeable {
return (WMF_UNIT, WMF_UNIT);
}
let k = 72.0 / u16_at(14).filter(|v| *v > 0).map_or(1440.0, f64::from);
(k, k)
}
Kind::Emf => {
// Device pixels a millimetre on each axis: szlDevice over szlMicrometers when the header
// has them, else over szlMillimeters (both sizes must be positive).
let device = positive(i32_at(72)).zip(positive(i32_at(76)));
let micro = (u32_at(4).is_some_and(|s| s >= 108))
.then(|| u32_at(100).zip(u32_at(104)).filter(|(w, h)| *w > 0 && *h > 0).map(|(w, h)| (f64::from(w) / 1000.0, f64::from(h) / 1000.0)))
.flatten();
let mm = micro.or_else(|| positive(i32_at(80)).zip(positive(i32_at(84))));
let px_mm = device.zip(mm).map(|((w, h), (mw, mh))| (w / mw, h / mh));
let frame = matches!((i32_at(24), i32_at(28), i32_at(32), i32_at(36)), (Some(l), Some(t), Some(r), Some(b)) if r > l && b > t);
let ok = |v: f64| v.is_finite() && v > 0.0;
match px_mm {
Some(_) if frame => (1.0, 1.0),
Some((x, y)) if ok(x) && ok(y) => (PT_PER_MM / x, PT_PER_MM / y),
_ => (PT_PER_PX, PT_PER_PX),
}
}
}
}
/// What a stroke is drawn with, to tell whether two strokes join into one path.
#[derive(Clone, PartialEq)]
struct Pen {
color: [u8; 4],
width: f32,
line: LineStyle,
even_odd: bool,
chain: Vec<u32>,
}
/// Strokes drawn one after another, not added yet: their pen, clips and path (document space).
struct Pending {
pen: Pen,
clips: Vec<Arc<Clip>>,
path: BezPath,
}
/// Clip paths already made, by address (the `Arc` keeps the address from being reused); None for
/// one that clips nothing in the picture.
type MadeClips = HashMap<*const ClipPath, (Arc<ClipPath>, Option<Arc<Clip>>)>;
/// The last clip region and the clip made for it.
type MadeRegion = (Vec<[f32; 4]>, Option<Arc<Clip>>);
/// Brush tiles already averaged, by address: items filled with the same brush share its tile. The
/// `Weak` keeps the address from being reused, and the tile's pixels are freed once the last item
/// that uses it has been read.
type Averaged = HashMap<*const craft_metafile::Tile, (Weak<craft_metafile::Tile>, Option<[u8; 4]>)>;
struct Mapper {
/// Picture units → points.
xf: Affine,
/// How much lengths (stroke widths, dashes) grow from the picture to points.
k: f64,
frame: Rect,
doc: Document,
out: Drawn,
warnings: Vec<String>,
next_clip: u32,
paths: MadeClips,
region: Option<MadeRegion>,
pending: Option<Pending>,
averaged: Averaged,
}
fn color(c: [u8; 4]) -> Paint {
rgb([c[0], c[1], c[2]])
}
/// The average color of a tile's pixels, weighted by their alpha, and their average alpha; None
/// for a clear tile.
fn average(rgba: &[u8]) -> Option<[u8; 4]> {
let pixels = rgba.as_chunks::<4>().0;
let mut sum = [0u64; 4];
for p in pixels {
let a = u64::from(p[3]);
sum[0] += u64::from(p[0]) * a;
sum[1] += u64::from(p[1]) * a;
sum[2] += u64::from(p[2]) * a;
sum[3] += a;
}
let a = sum[3];
let alpha = (a / pixels.len().max(1) as u64) as u8;
(a > 0).then(|| [(sum[0] / a) as u8, (sum[1] / a) as u8, (sum[2] / a) as u8, alpha.max(1)])
}
impl Mapper {
fn new(width: f64, height: f64, (kx, ky): (f64, f64)) -> Self {
let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 };
let (w, h) = (side(width * kx), side(height * ky));
let mut doc = Document::new(w, h);
doc.layers.clear();
Self {
xf: Affine::scale_non_uniform(kx, ky),
// The mean of the two, as the reader scales stroke lengths.
k: (kx + ky) / 2.0,
frame: Rect::new(0.0, 0.0, w, h),
doc,
out: vec![],
warnings: vec![],
next_clip: 0,
paths: HashMap::new(),
region: None,
pending: None,
averaged: HashMap::new(),
}
}
fn warn(&mut self, w: &str) {
if !self.warnings.iter().any(|x| x == w) {
self.warnings.push(w.to_string());
}
}
fn path(&self, segs: &[Seg]) -> BezPath {
let mut bp = craft_metafile::bez_path(segs);
bp.apply_affine(self.xf);
bp
}
/// A clip of `path` (document space), or None when it clips nothing in the picture.
fn clip(&mut self, path: BezPath, rule: FillRule) -> Option<Arc<Clip>> {
if around(&path, self.frame) {
return None;
}
self.next_clip += 1;
Some(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) }))
}
/// The clips an item is drawn under, outermost first; None when it shows nowhere.
fn chain(&mut self, region: Option<Vec<[f32; 4]>>, clips: &[Arc<ClipPath>]) -> Option<Vec<Arc<Clip>>> {
let mut chain = vec![];
if let Some(rects) = region {
if rects.is_empty() {
return None;
}
let made = match &self.region {
Some((last, made)) if *last == rects => made.clone(),
_ => {
let mut bp = BezPath::new();
for [x0, y0, x1, y1] in &rects {
bp.extend(shapes::rectangle(Rect::new(f64::from(*x0), f64::from(*y0), f64::from(*x1), f64::from(*y1))).to_bezpath());
}
bp.apply_affine(self.xf);
if !sane(bp.bounding_box()) {
self.warn(FAR_AWAY);
return None;
}
let made = self.clip(bp, FillRule::NonZero);
self.region = Some((rects, made.clone()));
made
}
};
chain.extend(made);
}
for c in clips {
let key = Arc::as_ptr(c);
let made = match self.paths.get(&key) {
Some((_, made)) => made.clone(),
None => {
let bp = self.path(&c.segs);
if !sane(bp.bounding_box()) {
self.warn(FAR_AWAY);
return None;
}
let made = self.clip(bp, if c.even_odd { FillRule::EvenOdd } else { FillRule::NonZero });
self.paths.insert(key, (c.clone(), made.clone()));
made
}
};
chain.extend(made);
}
if chain.len() > MAX_NEST {
chain.truncate(MAX_NEST);
self.warn(&deep_clips());
}
Some(chain)
}
fn push(&mut self, clips: Vec<Arc<Clip>>, mut node: Node) {
if self.out.len() >= MAX_NODES {
return self.warn(TOO_MANY);
}
if !node.visual_bounds().is_none_or(sane) {
return self.warn(FAR_AWAY);
}
node.id = self.doc.alloc_id();
self.out.push((clips, node));
}
/// Add the strokes waiting to be joined.
fn flush(&mut self) {
if let Some(p) = self.pending.take() {
let node = self.path_node(p.path, None, Some((p.pen.color, p.pen.width, &p.pen.line)), p.pen.even_odd);
if let Some(n) = node {
self.push(p.clips, n);
}
}
}
fn stroke_layer(&self, c: [u8; 4], width: f32, line: &LineStyle) -> StrokeLayer {
let w = f64::from(width) * self.k;
let mut st = StrokeLayer::new(color(c), if w > 0.0 && w.is_finite() { w } else { HAIRLINE });
st.opacity = f32::from(c[3]) / 255.0;
st.cap = match line.cap {
Cap::Round => LineCap::Round,
Cap::Square => LineCap::Square,
Cap::Flat => LineCap::Butt,
};
st.join = match line.join {
Join::Round => LineJoin::Round,
Join::Bevel => LineJoin::Bevel,
Join::Miter => LineJoin::Miter,
};
let miter = f64::from(line.miter_limit);
if miter.is_finite() && miter >= 1.0 {
st.miter_limit = miter;
}
let dash = Dash { pattern: line.dash.iter().map(|d| f64::from(*d) * self.k).collect(), offset: 0.0, align_corners: false };
st.dash = dash.is_dashed().then_some(dash);
st
}
/// A path node painted with `fill` and `stroke`; None when neither shows.
fn path_node(&self, bp: BezPath, fill: Option<[u8; 4]>, stroke: Option<([u8; 4], f32, &LineStyle)>, even_odd: bool) -> Option<Node> {
if bp.elements().is_empty() {
return None;
}
let mut items = vec![];
if let Some(c) = fill.filter(|c| c[3] > 0) {
let mut f = FillLayer::new(color(c));
f.opacity = f32::from(c[3]) / 255.0;
items.push(AppearanceItem::Fill(f));
}
if let Some((c, w, line)) = stroke.filter(|s| s.0[3] > 0) {
items.push(AppearanceItem::Stroke(self.stroke_layer(c, w, line)));
}
if items.is_empty() {
return None;
}
let mut n = Node::path(NodeId(0), PathData::from_bezpath(&bp), Appearance { items, ..Appearance::default() });
if let NodeKind::Path { rule, .. } = &mut n.kind {
*rule = if even_odd { FillRule::EvenOdd } else { FillRule::NonZero };
}
Some(n)
}
fn item(&mut self, item: Item) {
match item {
Item::Path { segs, fill, stroke, line, even_odd, region, clips } => {
let Some(chain) = self.chain(region, &clips) else { return self.flush() };
let bp = self.path(&segs);
// An open stroke with nothing filled waits, to join the next one.
if let (None, Some((c, w))) = (fill, stroke)
&& !segs.iter().any(|s| matches!(s, Seg::Close))
{
// A stroke that reaches too far is left out here, before it joins the strokes
// waiting, so they are still added.
let half = f64::from(w) * self.k;
let half = if half > 0.0 && half.is_finite() { half / 2.0 } else { HAIRLINE / 2.0 };
if !sane(bp.bounding_box().inflate(half, half)) {
self.flush();
return self.warn(FAR_AWAY);
}
let pen = Pen { color: c, width: w, line, even_odd, chain: chain.iter().map(|c| c.id).collect() };
let start = bp.elements().first().and_then(|e| match e {
PathEl::MoveTo(p) => Some(*p),
_ => None,
});
// A translucent stroke stays apart, so where strokes overlap each one shows. So
// does a dashed one, whose dashes start at its own start, and one whose caps
// or joins aren't round: a join where two strokes meet is not their two caps.
if let Some(p) = &mut self.pending
&& p.pen == pen
&& pen.color[3] == u8::MAX
&& pen.line.dash.is_empty()
&& matches!((&pen.line.cap, &pen.line.join), (Cap::Round, Join::Round))
&& start.is_some()
&& p.path.elements().last().and_then(|e| e.end_point()) == start
{
p.path.extend(bp.elements().iter().skip(1).copied());
return;
}
self.flush();
self.pending = Some(Pending { pen, clips: chain, path: bp });
return;
}
self.flush();
let stroke = stroke.map(|(c, w)| (c, w, &line));
if let Some(n) = self.path_node(bp, fill, stroke, even_odd) {
self.push(chain, n);
}
}
Item::Pattern { segs, even_odd, tile, region, clips } => {
self.flush();
let Some(chain) = self.chain(region, &clips) else { return };
let Some(c) = self.averaged.entry(Arc::as_ptr(&tile)).or_insert_with(|| (Arc::downgrade(&tile), average(&tile.rgba))).1 else {
return;
};
self.warn(PATTERNS);
let bp = self.path(&segs);
if let Some(n) = self.path_node(bp, Some(c), None, even_odd) {
self.push(chain, n);
}
}
Item::Bitmap { transform, width, height, rgba, region, clips, .. } => {
self.flush();
let Some(chain) = self.chain(region, &clips) else { return };
self.image(Rgba { width, height, pixels: rgba }, Affine::new(transform), chain);
}
Item::Text(t) => {
self.flush();
let Some(mut chain) = self.chain(t.region.clone(), &t.clips) else { return };
// The text's own clip rectangle, inside the others.
if let Some([x0, y0, x1, y1]) = t.clip {
let mut bp = shapes::rectangle(Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1)).abs()).to_bezpath();
bp.apply_affine(self.xf);
if !sane(bp.bounding_box()) {
return self.warn(FAR_AWAY);
}
if let Some(own) = self.clip(bp, FillRule::NonZero) {
// Past the stack, the text's own clip takes the innermost place kept.
if chain.len() >= MAX_NEST {
chain.truncate(MAX_NEST.saturating_sub(1));
self.warn(&deep_clips());
}
chain.push(own);
}
}
self.text(&t, chain);
}
}
}
/// An image whose unit square `unit` places in the picture.
fn image(&mut self, img: Rgba, unit: Affine, chain: Vec<Arc<Clip>>) {
if img.width == 0 || img.height == 0 {
return;
}
let xf = self.xf * unit * Affine::scale_non_uniform(1.0 / f64::from(img.width), 1.0 / f64::from(img.height));
if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 {
return;
}
let Ok(png) = img.to_png() else { return self.warn(BAD_IMAGE) };
let blob = ImageBlob::new("image/png", png);
let key = blob.content_key();
self.doc.images.entry(key.clone()).or_insert(blob);
let im = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None };
self.push(chain, Node::new(NodeId(0), NodeKind::Image(Box::new(im))));
}
fn text(&mut self, t: &craft_metafile::Text, chain: Vec<Arc<Clip>>) {
let s: String = t.text.chars().filter(|c| *c != '\0').collect();
if s.trim().is_empty() || t.color[3] == 0 {
return;
}
// Text space → document without the move: its vertical scale gives the type size, and what
// is left of it (a turn, a stretch across) goes on the text object.
let [a, b, c, d, ..] = t.transform;
let linear = self.xf * Affine::new([a, b, c, d, 0.0, 0.0]);
let [_, _, c, d, ..] = linear.as_coeffs();
let k = c.hypot(d);
let shape = if k > 1e-12 && k.is_finite() && linear.determinant().abs() > 1e-24 { Affine::scale(1.0 / k) * linear } else { Affine::IDENTITY };
let f = &t.font;
let h = f64::from(f.height);
// A negative height is the em; a positive one the cell (the em and the internal leading).
let em = if h < 0.0 { -h } else { h * 0.85 };
let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 };
let mut style = CharStyle { size, fill: color(t.color), stroke: Paint::None, ..CharStyle::default() };
if !f.family.trim().is_empty() {
style.font_family = f.family.trim().to_string();
}
style.font_style = match (f.weight >= 600, f.italic) {
(true, true) => "Bold Italic",
(true, false) => "Bold",
(false, true) => "Italic",
(false, false) => "Regular",
}
.into();
style.underline = f.underline;
style.strikethrough = f.strike;
// Where the baseline is below the reference point.
let drop = match t.v_align {
VAlign::Baseline => 0.0,
VAlign::Bottom => -0.2 * size,
VAlign::Top => 0.8 * size,
};
let origin = self.xf * Point::new(t.transform[4], t.transform[5]);
let mut text = TextObject::point(Point::ZERO, &s, style);
text.xf = Affine::translate(origin.to_vec2()) * shape * Affine::translate((0.0, drop));
text.para.justify = match t.h_align {
HAlign::Center => Justify::Center,
HAlign::Right => Justify::Right,
HAlign::Left => Justify::Left,
};
text.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text).bounds);
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text)));
n.opacity = f32::from(t.color[3]) / 255.0;
self.push(chain, n);
}
/// The document: what was drawn on one layer, clipped art in clipping groups.
fn finish(mut self, kind: Kind, skipped: u32) -> Imported {
self.flush();
if skipped > 0 {
let n = skipped;
self.warnings.push(format!(
"{n} record{} of kinds VectorCraft doesn't read {} skipped",
if n == 1 { "" } else { "s" },
if n == 1 { "was" } else { "were" }
));
}
let out = std::mem::take(&mut self.out);
let children = nest(&mut self.doc, out);
let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0));
if let Some(c) = layer.children_mut() {
*c = children;
}
self.doc.layers = vec![Arc::new(layer)];
Imported { document: self.doc, kind, warnings: self.warnings }
}
}
/// Does the file stop before its end-of-file record?
fn ends_early(bytes: &[u8], kind: Kind) -> bool {
let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]]));
let mut at = match kind {
Kind::Emf => 0,
Kind::Wmf => {
let start = if u32_at(0) == Some(PLACEABLE_KEY) { 22 } else { 0 };
let Some(words) = u16_at(start + 2) else { return true };
start + usize::from(words) * 2
}
};
loop {
let size = match kind {
Kind::Emf => {
let (Some(kind), Some(size)) = (u32_at(at), u32_at(at.saturating_add(4))) else { return true };
if kind == 14 {
return false;
}
// Records are a multiple of 4 bytes long; reading stops at one that isn't.
if !size.is_multiple_of(4) {
return true;
}
size as usize
}
Kind::Wmf => {
let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) else { return true };
if function == 0 {
return false;
}
(words as usize).saturating_mul(2)
}
};
if size < 6 {
return true;
}
at = at.saturating_add(size);
}
}
/// Read an EMF or WMF file.
pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?;
let pic = craft_metafile::parse(bytes).map_err(|e| match e {
craft_metafile::Error::NotMetafile => "not an EMF or WMF file".to_string(),
craft_metafile::Error::BadHeader => format!("the {} header is damaged", kind.id().to_uppercase()),
craft_metafile::Error::NoRecords => format!("the {} file holds no records", kind.id().to_uppercase()),
})?;
let k = unit(bytes, kind);
let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), k);
if ends_early(bytes, kind) {
m.warn(ENDS_EARLY);
}
if pic.items.len() >= READER_ITEMS {
m.warn(AT_LIMIT);
}
for item in pic.items {
m.item(item);
}
Ok(m.finish(kind, pic.skipped_records))
}
-338
View File
@@ -1,338 +0,0 @@
//! WMF records (MS-WMF) played on a [`Player`]. A placeable header gives the picture's box in
//! logical units and the units an inch; without one, the first window origin and extent are the
//! box, at 1440 units an inch.
use vectorcraft_geom::{Affine, Point, Rect, shapes};
use super::{ArcKind, BrushObj, FontObj, Obj, PenObj, Player};
use crate::bytes::Reader;
use crate::dib::{self, Alpha};
use crate::wmf::PLACEABLE_KEY;
use crate::{Imported, Kind};
/// Units an inch when the file doesn't say (twips).
const DEFAULT_INCH: f64 = 1440.0;
/// Records that change nothing VectorCraft keeps (background, raster and mapping details, palettes,
/// escapes).
const IGNORED: &[u16] = &[
0x0102, 0x0103, 0x0104, 0x0105, 0x0107, 0x0108, 0x0201, 0x020A, 0x020B, 0x020C, 0x020D, 0x020E, 0x020F, 0x0211, 0x0410, 0x0412, 0x0231, 0x0234,
0x0035, 0x0037, 0x0139, 0x0436, 0x0626,
];
fn point(r: &mut Reader) -> Option<Point> {
Some(Point::new(f64::from(r.i16()?), f64::from(r.i16()?)))
}
/// A point stored y first.
fn point_yx(r: &mut Reader) -> Option<Point> {
let y = f64::from(r.i16()?);
Some(Point::new(f64::from(r.i16()?), y))
}
/// A rectangle stored bottom, right, top, left.
fn rect_brtl(r: &mut Reader) -> Option<Rect> {
let (b, rt, t, l) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?);
Some(Rect::new(f64::from(l), f64::from(t), f64::from(rt), f64::from(b)))
}
fn color(r: &mut Reader) -> Option<[u8; 3]> {
let [red, g, b, _] = r.u32()?.to_le_bytes();
Some([red, g, b])
}
fn points(r: &mut Reader, n: usize) -> Option<Vec<Point>> {
if r.rest().len() < n * 4 {
return None;
}
(0..n).map(|_| point(r)).collect()
}
/// ANSI text (read as Latin-1).
fn ansi(b: &[u8]) -> String {
b.iter().map(|c| char::from(*c)).collect()
}
/// The records' start, and the box and units an inch of a placeable header.
fn header(bytes: &[u8]) -> Option<(usize, Option<(Rect, f64)>)> {
let mut r = Reader::new(bytes);
let placeable = if r.u32()? == PLACEABLE_KEY {
r.skip(2)?;
let (l, t, rt, b) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?);
let inch = r.u16()?;
let inch = if inch == 0 { DEFAULT_INCH } else { f64::from(inch) };
Some((Rect::new(f64::from(l), f64::from(t), f64::from(rt), f64::from(b)).abs(), inch))
} else {
None
};
let start = if placeable.is_some() { 22 } else { 0 };
let mut h = Reader::new(bytes.get(start..)?);
h.skip(2)?;
let words = usize::from(h.u16()?);
if words < 9 {
return None;
}
Some((start + words * 2, placeable))
}
/// The first window origin and extent, as the picture's box when there is no placeable header.
fn window(bytes: &[u8], mut at: usize) -> Option<Rect> {
let (mut org, mut ext) = (None, None);
while let Some(head) = bytes.get(at..at + 6) {
let words = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize;
let function = u16::from_le_bytes([head[4], head[5]]);
if words < 3 || function == 0 {
break;
}
let mut r = Reader::new(bytes.get(at + 6..).unwrap_or_default());
match function {
0x020B if org.is_none() => org = point_yx(&mut r),
0x020C if ext.is_none() => ext = point_yx(&mut r),
_ => {}
}
if org.is_some() && ext.is_some() {
break;
}
at = at.saturating_add(words.saturating_mul(2));
}
let o = org.unwrap_or(Point::ZERO);
let e = ext?;
Some(Rect::new(o.x, o.y, o.x + e.x, o.y + e.y).abs())
}
/// Logical → document for a placeable file whose window (`org`, `ext`) is mapped onto its box `b`;
/// a negative extent flips that axis, as in GDI.
fn window_map(b: Rect, k: f64, org: Point, ext: Point) -> Affine {
let ratio = |box_len: f64, e: f64| if e.abs() > 1e-12 { box_len / e } else { 1.0 };
Affine::scale_non_uniform(k * ratio(b.width(), ext.x), k * ratio(b.height(), ext.y)) * Affine::translate(-org.to_vec2())
}
pub(super) fn play(bytes: &[u8]) -> Result<Imported, String> {
let (start, placeable) = header(bytes).ok_or("the WMF header is damaged")?;
let (frame, inch) = match placeable {
Some((b, inch)) if b.width() > 0.0 && b.height() > 0.0 => (Some(b), inch),
_ => (window(bytes, start).filter(|w| w.width() > 0.0 && w.height() > 0.0), DEFAULT_INCH),
};
let k = 72.0 / inch;
let origin = frame.map_or(Point::ZERO, |f| f.origin());
let artboard = frame.map_or(Rect::new(0.0, 0.0, 1.0, 1.0), |f| Rect::new(0.0, 0.0, f.width() * k, f.height() * k));
let mut p = Player::new(Kind::Wmf, Affine::scale(k) * Affine::translate(-origin.to_vec2()), 25.4 / inch, artboard);
// With a placeable header, the window records map the window onto the box.
let placed = placeable.map(|(b, _)| b).filter(|b| b.width() > 0.0 && b.height() > 0.0);
let mut win = (placed.map_or(Point::ZERO, |b| b.origin()), placed.map_or(Point::ZERO, |b| Point::new(b.width(), b.height())));
let mut at = start;
let mut ended = false;
while let Some(head) = bytes.get(at..at + 6) {
let words = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize;
let function = u16::from_le_bytes([head[4], head[5]]);
if function == 0 {
ended = true;
break;
}
let Some(rec) = words.checked_mul(2).and_then(|n| bytes.get(at..at.checked_add(n)?)).filter(|_| words >= 3) else { break };
if !matches!(function, 0x0213 | 0x0214) {
p.flush();
}
if let (Some(b), 0x020B | 0x020C) = (placed, function) {
if let Some(v) = point_yx(&mut Reader::new(rec.get(6..).unwrap_or_default())) {
if function == 0x020B {
win.0 = v;
} else {
win.1 = v;
}
p.dev_to_doc = window_map(b, k, win.0, win.1);
}
} else if record(&mut p, function, rec.get(6..).unwrap_or_default()).is_none() {
p.skip();
}
at += rec.len();
}
if !ended {
p.warn("the file ends early: what it held was imported");
}
let mut out = p.finish();
// No box given: the art's bounds.
if frame.is_none()
&& let Some(b) = out.document.layers.first().and_then(|l| vectorcraft_doc::live::nodes_bounds(l.children().map_or(&[][..], |c| c.as_slice())))
&& let Some(a) = out.document.artboards.first_mut()
{
a.rect = Rect::from_origin_size(b.origin(), (b.width().max(1.0), b.height().max(1.0)));
}
Ok(out)
}
/// An image record's source rectangle (from the bottom for a bottom-up DIB) and destination.
fn blit(p: &mut Player, rop: u32, src: (i16, i16, i16, i16), dest: (i16, i16, i16, i16), packed: Option<&[u8]>) {
let (xd, yd, wd, hd) = (f64::from(dest.0), f64::from(dest.1), f64::from(dest.2), f64::from(dest.3));
let d = Rect::new(xd, yd, xd + wd, yd + hd);
let Some(packed) = packed else { return p.pattern_blit(d, rop) };
let parts = dib::split(packed);
let img = parts.ok_or_else(|| "damaged".to_string()).and_then(|(bmi, bits)| dib::decode(bmi, bits, Alpha::Ignore, &mut p.pixels_left));
let bottom_up = parts.and_then(|(bmi, _)| bmi.get(8..12)).is_some_and(|h| i32::from_le_bytes([h[0], h[1], h[2], h[3]]) > 0);
let ih = img.as_ref().map_or(0.0, |i| f64::from(i.height));
let (xs, ys, ws, hs) = (f64::from(src.0), f64::from(src.1), f64::from(src.2), f64::from(src.3));
let top = if bottom_up { ih - ys - hs } else { ys };
p.image(img, Rect::new(xs, top, xs + ws, top + hs), d, rop, 1.0);
}
/// PolyPolygon (0x0538).
fn rec_poly_polygon(p: &mut Player, r: &mut Reader) -> Option<()> {
let n = usize::from(r.u16()?);
if r.rest().len() < n * 2 {
return None;
}
let counts: Vec<usize> = (0..n).map(|_| r.u16().map(usize::from)).collect::<Option<_>>()?;
let mut polys = Vec::with_capacity(n);
for c in counts {
polys.push(points(r, c)?);
}
p.poly_poly(&polys, true);
Some(())
}
/// Arc (0x0817), Pie (0x081A) and Chord (0x0830).
fn rec_arc(p: &mut Player, function: u16, r: &mut Reader) -> Option<()> {
let (end, start) = (point_yx(r)?, point_yx(r)?);
let b = rect_brtl(r)?;
let kind = match function {
0x0817 => ArcKind::Open,
0x081A => ArcKind::Pie,
_ => ArcKind::Chord,
};
p.arc(b, start, end, kind);
Some(())
}
/// CreateFontIndirect (0x02FB).
fn rec_create_font(p: &mut Player, r: &mut Reader) -> Option<()> {
let height = f64::from(r.i16()?);
r.skip(2)?;
let escapement = f64::from(r.i16()?);
r.skip(2)?;
let weight = i32::from(r.i16()?);
let italic = r.bytes(1)?.first().is_some_and(|b| *b != 0);
r.skip(7)?;
let face: Vec<u8> = r.rest().iter().take(32).take_while(|b| **b != 0).copied().collect();
p.create(Obj::Font(FontObj { height, escapement, weight, italic, face: ansi(&face) }));
Some(())
}
/// TextOut (0x0521).
fn rec_text_out(p: &mut Player, r: &mut Reader) -> Option<()> {
let n = usize::try_from(r.i16()?).ok()?;
let s = ansi(r.bytes(n)?);
r.skip(n % 2)?;
let at = point_yx(r)?;
p.text(at, &s);
Some(())
}
/// ExtTextOut (0x0A32).
fn rec_ext_text_out(p: &mut Player, r: &mut Reader) -> Option<()> {
let at = point_yx(r)?;
let n = usize::try_from(r.i16()?).ok()?;
let opts = r.u16()?;
// ETO_OPAQUE or ETO_CLIPPED: a rectangle comes first.
if opts & 0x6 != 0 {
r.skip(8)?;
}
let s = ansi(r.bytes(n)?);
p.text(at, &s);
Some(())
}
/// StretchDIB (0x0F43).
fn rec_stretch_dib(p: &mut Player, r: &mut Reader) -> Option<()> {
let rop = r.u32()?;
r.skip(2)?;
let (hs, ws, ys, xs) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?);
let (hd, wd, yd, xd) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?);
blit(p, rop, (xs, ys, ws, hs), (xd, yd, wd, hd), Some(r.rest()));
Some(())
}
/// StretchBlt (0x0B41).
fn rec_stretch_blt(p: &mut Player, body: &[u8], r: &mut Reader) -> Option<()> {
let rop = r.u32()?;
let (hs, ws, ys, xs) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?);
// Without a bitmap, a reserved word comes before the destination.
let with_bitmap = body.len() > 22;
if !with_bitmap {
r.skip(2)?;
}
let (hd, wd, yd, xd) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?);
blit(p, rop, (xs, ys, ws, hs), (xd, yd, wd, hd), with_bitmap.then(|| r.rest()));
Some(())
}
/// BitBlt (0x0940).
fn rec_bit_blt(p: &mut Player, body: &[u8], r: &mut Reader) -> Option<()> {
let rop = r.u32()?;
let (ys, xs) = (r.i16()?, r.i16()?);
let with_bitmap = body.len() > 20;
if !with_bitmap {
r.skip(2)?;
}
let (h, w, yd, xd) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?);
blit(p, rop, (xs, ys, w, h), (xd, yd, w, h), with_bitmap.then(|| r.rest()));
Some(())
}
/// Play one record (`r`: its parameters). `None`: unknown or damaged.
fn record(p: &mut Player, function: u16, body: &[u8]) -> Option<()> {
let mut r = Reader::new(body);
match function {
0x001E => p.save(),
0x0127 => p.restore(i32::from(r.i16()?)),
0x0106 => p.set_fill_mode(r.u16()? == 1),
0x0209 => p.set_text_color(color(&mut r)?),
0x012E => p.set_text_align(u32::from(r.u16()?)),
0x0214 => p.move_to(point_yx(&mut r)?),
0x0213 => {
let pt = point_yx(&mut r)?;
p.poly_to(&[pt], false);
}
0x0324 | 0x0325 => {
let n = usize::try_from(r.i16()?).ok()?;
let pts = points(&mut r, n)?;
p.poly(&pts, function == 0x0324, false);
}
0x0538 => rec_poly_polygon(p, &mut r)?,
0x041B => p.figure(shapes::rectangle(rect_brtl(&mut r)?.abs()).to_bezpath(), true),
0x0418 => p.figure(shapes::ellipse(rect_brtl(&mut r)?.abs()).to_bezpath(), true),
0x061C => {
let (h, w) = (f64::from(r.i16()?), f64::from(r.i16()?));
p.figure(super::round_rect(rect_brtl(&mut r)?, w, h), true);
}
0x0817 | 0x081A | 0x0830 => rec_arc(p, function, &mut r)?,
0x0416 => p.clip_rect(rect_brtl(&mut r)?),
0x0415 => p.exclude_clip(),
0x012D => p.select(u32::from(r.u16()?)),
0x01F0 => p.delete(u32::from(r.u16()?)),
0x02FA => {
let style = u32::from(r.u16()?);
let width = f64::from(r.i16()?);
r.skip(2)?;
p.create(Obj::Pen(PenObj { style, width, color: color(&mut r)?, entries: vec![] }));
}
0x02FC => {
let style = u32::from(r.u16()?);
p.create(Obj::Brush(BrushObj::from_log(style, color(&mut r)?)));
}
0x02FB => rec_create_font(p, &mut r)?,
0x00F7 | 0x06FF => p.create(Obj::Other),
0x01F9 | 0x0142 => p.create(Obj::Brush(BrushObj::Pattern)),
0x0521 => rec_text_out(p, &mut r)?,
0x0A32 => rec_ext_text_out(p, &mut r)?,
0x0F43 => rec_stretch_dib(p, &mut r)?,
0x0B41 => rec_stretch_blt(p, body, &mut r)?,
0x0940 => rec_bit_blt(p, body, &mut r)?,
0x061D => {
let rop = r.u32()?;
let (h, w, y, x) = (f64::from(r.i16()?), f64::from(r.i16()?), f64::from(r.i16()?), f64::from(r.i16()?));
p.pattern_blit(Rect::new(x, y, x + w, y + h), rop);
}
f if IGNORED.contains(&f) => {}
_ => return None,
}
Some(())
}
+7 -6
View File
@@ -13,13 +13,14 @@
//! lines or gradients, so clipped art is written whole, images over white, dashes as separate
//! lines and gradients and patterns as one colour (each loss comes back as a warning).
//!
//! [`import`] reads either format back into a document of one artboard (the picture's frame) and
//! one layer: paths with fills and strokes, clipping, images and text. Records it doesn't read are
//! skipped, with one warning. [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2)
//! into the same kind of document.
//! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`)
//! into a document of one artboard (the picture's frame) and one layer: paths with fills and
//! strokes, clipping, images and text. Records it doesn't read are skipped, with one warning.
//! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of
//! document.
//!
//! - `bytes`: little-endian writing and bounds-checked reading.
//! - `dib`: device-independent bitmaps, both ways.
//! - `bytes`: little-endian writing.
//! - `dib`: device-independent bitmaps for the writers.
//! - `scene`: the document walk both writers share.
//! - `emf`, `wmf`: the writers.
//! - `import`: the readers.
+475 -9
View File
@@ -151,13 +151,14 @@ fn dashes_gradients_and_images_round_trip_through_emf() {
// ---------- hand-built records ----------
/// An EMF of `records` (type, body) with a frame of `w` × `h` hundredths of a millimetre on a
/// device of 100 pixels a millimetre.
/// device of 100 pixels a millimetre. Bodies are padded to a multiple of 4 bytes.
fn hand_emf(w: i32, h: i32, records: &[(u32, Vec<u8>)]) -> Vec<u8> {
let mut o = Out::default();
let rec = |o: &mut Out, kind: u32, body: &[u8]| {
o.u32(kind);
o.u32(8 + body.len() as u32);
o.u32(8 + body.len().next_multiple_of(4) as u32);
o.bytes(body);
o.pad(4);
};
let mut head = Out::default();
head.bytes(&[0; 16]);
@@ -336,6 +337,129 @@ fn wmf_window_is_mapped_onto_the_placeable_box() {
}
}
#[test]
fn wmf_without_a_placeable_header_is_read_at_1440_units_an_inch() {
// The window is 2880 × 1440 units: 2 × 1 inches. The rectangle is its left half.
let records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 2880])), (0x041B, le16(&[1440, 1440, 0, 0]))];
let plain = hand_wmf(2880, 1440, &records)[22..].to_vec();
let back = import(&plain).unwrap();
assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 144.0, 72.0), 1e-6), "{:?}", back.document.artboards[0].rect);
let p = paths(&back.document);
assert_eq!(p.len(), 1);
assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{:?}", p[0].geometric_bounds());
}
#[test]
fn wmf_without_a_placeable_box_in_a_metric_map_mode_is_read_at_96_pixels_an_inch() {
// MM_TWIPS (y up) and a window of 1440 twips square: one inch. The rectangle is the whole window.
let records = vec![(0x0103, le16(&[6])), (0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), (0x041B, le16(&[1440, 1440, 0, 0]))];
let boxed = hand_wmf(1440, 1440, &records);
let plain = boxed[22..].to_vec();
// The box runs from right to left, so it gives no size.
let mut inverted = boxed;
inverted[6..8].copy_from_slice(&1440i16.to_le_bytes());
inverted[10..12].copy_from_slice(&0i16.to_le_bytes());
for bytes in [plain, inverted] {
let back = import(&bytes).unwrap();
assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 72.0, 72.0), 1e-4), "{:?}", back.document.artboards[0].rect);
let p = paths(&back.document);
assert_eq!(p.len(), 1);
assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-4), "{:?}", p[0].geometric_bounds());
}
}
#[test]
fn wmf_whose_metric_map_mode_is_restored_away_is_read_at_1440_units_an_inch() {
// SAVEDC, MM_TWIPS, then RESTOREDC back to MM_TEXT, by a count of levels and by a level; the
// drawing is then the one in `wmf_without_a_placeable_header_is_read_at_1440_units_an_inch`.
for restore in [-1i16, 1] {
let records = vec![
(0x001E, Vec::new()),
(0x0103, le16(&[6])),
(0x0127, le16(&[restore])),
(0x020B, le16(&[0, 0])),
(0x020C, le16(&[1440, 2880])),
(0x041B, le16(&[1440, 1440, 0, 0])),
];
let plain = hand_wmf(2880, 1440, &records)[22..].to_vec();
let back = import(&plain).unwrap();
assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 144.0, 72.0), 1e-6), "{restore}: {:?}", back.document.artboards[0].rect);
let p = paths(&back.document);
assert_eq!(p.len(), 1);
assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{restore}: {:?}", p[0].geometric_bounds());
}
}
#[test]
fn wmf_that_draws_in_a_metric_map_mode_and_restores_is_read_at_96_pixels_an_inch() {
// SAVEDC, MM_TWIPS, a one-inch rectangle, then RESTOREDC back to MM_TEXT with nothing more drawn.
let records = vec![
(0x001E, Vec::new()),
(0x0103, le16(&[6])),
(0x020B, le16(&[0, 0])),
(0x020C, le16(&[1440, 1440])),
(0x041B, le16(&[1440, 1440, 0, 0])),
(0x0127, le16(&[-1])),
];
let plain = hand_wmf(1440, 1440, &records)[22..].to_vec();
let back = import(&plain).unwrap();
let p = paths(&back.document);
assert_eq!(p.len(), 1);
let b = p[0].geometric_bounds().unwrap();
assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "{b:?}");
}
#[test]
fn wmf_records_the_mix_mode_keeps_from_drawing_do_not_set_its_scale() {
// A rectangle of 1440 units in MM_TEXT; then SAVEDC, MM_TWIPS, a mix mode and two records that
// draw nothing under it, and RESTOREDC.
let rect = (0x041B, le16(&[1440, 1440, 0, 0]));
let patblt = |rop: u32| (0x061D, [rop.to_le_bytes().to_vec(), le16(&[100, 100, 0, 0])].concat());
let cases = [
// R2_NOP and R2_XORPEN: rectangles draw nothing.
(11i16, [rect.clone(), rect.clone()]),
(7, [rect.clone(), rect.clone()]),
// R2_NOP: PATBLT with PATCOPY fills nothing.
(11, [patblt(0x00F0_0021), patblt(0x00F0_0021)]),
// R2_COPYPEN: PATBLT with DSTINVERT is not drawn.
(13, [patblt(0x0055_0009), patblt(0x0055_0009)]),
];
for (mix, hidden) in cases {
let mut records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), rect.clone()];
records.extend([(0x001E, Vec::new()), (0x0103, le16(&[6])), (0x0104, le16(&[mix]))]);
records.extend(hidden);
records.push((0x0127, le16(&[-1])));
let plain = hand_wmf(1440, 1440, &records)[22..].to_vec();
let back = import(&plain).unwrap();
let p = paths(&back.document);
assert_eq!(p.len(), 1, "mix {mix}: {p:?}");
let b = p[0].geometric_bounds().unwrap();
assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "mix {mix}: {b:?}");
}
// R2_NOP, then SAVEDC, R2_COPYPEN and RESTOREDC bring R2_NOP back: the MM_TWIPS rectangle after
// them draws nothing.
let mut records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), rect.clone(), (0x0104, le16(&[11]))];
records.extend([(0x001E, Vec::new()), (0x0104, le16(&[13])), (0x0127, le16(&[-1])), (0x0103, le16(&[6])), rect]);
let back = import(&hand_wmf(1440, 1440, &records)[22..]).unwrap();
let p = paths(&back.document);
assert_eq!(p.len(), 1, "{p:?}");
let b = p[0].geometric_bounds().unwrap();
assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "restored: {b:?}");
}
#[test]
fn a_stroke_that_reaches_too_far_leaves_the_strokes_before_it() {
// The black pen draws from (0, 500) to (100, 500), then on to a point far outside the picture.
let records = vec![(37, le(&[0x8000_0007u32 as i32])), (27, le(&[0, 500])), (54, le(&[100, 500])), (54, le(&[100_000_000, 500]))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let p = paths(&back.document);
assert_eq!(p.len(), 1, "{p:?}");
let mm = 72.0 / 25.4;
let b = p[0].geometric_bounds().unwrap();
assert!((b.x0).abs() < 0.01 && (b.x1 - mm).abs() < 0.01 && (b.y0 - 5.0 * mm).abs() < 0.01, "{b:?}");
assert!(back.warnings.iter().any(|w| w.contains("far outside")), "{:?}", back.warnings);
}
#[test]
fn damaged_files_fail_or_import_partly() {
let good = emf(&sample()).bytes;
@@ -357,6 +481,18 @@ fn damaged_files_fail_or_import_partly() {
assert!(import(&huge).is_ok());
}
#[test]
fn a_file_with_more_objects_than_are_read_says_so() {
// RECTANGLE records: 10 more than the reader keeps, then a few under that.
let rect = (43, le(&[0, 0, 100, 100]));
let many = hand_emf(5000, 3000, &vec![rect.clone(); 200_010]);
let back = import(&many).unwrap();
assert_eq!(paths(&back.document).len(), 200_000);
assert!(back.warnings.iter().any(|w| w.contains("reached the most objects")), "{:?}", back.warnings);
let few = import(&hand_emf(5000, 3000, &vec![rect; 3])).unwrap();
assert!(few.warnings.is_empty(), "{:?}", few.warnings);
}
/// An EMR_STRETCHDIBITS copying `png` (a BI_PNG bitmap) to a 10 × 10 box.
fn png_stretch_dibits(png: &[u8]) -> Vec<u8> {
// Bounds; destination, source and its size; the BITMAPINFO and the bits (from the record start);
@@ -371,19 +507,29 @@ fn png_stretch_dibits(png: &[u8]) -> Vec<u8> {
}
#[test]
fn embedded_bitmaps_share_one_pixel_budget() {
// #3600: each bitmap was bounded but not their total, so many records of the largest one a record
// may hold cost minutes. Those past the file's budget are left out before they're decoded.
fn oversized_embedded_bitmaps_are_left_out_before_decoding() {
// #3600: many records of the largest bitmap a record may hold cost minutes. Each of these claims
// more pixels than one image may have, so the reader leaves it out from its header. (The reader's
// budget for all the images of one file is tested where the reader is.)
let records = vec![(81, png_stretch_dibits(&png_claiming(1 << 13, 1 << 13))); 5];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert!(back.warnings.iter().any(|w| w == "images past the most pixels one file may hold were left out"), "{:?}", back.warnings);
assert!(!all(&back.document).iter().any(|n| matches!(n.kind, NodeKind::Image(_))));
}
#[test]
fn clips_nest_only_so_deep() {
// Each clip inside the last one used to nest a clipping group one level deeper, past the stack.
let mut records = vec![(30, le(&[0, 0, 1500, 1500])); 200_000];
records.push((43, le(&[100, 100, 200, 200])));
// Each clip inside the last one nests a clipping group one level deeper; past the stack they
// are left out with a warning.
let mut records = vec![];
// As many as the reader keeps: one more than the stack.
for i in 0..32 {
// BEGINPATH, a rectangle a little smaller each time, ENDPATH, SELECTCLIPPATH (RGN_AND).
records.push((59, vec![]));
records.push((43, le(&[100 + i, 100 + i, 2000 - i, 2000 - i])));
records.push((60, vec![]));
records.push((67, le(&[1])));
}
records.push((43, le(&[500, 500, 600, 600])));
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let mut depth = 0;
let mut n = back.document.layers[0].children().unwrap()[0].clone();
@@ -393,4 +539,324 @@ fn clips_nest_only_so_deep() {
}
assert_eq!(depth, vectorcraft_doc::clipnest::MAX_NEST);
assert!(back.warnings.iter().any(|w| w.contains("clips nested more than")), "{:?}", back.warnings);
// A hostile count of clip records: each one used to nest a clipping group one level deeper,
// past the stack. They make one clip.
let mut records = vec![(30, le(&[0, 0, 1500, 1500])); 200_000];
records.push((43, le(&[100, 100, 200, 200])));
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let layer = back.document.layers[0].children().unwrap();
assert_eq!(layer.len(), 1);
let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) };
assert!(children.iter().all(|c| !matches!(c.kind, NodeKind::Group { .. })), "one level");
assert_eq!(paths(&back.document).len(), 1);
}
/// An EMR_COMMENT holding EMF+ `records` (type, flags, data).
fn emf_plus(records: &[(u16, u16, Vec<u8>)]) -> Vec<u8> {
let mut plus = Out::default();
for (kind, flags, data) in records {
plus.u16(*kind);
plus.u16(*flags);
plus.u32(12 + data.len() as u32);
plus.u32(data.len() as u32);
plus.bytes(data);
}
let mut body = Out::default();
body.u32(4 + plus.len() as u32);
// "EMF+"
body.u32(0x2B46_4D45);
body.bytes(&plus.0);
body.0
}
fn le_f32(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
#[test]
fn emf_plus_only_pictures_import_their_drawing() {
// An EMF+ only file: its EMF records draw nothing, so it was imported empty with a warning.
// EmfPlusHeader (version, flags, 96 dpi), FillRects with an inline green color (flag S) and one
// rectangle of 10 × 5 mm at (10, 10) mm in device pixels, EmfPlusEndOfFile.
let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]);
let rects = [le(&[0xFF00_FF00u32 as i32, 1]), le_f32(&[1000.0, 1000.0, 1000.0, 500.0])].concat();
let comment = emf_plus(&[(0x4001, 0, header), (0x400A, 0x8000, rects), (0x4002, 0, vec![])]);
let back = import(&hand_emf(5000, 3000, &[(70, comment)])).unwrap();
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
let p = paths(&back.document);
assert_eq!(p.len(), 1);
assert_eq!(fill_rgb(&p[0]), Some([0, 255, 0]));
let mm = 72.0 / 25.4;
let b = p[0].geometric_bounds().unwrap();
assert!(near(b, Rect::new(10.0 * mm, 10.0 * mm, 20.0 * mm, 15.0 * mm), 0.01), "{b:?}");
}
#[test]
fn hatched_brushes_fill_with_their_average_color() {
// CREATEBRUSHINDIRECT: a hatched (style 2) blue brush, selected; a null pen; a rectangle. The
// hatch is drawn over the white background, so the average is a light blue.
let records = vec![(39, le(&[1, 2, 0x00ff_0000, 0])), (37, le(&[1])), (37, le(&[0x8000_0008u32 as i32])), (43, le(&[1000, 1000, 2000, 1500]))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(back.warnings, vec!["hatched and pattern brushes are filled with their average color".to_string()]);
let p = paths(&back.document);
assert_eq!(p.len(), 1);
let [r, g, b] = fill_rgb(&p[0]).unwrap();
assert!(b == 255 && r == g && r > 0 && r < 255, "{:?}", [r, g, b]);
// With a transparent background (SETBKMODE 1) the hatch is blue with gaps: a translucent fill.
let mut records = records;
records.insert(0, (18, le(&[1])));
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let p = paths(&back.document);
assert_eq!(fill_rgb(&p[0]), Some([0, 0, 255]));
let AppearanceItem::Fill(f) = &p[0].appearance.items[0] else { panic!("a fill") };
assert!(f.opacity > 0.0 && f.opacity < 1.0, "{}", f.opacity);
}
#[test]
fn text_keeps_a_stretch_across() {
// A world transform twice as wide as it is high, a 10 mm font and "Hi".
let mut text = vec![0; 16];
text.extend(le(&[1, 0, 0]));
text.extend(le(&[1000, 1500, 2, 76, 0, 0, 0, 0, 0, 0]));
text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes));
let mut font = le(&[2, -1000, 0, 0, 0, 400]);
font.extend([0u8; 8]);
font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes));
let world = [2.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect();
let records = vec![(35, world), (82, font), (37, le(&[2])), (84, text)];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let t = all(&back.document)
.into_iter()
.find_map(|n| match n.kind {
NodeKind::Text(t) => Some(t),
_ => None,
})
.unwrap();
let mm = 72.0 / 25.4;
assert!((t.runs[0].style.size - 10.0 * mm).abs() < 0.01, "{}", t.runs[0].style.size);
let [a, b, c, d, ..] = t.xf.as_coeffs();
assert!((a - 2.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6, "{:?}", t.xf);
}
#[test]
fn a_clip_whose_box_holds_the_picture_still_clips() {
// A diamond around the middle of the picture, whose box holds the whole frame but which cuts
// off its corners: BEGINPATH, POLYGON, ENDPATH, SELECTCLIPPATH (RGN_COPY), then a rectangle.
let mut diamond = le(&[0, 0, 0, 0, 4]);
diamond.extend(le(&[2500, -500, 5500, 1500, 2500, 3500, -500, 1500]));
// A bow tie through the four corners of a box around the picture.
let mut bow_tie = le(&[0, 0, 0, 0, 4]);
bow_tie.extend(le(&[-500, -500, 5500, 3500, 5500, -500, -500, 3500]));
// Two open figures through the four corners, the top edge and the bottom edge, which enclose
// nothing: MOVETOEX, LINETO, MOVETOEX, LINETO.
let edges = vec![(27, le(&[-500, -500])), (54, le(&[5500, -500])), (27, le(&[5500, 3500])), (54, le(&[-500, 3500]))];
// One figure through the four corners that runs back over its edges and encloses nothing:
// POLYLINE top-left, top-right, top-left, bottom-left, bottom-right, bottom-left.
let mut retraced = le(&[0, 0, 0, 0, 6]);
retraced.extend(le(&[-500, -500, 5500, -500, -500, -500, -500, 3500, 5500, 3500, -500, 3500]));
for clip in [vec![(3, diamond)], vec![(3, bow_tie)], edges, vec![(4, retraced)]] {
let records = [vec![(59, vec![])], clip, vec![(60, vec![]), (67, le(&[5])), (43, le(&[0, 0, 5000, 3000]))]].concat();
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let layer = back.document.layers[0].children().unwrap();
assert_eq!(layer.len(), 1);
assert!(matches!(layer[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", layer[0].kind);
}
}
#[test]
fn dual_emf_plus_files_draw_their_emf_plus_records() {
// A dual file (header flag 1): a translucent red EMF+ fill, and a plain rectangle that is only
// the fallback for readers of plain records.
let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]);
let rects = [le(&[0x80FF_0000u32 as i32, 1]), le_f32(&[1000.0, 1000.0, 1000.0, 500.0])].concat();
let comment = emf_plus(&[(0x4001, 1, header), (0x400A, 0x8000, rects), (0x4002, 0, vec![])]);
let back = import(&hand_emf(5000, 3000, &[(70, comment), (43, le(&[3000, 1000, 4000, 2000]))])).unwrap();
let p = paths(&back.document);
assert_eq!(p.len(), 1);
assert_eq!(fill_rgb(&p[0]), Some([255, 0, 0]));
let AppearanceItem::Fill(f) = &p[0].appearance.items[0] else { panic!("a fill") };
assert!((f.opacity - 128.0 / 255.0).abs() < 1e-6, "{}", f.opacity);
}
#[test]
fn translucent_strokes_drawn_one_after_another_stay_apart() {
// EmfPlusObject: pen 0, 1 pixel wide, with a solid brush of `argb`; then two EmfPlusDrawLines
// with it, from A to B and from B back to A.
let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]);
let lines = |argb: u32| {
let pen = [le(&[0xDBC0_1002u32 as i32, 0, 0, 2]), le_f32(&[1.0]), le(&[0xDBC0_1002u32 as i32, 0, argb as i32])].concat();
let a_to_b = [le(&[2]), le_f32(&[1000.0, 1000.0, 3000.0, 1000.0])].concat();
let b_to_a = [le(&[2]), le_f32(&[3000.0, 1000.0, 1000.0, 1000.0])].concat();
let comment = emf_plus(&[(0x4001, 0, header.clone()), (0x4008, 0x0200, pen), (0x400D, 0, a_to_b), (0x400D, 0, b_to_a), (0x4002, 0, vec![])]);
paths(&import(&hand_emf(5000, 3000, &[(70, comment)])).unwrap().document)
};
// Each translucent stroke keeps its own opacity, so where they overlap both show.
let p = lines(0x80FF_0000);
assert_eq!(p.len(), 2, "{p:?}");
for n in &p {
let AppearanceItem::Stroke(st) = &n.appearance.items[0] else { panic!("a stroke") };
assert!((st.opacity - 128.0 / 255.0).abs() < 1e-6, "{}", st.opacity);
}
// Opaque strokes still join into one path.
assert_eq!(lines(0xFFFF_0000).len(), 1);
}
#[test]
fn strokes_join_only_with_round_caps_round_joins_and_no_dashes() {
// CREATEPENINDIRECT: a 20-unit black pen of `style`, selected; then two lines one after the
// other that meet at a right angle.
let lines = |style: i16| {
let records = vec![
(0x02FA, [le16(&[style, 20, 0]), 0u32.to_le_bytes().to_vec()].concat()),
(0x012D, le16(&[0])),
(0x0214, le16(&[100, 100])),
(0x0213, le16(&[100, 700])),
(0x0213, le16(&[700, 700])),
];
paths(&import(&hand_wmf(1440, 1440, &records)).unwrap().document)
};
// Round caps and round joins, a solid line: one path, as a round join is the two round caps.
assert_eq!(lines(0).len(), 1);
// Flat caps and miter joins, flat caps alone and miter joins alone: each line keeps its caps.
for style in [0x2200, 0x0200, 0x2000] {
let p = lines(style);
assert_eq!(p.len(), 2, "style {style:#x}: {p:?}");
}
// PS_DASH: each line's dashes start at its own start.
let p = lines(1);
assert_eq!(p.len(), 2, "{p:?}");
assert!(p.iter().all(|n| n.appearance.stroke().is_some_and(|st| st.dash.is_some())), "{p:?}");
}
#[test]
fn pattern_brushes_fill_with_their_average_color() {
// CREATEDIBPATTERNBRUSHPT: a 2 × 2 tile of 24-bit pixels, two red and two blue (bottom-up rows
// padded to 4 bytes); selected, a null pen, a rectangle.
let mut brush = le(&[1, 0, 32, 40, 72, 16]);
brush.extend(le(&[40, 2, 2, 0x0018_0001, 0, 0, 0, 0, 0, 0]));
brush.extend([0, 0, 255, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0]);
let records = vec![(94, brush), (37, le(&[1])), (37, le(&[0x8000_0008u32 as i32])), (43, le(&[1000, 1000, 2000, 1500]))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(back.warnings, vec!["hatched and pattern brushes are filled with their average color".to_string()]);
let p = paths(&back.document);
assert_eq!(p.len(), 1);
let [r, g, b] = fill_rgb(&p[0]).unwrap();
assert!((126..=128).contains(&r) && g == 0 && (126..=128).contains(&b), "{:?}", [r, g, b]);
}
#[test]
fn clipped_text_is_clipped_to_its_rectangle() {
// EXTTEXTOUTW with ETO_CLIPPED and a rectangle of 9–12 × 10–16 mm, in an underlined and struck
// through font.
let mut text = vec![0; 16];
text.extend(le(&[1, 0, 0]));
text.extend(le(&[1000, 1500, 2, 76, 4, 900, 1000, 1200, 1600, 0]));
text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes));
let mut font = le(&[2, -1000, 0, 0, 0, 400]);
font.extend([0, 1, 1, 0, 0, 0, 0, 0]);
font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes));
let mut records = vec![(82, font), (37, le(&[2])), (84, text)];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let layer = back.document.layers[0].children().unwrap();
assert_eq!(layer.len(), 1);
let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) };
let mm = 72.0 / 25.4;
let own = Rect::new(9.0 * mm, 10.0 * mm, 12.0 * mm, 16.0 * mm);
assert!(near(children[0].geometric_bounds().unwrap(), own, 0.01));
let NodeKind::Text(t) = &children[1].kind else { panic!("text") };
assert!(t.runs[0].style.underline && t.runs[0].style.strikethrough);
// Under clip paths nested as deep as the stack, the text's own clip is still the innermost.
for i in 0..32 {
records.insert(0, (67, le(&[1])));
records.insert(0, (60, vec![]));
records.insert(0, (43, le(&[100 + i, 100 + i, 4000 - i, 2500 - i])));
records.insert(0, (59, vec![]));
}
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let mut n = back.document.layers[0].children().unwrap()[0].clone();
while let NodeKind::Group { children, clip: true } = &n.kind
&& matches!(children.last().map(|c| &c.kind), Some(NodeKind::Group { .. }))
{
n = children.last().unwrap().clone();
}
let NodeKind::Group { children, clip: true } = &n.kind else { panic!("a clipping group: {:?}", n.kind) };
assert!(near(children[0].geometric_bounds().unwrap(), own, 0.01), "{:?}", children[0].geometric_bounds());
assert!(matches!(children[1].kind, NodeKind::Text(_)));
}
#[test]
fn excluded_clip_rectangles_clip() {
// EXCLUDECLIPRECT cuts the top-left of the picture out of the clip; the rectangle crosses it.
// The clip it cuts from is the picture's bounds (5000 × 3000 device pixels).
let records = vec![(29, le(&[0, 0, 1500, 1500])), (43, le(&[1000, 1000, 2000, 1500]))];
let mut bytes = hand_emf(5000, 3000, &records);
for (i, v) in [0i32, 0, 5000, 3000].iter().enumerate() {
bytes[8 + i * 4..12 + i * 4].copy_from_slice(&v.to_le_bytes());
}
let back = import(&bytes).unwrap();
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
let layer = back.document.layers[0].children().unwrap();
assert_eq!(layer.len(), 1);
assert!(matches!(layer[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", layer[0].kind);
}
#[test]
fn shapes_under_the_same_clip_share_one_clipping_group() {
let records = vec![(30, le(&[0, 0, 1500, 1500])), (43, le(&[100, 100, 200, 200])), (43, le(&[300, 300, 400, 400]))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let layer = back.document.layers[0].children().unwrap();
assert_eq!(layer.len(), 1);
let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) };
assert_eq!(children.len(), 3, "the clip and both rectangles");
}
#[test]
fn a_record_whose_size_is_not_a_multiple_of_4_ends_the_file() {
let records = vec![(43, le(&[100, 100, 200, 200])), (43, le(&[300, 300, 400, 400])), (43, le(&[500, 500, 600, 600]))];
let mut bytes = hand_emf(5000, 3000, &records);
// The second rectangle's size, after the header and the first rectangle.
let header = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize;
let first = u32::from_le_bytes(bytes[header + 4..header + 8].try_into().unwrap()) as usize;
let at = header + first + 4;
let size = u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap());
bytes[at..at + 4].copy_from_slice(&(size + 2).to_le_bytes());
let back = import(&bytes).unwrap();
assert_eq!(paths(&back.document).len(), 1);
assert_eq!(back.warnings, vec!["the file ends early: what it held was imported".to_string()]);
}
#[test]
fn wmf_with_an_inverted_placeable_box_is_read_at_its_units_an_inch() {
// The box runs from right to left, so it gives no size: the window (1440 units square, one inch
// at the header's 1440 units an inch) does. The rectangle is its top-left quarter.
let records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), (0x041B, le16(&[720, 720, 0, 0]))];
let mut bytes = hand_wmf(1440, 1440, &records);
bytes[6..8].copy_from_slice(&1440i16.to_le_bytes());
bytes[10..12].copy_from_slice(&0i16.to_le_bytes());
let back = import(&bytes).unwrap();
assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{:?}", back.document.artboards[0].rect);
let p = paths(&back.document);
assert_eq!(p.len(), 1);
assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 36.0, 36.0), 1e-6), "{:?}", p[0].geometric_bounds());
}
#[test]
fn emf_without_a_frame_is_read_at_its_device_resolution() {
// An empty frame, and bounds of 5000 × 3000 device pixels at 100 pixels a millimetre.
let mut bytes = hand_emf(0, 0, &[(43, le(&[1000, 1000, 2000, 1500]))]);
for (i, v) in [0i32, 0, 5000, 3000].iter().enumerate() {
bytes[8 + i * 4..12 + i * 4].copy_from_slice(&v.to_le_bytes());
}
let back = import(&bytes).unwrap();
let mm = 72.0 / 25.4;
assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 50.0 * mm, 30.0 * mm), 0.01), "{:?}", back.document.artboards[0].rect);
let p = paths(&back.document);
assert_eq!(p.len(), 1);
assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(10.0 * mm, 10.0 * mm, 20.0 * mm, 15.0 * mm), 0.01), "{:?}", p[0].geometric_bounds());
// A device 50 mm high: 200 pixels a millimetre down, so everything is half as tall.
bytes[84..88].copy_from_slice(&50i32.to_le_bytes());
let back = import(&bytes).unwrap();
assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 50.0 * mm, 15.0 * mm), 0.01), "{:?}", back.document.artboards[0].rect);
let p = paths(&back.document);
assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(10.0 * mm, 5.0 * mm, 20.0 * mm, 7.5 * mm), 0.01), "{:?}", p[0].geometric_bounds());
}
+5 -3
View File
@@ -45,6 +45,11 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha
let set = &opts.settings;
set.check()?;
vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?;
// The pages come from the artboards, which baking leaves as they are. The version a long page
// raises the file to decides whether the layers are written, so it is settled before baking.
let pages = pages(doc, opts)?;
let raised = for_long_pages(set, &pages)?;
let set = raised.as_ref().unwrap_or(set);
// Live geometry effects export as their result, in symbols' art too; raster effects are
// reported below.
// Only the layers this export writes place their instances' art (see `ex.non_printing` and
@@ -57,9 +62,6 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha
// Baking stops early when cancelled, leaving a half-baked copy that must not be written.
vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?;
let doc = baked.as_ref().unwrap_or(doc);
let pages = pages(doc, opts)?;
let raised = for_long_pages(set, &pages)?;
let set = raised.as_ref().unwrap_or(set);
// The file's Title is File Info's; the page information names the document, as its tab does.
let title = crate::pdfx::title(set.standard, opts.title.clone().unwrap_or_else(|| doc.info_title().to_owned()));
+10 -3
View File
@@ -14,6 +14,11 @@ struct Measured {
members: Vec<Measured>,
}
/// Box `b` grown by `reach`, the room brush art can paint past it; `b` itself when `reach` is 0.
fn brushed(b: Option<Rect>, reach: f64) -> Option<Rect> {
if reach > 0.0 { b.map(|b| b.inflate(reach, reach)) } else { b }
}
#[cfg(test)]
std::thread_local! {
/// The objects this thread has measured for the walk and for the links (tests).
@@ -312,15 +317,17 @@ impl Exporter<'_> {
krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity)
}
/// The box of `n`, and of the members of a plain group or layer.
/// The box of `n`, and of the members of a plain group or layer. A box grows by the room brush
/// art can paint past the brushed strokes of `n` and of the objects in it
/// ([`vectorcraft_brush::reach_within`]), as the renderer culls it.
fn measure(&self, n: &Node) -> Measured {
if !matches!(n.kind, NodeKind::Layer { clip: false, .. } | NodeKind::Group { clip: false, .. }) {
#[cfg(test)]
MEASURES.with(|m| m.set(m.get() + 1));
return Measured { bounds: n.visual_bounds_with(&self.symbols), members: vec![] };
return Measured { bounds: brushed(n.visual_bounds_with(&self.symbols), vectorcraft_brush::reach_within(n)), members: vec![] };
}
let members: Vec<_> = n.editing_children().iter().map(|c| self.measure(c)).collect();
Measured { bounds: n.visual_of_members(members.iter().map(|m| m.bounds)), members }
Measured { bounds: brushed(n.visual_of_members(members.iter().map(|m| m.bounds)), vectorcraft_brush::reach(n)), members }
}
pub(super) fn node(&mut self, s: &mut Surface, n: &Node, page: Rect, force: bool) {
+8 -4
View File
@@ -71,7 +71,9 @@ pub struct TileGrid {
/// Calls `f` with the bounds of each object of `n` that prints: visible, not on a template
/// layer and not a guide (layers are already picked by the Print Layers option). Symbol
/// instances are measured by their art from `symbols`.
/// instances are measured by their art from `symbols`. A box grows by the room brush art can
/// paint past the brushed strokes of the object and of the objects in it
/// ([`vectorcraft_brush::reach_within`]).
fn printed(n: &Node, symbols: &SymbolBoxes, f: &mut impl FnMut(Rect)) {
if !n.visible {
return;
@@ -85,7 +87,8 @@ fn printed(n: &Node, symbols: &SymbolBoxes, f: &mut impl FnMut(Rect)) {
}
_ => {
if let Some(b) = n.visual_bounds_with(symbols) {
f(b);
let reach = vectorcraft_brush::reach_within(n);
f(if reach > 0.0 { b.inflate(reach, reach) } else { b });
}
}
}
@@ -102,9 +105,10 @@ fn has_art(doc: &Document, r: Rect) -> bool {
any
}
/// The bounds of all the art that prints.
/// The bounds of all the art that prints, with the brush art it paints. The box of a symbol
/// instance whose art holds brushed strokes grows as in [`has_art`].
fn art_bounds(doc: &Document) -> Option<Rect> {
let symbols = doc.symbol_boxes();
let symbols = doc.symbol_boxes().with_brush_art();
let mut all: Option<Rect> = None;
for l in &doc.layers {
printed(l, &symbols, &mut |b| all = Some(all.map_or(b, |a| a.union(b))));
+71
View File
@@ -246,6 +246,77 @@ fn an_instance_whose_brush_art_reaches_the_page_is_written() {
assert!(close(l[0].geometric_bounds().unwrap(), Rect::new(-15.0, 30.0, 5.0, 70.0), 0.01), "{:?}", l[0].geometric_bounds());
}
/// A 200 × 100 pt document whose 3 pt. Round brush paints a 20 pt round nib.
fn doc_with_wide_nib() -> Document {
let mut d = doc(200.0, 100.0);
let mut lib = vectorcraft_brush::library(&d);
let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else {
panic!("the 3 pt. Round brush")
};
c.size = 20.0;
vectorcraft_brush::store(&mut d, &lib);
d
}
/// A line from (`x`, 40) to (`x`, 60) with a 1 pt black stroke, painted by the 3 pt. Round brush
/// when `brushed`.
fn nib_line(x: f64, brushed: bool) -> Node {
let mut stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
if brushed {
stroke.stroke_mut().unwrap().brush = Some("3 pt. Round".into());
}
Node::path(NodeId(0), shapes::line((x, 40.0).into(), (x, 60.0).into()), stroke)
}
#[test]
fn a_path_whose_brush_art_reaches_the_page_is_written() {
// The line at x = -5 lies left of the page, and the 20 pt nib paints 10 pt either side of it,
// onto the page: alone, in a group, in a knockout group and as a compound path.
let compound = |n: Node| {
let mut c = Node::new(NodeId(0), NodeKind::Compound { children: vec![Arc::new(nib_line(-5.0, false))], rule: FillRule::NonZero });
c.appearance = n.appearance;
c
};
let knockout = |n: Node| {
let mut g = Node::group(NodeId(0), vec![Arc::new(n), Arc::new(rect_node(Rect::new(150.0, 10.0, 170.0, 30.0), Color::rgb(0.0, 0.0, 1.0)))]);
g.knockout = vectorcraft_doc::Knockout::On;
g
};
let group = |n: Node| Node::group(NodeId(0), vec![Arc::new(n)]);
let wraps: [(&str, &dyn Fn(Node) -> Node); 4] =
[("path", &|n| n), ("group", &group), ("knockout group", &knockout), ("compound path", &compound)];
for (what, wrap) in wraps {
let mut d = doc_with_wide_nib();
add(&mut d, wrap(nib_line(-5.0, true)));
let out = roundtrip(&d);
let nib: Vec<Rect> = leaves(&out).iter().filter_map(|n| n.geometric_bounds()).filter(|b| b.x1 < 100.0).collect();
assert_eq!(nib.len(), 1, "{what}: the nib's art, {nib:?}");
assert!(close(nib[0], Rect::new(-15.0, 30.0, 5.0, 70.0), 0.01), "{what}: {nib:?}");
}
// Without its brush, or 100 pt left of the page, where the nib does not reach it, the line is
// left out.
for line in [nib_line(-5.0, false), nib_line(-100.0, true)] {
let mut d = doc_with_wide_nib();
add(&mut d, line);
assert!(leaves(&roundtrip(&d)).is_empty());
}
// A clipping path left of the page keeps the nib's art off it.
let mut d = doc_with_wide_nib();
let clip = Node::new(
NodeId(0),
NodeKind::Path {
path: shapes::rectangle(Rect::new(-30.0, 0.0, -2.0, 100.0)),
rule: FillRule::NonZero,
live: None,
clipping: true,
guide: false,
},
);
add(&mut d, Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(nib_line(-5.0, true))], clip: true }));
let out = roundtrip(&d);
assert!(leaves(&out).is_empty(), "{:?}", leaves(&out));
}
/// The live effects in a symbol's art apply where the instance places the art, as on the canvas:
/// the symbol's square at (10, 40), which a Transform effect moves 100 pt right, is written at
/// (110, 40).
+31
View File
@@ -131,6 +131,37 @@ fn pdf_layers_import_back_as_layers() {
}
}
/// A hidden layer written as a PDF layer places the live effects of its instances' symbol art,
/// also in a PDF/A-2b file at PDF 1.4 whose 17,000 pt page has it written as PDF 1.6: the symbol's
/// square from x = 10 to 40, which a Transform effect moves 100 pt right, is written from x = 110
/// to 140.
#[test]
fn a_hidden_layer_places_symbol_art_effects_when_a_long_page_raises_the_version() {
let mut d = Document::new(17_000.0, 300.0);
d.layers.clear();
let mut square = rect(&mut d, 10.0, RED);
square.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true });
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: square.into() });
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: vectorcraft_geom::Affine::IDENTITY });
let mut l = Node::layer(d.alloc_id(), "Hidden", LayerColor::Preset(0));
l.visible = false;
if let NodeKind::Layer { children, .. } = &mut l.kind {
children.push(instance.into());
}
d.layers.push(l.into());
for compatibility in [Compatibility::Pdf14, Compatibility::Pdf16] {
let settings = PdfSettings { standard: Standard::PdfA2b, compatibility, create_layers: true, ..PdfSettings::default() };
let r = export_with_report(&d, &PdfOptions { settings, created: Some(1_791_200_000), ..Default::default() }).unwrap();
assert!(r.bytes.starts_with(b"%PDF-1.6"), "{compatibility:?}");
let back = import_with_report(&r.bytes, &ImportOptions::default()).unwrap().document;
let hidden = back.layers.iter().find(|l| l.name.as_deref() == Some("Hidden")).expect("the hidden layer");
let art = hidden.children().unwrap();
assert_eq!(art.len(), 1, "{compatibility:?}");
let b = art[0].geometric_bounds().unwrap();
assert!((b.x0 - 110.0).abs() < 0.1 && (b.x1 - 140.0).abs() < 0.1, "{compatibility:?}: {b:?}");
}
}
/// The rows of `nodes` in paint order, depth first: `depth name visible` for layers, `depth fill`
/// for art.
fn tree(nodes: &[std::sync::Arc<Node>], depth: usize, out: &mut Vec<String>) {
+56
View File
@@ -451,6 +451,62 @@ fn a_symbol_instances_brush_art_keeps_its_artboard_printed() {
assert!(p[0].1.iter().any(|(_, paint)| rgb8(paint) == [255, 0, 0]), "{p:?}");
}
#[test]
fn a_brushed_paths_brush_art_keeps_its_artboard_printed_and_framed() {
// A line from (-5, 40) to (-5, 60) with a 1 pt red stroke painted by a 20 pt round nib, alone,
// in a group or as the art of a symbol instance: the line lies left of the artboard, and the nib
// paints 10 pt either side of it, onto the artboard.
let line = || {
let mut stroke = Appearance::basic(Paint::None, rgb(1.0, 0.0, 0.0), 1.0);
stroke.stroke_mut().unwrap().brush = Some("3 pt. Round".into());
Node::path(vectorcraft_doc::NodeId(0), shapes::line((-5.0, 40.0).into(), (-5.0, 60.0).into()), stroke)
};
for what in ["path", "group", "symbol instance"] {
let mut d = doc(100.0, 100.0, &[]);
let mut lib = vectorcraft_brush::library(&d);
let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else {
panic!("the 3 pt. Round brush")
};
c.size = 20.0;
vectorcraft_brush::store(&mut d, &lib);
let mut n = match what {
"path" => line(),
"group" => Node::group(vectorcraft_doc::NodeId(0), vec![Arc::new(line())]),
_ => {
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Nib".into(), art: Arc::new(line()) });
Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Nib".into(), xf: vectorcraft_geom::Affine::IDENTITY })
}
};
n.id = d.alloc_id();
let layer = d.default_layer().unwrap();
d.insert(Some(layer), 0, n).unwrap();
// Skip Blank Artboards keeps the artboard, and its page holds the nib's art.
let p = pages(&job(&d, json!({"skipBlank": true})).bytes);
assert_eq!(p.len(), 1, "{what}");
assert!(p[0].1.iter().any(|(_, paint)| rgb8(paint) == [255, 0, 0]), "{what}: {p:?}");
// Ignoring artboards, the page holds all the nib's art, 20 × 40 pt.
let pv = preview(&d, &settings(json!({"artboards": "ignore"}))).unwrap();
let t = pv.sheets[0].trim;
assert!(t[2] - t[0] >= 20.0 && t[3] - t[1] >= 40.0, "{what}: {t:?}");
}
// A compound path is painted with its own appearance: the brushed stroke left on its path
// paints nothing, and the artboard stays blank.
let mut d = doc(100.0, 100.0, &[]);
let kind = NodeKind::Compound { children: vec![Arc::new(line())], rule: vectorcraft_geom::FillRule::NonZero };
let mut compound = Node::new(d.alloc_id(), kind);
compound.appearance = Appearance::basic(Paint::None, rgb(1.0, 0.0, 0.0), 1.0).into();
let layer = d.default_layer().unwrap();
d.insert(Some(layer), 0, compound).unwrap();
assert!(preview(&d, &settings(json!({"skipBlank": true}))).is_err());
// A brushed stroke without a paint draws no brush art: the artboard stays blank.
let mut d = doc(100.0, 100.0, &[]);
let mut unpainted = line();
unpainted.id = d.alloc_id();
unpainted.appearance.stroke_mut().unwrap().paint = Paint::None;
d.insert(Some(layer), 0, unpainted).unwrap();
assert!(preview(&d, &settings(json!({"skipBlank": true}))).is_err());
}
#[test]
fn symbol_art_effects_print_where_they_draw() {
// A red square and the symbol's blue square, each moved 100 pt right by a Transform effect,
+5 -5
View File
@@ -155,19 +155,19 @@ pub(crate) fn path_cull_bounds(symbols: &SymbolBoxes, n: &Node, visual: impl FnO
/// How far brush art can paint past `n`'s brushed strokes, or past the brushed strokes in the art
/// of symbol instance `n`: `16 × w + 8`, where `w` is the widest stroke (at least 1) of `n` when it
/// has a visible brushed stroke and of the objects in that art that have one
/// has a visible brushed stroke with a paint and of the objects in that art that have one
/// ([`SymbolBoxes::brush_width`]) or the pieces live-effect plug-ins paint for them
/// ([`crate::fx::painted_brush_width`]), and 0 when neither has one.
/// ([`crate::fx::painted_brush_width`]), and 0 when neither has one. The room for `n`'s own strokes
/// is [`vectorcraft_brush::reach`], which the exports leave too.
pub(crate) fn pad(symbols: &SymbolBoxes, n: &Node) -> f64 {
let own = vectorcraft_brush::has_brush(n)
.then(|| n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max));
let own = vectorcraft_brush::reach(n);
let art = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } => {
symbols.brush_width(symbol).into_iter().chain(crate::fx::painted_brush_width(symbols, symbol)).reduce(f64::max).map(|w| w.max(1.0))
}
_ => None,
};
own.into_iter().chain(art).reduce(f64::max).map_or(0.0, |w| 16.0 * w + 8.0)
art.map_or(own, |w| own.max(16.0 * w + 8.0))
}
pub use vectorcraft_brush::instance_art;
+4
View File
@@ -194,6 +194,10 @@ pub(crate) fn type_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props {
if st.proportional_metrics {
v.push("\"palt\" 1".into());
}
// The East Asian glyph form: its one feature.
if let Some(tag) = st.glyph_form.feature().and_then(|t| std::str::from_utf8(t).ok()) {
v.push(format!("\"{tag}\" 1"));
}
if !v.is_empty() {
p.push(("font-feature-settings", v.join(", ")));
}
+10 -5
View File
@@ -508,12 +508,17 @@ impl ColorPainter for Tree<'_> {
return;
};
let Some(clip) = self.groups.get(at).and_then(|g| g.clip.clone()) else { return };
if at + 1 == self.groups.len()
&& let Some(g) = self.groups.last_mut()
{
g.flooded = g.children.is_empty();
}
let innermost = at + 1 == self.groups.len();
let before = self.groups.last().map_or(0, |g| g.children.len());
self.fill_path(&clip, &brush);
// Flooded only when this fill added the group's first child. A fill that paints nothing
// adds none and leaves the flag as it was, so the clip stays around what comes after it.
if innermost
&& let Some(g) = self.groups.last_mut()
&& g.children.len() > before
{
g.flooded = before == 0;
}
}
/// The glyph's outline filled, the brush moved by `brush_transform` (the glyph stays).
+3
View File
@@ -319,6 +319,9 @@ impl OtFeatures {
v.push(f(&t, u32::from(s.extra_values.get(i).copied().unwrap_or(0).max(1))));
}
}
if let Some(tag) = st.glyph_form.feature() {
v.push(f(tag, true));
}
if self.vertical {
// Not `vrt2`: its glyphs are already turned on their side, and the layout turns Latin
// and digits itself (they would lie upside down, and tate-chu-yoko break).
+14
View File
@@ -304,6 +304,20 @@ impl FontFace {
self.gsub.get_or_init(|| GsubIndex::read(self))
}
/// Does the face's `GSUB` table have feature `tag` with at least one lookup? At most
/// [`MAX_FEATURES`] feature records are read; false when the face has no `GSUB` table or it
/// cannot be read.
pub fn has_substitution_feature(&self, tag: [u8; 4]) -> bool {
let Some(font) = self.skrifa() else { return false };
let Some(features) = font.gsub().ok().and_then(|g| g.feature_list().ok()) else { return false };
features
.feature_records()
.iter()
.take(MAX_FEATURES)
.filter(|r| r.feature_tag().to_be_bytes() == tag)
.any(|r| r.feature(features.offset_data()).is_ok_and(|f| !f.lookup_list_indices().is_empty()))
}
/// What the features `aalt`, `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99`, `hist`,
/// `jalt`, `nalt`, `ornm` and `titl` of the face's `GSUB` table substitute for glyph `gid`, in
/// that order of features and within a feature in lookup order: the glyph of each single
+1
View File
@@ -86,6 +86,7 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool {
no_break,
language,
glyph_alternate,
glyph_form: _,
fill,
stroke,
stroke_width,
+8 -3
View File
@@ -287,6 +287,10 @@ fn place_block(g: &mut [SGlyph], s: &WariStyle, (vertical, whole): (bool, bool))
let rtl = !vertical && g.first().is_some_and(|gl| gl.level.is_rtl());
let (inset, outset) = if rtl { (after, before) } else { (before, after) };
let length = inset + block + outset;
// How far the glyphs reach above and below the line's baseline, each from its block line's
// baseline.
let above = g.iter().zip(&places).map(|(gl, p)| gl.ascent - p.1).fold(0.0, f64::max);
let below = g.iter().zip(&places).map(|(gl, p)| gl.descent + p.1).fold(0.0, f64::max);
let glyphs = g.len();
for (i, (gl, (along, across, advance))) in g.iter_mut().zip(places).enumerate() {
let em = gl.face.units_per_em() * gl.sy / r;
@@ -300,9 +304,10 @@ fn place_block(g: &mut [SGlyph], s: &WariStyle, (vertical, whole): (bool, bool))
if i + 1 < glyphs {
gl.keeps_next = true;
}
// The line keeps the height of the block's own size, and holds the whole stack.
gl.ascent = (ascent / r).max(-top);
gl.descent = (descent / r).max(bottom);
// The line keeps the height of the block's own size, and holds the whole stack with each
// block line's glyphs.
gl.ascent = (ascent / r).max(-top).max(above);
gl.descent = (descent / r).max(bottom).max(below);
if s.auto_leading {
gl.leading /= r;
}
+7 -3
View File
@@ -1028,6 +1028,8 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool {
no_break,
language,
glyph_alternate,
// An OpenType feature over its own characters, like `features`.
glyph_form: _,
} = a;
// Keep PartialEq's non-reflexive behavior for ignored numeric fields, without cloning styles.
let offsets = (standard_vertical_roman, tcy_up_down, tcy_left_right);
@@ -1096,7 +1098,7 @@ pub(crate) fn warichu_alike(a: &CharStyle, b: &CharStyle) -> bool {
/// character style's name, leading, baseline shift, rotation, Character Alignment, Character
/// Direction (text is shaped apart where its bidi level changes), Kashidas, the kerning (each glyph takes its
/// run's, see [`shape_segment`]), the space before a line's first character ([`space_before`]),
/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the OpenType features (each run's apply to its own characters, as features
/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the OpenType features and the East Asian glyph form (each run's apply to its own characters, as features
/// over a range of the one buffer) and the tracking, as long as the tracking keeps or drops
/// standard ligatures alike ([`crate::features::ligatures_suppressed_by`]).
fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
@@ -1159,6 +1161,8 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
no_break,
language,
glyph_alternate,
// Applied as a feature over its run's own characters, with `features`.
glyph_form: _,
} = a;
*font_family == b.font_family
&& warichu_alike(a, b)
@@ -1442,8 +1446,8 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
let mut ranged = Vec::new();
for (r, run_style) in runs.get(source_runs.clone()).unwrap_or_default() {
let (a, b) = (r.start.max(range.start), r.end.min(range.end));
if run_style.features != base_style.features && a < b {
let own = variant(&CharStyle { features: run_style.features.clone(), ..base_style.clone() });
if (run_style.features != base_style.features || run_style.glyph_form != base_style.glyph_form) && a < b {
let own = variant(&CharStyle { features: run_style.features.clone(), glyph_form: run_style.glyph_form, ..base_style.clone() });
ranged_features(base, &own, a..b, &mut ranged);
}
}
+43
View File
@@ -288,6 +288,49 @@ fn a_glyph_filled_with_one_colour_is_one_path() {
assert_eq!(fill(only), Paint::solid(rgb(COLR_RED)));
}
/// A fill that paints nothing (a palette index past the palette) followed by another glyph
/// inside the same glyph's clip keeps the clip: the second glyph is drawn clipped to the first,
/// not on its own.
#[test]
fn a_fill_that_paints_nothing_keeps_the_clip_around_the_glyph_after_it() {
use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList};
use write_fonts::types::GlyphId16;
let bytes = colr_font(false).unwrap();
let read = skrifa::FontRef::new(&bytes).unwrap();
let gid = |ch| GlyphId16::new(u16::try_from(read.charmap().map(ch).unwrap().to_u32()).unwrap());
let mut colr = Colr::new(0, None, None, 0);
let paint = ColrPaint::glyph(ColrPaint::colr_layers(2, 0), gid('O'));
colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(gid(COLOUR_CHAR), paint)])).into();
colr.layer_list = Some(LayerList::new(2, vec![solid(99), ColrPaint::glyph(solid(0), gid('I'))])).into();
let font = crate::test_fonts::colr_font_with("Colrtest Empty Fill", &colr).unwrap();
let root = art(&font, COLOUR_CHAR);
let [clipped] = children(&root) else { panic!("{:?}", children(&root).iter().map(|c| c.kind_label()).collect::<Vec<_>>()) };
assert!(matches!(clipped.kind, NodeKind::Group { clip: true, .. }), "the `O` still clips: {}", clipped.kind_label());
let [clip, inner] = children(clipped) else { panic!("{:?}", children(clipped).iter().map(|c| c.kind_label()).collect::<Vec<_>>()) };
assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{}", clip.kind_label());
assert_eq!(fill(inner), Paint::solid(rgb(COLR_RED)));
}
/// A fill that paints nothing after a colour flooding the glyph leaves it that glyph filled:
/// one path, as without the empty fill.
#[test]
fn a_fill_that_paints_nothing_after_a_flood_keeps_one_path() {
use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList};
use write_fonts::types::GlyphId16;
let bytes = colr_font(false).unwrap();
let read = skrifa::FontRef::new(&bytes).unwrap();
let gid = |ch| GlyphId16::new(u16::try_from(read.charmap().map(ch).unwrap().to_u32()).unwrap());
let mut colr = Colr::new(0, None, None, 0);
let paint = ColrPaint::glyph(ColrPaint::colr_layers(2, 0), gid('O'));
colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(gid(COLOUR_CHAR), paint)])).into();
colr.layer_list = Some(LayerList::new(2, vec![solid(0), solid(99)])).into();
let font = crate::test_fonts::colr_font_with("Colrtest Flood Then Empty", &colr).unwrap();
let root = art(&font, COLOUR_CHAR);
let [only] = children(&root) else { panic!("{:?}", children(&root).iter().map(|c| c.kind_label()).collect::<Vec<_>>()) };
assert!(matches!(only.kind, NodeKind::Path { .. }), "{}", only.kind_label());
assert_eq!(fill(only), Paint::solid(rgb(COLR_RED)));
}
/// A sweep glyph in a font without clip boxes, its base glyph without an outline (the space's,
/// as COLRv1 fonts make them): its image is as large as what it paints.
#[test]
+37
View File
@@ -2041,3 +2041,40 @@ fn soft_return_breaks_line_even_inside_no_break() {
let lay = layout(db(), &t);
assert_eq!(lay.lines.len(), 2, "soft return honors line break despite no_break");
}
/// An East Asian glyph form (the Glyphs panel menu's Traditional Forms, JIS 78 Forms, …) draws
/// the characters with the font's glyphs of that form, and Default with its default glyphs. Needs
/// craft-fonts' BIZ UDMincho, which has traditional, expert, JIS 78, 83 and 90, full-width and
/// half-width forms and no JIS 04 forms (skipped without it). A form on one character of a run
/// changes that character only.
#[test]
fn glyph_forms_draw_the_fonts_east_asian_forms() {
use vectorcraft_doc::GlyphForm;
const FAMILY: &str = "BIZ UDMincho";
if db().face(FAMILY, "Regular").is_none_or(|f| f.family != FAMILY) {
eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)");
return;
}
let st = |form| CharStyle { size: 20.0, font_family: FAMILY.into(), glyph_form: form, ..CharStyle::default() };
let glyphs = |text: &str, form| layout(db(), &TextObject::point(Point::ZERO, text, st(form))).glyphs;
let gids = |text: &str, form| glyphs(text, form).iter().map(|g| g.gid).collect::<Vec<_>>();
for (form, text) in
[(GlyphForm::Traditional, "亜"), (GlyphForm::Expert, "唖"), (GlyphForm::Jis78, "唖"), (GlyphForm::Jis83, "芦"), (GlyphForm::Jis90, "芦")]
{
assert_ne!(gids(text, form), gids(text, GlyphForm::Default), "{form:?} {text}");
}
// The font has no JIS 04 forms, so the characters keep their glyphs.
assert_eq!(gids("亜唖芦", GlyphForm::Jis04), gids("亜唖芦", GlyphForm::Default));
// Full-width Latin takes a whole em, half-width punctuation half of one.
let advance = |text: &str, form| glyphs(text, form).first().map_or(0.0, |g| g.advance);
assert!(advance("A", GlyphForm::Default) < 15.0, "{}", advance("A", GlyphForm::Default));
assert!((advance("A", GlyphForm::FullWidth) - 20.0).abs() < 0.01, "{}", advance("A", GlyphForm::FullWidth));
assert!((advance("、", GlyphForm::Default) - 20.0).abs() < 0.01, "{}", advance("、", GlyphForm::Default));
assert!((advance("、", GlyphForm::HalfWidth) - 10.0).abs() < 0.01, "{}", advance("、", GlyphForm::HalfWidth));
// Traditional Forms on the middle character only.
let mut t = TextObject::point(Point::ZERO, "亜亜亜", st(GlyphForm::Default));
edit::style_range(&mut t.runs, 3, 6, |s| s.glyph_form = GlyphForm::Traditional);
let ids: Vec<u32> = layout(db(), &t).glyphs.iter().map(|g| g.gid).collect();
let (plain, traditional) = (gids("亜", GlyphForm::Default), gids("亜", GlyphForm::Traditional));
assert_eq!(ids, [plain[0], traditional[0], plain[0]]);
}
+18
View File
@@ -626,6 +626,24 @@ fn a_block_of_several_fonts_keeps_the_tallest_of_them() {
assert!(first_short.0 >= plain[pair.0].0 - 1e-6 && first_short.1 >= deepest - 1e-6, "{first_short:?} {plain:?}");
}
/// The line holds each block line's characters at their own height: with a wide Line Gap, the
/// ascent of the top block line's characters and the descent of the bottom one's stay inside the
/// line.
#[test]
fn a_wide_line_gap_keeps_the_outer_block_lines_inside_the_line() {
let small = layout(db(), &point("x", style(10.0)));
let (ascent, descent) = (small.lines[0].ascent, small.lines[0].descent);
for lines in [2, 3] {
let l = layout(db(), &with_block("cdefgh", CharStyle { warichu_lines: lines, warichu_gap: 20.0, ..marked(20.0) }));
let line = &l.lines[0];
let block = &l.glyphs[2..8];
let top = block.iter().map(|g| g.origin.y).fold(f64::INFINITY, f64::min);
let bottom = block.iter().map(|g| g.origin.y).fold(f64::NEG_INFINITY, f64::max);
assert!(line.baseline - line.ascent <= top - ascent + 1e-6, "{lines}: {} {} {top} {ascent}", line.baseline, line.ascent);
assert!(line.baseline + line.descent >= bottom + descent - 1e-6, "{lines}: {} {} {bottom} {descent}", line.baseline, line.descent);
}
}
/// Warichu Settings on characters not marked Warichu leave their shaping alone: "fi" keeps its
/// ligature when only the f has other settings.
#[test]
+1 -1
View File
@@ -134,7 +134,7 @@ impl Tool for EnclosingLassoTool {
let symbols = cx.doc.symbol_boxes();
let region = (points.len() >= 3).then(|| Region::new(polygon(&points, true))).flatten();
let mut ids = if let Some(region) = region {
enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation)
enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline)
.into_iter()
.filter(|id| cx.doc.node(*id).is_some_and(|n| node_inside(n, &symbols, &region)))
.collect()
@@ -367,3 +367,25 @@ fn enclosing_lasso_considers_the_geometry_a_visible_compound_paints() {
);
}
}
/// A loop around clipped art that the clipping path's own shape holds, but not the region a live
/// effect moved it to, selects the art in Outline view only, which draws the clipping path without
/// its effects.
#[test]
fn outline_view_loops_measure_clipped_art_by_the_plain_clipping_path() {
let (d, _, art) = doc_with_moved_clip_region();
let s = Selection::default();
let p = paint();
let around = [(410.0, 410.0), (490.0, 410.0), (490.0, 490.0), (410.0, 490.0)];
let gesture = |outline: bool| {
let cx = ToolContext { outline, ..cx(&d, &s, &p) };
let mut tool = crate::create(ID);
tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 410.0, 410.0));
for &(x, y) in &around[1..] {
tool.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y));
}
tool.pointer(&cx, &PointerEvent::new(PointerKind::Up, 410.0, 490.0))
};
assert_eq!(gesture(true), vec![Action::Exec("select.set".into(), json!({"ids": [art.0]}))]);
assert_eq!(gesture(false), vec![Action::Exec("select.set".into(), json!({"ids": []}))]);
}
+4 -4
View File
@@ -55,7 +55,7 @@ use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use serde_json::{Value, json};
use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline};
use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline_in_view};
use vectorcraft_doc::{AnchorRef, Node, NodeId, NodeKind, Selection, symbol_overrides};
use vectorcraft_geom::{Anchor, PathData, PathSeg, Point, Rect, Vec2};
@@ -1029,7 +1029,7 @@ impl Tool for DirectSelectionTool {
out.extend(self.mesh.overlays(cx, &|id| cx.selection.contains(id)));
if !self.group {
if let Some(sp) = &cx.selection.symbol_part
&& let Some(path) = cx.doc.node(sp.instance).and_then(|n| symbol_part_outline(cx.doc, n, &sp.path))
&& let Some(path) = cx.doc.node(sp.instance).and_then(|n| symbol_part_outline_in_view(cx.doc, n, &sp.path, cx.hit_options()))
{
out.push(Overlay::Path { path, color: cx.doc.layer_color(sp.instance), width: 1.0, dashed: false });
}
@@ -1608,7 +1608,7 @@ impl DirectSelectionTool {
// (members of groups too), each whole, as a click selects one; with an Alt-marquee, every
// object it touches, each whole.
if enclosed || whole {
let mut touched = vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true);
let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline);
let editable = cx.doc.editable();
touched.retain(|id| editable(*id));
let picked = if enclosed { crate::select::inside(cx, r, touched) } else { touched };
@@ -1680,7 +1680,7 @@ impl DirectSelectionTool {
}
// Objects without anchors to pick (type, images, symbols…) are selected whole when
// the marquee touches them, as with the Selection tool (#927).
for id in vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true) {
for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline) {
let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }));
if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) {
sel.push((id, vec![]));
+23
View File
@@ -2396,3 +2396,26 @@ fn type_on_a_path_shows_and_drags_its_paths_handles() {
assert!((v["x"].as_f64().unwrap() - 400.0).abs() < 1e-9, "Shift keeps it straight above its anchor: {v}");
assert!(handles(&ToolContext { handles_multiple: false, ..cx(&d, &s, &p) }).is_empty());
}
/// An Alt-marquee across clipped art where the clipping path's own shape, but not the region a
/// live effect moved it to, lets it show selects the art in Outline view only, which draws the
/// clipping path without its effects.
#[test]
fn outline_view_marquees_measure_clipped_art_by_the_plain_clipping_path() {
let (d, _, art) = doc_with_moved_clip_region();
let s = Selection::default();
let p = paint();
let alt = Mods { alt: true, ..Mods::default() };
let marquee = |outline: bool| {
let c = ToolContext { outline, ..cx(&d, &s, &p) };
let mut t = DirectSelectionTool::new(false);
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 440.0, 410.0).with_mods(alt));
t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 460.0, 430.0).with_mods(alt));
t.pointer(&c, &PointerEvent::new(PointerKind::Up, 460.0, 430.0).with_mods(alt))
};
let selects = |a: &[Action]| a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([art.0])));
let a = marquee(true);
assert!(selects(&a), "outline: {a:?}");
let a = marquee(false);
assert!(!selects(&a), "preview: {a:?}");
}
+30
View File
@@ -450,6 +450,36 @@ pub(crate) mod testutil {
(d, g, clip, art)
}
/// A document with the rectangle of [`doc_with_rect`] and a clip group whose clipping path,
/// (400, 400)–(500, 500), has a live effect that moves the region it clips to 100 pt right
/// (registered with [`vectorcraft_doc::hit::set_clip_region`]), over art at (420, 420)–(480, 480),
/// inside the clipping path's own shape and outside the moved region: the document, the clip
/// group and the art.
pub fn doc_with_moved_clip_region() -> (Document, NodeId, NodeId) {
fn moved(clip: &Node) -> Option<Option<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)>> {
let mut moves = false;
clip.walk(&mut |n| moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move"));
if !moves {
return None;
}
Some(vectorcraft_doc::hit::clip_regions(clip).into_iter().next().map(|(mut bp, rule)| {
bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0)));
(bp, rule)
}))
}
vectorcraft_doc::hit::set_clip_region(moved);
let (mut d, _) = doc_with_rect();
let l = d.layers[0].id;
let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
let mut path = Node::path(clip, shapes::rectangle(Rect::new(400.0, 400.0, 500.0, 500.0)), Default::default());
path.appearance.effects.push(vectorcraft_doc::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
let picture = Node::path(art, shapes::rectangle(Rect::new(420.0, 420.0, 480.0, 480.0)), Appearance::default_art());
let group =
Node::new(g, vectorcraft_doc::NodeKind::Group { children: vec![std::sync::Arc::new(path), std::sync::Arc::new(picture)], clip: true });
d.insert(Some(l), 1, group).unwrap();
(d, g, art)
}
/// A new layer of `d`, above the others, with the unpainted rectangle `mask` as its clipping
/// mask and `art` clipped by it: the layer and the clipping mask.
pub fn add_masked_layer(d: &mut Document, mask: Rect, art: Node) -> (NodeId, NodeId) {
+2 -2
View File
@@ -40,7 +40,7 @@ use std::cell::RefCell;
use std::collections::HashMap;
use serde_json::{Value, json};
use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee, objects_at, selected_hidden_at};
use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee_in_view, objects_at, selected_hidden_at};
use vectorcraft_doc::{NodeId, OrientedBox};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
@@ -1157,7 +1157,7 @@ impl Tool for SelectionTool {
if r.width() < Self::drag_threshold(cx) && r.height() < Self::drag_threshold(cx) {
return if toggle { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] };
}
let touched = marquee(cx.doc, r, cx.isolation, false);
let touched = marquee_in_view(cx.doc, r, cx.isolation, false, cx.outline);
let enclosed = marquee_enclosed(cx, enclosed, marquee_direction(cx, start, p, directional_inside));
let ids = if enclosed { inside(cx, r, touched) } else { touched };
let art = Action::Exec(if toggle { "select.toggle" } else { "select.set" }.into(), json!({ "ids": json_ids(&ids) }));
+19
View File
@@ -2646,3 +2646,22 @@ fn outline_view_click_through_an_image_selects_the_path_behind() {
assert!(!selects(&a, back), "preview, {picked:?} selected: {a:?}");
}
}
/// A marquee across clipped art where the clipping path's own shape, but not the region a live
/// effect moved it to, lets it show reaches the clip group in Outline view only, which draws the
/// clipping path without its effects.
#[test]
fn outline_view_marquees_measure_a_clip_group_by_its_plain_clipping_path() {
let (d, g, _) = doc_with_moved_clip_region();
let s = Selection::default();
let p = paint();
let marquee = |outline: bool| {
let cx = ToolContext { outline, ..cx(&d, &s, &p) };
let mut t = SelectionTool::default();
t.pointer(&cx, &ev(PointerKind::Down, 440.0, 410.0));
t.pointer(&cx, &ev(PointerKind::Drag, 460.0, 430.0));
t.pointer(&cx, &ev(PointerKind::Up, 460.0, 430.0))
};
assert_eq!(marquee(true), vec![Action::Exec("select.set".into(), json!({"ids": [g.0]}))]);
assert_eq!(marquee(false), vec![Action::Exec("select.set".into(), json!({"ids": []}))]);
}
+12 -12
View File
@@ -241,19 +241,19 @@ pub fn preset(name: &str) -> Option<TraceParams> {
// many as its tones need where it is not.
// (Color detail 85: a colour on a hundredth of the picture is still one of its colours.)
"auto color" => TraceParams { palette: Palette::Automatic, color_detail: 85.0, ..color(6, 65.0, 60.0, 16, Method::Abutting) },
"high fidelity photo" => color(64, 90.0, 25.0, 4, Method::Overlapping),
"low fidelity photo" => color(20, 60.0, 50.0, 12, Method::Overlapping),
"3 colors" => color(3, 60.0, 60.0, 20, Method::Abutting),
"6 colors" => color(6, 65.0, 60.0, 16, Method::Abutting),
"16 colors" => color(16, 70.0, 55.0, 10, Method::Abutting),
"shades of gray" => TraceParams { mode: Mode::Grayscale, colors: 8, paths: 60.0, corners: 50.0, noise: 10, method: Method::Overlapping, ..d },
"black and white logo" => bw(128, 95.0, 80.0, 8, true),
"sketched art" => bw(150, 50.0, 50.0, 100, false),
"silhouettes" => bw(200, 40.0, 60.0, 30, false),
"line art" => bw(128, 80.0, 70.0, 10, false),
"technical drawing" => bw(128, 95.0, 90.0, 4, true),
"high fidelity photo" => color(64, 50.0, 50.0, 5, Method::Overlapping),
"low fidelity photo" => color(20, 50.0, 50.0, 10, Method::Overlapping),
"3 colors" => color(3, 50.0, 50.0, 15, Method::Abutting),
"6 colors" => color(6, 50.0, 50.0, 15, Method::Abutting),
"16 colors" => color(16, 50.0, 50.0, 15, Method::Abutting),
"shades of gray" => TraceParams { mode: Mode::Grayscale, colors: 8, paths: 50.0, corners: 50.0, noise: 15, method: Method::Overlapping, ..d },
"black and white logo" => bw(128, 50.0, 75.0, 25, true),
"sketched art" => bw(150, 50.0, 50.0, 20, false),
"silhouettes" => bw(200, 50.0, 50.0, 90, false),
"line art" => bw(128, 50.0, 75.0, 20, false),
"technical drawing" => bw(128, 50.0, 100.0, 1, true),
// Black outlines: lines as stroked centre lines, wider areas as stroked outlines.
"outline" => TraceParams { fills: false, strokes: true, ..bw(128, 80.0, 70.0, 10, false) },
"outline" => TraceParams { fills: false, strokes: true, ..bw(128, 50.0, 75.0, 20, false) },
// Flat-colour logos: colours found automatically, edges placed to a fraction of a pixel.
"flat logo" => TraceParams { mode: Mode::Logo, colors: 8, paths: 60.0, corners: 50.0, noise: 6, snap_curves_to_lines: true, ..d },
_ => return None,
+29
View File
@@ -892,6 +892,35 @@ fn presets_resolve() {
assert!(preset("nope").is_none());
}
#[test]
fn presets_have_their_paths_corners_and_noise() {
let expected: &[(&str, f64, f64, u32)] = &[
("Default", 50.0, 75.0, 25),
("High Fidelity Photo", 50.0, 50.0, 5),
("Low Fidelity Photo", 50.0, 50.0, 10),
("3 Colors", 50.0, 50.0, 15),
("6 Colors", 50.0, 50.0, 15),
("16 Colors", 50.0, 50.0, 15),
("Shades of Gray", 50.0, 50.0, 15),
("Black and White Logo", 50.0, 75.0, 25),
("Sketched Art", 50.0, 50.0, 20),
("Silhouettes", 50.0, 50.0, 90),
("Line Art", 50.0, 75.0, 20),
("Technical Drawing", 50.0, 100.0, 1),
("Outline", 50.0, 75.0, 20),
];
for &(name, paths, corners, noise) in expected {
let p = preset(name).unwrap();
assert_eq!((p.paths, p.corners, p.noise), (paths, corners, noise), "{name}");
}
// The color counts stay as they were.
let colors: Vec<u32> = ["High Fidelity Photo", "Low Fidelity Photo", "3 Colors", "6 Colors", "16 Colors", "Shades of Gray"]
.iter()
.map(|n| preset(n).unwrap().colors)
.collect();
assert_eq!(colors, [64, 20, 3, 6, 16, 8]);
}
#[test]
fn params_json_roundtrip_and_partial() {
let p = preset("6 Colors").unwrap();
+179 -50
View File
@@ -1,16 +1,22 @@
//! Apply SVG Filter (Effect › SVG Filters › Apply SVG Filter…): the document's SVG filters in a
//! list. OK applies the selected one to the selection as a live effect (`svgFilter.apply`), or,
//! opened from the Appearance panel for an applied SVG filter, puts it in that effect's place
//! (`effect.setParams`). New and Edit open the filter's code under the list; Save adds the filter
//! or replaces the one being edited (`svgFilter.define`). Delete removes the selected filter
//! (`svgFilter.delete`) and Import… adds the filters of an SVG file (`svgFilter.import`). Those
//! act at once. Effect › SVG Filters lists the same filters below its first items.
//! Apply SVG Filter (Effect › SVG Filters › Apply SVG Filter…): the default SVG filters and the
//! document's own in a list, the defaults first. OK applies the selected one to the selection as a
//! live effect, or, opened from the Appearance panel for an applied SVG filter, puts it in that
//! effect's place (`svgFilter.apply`, with `index`). New and Edit open the filter's code under the
//! list; Save adds the filter or replaces the one being edited (`svgFilter.define`). Delete
//! removes the selected filter (`svgFilter.delete`) and Import… adds the filters of an SVG file
//! (`svgFilter.import`). Those act at once. Effect › SVG Filters lists the same filters below its
//! first items.
//!
//! A default is not in the document until it is applied or edited: the document then holds a copy
//! under the default's name, which is listed in the default's place. Delete is off for a default
//! the document holds no copy of.
//!
//! Fields: `selected` (a filter's name), `code` (the code being edited), `editing` (`""`, `"new"`
//! or the name of the filter being edited), and with an applied effect `__index`, `__item` and
//! `missing` (the name of a deleted filter the effect names).
use serde_json::{Value, json};
use vectorcraft_effects::svg_filter::defaults::{DEFAULT_FILTERS, Listed, default_filter, listed};
use vectorcraft_engine::doc::SvgFilter;
use super::DialogSpec;
@@ -25,20 +31,21 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Apply SVG Filter…").trim_end_matches('…').to_string(),
body,
confirm,
ok_enabled: Some(|app, d| d.str("editing").is_empty() && filters(app).iter().any(|f| f.name == d.str("selected"))),
ok_enabled: Some(|app, d| d.str("editing").is_empty() && filters(app).0.iter().any(|f| f.filter.name == d.str("selected"))),
min_width: 440.0,
..DialogSpec::FORM
};
/// The active document's SVG filters.
fn filters(app: &VectorcraftApp) -> Vec<SvgFilter> {
app.session.active().map(|st| st.doc.svg_filters.clone()).unwrap_or_default()
/// The filters the dialog lists for the active document, and how many come first as the defaults.
fn filters(app: &VectorcraftApp) -> (Vec<Listed>, usize) {
listed(app.session.active().map(|st| st.doc.svg_filters.as_slice()).unwrap_or_default())
}
/// `ui.svgFilterDialog {index?, item?}`: open Apply SVG Filter for the active document; with
/// `index`, for the applied SVG filter at `index` of `item` (null: the object's effects): the
/// document's filter of its name selected; when the document has none of its name, the name shown
/// above the list if the filter was deleted, or else its code open as a new filter.
/// document's filter of its name selected, or the default of its name when the effect draws with
/// the default's code or with nothing; when neither has its name, the name shown above the list if
/// the filter was deleted, or else its code open as a new filter.
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
if app.session.active().is_none() {
return Err("no document open".into());
@@ -53,17 +60,19 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let e = applied.get(k as usize).filter(|e| e.id == vectorcraft_effects::SVG_FILTER).ok_or_else(|| format!("no SVG filter at index {k}"))?;
let name = e.params.get("name").and_then(Value::as_str).unwrap_or_default().to_string();
let xml = e.params.get("xml").and_then(Value::as_str).unwrap_or_default().to_string();
let held = filters(app).into_iter().find(|f| f.name == name);
match held {
// The document's filter it names: selected.
Some(_) => fields["selected"] = json!(name),
let held = app.session.active().is_some_and(|st| st.doc.svg_filters.iter().any(|f| f.name == name));
// A default the document holds no copy of, when the effect draws with its code or with nothing.
let default = default_filter(&name).is_some_and(|d| xml.is_empty() || xml == d.xml);
if held || default {
// The filter it names: selected.
fields["selected"] = json!(name);
} else if xml.is_empty() {
// Deleted from the document: shown above the list, not selectable; OK waits for a choice.
None if xml.is_empty() => fields["missing"] = json!(name),
fields["missing"] = json!(name);
} else {
// A filter the document doesn't hold (from an opened file): its code, to add it.
None => {
fields["code"] = json!(xml);
fields["editing"] = json!("new");
}
fields["code"] = json!(xml);
fields["editing"] = json!("new");
}
fields["__index"] = json!(k);
// As given: `null` is the object's own effects, and none is the active item's.
@@ -75,33 +84,39 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
Ok(Value::Null)
}
/// OK: the selected filter to the selection, or in the applied effect's place.
/// OK: the selected filter to the selection, or in the applied effect's place. A default the
/// document holds no copy of is copied into it in the same undo step.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let name = d.str("selected");
let f = filters(app).into_iter().find(|f| f.name == name).ok_or("select an SVG filter")?;
let r = match d.fields.get("__index").and_then(Value::as_u64) {
Some(k) => {
let mut p = json!({ "index": k, "params": { "name": f.name, "xml": f.xml } });
if let Some(item) = d.fields.get("__item") {
p["item"] = item.clone();
}
app.run("effect.setParams", p)?
let f = filters(app).0.into_iter().find(|f| f.filter.name == name).ok_or("select an SVG filter")?;
let mut p = json!({ "name": f.filter.name });
if let Some(k) = d.fields.get("__index").and_then(Value::as_u64) {
p["index"] = json!(k);
if let Some(item) = d.fields.get("__item") {
p["item"] = item.clone();
}
None => app.run("svgFilter.apply", json!({ "name": f.name }))?,
};
}
let r = app.run("svgFilter.apply", p)?;
app.ui.dialog = None;
Ok(r)
}
/// The active document's filter names, mirrored for the (static) menu tree ([`sync`]).
/// The names of the active document's filters that are not a default's, mirrored for the (static)
/// menu tree ([`sync`]).
fn names_store() -> &'static std::sync::RwLock<Vec<&'static str>> {
static NAMES: std::sync::OnceLock<std::sync::RwLock<Vec<&'static str>>> = std::sync::OnceLock::new();
NAMES.get_or_init(Default::default)
}
/// Mirror the active document's SVG filter names for the menu tree (cheap when unchanged).
/// The names of `held`, a document's filters, that are not a default's, in their order.
fn own_names(held: &[SvgFilter]) -> Vec<String> {
held.iter().filter(|f| default_filter(&f.name).is_none()).map(|f| f.name.clone()).collect()
}
/// Mirror the active document's SVG filter names for the menu tree (cheap when unchanged). A
/// filter with a default's name is the menu's entry of that name already.
pub fn sync(app: &VectorcraftApp) {
let names: Vec<String> = app.session.active().map(|st| st.doc.svg_filters.iter().map(|f| f.name.clone()).collect()).unwrap_or_default();
let names: Vec<String> = app.session.active().map(|st| own_names(&st.doc.svg_filters)).unwrap_or_default();
let same = names_store().read().map(|v| v.len() == names.len() && v.iter().zip(&names).all(|(a, b)| *a == b)).unwrap_or(true);
if !same {
if let Ok(mut v) = names_store().write() {
@@ -111,20 +126,23 @@ pub fn sync(app: &VectorcraftApp) {
}
}
/// Effect › SVG Filters: Apply SVG Filter…, Import SVG Filter… and then the active document's
/// filters, each applying itself to the selection.
/// Effect › SVG Filters: Apply SVG Filter…, Import SVG Filter…, the default filters and then the
/// active document's other filters, each applying itself to the selection.
pub fn menu_items() -> Vec<crate::menus::Item> {
items_for(names_store().read().map(|v| v.clone()).unwrap_or_default())
}
/// [`menu_items`] for filters named `names`.
/// [`menu_items`] for a document whose filters that are not a default's are named `names`.
fn items_for(names: Vec<&'static str>) -> Vec<crate::menus::Item> {
use crate::menus::Item;
let apply = |n: &'static str| Item::Cmd(n, "svgFilter.apply", json!({ "name": n }));
let mut v =
vec![Item::Cmd("Apply SVG Filter…", "ui.svgFilterDialog", Value::Null), Item::Cmd("Import SVG Filter…", "ui.importSvgFilter", Value::Null)];
v.push(Item::Sep);
v.extend(DEFAULT_FILTERS.iter().map(|d| apply(d.name)));
if !names.is_empty() {
v.push(Item::Sep);
v.extend(names.into_iter().map(|n| Item::Cmd(n, "svgFilter.apply", json!({ "name": n }))));
v.extend(names.into_iter().map(apply));
}
v
}
@@ -170,7 +188,8 @@ enum Action {
}
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let list = filters(app);
let (list, defaults) = filters(app);
let held = list.iter().filter(|f| !f.default).count();
let selected = d.str("selected");
let editing = d.str("editing");
let mut act = None;
@@ -184,7 +203,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
if !missing.is_empty() {
ui.add_enabled_ui(false, |ui| ui.selectable_label(false, missing.as_str()));
}
for f in &list {
for (i, Listed { filter: f, .. }) in list.iter().enumerate() {
// The document's other filters follow the defaults, below a line.
if i == defaults && i > 0 {
ui.separator();
}
let r = ui.selectable_label(f.name == selected, f.name.as_str());
if r.double_clicked() && editing.is_empty() {
act = Some(Action::Edit(f.name.clone()));
@@ -195,17 +218,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
});
});
ui.add_space(6.0);
let has = list.iter().any(|f| f.name == selected);
let chosen = list.iter().find(|f| f.filter.name == selected);
let has = chosen.is_some();
// A default the document holds no copy of has nothing to delete.
let deletable = chosen.is_some_and(|f| !f.default);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
let idle = editing.is_empty();
if ui.add_enabled_ui(idle && list.len() < SvgFilter::MAX, |ui| widgets::flat_button(ui, tl!("New"), 64.0)).inner.clicked() {
if ui.add_enabled_ui(idle && held < SvgFilter::MAX, |ui| widgets::flat_button(ui, tl!("New"), 64.0)).inner.clicked() {
act = Some(Action::New);
}
if ui.add_enabled_ui(idle && has, |ui| widgets::flat_button(ui, tl!("Edit"), 64.0)).inner.clicked() {
act = Some(Action::Edit(selected.clone()));
}
if ui.add_enabled_ui(idle && has, |ui| widgets::flat_button(ui, tl!("Delete"), 64.0)).inner.clicked() {
if ui.add_enabled_ui(idle && deletable, |ui| widgets::flat_button(ui, tl!("Delete"), 64.0)).inner.clicked() {
act = Some(Action::Delete);
}
if crate::picks::can(app, &PickRequest::Open(pick()))
@@ -245,7 +271,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
Ok(())
}
Some(Action::Edit(name)) => {
if let Some(f) = list.iter().find(|f| f.name == name) {
if let Some(f) = list.iter().map(|f| &f.filter).find(|f| f.name == name) {
d.fields.insert("selected".into(), json!(f.name));
d.fields.insert("editing".into(), json!(f.name));
d.fields.insert("code".into(), json!(f.xml));
@@ -322,7 +348,9 @@ mod tests {
crate::menus::invoke(&mut app, "ui.svgFilterDialog", json!({}));
let mut d = app.ui.dialog.clone().unwrap();
assert_eq!(d.kind, KIND);
assert!(frame(&mut app, &mut d).iter().any(|t| t == "Shift"), "the filter's name, as it is");
// Below the defaults, which fill the rows the list shows at first.
assert_eq!(filters(&app).0.last().map(|f| f.filter.name.as_str()), Some("Shift"), "the filter's name, as it is");
assert!(!frame(&mut app, &mut d).is_empty());
assert!(!(SPEC.ok_enabled.unwrap())(&app, &d), "nothing selected");
d.fields.insert("selected".into(), json!("Shift"));
assert!((SPEC.ok_enabled.unwrap())(&app, &d));
@@ -411,11 +439,30 @@ mod tests {
use crate::menus::Item;
let ids =
|items: &[Item]| items.iter().map(|i| if let Item::Cmd(l, c, p) = i { format!("{l} {c} {p}") } else { "—".into() }).collect::<Vec<_>>();
assert_eq!(ids(&items_for(vec![])), ["Apply SVG Filter… ui.svgFilterDialog null", "Import SVG Filter… ui.importSvgFilter null"]);
// The defaults follow the commands in every document, and with no document.
let plain = ids(&items_for(vec![]));
assert_eq!(
ids(&items_for(vec!["Shift", "A (1)"]))[2..],
["—", "Shift svgFilter.apply {\"name\":\"Shift\"}", "A (1) svgFilter.apply {\"name\":\"A (1)\"}"]
plain[..4],
[
"Apply SVG Filter… ui.svgFilterDialog null",
"Import SVG Filter… ui.importSvgFilter null",
"—",
"Soft Blur svgFilter.apply {\"name\":\"Soft Blur\"}"
]
);
assert_eq!(plain.len(), 3 + DEFAULT_FILTERS.len());
assert_eq!(plain.last().map(String::as_str), Some("Hue Shift svgFilter.apply {\"name\":\"Hue Shift\"}"));
// The document's other filters come below them.
let with = ids(&items_for(vec!["Shift", "A (1)"]));
assert_eq!(with[..plain.len()], plain[..]);
assert_eq!(with[plain.len()..], ["—", "Shift svgFilter.apply {\"name\":\"Shift\"}", "A (1) svgFilter.apply {\"name\":\"A (1)\"}"]);
// A document's filter with a default's name is that default's entry.
let held = [
SvgFilter { name: "Glow".into(), xml: String::new() },
SvgFilter { name: "Shift".into(), xml: String::new() },
SvgFilter { name: "glow".into(), xml: String::new() },
];
assert_eq!(own_names(&held), ["Shift", "glow"]);
let mut app = app();
assert!(!crate::menus::enabled(&app, "svgFilter.apply"), "nothing selected");
app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
@@ -423,6 +470,88 @@ mod tests {
assert_eq!(crate::menus::display_label(&app, "svgFilter.apply", "Shift"), "Shift", "a filter's name as it is");
}
/// The steps in the active document's undo history.
fn steps(app: &VectorcraftApp) -> usize {
app.session.active().unwrap().history.undo.len()
}
#[test]
fn a_default_is_listed_first_and_ok_copies_it_into_the_document() {
let mut app = app();
app.session.execute("svgFilter.define", &json!({"xml": SHIFT})).unwrap();
let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
open(&mut app, &json!({})).unwrap();
let mut d = app.ui.dialog.clone().unwrap();
let (list, defaults) = filters(&app);
let names: Vec<&str> = list.iter().map(|f| f.filter.name.as_str()).collect();
assert_eq!((defaults, names.len()), (DEFAULT_FILTERS.len(), DEFAULT_FILTERS.len() + 1));
assert_eq!((names[0], names[defaults - 1], names[defaults]), ("Soft Blur", "Hue Shift", "Shift"), "the defaults, then the document's own");
assert!(frame(&mut app, &mut d).iter().any(|t| t == "Soft Blur"), "a default's name, as it is");
d.fields.insert("selected".into(), json!("Soft Shadow"));
assert!((SPEC.ok_enabled.unwrap())(&app, &d), "a default can be applied");
let before = steps(&app);
confirm(&mut app, &d).unwrap();
assert_eq!(steps(&app), before + 1, "one undo step");
let doc = &app.session.active().unwrap().doc;
assert_eq!(doc.svg_filters.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["Shift", "Soft Shadow"]);
let fx = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects;
assert_eq!((fx.len(), fx[0].params["name"].as_str()), (1, Some("Soft Shadow")));
assert_eq!(fx[0].params["xml"].as_str(), default_filter("Soft Shadow").map(|f| f.xml));
// Opened for that effect, the document's copy is selected; OK with another default puts it
// in the effect's place and copies it, in one step.
app.run("effect.dialog", json!({"effect": "svg.filter", "index": 0, "item": null})).unwrap();
let mut d = app.ui.dialog.clone().unwrap();
assert_eq!((d.str("selected").as_str(), d.str("editing").as_str()), ("Soft Shadow", ""));
d.fields.insert("selected".into(), json!("Invert"));
let before = steps(&app);
confirm(&mut app, &d).unwrap();
assert_eq!(steps(&app), before + 1);
let doc = &app.session.active().unwrap().doc;
let fx = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects;
assert_eq!((fx.len(), fx[0].params["name"].as_str()), (1, Some("Invert")), "in its place, not added");
assert_eq!(doc.svg_filters.len(), 3);
}
/// Edit on a default opens its code, and Save keeps the edited copy in the document under the
/// default's name; an effect that names a default the document no longer holds selects it.
#[test]
fn an_edited_default_is_saved_in_the_document() {
let mut app = app();
let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
// Save, as its button does for the default being edited.
let edited = r#"<filter id="Thin"><feMorphology operator="erode" radius="3"/></filter>"#;
let r = app.run("svgFilter.define", json!({"xml": edited, "replace": "Thin"})).unwrap();
assert_eq!(r["name"], "Thin");
assert_eq!(filters(&app).0.iter().filter(|f| !f.default).map(|f| f.filter.xml.as_str()).collect::<Vec<_>>(), [edited]);
assert_eq!(filters(&app).0.len(), DEFAULT_FILTERS.len(), "in the default's place");
app.session.execute("svgFilter.apply", &json!({"name": "Thin"})).unwrap();
// Deleted: the default is listed again, and the effect that names it selects the default.
app.session.execute("svgFilter.delete", &json!({"name": "Thin"})).unwrap();
assert!(filters(&app).0.iter().all(|f| f.default));
app.run("effect.dialog", json!({"effect": "svg.filter", "index": 0, "item": null})).unwrap();
let d = app.ui.dialog.clone().unwrap();
assert_eq!((d.str("selected").as_str(), d.str("missing").as_str(), d.str("editing").as_str()), ("Thin", "", ""));
confirm(&mut app, &d).unwrap();
let doc = &app.session.active().unwrap().doc;
let fx = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects;
assert_eq!(fx[0].params["xml"].as_str(), default_filter("Thin").map(|f| f.xml), "the default again");
// An applied filter with a default's name and other code opens as code to save.
let e = vectorcraft_doc::Effect {
id: "svg.filter".into(),
params: json!({"name": "Glow", "xml": "<filter id=\"Glow\"><feOffset dx=\"1\"/></filter>"}),
visible: true,
};
app.session
.edit("Plant", |d, _| {
d.node_mut(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects = vec![e];
Ok(())
})
.unwrap();
app.run("effect.dialog", json!({"effect": "svg.filter", "index": 0, "item": null})).unwrap();
let d = app.ui.dialog.clone().unwrap();
assert_eq!((d.str("editing").as_str(), d.str("selected").as_str()), ("new", ""));
}
#[test]
fn new_saves_the_code_and_selects_the_filter() {
let mut app = app();
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1253,7 +1253,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.svgFilterDialog",
"Apply SVG Filter…",
"",
"{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's filters; OK runs svgFilter.apply with selected, or effect.setParams on the applied effect; New and Edit open the code, Save runs svgFilter.define, Delete runs svgFilter.delete and Import… svgFilter.import with a picked SVG file",
"{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's defaults (the document's filter of a default's name in its place) and then the document's other filters; OK runs svgFilter.apply with selected, and with index and item for the applied effect; New and Edit open the code, Save runs svgFilter.define (replace: the filter edited, a default included), Delete runs svgFilter.delete (off for a default the document holds no copy of) and Import… svgFilter.import with a picked SVG file",
),
(
"ui.importSvgFilter",
+14
View File
@@ -108,6 +108,20 @@ pub(crate) fn shared<T: PartialEq>(app: &VectorcraftApp, f: impl Fn(&CharStyle)
shared_styles(app, |_, _, style, _| Some(f(style)))
}
/// The fonts (family and style) of the character styles the panels act on ([`shared`]), each
/// once, in the order the runs come.
pub(crate) fn selected_fonts(app: &VectorcraftApp) -> Vec<(String, String)> {
let fonts = std::cell::RefCell::new(Vec::<(String, String)>::new());
shared_styles(app, |_, _, style, _| {
let mut fonts = fonts.borrow_mut();
if !fonts.iter().any(|(family, face)| *family == style.font_family && *face == style.font_style) {
fonts.push((style.font_family.clone(), style.font_style.clone()));
}
Some(())
});
fonts.into_inner()
}
/// Dimensional controls use document units and tolerate arithmetic roundoff when comparing
/// compensated runs. Keep raw styles available to font/paragraph controls and style definitions,
/// even if a collapsed affine prevents editing dimensions.
+161 -2
View File
@@ -9,12 +9,14 @@
//! that glyph as one of its alternates in its word. A glyph no feature reaches whose name does
//! not belong to another letter is applied as a glyph choice, which may not join. Other glyphs
//! are drawn dimmed, and their tooltips say why they cannot be applied to the selection.
//! With Show East Asian Options, the panel menu sets the selected characters' East Asian glyph
//! form ([`glyph_form_items`]).
use std::collections::HashMap;
use egui::{Color32, Sense, Stroke, StrokeKind, Ui, vec2};
use serde_json::json;
use vectorcraft_doc::{CharStyle, NodeId, NodeKind};
use vectorcraft_doc::{CharStyle, GlyphForm, NodeId, NodeKind};
use vectorcraft_geom::{Affine, BezPath, PathEl};
use vectorcraft_text::FontDb;
@@ -904,11 +906,115 @@ fn zoom_button(ui: &mut Ui, id: &str, label: &str, tip: &str, enabled: bool) ->
resp.on_hover_text(tl!(tip)).clicked() && enabled
}
pub fn menu(_app: &mut VectorcraftApp, ui: &mut Ui) {
/// The menu label of East Asian glyph form `form` ([`GlyphForm::ALL`]).
fn glyph_form_label(form: GlyphForm) -> &'static str {
match form {
GlyphForm::Traditional => "Traditional Forms",
GlyphForm::Expert => "Expert Forms",
GlyphForm::Jis04 => "JIS 04 Forms",
GlyphForm::Jis90 => "JIS 90 Forms",
GlyphForm::Jis78 => "JIS 78 Forms",
GlyphForm::Jis83 => "JIS 83 Forms",
GlyphForm::FullWidth => "Monospaced Full-Width Forms",
GlyphForm::HalfWidth => "Monospaced Half-Width Forms",
GlyphForm::ThirdWidth => "Monospaced Third-Width Forms",
GlyphForm::QuarterWidth => "Monospaced Quarter-Width Forms",
GlyphForm::Default => "Revert To Default Forms",
}
}
/// The ids of the faces that draw the characters [`glyph_form_items`] acts on: the faces the
/// fonts of their styles name, and the faces layout draws them with, fallback faces included:
/// the Type tool's selected range (every frame of its story after Select All in threaded text,
/// the whole text object at a caret), else every frame of the selected stories. Laid out once for
/// each document revision, selection and set of fonts while the menu is open, overflow text
/// included.
fn selection_faces(app: &VectorcraftApp, ui: &Ui) -> Vec<u32> {
type Key = (u64, u64, u64, Option<(NodeId, usize, usize)>, Vec<NodeId>);
let editing = super::character::text_editing(app).map(|(id, a, b)| (id, a.min(b), a.max(b)));
let Some(state) = app.session.active() else { return vec![] };
let story = super::character::text_story(app);
let stories = match editing {
Some(_) => story.clone().unwrap_or_default(),
None => super::character::selected_stories(app),
};
let db = FontDb::global();
let key: Key = (state.uid, state.revision, db.generation(), editing, stories);
let slot = ui.scope_id().with("gl-form-faces");
if let Some((cached, ids)) = ui.ctx().data(|d| d.get_temp::<(Key, Vec<u32>)>(slot))
&& cached == key
{
return ids;
}
let mut ids: Vec<u32> =
super::character::selected_fonts(app).iter().filter_map(|(family, style)| db.face(family, style)).map(|f| f.id()).collect();
let mut add = |t: &vectorcraft_doc::TextObject, range: Option<(usize, usize)>| {
// Laid out as point type, so that text overflowing its area or path counts too.
let mut all = t.clone();
all.kind = vectorcraft_doc::TextKind::Point;
for g in vectorcraft_text::layout(db, &all).glyphs {
// A glyph counts when its characters overlap the range (a ligature may start before it).
if range.is_none_or(|(a, b)| g.byte < b && g.byte + g.len.max(1) > a) && !ids.contains(&g.font_id) {
ids.push(g.font_id);
}
}
};
let text = |id: NodeId| match state.doc.node(id).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => Some(t),
_ => None,
};
match (editing, story) {
// After Select All in threaded text: every frame of the story.
(Some(_), Some(frames)) => frames.into_iter().filter_map(text).for_each(|t| add(t, None)),
(Some((id, a, b)), None) => {
if let Some(t) = text(id) {
// A caret applies the form to all the text of the object.
add(t, (a < b).then_some((a, b)));
}
}
(None, _) => super::character::selected_story_texts(app).into_iter().for_each(|t| add(t, None)),
}
ui.ctx().data_mut(|d| d.insert_temp(slot, (key, ids.clone())));
ids
}
/// The East Asian glyph forms of the panel menu, with Show East Asian Options: each draws the
/// selected characters (all the text of the selected type objects without a Type tool range) in
/// one form of their font, and is checked when they all have it; a form none of the faces that
/// draw the selected text has a feature for ([`selection_faces`]) is disabled. Revert To Default
/// Forms draws the font's default glyphs.
/// Public behavior: [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)
/// (Replace Asian characters with a different glyph form).
fn glyph_form_items(app: &mut VectorcraftApp, ui: &mut Ui) {
let has = super::character::text_style(app).is_some();
let db = FontDb::global();
let faces: Vec<_> = selection_faces(app, ui).into_iter().filter_map(|id| db.face_by_id(id)).collect();
let current = super::character::shared(app, |s| s.glyph_form);
for form in GlyphForm::ALL {
let enabled = match form.feature() {
Some(tag) => faces.iter().any(|f| f.has_substitution_feature(*tag)),
None => has,
};
let checked = form != GlyphForm::Default && current == Some(form);
if form == GlyphForm::Default {
ui.separator();
}
// Choosing the form every selected character already has changes nothing.
if menu_item(ui, tl!(glyph_form_label(form)), enabled, checked) && current != Some(form) {
super::character::format(app, json!({"glyphForm": form.id()}));
}
}
}
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
if menu_item(ui, tl!("Use the Selected Text's Font"), true, false) {
set_pstate::<Option<(String, String)>>(ui.ctx(), "gl-font", None);
}
ui.separator();
if app.session.prefs.show_east_asian_options {
glyph_form_items(app, ui);
ui.separator();
}
for (i, (name, _, _)) in SUBSETS.iter().enumerate() {
let cur: usize = pstate(ui.ctx(), "gl-subset");
if menu_item(ui, tl!(name), true, cur == i) {
@@ -1102,6 +1208,59 @@ mod tests {
text_anchors(&shapes(ctx, app, vec![])).into_iter().map(|(t, _)| t).collect()
}
/// With Show East Asian Options, the panel menu lists the East Asian glyph forms; choosing one
/// draws the Type tool's selected characters in it, checks it, and Revert To Default Forms
/// takes it away. A form the font has no feature for is disabled. The second half needs
/// craft-fonts' BIZ UDMincho, which has JIS 78 forms and no JIS 04 forms (skipped without it).
#[test]
fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() {
let (mut app, id) = editing("亜唖");
let ctx = egui::Context::default();
let labels = |app: &mut VectorcraftApp| menu_texts(&ctx, app, vec![]).into_iter().map(|(t, _)| t).collect::<Vec<_>>();
let plain = |l: &String| l.trim_start_matches(['✓', ' ']).to_string();
app.session.prefs.show_east_asian_options = false;
assert!(!labels(&mut app).iter().map(plain).any(|l| l == "JIS 78 Forms"), "hidden without Show East Asian Options");
app.session.prefs.show_east_asian_options = true;
let shown: Vec<String> = labels(&mut app).iter().map(plain).collect();
for form in GlyphForm::ALL {
assert!(shown.iter().any(|l| l == glyph_form_label(form)), "{form:?} in {shown:?}");
}
const FAMILY: &str = "BIZ UDMincho";
if FontDb::global().face(FAMILY, "Regular").is_none_or(|f| f.family != FAMILY) {
eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)");
return;
}
app.run("text.setRangeStyle", json!({"id": id, "font": FAMILY})).unwrap();
let forms = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap_or(0))).unwrap().kind {
NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::<Vec<_>>(),
_ => panic!("text"),
};
select(&mut app, 3, 6);
choose(&ctx, &mut app, "JIS 78 Forms");
assert_eq!(forms(&app), [("亜".to_string(), GlyphForm::Default), ("唖".to_string(), GlyphForm::Jis78)]);
assert!(labels(&mut app).iter().any(|l| l.starts_with('✓') && l.ends_with("JIS 78 Forms")), "checked");
// A selection whose first font has no JIS 83 forms, and whose second one does, takes them.
let fallback = vectorcraft_text::FALLBACK_FAMILY;
if FontDb::global().face(fallback, "Regular").is_some_and(|f| !f.has_substitution_feature(*b"jp83")) {
app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": fallback})).unwrap();
select(&mut app, 0, 6);
choose(&ctx, &mut app, "JIS 83 Forms");
assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Jis83), "{:?}", forms(&app));
app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": FAMILY})).unwrap();
app.run("text.setRangeStyle", json!({"id": id, "glyphForm": "default"})).unwrap();
select(&mut app, 3, 6);
choose(&ctx, &mut app, "JIS 78 Forms");
}
// Choosing it again changes nothing, and the font has no JIS 04 forms: that item is disabled.
let n = app.session.active().unwrap().history.undo.len();
choose(&ctx, &mut app, "JIS 78 Forms");
choose(&ctx, &mut app, "JIS 04 Forms");
assert_eq!(app.session.active().unwrap().history.undo.len(), n);
assert_eq!(forms(&app)[1].1, GlyphForm::Jis78);
choose(&ctx, &mut app, "Revert To Default Forms");
assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Default), "{:?}", forms(&app));
}
/// Show › Alternates for Current Selection lists the selected character's alternates from the
/// font of its text, whatever font the panel browses; a double-click draws the character with
/// one. A character without alternates, no selected character and a missing font each show a
+51 -12
View File
@@ -92,28 +92,29 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option<
let mut c: Cache = pstate(ctx, "links-cache");
let stale = c.key != key || now - c.at > RECHECK;
if stale {
let same_doc = c.key == key;
c.list = app.session.execute("links.list", &json!({ "show": o.show, "sort": o.sort, "dcsTransparency": o.dcs })).ok()?;
(c.key, c.at) = (key, now);
// One pass over the stored art for the rows outside the layer tree and the objects whose
// opacity masks hold them, not one per frame.
let mut want: std::collections::HashSet<u64> = c.list["links"]
// opacity masks hold them, not one per frame. An object in the layer tree is looked up by
// its index when drawn.
let doc = app.session.active().map(|st| &st.doc);
let want: std::collections::HashSet<u64> = c.list["links"]
.as_array()
.into_iter()
.flatten()
.filter(|r| nested_row(r))
.flat_map(|r| [r["id"].as_u64(), r["owner"]["maskOf"].as_u64()])
.flatten()
.filter(|id| doc.is_some_and(|d| d.node(NodeId(*id)).is_none()))
.collect();
c.nested.clear();
if !want.is_empty()
&& let Some(st) = app.session.active()
{
st.doc.visit_stored_arcs(|n, place| {
if !place.in_layers() && want.remove(&n.id.0) {
c.nested.push((n.id.0, std::sync::Arc::clone(n)));
}
});
c.nested.sort_by_key(|(id, _)| *id);
// The same revision keeps the objects collected for it, so their thumbnails are not drawn
// again each time the files are looked at.
if !(same_doc && want.iter().all(|id| c.nested_node(*id).is_some())) {
c.nested = match doc {
Some(d) if !want.is_empty() => stored_objects(d, want),
_ => vec![],
};
}
}
let want = first.filter(|_| o.info);
@@ -126,6 +127,44 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option<
Some(c)
}
/// The objects of `doc` outside the layer tree whose ids are in `want`, sorted by id. The art of
/// the stored brushes is set on `doc` only while a command uses it ([`Document::mounted_art`]), so
/// when an id is not found otherwise that art is set on a copy of `doc`, which gives its objects
/// the ids `links.list` reports for them.
///
/// [`Document::mounted_art`]: vectorcraft_doc::Document::mounted_art
pub(super) fn stored_objects(
doc: &vectorcraft_doc::Document,
mut want: std::collections::HashSet<u64>,
) -> Vec<(u64, std::sync::Arc<vectorcraft_doc::Node>)> {
let mut out = vec![];
collect_stored(doc, &mut want, &mut out);
if !want.is_empty() && doc.mounted_art.is_empty() {
let art = vectorcraft_brush::stored_art::StoredArt::read(doc);
if !art.is_empty() {
let mut d = doc.clone();
art.mount(&mut d);
collect_stored(&d, &mut want, &mut out);
}
}
out.sort_by_key(|(id, _)| *id);
out
}
/// Adds the objects of `d` outside the layer tree whose ids are in `want` to `out`, taking their
/// ids out of `want`.
fn collect_stored(
d: &vectorcraft_doc::Document,
want: &mut std::collections::HashSet<u64>,
out: &mut Vec<(u64, std::sync::Arc<vectorcraft_doc::Node>)>,
) {
d.visit_stored_arcs(|n, place| {
if !place.in_layers() && want.remove(&n.id.0) {
out.push((n.id.0, std::sync::Arc::clone(n)));
}
});
}
/// The ids of the selected image objects and placed documents.
fn selected_images(app: &VectorcraftApp) -> Vec<u64> {
let Some(st) = app.session.active() else { return vec![] };
+22
View File
@@ -238,6 +238,28 @@ fn a_mask_rows_tooltip_names_its_object_inside_a_symbol() {
assert!(text.iter().any(|t| t.contains(&want)), "{want} in {text:?}");
}
/// The row of an image in a stored brush's art finds its object for the thumbnail, though that art
/// is set on the document only while a command uses it.
#[test]
fn a_row_in_a_stored_brushs_art_finds_its_object() {
let dir = Folder::new("brush-art");
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let leaf = dir.file("leaf.png", &png(30, 20));
let id = app.run("file.place", json!({"path": leaf, "at": [100, 100]})).unwrap()["ids"][0].as_u64().unwrap();
app.run("brush.new", json!({"type": "scatter", "name": "Leaf", "ids": [id]})).unwrap();
app.run("edit.clear", json!({"ids": [id]})).unwrap();
let list = app.run("links.list", json!({})).unwrap();
let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == "leaf.png").unwrap_or_else(|| panic!("{list}")).clone();
assert_eq!(row["owner"]["kind"], "brush", "{list}");
let row = row["id"].as_u64().unwrap();
let doc = &app.session.active().unwrap().doc;
assert!(doc.mounted_art.is_empty(), "the brush's art is not set on the document");
let found = super::links::stored_objects(doc, [row].into());
assert_eq!(found.iter().map(|(id, _)| *id).collect::<Vec<_>>(), [row]);
assert!(matches!(found[0].1.kind, vectorcraft_doc::NodeKind::Image(_)), "{:?}", found[0].1.kind);
}
#[test]
fn an_empty_document_shows_how_to_add_images() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+1 -1
View File
@@ -27,7 +27,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md](
| Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own |
| Rasterize | Rasterize… (as a live effect) | 1/1 | — |
| Stylize | Drop Shadow, Feather, Inner Glow, Outer Glow, Round Corners, Scribble | 6/6 | Scribble Options' Settings presets |
| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists the document's own filters: VectorCraft ships no default filters. A filter that is the object's last effect is written to SVG as a `<filter>` element; otherwise SVG export draws the object as an image. A filter on a turned or skewed object in an imported SVG is left out with a warning |
| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists 14 default filters and then the document's own; the public page names no default set, so the set, names and values are VectorCraft's own, and a default is copied into the document when it is applied or edited. A filter that is the object's last effect is written to SVG as a `<filter>` element; otherwise SVG export draws the object as an image. A filter on a turned or skewed object in an imported SVG is left out with a warning |
| Warp | Arc, Arc Lower, Arc Upper, Arch, Bulge, Shell Lower, Shell Upper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist | 15/15 | warp point editing in envelopes; each style bends the bounds as one Bézier patch (`version` 1), so Arc's edges are cubic curves close to concentric arcs; warps saved without a version keep the earlier map, where Arc is a circular arc in the object's own proportions (#1578) |
Document Raster Effects Settings exists. When the 64 million pixel cap on an effect image lowers
+9 -1
View File
@@ -18,6 +18,13 @@ its current location. Opening the controls does not add a document undo step.
| Create | Fills / Strokes | Creates filled areas, stroked lines, or both. |
| Ignore Color | Color picker | Leaves out the selected color (white by default). |
The built-in presets other than Auto Color and Flat Logo all use Paths 50, and so do their enhanced
versions. Among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White
Logo, Line Art and Outline, and 50 in the other eight. Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo, 10 in Low Fidelity Photo, 15 in 3 Colors,
6 Colors, 16 Colors and Shades of Gray, 20 in Sketched Art, Line Art and Outline, 25 in Default and
Black and White Logo, and 90 in Silhouettes (see
[image-trace-quality.md](image-trace-quality.md#preset-paths-corners-and-noise)).
Sliders apply on release, and their numeric fields can be edited directly. Each committed
adjustment re-traces the selected object as one undo step and changes the preset to Custom.
While dragging, the preset and Enhanced row stay in place until release so the
@@ -142,7 +149,8 @@ further: the factor doubles until at most 150,000 remain or the working copy has
most 16,384 pixels (at most six times). A trace that would
make more than 8,000,000 anchor points (2,000,000 on the web) is refused to protect memory, with advice:
raise Noise, lower Paths or Colors, or pick a lower-fidelity preset. A trace keeps
about 90 bytes an anchor; a 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million.
about 90 bytes an anchor; a 4000 × 3000 photo at Limited 64 colors, Paths 90, Corners 25 and Noise 4
makes about 1.9 million.
**Tracing in the background.** On the desktop a trace runs on a thread of its own, so the window
keeps answering while a photo or a large image is traced (#3098). Make, Make and Expand, the task
bar's Image Trace and the panel's Trace and presets start it. The status bar says "Tracing the
+44
View File
@@ -82,6 +82,9 @@ gradient, texture, sensor noise):
(The last two rows were measured without a limit; they are refused now.) The 4000 × 3000 High Fidelity
Photo trace was 86,000 anchors under the old limit; a noisier scan of the same size would have been
refused. At 8,000,000 anchors a trace keeps about 0.7 GB, with a peak of about 0.9 GB while tracing.
The preset rows were measured with the earlier preset values: High Fidelity Photo at Paths 90, Corners 25
and Noise 4, Low Fidelity Photo at Paths 60, Noise 12 and 16 Colors at Paths 70, Corners 55 and Noise 10
(see [Preset Paths, Corners and Noise](#preset-paths-corners-and-noise)).
## Collapsed loops keep few segments
A small closed loop (or a piece that returns to its own junction) whose fit collapsed to a single
cubic cannot stay as one, so it kept every positioned point as a straight segment. A looser Paths
@@ -225,6 +228,47 @@ in a smooth area), `a_staircase_that_runs_on_from_a_smooth_area_into_an_edge_kee
`a_staircase_of_mixed_one_pixel_and_longer_steps_is_one_slope_without_a_notch`,
`a_run_of_two_steps_keeps_its_corners`, `a_junction_on_a_step_ends_the_staircase_there` and
`a_step_whose_cracks_read_as_an_edge_ends_the_staircase_there`.
## Preset Paths, Corners and Noise
Every built-in preset other than Auto Color and Flat Logo traces at Paths 50. Corners and Noise are:
| preset | Paths | Corners | Noise | before |
|:--|--:|--:|--:|:--|
| Default | 50 | 75 | 25 | unchanged |
| High Fidelity Photo | 50 | 50 | 5 | 90, 25, 4 |
| Low Fidelity Photo | 50 | 50 | 10 | 60, 50, 12 |
| 3 Colors | 50 | 50 | 15 | 60, 60, 20 |
| 6 Colors | 50 | 50 | 15 | 65, 60, 16 |
| 16 Colors | 50 | 50 | 15 | 70, 55, 10 |
| Shades of Gray | 50 | 50 | 15 | 60, 50, 10 |
| Black and White Logo | 50 | 75 | 25 | 95, 80, 8 |
| Sketched Art | 50 | 50 | 20 | 50, 50, 100 |
| Silhouettes | 50 | 50 | 90 | 40, 60, 30 |
| Line Art | 50 | 75 | 20 | 80, 70, 10 |
| Technical Drawing | 50 | 100 | 1 | 95, 90, 4 |
| Outline | 50 | 75 | 20 | 80, 70, 10 |
The palettes, color counts, thresholds and other options of the presets did not change. The enhanced
versions of these presets use the same Paths, Corners and Noise.
Measured with the harness below (section 1, each preset on the inputs it is meant for), before and after:
anchors fall in 10 of the 12 changed presets, for example 5,494 to 3,136 (High Fidelity Photo), 33 to 27
(16 Colors), 27 to 14 (Black and White Logo) and 43 to 28 (Line Art); Silhouettes rises from 13 to 15 and
Sketched Art does not change. Outlines on flat art lie further from the true edge: off mean 0.100 to 0.123
px (16 Colors), 0.101 to 0.119 (6 Colors), 0.104 to 0.129 (3 Colors), 0.064 to 0.092 (Black and White Logo)
and 0.056 to 0.074 (Line Art), and off max 1.00 to 1.16 px in 6 Colors and 16 Colors. Technical Drawing
leaves 1.4 specks (was 0.5), and Outline's stroked center lines lie 0.095 px off (was 0.086) with 2.7
anchors a stroke (was 3.0). ΔE changes by 0.01 or less except Line Art and Outline (2.62 and 2.61 to 2.66
and 2.67); edge ΔE rises in 8 of the 12, for example 4.79 to 5.25 (16 Colors), 3.98 to 4.46 (3 Colors) and 9.46 to 10.03
(Black and White Logo). On synthetic shapes and photos of 300 to 4,000 px traced outside this harness,
High Fidelity Photo makes 41% fewer anchors and 16 Colors 20% fewer; the mean pixel difference of each
trace changes by −0.23 to +0.26 of a level; 16 Colors leaves 41 staircases of steps of 2 px or more where it left 40, High
Fidelity Photo 440 where it left 391, Low Fidelity Photo 96 where it left 77, Line Art 17 where it left 13, Outline 13
where it left 10 and 3 Colors 14 where it left 12. On the same images Sketched Art makes 4,084 anchors where it made
3,936 and Silhouettes 1,608 where it made 1,578. The figures for these twelve presets and their enhanced versions in
the other sections of this file, and in the Image Trace entries of
[target-app-parity.md](target-app-parity.md), were measured at the earlier values.
Test: `presets_have_their_paths_corners_and_noise` in `crates/trace/src/tests.rs`.
## A simpler contour walk
`contour::trace_mask` follows each region's outline along the pixel cracks with the inside on the
right. It used to build a table of outgoing directions for every pixel corner in a raster pass and
+2 -2
View File
@@ -37,7 +37,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a
| French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) |
| Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) |
| Indonesian | `id` | 6,825 rows, 1,036 of them `@msg` and 47 `@msgplural` (counted 2026-11-14 on `main` at `676f0524cc`): the untranslated report lists 60 missing menu strings, 35 `tl!` literals and 13 undo labels for it; not in `COMPLETE_MESSAGES`, and checked against the same scanned messages it lacks 2,508; one plural form | most dialogs and tooltips; status and error messages partial | Latin | no | full | — (review) |
| Japanese | `ja` | 4,004 / 4,020 (99.6%) | all | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) |
| Japanese | `ja` | 4,004 / 4,020 (99.6%) | partial (3,562 `@msg` and 49 `@msgplural` rows, counted 2026-11-14: the untranslated report lists 98 messages without a Japanese row, 77 of which every complete-message language lacks; open #7116 and #7211 translate 35 of them) | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) |
| German | `de` | 3,952 / 4,020 (98%; menus, literals and messages complete when counted) | all (3,563 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 52 missing messages for it, which open #7116, #7211 and #7378 translate) | Latin | contributor-written, not reviewed | full | — (review) |
| Korean | `ko` | 4,870 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form | all (3,438 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 39 missing messages for it) | Hangul from an installed system font on the desktop (Apple SD Gothic Neo, Malgun Gothic, Noto Sans CJK KR…); the web build has no Korean UI font yet (craft-fonts); IME path exists | no (AI-drafted) | full | — (review; web font) |
| Vietnamese | `vi` | 4,886 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form; 4,046 plain + 18 `@plural` + 28 contextual + 794 `@msg` | dialogs and tooltips all; messages partial (1,750 `@msg` and 49 `@msgplural` rows, counted 2026-11-14: the untranslated report lists 1,875 messages without a Vietnamese row, 53 of which open #7211, #7378, #7405 and #7434 translate) | Latin with Vietnamese diacritics (stacked marks attach in precomposed, decomposed and keyboard forms, #4491; glyph tests pass) | contributor is a Vietnamese speaker; AI-assisted draft, further native review welcome | full | — (review) |
@@ -67,7 +67,7 @@ plus review. Native-speaker review is human work and isn't in the hours.
| Bulgarian | `bg` | 5,245 rows, 763 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial | full; AI-drafted, native review pending |
| Greek | `el` | 5,251 rows, 795 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | full; native review welcome |
| Georgian | `ka` | 5,200 rows (counted 2026-10-21): menus, panels, dialogs, plurals (one count-neutral form) and messages, tested complete; reviewed by a native speaker | full |
| Turkish | `tr` | 5,558 rows, 880 of them `@msg` (counted 2026-10-28); 6 menu strings and the default swatch names still fall back to English | full |
| Turkish | `tr` | 9,175 rows, 3,446 of them `@msg` and 48 `@msgplural` (counted 2026-11-13); 41 messages, 62 menu strings, 26 `tl!` literals, 13 undo labels and the default swatch names still fall back to English | full |
| Catalan | `ca` | 5,626 rows, 881 of them `@msg` (counted 2026-10-28): menus, `tl!` literals and messages complete when counted; one/other plurals; every `ca-*` locale resolves here | full; AI-drafted, native review welcome |
Twenty-seven non-English catalogs in all (registry count, 2026-11-06). Illustrator, as its public documentation lists, ships around two dozen
+66 -18
View File
@@ -878,10 +878,14 @@ leaves room for a legend label's stored indents, spacing and leading.
When a graph is drawn again, its plot moves and scales with any move or scale of the graph made since it was last
drawn. The graph saves the bounds of its art other than type as `placedArt` (and the bounds of all of its art as
`placed`), and measures the move or scale on those. Changing the size, indents or spacing of the labels, moving a label
on its own and `type.createOutlines` on labels do not move or scale the plot. A graph opened from a `.ai` file saves
`placedArt` too. A graph saved without `placedArt`, or with a `placedArt` that has no width or height, is measured on
`placed`.
`placed`), and measures the move or scale on those. Changing the size or indents of the labels, moving a label on its
own, `type.createOutlines` on labels and `object.path.outlineStroke` on the graph's strokes do not move or scale the
plot. Outlined labels are no longer type: moving one of them on its own, like moving a swatch, an axis or a tick mark on
its own, can move or scale the plot at the next redraw. When all of a graph's art other than type has been deleted, or
the art measured has no width or no height, a redraw leaves the plot where it is and does not follow a move or scale of
the graph. A graph opened from a `.ai` file
saves `placedArt` too. A graph saved without `placedArt`, or with a `placedArt` that has no width or height, is
measured on `placed`.
The `appearance.*` commands, `graphicStyle.apply` and `graphicStyle.redefine`, and the paint, stroke, gradient and
transparency commands given an `item` (or the Appearance panel's active row) store a graph label's object rows for its
@@ -1106,8 +1110,9 @@ way. `document.exportPdf {useArtboards: false}` writes that one page as well, an
art's bounds is measured without what the plot leaves out: non-printing layers, objects at 0% opacity, placed images,
gradient meshes whose every point is at 0% opacity, and paths without effects whose fills and strokes paint nothing.
An image or a mesh with a Crop Marks effect, or with a Vector Halftone effect that makes dots, is measured.
Such objects in the art of a symbol that is not dynamic are left out of its instances too, and an instance whose
symbol holds nothing else is left out.
Such objects in the art of a symbol are left out of its instances too, and an instance whose symbol holds nothing
else is left out. In the art of a dynamic symbol, an object that an instance's fill, stroke or opacity makes
the plot draw is measured.
A document whose only visible art is left out is refused, and Export As refuses an HP-GL plot of it before the save
dialog. A PDF of that page, from either command, carries no Preserve Editing data; when Preserve Editing is on (as it
is in VectorCraft Default), the export comes back with a warning that says so. A `.ai` export with
@@ -5133,8 +5138,12 @@ when its symbol or a symbol nested in its art holds an instance of itself, and w
nest 32 deep in its art. PDF and EPS export and the SVG of an artboard leave out art outside the page or artboard, and
Skip Blank Artboards skips an artboard with no art on it. For both, the box of an instance whose art holds brushed
strokes grows by 16 times the widest stroke (at least 1 pt) of the objects in its art that have a brushed stroke,
plus 8 pt. The SVG of an artboard also keeps an object whose effects paint onto the artboard, and an object that holds
an instance when the effects in the symbol's art, or the instance's own, paint onto it.
plus 8 pt. PDF and EPS export and Skip Blank Artboards grow the box of an object with a visible, painted brushed stroke the
same way, by its own widest stroke, and the box of an object that holds one by the largest such room among them (of a
clip group, only its clipping path counts). Print with Ignore Artboards frames the page around the art with the same
room for brushed objects and for instances whose art holds brushed strokes. The SVG of an artboard also keeps an
object whose effects paint onto the artboard, and an object that holds an instance when the effects in the symbol's
art, or the instance's own, paint onto it.
## Expand
@@ -5252,8 +5261,19 @@ it. The native format keeps the events and the files.
## SVG filters
Effect › SVG Filters lists the document's SVG filters below Apply SVG Filter… and Import SVG Filter…; choosing one
applies it to the selection. `svgFilter.list {}` returns them as `filters: [{name, xml}]`. Each is one `<filter>`
Effect › SVG Filters lists the default SVG filters and then the document's other filters below Apply SVG Filter… and
Import SVG Filter…; choosing one applies it to the selection
([apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html)).
The 14 defaults are VectorCraft's own set, written with [SVG 1.1 filter primitives](https://www.w3.org/TR/SVG11/filters.html):
Soft Blur, Heavy Blur, Soft Shadow, Hard Shadow, Glow, Bevel, Emboss, Thicken, Thin, Rough Edges, Grain, Grayscale,
Invert and Hue Shift. Every document lists them, and a document holds none of them until one is applied or edited
there. `svgFilter.apply` with a default's name copies the default into the document in the same undo step (refused
when the document already holds 64 filters), and `svgFilter.define` with `replace` naming a default adds the edited
copy under that name (code equal to the default's adds nothing). The document's filter of a default's name is then
listed in the default's place. `svgFilter.delete` refuses a default the document holds no copy of; deleting the copy
lists the default again, and applying the default again makes the effects that still name it draw with it.
`svgFilter.list {}` returns the document's filters as `filters: [{name, xml}]` and the defaults as
`defaults: [{name, xml, inDocument}]`. Each filter is one `<filter>`
element whose `id` is its name, with 1 to 64 primitives and at most 64 KB of XML (`feTurbulence` octaves up to 10,
`feConvolveMatrix` kernels up to 9 cells a side, `feMorphology` radii and `kernelUnitLength` up to 100 and
`stdDeviation` up to 500 user units, elements nested at most 16 deep). It holds only filter primitives,
@@ -5264,8 +5284,9 @@ a filter after the others, or with `replace` replaces the filter of that name, w
filter has is refused, and the same filter again records no undo step. `svgFilter.delete {name}` removes one, and `svgFilter.import
{path?|svg?}` adds the `<filter>` elements of an SVG file (at most 16 MB, not SVGZ, the first 256 filters) or of SVG text, leaving out the names the
document already has and the filters `svgFilter.define` would refuse (`{added, skipped}`). Each change is one undo
step. `svgFilter.apply {name, ids?|id?, item?}` applies one as the live effect `svg.filter`, as `effect.apply` does,
in one undo step. The effect (`{name, xml, scale, origin}`) names the document's filter: editing the filter changes
step. `svgFilter.apply {name, ids?|id?, item?, index?}` applies one as the live effect `svg.filter`, as `effect.apply` does,
in one undo step; with `index` it puts the filter in the place of the applied `svg.filter` effect at that index of
`item`, as `effect.setParams` does, and an index that is not an applied SVG filter is an error. The effect (`{name, xml, scale, origin}`) names the document's filter: editing the filter changes
what every object that uses it draws, in the edit's one undo step, and an application after an edit takes the edited
filter. Deleting a filter that objects use leaves their effects in place, still named, drawing nothing (their `xml`
empty) until a filter of that name is defined or imported again. A pasted effect that names one of the document's
@@ -7912,10 +7933,11 @@ and is missing from the picture" once for all such images.
`document.open` and `file.place` read `.emf` and `.wmf` (placeable or not) into one artboard, the picture's frame, and
one layer: paths with their fills and strokes (pens become strokes with caps, joins and dashes), clipping groups,
images and point type in the font the file names. Records VectorCraft doesn't read (EMF+ drawing among them) are
skipped with one warning. `clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard
for `edit.paste`; the app pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's
clipboard service offers it (the Windows desktop service doesn't read metafiles yet).
images and point type in the font the file names. An EMF that draws with EMF+ records is read from them. Hatched and
pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning.
`clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard for `edit.paste`; the app
pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's clipboard service offers it
(the Windows desktop service doesn't read metafiles yet).
```json
{"name":"export","arguments":{"path":"/tmp/logo.emf"}}
@@ -9015,7 +9037,8 @@ Options). Warichu characters are set at `warichuScale` percent of their size (10
`warichuLines` lines (a whole number from 1 to 6, default 2) inside their line: one above the other in horizontal type
and side by side across the column in vertical type, the first line above or to the right. `warichuGap` is the space
between the lines in points (0 to 100, default 0, document points as `baselineShift`). The stack is centered across the
line on the center of the line's ideographic em box, and the line keeps the height of the characters' own size.
line on the center of the line's ideographic em box, and the line keeps the height of the characters' own size, or
more when the stack needs it: the line's ascent and descent take in the characters of the outer lines.
A stretch of warichu characters is one block that takes the settings of its first character; a character with other
settings, another size or the other kind of leading (Auto or a number) starts a new one, and a tab, a forced line break or a tate-chu-yoko character ends it. In
vertical type a character marked `tateChuYoko` as well is set as tate-chu-yoko at its own size, and two or three digits
@@ -9062,7 +9085,11 @@ menus, and a value typed past 1000 sets 1000; Reset Panel sets both to 0. Charac
in Advanced Character Formats. With Fractional Widths off or System Layout on, each side is set in whole points, and
justification keeps that width. Live SVG text places each character the space moves, and type on a path with
Insert Aki is written as outlines. An SVG saved without Preserve Editing (`preserveEditing`) reopens without the
Insert Aki values; save it with Preserve Editing to keep them editable.
Insert Aki values; save it with Preserve Editing to keep them editable. An `.ai` file's text document keeps both
values, and opening the file reads them back. The stored values are read in thousandths of an em and a negative
value opens as 0; these are VectorCraft's own rules. When a legacy `.ai` save writes type as text, it writes type with
Insert Aki without the values and warns that they are left out. With `outlineText: true` it writes the type as outlines,
which keep the space Insert Aki adds, and does not warn that the values are left out.
```json
{"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"akiRight":500}}}
@@ -9090,6 +9117,27 @@ as outlines.
{"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"tsume":50}}}
```
## East Asian glyph forms
`text.setFormat` and `text.setRangeStyle {glyphForm}` set the East Asian glyph form the characters are drawn in
([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): `"traditional"`,
`"expert"`, `"jis04"`, `"jis90"`, `"jis78"`, `"jis83"`, `"fullWidth"`, `"halfWidth"`, `"thirdWidth"` or
`"quarterWidth"`, which draw them with the font's OpenType feature `trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`,
`fwid`, `hwid`, `twid` or `qwid` ([feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)),
or `"default"`, the font's default glyphs. A character holds one form at a time, so setting one replaces another. The
text keeps its characters, and a character the font has no glyph of that form for keeps its own. Runs that differ only
in their form are shaped as one piece of text. The form is saved only when it is not `"default"`, character styles
carry it, PDF draws the glyphs the canvas draws, and live SVG text writes it in `font-feature-settings`. Another value
is refused with `` `glyphForm` must be one of "traditional", … ``. One undo step, and a `text.setFormat` call that
gives the form the characters already have records none. With Show East Asian Options on, the Glyphs panel menu lists
the ten forms and Revert To Default Forms: a form is checked when every selected character has it, choosing it again
does nothing, and it is disabled when none of the faces that draw the selected text, fallback faces included, has a
feature for it.
```json
{"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"glyphForm":"jis78"}}}
```
## Composite Fonts
A composite font sets each class of character in a font of its own
+10 -3
View File
@@ -921,10 +921,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- The Polish catalog (`crates/ui-egui/src/i18n/pl.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,439 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 46 Polish messages: 44 that open #7211, #7214, #7116, #7330 and #1931 translate, and 2 that no language has a row for. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English.
- The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`).
- The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`).
- The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,421 `@msg` rows: a row for each status and error message the untranslated report (`untranslated_report`) finds in the sources, except 38. The report lists those 38 for Japanese: the 36 composite font errors that open #7211 translates, `select a path` (open #7214) and the justification order error (open #7116). The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording.
- The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording.
- A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`).
- The status bar translates the errors a script's `File` and `Folder` objects, `vc.run`, `$.evalFile`, the `$` object's properties and functions, `alert`, `confirm` and `prompt`, `vc.document` and `vc.log` raise, the limits a run can pass, and the errors of Drop Script Engine, and the line for a run that fails (a syntax error, a thrown error, a limit, a stop or an internal error, with the script's name, the line and column, the included file it is in and the files left written), in every language that translates every message. The script's name, paths, numbers, command ids and the text a script throws itself are shown as they are. A failure with no line and column, such as an error in code `eval` compiled, is shown with one colon after the script's name (`an_error_without_a_place_names_the_script_and_kind`). A message template that names a value twice matches only when both places hold the same text, so the line for a failed run is not taken for the message inside it (`a_repeated_placeholder_matches_the_same_text`). The untranslated-strings report also lists the messages the script host's `fail`, `value` and `over` helpers take and the errors the script interpreter throws, and a constant's text comes from the file or crate that declares it, so the Scripts menu's headers are not listed as messages (`script_errors_are_translated`, `script_host_errors_are_translated`, `message_scan_reads_script_interpreter_errors`, `message_scan_reads_constants_of_the_file_and_its_crate`, `message_scan_skips_test_modules_with_any_test_cfg`).
- The status bar also translates the errors the script interpreter's core throws (an unknown name, a property of `null` or `undefined`, a property that cannot be defined, assigned or deleted and the reason, a value that is not a function or a constructor, an invalid array length, an invalid assignment target), on their own and in the line for a failed run, in every language that translates every message. Names, property names (a value a message quotes in `'…'` is shown as written, like one in `"…"`, even when it matches a translated message), `null`, `undefined`, `in`, `instanceof` and the error's type (`TypeError`, `ReferenceError` and the others) are shown as they are, and a script that catches the error still reads its English message. An error about a property of `null` or `undefined` names a computed property whose name is not an object and is at most 256 units long, and otherwise says only that the script read or set a property, instead of naming an empty property (`script_interpreter_core_errors_are_translated`, `errors_about_null_and_undefined_name_the_property`, `message_scan_reads_script_interpreter_errors`).
- The Turkish catalog (`crates/ui-egui/src/i18n/tr.tsv`) has an `@msg` row for all but 41 of the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,446 `@msg` rows in all. The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording.
- The Hungarian catalog (`crates/ui-egui/src/i18n/hu.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,444 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 40 Hungarian messages: the composite font, justification order and connect end errors that open #7211, #7116 and #7330 translate, and two messages that no catalog has a row for. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording.
- The Dutch catalog (`crates/ui-egui/src/i18n/nl.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,447 `@msg` rows in all. The report lists 41 Dutch messages: the composite font errors, the justification spacing error and the `connect` end error, which open #7211, #7116 and #7330 translate, and three unknown-parameter and range errors (``unknown parameter `{within}{key}`; {why}``, ``unknown parameter `{within}settings.{format}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`), which open #7353 rewrites so that a catalog row can match them. The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording.
- The Traditional Chinese catalog (`crates/ui-egui/src/i18n/zh-hant.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,438 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 40 Traditional Chinese messages: open #7211, #7116 and #7330 add the rows for 38 of them, and the other 2 have no row in any catalog. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English.
@@ -1447,9 +1448,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
The Paragraph panel's Mojikumi Set lists the five predefined sets the help page names (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku and YakumonoZenkaku), then Line-end Punctuation Half Width, and `text.setFormat {mojikumi}` takes each of them. YakumonoHankaku sets every bracket, comma and full stop half width and takes a quarter em off each side of a middle dot; GyomatsuYakumonoHankaku keeps punctuation full width inside a line, sets an opening bracket flush at a line's start and a closing mark half width at its end, and takes the quarter em after a middle dot off at a line's end; GyomatsuYakumonoZenkaku keeps punctuation full width and adds a quarter em between Japanese and Latin text; YakumonoZenkaku sets characters as None does. These widths are VectorCraft's own rules, from the help page's one-line description of each set. Both composers and vertical type measure each line as it is set, the sets save with the document and paragraph styles, and a `.ai` save reports the new sets as left out (`crates/text/src/tests/vertical.rs`, `crates/ui-egui/src/panels/paragraph/tests.rs`). Scores and estimates are unchanged.
Interface text in characters the interface's fonts lack, drawn in a bundled Japanese, Georgian or Devanagari face or in an installed font that covers them, sits on the baseline of the Latin text beside it, monospace text included (#5816; `crates/ui-egui/src/ui_fonts.rs`, `crates/ui-egui/src/theme.rs`).
Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment.
The Glyphs panel menu (with the East Asian options) offers Traditional, Expert, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); each draws the selected characters with the font's OpenType feature for that form (`trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, `fwid`, `hwid`, `twid`, `qwid`), one form at a time, and a form none of the faces that draw the selected text has a feature for is disabled. `text.setFormat` and `text.setRangeStyle {glyphForm}` set it; the native file, character styles, the canvas, PDF and SVG (`font-feature-settings`) keep it (`tests::typo::glyph_forms_draw_the_fonts_east_asian_forms`, `typecmd::area_tests::glyph_form_is_one_character_attribute_saved_only_when_set`, `panels::glyphs` tests).
Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, on a vertical path it moves toward the path's start and to the path's left, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them.
A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past the coordinate limit (`MAX_COORD`) either way opens with the nearer end, as the type's own offsets do; an offset within it stays as saved.
Character panel › Insert Aki Left and Insert Aki Right (with the East Asian options; `text.setFormat` or `text.setRangeStyle {akiLeft, akiRight}`, thousandths of an em from 0 to 1000, 0 by default) add space before and after each selected character, measured as tracking is, and kept as set through justification ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); before and after follow the reading order in vertical and right-to-left type, character styles carry both values (Character Style Options › Advanced Character Formats edits them), and a file holding a value outside the range opens with the nearer end.
Insert Aki Left and Right open from an `.ai` file's text document (read in thousandths of an em, the unit the [scripting reference](https://web.archive.org/web/20160410092022/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/pdf/illustrator/pdfs/illustrator_scripting_reference_applescript.pdf#page=90) gives `aki left` and `aki right`; VectorCraft's own rule for the stored value) from the run, its character style, the styles that one is based on, `[Normal Character Style]` and the document's defaults in that order. A negative value or one that is not a number opens as 0, and a value past 1000 opens as 1000. An `.ai` save writes each run's nonzero values in the form that reader reads. A legacy `.ai` save writes type with Insert Aki as text without it and reports that it is left out; type it writes as outlines keeps the space.
Character panel › Tsume (with the East Asian options; `text.setFormat` or `text.setRangeStyle {tsume}`) narrows the space around each selected character ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); by VectorCraft's own rule the value is a percentage from 0 to 100, 0 by default, of the blank space on each side of the character's ink that horizontal type takes away without changing the glyph's shape, with tracking, kerning and Insert Aki added after it. Character styles carry it (Character Style Options › Advanced Character Formats edits it), and a file holding a value outside the range opens with the nearer end.
The Character panel's All Caps, Underline and Strikethrough buttons and its menu's All Caps, Underline, Strikethrough, Proportional Metrics, Tate-chu-yoko and No Break show off while only some of the selected characters have the attribute, and choosing one then turns it on for all of them, as `type.underline` (Cmd+Shift+U) does for underlining; the Character Alignment and Digits submenus check no item while the selected characters differ. `text.setFormat` refuses a value that is not true or false for its on/off attributes, as `text.setRangeStyle` does.
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks. The constant alpha soft mask that PDF and `.ai` export draw a CMYK page with transparency through is white, so applications that read every soft mask by its luminosity show the page too (#1359, part of #1286).
@@ -1491,6 +1494,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Image Trace, cut-out edges:** in Color and Grayscale, a semi-transparent pixel (alpha 128 to 254) on the edge of a cut-out image, beside a pixel that is less than half opaque, traces as a color of the fully opaque pixels within two pixels of it when its own color is that color or a darker shade of it, and of several such colors, as the one the most of those pixels have (art across a transparent gap does not count), so a darkened edge tone no longer traces as a 1 px sliver of an unrelated palette color, while a thin semi-transparent outline of another color keeps its own; code-drawn cut-out, opaque-edge and thin-outline tests in `crates/trace`.
- **Image Trace, cut-out edges choose no color:** in Color and Grayscale, the edge pixels that take the color beside them, and the semi-transparent pixels within two pixels of them whose color is also the opaque art's color blended with the background, do not count when the palette or the grays are chosen, so the edge of a cut-out image no longer adds a second shade of a color to Auto Color's palette, takes away an outline's color or takes a gray of its own; beside those pixels, the anti-aliasing between a color and an outline drawn along the edge is no color of Auto Color's own when it lies at least 0.45 of the way from the color to the outline and at least one in 32 of its pixels has both around it (edge pixels that choose no color count when they lie within 2.5 Oklab × 100 of the nearest of those colors): its pixels trace as the outline, so a thin outline stays a ring of few pieces, except beside an outline along the edge with a region of 8 pixels of its own, where each takes the nearer of the two, so a wider outline is not drawn wider; an outline over the edge in the color of other art traces in that color, while an opaque rim drawn along the edge keeps its color, also where other art reaches it; a thin semi-transparent outline of another color still counts, and opaque images trace as before; code-drawn cut-out outline, rim, opaque line and grayscale edge tests in `crates/trace`.
- **Image Trace, blurred edges:** in Color with a Limited palette of at most 16 colors (3 Colors, 6 Colors, 16 Colors) and in Grayscale with at most 16 grays (Shades of Gray), by VectorCraft's own rule (RGB distances, 0 to 255 a channel), a blend pixel with no unblended pixel of its own color within 4 pixels takes the nearer side of the pair of colors within 8 pixels that it is best a blend of, of the 8 colors within 8 pixels nearest to its color, when that pair explains it twice as well as its own color, or when it lies between the two and off the line between them by less than 0.15 of their distance apart; it keeps its color when it is one of the pair. Grayscale compares lightness. The in-between tones of an edge blurred over several pixels no longer trace as rings around it. High Fidelity Photo, Low Fidelity Photo and Black and White trace as before, and so do Automatic, Full Tone and Document Library palettes. Noisy and textured images settle more of their pixels. By `crates/trace/tests/quality` (256 px variants), 16 Colors on blurred flat art went from 9.0 paths to 3.0, 158 anchors to 34 and 0.239 px off to 0.069, and 6 Colors from 6.0 paths to 3.0 and 0.226 px off to 0.071; askew shapes take up to 11 px more area in colors the art does not have, and with 16 Colors the largest distance from a thin line's outline to the trace goes from 23.5 px to 45.3 (see [quality notes](image-trace-quality.md#blurred-edges)). Code-drawn blurred-disc and grayscale ramp tests in `crates/trace`.
- **Image Trace, preset Paths, Corners and Noise:** every built-in preset but Auto Color and Flat Logo traces at Paths 50, and so do their enhanced versions; among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline and 50 in the other eight, and Noise is 1 to 90 px by preset. Palettes and color counts are unchanged. Figures for these presets in the other Image Trace entries were measured at the earlier values. By `crates/trace/tests/quality`, High Fidelity Photo goes from 5,494 anchors to 3,136 and Black and White Logo from 27 to 14, while 16 Colors on flat art goes from 0.100 px off to 0.123 (see [quality notes](image-trace-quality.md#preset-paths-corners-and-noise)). Test `presets_have_their_paths_corners_and_noise` in `crates/trace`.
- **Image Trace, simpler contour walk:** `contour::trace_mask` works out each turn from the pixels during the walk, with no precomputed direction table and no assertion; identical loops to the previous walk on every 4 × 4 mask (see [quality notes](image-trace-quality.md#a-simpler-contour-walk)).
- **Image Trace, measured:** `crates/trace/tests/quality` traces drawings made from known vector art with every preset and [`image-trace-quality.md`](image-trace-quality.md) records the numbers against the baseline. Black and White, Grayscale and Color place each edge by the blend of the pixels across it (to a fraction of a pixel on anti-aliased and blurred images; hard-edged images are read as staircases) and fit outlines as Flat Logo does. *Measured* on each preset's own inputs, all sizes and variants: Default's outlines went from 0.31 px off on average to 0.09 (largest 1.51 to 1.02), Black and White Logo's from 0.27 to 0.06 with 0.3 kinks per trace where it had 15, and the gaps between abutting paths from 64 px to 22. On clean curved shapes Black and White Logo is 0.02 px off (the open tracer measured beside it: 0.20). The palette is made of the picture's own colours (blends along edges take none of it, colours that noise made of one colour merge, a blend pixel goes to one of the two colours it lies between; #1504): 16 Colors on flat art, all variants, went from 70 paths to 4.2 and from 5.1 px off to 0.13, with no path left in a colour the art doesn't have (5.9 before). Photos are smoothed within their tones before they are quantised and stacked layers go by lightness (#1516): High Fidelity Photo went from 3,653 paths to 121 with its colour error down from 2.30 to 1.75, and a 16 megapixel photo-like image is traced in 3.5 s where 4 megapixels were refused. Since then, by the same harness: outlines are cut at their junctions and each shared piece is fitted once (#1535: gaps and overlaps between abutting paths 22 to 50 px of area down to under 2); layers are traced within the box of their pixels and a few at a time (#1546: a 16 megapixel photo 3.9 GB to 0.9 GB); black and white are read against the image's own black and the paper near each edge (#1563, for thin lines in blurred and scanned art); Ignore Color and the Auto Color and Outline presets (#1574); Snap Curves To Lines levels lines within 2.5 degrees of level or upright (#1593, the angle our choice); Create: Strokes puts centre lines in the middle of their ink and makes them as wide as it (#1595: Outline 0.295 to 0.052 px from the true centre line, 18.4 to 2.7 anchors a stroke); sharp corners whose pixel is mostly outside the shape stay corners (#1609: Default 69% to 76% kept). Three options, each off unless asked for as the legacy presets have them: Shapes (#1609: 57 to 62% of plain circles, ellipses, rectangles and regular polygons come out as live shapes, rounded rectangles rarely), Auto Grouping (#1618: paths grouped with what lies inside them, the same picture) and Gradients (#1627: linear gradients traced as one gradient-filled path; on gradient inputs 6 Colors' colour error 2.12 to 0.62 with 6.4 to 3.4 paths, none found in flat art). Snap Curves To Lines moves no end of a line by more than 1.6 px, so long lines a degree or two off stay as the image has them (#1647: Technical Drawing's largest distance 4.21 px to 1.46). Flat Logo takes the tones a scan's uneven paper makes of one colour for one colour (#1657: on scans 470 paths and 21 px off to 8.5 paths and 0.09 px). Shapes finds rounded rectangles and shapes in aliased, blurred and scanned art (#1845: 57 to 62% of the plain shapes up to 98 to 100%, no false shape but one line 2 px wide). Stroked lines get square caps where their ink is cut square, and a wide end that turned towards a corner goes back on its line (#1846: Outline's largest distance 2.94 px to 0.88, 14 anchors to 10). Each of the 14 documented presets has an enhanced version with Auto Grouping and, in all but High Fidelity Photo, Shapes (#1847), measured beside its preset: equal or better within 0.005 px and 1% of edge ΔE on every preset's own inputs (Default 0.091 to 0.083 px); Auto Grouping keeps traced order in its groups, which removed a light seam along the counters of letters. Gradients grows a gradient over the pixels noise and soft rims took off it (#1848: blurred and noisy linear gradients 3 to 11 paths beside the gradient down to 0.5 with 6 Colors, 24 to 56 down to 0.5 to 1.5 with High Fidelity Photo). Silhouettes is 0.52 px off because its threshold is 200 (0.11 px at 128). Still weak, by the same numbers: rounded rectangles and other line-and-arc outlines take 12 to 16 anchors (the fitter does not split lines from arcs), blurred and scanned polygons lose corners, hairlines under half a pixel are lost to the threshold, aliased art is about 0.25 px off, a scan's uneven paper splits into tones when more colours are asked for than the art has, stroke junctions stay at their skeleton pixels, a three-stop gradient in a small or scanned disc is not found, radial gradients stay bands (a draft, #1849, traces them; the documented option is for linear ones, so it waits for a decision), near-regular polygons a few dozen pixels across are made regular with Shapes (up to 0.5 px off), and aliased stroked lines are 0.8 px off at Line truncated
- **Gradient mesh from an image:** Object › Create Gradient Mesh (`object.mesh.create`) on an embedded image makes a mesh of 1 to 50 rows and columns over the picture's rectangle, placed with the image's transform; each point takes the alpha-weighted average colour and the opacity of the area around it, and Appearance and Highlight apply. A linked image is refused with a message to embed it (#1676). Scores and hours unchanged.
@@ -1640,7 +1644,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents.
- **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document state; a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks.
- **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document view state saved in native files (#1968); a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks.
The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export, and type used as a clipping path keeps them when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it.
The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export. When the clipping path has a fill or stroke of its own, the geometry effects of those fills and strokes apply after the group's geometry effects instead. Type used as a clipping path keeps its geometry effects when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it.
Clicks, Select Behind, the Unlock submenu, marquees and the Enclosing Lasso inside a clip group or a clipping layer follow that area too: the clipped art is found where the effects moved it and not where they took it away. The clipping path itself is still found by its own outline and anchors. A hidden member of a group used as a clipping path does not clip, and a geometry effect on it does not change where clicks land. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. Direct Selection picks and outlines an object of a dynamic symbol's art by the same rules. `doc::hit::tests` and the engine's `tests::clip` cover it.
- **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`).
On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels.
Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports.
@@ -1813,6 +1818,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- HEIC and HEIF images open and place from `.heic` and `.heif`, as the [supported file formats](https://helpx.adobe.com/illustrator/kb/supported-file-formats-illustrator.html) list High Efficiency Image under both Open and Place (and [Fix HEIF file import errors on Windows](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/fix-heif-file-import-errors-on-windows.html) covers both ways of bringing HEIF files in): HEVC-coded single pictures and grids of tiles, 8 to 10 bits, with an alpha image, decoded by heic-rs in the engine's default `heif` feature. The container's rotation, mirror and crop are applied. Without an `nclx` box, the HEVC stream's video signal type gives the samples' matrix and range. An RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; the EXIF resolution tags size the image, or 72 ppi. Image sequences, other codings and grids of cropped tiles are refused with a message, and so is every HEIF file in a build without the feature. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_heifread.rs`).
- HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`, or a name no other format reads when the file starts with plotter instructions) open and place as paths on one layer, the artboard round the art: each line drawn with the pen down is a stroked path in its pen's color and width, line types become dash patterns, circles, arcs, wedges and Bézier curves are curves, filled and edged rectangles, wedges and polygons (polygon mode) are filled or stroked paths, and encoded polylines, scaling points, user units and rotation are read. Labels, symbol mode's symbols, raster images and hatching aren't drawn and are listed in the warnings (`crates/cad/src/hpgl/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`).
- PICT pictures (`.pct`, `.pic`, and `.pict` as VectorCraft's own name) open and place, as [the help page](https://helpx.adobe.com/archive/illustrator/illustrator-cs5-5-troubleshooting.pdf) lists Macintosh PICT under both opening and placing: versions 1 and 2, with or without the file's 512 bytes of application data, read by the opcodes of Apple's [Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html). Lines, rectangles, rounded rectangles, ovals, arcs, polygons and regions become paths in their pen and pattern colors, text becomes point type in the font the picture names, bitmaps, pixel maps and QuickTime JPEG images become images, and the clip region clips what follows it; File › Place places the picture as one group clipped to its frame. Inverted shapes, other transfer modes and other QuickTime formats come back as warnings, and a picture cut short keeps what came before it (`crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs`).
- EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`).
- Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`).
- HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`).
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546).
@@ -1962,7 +1968,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Raster-effect resolution in PDF:** when the 64 million pixel cap on an effect image renders an object's raster effects below the document's raster effects resolution, PDF export warns once per object with the requested and the lowest achieved ppi (`crates/engine/src/tests/pdfraster.rs`).
- **Rasterize effect:** Effect › Rasterize… (`rasterize`) draws an object as an image of square pixels at its own resolution or the document's raster effects resolution, with Object › Rasterize's color model, background, anti-aliasing, clipping mask and room around the object, while its paths stay editable. Expand Appearance and PDF and SVG export of an object whose only raster effect is Rasterize give the image Object › Rasterize gives (`crates/engine/src/tests/rastersettings.rs`, `crates/render/src/tests/rasterize.rs`). Behavior reference: [How to save artwork in Illustrator](https://helpx.adobe.com/illustrator/using/saving-artwork.html), [Work with effects](https://helpx.adobe.com/illustrator/using/effects.html).
- **Rasterize colour models:** Object › Rasterize with the Grayscale colour model makes a grayscale image (a gray PNG, with alpha over a transparent background), and with Bitmap a 1-bit image (a TIFF), or a black-and-white gray PNG with alpha over a transparent background; `image.info` and the Control bar say Grayscale, and a fill color colorizes the image, in RGB and CMYK documents (#6969). Expand Appearance and PDF export of a Rasterize effect make the same images. Regression coverage: `rasterize_to_grayscale_or_bitmap_makes_a_grayscale_image` (`crates/engine/src/tests/rastersettings.rs`) and `gray_and_bilevel_images_store_gray` (`crates/render/src/encode/tests.rs`). Scores and estimates unchanged.
- **SVG filters:** Effect › SVG Filters lists the document's own SVG filters below Apply SVG Filter… and Import SVG Filter…, and choosing one applies it to the selection as a live effect in one undo step (`svgFilter.apply`). Apply SVG Filter applies the selected filter, New and Edit open its code, and Delete and Import… remove filters or add those of an SVG file (`svgFilter.define`, `svgFilter.delete`, `svgFilter.import`). VectorCraft ships no default filters. The canvas, raster export and PDF draw the filter at the Document Raster Effects resolution; SVG export writes it as a `<filter>` element when it is the object's last effect and otherwise draws the object as an image; SVG import keeps filters the other live effects can't express as this effect instead of leaving them out; the native format keeps the filters (`crates/engine/src/tests/svgfilter.rs`, `crates/effects/src/svg_filter/tests.rs`). Behavior reference: [Apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html), [CS5 help, Apply SVG effects](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=402), [SVG 1.1 Filter Effects](https://www.w3.org/TR/SVG11/filters.html).
- **SVG filters:** Effect › SVG Filters lists 14 default SVG filters and then the document's own below Apply SVG Filter… and Import SVG Filter…, and choosing one applies it to the selection as a live effect in one undo step (`svgFilter.apply`). Apply SVG Filter applies the selected filter, New and Edit open its code, and Delete and Import… remove filters or add those of an SVG file (`svgFilter.define`, `svgFilter.delete`, `svgFilter.import`). The public page names no default set: the defaults (Soft Blur to Hue Shift, `crates/effects/src/svg_filter/defaults.rs`) are VectorCraft's own, written with SVG 1.1 primitives. A default is copied into the document when it is applied or edited, and Delete does not remove a default. The canvas, raster export and PDF draw the filter at the Document Raster Effects resolution; SVG export writes it as a `<filter>` element when it is the object's last effect and otherwise draws the object as an image; SVG import keeps filters the other live effects can't express as this effect instead of leaving them out; the native format keeps the filters (`crates/engine/src/tests/svgfilter.rs`, `crates/effects/src/svg_filter/tests.rs`). Behavior reference: [Apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html), [CS5 help, Apply SVG effects](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=402), [SVG 1.1 Filter Effects](https://www.w3.org/TR/SVG11/filters.html).
- **Pattern tiles:** the renderer keeps a tile of each pattern for each scale it rasterizes the pattern at, until the tiles fill the tile cache's budget, and then drops the least recently used tiles first. Objects that show one pattern at different scales, such as a pattern scaled to 25% with Transform Pattern Tiles next to the same pattern at 100%, draw from tiles kept between frames.
@@ -2071,6 +2077,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged.
- **Later effects on every fill or stroke a painted effect returns (G17):** when a painted effect on a fill or stroke returns several fills or strokes, a later live-effect plug-in in that fill's or stroke's stack, and a later geometry effect on strokes, runs once on each of them in paint order, given its own paint and its own `_context.item` among them. Each run's pieces replace only that fill or stroke. A run that fails, is refused, is deferred or would pass the effects' budget leaves only its own fill or stroke as it was, and the others still run; a deferred stage is listed once, at the source fill's or stroke's place. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/effects/src/tests/painted.rs`. Scores and hours unchanged.
- **Painted pieces with brushed strokes are culled and measured by their brush art (G17):** a piece that keeps the object's brushed stroke draws the brush along the piece's own path at the piece's stroke width. Culling leaves VectorCraft's usual room for brush art (16 × the stroke width + 8 pt) past each piece, from the piece's width rather than the object's, and so does culling of a group, layer, symbol instance, blend, envelope or repeat that holds the object. A group or layer also leaves that room for each brushed path among its members, painted or not. Object › Rasterize takes the brush art drawn along each piece and leaves out the object's own brush art, which is not drawn. Pieces without a brush are culled as before. Regressions: `crates/render/src/tests/paintedbrush.rs`. Scores and hours unchanged.
- **Brushed paths just off the page are exported and printed:** PDF and EPS export keep a path or compound path whose brush art reaches the page while the path lies just off it, alone or in a group, by leaving the canvas's room for brush art (16 × the widest stroke + 8 pt, VectorCraft's own value) past its box. Skip Blank Artboards keeps an artboard such brush art reaches, and Print with Ignore Artboards frames the page with that room around brushed paths and around instances whose art holds brushed strokes. A clip group leaves room only for its clipping path. Art without brushed strokes is written as before. Regressions: `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/print.rs`, `crates/eps/src/tests.rs`. Scores and hours unchanged.
- **Live-effect plug-ins while a document opens (G17):** the live-effect plug-in runs of a document's first view on screen share a 2,000 ms budget (VectorCraft's own value). A stage left out for time, or one that times out, fails, has no plug-in or meets Safe Mode, draws its input unchanged and is deferred; the status bar says how many, `effect.deferredStatus` lists them with their object, effect and reason, and Effect › Refresh Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget. Each document has its own budget, an edit runs the stages it changes, and exports, Expand Appearance and commands run every stage under the 5 s limit of each run. The web build times the budget and each run's limit with the page's `performance.now()`. Regressions: `crates/plugins/src/deferred.rs`, `crates/plugins/src/effect.rs`, `crates/plugins/src/host.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged.
- **Refreshing many deferred effects (G17):** Refresh Deferred Effects (`effect.refreshDeferred`) looks up the objects asked for, the stages reached, the objects drawn whole and the inputs that ran in hash sets, so its time no longer grows with the square of the number of deferred stages. The deferred records are indexed by stage and input, so asking whether a stage stays deferred, replacing a stage's records when it runs, and ending a drawing after the first view look at that stage's records only, and the records keep the order they were made in. With 40,000 deferred stages, one refresh in a release build took 38 ms, down from 1,036 ms, and asking about and running each stage once took 16 ms, down from 2,287 ms (wall-clock time on a computer busy with other builds, one run each). Regressions: `crates/plugins/src/deferred.rs`. Scores and hours unchanged.
- **Refresh Deferred Effects by object (G17):** `effect.refreshDeferred` takes `ids`, or `id` for one, naming objects in the layers or in the art of a symbol, pattern, brush or opacity mask, the objects `effect.deferredStatus` lists; an object without a deferred stage adds nothing to the counts, and an id of no object in the document is an error. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged.
+1
View File
@@ -69,6 +69,7 @@ against Illustrator's public documentation; **estimated** unless noted.
| CJK: East Asian Type units (Q, Ha) | done | Preferences › Units › East Asian Type (`unitsAsianType`, Points by default) offers every unit and Q and Ha, a quarter of a millimetre each ([Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/): 0.709 pt per Q; [InDesign's unit notation](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html): `q`, `h`). The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` |
| CJK: manual tate-chu-yoko | done | Character panel menu › Tate-chu-yoko (`text.setFormat` / `text.setRangeStyle {tateChuYoko}`), with Show East Asian Options: marked characters stand side by side across one em of a vertical column, squeezed to the em when wider; two or three half-width digits still do so without the mark; horizontal type keeps the mark and does not move them. Tate-chu-yoko Settings… (`ui.tateChuYokoSettings`, `{tcyUpDown, tcyLeftRight}` in points) moves a marked block up or down and right or left as one piece. Evidence: `tests_vertical::manual_tate_chu_yoko_sets_marked_characters_across_one_em`, `tests_vertical::tate_chu_yoko_settings_move_a_marked_block_up_down_left_and_right`, `typecmd::tate_chu_yoko_is_a_character_attribute_saved_only_when_on`, `typecmd::tate_chu_yoko_settings_are_character_attributes_saved_only_when_set`, `dialogs::tate_chu_yoko::tests` |
| CJK: Standard Vertical Roman Alignment | done | Character panel menu › Standard Vertical Roman Alignment (`text.setFormat` / `text.setRangeStyle {standardVerticalRoman}`), with Show East Asian Options, off by default: in vertical type the marked half-width characters (Latin letters, digits and other characters that would lie on their side) stand upright one below the other, each in its upright cell; spaces keep their width and tate-chu-yoko blocks stay across the column; horizontal type keeps the mark and does not change. Character Style Options has its own checkbox for it. Evidence: `tests_vertical::standard_vertical_roman_alignment_stands_half_width_characters_upright`, `typecmd::standard_vertical_roman_is_a_character_attribute_saved_only_when_on` |
| CJK: East Asian glyph forms | done | Glyphs panel menu › Traditional Forms, Expert Forms, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms, with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): the selected characters are drawn with the font's OpenType feature for that form (`trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, `fwid`, `hwid`, `twid`, `qwid`; [feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)), one form at a time (`text.setFormat` / `text.setRangeStyle {glyphForm}`); a form none of the faces that draw the selected text (fallback faces included) has a feature for is disabled, and Revert To Default Forms draws the default glyphs. Saved natively only when set, carried by character styles, drawn on the canvas and in PDF, and written to SVG as `font-feature-settings`. Character Style Options has no field for it. Evidence: `tests::typo::glyph_forms_draw_the_fonts_east_asian_forms`, `typecmd::area_tests::glyph_form_is_one_character_attribute_saved_only_when_set`, `panels::glyphs::tests::east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form` |
| CJK: warichu | done | Character panel menu › Warichu and Warichu Settings… (`text.setFormat` / `text.setRangeStyle {warichu, warichuLines, warichuGap, warichuScale, warichuAlign}`, `ui.warichuSettings`), with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): marked characters set at a percentage of their size and stacked on 1 to 6 lines inside their line, one above the other in horizontal type and side by side in vertical type, with a line gap and eight alignments; a block stays whole on one line. Saved natively, carried by character styles, drawn on the canvas and in every export (SVG, PDF and `.ai` write such type as outlines). Type on a path sets the characters at their own size. Evidence: `tests::warichu`, `dialogs::warichu::tests`, `typecmd::area_tests::warichu_is_a_character_attribute_set_saved_and_exported` |
| CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per class; SVG and legacy `.ai` write it as outlines. Not yet: custom character sets, the Units menu, Show Sample. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `compositefonts::tests`, `dialogs::composite_fonts::tests` |
| CJK: ruby | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`) | #633 |