diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs
index 9f9ba151e9..c7c3e408b4 100644
--- a/crates/doc/src/blend.rs
+++ b/crates/doc/src/blend.rs
@@ -840,15 +840,19 @@ fn reorient_strokes(n: &mut Node, o: Orient) {
}
}
-/// Turn the strokes of path `n` for Reverse Path Direction, before its subpaths flagged in
-/// `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its last
-/// anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and rotation
-/// then run the new way, so the stroke draws as it did. A stroke reads one profile along every
-/// subpath, so it turns only when all of them turn alike. Arrowheads stay at the path's start and
-/// end.
+/// Turn the strokes of path or compound path `n` for Reverse Path Direction, before its subpaths
+/// flagged in `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its
+/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and
+/// rotation then run the new way, so the stroke draws as it did. A compound path's subpaths are
+/// its members' subpaths in order. A stroke reads one profile along every subpath, so it turns
+/// only when all of them turn alike. Arrowheads stay at the path's start and end.
pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) {
- let NodeKind::Path { path, .. } = &n.kind else { return };
- let mut turns = path.subpaths.iter().enumerate().map(|(i, sp)| {
+ let subpaths: Vec<&SubPath> = match &n.kind {
+ NodeKind::Path { path, .. } => path.subpaths.iter().collect(),
+ NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).flat_map(|pd| &pd.subpaths).collect(),
+ _ => return,
+ };
+ let mut turns = subpaths.into_iter().enumerate().map(|(i, sp)| {
let mut o = Orient::of(sp);
if reversed.get(i).copied().unwrap_or(false) {
if sp.closed {
diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs
index 77454f64a1..71c6642846 100644
--- a/crates/doc/src/cmyk.rs
+++ b/crates/doc/src/cmyk.rs
@@ -332,20 +332,24 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> {
None
}
-/// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too.
-pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder>)> {
+/// The decoder of TIFF `bytes`' first image; `None` for other bytes and [`oversized_tiff`] images.
+fn tiff_decoder(bytes: &[u8]) -> Option>> {
if !is_tiff(bytes) || oversized_tiff(bytes).is_some() {
return None;
}
- let mut d = tiff::decoder::Decoder::new(Cursor::new(bytes)).ok()?;
+ tiff::decoder::Decoder::new(Cursor::new(bytes)).ok()
+}
+
+/// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too.
+pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder>)> {
+ let mut d = tiff_decoder(bytes)?;
Some((d.colortype().ok()?, d))
}
/// The Orientation tag of TIFF `bytes`' first image, of any unsigned type; `None` for other images
-/// and TIFFs without one. Reads only its header.
+/// and TIFFs without one. Reads only its header, for any color type.
pub fn tiff_orientation(bytes: &[u8]) -> Option {
- let (_, mut d) = tiff(bytes)?;
- d.find_tag_unsigned::(tiff::tags::Tag::Orientation).ok().flatten()
+ tiff_decoder(bytes)?.find_tag_unsigned::(tiff::tags::Tag::Orientation).ok().flatten()
}
/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when
@@ -363,8 +367,160 @@ pub fn exif_orientation(bytes: &[u8]) -> Option {
decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms)
}
+/// TIFF bytes as a reader sees them with some of them replaced: each patch is an offset and the
+/// bytes read there instead, at most four, in order of offset without overlaps. The file is not
+/// copied.
+struct Patched<'a> {
+ bytes: Cursor<&'a [u8]>,
+ patches: Vec<(usize, &'static [u8])>,
+}
+
+impl std::io::Read for Patched<'_> {
+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result {
+ let start = usize::try_from(self.bytes.position()).unwrap_or(usize::MAX);
+ let read = std::io::Read::read(&mut self.bytes, buf)?;
+ let got = buf.get_mut(..read).unwrap_or_default();
+ let end = start.saturating_add(read);
+ // The patches are in order and apart, and each is at most four bytes long.
+ let first = self.patches.partition_point(|&(at, _)| at.saturating_add(4) <= start);
+ for &(at, with) in self.patches.get(first..).unwrap_or_default().iter().take_while(|&&(at, _)| at < end) {
+ for (k, &b) in with.iter().enumerate() {
+ if let Some(slot) = at.checked_add(k).and_then(|i| i.checked_sub(start)).and_then(|i| got.get_mut(i)) {
+ *slot = b;
+ }
+ }
+ }
+ Ok(read)
+ }
+}
+
+impl std::io::Seek for Patched<'_> {
+ fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result {
+ std::io::Seek::seek(&mut self.bytes, to)
+ }
+}
+
+/// TIFF `bytes` read with the PhotometricInterpretation (tag 262) of their first image set to 1
+/// (black is zero) in each of its entries that holds one SHORT or LONG value. The decoder gives
+/// every sample of a grayscale image's pixels, in the order the file stores them, where it gives a
+/// CMYK image's inks and at most the first extra sample, and doesn't read a white-is-zero image
+/// with extra samples. `None` for bytes that aren't a TIFF and when the first image has no such
+/// entry.
+fn as_black_is_zero(bytes: &[u8]) -> Option> {
+ let le = bytes.starts_with(b"II*\0");
+ if !le && !bytes.starts_with(b"MM\0*") {
+ return None;
+ }
+ let u16_at = |at: usize| -> Option {
+ 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) })
+ };
+ let u32_at = |at: usize| -> Option {
+ 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()?;
+ let mut patches = Vec::new();
+ for i in 0..usize::from(u16_at(ifd)?) {
+ let e = ifd.checked_add(i.checked_mul(12)?.checked_add(2)?)?;
+ let (Some(tag), Some(ty), Some(count)) = (u16_at(e), u16_at(e.checked_add(2)?), u32_at(e.checked_add(4)?)) else { break };
+ if tag != 262 || count != 1 {
+ continue;
+ }
+ // The value sits in the entry, in the file's byte order.
+ let one: &'static [u8] = match (ty, le) {
+ (3, true) => &[1, 0],
+ (3, false) => &[0, 1],
+ (4, true) => &[1, 0, 0, 0],
+ (4, false) => &[0, 0, 0, 1],
+ _ => continue,
+ };
+ let at = e.checked_add(8)?;
+ bytes.get(at..at.checked_add(one.len())?)?;
+ patches.push((at, one));
+ }
+ (!patches.is_empty()).then(|| Patched { bytes: Cursor::new(bytes), patches })
+}
+
+/// The ExtraSamples values of the image `d` reads, one for each sample after its color, in order:
+/// 0 not alpha, 1 associated alpha, 2 unassociated alpha. Empty without the tag.
+fn extra_samples(d: &mut tiff::decoder::Decoder>) -> Vec {
+ d.find_tag_unsigned_vec::(tiff::tags::Tag::ExtraSamples).ok().flatten().unwrap_or_default()
+}
+
+/// Does `kind`, the color type of the TIFF `d` reads, hold inks that Open and Place keep: CMYK of 8
+/// or 16 bits, with no extra sample that the file names as alpha? The decoder gives a CMYK color
+/// type to a file whose alpha follows another extra sample. [`ImageBlob::cmyk`] reads the inks of
+/// such a file all the same: a document saved with one as a CMYK image keeps it.
+fn cmyk_inks(kind: tiff::ColorType, d: &mut tiff::decoder::Decoder>) -> bool {
+ matches!(kind, tiff::ColorType::CMYK(8 | 16)) && !extra_samples(d).iter().any(|e| matches!(e, 1 | 2))
+}
+
+/// Most samples a pixel of a TIFF is read with, its color and extra samples included, as the
+/// file's SamplesPerPixel counts them: VectorCraft's own limit.
+const MAX_EXTRA_SAMPLES_PIXEL: usize = 64;
+
+/// The bytes of the row the decoder of the TIFF `d` reads takes before it reads each strip or tile
+/// of a file that stores a pixel's samples together and has more of them (its SamplesPerPixel)
+/// than the decoder gives: one row of the strip or tile, every sample of each pixel. 0 for other
+/// files. `None` when the file has more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples a pixel, when its
+/// samples aren't unsigned integers (a SampleFormat other than 1, which the readers don't take, and
+/// which the floating-point predictor needs) and when its color type isn't read. Reads only the
+/// file's tags.
+fn row_buffer(d: &mut tiff::decoder::Decoder) -> Option {
+ use tiff::tags::Tag;
+ let kind = d.colortype().ok()?;
+ let all = d.find_tag_unsigned::(Tag::SamplesPerPixel).ok()?.unwrap_or(1);
+ if usize::from(all) > MAX_EXTRA_SAMPLES_PIXEL {
+ return None;
+ }
+ if d.find_tag_unsigned_vec::(Tag::SampleFormat).ok()?.is_some_and(|f| f.iter().any(|&f| f != 1)) {
+ return None;
+ }
+ if all <= kind.num_samples() || planar(d) {
+ return Some(0);
+ }
+ // A strip is as wide as the image, a tile as its TileWidth.
+ let width = match d.get_chunk_type() {
+ tiff::decoder::ChunkType::Tile => d.find_tag_unsigned::(Tag::TileWidth).ok()??,
+ tiff::decoder::ChunkType::Strip => d.dimensions().ok()?.0,
+ };
+ u64::from(width).checked_mul(u64::from(all))?.checked_mul(u64::from(kind.bit_depth().div_ceil(8)))
+}
+
+/// `d`, the decoder of a TIFF of `file` bytes, set to decode `n` pixels of `per` samples of `bits`
+/// bits each into RGBA. `None` when the file has more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples a
+/// pixel, when its samples aren't unsigned integers (a SampleFormat other than 1), and when the
+/// decoded samples, the copy that puts a planar file's samples pixel by pixel, the row the decoder
+/// reads each strip or tile into ([`row_buffer`]) and the RGBA pixels together take more than
+/// [`crate::MAX_RASTER_ALLOC`]. The decoder may then decode no more than those samples, and read no
+/// strip or tile of more compressed bytes than the file holds (nor more than its own limit of
+/// 128 MiB).
+fn with_room(
+ mut d: tiff::decoder::Decoder,
+ file: usize,
+ n: usize,
+ per: usize,
+ bits: u8,
+) -> Option> {
+ if per > MAX_EXTRA_SAMPLES_PIXEL {
+ return None;
+ }
+ let row = row_buffer(&mut d)?;
+ let need = n.checked_mul(per)?.checked_mul(usize::from(bits.div_ceil(8)))?;
+ let copies = if per > 1 && planar(&mut d) { 2 } else { 1 };
+ let peak = u64::try_from(need).ok()?.checked_mul(copies)?.checked_add(u64::try_from(n).ok()?.checked_mul(4)?)?.checked_add(row)?;
+ if peak > crate::MAX_RASTER_ALLOC {
+ return None;
+ }
+ let mut limits = tiff::decoder::Limits::default();
+ limits.decoding_buffer_size = need;
+ limits.intermediate_buffer_size = limits.intermediate_buffer_size.min(file);
+ Some(d.with_limits(limits))
+}
+
/// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)?
-fn planar(d: &mut tiff::decoder::Decoder>) -> bool {
+fn planar(d: &mut tiff::decoder::Decoder) -> bool {
d.find_tag_unsigned::(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1)
}
@@ -372,7 +528,10 @@ fn planar(d: &mut tiff::decoder::Decoder>) -> bool {
/// type has), pixel by pixel and 8 bits each (16-bit samples to their high byte), whether the file
/// stores each pixel's samples together or one plane per channel. `None` when they don't decode to
/// that many samples, which includes images whose planes together need more than the decoder's
-/// limit (256 MB of samples).
+/// limit (256 MiB of samples), and, before any decoding, files with more than
+/// [`MAX_EXTRA_SAMPLES_PIXEL`] samples a pixel, files whose samples aren't unsigned integers (a
+/// SampleFormat other than 1) and ones whose samples with the row the decoder reads each strip or
+/// tile into ([`row_buffer`]) take more than [`crate::MAX_RASTER_ALLOC`].
pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option> {
Some(match read_samples_at_depth(d, n, per)? {
Samples::Eight(v) => v,
@@ -404,7 +563,20 @@ enum SampleSlice<'a> {
}
/// [`read_samples`], keeping 16-bit samples at 16 bits.
-fn read_samples_at_depth(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option {
+fn read_samples_at_depth(d: &mut tiff::decoder::Decoder, n: usize, per: usize) -> Option {
+ // Checked from the tags, before anything is decoded.
+ let row = row_buffer(d)?;
+ let bytes = u64::from(d.colortype().ok()?.bit_depth().div_ceil(8));
+ let need = u64::try_from(n).ok()?.checked_mul(u64::try_from(per).ok()?)?.checked_mul(bytes)?;
+ if need.checked_add(row)? > crate::MAX_RASTER_ALLOC {
+ return None;
+ }
+ decode_samples(d, n, per)
+}
+
+/// [`read_samples_at_depth`] without its checks, for a decoder that [`with_room`] made. Its tags
+/// can't be read once its limits are set: the decoder holds a tag's values to its decoding limit.
+fn decode_samples(d: &mut tiff::decoder::Decoder, n: usize, per: usize) -> Option {
let mut buf = tiff::decoder::DecodingResult::U8(Vec::new());
let layout = d.read_image_to_buffer(&mut buf).ok()?;
match buf {
@@ -415,7 +587,8 @@ fn read_samples_at_depth(d: &mut tiff::decoder::Decoder>, n: usize
}
/// `data`, the samples of `n` pixels, `per` to a pixel, stored in `planes` planes, as the samples
-/// pixel by pixel; `None` when it doesn't hold that many samples or a plane per sample.
+/// pixel by pixel; `None` when it doesn't hold that many samples or a plane per sample. The copy
+/// of a planar file's samples is allocated once, at its length.
fn chunky(data: Vec, planes: usize, n: usize, per: usize) -> Option> {
if Some(data.len()) != n.checked_mul(per) {
return None;
@@ -427,7 +600,13 @@ fn chunky(data: Vec, planes: usize, n: usize, per: usize) -> Option<
return None;
}
let planes: Vec<&[T]> = data.chunks_exact(n).collect();
- Some((0..n).flat_map(|i| planes.iter().filter_map(move |p| p.get(i).copied())).collect())
+ let mut out = Vec::with_capacity(data.len());
+ for i in 0..n {
+ for p in &planes {
+ out.push(*p.get(i)?);
+ }
+ }
+ Some(out)
}
/// The color space an ICC profile's header names (bytes 16 to 19, such as `RGB `, `GRAY` or
@@ -473,10 +652,14 @@ struct CmykSource {
}
/// The samples of CMYK TIFF `bytes` (8 or 16 bits), their inks together or one plane per ink, with
-/// the TIFF's CMYK ICC profile; `None` for other images and ones larger than [`MAX_CMYK_PIXELS`].
+/// the TIFF's CMYK ICC profile; `None` for other images, CMYK ones with alpha, ones larger than
+/// [`MAX_CMYK_PIXELS`], and, before any decoding, ones with more than [`MAX_EXTRA_SAMPLES_PIXEL`]
+/// samples a pixel (their SamplesPerPixel), ones whose samples aren't unsigned integers (a
+/// SampleFormat other than 1) and ones whose samples with the row the decoder reads each strip or
+/// tile into ([`row_buffer`]) take more than [`crate::MAX_RASTER_ALLOC`].
fn tiff_source(bytes: &[u8]) -> Option {
let (kind, mut d) = tiff(bytes)?;
- if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) {
+ if !cmyk_inks(kind, &mut d) {
return None;
}
let (width, height) = d.dimensions().ok()?;
@@ -687,7 +870,10 @@ fn jpeg_inks(bytes: &[u8]) -> Option {
}
/// The ink amounts of a CMYK TIFF (16-bit samples to 8 bits), its inks stored together or one plane
-/// per ink.
+/// per ink. `None` for other images, ones larger than [`MAX_CMYK_PIXELS`], and the files
+/// [`read_samples`] refuses: more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples a pixel, samples that
+/// aren't unsigned integers, or samples that with the decoder's row take more than
+/// [`crate::MAX_RASTER_ALLOC`].
fn tiff_inks(bytes: &[u8]) -> Option {
let (kind, mut d) = tiff(bytes)?;
let (w, h) = d.dimensions().ok()?;
@@ -701,8 +887,8 @@ fn tiff_inks(bytes: &[u8]) -> Option {
/// CMYK TIFF `bytes` that no orientation turns ([`turned_cmyk`] stores the others) as Open and
/// Place store them: as they are, or, when they store one plane per ink, which the image decoder
/// doesn't read, their inks together in a CMYK TIFF with the resolution `ppi`, at the 8 or 16 bits
-/// the file has, carrying the file's CMYK ICC profile. `None` for other images and for CMYK TIFFs
-/// whose inks [`ImageBlob::cmyk`] doesn't read.
+/// the file has, carrying the file's CMYK ICC profile. `None` for other images, for CMYK TIFFs
+/// with an extra sample named as alpha and for ones whose inks [`ImageBlob::cmyk`] doesn't read.
pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option> {
let source = tiff_source(bytes)?;
let (_, mut d) = tiff(bytes)?;
@@ -716,7 +902,8 @@ pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option
/// inks turned and written again as a CMYK TIFF with the resolution `ppi` of the turned pixels,
/// with the turned width and height. A TIFF keeps its 8 or 16 bits, a JPEG has 8, and both keep
/// their CMYK ICC profile (a JPEG's put together from all its APP2 segments). `None` for other
-/// images and for CMYK images whose inks [`ImageBlob::cmyk`] doesn't read.
+/// images, for CMYK TIFFs with an extra sample named as alpha and for CMYK images whose inks
+/// [`ImageBlob::cmyk`] doesn't read.
pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: Option<(f64, f64)>) -> Option<(Vec, (u32, u32))> {
let CmykSource { width, height, samples, icc } = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_source(bytes) } else { tiff_source(bytes) }?;
// Four inks to a pixel, turned as four channels of the same depth are.
@@ -735,31 +922,58 @@ pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi:
}
/// A TIFF whose pixels have samples after their colour, which the image decoder doesn't read at
-/// all, as RGBA pixels: CMYK with an alpha channel (5 samples), each colour converted by `rgb` (ink
-/// amounts 0..1 → sRGB 0..1; the inks can't be kept with the transparency, so they show as RGB),
-/// and grayscale with extra samples, of which the first is the alpha when the file says so (other
-/// channels are left out). Associated (premultiplied) alpha is divided back out, and a pixel with
-/// no associated alpha has no color. 16-bit samples are converted at 16 bits, and only the result
-/// is rounded to 8 bits. The samples may be stored together or one plane per channel. `None` for
-/// other images and ones larger than [`MAX_CMYK_PIXELS`].
+/// all, as RGBA pixels: CMYK with an alpha channel, each color converted by `rgb` (ink amounts
+/// 0..1 → sRGB 0..1; the inks can't be kept with the transparency, so they show as RGB), and
+/// grayscale with extra samples. The alpha is the first extra sample whose ExtraSamples value
+/// names it (1 or 2), whatever extra samples come before it; the other extra samples are left out,
+/// and without such a value the pixels are opaque. A CMYK file with a fifth sample and no
+/// ExtraSamples tag has that sample as unassociated alpha. Associated (premultiplied) alpha is
+/// divided back out, and a pixel with no associated alpha has no color. 16-bit samples are
+/// converted at 16 bits, and only the result is rounded to 8 bits. The samples may be stored
+/// together or one plane per channel. A CMYK file with two or more samples past its inks and its
+/// ExtraSamples values (or with no ExtraSamples tag) is read too, opaque when none of those values
+/// names an alpha. `None` for other images, CMYK ones without alpha (their inks are read by
+/// [`ImageBlob::cmyk`]), ones larger than [`MAX_CMYK_PIXELS`], ones whose SamplesPerPixel is more
+/// than [`MAX_EXTRA_SAMPLES_PIXEL`], ones whose samples aren't unsigned integers (a SampleFormat
+/// other than 1) and ones whose samples, with the copy a planar file needs, the row the decoder
+/// reads each strip or tile into and the RGBA pixels, take more than [`crate::MAX_RASTER_ALLOC`];
+/// those are refused from the file's tags, before any decoding.
pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) -> Option {
use tiff::tags::Tag;
- let (kind, mut d) = tiff(bytes)?;
+ let mut d = tiff_decoder(bytes)?;
+ // The decoder gives no color type to a CMYK file that has six or more samples besides the
+ // ones its ExtraSamples values count.
+ let kind = d.colortype().ok();
let (w, h) = d.dimensions().ok()?;
- // 0: white is zero, 1: black is zero (the two grayscales).
+ // 0: white is zero, 1: black is zero (the two grayscales), 5: CMYK.
let photometric = d.find_tag_unsigned::(Tag::PhotometricInterpretation).ok().flatten();
- // ExtraSamples 1: associated alpha (premultiplied colour), 2: unassociated alpha, 0: not alpha.
- let extra = d.find_tag_unsigned_vec::(Tag::ExtraSamples).ok().flatten().and_then(|v| v.first().copied());
- // (samples in a pixel, how many of them are its colour, is the next one alpha?)
- let (samples, colour, alpha) = match kind {
- tiff::ColorType::CMYKA(8 | 16) => (5, 4, true),
- tiff::ColorType::Multiband { bit_depth: 8 | 16, num_samples: n @ 2.. } if matches!(photometric, Some(0 | 1)) => {
- (usize::from(n), 1, matches!(extra, Some(1 | 2)))
- }
+ let extras = extra_samples(&mut d);
+ // The first extra sample named as alpha: (its place among the extra samples, is it associated?)
+ let named = extras.iter().position(|e| matches!(e, 1 | 2)).map(|i| (i, extras.get(i) == Some(&1)));
+ // The samples of a pixel that no ExtraSamples value counts.
+ let uncounted = d.find_tag_unsigned::(Tag::SamplesPerPixel).ok().flatten().and_then(|all| usize::from(all).checked_sub(extras.len()));
+ // (how many of a pixel's samples are its color, the alpha among the extra samples)
+ let (colour, alpha) = match kind {
+ Some(tiff::ColorType::CMYKA(8 | 16)) => (4, if extras.is_empty() { Some((0, false)) } else { named }),
+ Some(tiff::ColorType::CMYK(8 | 16)) if named.is_some() => (4, named),
+ Some(tiff::ColorType::Multiband { bit_depth: 8 | 16, num_samples: 2.. }) if matches!(photometric, Some(0 | 1)) => (1, named),
+ None if photometric == Some(5) && uncounted.is_some_and(|c| c > 5) => (4, named),
_ => return None,
};
let n = usize::try_from(pixels(w, h)?).ok()?;
- let data = read_samples_at_depth(&mut d, n, samples)?;
+ // The decoder gives a CMYK pixel its inks and at most one extra sample, and doesn't read
+ // white-is-zero gray with extra samples: those are read as black-is-zero gray, every sample.
+ let given = kind.map_or(0, |k| usize::from(k.num_samples()));
+ let (data, samples) = if photometric == Some(0) || kind.is_none() || alpha.is_some_and(|(i, _)| colour + i >= given) {
+ let mut d = tiff::decoder::Decoder::new(as_black_is_zero(bytes)?).ok()?;
+ let tiff::ColorType::Multiband { bit_depth: bits @ (8 | 16), num_samples } = d.colortype().ok()? else { return None };
+ let samples = usize::from(num_samples);
+ (decode_samples(&mut with_room(d, bytes.len(), n, samples, bits)?, n, samples)?, samples)
+ } else {
+ (decode_samples(&mut with_room(d, bytes.len(), n, given, kind?.bit_depth())?, n, given)?, given)
+ };
+ // (the alpha's sample in a pixel, is it associated?), when the pixel has that sample.
+ let alpha = alpha.map(|(i, associated)| (colour + i, associated)).filter(|(at, _)| *at < samples);
// Sample `i` of the image, 0..1.
let level_at = |i: usize| match &data {
Samples::Eight(v) => v.get(i).map(|&s| f32::from(s) / 255.0),
@@ -772,13 +986,16 @@ pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3])
};
let mut out = Vec::with_capacity(n.checked_mul(4)?);
for first in (0..n).map(|p| p * samples) {
- let (opacity, a) = if alpha { (byte_at(first + colour).unwrap_or(u8::MAX), level_at(first + colour).unwrap_or(1.0)) } else { (u8::MAX, 1.0) };
+ let (opacity, a) = match alpha {
+ Some((at, _)) => (byte_at(first + at).unwrap_or(u8::MAX), level_at(first + at).unwrap_or(1.0)),
+ None => (u8::MAX, 1.0),
+ };
let level = |s: usize| {
let v = level_at(first + s).unwrap_or(0.0);
- match extra {
- Some(1) if a > 0.0 => (v / a).min(1.0),
+ match alpha {
+ Some((_, true)) if a > 0.0 => (v / a).min(1.0),
// No associated alpha: the color is zero (TIFF 6.0, Associated Alpha Handling).
- Some(1) if alpha => 0.0,
+ Some((_, true)) => 0.0,
_ => v,
}
};
@@ -1083,6 +1300,380 @@ mod tests {
assert_eq!(gray.into_raw(), [0, 0, 0, 0], "a gray of zero");
}
+ /// A pixel type of `$n` samples of `$inner`, `$bits` bits each, in color space `$space`.
+ macro_rules! samples {
+ ($name:ident, $inner:ty, $space:ident, $bits:literal, $n:literal) => {
+ struct $name;
+ impl tiff::encoder::colortype::ColorType for $name {
+ type Inner = $inner;
+ const TIFF_VALUE: tiff::tags::PhotometricInterpretation = tiff::tags::PhotometricInterpretation::$space;
+ const BITS_PER_SAMPLE: &'static [u16] = &[$bits; $n];
+ const SAMPLE_FORMAT: &'static [tiff::tags::SampleFormat] = &[tiff::tags::SampleFormat::Uint; $n];
+ fn horizontal_predict(row: &[$inner], result: &mut Vec<$inner>) {
+ result.extend_from_slice(row);
+ }
+ }
+ };
+ }
+ samples!(Cmyk6x8, u8, CMYK, 8, 6);
+ samples!(Cmyk6x16, u16, CMYK, 16, 6);
+ samples!(Cmyk7x8, u8, CMYK, 8, 7);
+ samples!(Cmyk8x8, u8, CMYK, 8, 8);
+ samples!(Gray3x8, u8, BlackIsZero, 8, 3);
+ samples!(WhiteGray2x8, u8, WhiteIsZero, 8, 2);
+
+ /// A one-row TIFF of `C`'s pixels `data`, with the ExtraSamples values `extra`.
+ fn extras_tiff(extra: &[u16], data: &[C::Inner]) -> Vec
+ where
+ [C::Inner]: tiff::encoder::TiffValue,
+ {
+ let samples = C::BITS_PER_SAMPLE.len();
+ let mut file = Cursor::new(Vec::new());
+ let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap();
+ let mut img = enc.new_image::(u32::try_from(data.len() / samples).unwrap(), 1).unwrap();
+ img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, extra).unwrap();
+ img.write_data(data).unwrap();
+ file.into_inner()
+ }
+
+ /// Two pixels of four inks with an alpha sample and another extra sample, the alpha first when
+ /// `alpha_first`: cyan at an alpha of 128 (or premultiplied, at 128 of cyan when `associated`)
+ /// with an extra sample of 9, then black, opaque, with an extra sample of 64.
+ fn inks_alpha_and_extra(alpha_first: bool, associated: bool) -> Vec {
+ let cyan = if associated { 128 } else { 255 };
+ let px = |inks: [u16; 4], alpha: u16, other: u16| {
+ let extras = if alpha_first { [alpha, other] } else { [other, alpha] };
+ [&inks[..], &extras[..]].concat()
+ };
+ [px([cyan, 0, 0, 0], 128, 9), px([0, 0, 0, 255], 255, 64)].concat()
+ }
+
+ /// A CMYK TIFF whose pixels have alpha and another extra sample reads the sample its
+ /// ExtraSamples names as alpha, first or second, at 8 and 16 bits, and leaves the other out.
+ /// Open and Place don't keep its inks. A blob that holds the file, as a document saved with it
+ /// as a CMYK image does, is a CMYK image with those inks when the alpha is the second extra
+ /// sample.
+ #[test]
+ fn a_cmyk_tiff_with_alpha_and_another_extra_sample_reads_its_alpha() {
+ let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)];
+ for extra in [[1, 0], [2, 0], [0, 1], [0, 2]] {
+ let data = inks_alpha_and_extra(extra[0] != 0, extra.contains(&1));
+ let eight: Vec = data.iter().map(|&v| u8::try_from(v).unwrap()).collect();
+ let sixteen: Vec = data.iter().map(|&v| v * 257).collect();
+ for (bits, bytes) in [(8, extras_tiff::(&extra, &eight)), (16, extras_tiff::(&extra, &sixteen))] {
+ let px = extra_samples_tiff_rgba(&bytes, naive).unwrap_or_else(|| panic!("{extra:?}, {bits} bits: reads"));
+ assert_eq!(px.into_raw(), [0, 255, 255, 128, 0, 0, 0, 255], "{extra:?}, {bits} bits: cyan at half alpha, then black");
+ assert!(stored_cmyk_tiff(&bytes, None).is_none(), "{extra:?}, {bits} bits: the inks can't be kept with the alpha");
+ let b = ImageBlob::new("image/tiff", bytes);
+ if extra[0] != 0 {
+ // The decoder gives these the color type of CMYK with alpha.
+ assert!(!b.is_cmyk() && b.cmyk().is_none(), "{extra:?}, {bits} bits: never stored as inks");
+ continue;
+ }
+ assert!(b.is_cmyk(), "{extra:?}, {bits} bits: a stored one stays a CMYK image");
+ assert_eq!(b.is_cmyk16(), bits == 16, "{extra:?}, {bits} bits");
+ let cyan = u8::try_from(data[0]).unwrap();
+ assert_eq!(b.cmyk().map(|i| i.data), Some(vec![cyan, 0, 0, 0, 0, 0, 0, 255]), "{extra:?}, {bits} bits: a stored one keeps its inks");
+ }
+ }
+ // Two extra samples, neither of them alpha: the inks are kept, as with one.
+ let bytes = extras_tiff::(&[0, 0], &[255, 0, 0, 0, 9, 128, 0, 0, 0, 255, 64, 255]);
+ assert!(extra_samples_tiff_rgba(&bytes, naive).is_none(), "not alpha: not this reader's");
+ assert!(stored_cmyk_tiff(&bytes, None).is_some());
+ let b = ImageBlob::new("image/tiff", bytes);
+ assert!(b.is_cmyk() && !b.is_cmyk16());
+ assert_eq!(b.cmyk().map(|i| i.data), Some(vec![255, 0, 0, 0, 0, 0, 0, 255]));
+ }
+
+ /// A CMYK TIFF of six samples a pixel whose ExtraSamples has only one value: the sample after
+ /// the inks is alpha only when that value says so, and the sample after it is never alpha. Files
+ /// with more samples than the decoder gives a color type read the same way, opaque when no
+ /// value names an alpha.
+ #[test]
+ fn a_cmyk_tiff_with_fewer_extra_sample_values_than_samples_reads_only_a_named_alpha() {
+ let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)];
+ let data = [255, 0, 0, 0, 128, 9, 0, 0, 0, 255, 255, 64];
+ let read = |extra: u16| extra_samples_tiff_rgba(&extras_tiff::(&[extra], &data), naive).expect("reads").into_raw();
+ assert_eq!(read(2), [0, 255, 255, 128, 0, 0, 0, 255], "the sample after the inks is the alpha");
+ assert_eq!(read(0), [0, 255, 255, 255, 0, 0, 0, 255], "not alpha: opaque");
+ // Eight samples with two values: the decoder gives the file no color type. The second
+ // value names the sixth sample as the alpha.
+ let wide = [255, 0, 0, 0, 9, 128, 17, 18];
+ let px = extra_samples_tiff_rgba(&extras_tiff::(&[0, 2], &wide), naive).expect("reads");
+ assert_eq!(px.into_raw(), [0, 255, 255, 128], "cyan at the alpha the second value names");
+ let px = extra_samples_tiff_rgba(&extras_tiff::(&[0, 0], &wide), naive).expect("no value names an alpha: reads");
+ assert_eq!(px.into_raw(), [0, 255, 255, 255], "no value names an alpha: opaque cyan");
+ // Six samples and no ExtraSamples tag: the decoder gives the file no color type either.
+ let mut file = Cursor::new(Vec::new());
+ let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap();
+ enc.write_image::(1, 1, &wide[..6]).unwrap();
+ let px = extra_samples_tiff_rgba(&file.into_inner(), naive).expect("no ExtraSamples tag: reads");
+ assert_eq!(px.into_raw(), [0, 255, 255, 255], "no ExtraSamples tag: opaque cyan");
+ // Seven samples with two values: the decoder reads it as CMYK with alpha.
+ let px = extra_samples_tiff_rgba(&extras_tiff::(&[0, 2], &wide[..7]), naive).expect("reads");
+ assert_eq!(px.into_raw(), [0, 255, 255, 128], "seven samples: cyan at the alpha the second value names");
+ // Its Orientation tag is read too.
+ let mut file = Cursor::new(Vec::new());
+ let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap();
+ let mut img = enc.new_image::(1, 1).unwrap();
+ img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[0u16, 2][..]).unwrap();
+ img.encoder().write_tag(tiff::tags::Tag::Orientation, 6u16).unwrap();
+ img.write_data(&wide).unwrap();
+ let turned = file.into_inner();
+ assert_eq!(tiff_orientation(&turned), Some(6));
+ assert_eq!(exif_orientation(&turned), Some(image::metadata::Orientation::Rotate90));
+ }
+
+ /// A white-is-zero grayscale TIFF `width` pixels wide and `rows` tall (2 or more), each pixel
+ /// `samples` samples of 8 bits: a level of 0, an unassociated alpha of 128, then zeros. Each
+ /// row is a strip, and every strip is the same bytes of the file.
+ fn tall_gray_tiff(width: u32, rows: u32, samples: u16) -> Vec {
+ gray_tiff(width, rows, samples, false)
+ }
+
+ /// [`tall_gray_tiff`], or with `planar` one plane per sample, each row of each plane a strip
+ /// of zeros, every strip the same bytes of the file.
+ fn gray_tiff(width: u32, rows: u32, samples: u16, planar: bool) -> Vec {
+ let at = |f: &Vec| u32::try_from(f.len()).unwrap();
+ let mut f = b"II*\0\0\0\0\0".to_vec();
+ let row = at(&f);
+ if planar {
+ f.resize(f.len() + usize::try_from(width).unwrap(), 0);
+ } else {
+ for _ in 0..width {
+ f.extend([0, 128]);
+ f.resize(f.len() + usize::from(samples) - 2, 0);
+ }
+ }
+ let (strips, strip) = if planar { (rows * u32::from(samples), width) } else { (rows, width * u32::from(samples)) };
+ let offsets = at(&f);
+ f.extend((0..strips).flat_map(|_| row.to_le_bytes()));
+ let counts = at(&f);
+ f.extend((0..strips).flat_map(|_| strip.to_le_bytes()));
+ let ifd = at(&f);
+ f[4..8].copy_from_slice(&ifd.to_le_bytes());
+ // (tag, type (3 SHORT, 4 LONG), count, value or offset)
+ let entries = [
+ (256u16, 4u16, 1, width),
+ (257, 4, 1, rows),
+ (258, 3, 1, 8),
+ (259, 3, 1, 1),
+ (262, 3, 1, 0),
+ (273, 4, strips, offsets),
+ (277, 3, 1, u32::from(samples)),
+ (278, 4, 1, 1),
+ (279, 4, strips, counts),
+ (284, 3, 1, if planar { 2 } else { 1 }),
+ (338, 3, 1, 2),
+ ];
+ f.extend(u16::try_from(entries.len()).unwrap().to_le_bytes());
+ for (tag, ty, count, value) in entries {
+ f.extend([tag.to_le_bytes(), ty.to_le_bytes()].concat());
+ f.extend([count.to_le_bytes(), value.to_le_bytes()].concat());
+ }
+ f.extend([0; 4]);
+ f
+ }
+
+ /// A TIFF with extra samples whose samples take more than the decoder's own limit of 256 MiB
+ /// reads: here 256 × 16,385 pixels of 64 samples, 16,384 bytes more than the limit.
+ #[test]
+ fn a_tiff_with_extra_samples_past_the_decoders_limit_reads() {
+ let (width, rows, samples) = (256, 16_385, 64);
+ assert!(u64::from(width * rows) * u64::from(samples) > 256 << 20);
+ let px = extra_samples_tiff_rgba(&tall_gray_tiff(width, rows, samples), |_| [0.0; 3]).expect("reads");
+ assert_eq!((px.width(), px.height()), (width, rows));
+ assert!(px.pixels().all(|p| p.0 == [255, 255, 255, 128]), "white at an alpha of 128");
+ }
+
+ /// A pixel of more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples is not read.
+ #[test]
+ fn a_tiff_with_too_many_samples_a_pixel_is_not_read() {
+ let samples = u16::try_from(MAX_EXTRA_SAMPLES_PIXEL).unwrap();
+ assert!(extra_samples_tiff_rgba(&tall_gray_tiff(2, 2, samples), |_| [0.0; 3]).is_some(), "at the limit: reads");
+ assert!(extra_samples_tiff_rgba(&tall_gray_tiff(2, 2, samples + 1), |_| [0.0; 3]).is_none(), "past it: not read");
+ }
+
+ /// The header of a one-row CMYK TIFF `width` pixels wide, each pixel `samples` samples of
+ /// `bits` bits stored together, with the ExtraSamples values `extras` (more than two). Its one
+ /// strip claims every sample of the row, uncompressed, and holds four bytes of zeros.
+ fn cmyk_header(width: u32, samples: u16, bits: u16, extras: &[u16]) -> Vec {
+ assert!(extras.len() > 2, "the values sit outside the entry");
+ let mut f = b"II*\0\0\0\0\0".to_vec();
+ f.extend([0; 4]);
+ let at = u32::try_from(f.len()).unwrap();
+ f.extend(extras.iter().flat_map(|e| e.to_le_bytes()));
+ let ifd = u32::try_from(f.len()).unwrap();
+ f[4..8].copy_from_slice(&ifd.to_le_bytes());
+ let strip = u32::try_from(u64::from(width) * u64::from(samples) * u64::from(bits / 8)).unwrap();
+ // (tag, type (3 SHORT, 4 LONG), count, value or offset)
+ let entries = [
+ (256u16, 4u16, 1, width),
+ (257, 4, 1, 1),
+ (258, 3, 1, u32::from(bits)),
+ (259, 3, 1, 1),
+ (262, 3, 1, 5),
+ (273, 4, 1, 8),
+ (277, 3, 1, u32::from(samples)),
+ (278, 4, 1, 1),
+ (279, 4, 1, strip),
+ (284, 3, 1, 1),
+ (338, 3, u32::try_from(extras.len()).unwrap(), at),
+ ];
+ f.extend(u16::try_from(entries.len()).unwrap().to_le_bytes());
+ for (tag, ty, count, value) in entries {
+ f.extend([tag.to_le_bytes(), ty.to_le_bytes()].concat());
+ f.extend([count.to_le_bytes(), value.to_le_bytes()].concat());
+ }
+ f.extend([0; 4]);
+ f
+ }
+
+ /// A CMYK TIFF whose first ExtraSamples value is alpha has the color type of CMYK with alpha,
+ /// five samples, however many samples its pixels have; one with more than
+ /// [`MAX_EXTRA_SAMPLES_PIXEL`] is refused from its tags, before the decoder takes a row of
+ /// every sample (here 8,192 × 65,535 × 2 bytes, 1 GiB). Neither is it read as inks.
+ #[test]
+ fn a_cmyk_tiff_with_more_samples_a_pixel_than_the_limit_is_refused_before_decoding() {
+ let (width, samples) = (8192u32, u16::MAX);
+ for first in [1u16, 0] {
+ let extras: Vec = std::iter::once(first).chain(std::iter::repeat_n(0, usize::from(samples) - 5)).collect();
+ let bytes = cmyk_header(width, samples, 16, &extras);
+ let mut d = tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap();
+ let kind = d.colortype().unwrap();
+ assert_eq!(kind, if first == 1 { tiff::ColorType::CMYKA(16) } else { tiff::ColorType::CMYK(16) });
+ assert_eq!(row_buffer(&mut d), None, "{kind:?}: refused from the tags");
+ let given = usize::from(kind.num_samples());
+ assert!(with_room(d, bytes.len(), usize::try_from(width).unwrap(), given, 16).is_none(), "{kind:?}: refused before the decode");
+ assert!(extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).is_none(), "{kind:?}");
+ assert!(ImageBlob::new("image/tiff", bytes).cmyk().is_none(), "{kind:?}: no inks");
+ }
+ }
+
+ /// The row the decoder reads each strip of a CMYK TIFF with alpha into, every sample of the
+ /// row, counts in the allowance: 2²⁴ pixels of 64 16-bit samples, whose five decoded samples
+ /// and RGBA pixels fit but not with that row of 2 GiB.
+ #[test]
+ fn the_decoders_row_of_every_sample_counts_in_the_allowance() {
+ let width = 1u32 << 24;
+ let samples = u16::try_from(MAX_EXTRA_SAMPLES_PIXEL).unwrap();
+ let extras: Vec = std::iter::once(2).chain(std::iter::repeat_n(0, usize::from(samples) - 5)).collect();
+ let bytes = cmyk_header(width, samples, 16, &extras);
+ let n = usize::try_from(width).unwrap();
+ let (need, rgba, row) = (u64::from(width) * 5 * 2, u64::from(width) * 4, u64::from(width) * u64::from(samples) * 2);
+ assert!(need + rgba <= crate::MAX_RASTER_ALLOC && need + rgba + row > crate::MAX_RASTER_ALLOC);
+ let mut d = tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap();
+ assert_eq!(d.colortype().unwrap(), tiff::ColorType::CMYKA(16));
+ assert_eq!(row_buffer(&mut d), Some(row));
+ assert!(with_room(d, bytes.len(), n, 5, 16).is_none(), "refused before the decode");
+ assert!(extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).is_none());
+ }
+
+ /// A TIFF whose samples aren't unsigned integers is refused from its tags.
+ #[test]
+ fn a_tiff_of_float_samples_is_refused_from_its_tags() {
+ use tiff::encoder::colortype::{Gray8, Gray32Float};
+ let mut file = Cursor::new(Vec::new());
+ tiff::encoder::TiffEncoder::new(&mut file).unwrap().write_image::(2, 1, &[0.25, 0.5]).unwrap();
+ let float = file.into_inner();
+ let mut d = tiff::decoder::Decoder::new(Cursor::new(&float[..])).unwrap();
+ assert_eq!(row_buffer(&mut d), None, "floats: refused");
+ assert!(read_samples_at_depth(&mut d, 2, 1).is_none());
+ let mut file = Cursor::new(Vec::new());
+ tiff::encoder::TiffEncoder::new(&mut file).unwrap().write_image::(2, 1, &[64, 128]).unwrap();
+ let bytes = file.into_inner();
+ let mut d = tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap();
+ assert_eq!(row_buffer(&mut d), Some(0), "unsigned: no extra row");
+ assert_eq!(read_samples_at_depth(&mut d, 2, 1), Some(Samples::Eight(vec![64, 128])));
+ }
+
+ /// The copy that puts a planar file's samples pixel by pixel is allocated at its length, so
+ /// the reader holds no more than the allowance counts. 33 samples: a copy that grew as it
+ /// was filled would hold room for 64.
+ #[test]
+ fn the_planar_copy_is_allocated_at_its_length() {
+ let (n, per) = (11u8, 3u8);
+ let data: Vec = (0..n * per).collect();
+ let len = data.len();
+ let out = chunky(data, usize::from(per), usize::from(n), usize::from(per)).unwrap();
+ let pixel_by_pixel: Vec = (0..n).flat_map(|i| (0..per).map(move |p| p * n + i)).collect();
+ assert_eq!(out, pixel_by_pixel);
+ assert!(out.capacity() >= len && out.capacity() < len.next_power_of_two(), "capacity {} for {len} samples", out.capacity());
+ }
+
+ /// A TIFF whose decoded samples fit [`crate::MAX_RASTER_ALLOC`] but not with its RGBA pixels
+ /// beside them is refused before its samples are decoded; so is one whose samples fit with
+ /// the RGBA pixels but not with the copy a planar file needs. The file holds one row of pixels,
+ /// which every strip reuses.
+ #[test]
+ fn a_tiff_whose_decode_with_its_rgba_takes_more_than_the_allowance_is_refused() {
+ let side = 8192u32;
+ let n = usize::try_from(u64::from(side) * u64::from(side)).unwrap();
+ assert_eq!(u64::try_from(n).unwrap(), MAX_CMYK_PIXELS);
+ let max = usize::try_from(crate::MAX_RASTER_ALLOC).unwrap();
+ // One sample fewer than fills the allowance: the samples alone fit.
+ let per = max / n - 1;
+ assert!(n * per <= max && n * per + 4 * n > max);
+ let bytes = tall_gray_tiff(side, side, u16::try_from(per).unwrap());
+ let decoder = || tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap();
+ assert!(with_room(decoder(), bytes.len(), n, per, 8).is_none(), "refused before the decode");
+ assert!(extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).is_none());
+ // Half the allowance in samples fits with the RGBA pixels, but not twice over.
+ let half = max / n / 2;
+ assert!(with_room(decoder(), bytes.len(), n, half, 8).is_some(), "stored together: fits");
+ let planar = gray_tiff(side, side, u16::try_from(half).unwrap(), true);
+ let decoder = tiff::decoder::Decoder::new(Cursor::new(&planar[..])).unwrap();
+ assert!(with_room(decoder, planar.len(), n, half, 8).is_none(), "one plane per sample: refused");
+ }
+
+ /// Patched bytes read the same whole, a byte at a time and after a seek into a patch.
+ #[test]
+ fn patched_bytes_read_with_their_patches() {
+ use std::io::{Read, Seek, SeekFrom};
+ let bytes: Vec = (10..30).collect();
+ let patched = || Patched { bytes: Cursor::new(&bytes[..]), patches: vec![(4, &[1, 0]), (19, &[7, 7])] };
+ let want = [10, 11, 12, 13, 1, 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 7];
+ let mut whole = Vec::new();
+ patched().read_to_end(&mut whole).unwrap();
+ assert_eq!(whole, want);
+ let mut one = patched();
+ let bytewise: Vec = (0..want.len())
+ .map(|_| {
+ let mut b = [0];
+ assert_eq!(one.read(&mut b).unwrap(), 1);
+ b[0]
+ })
+ .collect();
+ assert_eq!(bytewise, want);
+ let mut from = patched();
+ from.seek(SeekFrom::Start(5)).unwrap();
+ let mut b = [9; 3];
+ from.read_exact(&mut b).unwrap();
+ assert_eq!(b, [0, 16, 17], "the second byte of the first patch, then the file");
+ }
+
+ /// A grayscale TIFF whose alpha follows another extra sample reads that alpha.
+ #[test]
+ fn a_grayscale_tiff_with_alpha_after_another_extra_sample_reads_its_alpha() {
+ let read =
+ |extra: [u16; 2], data: &[u8]| extra_samples_tiff_rgba(&extras_tiff::(&extra, data), |_| [0.0; 3]).expect("reads").into_raw();
+ // A gray of 64 at an alpha of 204 (premultiplied: 51), with an extra sample of 9.
+ assert_eq!(read([0, 2], &[64, 9, 204]), [64, 64, 64, 204], "unassociated");
+ assert_eq!(read([0, 1], &[51, 9, 204]), [64, 64, 64, 204], "associated, divided back out");
+ assert_eq!(read([2, 0], &[64, 204, 9]), [64, 64, 64, 204], "the alpha first");
+ assert_eq!(read([0, 0], &[64, 9, 204]), [64, 64, 64, 255], "no alpha: opaque");
+ }
+
+ /// A grayscale TIFF whose white is zero (PhotometricInterpretation 0), with alpha, reads with
+ /// its levels turned around.
+ #[test]
+ fn a_white_is_zero_grayscale_tiff_with_alpha_reads_as_rgba() {
+ // White, opaque; black at an alpha of 128.
+ let bytes = extras_tiff::(&[2], &[0, 255, 255, 128]);
+ let px = extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).expect("reads");
+ assert_eq!(px.into_raw(), [255, 255, 255, 255, 0, 0, 0, 128]);
+ }
+
/// A header claiming more tiles than can be counted: (2^32 − 1)² pixels in tiles of one pixel,
/// times 2 planes.
#[test]
diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs
index b0c50d5042..54d97a4527 100644
--- a/crates/effects/src/bake.rs
+++ b/crates/effects/src/bake.rs
@@ -199,8 +199,19 @@ fn placed_fits(baked: &Node, spent: u64, dropped: u64) -> Option {
}
/// The names of the symbols of `d` whose art needs baking ([`needs_bake`]), and of those whose art
-/// holds an instance of one of them at any depth.
+/// holds an instance of one of them at any depth, in the art of enabled opacity masks too.
fn drawn_symbols(d: &Document) -> HashSet {
+ fn used(n: &Node, names: &mut Vec) {
+ if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
+ names.push(symbol.clone());
+ }
+ if let Some(m) = n.extras().mask.as_ref().filter(|m| !m.disabled) {
+ used(&m.art, names);
+ }
+ for c in n.children().into_iter().flatten() {
+ used(c, names);
+ }
+ }
let mut out: HashSet = d.symbols.iter().filter(|s| needs_bake(&s.art)).map(|s| s.name.clone()).collect();
if out.is_empty() {
return out;
@@ -211,11 +222,7 @@ fn drawn_symbols(d: &Document) -> HashSet {
.filter(|s| !out.contains(&s.name))
.map(|s| {
let mut names = vec![];
- s.art.walk(&mut |c| {
- if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
- names.push(symbol.clone());
- }
- });
+ used(&s.art, &mut names);
(s.name.as_str(), names)
})
.collect();
@@ -233,14 +240,22 @@ fn drawn_symbols(d: &Document) -> HashSet {
}
/// Does `n`'s subtree hold an instance of a symbol that [`bake_document_placing_symbols`] replaces
-/// by its placed art? False outside it, and for objects the export does not write ([`unwritten`]).
+/// by its placed art, in the art of its enabled opacity masks too? False outside it, and for
+/// objects the export does not write ([`unwritten`]).
fn holds_placed_symbol(n: &Node) -> bool {
- fn walk(n: &Node, symbols: &HashSet) -> bool {
+ placed_symbol_in(n, true)
+}
+
+/// [`holds_placed_symbol`], with the art of `n`'s own opacity mask left out unless `own_mask`
+/// (the art of the masks inside `n` is always looked into).
+fn placed_symbol_in(n: &Node, own_mask: bool) -> bool {
+ fn walk(n: &Node, symbols: &HashSet, own_mask: bool) -> bool {
!unwritten(n)
&& (matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.contains(symbol))
- || n.children().is_some_and(|ch| ch.iter().any(|c| walk(c, symbols))))
+ || (own_mask && !n.is_ruler_guide() && n.extras().mask.as_ref().is_some_and(|m| !m.disabled && walk(&m.art, symbols, true)))
+ || n.children().is_some_and(|ch| ch.iter().any(|c| walk(c, symbols, true))))
}
- !UNWRITTEN.with(|c| c.get()) && PLACING.with(|p| p.borrow().as_ref().is_some_and(|p| walk(n, &p.symbols)))
+ !UNWRITTEN.with(|c| c.get()) && PLACING.with(|p| p.borrow().as_ref().is_some_and(|p| walk(n, &p.symbols, own_mask)))
}
/// Symbol instance `n`, while [`bake_document_placing_symbols`] bakes and its symbol is one it
@@ -278,8 +293,29 @@ fn placed_symbol_art(d: &Document, n: &Node) -> Option<(Node, u64)> {
Some((g, most))
}
-/// `n` with its geometry effects evaluated (`None` = unchanged).
+/// `n` with its geometry effects evaluated (`None` = unchanged), and the art of its enabled opacity
+/// mask baked one level deeper when it holds instances that [`bake_document_placing_symbols`]
+/// places ([`holds_placed_symbol`]), so the mask masks with the art the instances draw. The art is
+/// baked only while the object baked from `n` still carries `n`'s mask art; art already baked
+/// with `n`'s recolored or placed form is not baked again. A ruler guide's mask stays as it is.
fn bake_node(d: &mut Document, n: &Node) -> Option {
+ let out = bake_object(d, n);
+ let Some(mask) = n.extras().mask.as_ref().filter(|m| !m.disabled && !n.is_ruler_guide() && !unwritten(n) && holds_placed_symbol(&m.art)) else {
+ return out;
+ };
+ let changed = out.is_some();
+ let mut out = out.unwrap_or_else(|| n.clone());
+ let Some(slot) = out.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|s| Arc::ptr_eq(&s.art, &mask.art)) else {
+ return changed.then_some(out);
+ };
+ let Some(art) = one_deeper(|| bake_node(d, &mask.art)) else { return changed.then_some(out) };
+ slot.art = Arc::new(art);
+ Some(out)
+}
+
+/// `n` with its geometry effects evaluated (`None` = unchanged); its opacity mask is left to
+/// [`bake_node`].
+fn bake_object(d: &mut Document, n: &Node) -> Option {
// Inside an object the export leaves out, effects are baked but no instance is placed.
if !UNWRITTEN.with(|c| c.get()) && unwritten(n) {
UNWRITTEN.with(|c| c.set(true));
@@ -289,7 +325,8 @@ fn bake_node(d: &mut Document, n: &Node) -> Option {
}
// A cancelled export leaves the rest of the document as it is: the caller drops the result.
// A ruler guide draws nothing and stays as it is, last in its layer.
- if n.is_ruler_guide() || !(needs_bake(n) || holds_placed_symbol(n)) || vectorcraft_doc::cancel::is_cancelled() {
+ // An object whose own mask's art alone holds placed instances stays as it is here.
+ if n.is_ruler_guide() || !(needs_bake(n) || placed_symbol_in(n, false)) || vectorcraft_doc::cancel::is_cancelled() {
return None;
}
// Colour adjustments: the object recoloured (inside it too), then baked as it is.
diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs
index 7b353f78f9..fba4f75e5f 100644
--- a/crates/effects/src/bake/tests.rs
+++ b/crates/effects/src/bake/tests.rs
@@ -1169,6 +1169,74 @@ fn placing_symbols_reaches_the_art_of_nested_instances() {
assert!(near_rect(bounds(&out, 900), Rect::new(110.0, 140.0, 120.0, 150.0)), "{:?}", bounds(&out, 900));
}
+/// A 10 pt square with id `id`, masked by `art` (the mask enabled unless `disabled`).
+fn masked_square(id: u64, art: Node, disabled: bool) -> Node {
+ let mut n = Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
+ let mut mask = vectorcraft_doc::OpacityMask::new(art, false);
+ mask.disabled = disabled;
+ n.extras_mut().mask = Some(Box::new(mask));
+ n
+}
+
+/// Whether the art of `n`'s opacity mask is still a symbol instance, and its bounds when it is not.
+fn mask_art(n: &Node) -> (bool, Option) {
+ let art = &n.extras().mask.as_ref().unwrap_or_else(|| panic!("node {:?} has a mask", n.id)).art;
+ (matches!(art.kind, NodeKind::SymbolInstance { .. }), art.geometric_bounds())
+}
+
+/// An instance in the art of an enabled opacity mask is placed and baked like any other, so the
+/// mask masks with the art the instance draws, and the masked object stays as it is (a clipping
+/// path stays one); one in a disabled mask, in the mask of an object the export leaves out, or in
+/// a ruler guide's mask, stays as it is.
+#[test]
+fn placing_symbols_reaches_instances_in_opacity_masks() {
+ use vectorcraft_geom::Affine;
+ let mut d = doc_with(masked_square(700, instance(900, "S", Affine::IDENTITY), false));
+ let layer = d.layers[0].id;
+ d.insert(Some(layer), 1, masked_square(701, instance(901, "S", Affine::IDENTITY), true)).unwrap();
+ let mut hidden = masked_square(702, instance(902, "S", Affine::IDENTITY), false);
+ hidden.visible = false;
+ d.insert(Some(layer), 2, hidden).unwrap();
+ let mut clipping = masked_square(703, instance(903, "S", Affine::IDENTITY), false);
+ if let NodeKind::Path { clipping: c, .. } = &mut clipping.kind {
+ *c = true;
+ }
+ d.insert(Some(layer), 3, Node::group(NodeId(704), vec![Arc::new(clipping)])).unwrap();
+ let mut guide = Node::new(NodeId(705), NodeKind::RulerGuide { vertical: false, pos: 5.0, artboard: None });
+ guide.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(instance(905, "S", Affine::IDENTITY), false)));
+ d.insert(Some(layer), 4, guide).unwrap();
+ add_symbol(&mut d, "S", moved_square(800));
+ let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
+ for id in [700, 703] {
+ let (still, b) = mask_art(out.node(NodeId(id)).unwrap());
+ assert!(!still && b.is_some_and(|b| near_rect(b, Rect::new(110.0, 40.0, 120.0, 50.0))), "{id}: {b:?}");
+ }
+ assert!(matches!(out.node(NodeId(703)).unwrap().kind, NodeKind::Path { clipping: true, .. }), "the clipping path stays one");
+ assert!(mask_art(out.node(NodeId(701)).unwrap()).0, "a disabled mask's instance stays");
+ assert!(mask_art(out.node(NodeId(702)).unwrap()).0, "a hidden object's mask's instance stays");
+ assert!(mask_art(out.node(NodeId(705)).unwrap()).0, "a ruler guide's mask's instance stays");
+}
+
+/// A symbol whose art holds an instance only in an opacity mask's art is placed too, and the
+/// instance in its mask is placed with it.
+#[test]
+fn placing_symbols_reaches_instances_in_the_masks_of_symbol_art() {
+ use vectorcraft_geom::Affine;
+ let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY));
+ add_symbol(&mut d, "Inner", moved_square(800));
+ add_symbol(&mut d, "Outer", masked_square(803, instance(802, "Inner", Affine::IDENTITY), false));
+ let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
+ assert!(!is_instance(&out, 900), "the outer instance is placed");
+ let mut found = None;
+ out.node(NodeId(900)).unwrap().walk(&mut |n| {
+ if n.id == NodeId(803) {
+ found = Some(mask_art(n));
+ }
+ });
+ let (still, b) = found.unwrap_or_else(|| panic!("the masked square is in the placed art"));
+ assert!(!still && b.is_some_and(|b| near_rect(b, Rect::new(110.0, 40.0, 120.0, 50.0))), "{b:?}");
+}
+
/// A symbol whose art holds an instance of itself is placed until the depth limit, and the export
/// ends.
#[test]
diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs
index 424beebe17..67677656e6 100644
--- a/crates/effects/src/catalog.rs
+++ b/crates/effects/src/catalog.rs
@@ -468,8 +468,8 @@ pub fn effect_catalog() -> Vec {
"blur.radial",
"Radial Blur…",
BLUR,
- "{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples)} blurs around the object's centre",
- json!({"amount": 10.0, "method": "spin", "quality": "good"}),
+ "{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples), centerX: 0..1 (0.5; the Blur Center across the object's bounds, 0 their left edge), centerY: 0..1 (0.5; the Blur Center down the object's bounds, 0 their top edge)} blurs around the Blur Center, which moves and scales with the object. A centerX or centerY outside 0..1 is refused",
+ json!({"amount": 10.0, "method": "spin", "quality": "good", "centerX": 0.5, "centerY": 0.5}),
),
r(
"blur.smart",
diff --git a/crates/effects/src/pixel.rs b/crates/effects/src/pixel.rs
index 89eb541b19..0c159f8485 100644
--- a/crates/effects/src/pixel.rs
+++ b/crates/effects/src/pixel.rs
@@ -30,7 +30,7 @@ mod texture;
mod video;
use serde_json::Value;
-use vectorcraft_geom::{Affine, Point, Rect};
+use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use crate::util::{flag, num, text};
@@ -158,9 +158,10 @@ pub enum PixelFx {
/// (1..20), then a [`Texture`] surface scaled by `scaling` (0.5..2), in relief as strong as
/// `relief` (0..50) and lit from `light`; `invert` turns the surface's heights over.
RoughPastels { length: f64, detail: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool },
- /// Blur › Radial Blur around the object's centre: along arcs (spin, an arc of `amount`°) or
- /// along rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples.
- RadialBlur { amount: f64, zoom: bool, passes: u32 },
+ /// Blur › Radial Blur around its Blur Center, `center` (0..1 across and down the object's
+ /// bounds; (0.5, 0.5) the object's centre): along arcs (spin, an arc of `amount`°) or along
+ /// rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples.
+ RadialBlur { amount: f64, zoom: bool, passes: u32, center: [f64; 2] },
/// Blur › Smart Blur (Normal mode): each pixel averaged with the neighbours within `radius`
/// whose colour differs from its own by no more than `threshold` levels, over a grid of
/// `samples` × `samples` neighbours at most.
@@ -314,9 +315,12 @@ pub struct PixelSpace {
pub to_doc: Affine,
/// The size of a pixel in document units.
pub px: f64,
- /// The object's centre (document coordinates): where Radial Blur blurs around, and where the
- /// Pixelate filters' patterns are anchored (so they move with the object).
+ /// The object's centre (document coordinates): where Radial Blur blurs around by default, and
+ /// where the Pixelate filters' patterns are anchored (so they move with the object).
pub center: Point,
+ /// The width and height of the object's bounds (document units), centred on `center`: Radial
+ /// Blur's Blur Center lies at a share of them.
+ pub size: Vec2,
/// What the colour channels hold.
pub channels: Channels,
/// The height of a line of the document's raster grid (document units: 72 / Document Raster
@@ -421,6 +425,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option {
amount: num(p, "amount", 10.0).clamp(1.0, 100.0),
zoom: text(p, "method", "spin").eq_ignore_ascii_case("zoom"),
passes: quality([("draft", 4), ("good", 6), ("best", 8)], 6),
+ center: [num(p, "centerX", 0.5).clamp(0.0, 1.0), num(p, "centerY", 0.5).clamp(0.0, 1.0)],
},
"blur.smart" => PixelFx::SmartBlur {
radius: num(p, "radius", 3.0).clamp(0.1, 100.0),
@@ -608,13 +613,13 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option {
impl PixelFx {
/// How far beyond `bounds` (the content's, document units) the effect can paint.
pub fn outset(&self, bounds: Rect) -> f64 {
- // From the centre to the farthest corner, and to the nearest side.
- let far = 0.5 * bounds.width().hypot(bounds.height());
- let near = 0.5 * bounds.width().min(bounds.height());
match *self {
- // A rotated corner reaches the circle through the corners.
- PixelFx::RadialBlur { zoom: false, .. } => (far - near).max(0.0),
- PixelFx::RadialBlur { amount, zoom: true, .. } => far * (blur::zoom_extent(amount).exp() - 1.0),
+ // A rotated corner reaches the circle about the Blur Center through the farthest corner.
+ PixelFx::RadialBlur { zoom: false, center, .. } => {
+ let (far, near) = blur::center_reach(bounds, center);
+ (far - near).max(0.0)
+ }
+ PixelFx::RadialBlur { amount, zoom: true, center, .. } => blur::center_reach(bounds, center).0 * (blur::zoom_extent(amount).exp() - 1.0),
PixelFx::SmartBlur { radius, .. } => radius,
PixelFx::AccentedEdges { .. } => 0.0,
// Strokes reach out of the object as far as they reach into it.
@@ -786,7 +791,7 @@ impl PixelFx {
PixelFx::RoughPastels { length, detail, ref texture, scaling, relief, light, invert } => {
artistic::rough_pastels(px, w, h, space, length, detail, texture, scaling, relief, light, invert)
}
- PixelFx::RadialBlur { amount, zoom, passes } => blur::radial(px, w, h, space, amount, zoom, passes),
+ PixelFx::RadialBlur { amount, zoom, passes, center } => blur::radial(px, w, h, space, amount, zoom, passes, center),
PixelFx::SmartBlur { radius, threshold, samples, mode: SmartBlurMode::Normal } => {
blur::smart(px, w, h, to_px(radius), threshold, samples)
}
diff --git a/crates/effects/src/pixel/blur.rs b/crates/effects/src/pixel/blur.rs
index 0a061571ba..877061922d 100644
--- a/crates/effects/src/pixel/blur.rs
+++ b/crates/effects/src/pixel/blur.rs
@@ -1,6 +1,6 @@
//! Blur › Radial Blur and Smart Blur (Normal, Edge Only and Overlay Edge).
-use vectorcraft_geom::{Affine, Point, Vec2};
+use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use super::{PixelSpace, Px16, box_blur, pick, to8, to16};
@@ -29,13 +29,31 @@ fn bilinear(buf: &[Px16], w: usize, h: usize, x: f64, y: f64) -> [f32; 4] {
std::array::from_fn(|i| a[i] * wa + b[i] * wb + c[i] * wc + d[i] * wd)
}
-/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the centre over
-/// evenly spaced steps spanning `amount`. Each pass averages the previous result with itself
-/// turned both ways by half the last step, so `passes` passes average 2^`passes` samples at two
-/// lookups a pixel each.
-pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32) {
+/// How far Radial Blur's Blur Center `center` (0..1 across and down `bounds`) lies from the
+/// farthest corner of `bounds`, and from its nearest side.
+pub(super) fn center_reach(bounds: Rect, center: [f64; 2]) -> (f64, f64) {
+ // The share of the width (height) on the far side of the center, doubled: 1 at the middle.
+ let far = |f: f64| 1.0 + (2.0 * f - 1.0).abs();
+ let (w, h) = (bounds.width(), bounds.height());
+ let near = ((2.0 - far(center[0])) * w).min((2.0 - far(center[1])) * h);
+ (0.5 * (far(center[0]) * w).hypot(far(center[1]) * h), 0.5 * near)
+}
+
+/// Where Radial Blur's Blur Center `center` (0..1 across and down the object's bounds) lies in the
+/// document: the object's centre at (0.5, 0.5).
+pub(super) fn blur_center(space: &PixelSpace, center: [f64; 2]) -> Point {
+ let shift = Vec2::new((center[0] - 0.5) * space.size.x, (center[1] - 0.5) * space.size.y);
+ if shift.x.is_finite() && shift.y.is_finite() { space.center + shift } else { space.center }
+}
+
+/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the Blur Center
+/// (`center`, [`blur_center`]) over evenly spaced steps spanning `amount`. Each pass averages the
+/// previous result with itself turned both ways by half the last step, so `passes` passes average
+/// 2^`passes` samples at two lookups a pixel each.
+#[allow(clippy::too_many_arguments)] // the effect's four options
+pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32, center: [f64; 2]) {
// The centre in pixel index coordinates (pixel centres at whole numbers).
- let c = space.to_doc.inverse() * space.center - Vec2::new(0.5, 0.5);
+ let c = space.to_doc.inverse() * blur_center(space, center) - Vec2::new(0.5, 0.5);
if !(c.x.is_finite() && c.y.is_finite()) {
return;
}
diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs
index a1a083f0fe..a1e73eab33 100644
--- a/crates/effects/src/pixel/tests.rs
+++ b/crates/effects/src/pixel/tests.rs
@@ -12,6 +12,7 @@ fn space(w: usize, h: usize) -> PixelSpace {
to_doc: Affine::IDENTITY,
px: 1.0,
center: Point::new(w / 2.0, h / 2.0),
+ size: vectorcraft_geom::Vec2::new(w, h),
channels: Channels::Rgb,
line: 1.0,
extent: 0.5 * w.hypot(h),
@@ -479,12 +480,16 @@ fn film_grain_leaves_invalid_coordinate_spaces_alone() {
#[test]
fn params_take_defaults_and_stay_in_range() {
- assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6 });
+ assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6, center: [0.5, 0.5] });
assert_eq!(
- fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best"})),
- PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8 }
+ fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best", "centerX": 0.25, "centerY": 1})),
+ PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8, center: [0.25, 1.0] }
+ );
+ // A saved center outside the bounds (the commands refuse one) draws at the nearest edge.
+ assert_eq!(
+ fx("blur.radial", json!({"amount": -5, "quality": "nonsense", "centerX": -3, "centerY": 7})),
+ PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6, center: [0.0, 1.0] }
);
- assert_eq!(fx("blur.radial", json!({"amount": -5, "quality": "nonsense"})), PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6 });
assert_eq!(fx("blur.smart", json!({})), PixelFx::SmartBlur { radius: 3.0, threshold: 25.0, samples: 7, mode: SmartBlurMode::Normal });
assert_eq!(
fx("blur.smart", json!({"radius": "1e999", "threshold": -1, "quality": "low", "blurMode": "EDGEONLY"})),
@@ -519,6 +524,11 @@ fn outsets_follow_the_object() {
let far = 0.5 * 100f64.hypot(50.0);
assert!((spin.outset(b) - (far - 25.0)).abs() < 1e-9);
assert!(fx("blur.radial", json!({"method": "zoom", "amount": 100})).outset(b) > 0.4 * far);
+ // About a corner the spin reaches the circle through the opposite corner, the whole diagonal out.
+ let corner = fx("blur.radial", json!({"centerX": 0, "centerY": 0}));
+ assert!((corner.outset(b) - 100f64.hypot(50.0)).abs() < 1e-9, "{}", corner.outset(b));
+ let zoom = |center: f64| fx("blur.radial", json!({"method": "zoom", "amount": 100, "centerX": center, "centerY": center})).outset(b);
+ assert!((zoom(1.0) - 2.0 * zoom(0.5)).abs() < 1e-9, "a zoom about a corner reaches twice as far");
assert_eq!(fx("blur.smart", json!({"radius": 4})).outset(b), 4.0);
assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(1.0), Some(4.0));
// The edge modes also read the copy blurred over a wide radius's samples.
@@ -633,6 +643,40 @@ fn spin_blur_smears_along_arcs_and_keeps_the_centre() {
assert_eq!(at(&z, w, 32, 16)[3], 0, "not across it");
}
+/// The Blur Center moves the point the blur turns about: a dot on it stays sharp, a dot on the
+/// object's centre then spreads, and the center follows the object when it moves or is scaled.
+#[test]
+fn radial_blur_turns_about_its_blur_center() {
+ let (w, h) = (41, 41);
+ // A dot on pixel (10, 30), whose centre (10.5, 30.5) is the Blur Center below, and one on the
+ // object's centre.
+ let src = image(w, h, |x, y| if (x == 10 && y == 30) || (x == 20 && y == 20) { grey(255) } else { [0, 0, 0, 0] });
+ let blur = |p: serde_json::Value, s: &PixelSpace, src: &[u8]| {
+ let mut d = src.to_vec();
+ fx("blur.radial", p).apply(&mut d, w, h, s);
+ d
+ };
+ let off = json!({"amount": 60, "quality": "best", "centerX": 10.5 / 41.0, "centerY": 30.5 / 41.0});
+ let d = blur(off.clone(), &space(w, h), &src);
+ assert!(at(&d, w, 10, 30)[3] > 100, "the dot on the Blur Center barely moves: {:?}", at(&d, w, 10, 30));
+ assert!(at(&d, w, 20, 20)[3] < 100, "the dot on the object's centre spreads: {:?}", at(&d, w, 20, 20));
+ // The default center is the object's centre, the same as no center at all.
+ assert_eq!(blur(json!({"amount": 60, "centerX": 0.5, "centerY": 0.5}), &space(w, h), &src), blur(json!({"amount": 60}), &space(w, h), &src));
+ // Moved 7 pt right and 3 pt down, the object draws the same pixels.
+ let moved =
+ PixelSpace { to_doc: Affine::translate((7.0, 3.0)), center: space(w, h).center + vectorcraft_geom::Vec2::new(7.0, 3.0), ..space(w, h) };
+ assert_eq!(blur(off.clone(), &moved, &src), d, "the center moves with the object");
+ // Drawn at twice the size (two points a pixel), the center lies on the same pixels.
+ let big = PixelSpace {
+ to_doc: Affine::scale(2.0),
+ px: 2.0,
+ center: Point::new(41.0, 41.0),
+ size: vectorcraft_geom::Vec2::new(82.0, 82.0),
+ ..space(w, h)
+ };
+ assert_eq!(blur(off, &big, &src), d, "the center scales with the object");
+}
+
#[test]
fn smart_blur_smooths_noise_and_keeps_edges() {
let (w, h) = (40, 20);
@@ -862,6 +906,7 @@ fn lengths_are_document_units() {
to_doc: Affine::scale(1.0 / scale as f64),
px: 1.0 / scale as f64,
center: Point::ZERO,
+ size: vectorcraft_geom::Vec2::ZERO,
channels: Channels::Rgb,
line: 1.0,
extent: 0.0,
@@ -916,7 +961,15 @@ fn linear_light_blur_mixes_light_not_values() {
fn pixel_timings() {
let (w, h) = (2000, 2000);
let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]);
- let s = PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1000.0, 1000.0), channels: Channels::Rgb, line: 1.0, extent: 0.0 };
+ let s = PixelSpace {
+ to_doc: Affine::IDENTITY,
+ px: 1.0,
+ center: Point::new(1000.0, 1000.0),
+ size: vectorcraft_geom::Vec2::new(2000.0, 2000.0),
+ channels: Channels::Rgb,
+ line: 1.0,
+ extent: 0.0,
+ };
let cases = [
("blur.radial", json!({"quality": "draft"})),
("blur.radial", json!({"quality": "good"})),
diff --git a/crates/effects/src/pixel/tests_paint.rs b/crates/effects/src/pixel/tests_paint.rs
index e84e587c9a..20fb8d10f2 100644
--- a/crates/effects/src/pixel/tests_paint.rs
+++ b/crates/effects/src/pixel/tests_paint.rs
@@ -14,6 +14,7 @@ fn space(w: usize, h: usize) -> PixelSpace {
to_doc: Affine::IDENTITY,
px: 1.0,
center: Point::new(w / 2.0, h / 2.0),
+ size: vectorcraft_geom::Vec2::new(w, h),
channels: Channels::Rgb,
line: 1.0,
extent: 0.5 * w.hypot(h),
diff --git a/crates/effects/src/pixel/tests_sketch.rs b/crates/effects/src/pixel/tests_sketch.rs
index fd467a23ca..127b79c5f0 100644
--- a/crates/effects/src/pixel/tests_sketch.rs
+++ b/crates/effects/src/pixel/tests_sketch.rs
@@ -14,6 +14,7 @@ fn space(w: usize, h: usize) -> PixelSpace {
to_doc: Affine::IDENTITY,
px: 1.0,
center: Point::new(w / 2.0, h / 2.0),
+ size: vectorcraft_geom::Vec2::new(w, h),
channels: Channels::Rgb,
line: 1.0,
extent: 0.5 * w.hypot(h),
diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs
index ab163e45cd..945eb639aa 100644
--- a/crates/effects/src/solids/tests.rs
+++ b/crates/effects/src/solids/tests.rs
@@ -1115,6 +1115,44 @@ fn the_check_builds_the_profile_of_a_shape_with_no_fill() {
}
}
+/// A filled shape is checked about the bounds the effect draws its solid about, which take in the
+/// strokes beside it. A shape of many small curves is too complex for Extrude & Bevel about the
+/// shapes' own bounds, where its curves are sampled more finely, and passes about the bounds of a
+/// wide stroke in its group, as its solid draws there.
+#[test]
+fn the_check_builds_a_filled_shape_about_the_bounds_its_solid_draws_about() {
+ // 900 curves about (100, 100), each bulging 1 pt out from a side of a polygon 80 pt across.
+ let corners = 900;
+ let center = Point::new(100.0, 100.0);
+ let corner = |k: usize| {
+ let (s, c) = (k as f64 * std::f64::consts::TAU / corners as f64).sin_cos();
+ Point::new(center.x + 40.0 * c, center.y + 40.0 * s)
+ };
+ let mut b = BezPath::new();
+ b.move_to(corner(0));
+ for k in 0..corners {
+ let (p0, p3) = (corner(k), corner(k + 1));
+ let out = p0.midpoint(p3) - center;
+ let out = out / out.hypot();
+ b.curve_to(p0 + (p3 - p0) / 3.0 + out, p0 + (p3 - p0) * (2.0 / 3.0) + out, p3);
+ }
+ b.close_path();
+ let filled = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
+ let mut line = BezPath::new();
+ line.move_to((80.0, 100.0));
+ line.line_to((120.0, 100.0));
+ let mut wide = Node::path(NodeId(2), PathData::from_bezpath(&line), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2000.0));
+ wide.appearance.items.retain(|i| matches!(i, AppearanceItem::Stroke(_)));
+ let p = json!({"bevel": "rounded", "bevelRepeat": 6});
+ let (path, rule) = profile(&filled).unwrap();
+ let own = path.bounds().unwrap().union(wide.path_data().unwrap().bounds().unwrap());
+ assert_eq!(facets(EXTRUDE, &path, rule, own, &p).map(|_| ()), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()), "about its own bounds");
+ let mut g = Node::group(NodeId(9999), vec![Arc::new(filled), Arc::new(wide)]);
+ assert_eq!(validate_solid(&g, EXTRUDE, &p), Ok(()));
+ g.appearance.effects.push(fx(EXTRUDE, p));
+ assert!(solid_art(&g).is_some(), "the solid draws");
+}
+
/// A convex polygon of `corners` corners about (20,000, 20,000), filled red, with no stroke.
fn polygon_node(id: u64, corners: usize) -> Node {
let points: Vec = (0..corners)
diff --git a/crates/effects/src/svg_filter/defaults.rs b/crates/effects/src/svg_filter/defaults.rs
index 5ce67fac6b..95a84ca273 100644
--- a/crates/effects/src/svg_filter/defaults.rs
+++ b/crates/effects/src/svg_filter/defaults.rs
@@ -128,6 +128,7 @@ mod tests {
to_doc: Affine::scale(1.0),
px: 1.0,
center: Point::new(wd / 2.0, wd / 2.0),
+ size: vectorcraft_geom::Vec2::new(wd, wd),
channels: Channels::Rgb,
line: 1.0,
extent: 0.5 * wd.hypot(wd),
diff --git a/crates/effects/src/svg_filter/tests.rs b/crates/effects/src/svg_filter/tests.rs
index df1956f3f0..f93cb53124 100644
--- a/crates/effects/src/svg_filter/tests.rs
+++ b/crates/effects/src/svg_filter/tests.rs
@@ -10,7 +10,15 @@ use crate::{PixelFx, RasterFx, raster_effects};
/// resolution whose pixels are `line` points wide.
fn space(w: usize, h: usize, px: f64, line: f64) -> PixelSpace {
let (wd, hd) = (w as f64 * px, h as f64 * px);
- PixelSpace { to_doc: Affine::scale(px), px, center: Point::new(wd / 2.0, hd / 2.0), channels: Channels::Rgb, line, extent: 0.5 * wd.hypot(hd) }
+ PixelSpace {
+ to_doc: Affine::scale(px),
+ px,
+ center: Point::new(wd / 2.0, hd / 2.0),
+ size: vectorcraft_geom::Vec2::new(wd, hd),
+ channels: Channels::Rgb,
+ line,
+ extent: 0.5 * wd.hypot(hd),
+ }
}
/// `w` × `h` premultiplied pixels: `f(x, y)` each.
diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs
index c43d383c19..c605b6461f 100644
--- a/crates/effects/src/tests.rs
+++ b/crates/effects/src/tests.rs
@@ -1850,6 +1850,7 @@ fn rasterize_compose_leaves_the_raster_alone_when_the_sizes_do_not_fit() {
to_doc: Affine::IDENTITY,
px: 1.0,
center: Point::new(1.0, 1.0),
+ size: vectorcraft_geom::Vec2::new(2.0, 2.0),
channels: pixel::Channels::Rgb,
line: 1.0,
extent: std::f64::consts::SQRT_2,
diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs
index 6a1f0d6496..07eb025798 100644
--- a/crates/engine/src/cmd/buildcmds.rs
+++ b/crates/engine/src/cmd/buildcmds.rs
@@ -117,7 +117,7 @@ pub fn specs() -> Vec {
"Live Paint Bucket",
[],
None,
- "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face}",
+ "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face, count (faces reached)}",
has_doc,
lp_fill
),
@@ -126,7 +126,7 @@ pub fn specs() -> Vec {
"Live Paint Bucket (Stroke)",
[],
None,
- "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point; when it already has the paint and the width, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge}",
+ "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached takes the paint and width in its topmost stroke that is shown, or in a new stroke above the others when it has none; when every edge it reaches already has the paint and the width there, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
has_doc,
lp_stroke_edge
),
diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs
index 1554ef7328..20e22d261e 100644
--- a/crates/engine/src/cmd/buildcmds/live_paint.rs
+++ b/crates/engine/src/cmd/buildcmds/live_paint.rs
@@ -363,9 +363,52 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result {
Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": closed }))
}
+/// Which parts a Live Paint Bucket click paints besides the one under the pointer.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum LpScope {
+ /// The part under the pointer alone (a click).
+ One,
+ /// A face and the faces reached from it across edges that draw no stroke ([`b::flood_faces`]),
+ /// or an edge and the edges joined to it end to end that draw with the same stroke paint
+ /// ([`b::connected_edges`], [`b::lp_stroke_paint`]) (a double-click).
+ Connected,
+ /// Every face with the same fill, or every edge that draws with the same stroke paint, in the
+ /// group (a triple-click).
+ SamePaint,
+}
+
+/// The `scope` of `livePaint.fill` and `livePaint.strokeEdge`: `one` when left out or null.
+fn scope_param(p: &Value, c: &str) -> Result {
+ match p.get("scope").filter(|v| !v.is_null()) {
+ None => Ok(LpScope::One),
+ Some(v) => match v.as_str() {
+ Some("one") => Ok(LpScope::One),
+ Some("connected") => Ok(LpScope::Connected),
+ Some("samePaint") => Ok(LpScope::SamePaint),
+ _ => Err(bad(c, "scope must be \"one\", \"connected\" or \"samePaint\"")),
+ },
+ }
+}
+
+/// The `match` of `livePaint.fill` and `livePaint.strokeEdge`: a paint as the document stores it,
+/// None when left out or null. With `allowed` false (a scope that compares no paints) a `match` is
+/// an error naming `scopes`, the scopes it applies to.
+fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result> {
+ let Some(v) = p.get("match").filter(|v| !v.is_null()) else { return Ok(None) };
+ if !allowed {
+ return Err(bad(c, format!("match applies only with scope {scopes}")));
+ }
+ serde_json::from_value::(v.clone()).map(Some).map_err(|_| bad(c, "match must be a paint as the document stores it"))
+}
+
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result {
const C: &str = "livePaint.fill";
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
+ let scope = scope_param(p, C)?;
+ let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
+ if scope != LpScope::One && p.get("points").is_some() {
+ return Err(bad(C, "scope applies to a click: leave out points"));
+ }
let parse_chunk = |input: &Value, start: Point| -> Result> {
let values = input
.as_array()
@@ -400,7 +443,8 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result {
let group = object_param(p, "group", C)?;
let roots = if group.is_none() { root_ids(s, p)? } else { vec![] };
// The faces the click or drag paints in Live Paint group `gid`: the visible face at the point,
- // and every visible face the drag crosses; → (the face at the point, the faces).
+ // the faces its scope adds, and every visible face the drag crosses; → (the face at the point,
+ // the faces).
let targets_in = |d: &Document, gid: NodeId| -> Result<(NodeId, std::collections::BTreeSet)> {
let fid = d
.node(gid)
@@ -408,6 +452,18 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result {
.map(|f| f.id)
.ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?;
let mut targets = std::collections::BTreeSet::from([fid]);
+ if scope != LpScope::One {
+ let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
+ if scope == LpScope::Connected {
+ targets.extend(b::flood_faces(n, fid));
+ } else {
+ let like = match &like {
+ Some(m) => m.clone(),
+ None => d.node(fid).ok_or(EngineError::NoNode(fid))?.appearance.fill_paint(),
+ };
+ targets.extend(b::faces(n).into_iter().filter(|f| f.visible && f.appearance.fill_paint() == like).map(|f| f.id));
+ }
+ }
if let Some(points) = points {
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
// Use the existing region-crossing probes, so even a face narrower than the distance
@@ -457,34 +513,36 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result {
}
}
};
- let (g, face) = match live {
+ let (g, face, count) = match live {
Some(gid) => {
let (fid, targets) = targets_in(&s.doc()?.doc, gid)?;
+ let count = targets.len();
// Faces that already have the paint stay as they are: when every face has it, nothing
// changes and no undo step is recorded.
let d = &s.doc()?.doc;
let unpainted: Vec = targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| f.appearance.fill_paint() != paint)).collect();
if unpainted.is_empty() {
- return Ok(json!({ "group": gid.0, "face": fid.0 }));
+ return Ok(json!({ "group": gid.0, "face": fid.0, "count": count }));
}
s.edit("Live Paint Bucket", |d, _| {
for target in unpainted {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
}
- Ok((gid, fid))
+ Ok((gid, fid, count))
})?
}
None => s.edit("Live Paint Bucket", |d, sel| {
let gid = make_live(d, sel, &roots)?.0;
let (fid, targets) = targets_in(d, gid)?;
+ let count = targets.len();
for target in targets {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
}
- Ok((gid, fid))
+ Ok((gid, fid, count))
})?,
};
s.remember_paint(&paint);
- Ok(json!({ "group": g.0, "face": face.0 }))
+ Ok(json!({ "group": g.0, "face": face.0, "count": count }))
}
pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result {
@@ -498,31 +556,72 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result {
return Err(bad(C, "width out of range"));
}
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
- let (eid, unchanged) = {
+ let scope = scope_param(p, C)?;
+ let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
+ let (eid, count, changed) = {
let d = &s.doc()?.doc;
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
- let e = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
- // An edge that already has the paint and the width (or has no stroke and gets none) stays as
- // it is, and no undo step is recorded.
- let unchanged = match e.appearance.stroke() {
- Some(st) => st.paint == paint && st.width == width,
- None => paint.is_none(),
+ let start = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
+ let eid = start.id;
+ let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
+ let targets = match scope {
+ LpScope::One => vec![eid],
+ LpScope::Connected => b::connected_edges(n, eid, &like),
+ LpScope::SamePaint => std::iter::once(eid)
+ .chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
+ .collect(),
};
- (e.id, unchanged)
+ let count = targets.len();
+ // An edge whose shown stroke already has the paint and the width (or that has no shown stroke
+ // and gets none) stays as it is; when every edge does, nothing changes and no undo step is
+ // recorded.
+ let changed: Vec = targets
+ .into_iter()
+ .filter(|t| {
+ d.node(*t).is_none_or(|e| match shown_stroke(e) {
+ Some(st) => !(st.paint == paint && st.width == width),
+ None => !paint.is_none(),
+ })
+ })
+ .collect();
+ (eid, count, changed)
};
- if unchanged {
- return Ok(json!({ "group": g.0, "edge": eid.0 }));
+ if changed.is_empty() {
+ return Ok(json!({ "group": g.0, "edge": eid.0, "count": count }));
}
- let edge = s.edit("Live Paint Bucket", |d, _| {
- let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?;
- e.appearance.set_stroke(paint.clone());
- if let Some(st) = e.appearance.stroke_mut() {
- st.width = width;
+ s.edit("Live Paint Bucket", |d, _| {
+ for target in &changed {
+ let e = d.node_mut(*target).ok_or(EngineError::NoNode(*target))?;
+ match shown_stroke_mut(e) {
+ Some(st) => {
+ st.paint = paint.clone();
+ st.width = width;
+ }
+ None => e.appearance.items.push(super::AppearanceItem::Stroke(super::StrokeLayer::new(paint.clone(), width))),
+ }
}
- Ok(eid)
+ Ok(())
})?;
s.remember_paint(&paint);
- Ok(json!({ "group": g.0, "edge": edge.0 }))
+ Ok(json!({ "group": g.0, "edge": eid.0, "count": count }))
+}
+
+/// The stroke `livePaint.strokeEdge` paints on Live Paint edge `e`: its topmost stroke that is
+/// shown. None when it has no stroke or every stroke is hidden; the command then adds a stroke
+/// above the others.
+fn shown_stroke(e: &Node) -> Option<&super::StrokeLayer> {
+ e.appearance.items.iter().rev().find_map(|i| match i {
+ super::AppearanceItem::Stroke(s) if s.visible => Some(s),
+ _ => None,
+ })
+}
+
+/// [`shown_stroke`], to change.
+fn shown_stroke_mut(e: &mut Node) -> Option<&mut super::StrokeLayer> {
+ e.appearance.items.iter_mut().rev().find_map(|i| match i {
+ super::AppearanceItem::Stroke(s) if s.visible => Some(s),
+ _ => None,
+ })
}
/// Every fill and stroke row of face or edge `n`, bottom first, as `livePaint.info` lists them. A
diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs
index 647f4a4342..90d58541a6 100644
--- a/crates/engine/src/cmd/distortcmds/perspective.rs
+++ b/crates/engine/src/cmd/distortcmds/perspective.rs
@@ -104,9 +104,14 @@ fn plane_param(g: &PerspectiveGrid, p: &Value, cmd: &str) -> Result {
Ok(plane)
}
+/// The objects a perspective command acts on: the outermost of `ids` (each once, in the order first
+/// given), else the selection's roots.
pub(super) fn roots(s: &Session, p: &Value) -> Result> {
match named_ids(p)? {
- Some(v) => Ok(outermost(&s.doc()?.doc, v)),
+ Some(v) => {
+ let mut seen = std::collections::HashSet::new();
+ Ok(outermost(&s.doc()?.doc, v.into_iter().filter(|id| seen.insert(*id)).collect()))
+ }
None => selected_roots(s),
}
}
diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs
index 974d876d2e..041476a2ed 100644
--- a/crates/engine/src/cmd/effectcmd.rs
+++ b/crates/engine/src/cmd/effectcmd.rs
@@ -427,6 +427,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result {
}
super::params::check_effect_color(C, id, ¶ms)?;
super::params::check_effect_channel(C, id, ¶ms)?;
+ super::params::check_effect_center(C, id, ¶ms)?;
// Crop Marks take their style from the preferences when applied.
if id == effects::CROP_MARKS && params.get("style").is_none() {
params["style"] = json!(s.crop_mark_style().id());
@@ -740,6 +741,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result {
for effect in &edited {
super::params::check_effect_color(C, effect, ¶ms)?;
super::params::check_effect_channel(C, effect, ¶ms)?;
+ super::params::check_effect_center(C, effect, ¶ms)?;
}
if edited.iter().any(|e| texture_load_effect(e)) {
load_texture(&mut params, C)?;
diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs
index 306aaa4797..b3389e190d 100644
--- a/crates/engine/src/cmd/effectcmd/tests.rs
+++ b/crates/engine/src/cmd/effectcmd/tests.rs
@@ -1016,3 +1016,69 @@ fn a_3d_shadow_is_one_undo_step_saved_exported_and_expanded() {
});
assert_eq!(shadows, 1);
}
+
+/// Radial Blur's Blur Center: stored as given, drawn about that point of the object's bounds, and
+/// a value outside 0 to 1 (or not a number) is refused with nothing changed and no undo step.
+#[test]
+fn radial_blur_center_is_stored_drawn_and_checked() {
+ let (mut s, id) = session_with_rect();
+ let draw = |s: &Session| {
+ vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
+ };
+ s.execute("effect.apply", &json!({"effect": "blur.radial", "params": {"amount": 40}})).unwrap();
+ assert_eq!(node(&s, id).appearance.effects[0].params["centerX"], json!(0.5), "the default center is stored");
+ let middle = draw(&s);
+ s.execute("effect.setParams", &json!({"index": 0, "params": {"centerX": 0.5, "centerY": 0.5}})).unwrap();
+ assert_eq!(draw(&s), middle, "the default center draws as before");
+ s.execute("effect.setParams", &json!({"index": 0, "params": {"centerX": 0, "centerY": 1}})).unwrap();
+ let params = node(&s, id).appearance.effects[0].params.clone();
+ assert_eq!((params["centerX"].clone(), params["centerY"].clone()), (json!(0), json!(1)));
+ let corner = draw(&s);
+ assert_ne!(corner, middle, "the blur turns about the bottom-left corner");
+ let undo = s.doc().unwrap().history.undo.len();
+ for (cmd, params) in [
+ ("effect.setParams", json!({"index": 0, "params": {"centerX": 1.5}})),
+ ("effect.setParams", json!({"index": 0, "params": {"centerY": -0.01}})),
+ ("effect.setParams", json!({"index": 0, "params": {"centerX": "0.5"}})),
+ ("effect.apply", json!({"effect": "blur.radial", "params": {"centerY": 2}})),
+ ] {
+ let e = s.execute(cmd, ¶ms).unwrap_err().to_string();
+ assert!(e.contains("must be a number"), "{cmd} {params}: {e}");
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cmd} {params}");
+ assert_eq!(node(&s, id).appearance.effects.len(), 1, "{cmd} {params}");
+ assert_eq!(draw(&s), corner, "{cmd} {params}");
+ }
+ // A replayed journal is checked too: the refusal is the command's own.
+ let e = s.replay("effect.setParams", &json!({"index": 0, "params": {"centerX": 7}})).unwrap_err().to_string();
+ assert!(e.contains("`centerX` must be a number from 0 to 1"), "{e}");
+ // Moving the object moves the blur with it.
+ s.execute("object.move", &json!({"ids": [id.0], "dx": 40, "dy": 20})).unwrap();
+ let moved = draw(&s);
+ let at = |px: &[u8], x: usize, y: usize| px[(y * 300 + x) * 4..][..4].to_vec();
+ for (x, y) in [(95, 150), (150, 205), (205, 95), (120, 120)] {
+ assert_eq!(at(&moved, x + 40, y + 20), at(&corner, x, y), "({x}, {y})");
+ }
+}
+
+/// A Rasterize with transparent room around the art, before another Rasterize, splits the stack,
+/// and the part after the split paints around content the room spreads. The Blur Center still
+/// lies in the object's own bounds, so the blur draws as it does without the room.
+#[test]
+fn radial_blur_center_stays_in_the_object_when_the_stack_splits() {
+ let draw = |room: bool| {
+ let (mut s, _) = session_with_rect();
+ let mut stack = vec![("rasterize", json!({})), ("blur.radial", json!({"amount": 60, "centerX": 0, "centerY": 0}))];
+ if room {
+ stack.insert(0, ("rasterize", json!({"addAround": 40})));
+ }
+ for (effect, params) in stack {
+ s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap();
+ }
+ vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
+ };
+ let (plain, split) = (draw(false), draw(true));
+ let alpha = |px: &[u8]| px.iter().skip(3).step_by(4).map(|a| u64::from(*a)).sum::();
+ assert!(alpha(&plain) > 0, "the blurred art draws");
+ let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count();
+ assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art");
+}
diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs
index ee33f64c41..7ed3fb723d 100644
--- a/crates/engine/src/cmd/fileio/load.rs
+++ b/crates/engine/src/cmd/fileio/load.rs
@@ -864,7 +864,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option {
/// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per
/// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]);
/// CMYK TIFFs with an alpha channel, which the decoder can't read, become RGBA in the active color
-/// settings' CMYK, as do CMYK Photoshop documents, whose merged image is read ([`psdread`]).
+/// settings' CMYK, whichever of their extra channels is the alpha
+/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]), as do CMYK Photoshop documents, whose
+/// merged image is read ([`psdread`]).
/// 1-bit TIFFs compressed with CCITT Group 3, which the decoder can't read either, become RGBA
/// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]).
/// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read
diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs
index 7374e26e2b..b66b22d1a8 100644
--- a/crates/engine/src/cmd/fileio/tests.rs
+++ b/crates/engine/src/cmd/fileio/tests.rs
@@ -202,6 +202,41 @@ fn a_16_bit_cmyk_tiff_with_alpha_places_at_16_bits() {
}
}
+/// A CMYK or grayscale TIFF whose alpha follows another extra sample opens and places with that
+/// alpha, at 8 and 16 bits, chunky and planar; a CMYK one is not kept as inks. A CMYK one with two
+/// more samples than its ExtraSamples values count does too.
+#[test]
+fn a_tiff_with_alpha_after_another_extra_sample_places_with_its_alpha() {
+ let none = vec![0u16; 6];
+ let full = vec![255u16; 6];
+ let other = vec![9u16, 8, 7, 6, 5, 4];
+ let alpha = vec![255u16, 128, 0, 255, 64, 1];
+ let inks = [full.clone(), none.clone(), none.clone(), none.clone()];
+ let cases = [
+ ("CMYK", 5, vec![full.clone(), none.clone(), none.clone(), none.clone(), other.clone(), alpha.clone()]),
+ ("CMYK, two more samples", 5, [&inks[..], &[other.clone(), alpha.clone(), other.clone(), full.clone()]].concat()),
+ ("gray", 1, vec![full.clone(), other.clone(), alpha.clone()]),
+ ];
+ for (what, photometric, channels) in cases {
+ for bits in [8, 16] {
+ let wide: Vec> = channels.iter().map(|ch| ch.iter().map(|v| if bits == 16 { v * 257 } else { *v }).collect()).collect();
+ for planar in [false, true] {
+ let what = format!("{what}, {bits} bits, planar {planar}");
+ let file = hand_tiff(photometric, bits, &[0, 2], planar, &wide);
+ let (inks, rgba) = kept(&what, &file);
+ assert_eq!(inks, None, "{what}: shown as RGB with its alpha");
+ let alphas: Vec = rgba.iter().skip(3).step_by(4).copied().collect();
+ assert_eq!(alphas, [255, 128, 0, 255, 64, 1], "{what}: the alpha is the second extra sample");
+ let mut s = session(100.0, 100.0, 1);
+ s.execute("file.place", &json!({"name": "a.tif", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap();
+ let blob = &s.doc().unwrap().doc.images[&image_of(&s).key];
+ let placed = image::load_from_memory(&blob.bytes).unwrap().to_rgba8().into_raw();
+ assert_eq!(placed, rgba, "{what}: Place reads it as Open does");
+ }
+ }
+ }
+}
+
/// A planar TIFF whose header claims more strips than the decoder can count (here 2^31 + 1 rows
/// a strip each, times 5 planes) is refused as too large to draw, without a panic.
#[test]
diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs
index 3a6ee2fdf5..06557e6f59 100644
--- a/crates/engine/src/cmd/graph.rs
+++ b/crates/engine/src/cmd/graph.rs
@@ -37,9 +37,9 @@ use axis::{nice_axis, tick_values};
#[cfg(test)]
use columns::{fill_totals, total_text};
pub use commands::specs;
-pub(crate) use data::apply_csv;
+pub(crate) use data::{apply_csv, parse_csv};
#[cfg(test)]
-use data::{fmt_value, parse_csv, to_csv};
+use data::{fmt_value, to_csv};
pub(crate) use edit::{graphs_holding, keep_placed};
#[cfg(test)]
use generate::generate;
diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs
index f7f672325e..68a83fd80a 100644
--- a/crates/engine/src/cmd/graph/data.rs
+++ b/crates/engine/src/cmd/graph/data.rs
@@ -42,7 +42,7 @@ fn cell(c: &str) -> Cell {
}
}
-pub(super) fn parse_csv(csv: &str) -> (Vec, Vec, Vec>>) {
+pub(crate) fn parse_csv(csv: &str) -> (Vec, Vec, Vec>>) {
let csv = csv.strip_prefix('\u{feff}').unwrap_or(csv);
// Records end at line breaks outside quotes; a record is tab-separated if it has a tab outside quotes.
let rows: Vec> = split_unquoted(csv, '\n')
diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs
index 290e099500..8e56ad8ae6 100644
--- a/crates/engine/src/cmd/graph/labels.rs
+++ b/crates/engine/src/cmd/graph/labels.rs
@@ -149,20 +149,22 @@ impl Gen<'_> {
refresh_bounds(&mut t);
t
}
- /// A category or series label: a `|` in it starts a new line (Add graph labels). `middle`: the lines are centred
- /// on `at` (labels beside an axis or in a wedge) instead of running down from it.
+ /// A category or series label: a `|` in it starts a new line (Add graph labels), as does a line break a quoted CSV
+ /// cell keeps. `middle`: the lines are centred on `at` (labels beside an axis or in a wedge) instead of running down
+ /// from it.
pub(super) fn label(&mut self, role: Role, at: Point, s: &str, justify: Justify, middle: bool) -> Arc {
- let lines = s.split('|').count();
+ let text = s.replace('|', "\n");
+ let lines = text.split('\n').count();
// Default leading puts the first and last baselines this far above and below `at`.
let half = (lines - 1) as f64 * label_size(self.styles, role) * 1.2 / 2.0;
let start = if middle { Point::new(at.x, at.y - half) } else { at };
- let mut t = self.text_object(role, start, &s.replace('|', "\n"), justify);
+ let mut t = self.text_object(role, start, &text, justify);
// Kept leading or paragraph spacing moves the lines: put the middle of the first and last baselines on `at`. An
// empty line has no baseline: an empty first or last line leaves the label where the default leading puts it.
if middle && kept_para(self.styles, role).is_some() {
let ys: Vec = t.baselines().map(|(a, _)| a.y).collect();
- let ends_set = s.split('|').next().is_some_and(|l| !l.is_empty()) && s.split('|').next_back().is_some_and(|l| !l.is_empty());
- let set = s.split('|').filter(|l| !l.is_empty()).count();
+ let ends_set = text.split('\n').next().is_some_and(|l| !l.is_empty()) && text.split('\n').next_back().is_some_and(|l| !l.is_empty());
+ let set = text.split('\n').filter(|l| !l.is_empty()).count();
if let (Some(first), Some(last), true) = (ys.first(), ys.last(), ends_set && ys.len() == set) {
t.xf = Affine::translate((0.0, half - (first + last) / 2.0)) * t.xf;
}
diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs
index 8cbd24e50e..f167a124d6 100644
--- a/crates/engine/src/cmd/graph/tests.rs
+++ b/crates/engine/src/cmd/graph/tests.rs
@@ -7142,6 +7142,43 @@ fn a_centered_label_with_an_empty_middle_line_and_kept_leading_stays_centered()
assert!((after - before).abs() < 0.01, "the three-line category label keeps its middle: {before} {after}");
}
+#[test]
+fn a_centered_label_with_a_line_break_in_its_text_is_set_as_with_a_bar() {
+ // A quoted CSV cell keeps its line breaks, so they reach the label as well as the `|` it is written with.
+ for (bar, quoted, text) in [("Q|1", "\"Q\n1\"", "Q\n1"), ("Q|||1", "\"Q\n||1\"", "Q\n\n\n1")] {
+ let label_middle = |s: &Session, id: NodeId| {
+ let n = s.doc().unwrap().doc.node(id).unwrap().clone();
+ let label =
+ group(&n, "Axes").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)).unwrap();
+ let b = label.geometric_bounds().unwrap();
+ (b.y0 + b.y1) / 2.0
+ };
+ let drawn = |cat: &str, leading: bool| {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
+ let csv = format!(",2024,2025\n{cat},3,2\nQ2,5,4\nQ3,-1,6");
+ let id = NodeId(
+ s.execute("graph.create", &json!({"type": "bar", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
+ .as_u64()
+ .unwrap(),
+ );
+ if leading {
+ let l = text_id(&s, id, "Axes", text);
+ s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
+ s.execute("text.setFormat", &json!({"autoLeading": 400})).unwrap();
+ s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
+ s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
+ }
+ label_middle(&s, id)
+ };
+ for leading in [false, true] {
+ let (by_bar, by_break) = (drawn(bar, leading), drawn(quoted, leading));
+ assert!((by_bar - by_break).abs() < 0.01, "{text:?} sits where {bar:?} does (kept leading: {leading}): {by_bar} {by_break}");
+ }
+ assert!((drawn(quoted, true) - drawn(quoted, false)).abs() < 0.01, "{text:?} keeps its middle with kept leading");
+ }
+}
+
#[test]
fn a_legend_across_top_measures_its_labels_with_system_layout() {
let mut s = Session::new();
diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs
index 4bb6bcba1d..736358ff9b 100644
--- a/crates/engine/src/cmd/params.rs
+++ b/crates/engine/src/cmd/params.rs
@@ -382,7 +382,8 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
return Err(bad(id, format!("`version` must be 0 or {newest}")));
}
check_effect_color(id, effect, params)?;
- check_effect_channel(id, effect, params)
+ check_effect_channel(id, effect, params)?;
+ check_effect_center(id, effect, params)
}
/// The type of the values in `params` of effect `effect`, as command `id` was given them: a key
@@ -500,6 +501,22 @@ pub(crate) fn check_effect_channel(id: &str, effect: &str, params: &Value) -> Re
Err(bad(id, format!("`{key}` must be one of {}", vectorcraft_render::effects::CHANNELS.join(", "))))
}
+/// The Blur Center (`centerX`, `centerY`) in `params` of Radial Blur (`effect`), as command `id`
+/// was given it: a parameter error unless each is a number from 0 to 1 (a share of the object's
+/// bounds). `effect.apply` and `effect.setParams` run this themselves before they edit, as they
+/// run [`check_effect_channel`].
+pub(crate) fn check_effect_center(id: &str, effect: &str, params: &Value) -> Result<()> {
+ if effect != "blur.radial" {
+ return Ok(());
+ }
+ for key in ["centerX", "centerY"] {
+ if params.get(key).is_some_and(|v| !v.as_f64().is_some_and(|x| (0.0..=1.0).contains(&x))) {
+ return Err(bad(id, format!("`{key}` must be a number from 0 to 1")));
+ }
+ }
+ Ok(())
+}
+
/// Commands whose params aren't checked yet (#1442): they read keys in ways the audit of the
/// descriptions couldn't follow (a list of keys in a loop, a whole object read as settings), so
/// their descriptions aren't proven to name every key they take. Sorted; take a command out once
diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs
index 2ad2b70049..0fb450fa43 100644
--- a/crates/engine/src/cmd/path.rs
+++ b/crates/engine/src/cmd/path.rs
@@ -77,7 +77,7 @@ pub fn specs() -> Vec {
"Reverse Path Direction",
["Object", "Path"],
None,
- "{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step; when every subpath of a path turns alike, its strokes' width profiles (sides swapped) and pen pressure, tilt, bearing and rotation turn with it, so they draw as before → {changed: paths}",
+ "{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step; when every subpath of a path or compound path turns alike, its strokes' width profiles (sides swapped) and pen pressure, tilt, bearing and rotation turn with it, so they draw as before → {changed: paths}",
has_selected_path,
reverse
),
@@ -458,14 +458,33 @@ fn reverse(s: &mut Session, p: &Value) -> Result {
if ids.is_empty() {
return Err(bad(C, "select paths"));
}
+ let flip_of = |path: &PathData| -> Vec {
+ match subpath {
+ Some(si) => (0..path.subpaths.len()).map(|i| i == si).collect(),
+ None => path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect(),
+ }
+ };
let changed = super::overprint::edit_counted(s, "Reverse Path Direction", |d| {
+ // A compound path's own strokes run along its members' subpaths in order, so they turn
+ // with them, read before any member turns.
+ let compounds: BTreeSet = ids.iter().map(|id| compound_or_self(d, *id)).filter(|c| ids.binary_search(c).is_err()).collect();
+ for c in compounds {
+ let Some(NodeKind::Compound { children, .. }) = d.node(c).map(|n| &n.kind) else { continue };
+ let flip: Vec = children
+ .iter()
+ .filter_map(|m| m.path_data().map(|pd| if ids.binary_search(&m.id).is_ok() { flip_of(pd) } else { vec![false; pd.subpaths.len()] }))
+ .flatten()
+ .collect();
+ if flip.contains(&true)
+ && let Some(n) = d.node_mut(c)
+ {
+ vectorcraft_doc::blend::reverse_stroke_records(n, &flip);
+ }
+ }
let mut changed = 0;
for id in &ids {
let path = path_mut(d, *id)?;
- let flip: Vec = match subpath {
- Some(si) => (0..path.subpaths.len()).map(|i| i == si).collect(),
- None => path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect(),
- };
+ let flip = flip_of(path);
if !flip.contains(&true) {
continue;
}
diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs
index 5f8d6605b3..a73c16448b 100644
--- a/crates/engine/src/cmd/variablecmds.rs
+++ b/crates/engine/src/cmd/variablecmds.rs
@@ -9,8 +9,8 @@
//! before an image variable); import replaces the datasets, names the rows Data Set 1, 2…,
//! also reads tab-separated files, and reads header cells that define new variables (`#` for
//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
-//! text variables and data sets of a variable library, the XML file of the reference app's Save
-//! Variable Library, and `variable.saveLibrary` writes the text variables and data sets as one.
+//! variables and data sets of a variable library, the XML file of the reference app's Save
+//! Variable Library, and `variable.saveLibrary` writes the variables and data sets as one.
//! Agents reach every command through `run_command`, like all engine commands.
use std::collections::{BTreeMap, BTreeSet};
@@ -886,7 +886,7 @@ pub fn specs() -> Vec {
"Load Variable Library…",
["Window", "Variables"],
None,
- "{path? | xml? | dataBase64?} replace the document's variables and data sets with a variable library's (XML: `variableSets` › `variableSet` › `variables` of `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements with `dataSetName`) in one undo step (none when the document already holds what the library gives). Every data set is deleted, and every variable of the document is deleted with its bindings and values except a text variable the library also declares, which keeps its bindings; then the library's other variables whose `trait` is `textcontent` are defined as text variables, unbound, and each data set takes a value for a variable from the `p` elements of the element named after it, one paragraph each. Variables of other kinds are left out and named in `skipped` and `warning`. Refused while the variables are locked when it would delete or define a variable → {variables, deleted, deletedDataSets, names, skipped, warning?}",
+ "{path? | xml? | dataBase64?} replace the document's variables and data sets with a variable library's (XML: `variableSets` › `variableSet` › `variables` of `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements with `dataSetName`) in one undo step (none when the document already holds what the library gives). Every data set is deleted, and every variable of the document is deleted with its bindings and values except a variable the library also declares with the same kind, which keeps its bindings; then the library's other variables are defined, unbound, with the kind of their `trait`: `textcontent` text, `visibility` visibility, `fileref` image, `graphdata` graph, and any other or none unknown (no values). Each data set takes a variable's value from the element named after it: a text value from its `p` elements, one paragraph each; a visibility value from `true` or `false`; an image value from a file's absolute path or a `file:` URL (the file isn't read); a graph value from a `data` element (`propertyRow` series names, `values` › `row` with a first `value` key=\"name\" category), read as the CSV graph.setData takes. A value that doesn't fit its kind is refused. Refused while the variables are locked when it would delete or define a variable → {variables, deleted, deletedDataSets, names}",
has_doc,
load_library
),
@@ -895,7 +895,7 @@ pub fn specs() -> Vec {
"Save Variable Library…",
["Window", "Variables"],
None,
- "{path?} write the document's text variables and every data set as a variable library, the XML that variable.loadLibrary reads: a `variable` element with `varName` and `trait=\"textcontent\"` per text variable, and a `sampleDataSet` element with `dataSetName` per data set, holding an element named after each text variable it has a value for, with one `p` element per line of the value. Variables of other kinds are left out with their values and named in `skipped` and `warning`. Refused without a text variable, for a text variable whose name isn't an XML name (letters, digits, `-`, `_` and `.`, starting with a letter or `_`), for a data set name or value that holds a control character, for a data set name with white space at either end, for a name longer than 255 characters or used twice, and past variable.loadLibrary's caps (256 variables, 1,000 data sets, 8 MiB). Without path → {xml, variables, datasets, skipped, warning?}; with it → {path, variables, datasets, skipped, warning?}",
+ "{path?} write the document's variables and every data set as a variable library, the XML that variable.loadLibrary reads: a `variable` element with `varName` per variable, with the `trait` of its kind (`textcontent`, `visibility`, `fileref` for image, `graphdata` for graph; none for an unknown kind), and a `sampleDataSet` element with `dataSetName` per data set, holding an element named after each variable it has a value for: one `p` element per line of a text value, `true` or `false`, an image's path (a `file:///` URL for a path from a Unix root), or graph data as a `data` element. Refused without a variable, for a variable whose name isn't an XML name (letters, digits, `-`, `_` and `.`, starting with a letter or `_`; not asked of an unknown kind), for a name or value that holds a control character, for a name with white space at either end, for a name longer than 255 characters or used twice, for an image value that isn't a file's absolute path, and past variable.loadLibrary's caps (256 variables, 1,000 data sets, 8 MiB). Without path → {xml, variables, datasets}; with it → {path, variables, datasets}",
has_doc,
save_library
),
diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs
index e1f4ae0bd5..2392a80ee4 100644
--- a/crates/engine/src/cmd/variablecmds/library.rs
+++ b/crates/engine/src/cmd/variablecmds/library.rs
@@ -1,18 +1,29 @@
use std::collections::HashMap;
+use std::fmt::Write as _;
+
+use vectorcraft_doc::{GraphSpec, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES};
+
use super::{
- BTreeMap, BTreeSet, DataSet, DataValue, Document, EngineError, MAX_NAME, NodeId, NodeKind, Result, Session, Value, Variable, VariableKind,
- Variables, absolute_path, bad, json, named, read_file_head, str_param, variables_unlocked, write_file,
+ BTreeMap, BTreeSet, DataSet, DataValue, Document, EngineError, MAX_GRAPH_CSV, MAX_NAME, NodeId, NodeKind, Result, Session, Value, Variable,
+ VariableKind, Variables, absolute_path, bad, json, named, read_file_head, str_param, variables_unlocked, write_file,
};
/// The namespace of a variable library's elements, the default namespace of its data sets' values,
-/// and the `category` of its text variables.
+/// and the `category` of its visibility and image variables.
const NS_VARIABLES: &str = "http://ns.adobe.com/Variables/1.0/"; // brand-ok: the namespace variable libraries use
const NS_CUSTOM: &str = "http://ns.adobe.com/GenericCustomNamespace/1.0/"; // brand-ok: the namespace variable libraries use
+/// The `category` of a library's text variables.
const NS_FLOWS: &str = "http://ns.adobe.com/Flows/1.0/"; // brand-ok: the namespace variable libraries use
+/// The `category` of a library's graph variables.
+const NS_GRAPHS: &str = "http://ns.adobe.com/Graphs/1.0/"; // brand-ok: the namespace variable libraries use
+
+/// The white space XML puts round a value: a value's text is read without it at either end.
+const XML_SPACE: [char; 4] = [' ', '\t', '\n', '\r'];
+
/// Caps on a variable library (paths and MCP payloads are untrusted): its size, its XML nodes, how
/// deep its elements nest, and the entities, variables and data sets it declares.
const MAX_LIBRARY_BYTES: usize = 8 << 20;
@@ -170,16 +181,47 @@ fn without_doctype(xml: &str, cmd: &str) -> Result {
Ok(out)
}
-/// A variable library as Load Variable Library reads it: the names of its text variables in the
-/// order it declares them, the name and `trait` of each variable of another kind, its data sets
-/// with their text values, and the element id each text variable's `docRef` names.
+/// One variable a library declares: its name, its kind, and its `trait` as the library spells it
+/// (`None` when it has none).
+struct LibraryVariable {
+ name: String,
+ kind: VariableKind,
+ trait_name: Option,
+}
+
+/// A variable library as Load Variable Library reads it: its variables in the order it declares
+/// them, its data sets with their values, and the element id each text variable's `docRef` names.
pub(crate) struct Library {
- text: Vec,
- other: Vec<(String, String)>,
+ variables: Vec,
datasets: Vec,
refs: Vec<(String, String)>,
}
+/// The kind of a library variable whose `trait` is `t`: `textcontent` is text, `visibility` is
+/// visibility, `fileref` (a linked file) is image and `graphdata` is graph. A variable without a
+/// `trait`, or with one VectorCraft doesn't know, is of unknown kind.
+fn trait_kind(t: Option<&str>) -> VariableKind {
+ match t {
+ Some("textcontent") => VariableKind::Text,
+ Some("visibility") => VariableKind::Visibility,
+ Some("fileref") => VariableKind::Image,
+ Some("graphdata") => VariableKind::Graph,
+ _ => VariableKind::Unknown,
+ }
+}
+
+/// The `trait` and the `category` reference a library declares a variable of `kind` with, or `None`
+/// for a variable of unknown kind, which is declared with neither.
+fn kind_trait(kind: VariableKind) -> Option<(&'static str, &'static str)> {
+ match kind {
+ VariableKind::Text => Some(("textcontent", "&ns_flows;")),
+ VariableKind::Visibility => Some(("visibility", "&ns_vars;")),
+ VariableKind::Image => Some(("fileref", "&ns_vars;")),
+ VariableKind::Graph => Some(("graphdata", "&ns_graphs;")),
+ VariableKind::Unknown => None,
+ }
+}
+
impl Library {
/// The element ids the text variables' `docRef`s name.
pub(crate) fn elements(&self) -> std::collections::HashSet {
@@ -190,13 +232,13 @@ impl Library {
/// Read a variable library: XML whose `variableSets` element holds `variableSet` elements, each
/// with a `variables` element of `variable` elements (`varName`, `trait`) and a `sampleDataSets`
/// element of `sampleDataSet` elements (`dataSetName`). Elements are matched by their local names.
-/// A variable whose `trait` is `textcontent` is a text variable. In a data set, an element named
-/// after a text variable gives its value: the text of its `p` elements, one paragraph each, and
-/// none when it has no `p` element. Values for variables of other kinds are left out. A variable
-/// or data set declared twice, a value for a variable the library doesn't declare, and a library
-/// past the caps are refused. Entities that its document type declaration defines are read as
-/// [`without_doctype`] says.
-fn parse_library(xml: &str, cmd: &str) -> Result {
+/// A variable's kind comes from its `trait` ([`trait_kind`]). In a data set, an element named after
+/// a variable gives its value, as [`library_value`] reads it. A variable or data set declared
+/// twice, a value for a variable the library doesn't declare, a value that doesn't fit its
+/// variable's kind, and a library past the caps are refused. With `text_only`, only text values
+/// are read, and the values of the other kinds are passed over unread. Entities that its document
+/// type declaration defines are read as [`without_doctype`] says.
+fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result {
let xml = without_doctype(xml, cmd)?;
// roxmltree parses nested elements recursively.
if crate::cmd::place::docx::nesting(&xml) > MAX_LIBRARY_NESTING {
@@ -210,32 +252,29 @@ fn parse_library(xml: &str, cmd: &str) -> Result {
return Err(bad(cmd, "the file holds no `variableSets` element"));
};
let sets: Vec = root.children().filter(|n| is(n, "variableSet")).collect();
- let (mut text, mut other, mut declared, mut refs) = (Vec::new(), Vec::new(), BTreeSet::new(), Vec::new());
+ let (mut variables, mut kinds, mut refs) = (Vec::new(), BTreeMap::new(), Vec::new());
for var in sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "variables")).flat_map(|v| v.children()).filter(|n| is(n, "variable")) {
let name = named(var.attribute("varName"), "varName", cmd)?;
- if !declared.insert(name.clone()) {
+ let trait_name = var.attribute("trait").map(|t| t.chars().take(MAX_NAME).collect::());
+ let kind = trait_kind(trait_name.as_deref());
+ if kinds.insert(name.clone(), kind).is_some() {
return Err(bad(cmd, format!("variable `{name}` is declared twice")));
}
- if declared.len() > MAX_LIBRARY_VARIABLES {
+ if kinds.len() > MAX_LIBRARY_VARIABLES {
return Err(bad(cmd, format!("the variable library declares more than {MAX_LIBRARY_VARIABLES} variables")));
}
- match var.attribute("trait") {
- Some("textcontent") => {
- // `docRef="id('…')"` names the element of the variable's bound object.
- let element = var.attribute("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty());
- if let Some(element) = element {
- refs.push((name.clone(), element.to_string()));
- }
- text.push(name);
+ if kind == VariableKind::Text {
+ // `docRef="id('…')"` names the element of the variable's bound object.
+ let element = var.attribute("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty());
+ if let Some(element) = element {
+ refs.push((name.clone(), element.to_string()));
}
- Some(t) => other.push((name, t.chars().take(MAX_NAME).collect())),
- None => return Err(bad(cmd, format!("variable `{name}` has no `trait`"))),
}
+ variables.push(LibraryVariable { name, kind, trait_name });
}
- if declared.is_empty() {
+ if variables.is_empty() {
return Err(bad(cmd, "the variable library declares no variables"));
}
- let text_names: BTreeSet<&str> = text.iter().map(String::as_str).collect();
let (mut datasets, mut seen) = (Vec::new(), BTreeSet::new());
for row in
sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "sampleDataSets")).flat_map(|d| d.children()).filter(|n| is(n, "sampleDataSet"))
@@ -250,27 +289,197 @@ fn parse_library(xml: &str, cmd: &str) -> Result {
let (mut values, mut held) = (BTreeMap::new(), BTreeSet::new());
for el in row.children().filter(roxmltree::Node::is_element) {
let var = el.tag_name().name();
- if !declared.contains(var) {
+ let Some(kind) = kinds.get(var) else {
return Err(bad(cmd, format!("data set `{name}` holds a value for `{var}`, which the library doesn't declare")));
- }
+ };
if !held.insert(var) {
return Err(bad(cmd, format!("data set `{name}` holds two values for `{var}`")));
}
- if !text_names.contains(var) {
+ if text_only && *kind != VariableKind::Text {
continue;
}
- let paras: Vec = el
- .children()
- .filter(|n| is(n, "p"))
- .map(|p| p.descendants().filter(roxmltree::Node::is_text).filter_map(|t| t.text()).collect())
- .collect();
- if !paras.is_empty() {
- values.insert(var.to_string(), DataValue::Text(paras.join("\n")));
+ if let Some(value) = library_value(el, *kind, &name, cmd)? {
+ values.insert(var.to_string(), value);
}
}
datasets.push(DataSet { name, values });
}
- Ok(Library { text, other, datasets, refs })
+ Ok(Library { variables, datasets, refs })
+}
+
+/// The value a data set's element `el` gives a variable of `kind`, or `None` when it gives none.
+/// A text value is the text of its `p` elements, one paragraph each, and none without a `p`
+/// element. A visibility value is `true` or `false`, in any case. An image value is the absolute
+/// path of a file, or a `file:` URL of one ([`library_path`]); the file isn't read. A graph value is
+/// a `data` element ([`graph_value`]). Visibility, image and graph values are read without the
+/// white space round them, and an element holding only white space gives none. A variable of
+/// unknown kind takes no value, so what its element holds is passed over. `set` names the data set
+/// in the errors.
+fn library_value(el: roxmltree::Node, kind: VariableKind, set: &str, cmd: &str) -> Result> {
+ let refused = |what: &str| bad(cmd, format!("data set `{set}` holds a value for `{}` that isn't {what}", el.tag_name().name()));
+ let text = || if elements(el).next().is_some() { None } else { Some(deep_text(el)) };
+ match kind {
+ VariableKind::Text => {
+ let paras: Vec = elements(el).filter(|n| n.tag_name().name() == "p").map(deep_text).collect();
+ Ok((!paras.is_empty()).then(|| DataValue::Text(paras.join("\n"))))
+ }
+ VariableKind::Visibility => {
+ let what = "`true` or `false`";
+ let text = text().ok_or_else(|| refused(what))?;
+ match text.trim_matches(XML_SPACE) {
+ "" => Ok(None),
+ t if t.eq_ignore_ascii_case("true") => Ok(Some(DataValue::Visible(true))),
+ t if t.eq_ignore_ascii_case("false") => Ok(Some(DataValue::Visible(false))),
+ _ => Err(refused(what)),
+ }
+ }
+ VariableKind::Image => {
+ let what = "a file's absolute path or `file:` URL";
+ let text = text().ok_or_else(|| refused(what))?;
+ match text.trim_matches(XML_SPACE) {
+ "" => Ok(None),
+ t => library_path(t).map(|p| Some(DataValue::Image(p))).ok_or_else(|| refused(what)),
+ }
+ }
+ VariableKind::Graph => graph_value(el, set, cmd),
+ VariableKind::Unknown => Ok(None),
+ }
+}
+
+/// The elements among `n`'s children.
+fn elements<'a, 'i>(n: roxmltree::Node<'a, 'i>) -> impl Iterator- > {
+ n.children().filter(roxmltree::Node::is_element)
+}
+
+/// The text of every text node inside `n`, in order.
+fn deep_text(n: roxmltree::Node) -> String {
+ n.descendants().filter(roxmltree::Node::is_text).filter_map(|t| t.text()).collect()
+}
+
+/// The absolute path a library's image value `text` names: a `file:` URL's path (`file:///…`,
+/// `file://localhost/…` or `file:/…`), its `%XX` escapes decoded (a URL with a host names a share,
+/// `//host/…`), or `text` itself. `None` unless that is an absolute path: one starting with `/` or
+/// `\\`, or a drive's path from its root (`C:\…`, `C:/…`).
+fn library_path(text: &str) -> Option
{
+ let drive = |p: &str| matches!(p.as_bytes(), [l, b':', b'\\' | b'/', ..] if l.is_ascii_alphabetic());
+ let url = match (text.strip_prefix("file://"), text.strip_prefix("file:")) {
+ (Some(rest), _) => Some(rest.strip_prefix("localhost").filter(|r| r.starts_with('/')).unwrap_or(rest)),
+ // `file:/…` names a path without a host.
+ (None, Some(rest)) if rest.starts_with('/') => Some(rest),
+ _ => None,
+ };
+ let path = match url {
+ Some(rest) => {
+ if rest.starts_with('/') {
+ let p = percent_decoded(rest.trim_start_matches('/'));
+ if drive(&p) { p } else { format!("/{p}") }
+ } else {
+ format!("//{}", percent_decoded(rest))
+ }
+ }
+ None => text.to_string(),
+ };
+ (path.len() > 1 && (path.starts_with('/') || path.starts_with("\\\\") || drive(&path))).then_some(path)
+}
+
+/// `s` with its `%XX` escapes decoded, or as it is when the decoded bytes aren't UTF-8.
+fn percent_decoded(s: &str) -> String {
+ let hex = |b: u8| char::from(b).to_digit(16);
+ let (mut out, mut rest) = (Vec::with_capacity(s.len()), s.as_bytes());
+ while let Some((&b, tail)) = rest.split_first() {
+ match tail {
+ [h, l, more @ ..] if b == b'%' && hex(*h).is_some() && hex(*l).is_some() => {
+ out.push(((hex(*h).unwrap_or(0) << 4) | hex(*l).unwrap_or(0)) as u8);
+ rest = more;
+ }
+ _ => {
+ out.push(b);
+ rest = tail;
+ }
+ }
+ }
+ String::from_utf8(out).unwrap_or_else(|_| s.to_string())
+}
+
+/// How a library writes the image value `path`: an absolute path from the root of a Unix file
+/// system as a `file:` URL (`file:///` and the path, with `%`, `#`, `?`, spaces, controls and
+/// bytes past ASCII escaped), any other path as it is. [`library_path`] reads it back.
+fn library_file(path: &str) -> String {
+ if !path.starts_with('/') || path.starts_with("//") {
+ return path.to_string();
+ }
+ let mut url = String::from("file:///");
+ for &b in path.as_bytes() {
+ if matches!(b, b'%' | b'#' | b'?') || !(0x21..=0x7e).contains(&b) {
+ let _ = write!(url, "%{b:02X}");
+ } else {
+ url.push(char::from(b));
+ }
+ }
+ url
+}
+
+/// A library's graph value: the `data` element that `el` holds, read as CSV of the kind Graph
+/// Data takes. Its `propertyRow` holds a corner cell and then the names of the series, and each
+/// `row` of its `values` holds the row's category in a first `value` whose `key` is `name`, then
+/// the row's values. The graph has categories when a row's name isn't blank or is marked
+/// `type="string"`. Labels are read as they are; a value is read without the white space round it,
+/// and one that is empty, marked `type="string"` or not a finite number is a blank. Without rows or
+/// series, or when `el` holds only white space, there is no value. Anything else in `el`, more than
+/// [`MAX_GRAPH_CATEGORIES`] rows or [`MAX_GRAPH_SERIES`] series (what a graph holds), and CSV longer
+/// than graph values hold, are refused.
+fn graph_value(el: roxmltree::Node, set: &str, cmd: &str) -> Result> {
+ let var = el.tag_name().name();
+ let refused = || bad(cmd, format!("data set `{set}` holds a value for `{var}` that isn't a graph's `data` element"));
+ let named = |name: &'static str| move |n: &roxmltree::Node| n.tag_name().name() == name;
+ let mut children = elements(el);
+ let data = match (children.next(), children.next()) {
+ (None, _) if deep_text(el).trim_matches(XML_SPACE).is_empty() => return Ok(None),
+ (Some(data), None) if data.tag_name().name() == "data" => data,
+ _ => return Err(refused()),
+ };
+ // Labels keep their white space; numbers are read without it.
+ let series: Vec =
+ elements(data).find(named("propertyRow")).map(|r| elements(r).filter(named("value")).skip(1).map(deep_text).collect()).unwrap_or_default();
+ let rows: Vec =
+ elements(data).filter(named("values")).flat_map(elements).filter(named("row")).take(MAX_GRAPH_CATEGORIES + 1).collect();
+ if rows.is_empty() && series.is_empty() {
+ return Ok(None);
+ }
+ let too_many = || bad(cmd, format!("data set `{set}` holds a graph value for `{var}` with {}", graph_limits()));
+ // A row's values after its name.
+ let wide = |row: &roxmltree::Node| {
+ let mut values = elements(*row).filter(named("value")).peekable();
+ let _name = values.next_if(|v| v.attribute("key") == Some("name"));
+ values.count() > MAX_GRAPH_SERIES
+ };
+ if rows.len() > MAX_GRAPH_CATEGORIES || series.len() > MAX_GRAPH_SERIES || rows.iter().any(wide) {
+ return Err(too_many());
+ }
+ // Each row's name and the values after it. A blank name marked `type="string"` is a blank
+ // category, so a graph whose categories are all blank keeps them.
+ let mut labelled = false;
+ let read: Vec<(Option, Vec>)> = rows
+ .iter()
+ .map(|row| {
+ let mut values = elements(*row).filter(named("value")).peekable();
+ let name = values.next_if(|v| v.attribute("key") == Some("name"));
+ labelled |= name.is_some_and(|v| v.attribute("type") == Some("string") || !deep_text(v).is_empty());
+ let name = name.map(deep_text);
+ let number = |v: roxmltree::Node| deep_text(v).trim_matches(XML_SPACE).parse::().ok().filter(|n| n.is_finite());
+ let numbers = values.map(|v| if v.attribute("type") == Some("string") { None } else { number(v) });
+ (name, numbers.collect())
+ })
+ .collect();
+ let categories = if labelled { read.iter().map(|(name, _)| name.clone().unwrap_or_default()).collect() } else { vec![] };
+ let mut spec = GraphSpec { series, categories, ..GraphSpec::default() };
+ spec.set_cells(read.into_iter().map(|(_, numbers)| numbers).collect());
+ // Data set values hold graph data without the line break at its end.
+ let csv = spec.to_csv().trim_end().to_string();
+ if csv.len() > MAX_GRAPH_CSV {
+ return Err(bad(cmd, format!("data set `{set}` holds a graph value for `{var}` longer than {MAX_GRAPH_CSV} bytes")));
+ }
+ Ok(Some(DataValue::Graph(csv)))
}
/// The variable library an SVG carries (SVG Options › Include Variable Data), read as
@@ -317,7 +526,8 @@ pub(crate) fn svg_library(svg: &str) -> Option> {
for (name, value) in &entities {
element = element.replace(name.as_str(), value);
}
- parse_library(&format!("{element} "), C)
+ // The SVG keeps only the text variables, so the values of the other kinds aren't read.
+ parse_library(&format!("{element} "), C, true)
};
Some(read())
}
@@ -389,12 +599,16 @@ fn variable_sets_range(svg: &str) -> Option<(usize, Option)> {
/// the type object made of the element its `docRef` names, or the one type object among the
/// objects a group made of it holds (`found`: the object made of each element, by id). A `docRef`
/// that names no type object, or one another variable is bound to already, binds nothing. The art
-/// stays as the file draws it. The warning about the variables of other kinds that were left out,
-/// if any.
+/// stays as the file draws it. Variables of other kinds are left out with their values. The
+/// warning about those variables, if any.
pub(crate) fn give_svg_library(doc: &mut Document, lib: Library, found: &HashMap) -> Option {
+ let (text, other): (Vec, Vec) = lib.variables.into_iter().partition(|v| v.kind == VariableKind::Text);
let mut vars =
- Variables { variables: lib.text.iter().map(|n| Variable { name: n.clone(), kind: VariableKind::Text }).collect(), ..Variables::default() };
+ Variables { variables: text.iter().map(|v| Variable { name: v.name.clone(), kind: VariableKind::Text }).collect(), ..Variables::default() };
vars.datasets = lib.datasets;
+ for ds in &mut vars.datasets {
+ ds.values.retain(|_, v| matches!(v, DataValue::Text(_)));
+ }
// A type object written with a paint of its own, or with fills and strokes of its appearance,
// is a group around its text (and the appearance's paths).
let text_of = |id: NodeId| match doc.node(id).map(|n| &n.kind) {
@@ -415,32 +629,32 @@ pub(crate) fn give_svg_library(doc: &mut Document, lib: Library, found: &HashMap
}
}
doc.variables = vars.into();
- left_out_warning(lib.other.iter().map(|(_, t)| t.as_str()))
+ left_out_warning(other.iter().map(|v| v.trait_name.as_deref().unwrap_or_else(|| v.kind.label())))
}
/// Load Variable Library: replace the document's variables and data sets with a variable library's
/// ([`parse_library`]) in one undo step, or none when the document already holds what the library
/// gives. Every data set is deleted, and every variable of the document is deleted with its
-/// bindings and values, except a text variable the library also declares: it stays bound to its
-/// objects, so the library's data sets change them (#4136; a template's bound variables take a
-/// library of the same names:
+/// bindings and values, except a variable the library also declares with the same kind: it stays
+/// bound to its objects, so the library's data sets change them (#4136; a template's bound
+/// variables take a library of the same names:
/// ). The
-/// library's other text variables are then defined, unbound, and its data sets are added. The
-/// library's variables of other kinds are left out, named in `skipped` and in a warning.
+/// library's other variables are then defined with their kinds, unbound, and its data sets are
+/// added.
pub(super) fn load_library(s: &mut Session, p: &Value) -> Result {
const C: &str = "variable.loadLibrary";
let bytes = library_bytes(p, C)?;
let xml = std::str::from_utf8(bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&bytes)).map_err(|_| bad(C, "the variable library is not UTF-8"))?;
- let lib = parse_library(xml, C)?;
+ let lib = parse_library(xml, C, false)?;
let vars = &s.doc()?.doc.variables;
- let kept = |v: &Variable| v.kind == VariableKind::Text && lib.text.contains(&v.name);
+ let kept = |v: &Variable| lib.variables.iter().any(|l| l.name == v.name && l.kind == v.kind);
let deleted: Vec = vars.variables.iter().filter(|v| !kept(v)).map(|v| v.name.clone()).collect();
let deleted_sets: Vec = vars.datasets.iter().map(|d| d.name.clone()).collect();
let added: Vec = lib
- .text
+ .variables
.iter()
- .filter(|n| !vars.variables.iter().any(|v| kept(v) && &v.name == *n))
- .map(|n| Variable { name: n.clone(), kind: VariableKind::Text })
+ .filter(|l| !vars.variables.iter().any(|v| kept(v) && v.name == l.name))
+ .map(|l| Variable { name: l.name.clone(), kind: l.kind })
.collect();
// Lock Variables refuses New Variable and Delete Variable, so the load is refused when it would
// delete or define a variable.
@@ -460,14 +674,8 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result {
let st = s.doc_mut()?;
st.drop_stale_variables_highlight();
st.revision += 1;
- let skipped: Vec = lib.other.iter().map(|(name, t)| json!({"name": name, "trait": t})).collect();
- let mut out = json!({
- "variables": lib.text, "deleted": deleted, "deletedDataSets": deleted_sets, "names": names, "skipped": skipped,
- });
- if let Some(warning) = left_out_warning(lib.other.iter().map(|(_, t)| t.as_str())) {
- out["warning"] = json!(warning);
- }
- Ok(out)
+ let declared: Vec<&str> = lib.variables.iter().map(|l| l.name.as_str()).collect();
+ Ok(json!({"variables": declared, "deleted": deleted, "deletedDataSets": deleted_sets, "names": names}))
}
/// The warning about variables that aren't text and were left out, given the kind of each: every
@@ -533,26 +741,95 @@ fn push_escaped(out: &mut String, c: char, attribute: bool) {
}
}
-/// Save Variable Library: the document's text variables and its data sets as a variable library in
-/// the layout [`parse_library`] reads, so Load Variable Library reads back the same text variables,
-/// data set names and text values. A text value is written as one `p` element per line. Variables
-/// of other kinds are left out with their values, named in `skipped` and in a warning. A text
-/// variable whose name can't name an element ([`element_name`]), a data set name or text value that
-/// holds a character XML can't hold, a name that Load Variable Library would read differently or
-/// refuse (white space at either end of a data set name, a name longer than `MAX_NAME` characters,
-/// a name used twice), and a library past the caps Load Variable Library reads are refused. With `path` the library is written to the file; without it the reply carries it as
-/// `xml`.
+/// Add the graph value `csv` of the variable `var` to `xml` as the `data` element [`graph_value`]
+/// reads: the CSV read as Graph Data reads it, a `propertyRow` with a blank corner cell and the
+/// series names when it names series, and a `row` per category, its name in a first `value` with
+/// `key="name"` (blank without categories) and then a `value` per series, blank where the row has
+/// none. A label that isn't a number is marked `type="string"`, and so is a blank category. CSV
+/// that names series and has no rows is written as the `propertyRow` alone. Refused for CSV with
+/// neither rows nor series, which reads back as no value, for more than [`MAX_GRAPH_CATEGORIES`]
+/// rows or [`MAX_GRAPH_SERIES`] series (what a graph holds), when a label holds a character XML
+/// can't hold, and when `xml` grows past `room` bytes.
+fn push_graph(xml: &mut String, var: &str, csv: &str, room: usize) -> std::result::Result<(), GraphRefusal> {
+ let (series, categories, rows) = super::super::graph::parse_csv(csv);
+ if rows.is_empty() && series.is_empty() {
+ return Err(GraphRefusal::Empty);
+ }
+ let width = rows.iter().map(Vec::len).max().unwrap_or(0).max(series.len());
+ if rows.len() > MAX_GRAPH_CATEGORIES || width > MAX_GRAPH_SERIES {
+ return Err(GraphRefusal::TooMany);
+ }
+ if !series.iter().chain(&categories).all(|l| l.chars().all(xml_char)) {
+ return Err(GraphRefusal::Control);
+ }
+ let labelled = !categories.is_empty();
+ let label = |l: &str, category: bool| {
+ let text = !l.is_empty() && l.trim().parse::().is_err();
+ let blank_category = category && labelled && l.is_empty();
+ let key = if category { " key=\"name\"" } else { "" };
+ let string = if text || blank_category { " type=\"string\"" } else { "" };
+ format!("{} ", escaped(l, false))
+ };
+ let _ = writeln!(xml, "\t\t\t\t<{var}>\n\t\t\t\t\t", width + usize::from(labelled));
+ if !series.is_empty() {
+ let names: String = (0..width).map(|s| label(series.get(s).map(String::as_str).unwrap_or_default(), false)).collect();
+ let _ = writeln!(xml, "\t\t\t\t\t\t {names} ");
+ }
+ xml.push_str("\t\t\t\t\t\t\n");
+ for (i, row) in rows.iter().enumerate() {
+ let name = label(categories.get(i).map(String::as_str).unwrap_or_default(), true);
+ let values: String = (0..width)
+ .map(|s| match row.get(s).copied().flatten() {
+ Some(v) => format!("{v} "),
+ None => " ".to_string(),
+ })
+ .collect();
+ let _ = writeln!(xml, "\t\t\t\t\t\t\t{name}{values}
");
+ if xml.len() > room {
+ return Err(GraphRefusal::TooLarge);
+ }
+ }
+ let _ = writeln!(xml, "\t\t\t\t\t\t \n\t\t\t\t\t \n\t\t\t\t{var}>");
+ Ok(())
+}
+
+/// What a graph holds at most, for the errors about graph data past it.
+fn graph_limits() -> String {
+ format!("more than {MAX_GRAPH_CATEGORIES} rows or {MAX_GRAPH_SERIES} series, which a graph doesn't hold")
+}
+
+/// Why [`push_graph`] refused a graph value.
+enum GraphRefusal {
+ /// A label holds a character XML can't hold.
+ Control,
+ /// The data has more rows or series than a graph holds.
+ TooMany,
+ /// The data has neither rows nor series.
+ Empty,
+ /// The library grew past the room it has.
+ TooLarge,
+}
+
+/// Save Variable Library: the document's variables and its data sets as a variable library in the
+/// layout [`parse_library`] reads, so Load Variable Library reads back the same variables with their
+/// kinds, data set names and values. Each variable is declared with the `trait` and `category` of
+/// its kind ([`kind_trait`]), and a variable of unknown kind with neither. A text value is written
+/// as one `p` element per line, a visibility value as `true` or `false`, an image value as
+/// [`library_file`] writes its path, and a graph value as a `data` element ([`push_graph`]). A
+/// variable whose name can't name an element ([`element_name`]; a variable of unknown kind has no
+/// values, so no element is named after it), a name or value that holds a character XML can't
+/// hold, a name that Load Variable Library would read differently or refuse (white space at either
+/// end, a name longer than `MAX_NAME` characters, a name used twice), an image value that isn't a
+/// file's absolute path, and a library past the caps Load Variable Library reads are refused. With
+/// `path` the library is written to the file; without it the reply carries it as `xml`.
pub(super) fn save_library(s: &mut Session, p: &Value) -> Result {
const C: &str = "variable.saveLibrary";
let vars = &s.doc()?.doc.variables;
if vars.variables.is_empty() {
return Err(bad(C, "define a variable first"));
}
- let (text, other): (Vec<&Variable>, Vec<&Variable>) = vars.variables.iter().partition(|v| v.kind == VariableKind::Text);
- if text.is_empty() {
- return Err(bad(C, "a variable library holds text variables, and the document has none"));
- }
- if let Some(name) = text.iter().map(|v| &v.name).find(|n| !element_name(n)) {
+ let all: Vec<&Variable> = vars.variables.iter().collect();
+ if let Some(name) = all.iter().filter(|v| v.kind != VariableKind::Unknown).map(|v| &v.name).find(|n| !element_name(n)) {
return Err(bad(
C,
format!(
@@ -560,48 +837,62 @@ pub(super) fn save_library(s: &mut Session, p: &Value) -> Result {
),
));
}
- // Load Variable Library refuses a name longer than `MAX_NAME` characters and a name declared
- // twice.
+ // Load Variable Library reads a name trimmed and refuses one longer than `MAX_NAME` characters
+ // or declared twice.
let mut declared = BTreeSet::new();
- for v in &text {
- named(Some(&v.name), "varName", C)?;
+ for v in &all {
+ if named(Some(&v.name), "varName", C)? != v.name || !v.name.chars().all(xml_char) {
+ return Err(bad(
+ C,
+ format!("variable `{}` starts or ends with white space or holds a control character, which a variable library can't hold", v.name),
+ ));
+ }
if !declared.insert(v.name.as_str()) {
return Err(bad(C, format!("variable `{}` is already defined", v.name)));
}
}
- if text.len() > MAX_LIBRARY_VARIABLES {
+ if all.len() > MAX_LIBRARY_VARIABLES {
return Err(bad(C, format!("the variable library declares more than {MAX_LIBRARY_VARIABLES} variables")));
}
if vars.datasets.len() > MAX_LIBRARY_DATASETS {
return Err(bad(C, format!("the variable library declares more than {MAX_LIBRARY_DATASETS} data sets")));
}
- fn text_value<'a>(ds: &'a DataSet, var: &str) -> Option<&'a str> {
- match ds.values.get(var) {
- Some(DataValue::Text(t)) => Some(t.as_str()),
- _ => None,
- }
- }
let mut xml = format!(
"\n\
\n\
\t\n\
\t\n\
+ \t\n\
]>\n\
\n\
\n\
\t\n\
\t\t\n"
);
- for v in &text {
- xml += &format!("\t\t\t \n", v.name);
+ for v in &all {
+ let name = escaped(&v.name, true);
+ match kind_trait(v.kind) {
+ Some((t, category)) => xml += &format!("\t\t\t \n"),
+ None => xml += &format!("\t\t\t \n"),
+ }
}
xml += "\t\t \n\t\t\n";
- // Load Variable Library caps the file and the text its entity references expand to: one
- // `&ns_flows;` per variable, two `&ns_vars;` and one `&ns_custom;`. The library stays within
- // the cap less what the references add.
+ // Load Variable Library caps the file and the text its entity references expand to: each
+ // variable's `category`, two `&ns_vars;` and one `&ns_custom;`. The library stays within the
+ // cap less what the references add.
let grows = |value: &str, reference: &str| value.len().saturating_sub(reference.len());
- let growth = text.len() * grows(NS_FLOWS, "&ns_flows;") + 2 * grows(NS_VARIABLES, "&ns_vars;") + grows(NS_CUSTOM, "&ns_custom;");
+ let growth = all
+ .iter()
+ .filter_map(|v| kind_trait(v.kind))
+ .map(|(_, category)| match category {
+ "&ns_flows;" => grows(NS_FLOWS, category),
+ "&ns_graphs;" => grows(NS_GRAPHS, category),
+ _ => grows(NS_VARIABLES, category),
+ })
+ .sum::()
+ + 2 * grows(NS_VARIABLES, "&ns_vars;")
+ + grows(NS_CUSTOM, "&ns_custom;");
let room = MAX_LIBRARY_BYTES.saturating_sub(growth);
let too_large = || bad(C, format!("the variable library is larger than {MAX_LIBRARY_BYTES} bytes"));
let mut seen = BTreeSet::new();
@@ -615,25 +906,61 @@ pub(super) fn save_library(s: &mut Session, p: &Value) -> Result {
if !seen.insert(name.as_str()) {
return Err(bad(C, format!("dataset `{name}` already exists")));
}
- if !name.chars().all(xml_char) || text.iter().filter_map(|v| text_value(ds, &v.name)).any(|t| !t.chars().all(xml_char)) {
- return Err(bad(C, format!("data set `{name}` holds a control character, which a variable library can't hold")));
+ let control = || bad(C, format!("data set `{name}` holds a control character, which a variable library can't hold"));
+ let mut text_values = all.iter().filter_map(|v| match ds.values.get(&v.name) {
+ Some(DataValue::Text(t)) if v.kind == VariableKind::Text => Some(t),
+ _ => None,
+ });
+ if !name.chars().all(xml_char) || text_values.any(|t| !t.chars().all(xml_char)) {
+ return Err(control());
}
xml += &format!("\t\t\t\n", escaped(name, true));
- for v in &text {
- let Some(t) = text_value(ds, &v.name) else { continue };
- xml += &format!("\t\t\t\t<{}>\n", v.name);
- for line in t.split('\n') {
- xml += "\t\t\t\t\t";
- // A value can be larger than the cap, so the text stops growing once it passes it.
- for c in line.chars() {
- push_escaped(&mut xml, c, false);
- if xml.len() > room {
- return Err(too_large());
+ for v in &all {
+ let Some(value) = ds.values.get(&v.name).filter(|value| value.fits(v.kind)) else { continue };
+ let var = &v.name;
+ match value {
+ DataValue::Text(t) => {
+ xml += &format!("\t\t\t\t<{var}>\n");
+ for line in t.split('\n') {
+ xml += "\t\t\t\t\t
";
+ // A value can be larger than the cap, so the text stops growing once it passes it.
+ for c in line.chars() {
+ push_escaped(&mut xml, c, false);
+ if xml.len() > room {
+ return Err(too_large());
+ }
+ }
+ xml += "
\n";
}
+ xml += &format!("\t\t\t\t{var}>\n");
}
- xml += "
\n";
+ DataValue::Visible(shown) => xml += &format!("\t\t\t\t<{var}>{shown}{var}>\n"),
+ DataValue::Image(path) => {
+ // Load Variable Library reads back only a file's absolute path.
+ let file = library_file(path);
+ if library_path(file.trim_matches(XML_SPACE)).as_deref() != Some(path.as_str()) {
+ return Err(bad(C, format!("data set `{name}` holds an image value for `{var}` that isn't a file's absolute path")));
+ }
+ if !file.chars().all(xml_char) {
+ return Err(control());
+ }
+ xml += &format!("\t\t\t\t<{var}>{}{var}>\n", escaped(&file, false));
+ }
+ DataValue::Graph(csv) => match push_graph(&mut xml, var, csv, room) {
+ Ok(()) => {}
+ Err(GraphRefusal::Control) => return Err(control()),
+ Err(GraphRefusal::TooMany) => {
+ return Err(bad(C, format!("data set `{name}` holds a graph value for `{var}` with {}", graph_limits())));
+ }
+ Err(GraphRefusal::Empty) => {
+ return Err(bad(C, format!("data set `{name}` holds a graph value for `{var}` without rows or series")));
+ }
+ Err(GraphRefusal::TooLarge) => return Err(too_large()),
+ },
+ }
+ if xml.len() > room {
+ return Err(too_large());
}
- xml += &format!("\t\t\t\t{}>\n", v.name);
}
xml += "\t\t\t\n";
if xml.len() > room {
@@ -644,13 +971,7 @@ pub(super) fn save_library(s: &mut Session, p: &Value) -> Result {
if xml.len() > room {
return Err(too_large());
}
- let skipped: Vec = other.iter().map(|v| json!({"name": v.name, "kind": v.kind.label()})).collect();
- let mut out = json!({
- "variables": text.iter().map(|v| v.name.as_str()).collect::>(), "datasets": vars.datasets.len(), "skipped": skipped,
- });
- if let Some(warning) = left_out_warning(other.iter().map(|v| v.kind.label())) {
- out["warning"] = json!(warning);
- }
+ let mut out = json!({"variables": all.iter().map(|v| v.name.as_str()).collect::>(), "datasets": vars.datasets.len()});
match str_param(p, "path") {
Some(path) => {
let path = absolute_path(path);
diff --git a/crates/engine/src/tests/attributes.rs b/crates/engine/src/tests/attributes.rs
index 8ddfc352a1..b6d00111e2 100644
--- a/crates/engine/src/tests/attributes.rs
+++ b/crates/engine/src/tests/attributes.rs
@@ -218,6 +218,39 @@ fn reverse_path_direction_turns_the_width_profile_and_pen_records_with_the_path(
}
}
+#[test]
+fn reverse_path_direction_turns_a_compound_paths_own_width_profile_and_pen_records() {
+ use vectorcraft_doc::{AngleProfile, PressureProfile, WidthProfile};
+ let mut s = session();
+ let (a, b) = (rect(&mut s, 0.0), rect(&mut s, 50.0));
+ run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
+ run(&mut s, "object.compoundPath.make", json!({}));
+ let compound = s.doc().unwrap().selection.objects[0];
+ // A lone rectangle of the same shape, whose strokes Reverse Path Direction already turns.
+ let lone = rect(&mut s, 0.0);
+ let profile = WidthProfile { points: vec![(0.0, 0.2, 0.6), (0.3, 1.0, 0.4), (1.0, 0.5, 0.9)] };
+ let pressure = PressureProfile { points: vec![(0.0, 0.1), (0.25, 0.9), (1.0, 0.4)] };
+ let bearing = AngleProfile { points: vec![(0.0, 10.0), (0.6, 80.0), (1.0, 170.0)] };
+ s.edit("set", |d, _| {
+ for id in [compound, lone] {
+ let st = d.node_mut(id).unwrap().appearance.stroke_mut().unwrap();
+ st.profile = Some(profile.clone());
+ st.pressure = Some(pressure.clone());
+ st.bearing = Some(bearing.clone());
+ }
+ Ok(())
+ })
+ .unwrap();
+ run(&mut s, "select.set", json!({"ids": [compound.0, lone.0]}));
+ assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 3);
+ let stroke = |id: NodeId| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke().unwrap().clone();
+ let (got, want) = (stroke(compound), stroke(lone));
+ assert_ne!(want.profile.as_ref(), Some(&profile), "the lone rectangle's profile turned");
+ assert_eq!(got.profile, want.profile, "both members turned alike, so the compound path's profile turns as the rectangle's does");
+ assert_eq!(got.pressure, want.pressure);
+ assert_eq!(got.bearing, want.bearing);
+}
+
#[test]
fn attributes_survive_a_native_round_trip() {
let mut s = session();
diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs
index 8fd5a3aa45..b1e90324ba 100644
--- a/crates/engine/src/tests/build.rs
+++ b/crates/engine/src/tests/build.rs
@@ -2781,7 +2781,7 @@ fn live_paint_fill_same_paint_is_no_op() {
let mut before = snapshot(&s);
let click = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#00ff00"})).unwrap();
let face = vectorcraft_tools::builder::face_at(&node(&s, g), Point::new(75.0, 50.0)).unwrap().id;
- assert_eq!(click, json!({"group": g.0, "face": face.0}), "the usual reply");
+ assert_eq!(click, json!({"group": g.0, "face": face.0, "count": 1}), "the usual reply");
assert_unchanged(&mut s, &mut before, "a click on a face with the paint");
s.execute("livePaint.fill", &drag).unwrap();
assert_unchanged(&mut s, &mut before, "a drag over faces with the paint");
@@ -2850,6 +2850,42 @@ fn live_paint_stroke_edge_same_paint_and_width_is_no_op() {
assert_eq!(history_state(&s).0, before.1.0 + 1);
}
+/// With `scope`, faces and edges that already have the paint (and the width) are skipped: when
+/// every face or edge the call reaches has it, nothing changes, and when some do, only the others
+/// are painted, in one undo step. `count` is every face or edge reached.
+#[test]
+fn live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "points": [[25, 50], [125, 50]], "color": "#00ff00"})).unwrap();
+ let edges =
+ s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [100, 50], "scope": "samePaint", "color": "#ff0000", "width": 3})).unwrap();
+ redo_waiting_and_saved(&mut s, g);
+ let mut before = snapshot(&s);
+ let same = json!({"group": g.0, "point": [75, 50], "scope": "samePaint", "color": "#00ff00"});
+ assert_eq!(s.execute("livePaint.fill", &same).unwrap()["count"], 3);
+ assert_unchanged(&mut s, &mut before, "a samePaint fill where every face has the paint");
+ let again = json!({"group": g.0, "point": [100, 50], "scope": "samePaint", "color": "#ff0000", "width": 3});
+ assert_eq!(s.execute("livePaint.strokeEdge", &again).unwrap()["count"], edges["count"]);
+ assert_unchanged(&mut s, &mut before, "a samePaint stroke where every edge has the paint and the width");
+ // One face of the three without the paint: only it is filled, in one undo step.
+ let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
+ let red = Paint::solid(Color::from_hex("#ff0000").unwrap());
+ s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#ff0000"})).unwrap();
+ let depth = history_state(&s).0;
+ let like = serde_json::to_value(&green).unwrap();
+ let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "scope": "samePaint", "match": like, "color": "#00ff00"})).unwrap();
+ assert_eq!(r["count"], 3);
+ assert_eq!(history_state(&s).0, depth + 1);
+ let fill_at = |s: &Session, x: f64| vectorcraft_tools::builder::face_at(&node(s, g), Point::new(x, 50.0)).unwrap().appearance.fill_paint();
+ for x in [25.0, 75.0, 125.0] {
+ assert_eq!(fill_at(&s, x), green, "{x}");
+ }
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(fill_at(&s, 25.0), red);
+ assert_eq!((fill_at(&s, 75.0), fill_at(&s, 125.0)), (green.clone(), green));
+}
+
#[test]
fn live_paint_gap_options_same_values_are_no_op() {
let mut s = session();
@@ -3012,6 +3048,472 @@ fn live_paint_fill_skips_hidden_faces() {
assert!(!node(&s, hidden).visible);
}
+/// A Live Paint group of 50 pt squares side by side, 50 pt tall, with their left sides at each of
+/// `xs`.
+fn live_squares(s: &mut Session, xs: &[f64]) -> NodeId {
+ let ids: Vec = xs.iter().map(|&x| rect(s, x, 0.0, 50.0, 50.0).0).collect();
+ s.execute("select.set", &json!({"ids": ids})).unwrap();
+ NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap())
+}
+
+/// The ids of the faces of `g` that hold `p`, in the order given.
+fn faces_at(s: &Session, g: NodeId, ps: &[(f64, f64)]) -> Vec {
+ ps.iter().map(|&(x, y)| vectorcraft_tools::builder::face_at(&node(s, g), Point::new(x, y)).unwrap().id).collect()
+}
+
+/// The edges of `g` whose bounds lie within `r`.
+fn edges_in(s: &Session, g: NodeId, r: Rect) -> Vec {
+ let r = r.inflate(1e-6, 1e-6);
+ vectorcraft_tools::builder::edges(&node(s, g))
+ .iter()
+ .filter(|e| e.geometric_bounds().is_some_and(|bb| r.contains(Point::new(bb.x0, bb.y0)) && r.contains(Point::new(bb.x1, bb.y1))))
+ .map(|e| e.id)
+ .collect()
+}
+
+/// Give `ids` stroke paint `paint` at weight 1 (none: no stroke), and `fill` to the faces in `faces`.
+fn paint_parts(s: &mut Session, ids: &[NodeId], paint: &Paint, faces: &[(NodeId, Paint)]) {
+ s.edit("t", |d, _| {
+ for id in ids {
+ let n = d.node_mut(*id).unwrap();
+ n.appearance.set_stroke(paint.clone());
+ if let Some(st) = n.appearance.stroke_mut() {
+ st.width = 1.0;
+ }
+ }
+ for (id, fill) in faces {
+ d.node_mut(*id).unwrap().appearance.set_fill(fill.clone());
+ }
+ Ok(())
+ })
+ .unwrap();
+}
+
+fn fill_of(s: &Session, id: NodeId) -> Paint {
+ node(s, id).appearance.fill_paint()
+}
+
+/// A double-click on a face fills it and the faces reached across edges that draw no stroke; a
+/// stroked edge and a hidden face stop the flood.
+#[test]
+fn live_paint_bucket_double_click_floods_across_unstroked_edges() {
+ let mut s = session();
+ let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
+ let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
+ let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
+ paint_parts(&mut s, &all, &Paint::None, &[]);
+ let stroked = edges_in(&s, g, Rect::new(150.0, 0.0, 150.0, 50.0));
+ assert!(!stroked.is_empty());
+ paint_parts(&mut s, &stroked, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[]);
+ let white = fill_of(&s, d);
+ let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
+ assert_ne!(white, green);
+ let depth = s.doc().unwrap().history.undo.len();
+ let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap();
+ assert_eq!((&r["face"], &r["count"]), (&json!(a.0), &json!(3)));
+ assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green.clone(), white.clone()]);
+ assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1, "one undo step");
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!([a, b, c].iter().all(|f| fill_of(&s, *f) != green));
+ // A hidden face is not filled and does not pass the flood on.
+ s.execute("object.setProps", &json!({"ids": [b.0], "visible": false})).unwrap();
+ let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap();
+ assert_eq!(r["count"], 1);
+ assert_eq!([a, b, c].map(|f| fill_of(&s, f) == green), [true, false, false]);
+ while s.doc().unwrap().history.undo.len() > depth {
+ s.execute("edit.undo", &json!({})).unwrap();
+ }
+ // The tool: two clicks and the double-click that follows them.
+ let v = ViewInfo::default();
+ s.select_tool("livePaintBucket", v).unwrap();
+ s.paint.fill = green.clone();
+ for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
+ s.pointer(&PointerEvent::new(kind, 125.0, 25.0), v).unwrap();
+ }
+ assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green, white]);
+}
+
+/// An edge that draws no stroke (fully transparent, or with its stroke hidden) lets a flood across
+/// although it stores a stroke paint, and an edge scope compares the stroke paint each edge draws
+/// with.
+#[test]
+fn live_paint_bucket_scopes_follow_the_stroke_an_edge_draws() {
+ let mut s = session();
+ let g = live_squares(&mut s, &[0.0, 50.0, 100.0]);
+ let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
+ let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 151.0, 51.0));
+ paint_parts(&mut s, &all, &black, &[]);
+ let clear = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0));
+ let hidden = edges_in(&s, g, Rect::new(100.0, 0.0, 100.0, 50.0));
+ assert!(!clear.is_empty() && !hidden.is_empty());
+ s.edit("t", |d, _| {
+ for id in &clear {
+ d.node_mut(*id).unwrap().opacity = 0.0;
+ }
+ for id in &hidden {
+ d.node_mut(*id).unwrap().appearance.stroke_mut().unwrap().visible = false;
+ }
+ Ok(())
+ })
+ .unwrap();
+ let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap();
+ assert_eq!(r["count"], 3, "the flood crosses both middle edges");
+ s.execute("edit.undo", &json!({})).unwrap();
+ let stroke = |s: &mut Session, at: [f64; 2]| {
+ let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": at, "color": "#00ff00", "width": 3, "scope": "samePaint"})).unwrap();
+ s.execute("edit.undo", &json!({})).unwrap();
+ r["count"].clone()
+ };
+ assert_eq!(stroke(&mut s, [25.0, 0.0]), json!(all.len() - clear.len() - hidden.len()), "the edges that draw black");
+ assert_eq!(stroke(&mut s, [50.0, 25.0]), json!(clear.len() + hidden.len()), "the edges that draw no stroke");
+ // With the top edge between them fully transparent too, the connected scope walks from the edge
+ // at x = 50 through it to the edge at x = 100, and reaches no edge that draws black.
+ let top = edges_in(&s, g, Rect::new(50.0, 0.0, 100.0, 0.0));
+ assert_eq!(top.len(), 1);
+ s.edit("t", |d, _| {
+ d.node_mut(top[0]).unwrap().opacity = 0.0;
+ Ok(())
+ })
+ .unwrap();
+ let r =
+ s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [50, 25], "color": "#00ff00", "width": 3, "scope": "connected"})).unwrap();
+ assert_eq!(r["count"], json!(clear.len() + top.len() + hidden.len()));
+}
+
+/// `livePaint.strokeEdge` paints an edge's topmost stroke that is shown, so the edge then draws
+/// with the paint; an edge whose strokes are all hidden takes a new stroke above them. Painting
+/// again changes nothing.
+#[test]
+fn live_paint_stroke_edge_paints_the_shown_stroke() {
+ let mut s = session();
+ let g = live_squares(&mut s, &[0.0, 50.0]);
+ let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
+ let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
+ let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
+ let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0));
+ paint_parts(&mut s, &all, &black, &[]);
+ let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0));
+ let left: Vec = edges_in(&s, g, Rect::new(0.0, 0.0, 50.0, 50.0)).into_iter().filter(|e| !middle.contains(e)).collect();
+ let (&[m], &[l]) = (&middle[..], &left[..]) else { panic!("one middle edge and one other edge round the left face") };
+ // The middle edge draws red under a hidden black stroke; every stroke of the left face's other
+ // edge is hidden.
+ s.edit("t", |d, _| {
+ let n = d.node_mut(m).unwrap();
+ n.appearance.items.insert(0, AppearanceItem::Stroke(vectorcraft_doc::appearance::StrokeLayer::new(red.clone(), 1.0)));
+ n.appearance.stroke_mut().unwrap().visible = false;
+ d.node_mut(l).unwrap().appearance.stroke_mut().unwrap().visible = false;
+ Ok(())
+ })
+ .unwrap();
+ let drawn = |s: &Session, id: NodeId| vectorcraft_tools::builder::lp_stroke_paint(&node(s, id));
+ assert_eq!(drawn(&s, m), red);
+ let paint = |s: &mut Session, at: [f64; 2]| {
+ s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": at, "color": "#00ff00", "width": 2})).unwrap();
+ };
+ for (id, at) in [(m, [50.0, 25.0]), (l, [0.0, 25.0])] {
+ paint(&mut s, at);
+ assert_eq!(drawn(&s, id), green, "{id}");
+ let depth = history_state(&s).0;
+ paint(&mut s, at);
+ assert_eq!(history_state(&s).0, depth, "painting {id} again");
+ }
+ assert_eq!(node(&s, m).appearance.items.len(), 2, "the hidden stroke stays as it was");
+ assert_eq!(node(&s, l).appearance.items.len(), 2, "a new stroke above the hidden one");
+}
+
+/// With Cmd held, the Live Paint Bucket's presses go to the selection tool Cmd lends, and the
+/// double-click and triple-click that follow them paint nothing.
+#[test]
+fn live_paint_bucket_cmd_double_and_triple_click_paint_nothing() {
+ let mut s = session();
+ let g = live_squares(&mut s, &[0.0, 50.0, 100.0]);
+ let faces = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0)]);
+ let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 151.0, 51.0));
+ paint_parts(&mut s, &all, &Paint::None, &[]);
+ let before: Vec = faces.iter().map(|f| fill_of(&s, *f)).collect();
+ let v = ViewInfo::default();
+ s.select_tool("livePaintBucket", v).unwrap();
+ s.paint.fill = Paint::solid(Color::from_hex("#00ff00").unwrap());
+ let cmd = Mods { cmd: true, ..Default::default() };
+ let (down, up) = (PointerKind::Down, PointerKind::Up);
+ for kind in [down, up, down, up, PointerKind::DoubleClick, down, up, PointerKind::TripleClick] {
+ s.pointer(&PointerEvent::new(kind, 75.0, 25.0).with_mods(cmd), v).unwrap();
+ }
+ assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::>(), before);
+ assert_eq!(s.tool_id(), "livePaintBucket");
+}
+
+/// The flood crosses curved edges, and reaches a face 0.012 pt wide.
+#[test]
+fn live_paint_bucket_double_click_floods_curved_and_narrow_faces() {
+ let mut s = session();
+ let ids: Vec = [0.0, 60.0]
+ .iter()
+ .map(|&x| s.execute("shape.ellipse", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap())
+ .collect();
+ s.execute("select.set", &json!({"ids": ids})).unwrap();
+ let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
+ let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 161.0, 101.0));
+ paint_parts(&mut s, &all, &Paint::None, &[]);
+ let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [20, 50], "color": "#00ff00", "scope": "connected"})).unwrap();
+ assert_eq!(r["count"], 3, "both lunes and the lens between them");
+
+ let mut s = session();
+ let ids = [rect(&mut s, 0.0, 0.0, 50.0, 50.0).0, rect(&mut s, 49.988, 0.0, 50.0, 50.0).0];
+ s.execute("select.set", &json!({"ids": ids})).unwrap();
+ let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
+ let [a, sliver, c] = faces_at(&s, g, &[(25.0, 25.0), (49.994, 25.0), (75.0, 25.0)])[..] else { panic!("three faces") };
+ assert!(a != sliver && sliver != c);
+ let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0));
+ paint_parts(&mut s, &all, &Paint::None, &[]);
+ let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
+ let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap();
+ assert_eq!(r["count"], 3);
+ assert_eq!([a, sliver, c].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green]);
+}
+
+/// The flood crosses a hidden edge, and an edge that a Gap Detection gap meets partway along, but
+/// not the gap.
+#[test]
+fn live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps() {
+ let mut s = session();
+ let g = live_squares(&mut s, &[0.0, 50.0]);
+ let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
+ let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0));
+ paint_parts(&mut s, &all, &black, &[]);
+ let fill = |s: &mut Session, g: NodeId, at: [f64; 2]| {
+ s.execute("livePaint.fill", &json!({"group": g.0, "point": at, "color": "#00ff00", "scope": "connected"})).unwrap()["count"].clone()
+ };
+ assert_eq!(fill(&mut s, g, [25.0, 25.0]), 1, "a stroked edge stops the flood");
+ s.execute("edit.undo", &json!({})).unwrap();
+ let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0));
+ s.execute("object.setProps", &json!({"ids": middle.iter().map(|e| e.0).collect::>(), "visible": false})).unwrap();
+ assert_eq!(fill(&mut s, g, [25.0, 25.0]), 2, "a hidden edge does not");
+
+ // Square B (100..200 by 0..100) over square C (100..200 by 100..200), and a line down the middle
+ // of B that stops 2 pt short of their shared edge: Gap Detection closes it, so B is two faces
+ // that each run along part of the shared edge, which is one edge segment.
+ let mut s = session();
+ let mut ids = vec![rect(&mut s, 100.0, 0.0, 100.0, 100.0).0, rect(&mut s, 100.0, 100.0, 100.0, 100.0).0];
+ let line = s.execute("path.create", &json!({"anchors": [{"x": 150, "y": 0}, {"x": 150, "y": 98}]})).unwrap();
+ ids.push(line["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": ids})).unwrap();
+ let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
+ s.execute("livePaint.gapOptions", &json!({"id": g.0, "detect": true, "size": "small"})).unwrap();
+ let [b1, b2, c] = faces_at(&s, g, &[(125.0, 50.0), (175.0, 50.0), (150.0, 150.0)])[..] else { panic!("three faces") };
+ assert!(b1 != b2 && b2 != c && b1 != c);
+ let all = edges_in(&s, g, Rect::new(99.0, -1.0, 201.0, 201.0));
+ paint_parts(&mut s, &all, &black, &[]);
+ let shared = edges_in(&s, g, Rect::new(100.0, 100.0, 200.0, 100.0));
+ assert!(!shared.is_empty());
+ paint_parts(&mut s, &shared, &Paint::None, &[]);
+ assert_eq!(fill(&mut s, g, [150.0, 150.0]), 3, "from C across the shared edge to both faces of B");
+ s.execute("edit.undo", &json!({})).unwrap();
+ // With the line and the shared edge stroked, only the gap lies between the two faces of B.
+ paint_parts(&mut s, &shared, &black, &[]);
+ assert_eq!(fill(&mut s, g, [125.0, 50.0]), 1, "the flood does not pass the gap");
+
+ // B alone, its outline drawing no stroke and the line stroked: the two faces of B run along
+ // different parts of the outline's bottom segment, on the same side, and the flood does not
+ // join them there.
+ let mut s = session();
+ let mut ids = vec![rect(&mut s, 100.0, 0.0, 100.0, 100.0).0];
+ let line = s.execute("path.create", &json!({"anchors": [{"x": 150, "y": 0}, {"x": 150, "y": 98}]})).unwrap();
+ ids.push(line["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": ids})).unwrap();
+ let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
+ s.execute("livePaint.gapOptions", &json!({"id": g.0, "detect": true, "size": "small"})).unwrap();
+ assert_eq!(vectorcraft_tools::builder::faces(&node(&s, g)).len(), 2);
+ let all = edges_in(&s, g, Rect::new(99.0, -1.0, 201.0, 101.0));
+ paint_parts(&mut s, &all, &Paint::None, &[]);
+ let line = edges_in(&s, g, Rect::new(150.0, 0.0, 150.0, 98.0));
+ assert!(!line.is_empty() && line.len() < all.len());
+ paint_parts(&mut s, &line, &black, &[]);
+ assert_eq!(fill(&mut s, g, [125.0, 50.0]), 1, "the gap parts the two faces along the bottom");
+}
+
+/// The flood crosses an edge into each face along it when a face's outline runs along the edge in
+/// one segment and the edge is split where another line meets it.
+#[test]
+fn live_paint_bucket_double_click_floods_along_edges_split_at_a_junction() {
+ // A square with a line across its middle, and a line from the top at x = 30 that crosses it and
+ // stops 20 pt below. The bottom face's outline runs along the middle line in one segment, from
+ // x = 0 to 100; the middle line's edges are split at x = 30.
+ let mut s = session();
+ let mut ids = vec![rect(&mut s, 0.0, 0.0, 100.0, 100.0).0];
+ for anchors in [json!([{"x": 0, "y": 50}, {"x": 100, "y": 50}]), json!([{"x": 30, "y": 0}, {"x": 30, "y": 70}])] {
+ ids.push(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap());
+ }
+ s.execute("select.set", &json!({"ids": ids})).unwrap();
+ let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
+ let [left, right, bottom] = faces_at(&s, g, &[(15.0, 25.0), (65.0, 25.0), (65.0, 75.0)])[..] else { panic!("three faces") };
+ assert!(left != right && right != bottom && left != bottom);
+ let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 101.0));
+ paint_parts(&mut s, &all, &Paint::None, &[]);
+ let down = edges_in(&s, g, Rect::new(30.0, 0.0, 30.0, 70.0));
+ assert!(!down.is_empty() && down.len() < all.len());
+ paint_parts(&mut s, &down, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[]);
+ let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
+ let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [65, 75], "color": "#00ff00", "scope": "connected"})).unwrap();
+ assert_eq!(r["count"], 3, "from the bottom face to both faces above the line");
+ assert_eq!([left, right, bottom].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green.clone()]);
+ s.execute("edit.undo", &json!({})).unwrap();
+ let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [15, 25], "color": "#00ff00", "scope": "connected"})).unwrap();
+ assert_eq!(r["count"], 3, "from the upper left face down to the bottom face and up again");
+}
+
+/// A triple-click on a face fills every face of the group with that face's fill, joined to it or
+/// not. Through the tool, the fill compared is the face's fill before the first click.
+#[test]
+fn live_paint_bucket_triple_click_fills_every_face_of_the_same_fill() {
+ let mut s = session();
+ let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
+ let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
+ let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
+ let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
+ let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
+ paint_parts(&mut s, &all, &Paint::None, &[(a, red.clone()), (b, blue.clone()), (c, red.clone()), (d, red.clone())]);
+ let stroked = edges_in(&s, g, Rect::new(100.0, 0.0, 100.0, 50.0));
+ paint_parts(&mut s, &stroked, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[]);
+ let depth = s.doc().unwrap().history.undo.len();
+ let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "samePaint"})).unwrap();
+ assert_eq!(r["count"], 3);
+ assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), blue.clone(), green.clone(), green.clone()]);
+ s.execute("edit.undo", &json!({})).unwrap();
+ // The tool: the first click fills the face, the double-click floods across x = 50 into B, and
+ // the triple-click fills the faces that were red.
+ let v = ViewInfo::default();
+ s.select_tool("livePaintBucket", v).unwrap();
+ s.paint.fill = green.clone();
+ for kind in [
+ PointerKind::Down,
+ PointerKind::Up,
+ PointerKind::Down,
+ PointerKind::Up,
+ PointerKind::DoubleClick,
+ PointerKind::Down,
+ PointerKind::Up,
+ PointerKind::TripleClick,
+ ] {
+ s.pointer(&PointerEvent::new(kind, 25.0, 25.0), v).unwrap();
+ }
+ assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green.clone(), green.clone()]);
+ // A match given by the caller is the fill compared.
+ while s.doc().unwrap().history.undo.len() > depth {
+ s.execute("edit.undo", &json!({})).unwrap();
+ }
+ assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [red.clone(), blue.clone(), red.clone(), red.clone()]);
+ let r = s
+ .execute(
+ "livePaint.fill",
+ &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "samePaint", "match": serde_json::to_value(&blue).unwrap()}),
+ )
+ .unwrap();
+ assert_eq!(r["count"], 2);
+ assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green, red.clone(), red]);
+}
+
+/// A triple-click whose first click makes the Live Paint group from the selected paths matches the
+/// fill the face was made with.
+#[test]
+fn live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill() {
+ let mut s = session();
+ let ids: Vec = [0.0, 100.0, 200.0].iter().map(|&x| rect(&mut s, x, 0.0, 50.0, 50.0)).collect();
+ let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
+ for (id, c) in ids.iter().zip([red, red, blue]) {
+ set_fill(&mut s, *id, c);
+ }
+ s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap();
+ let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
+ let v = ViewInfo::default();
+ s.select_tool("livePaintBucket", v).unwrap();
+ s.paint.fill = green.clone();
+ for kind in [
+ PointerKind::Down,
+ PointerKind::Up,
+ PointerKind::Down,
+ PointerKind::Up,
+ PointerKind::DoubleClick,
+ PointerKind::Down,
+ PointerKind::Up,
+ PointerKind::TripleClick,
+ ] {
+ s.pointer(&PointerEvent::new(kind, 25.0, 25.0), v).unwrap();
+ }
+ let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the clicks made a group");
+ let faces = faces_at(&s, g, &[(25.0, 25.0), (125.0, 25.0), (225.0, 25.0)]);
+ assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::>(), [green.clone(), green, Paint::solid(blue)]);
+}
+
+/// A double-click on an edge paints the edges joined to it that have its stroke, and a
+/// triple-click every edge of the group with that stroke; an edge with another stroke is left.
+#[test]
+fn live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges() {
+ let mut s = session();
+ let g = live_squares(&mut s, &[0.0, 50.0, 200.0]);
+ let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
+ let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
+ let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
+ let joined = edges_in(&s, g, Rect::new(0.0, 0.0, 100.0, 50.0));
+ let apart = edges_in(&s, g, Rect::new(200.0, 0.0, 250.0, 50.0));
+ let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0));
+ assert!(!apart.is_empty() && !middle.is_empty());
+ paint_parts(&mut s, &joined, &black, &[]);
+ paint_parts(&mut s, &apart, &black, &[]);
+ paint_parts(&mut s, &middle, &red, &[]);
+ let stroke = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).appearance.stroke_paint()).collect::>();
+ let outer: Vec = joined.iter().copied().filter(|e| !middle.contains(e)).collect();
+ let r =
+ s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [25, 0], "color": "#00ff00", "width": 3, "scope": "connected"})).unwrap();
+ assert_eq!(r["count"], outer.len());
+ assert!(stroke(&s, &outer).iter().all(|p| *p == green));
+ assert!(outer.iter().all(|e| node(&s, *e).appearance.stroke_width() == 3.0));
+ assert!(stroke(&s, &middle).iter().all(|p| *p == red), "another stroke is left");
+ assert!(stroke(&s, &apart).iter().all(|p| *p == black), "edges not joined are left");
+ s.execute("edit.undo", &json!({})).unwrap();
+ let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [25, 0], "color": "#00ff00", "scope": "samePaint"})).unwrap();
+ assert_eq!(r["count"], outer.len() + apart.len());
+ assert!(stroke(&s, &outer).iter().chain(&stroke(&s, &apart)).all(|p| *p == green));
+ assert!(stroke(&s, &middle).iter().all(|p| *p == red));
+ // A hidden edge is not painted.
+ s.execute("edit.undo", &json!({})).unwrap();
+ s.execute("object.setProps", &json!({"ids": [apart[0].0], "visible": false})).unwrap();
+ let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [25, 0], "color": "#00ff00", "scope": "samePaint"})).unwrap();
+ assert_eq!(r["count"], outer.len() + apart.len() - 1);
+ assert_eq!(node(&s, apart[0]).appearance.stroke_paint(), black);
+}
+
+/// A `scope` that is not one of the three, a `match` that is not a paint or is given with a scope
+/// that compares none, and a scope with a drag's points are refused; nothing changes.
+#[test]
+fn live_paint_scope_and_match_are_checked() {
+ let mut s = session();
+ let g = live(&mut s);
+ let none = serde_json::to_value(Paint::None).unwrap();
+ let before = s.doc().unwrap().doc.clone();
+ let depth = s.doc().unwrap().history.undo.len();
+ for (cmd, p) in [
+ ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "all"})),
+ ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": 2})),
+ ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "match": none})),
+ ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "connected", "match": none})),
+ ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "samePaint", "match": "red"})),
+ ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "connected", "points": [[75, 50], [125, 50]]})),
+ ("livePaint.strokeEdge", json!({"group": g.0, "point": [100, 50], "scope": "Connected"})),
+ ("livePaint.strokeEdge", json!({"group": g.0, "point": [100, 50], "scope": "one", "match": none})),
+ ("livePaint.strokeEdge", json!({"group": g.0, "point": [100, 50], "scope": "samePaint", "match": {"type": "plaid"}})),
+ ] {
+ assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}");
+ }
+ assert_eq!(s.doc().unwrap().doc, before);
+ assert_eq!(s.doc().unwrap().history.undo.len(), depth);
+ // "one" and null are a click's scope.
+ for scope in [json!("one"), Value::Null] {
+ let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "scope": scope})).unwrap();
+ assert_eq!(r["count"], 1);
+ }
+}
+
#[test]
fn live_paint_release_and_expand() {
let mut s = session();
diff --git a/crates/engine/src/tests/distort.rs b/crates/engine/src/tests/distort.rs
index d033fadee6..6f56a09b68 100644
--- a/crates/engine/src/tests/distort.rs
+++ b/crates/engine/src/tests/distort.rs
@@ -1,6 +1,6 @@
//! Width points, Liquify, Puppet Warp and Perspective Grid commands and tools.
-use serde_json::json;
+use serde_json::{Value, json};
use vectorcraft_geom::{PathData, Point, Rect, Shape};
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
@@ -625,6 +625,25 @@ fn attach_projects_onto_the_plane_and_releases() {
assert_eq!(path(&s, a).bounds().unwrap(), Rect::new(450.0, 300.0, 550.0, 400.0));
}
+#[test]
+fn a_repeated_id_attaches_moves_and_transforms_an_object_once() {
+ let edited = |cmd: &str, ids: &[u64], extra: Value| {
+ let mut s = session();
+ s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap();
+ let a = rect(&mut s, 450.0, 300.0, 100.0, 100.0);
+ let ids: Vec = ids.iter().map(|_| a.0).collect();
+ let mut p = json!({"ids": ids, "plane": "right"});
+ p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
+ s.execute(cmd, &p).unwrap();
+ path(&s, a)
+ };
+ let moved = json!({"from": [480.0, 330.0], "to": [500.0, 350.0], "constrain": true});
+ let scaled = json!({"matrix": [1.5, 0.0, 0.0, 1.5, 10.0, 0.0]});
+ for (cmd, extra) in [("perspective.attach", json!({})), ("perspective.move", moved), ("perspective.transform", scaled)] {
+ assert_eq!(edited(cmd, &[0, 0], extra.clone()), edited(cmd, &[0], extra), "{cmd}");
+ }
+}
+
#[test]
fn rectangle_tool_draws_in_perspective_on_the_active_plane() {
let mut s = session();
diff --git a/crates/engine/src/tests/rasterfilters.rs b/crates/engine/src/tests/rasterfilters.rs
index 534f79b1bc..521ba0adbf 100644
--- a/crates/engine/src/tests/rasterfilters.rs
+++ b/crates/engine/src/tests/rasterfilters.rs
@@ -143,19 +143,22 @@ fn listed_applied_edited_and_undone() {
}
}
// Numbers far out of range are stored as given and read clamped; the canvas still draws.
+ // Radial Blur's Blur Center is refused outside 0 to 1 instead.
+ let center = |id: &str, k: &str| id == "blur.radial" && matches!(k, "centerX" | "centerY");
for (id, _) in EFFECTS {
let defaults = vectorcraft_render::effects::default_params(id).unwrap();
let junk: serde_json::Map = defaults
.as_object()
.unwrap()
.iter()
- .filter(|(_, v)| v.is_number())
+ .filter(|(k, v)| v.is_number() && !center(id, k))
.enumerate()
.map(|(i, (k, _))| (k.clone(), json!(if i % 2 == 0 { 1e308 } else { -1e308 })))
.collect();
assert!(!junk.is_empty(), "{id}");
s.execute("effect.apply", &json!({"effect": id, "ids": [g], "params": junk})).unwrap();
}
+ assert!(s.execute("effect.apply", &json!({"effect": "blur.radial", "ids": [g], "params": {"centerX": 1e308}})).is_err());
let _ = render(&s);
let n = s.doc().unwrap().doc.node(NodeId(g)).unwrap().clone();
assert_eq!(n.appearance.effects.len(), 3);
diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs
index 6256088842..bb5b73b2f2 100644
--- a/crates/engine/src/tests/variables.rs
+++ b/crates/engine/src/tests/variables.rs
@@ -2284,7 +2284,7 @@ fn a_variable_library_defines_text_variables_and_data_sets() {
assert_eq!(r["variables"], json!(["Name", "Note"]));
assert_eq!((r["deleted"].clone(), r["deletedDataSets"].clone()), (json!([]), json!([])));
assert_eq!(r["names"], json!(["Row 1", "Row 2"]));
- assert_eq!((r["skipped"].clone(), r.get("warning")), (json!([]), None));
+ assert_eq!((r.get("skipped"), r.get("warning")), (None, None));
let listed = s.execute("variable.list", &json!({})).unwrap();
assert_eq!(listed["variables"], json!([{"name": "Name", "kind": "text", "bindings": 0}, {"name": "Note", "kind": "text", "bindings": 0}]));
let sets = s.execute("dataset.list", &json!({})).unwrap();
@@ -2405,13 +2405,14 @@ fn an_import_or_library_load_that_changes_nothing_records_no_undo_step() {
s.execute("variable.loadLibrary", &json!({"xml": other})).unwrap();
assert_eq!(super::history(&s), (undo + 1, 0, true));
- // While the variables are locked, a library without text variables still loads its data sets,
- // and loading it again changes nothing.
+ // While the variables are locked, a library of the variables the document has, with their
+ // kinds, still loads its data sets, and loading it again changes nothing.
let mut s = session();
let t = text(&mut s, "Alice");
- s.execute("variable.lock", &json!({"locked": true})).unwrap();
let xml = library(&[("Shown", "other")], &[("B", &[])]);
s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
+ s.execute("variable.lock", &json!({"locked": true})).unwrap();
+ s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
super::select_with_a_step_to_redo(&mut s, &[t]);
let before = super::history(&s);
s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
@@ -2432,22 +2433,89 @@ fn a_refused_variable_library_deletes_nothing() {
assert_eq!(s.doc().unwrap().doc.variables, before);
}
-/// A library's variables of other kinds are left out with their values, named in `skipped` and
-/// in a warning that gives each kind once with its count; its text variables load.
+/// A library of every kind, in the layout the public grammar gives: visibility (`visibility`),
+/// image (`fileref`) and graph (`graphdata`) variables beside a text variable, a variable without a
+/// `trait` and one whose `trait` VectorCraft doesn't know, with values in the forms
+/// [`a_variable_library_defines_every_kind_with_its_values`] reads.
+fn every_kind_library() -> String {
+ "\n\
+ ]>\n\
+ \
+ \
+ \
+ \
+ \
+ Bravo
true \
+ \n\t\tfile:////Users/me/Art%20Work/logo%23one.png\n\t\t \
+ North South \
+ Q1 10 2.5
\
+ 2024 -4 |
\
+ ignored \
+ FALSE C:\\Art\\logo.png \
+ 7 8 |
\
+ \n \
+ \n"
+ .to_string()
+}
+
+/// Load Variable Library defines a library's variables of every kind, unbound, with their values:
+/// a visibility value from `true` or `false` in any case, an image value from a file's absolute
+/// path or a `file:` URL (escapes decoded, the white space round it left out, the file not read),
+/// and a graph value from a `data` element, as the CSV Graph Data takes (series from its
+/// `propertyRow`, a category from each row's `key="name"` value, blanks where a row has no
+/// number). A variable without a `trait`, or with one VectorCraft doesn't know, is defined of
+/// unknown kind, without values. An element holding only white space gives no value.
#[test]
-fn a_variable_library_leaves_out_variables_that_are_not_text() {
+fn a_variable_library_defines_every_kind_with_its_values() {
let mut s = session();
- let xml = library(
- &[("Shown", "kindB"), ("Name", "textcontent"), ("Photo", "kindC"), ("Other", "kindB")],
- &[("A", &[("Shown", &["true"]), ("Name", &["Bravo"]), ("Photo", &["a.png"])])],
- );
- let r = s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
- assert_eq!(r["variables"], json!(["Name"]));
- assert_eq!(r["skipped"], json!([{"name": "Shown", "trait": "kindB"}, {"name": "Photo", "trait": "kindC"}, {"name": "Other", "trait": "kindB"}]));
- assert_eq!(r["warning"], "variables that aren't text were left out: kindB (2), kindC (1)");
+ let r = s.execute("variable.loadLibrary", &json!({"xml": every_kind_library()})).unwrap();
+ assert_eq!(r["variables"], json!(["Name", "Shown", "Photo", "Chart", "Loose", "Odd"]));
let vars = &s.doc().unwrap().doc.variables;
- assert_eq!(vars.variables.len(), 1);
- assert_eq!(vars.dataset("A").map(|d| d.values.len()), Some(1));
+ let kinds: Vec<(&str, &str)> = vars.variables.iter().map(|v| (v.name.as_str(), v.kind.label())).collect();
+ assert_eq!(kinds, [("Name", "text"), ("Shown", "visibility"), ("Photo", "image"), ("Chart", "graph"), ("Loose", "unknown"), ("Odd", "unknown")]);
+ assert!(vars.bindings.is_empty());
+ use vectorcraft_doc::DataValue::{Graph, Image, Text, Visible};
+ let a = &vars.dataset("A").unwrap().values;
+ assert_eq!(a.get("Name"), Some(&Text("Bravo".into())));
+ assert_eq!(a.get("Shown"), Some(&Visible(true)));
+ assert_eq!(a.get("Photo"), Some(&Image("/Users/me/Art Work/logo#one.png".into())));
+ assert_eq!(a.get("Chart"), Some(&Graph(",North,South\nQ1,10,2.5\n\"2024\",,-4".into())));
+ assert_eq!((a.get("Loose"), a.get("Odd")), (None, None));
+ let b = &vars.dataset("B").unwrap().values;
+ assert_eq!((b.get("Shown"), b.get("Photo")), (Some(&Visible(false)), Some(&Image("C:\\Art\\logo.png".into()))));
+ assert_eq!(b.get("Chart"), Some(&Graph(",,\n7,8".into())));
+ assert!(vars.dataset("C").unwrap().values.is_empty(), "{:?}", vars.dataset("C"));
+}
+
+/// A library's visibility, image and graph variables drive the art they are bound to: a variable
+/// the document already has with the same name and kind stays bound (#4136), so selecting a
+/// library's data set shows or hides the object, swaps the linked image's path and replaces the
+/// graph's data. A variable of the same name and another kind is replaced, and its bindings go.
+#[test]
+fn a_variable_library_keeps_bound_variables_of_every_kind() {
+ let mut s = session();
+ let r = rect(&mut s);
+ let graph = s.execute("graph.create", &json!({"type": "column", "x": 10, "y": 10, "width": 120, "height": 80, "csv": ",a\nX,1"})).unwrap()["id"]
+ .as_u64()
+ .unwrap();
+ for (name, kind, id) in [("Shown", "visibility", r.0), ("Chart", "graph", graph), ("Photo", "text", r.0)] {
+ s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
+ if kind != "text" {
+ s.execute("variable.bind", &json!({"variable": name, "ids": [id]})).unwrap();
+ }
+ }
+ let loaded = s.execute("variable.loadLibrary", &json!({"xml": every_kind_library()})).unwrap();
+ assert_eq!(loaded["deleted"], json!(["Photo"]), "Photo is an image variable in the library");
+ let listed = s.execute("variable.list", &json!({})).unwrap();
+ let bindings: Vec<(String, u64)> =
+ listed["variables"].as_array().unwrap().iter().map(|v| (v["name"].as_str().unwrap().to_string(), v["bindings"].as_u64().unwrap())).collect();
+ assert_eq!(bindings.iter().find(|(n, _)| n == "Shown").map(|b| b.1), Some(1));
+ assert_eq!(bindings.iter().find(|(n, _)| n == "Chart").map(|b| b.1), Some(1));
+ s.execute("dataset.select", &json!({"name": "B"})).unwrap();
+ let doc = &s.doc().unwrap().doc;
+ assert!(!doc.node(r).unwrap().visible, "Shown is false in B");
+ let csv = doc.node(NodeId(graph)).and_then(|n| n.extras().graph.as_ref()).map(|g| g.to_csv());
+ assert_eq!(csv.as_deref(), Some(",,\n7,8\n"), "B's graph data");
}
/// A library that isn't one, or that breaks its grammar or the caps, is refused, and the document
@@ -2477,12 +2545,36 @@ fn malformed_variable_libraries_are_refused() {
"&big;".repeat(8000),
" ".repeat(300_000)
);
+ // A library of one variable `Shown` of the trait given, and a data set holding `value`.
+ let kind_value = |t: &str, value: &str| {
+ format!(
+ " \
+ {value} "
+ )
+ };
+ // A library graph value of more rows or series than a graph holds.
+ let rows_past = format!("{} ", "1
".repeat(10_001));
+ let series_past =
+ format!("Q {}|
", "1 ".repeat(257));
+ // 2,000 rows of 20 values of eight digits are more CSV than a graph value holds.
+ let row = format!("{}
", "12345678 ".repeat(20));
+ let long_graph = format!("{} ", row.repeat(2_000));
let cases = [
("not well-formed XML", "".to_string()),
("no `variableSets` element", " ".to_string()),
("declares no variables", " ".to_string()),
("is declared twice", library(&[("Name", "textcontent"), ("Name", "textcontent")], &[])),
- ("has no `trait`", ok.replace(" trait=\"textcontent\"", "")),
+ ("for `Shown` that isn't `true` or `false`", kind_value("visibility", "maybe ")),
+ ("for `Shown` that isn't `true` or `false`", kind_value("visibility", "true
")),
+ ("for `Shown` that isn't a file's absolute path or `file:` URL", kind_value("fileref", "logo.png ")),
+ ("for `Shown` that isn't a file's absolute path or `file:` URL", kind_value("fileref", "C:logo.png ")),
+ ("for `Shown` that isn't a file's absolute path or `file:` URL", kind_value("fileref", "file:logo.png ")),
+ ("for `Shown` that isn't a graph's `data` element", kind_value("graphdata", "1,2 ")),
+ ("for `Shown` that isn't a graph's `data` element", kind_value("graphdata", " ")),
+ ("for `Shown` that isn't a graph's `data` element", kind_value("graphdata", " ")),
+ ("graph value for `Shown` longer than 262144 bytes", kind_value("graphdata", &long_graph)),
+ ("graph value for `Shown` with more than 10000 rows or 256 series", kind_value("graphdata", &rows_past)),
+ ("graph value for `Shown` with more than 10000 rows or 256 series", kind_value("graphdata", &series_past)),
("missing `varName`", ok.replace("varName=\"Name\"", "varName=\" \"")),
("missing `dataSetName`", ok.replace(" dataSetName=\"A\"", "")),
("data set `A` is declared twice", library(&[("Name", "textcontent")], &[("A", &[]), ("A", &[])])),
@@ -2531,51 +2623,50 @@ fn a_variable_library_expands_entities_of_plain_text() {
assert_eq!(value, Some(vectorcraft_doc::DataValue::Text("x-y \"z\"-x&a;".into())));
}
-/// Save Variable Library writes what Load Variable Library reads back: the text variables in their
-/// order, every data set by name and in order, and each text value as it was, with several lines,
-/// markup characters, quotes, a carriage return and an empty value. Variables of other kinds are
-/// left out with their values, named in `skipped` and in the warning. The library is written while
-/// the variables are locked too, to a file with `path`.
+/// Save Variable Library writes what Load Variable Library reads back: the variables of every kind
+/// in their order, every data set by name and in order, and each value as it was: text with several
+/// lines, markup characters, quotes, a carriage return and an empty value; visibility values;
+/// image paths with spaces, markup characters, `%`, `#` and letters past ASCII, from a Unix root,
+/// a drive and a share; and graph data with series, categories, a numeric category and blanks. A
+/// variable of unknown kind is declared without a `trait` and loads back as one. The library is
+/// written while the variables are locked too, to a file with `path`.
#[test]
-fn a_saved_variable_library_loads_back_the_text_variables_and_data_sets() {
+fn a_saved_variable_library_loads_back_every_variable_and_data_set() {
let mut s = session();
let t = text(&mut s, "Alice");
- for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text"), ("Photo", "image"), ("Badge", "visibility")] {
+ for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text"), ("Photo", "image"), ("Chart", "graph"), ("Badge", "visibility")]
+ {
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
}
s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap();
- s.execute("dataset.new", &json!({"name": "First", "values": {"Name": "Bravo", "Note": "One\nTwo & \r\n'four' \"five\"", "Shown": true}}))
- .unwrap();
- s.execute("dataset.new", &json!({"name": "Say \"hi\" & \tnow", "values": {"Name": "", "Photo": "a.png"}})).unwrap();
+ let chart = ",North,\"S, \"\"q\"\"\"\nQ1,10,2.5\n\"2024\",,-4";
+ let first = json!({"Name": "Bravo", "Note": "One\nTwo & \r\n'four' \"five\"", "Shown": true, "Photo": "/Users/me/Art & 100%/#1 ü.png", "Chart": chart});
+ s.execute("dataset.new", &json!({"name": "First", "values": first})).unwrap();
+ let second = json!({"Name": "", "Photo": "C:\\Art\\logo.png", "Badge": false, "Chart": ",,\n7,8"});
+ s.execute("dataset.new", &json!({"name": "Say \"hi\" & \tnow", "values": second})).unwrap();
+ s.execute("dataset.new", &json!({"name": "Share", "values": {"Photo": "\\\\server\\share\\a.png"}})).unwrap();
s.execute("dataset.new", &json!({"name": "Empty"})).unwrap();
+ // A file can declare a variable of unknown kind, which no command defines.
+ std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
+ .variables
+ .variables
+ .push(vectorcraft_doc::Variable { name: "Loose name".into(), kind: vectorcraft_doc::VariableKind::Unknown });
s.execute("variable.lock", &json!({"locked": true})).unwrap();
let before = s.doc().unwrap().doc.variables.clone();
let saved = s.execute("variable.saveLibrary", &json!({})).unwrap();
- assert_eq!(saved["variables"], json!(["Name", "Note"]));
- assert_eq!(saved["datasets"], json!(3));
- assert_eq!(
- saved["skipped"],
- json!([{"name": "Shown", "kind": "visibility"}, {"name": "Photo", "kind": "image"}, {"name": "Badge", "kind": "visibility"}])
- );
- assert_eq!(saved["warning"], "variables that aren't text were left out: visibility (2), image (1)");
+ assert_eq!(saved["variables"], json!(["Name", "Shown", "Note", "Photo", "Chart", "Badge", "Loose name"]));
+ assert_eq!(saved["datasets"], json!(4));
+ assert_eq!((saved.get("skipped"), saved.get("warning")), (None, None));
assert_eq!(s.doc().unwrap().doc.variables, before, "saving changes nothing");
let mut other = session();
- let loaded = other.execute("variable.loadLibrary", &json!({"xml": saved["xml"]})).unwrap();
- assert_eq!((loaded["skipped"].clone(), loaded.get("warning")), (json!([]), None));
+ other.execute("variable.loadLibrary", &json!({"xml": saved["xml"]})).unwrap();
let vars = &other.doc().unwrap().doc.variables;
- assert_eq!(vars.variables.iter().map(|v| (v.name.as_str(), v.kind.label())).collect::>(), [("Name", "text"), ("Note", "text")]);
- let text_only: Vec = before
- .datasets
- .iter()
- .map(|d| {
- let mut d = d.clone();
- d.values.retain(|k, _| k == "Name" || k == "Note");
- d
- })
- .collect();
- assert_eq!(vars.datasets, text_only);
+ assert_eq!(vars.variables, before.variables);
+ assert_eq!(vars.datasets, before.datasets);
+ // Saving the loaded library again writes the same file.
+ assert_eq!(other.execute("variable.saveLibrary", &json!({})).unwrap()["xml"], saved["xml"]);
let dir = Folder::new("vars-save-library");
let path = dir.file("library.xml");
@@ -2585,19 +2676,78 @@ fn a_saved_variable_library_loads_back_the_text_variables_and_data_sets() {
assert_eq!(std::fs::read_to_string(&path).unwrap(), saved["xml"].as_str().unwrap());
let mut from_file = session();
from_file.execute("variable.loadLibrary", &json!({"path": path})).unwrap();
- assert_eq!(from_file.doc().unwrap().doc.variables.datasets, text_only);
+ assert_eq!(from_file.doc().unwrap().doc.variables.datasets, before.datasets);
+}
+
+/// Graph data whose categories are all blank keeps them through a save and a load, and so does
+/// graph data of series names without rows; graph data with neither is refused. An image value
+/// written as a `file:/…` URL without a host loads as its path, graph data with more series than a
+/// graph holds is refused, and wide graph data is checked against the size cap as it is written.
+#[test]
+fn saved_graph_values_and_file_urls_load_back_at_their_edges() {
+ let mut s = session();
+ s.execute("variable.define", &json!({"name": "Chart", "kind": "graph"})).unwrap();
+ s.execute("dataset.new", &json!({"name": "A", "values": {"Chart": ",S\n\"\",1\n\"\",2"}})).unwrap();
+ let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_string();
+ assert!(xml.contains("1
"), "{xml}");
+ let mut other = session();
+ other.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
+ assert_eq!(other.doc().unwrap().doc.variables.datasets, s.doc().unwrap().doc.variables.datasets);
+ // Series names without rows load back, and graph data with neither is refused.
+ s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": ",North,South"}})).unwrap();
+ let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].clone();
+ let mut other = session();
+ other.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
+ assert_eq!(other.doc().unwrap().doc.variables.datasets, s.doc().unwrap().doc.variables.datasets);
+ s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": ","}})).unwrap();
+ let e = s.execute("variable.saveLibrary", &json!({})).unwrap_err().to_string();
+ assert!(e.contains("graph value for `Chart` without rows or series"), "{e}");
+
+ let url = "\
+ file:/tmp/logo%20one.png \
+ file:/C:/Art/logo.png ";
+ let mut s = session();
+ s.execute("variable.loadLibrary", &json!({"xml": url})).unwrap();
+ let image = |set: &str| s.doc().unwrap().doc.variables.dataset(set).and_then(|d| d.values.get("Photo")).cloned();
+ assert_eq!(image("A"), Some(vectorcraft_doc::DataValue::Image("/tmp/logo one.png".into())));
+ assert_eq!(image("B"), Some(vectorcraft_doc::DataValue::Image("C:/Art/logo.png".into())));
+
+ // More series than a graph holds are refused.
+ let mut s = session();
+ s.execute("variable.define", &json!({"name": "Chart", "kind": "graph"})).unwrap();
+ let wide = (0..257).map(|i| i.to_string()).collect::>().join(",");
+ s.execute("dataset.new", &json!({"name": "A", "values": {"Chart": wide}})).unwrap();
+ let e = s.execute("variable.saveLibrary", &json!({})).unwrap_err().to_string();
+ assert!(e.contains("graph value for `Chart` with more than 10000 rows or 256 series"), "{e}");
+ // One row of 256 values and 1,000 rows of one: every row is written 256 values wide.
+ let mut csv = (0..256).map(|i| i.to_string()).collect::>().join(",");
+ for i in 0..1_000 {
+ csv += &format!("\n{i}");
+ }
+ s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": csv.clone()}})).unwrap();
+ let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_string();
+ assert_eq!(xml.matches("").count(), 1_001);
+ assert!(xml.contains(""));
+ // Rows that make the library larger than 8 MiB are refused as each is written.
+ for i in 1_000..9_000 {
+ csv += &format!("\n{i}");
+ }
+ s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": csv}})).unwrap();
+ let e = s.execute("variable.saveLibrary", &json!({})).unwrap_err().to_string();
+ assert!(e.contains("larger than 8388608 bytes"), "{e}");
}
/// The library is the XML of the public grammar: a document type declaration with the namespace
-/// entities, `variableSets` › `variableSet` › `variables` with a `textcontent` variable per text
-/// variable, and `sampleDataSets` with a `sampleDataSet` per data set, holding an element per text
-/// variable it has a value for, with a `p` element per line. Markup characters, a carriage return,
-/// and a tab or quote in a data set name are escaped. A document with text variables and no data
-/// sets writes an empty `sampleDataSets`.
+/// entities, `variableSets` › `variableSet` › `variables` with a variable per variable, its `trait`
+/// and `category` those of its kind, and `sampleDataSets` with a `sampleDataSet` per data set,
+/// holding an element per variable it has a value for: a `p` element per line of a text value,
+/// `true` or `false`, a `file:` URL for an image's path from a Unix root, and a `data` element for
+/// graph data. Markup characters, a carriage return, and a tab or quote in a data set name are
+/// escaped. A document with variables and no data sets writes an empty `sampleDataSets`.
#[test]
fn a_saved_variable_library_has_the_library_layout() {
let mut s = session();
- for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text")] {
+ for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text"), ("Photo", "image"), ("Chart", "graph")] {
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
}
let head = "\n\
@@ -2605,13 +2755,17 @@ fn a_saved_variable_library_has_the_library_layout() {
\t\n\
\t\n\
\t\n\
+ \t\n\
]>\n\
\n\
\n\
\t\n\
\t\t\n\
\t\t\t \n\
+ \t\t\t \n\
\t\t\t \n\
+ \t\t\t \n\
+ \t\t\t \n\
\t\t \n\
\t\t\n";
let tail = "\t\t \n\t \n \n \n";
@@ -2619,7 +2773,8 @@ fn a_saved_variable_library_has_the_library_layout() {
assert_eq!(empty["xml"].as_str().unwrap(), format!("{head}{tail}"));
assert_eq!(empty["datasets"], json!(0));
- s.execute("dataset.new", &json!({"name": "A &\t\"B\"", "values": {"Name": "x\r\ny < z", "Shown": false}})).unwrap();
+ let values = json!({"Name": "x\r\ny < z", "Shown": false, "Photo": "/art/a b.png", "Chart": ",S\nQ1,1\n2,"});
+ s.execute("dataset.new", &json!({"name": "A &\t\"B\"", "values": values})).unwrap();
s.execute("dataset.new", &json!({"name": "C", "values": {"Note": ""}})).unwrap();
let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_string();
let sets = "\t\t\t\n\
@@ -2627,6 +2782,17 @@ fn a_saved_variable_library_has_the_library_layout() {
\t\t\t\t\tx
\n\
\t\t\t\t\ty < z
\n\
\t\t\t\t\n\
+ \t\t\t\tfalse \n\
+ \t\t\t\tfile:////art/a%20b.png \n\
+ \t\t\t\t\n\
+ \t\t\t\t\t\n\
+ \t\t\t\t\t\tS \n\
+ \t\t\t\t\t\t\n\
+ \t\t\t\t\t\t\tQ1 1
\n\
+ \t\t\t\t\t\t\t2
\n\
+ \t\t\t\t\t\t \n\
+ \t\t\t\t\t \n\
+ \t\t\t\t \n\
\t\t\t \n\
\t\t\t\n\
\t\t\t\t\n\
@@ -2636,10 +2802,11 @@ fn a_saved_variable_library_has_the_library_layout() {
assert_eq!(xml, format!("{head}{sets}{tail}"));
}
-/// Save Variable Library refuses a document without variables or without text variables, a text
-/// variable whose name can't name an element, a data set name or text value with a character XML
-/// can't hold, a name that Load Variable Library would read differently or refuse, and a library
-/// past the caps that Load Variable Library reads. A refused save writes no file.
+/// Save Variable Library refuses a document without variables, a variable whose name can't name an
+/// element (but for a variable of unknown kind), a data set name, text value or graph label with a
+/// character XML can't hold, an image value that isn't a file's absolute path, a name that Load
+/// Variable Library would read differently or refuse, and a library past the caps that Load
+/// Variable Library reads. A refused save writes no file.
#[test]
fn save_variable_library_refuses_what_a_library_cant_hold() {
let dir = Folder::new("vars-save-refused");
@@ -2652,14 +2819,41 @@ fn save_variable_library_refuses_what_a_library_cant_hold() {
let mut s = session();
refused(&mut s, "define a variable first");
+ // A library without text variables is saved.
s.execute("variable.define", &json!({"name": "Shown", "kind": "visibility"})).unwrap();
- refused(&mut s, "holds text variables, and the document has none");
+ assert_eq!(s.execute("variable.saveLibrary", &json!({})).unwrap()["variables"], json!(["Shown"]));
- for name in ["First Name", "1st", "a:b", "x/y", "-dash"] {
+ for (name, kind) in [("First Name", "text"), ("1st", "visibility"), ("a:b", "image"), ("x/y", "graph"), ("-dash", "text")] {
let mut s = session();
- s.execute("variable.define", &json!({"name": name, "kind": "text"})).unwrap();
+ s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
refused(&mut s, &format!("variable `{name}` can't be saved in a variable library"));
}
+ // No element is named after a variable of unknown kind, so its name can be any name.
+ let mut s = session();
+ std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
+ .variables
+ .variables
+ .push(vectorcraft_doc::Variable { name: "First \"Name\" & ".into(), kind: vectorcraft_doc::VariableKind::Unknown });
+ let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].clone();
+ let mut other = session();
+ other.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
+ assert_eq!(other.doc().unwrap().doc.variables.variables, s.doc().unwrap().doc.variables.variables);
+
+ // An image value that isn't a file's absolute path, which Load Variable Library refuses.
+ for path in ["a.png", "C:a.png", "C:\\a.png ", "/"] {
+ let mut s = session();
+ s.execute("variable.define", &json!({"name": "Photo", "kind": "image"})).unwrap();
+ std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.datasets.push(vectorcraft_doc::DataSet {
+ name: "A".into(),
+ values: [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into(),
+ });
+ refused(&mut s, "data set `A` holds an image value for `Photo` that isn't a file's absolute path");
+ }
+ // A graph label with a character XML can't hold.
+ let mut s = session();
+ s.execute("variable.define", &json!({"name": "Chart", "kind": "graph"})).unwrap();
+ s.execute("dataset.new", &json!({"name": "A", "values": {"Chart": ",S\u{1}\nQ1,1"}})).unwrap();
+ refused(&mut s, "data set `A` holds a control character");
for name in ["Ünïcode", "_x", "a.b-c_d", "名前"] {
let mut s = session();
s.execute("variable.define", &json!({"name": name, "kind": "text"})).unwrap();
@@ -2757,10 +2951,10 @@ fn a_saved_variable_library_near_the_size_cap_loads_back() {
/// While the variables are locked, a library that would delete or define a variable is refused, as
/// Delete Variable and New Variable are, and the document keeps its variables and data sets. That
-/// covers a library without text variables loaded into a document with variables, and one that
-/// adds a text variable to the document's. A library of the document's own text variables, and
-/// one without text variables loaded into a document without variables, delete and define none:
-/// they load, replacing the data sets.
+/// covers a library of other variables loaded into a document with variables, one that adds a
+/// variable to the document's, one that declares a document variable's name with another kind, and
+/// any library loaded into a document without variables. A library of the document's own variables
+/// with their kinds deletes and defines none: it loads, replacing the data sets.
#[test]
fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() {
let mut s = session();
@@ -2768,7 +2962,7 @@ fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() {
s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Old"}})).unwrap();
s.execute("variable.lock", &json!({"locked": true})).unwrap();
let before = s.doc().unwrap().doc.variables.clone();
- for vars in [&[("Shown", "other")][..], &[("Name", "textcontent"), ("Note", "textcontent")][..]] {
+ for vars in [&[("Shown", "other")][..], &[("Name", "textcontent"), ("Note", "textcontent")][..], &[("Name", "visibility")][..]] {
let e = s.execute("variable.loadLibrary", &json!({"xml": library(vars, &[("B", &[])])})).unwrap_err();
assert!(matches!(&e, EngineError::Disabled(cmd, why) if cmd == "variable.loadLibrary" && why == "variables are locked"), "{e}");
assert_eq!(s.doc().unwrap().doc.variables, before);
@@ -2780,13 +2974,13 @@ fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() {
let mut s = session();
s.execute("dataset.new", &json!({"name": "A"})).unwrap();
s.execute("variable.lock", &json!({"locked": true})).unwrap();
- let e = s.execute("variable.loadLibrary", &json!({"xml": library(&[("Name", "textcontent")], &[])})).unwrap_err();
- assert!(matches!(&e, EngineError::Disabled(_, why) if why == "variables are locked"), "{e}");
- let r = s.execute("variable.loadLibrary", &json!({"xml": library(&[("Shown", "other")], &[("B", &[])])})).unwrap();
- assert_eq!((r["deletedDataSets"].clone(), r["names"].clone()), (json!(["A"]), json!(["B"])));
+ for vars in [&[("Name", "textcontent")][..], &[("Shown", "other")][..]] {
+ let e = s.execute("variable.loadLibrary", &json!({"xml": library(vars, &[("B", &[])])})).unwrap_err();
+ assert!(matches!(&e, EngineError::Disabled(_, why) if why == "variables are locked"), "{e}");
+ }
let vars = &s.doc().unwrap().doc.variables;
assert!(vars.variables.is_empty() && vars.locked);
- assert_eq!(vars.datasets.iter().map(|d| d.name.as_str()).collect::>(), ["B"]);
+ assert_eq!(vars.datasets.iter().map(|d| d.name.as_str()).collect::>(), ["A"]);
}
/// A graph variable's data set applies its CSV as `graph.setData` does: a right-axis series the row's data no longer
@@ -3109,6 +3303,10 @@ fn an_svg_without_readable_variable_data_opens_its_art() {
let head = "";
let art = " ";
let untraited = format!("{head} {art}");
+ let relative = format!(
+ "{head} \
+ kept
a.png {art}"
+ );
let refs = "&ns_big;".repeat(40_000);
let big = "x".repeat(250);
let growing = format!(
@@ -3164,11 +3362,23 @@ fn an_svg_without_readable_variable_data_opens_its_art() {
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(o.doc().unwrap().doc.variables.variables.len(), 1);
- for (svg, why) in [(untraited, "variable `A` has no `trait`"), (growing, "entities expand to more than")] {
- let (o, warnings) = svg_opened(&svg, "broken.svg");
- assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("variable data wasn't read") && w.contains(why))), "{warnings:?}");
- let d = &o.doc().unwrap().doc;
- assert!(d.variables.variables.is_empty());
- assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens");
- }
+ // A variable without a `trait` is of unknown kind: the SVG leaves it out like the other kinds
+ // that aren't text.
+ let (o, warnings) = svg_opened(&untraited, "untraited.svg");
+ assert!(warnings.contains(&json!("variables that aren't text were left out: unknown (1)")), "{warnings:?}");
+ assert!(o.doc().unwrap().doc.variables.variables.is_empty());
+ // The values of the other kinds aren't read, so one that Load Variable Library would refuse
+ // leaves the text variables and their values as they open.
+ let (o, warnings) = svg_opened(&relative, "relative.svg");
+ assert!(warnings.contains(&json!("variables that aren't text were left out: fileref (1)")), "{warnings:?}");
+ let vars = &o.doc().unwrap().doc.variables;
+ assert_eq!(vars.variables.iter().map(|v| v.name.as_str()).collect::>(), ["T"]);
+ assert_eq!(vars.dataset("D").map(|d| d.values.clone()), Some([("T".to_string(), vectorcraft_doc::DataValue::Text("kept".into()))].into()));
+
+ let (o, warnings) = svg_opened(&growing, "broken.svg");
+ let why = "entities expand to more than";
+ assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("variable data wasn't read") && w.contains(why))), "{warnings:?}");
+ let d = &o.doc().unwrap().doc;
+ assert!(d.variables.variables.is_empty());
+ assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens");
}
diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs
index d33ad587fe..f6bc163e65 100644
--- a/crates/engine/src/tooling.rs
+++ b/crates/engine/src/tooling.rs
@@ -651,7 +651,7 @@ impl Session {
match ev.kind {
PointerKind::Down | PointerKind::Drag => self.pointer_held = true,
PointerKind::Up | PointerKind::Move => self.pointer_held = false,
- PointerKind::DoubleClick => {}
+ PointerKind::DoubleClick | PointerKind::TripleClick => {}
}
match ev.kind {
PointerKind::Down => {
diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs
index a768785abf..c2235eca77 100644
--- a/crates/engine/tests/import_fuzz.rs
+++ b/crates/engine/tests/import_fuzz.rs
@@ -664,6 +664,29 @@ proptest! {
survive(&svg, || vectorcraft_svg::import(&svg).ok())?;
}
+ /// Style sheets of descendant, child, sibling and `:not()` selectors over nested groups and the
+ /// `` copies of a rectangle inside them, in an SVG and in an SVG image it shows: the import
+ /// measures their matching before its own cascade and the SVG reader run.
+ #[test]
+ fn svg_hostile_selectors_over_copies_never_panic(
+ sheet in r#"([a-z.#:()>+* ]{1,24}\{fill:red\} ?){1,6}"#,
+ depth in 1usize..12,
+ copies in 0usize..4,
+ ) {
+ let groups = format!("{}{}", "".repeat(depth), " ".repeat(depth));
+ let inner = format!(
+ "{groups}{} ",
+ "".repeat(copies)
+ );
+ let image = format!(
+ " ",
+ vectorcraft_svg::base64_encode(inner.as_bytes())
+ );
+ for svg in [inner, image] {
+ survive(&svg, || vectorcraft_svg::import(&svg).ok())?;
+ }
+ }
+
/// Clip paths made of text, of `` elements showing text, and of both with shapes, each with
/// hostile attributes, clipping art that may clip by them in turn.
#[test]
diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs
index d160248a2d..8b081782d3 100644
--- a/crates/eps/src/import/ai/tests.rs
+++ b/crates/eps/src/import/ai/tests.rs
@@ -10339,13 +10339,35 @@ fn a_brushed_path_with_samples_of_the_pen_keeps_its_drawn_look() {
let a = art(&read_ok(&format!("{def}{style}{}", layer(&first))).doc);
assert_eq!(a.len(), 1, "{a:#?}");
assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the path, brushed: {a:#?}");
- // A brush whose modes are Fixed and Random, one whose pen modes vary by 0, and an Art brush
- // don't follow the pen: the path comes in brushed.
+ // Each setting that follows the pen keeps the drawn look on its own, with the other two fixed:
+ // the diameter with the pressure or the tilt, the roundness with the bearing and the angle with
+ // the barrel's rotation.
+ let one_setting = [
+ ("the diameter with the pressure", "1 4 8 40 40 30 30 2 0 0 0", [(6.0, 2.0), (40.0, 0.0), (30.0, 0.0)], [2, 0, 0]),
+ ("the diameter with the tilt", "1 4 8 40 40 30 30 4 0 0 0", [(6.0, 2.0), (40.0, 0.0), (30.0, 0.0)], [4, 0, 0]),
+ ("the roundness with the bearing", "1 6 6 30 50 30 30 0 5 0 0", [(6.0, 0.0), (40.0, 10.0), (30.0, 0.0)], [0, 5, 0]),
+ ("the angle with the rotation", "1 6 6 40 40 -150 210 0 0 6 0", [(6.0, 0.0), (40.0, 0.0), (30.0, 180.0)], [0, 0, 6]),
+ ];
+ for (why, params, settings, codes) in one_setting {
+ let def = plugin_object(CALLIGRAPHIC, "Six D", params);
+ let style = brushed_style("Six D", 0.5, settings, codes, 0);
+ let r = read_ok(&format!("{def}{style}{}", layer(&path)));
+ let a = art(&r.doc);
+ assert_eq!(a.len(), 1, "{why}: {a:#?}");
+ assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{why}: the drawn look, {a:#?}");
+ assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{why}: {:?}", r.warnings);
+ }
+ // A brush whose modes are Fixed and Random, one whose pen modes vary by 0, one whose only
+ // varying setting is Random beside a pen setting that varies by 0, and an Art brush don't
+ // follow the pen: the path comes in brushed.
let fixed_def = plugin_object(CALLIGRAPHIC, "Six D", &SIX_D.replace(" 2 5 6 0", " 0 1 0 0"));
let fixed = brushed_style("Six D", 0.5, SIX_D_SETTINGS, [0, 1, 0], 0);
let even_def = plugin_object(CALLIGRAPHIC, "Six D", "1 6 6 40 40 30 30 2 5 6 0");
let even = brushed_style("Six D", 0.5, [(6.0, 0.0), (40.0, 0.0), (30.0, 0.0)], [2, 5, 6], 0);
- for (why, def, style) in [("Fixed and Random", fixed_def, fixed), ("no variation", even_def, even)] {
+ let random_def = plugin_object(CALLIGRAPHIC, "Six D", "1 4 8 40 40 30 30 1 2 0 0");
+ let random = brushed_style("Six D", 0.5, [(6.0, 2.0), (40.0, 0.0), (30.0, 0.0)], [1, 2, 0], 0);
+ let cases = [("Fixed and Random", fixed_def, fixed), ("no variation", even_def, even), ("Random beside an even pen setting", random_def, random)];
+ for (why, def, style) in cases {
let r = read_ok(&format!("{def}{style}{}", layer(&path)));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{why}: {a:#?}");
diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs
index 69c7b5ba0e..8bd8afc2e5 100644
--- a/crates/mcp/src/headless.rs
+++ b/crates/mcp/src/headless.rs
@@ -81,6 +81,7 @@ pub(crate) fn pointer_kind(k: &str) -> Option {
"up" => PointerKind::Up,
"move" => PointerKind::Move,
"doubleclick" | "dblclick" => PointerKind::DoubleClick,
+ "tripleclick" => PointerKind::TripleClick,
_ => return None,
})
}
@@ -238,7 +239,7 @@ impl Headless {
.map(|(e, backquote)| {
let mods = packet_mods(e)?.unwrap_or(base);
let kind = s(e, "kind").unwrap_or("");
- let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?;
+ let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick|tripleclick)"))?;
PointerEvent::json_check(e)?;
if s(e, "space") == Some("screen") {
return Err("screen-space pointer events need the desktop app; use document coordinates".to_string());
diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs
index 1502f11662..b5fd1135aa 100644
--- a/crates/mcp/src/tests.rs
+++ b/crates/mcp/src/tests.rs
@@ -16,6 +16,7 @@ mod gradient;
mod limits;
mod links;
mod liquify;
+mod livepaint;
mod pen;
mod persp;
mod place;
diff --git a/crates/mcp/src/tests/livepaint.rs b/crates/mcp/src/tests/livepaint.rs
new file mode 100644
index 0000000000..0165823e6f
--- /dev/null
+++ b/crates/mcp/src/tests/livepaint.rs
@@ -0,0 +1,73 @@
+//! The Live Paint Bucket through MCP: `pointer_gesture` sends a triple-click as `tripleclick`.
+
+use serde_json::{Value, json};
+
+use crate::{Backend, Headless, call_tool};
+
+fn ok(h: &mut Headless, name: &str, args: Value) -> Value {
+ let r = call_tool(h, name, &args);
+ assert!(!r.is_error, "{name} {args}: {r:?}");
+ serde_json::from_str(r.content[0]["text"].as_str().unwrap()).unwrap_or(Value::Null)
+}
+
+fn run(h: &mut Headless, command: &str, params: Value) -> Value {
+ ok(h, "run_command", json!({"command": command, "params": params}))
+}
+
+/// The fill of each face of Live Paint group `g`, left to right.
+fn fills(h: &mut Headless, g: &Value) -> Vec {
+ let info = run(h, "livePaint.info", json!({"group": g}));
+ let mut faces = info["faces"].as_array().unwrap().clone();
+ faces.sort_by(|a, b| a["bounds"][0].as_f64().unwrap().total_cmp(&b["bounds"][0].as_f64().unwrap()));
+ faces.iter().map(|f| f["fill"].clone()).collect()
+}
+
+#[test]
+fn a_triple_click_fills_every_face_of_the_same_fill() {
+ let mut h = Headless::new();
+ h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap();
+ let a = run(&mut h, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
+ let b = run(&mut h, "shape.rectangle", json!({"x": 100, "y": 0, "width": 50, "height": 50}))["id"].clone();
+ let g = run(&mut h, "livePaint.make", json!({"ids": [a, b]}))["id"].clone();
+ for x in [25, 125] {
+ run(&mut h, "livePaint.fill", json!({"group": g, "point": [x, 25], "color": "#ff0000"}));
+ }
+ let red = fills(&mut h, &g);
+ assert_eq!(red[0], red[1]);
+ // With nothing selected, the current fill changes and the group keeps its faces' fills.
+ run(&mut h, "select.none", json!({}));
+ run(&mut h, "paint.setFill", json!({"color": "#00ff00"}));
+ assert_eq!(fills(&mut h, &g), red);
+ let ev = |kind: &str| json!({"kind": kind, "x": 25, "y": 25});
+ let clicks = [ev("down"), ev("up"), ev("down"), ev("up"), ev("doubleclick"), ev("down"), ev("up")];
+ ok(&mut h, "pointer_gesture", json!({"tool": "livePaintBucket", "events": clicks}));
+ let after_two = fills(&mut h, &g);
+ assert_eq!(after_two[1], red[1], "the face apart is left by the clicks and the double-click");
+ assert_ne!(after_two[0], red[0]);
+ ok(&mut h, "pointer_gesture", json!({"events": [ev("tripleclick")]}));
+ assert_eq!(fills(&mut h, &g), [after_two[0].clone(), after_two[0].clone()], "both faces were red");
+}
+
+/// With Space held (`mods.space`), the Live Paint Bucket's clicks, double-click and triple-click
+/// paint nothing.
+#[test]
+fn clicks_with_space_held_paint_nothing() {
+ let mut h = Headless::new();
+ h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap();
+ let a = run(&mut h, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
+ let b = run(&mut h, "shape.rectangle", json!({"x": 100, "y": 0, "width": 50, "height": 50}))["id"].clone();
+ let g = run(&mut h, "livePaint.make", json!({"ids": [a, b]}))["id"].clone();
+ for x in [25, 125] {
+ run(&mut h, "livePaint.fill", json!({"group": g, "point": [x, 25], "color": "#ff0000"}));
+ }
+ run(&mut h, "select.none", json!({}));
+ run(&mut h, "paint.setFill", json!({"color": "#00ff00"}));
+ let red = fills(&mut h, &g);
+ let ev = |kind: &str| json!({"kind": kind, "x": 25, "y": 25});
+ let clicks = [ev("down"), ev("up"), ev("down"), ev("up"), ev("doubleclick"), ev("down"), ev("up"), ev("tripleclick")];
+ ok(&mut h, "pointer_gesture", json!({"tool": "livePaintBucket", "mods": {"space": true}, "events": clicks}));
+ assert_eq!(fills(&mut h, &g), red);
+ // Without Space, the same clicks paint.
+ ok(&mut h, "pointer_gesture", json!({"events": [ev("down"), ev("up")]}));
+ assert_ne!(fills(&mut h, &g)[0], red[0]);
+}
diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs
index e7ba79df7c..ee3bd56095 100644
--- a/crates/mcp/src/tools/definitions.rs
+++ b/crates/mcp/src/tools/definitions.rs
@@ -205,7 +205,7 @@ pub fn tool_definitions() -> Vec {
"type": "array",
"minItems": 1,
"items": obj(json!({
- "kind": {"type": "string", "enum": ["down", "drag", "up", "move", "doubleclick"]},
+ "kind": {"type": "string", "enum": ["down", "drag", "up", "move", "doubleclick", "tripleclick"]},
"x": num("Document x (pt)"),
"y": num("Document y (pt)"),
"mods": mods_schema(),
diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs
index 8d410af183..8b9db99564 100644
--- a/crates/mcp/src/tools/dispatch.rs
+++ b/crates/mcp/src/tools/dispatch.rs
@@ -145,7 +145,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result {
pub(super) cache: Option,
/// Document-space bounds of the painted content.
pub(super) reach: Rect,
+ /// `reach` before the effects of an earlier part of a split stack spread it: the bounds Radial
+ /// Blur's Blur Center is placed in, so the center stays put wherever the stack splits.
+ pub(super) object: Rect,
/// Its silhouette: Feather and Inner Glow clip to it (without one, Feather only blurs and
/// Inner Glow is skipped).
pub(super) outline: Option<(&'a BezPath, FillRule)>,
diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs
index cdf817f1e4..f4a441f3cb 100644
--- a/crates/render/src/fx/pixels.rs
+++ b/crates/render/src/fx/pixels.rs
@@ -241,7 +241,10 @@ impl Renderer {
outline: feather_outline(&chain, content, content.reach.origin()),
});
let (center, extent) = (content.reach.center(), 0.5 * content.reach.width().hypot(content.reach.height()));
- let space = effects::PixelSpace { to_doc, px, center, channels, line, extent };
+ // The Blur Center lies in the object's bounds; a split stack's later part spreads `reach`
+ // evenly, so the centre stays the same.
+ let size = content.object.size().to_vec2();
+ let space = effects::PixelSpace { to_doc, px, center, size, channels, line, extent };
let (wz, hz) = (wu as usize, hu as usize);
// What the content covers after the effects run so far: Rasterize makes its image over it.
let mut bounds = content.bounds.unwrap_or(content.reach);
@@ -708,6 +711,7 @@ impl Renderer {
owner: None,
cache: Some((j + 1) << 8),
reach: ib.inflate(outset, outset),
+ object: ib.inflate(outset, outset),
outline: Some((&outline, orule)),
bounds,
kept: None,
diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs
index 65a886dc8c..d1a8429fd6 100644
--- a/crates/render/src/fx/renderer.rs
+++ b/crates/render/src/fx/renderer.rs
@@ -389,7 +389,7 @@ impl Renderer {
let bounds = rasterize_bounds(f.symbols, n, &rfx);
// Under Rasterize the content reaches as far as its fills' and strokes' raster effects paint.
let reach = bounds.map_or(reach, |b| reach.union(b));
- let content = Content { node: n, owner: None, cache: Some(0), reach, outline: Some((g, rule)), bounds, kept: None };
+ let content = Content { node: n, owner: None, cache: Some(0), reach, object: reach, outline: Some((g, rule)), bounds, kept: None };
let mut items = items;
self.raster_fx(ctx, f, &content, &rfx, &mut |r, c, fr| r.paint_items(c, fr, paints, g, rule, &gctx, items.as_deref_mut()));
ctx.set_transform(Affine::IDENTITY);
@@ -447,7 +447,16 @@ impl Renderer {
None => rasterize_bounds(f.symbols, a, &rfx),
};
let reach = bounds.map_or(reach, |b| reach.union(b));
- let content = Content { node: a, owner: Some(a), cache, reach, outline: region.as_deref().map(|r| (&r.0, r.1)), bounds, kept: None };
+ let content = Content {
+ node: a,
+ owner: Some(a),
+ cache,
+ reach,
+ object: reach,
+ outline: region.as_deref().map(|r| (&r.0, r.1)),
+ bounds,
+ kept: None,
+ };
self.raster_fx(ctx, f, &content, &rfx, &mut |r, c, fr| r.draw_fx_art(c, fr, a, &art));
ctx.set_transform(Affine::IDENTITY);
}
@@ -771,6 +780,7 @@ impl Renderer {
owner: content.owner,
cache: None,
reach: content.reach,
+ object: content.object,
outline: content.outline,
bounds: content.bounds,
kept: kept.as_ref(),
@@ -783,6 +793,7 @@ impl Renderer {
owner: content.owner,
cache: content.cache.filter(|_| !over),
reach,
+ object: content.object,
outline,
bounds: spread,
kept: content.kept.filter(|_| split == at),
diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs
index c17f689922..5267acd279 100644
--- a/crates/svg/src/import.rs
+++ b/crates/svg/src/import.rs
@@ -110,6 +110,8 @@ pub(crate) fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool)
return Err(too_deep());
}
let xml = parse(svg)?;
+ // Before the style cascade of `depth::height`, as `import` measures it.
+ budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?;
if depth::height(&xml, depth::MAX_ELEMENT_DEPTH).is_none() {
return Err(too_deep());
}
@@ -139,7 +141,7 @@ pub(crate) fn import_finding(
let xml = parse(svg)?;
// Before the style cascade of `depth::height` and the prepass, which keeps the declarations of
// each element it reads; measured again below on the text usvg reads when that differs.
- let styles = budget::check(&xml, budget::MAX_COPIED_STYLES, depth::MAX_ELEMENT_DEPTH)?;
+ let spent = budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?;
let Some(height) = depth::height(&xml, depth::MAX_ELEMENT_DEPTH) else {
return Err(too_deep());
};
@@ -160,13 +162,13 @@ pub(crate) fn import_finding(
let text_xml = found.text_source.as_deref().map(parse).transpose()?;
let (src, slots) = text::prepare(svg, &xml, text_xml.as_ref(), units.dpi, &mut warnings);
// Before usvg copies what ``s show and the style values of each copy: the text usvg reads.
- let styles = match &src {
- Cow::Borrowed(_) if !rewritten => styles,
- Cow::Borrowed(_) => budget::check(&xml, budget::MAX_COPIED_STYLES, usize::MAX)?,
- Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::MAX_COPIED_STYLES, usize::MAX)?,
+ let spent = match &src {
+ Cow::Borrowed(_) if !rewritten => spent,
+ Cow::Borrowed(_) => budget::check(&xml, budget::Cost::LIMITS, usize::MAX)?,
+ Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::LIMITS, usize::MAX)?,
};
let files = found.files;
- files.copied_styles(styles);
+ files.spent_by_svg(spent);
let tree = {
let opt = usvg::Options {
dpi: units.dpi as f32,
diff --git a/crates/svg/src/import/budget.rs b/crates/svg/src/import/budget.rs
index ec4de17eca..2520a8932a 100644
--- a/crates/svg/src/import/budget.rs
+++ b/crates/svg/src/import/budget.rs
@@ -20,13 +20,23 @@
//! would leave it out.
//!
//! The style sheets' rules are matched against each element once, as usvg matches them against
-//! each copy.
+//! each copy. usvg tests a selector against an element without keeping what it found, so a
+//! selector whose leftmost part matches nothing can test every set of ancestors in turn: the tests
+//! usvg makes for each copy are counted, and an SVG past [`MAX_SELECTOR_TESTS`] of them is refused.
+//! A look at an attribute counts one test for every 16 attributes of the element it scans, and one
+//! for every 16 bytes of the value it compares. Matching stops once the tests pass what is left of
+//! the limit.
+//!
+//! The import's own style cascade (`css::Styles`) keeps the declarations of the rules that match
+//! each element, once per element, and reads selectors usvg drops (`:not()`). What it keeps and the
+//! tests it makes count toward the same limits, measured before it runs.
+use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use usvg::roxmltree;
-use super::{MAX_NODES, SVG_NS, XNode};
+use super::{MAX_NODES, SVG_NS, XNode, css};
use crate::{MAX_ELEMENT_DEPTH, SvgError};
/// Most elements usvg may make of an SVG: [`MAX_NODES`], and below the 1,000,000 elements past
@@ -37,6 +47,10 @@ pub(crate) const MAX_SVG_ELEMENTS: usize = if MAX_NODES < 999_999 { MAX_NODES }
/// shows, all together: VectorCraft's own limit.
pub(crate) const MAX_COPIED_STYLES: u64 = 64 << 20;
+/// Most tests of a style sheet selector's parts against elements an SVG and the SVG images it
+/// shows may take, all together: VectorCraft's own limit.
+pub(crate) const MAX_SELECTOR_TESTS: u64 = 50_000_000;
+
/// What usvg keeps for each value it copies besides its bytes (the count and length of a shared
/// string).
const COPY: u64 = 16;
@@ -116,28 +130,59 @@ fn svg_name<'a>(n: XNode<'a, '_>) -> Option<&'a str> {
(n.is_element() && matches!(name.namespace(), None | Some(SVG_NS)) && ELEMENTS.contains(&name.name())).then(|| name.name())
}
-/// An element as the style sheets' selectors see it, as usvg matches them.
-struct Element<'a, 'i>(XNode<'a, 'i>);
+#[cfg(test)]
+thread_local! {
+ /// The selector tests the last measurement on this thread made as usvg matches the style
+ /// sheets, as far as it got.
+ static USVG_TESTS: Cell = const { Cell::new(0) };
+}
-impl simplecss::Element for Element<'_, '_> {
+/// An element as the style sheets' selectors see it, as usvg matches them. Each look at it counts
+/// as tests in `tests`; past `most` it has no parent or sibling and matches nothing, so the
+/// matching ends.
+struct Element<'a, 'i, 't> {
+ node: XNode<'a, 'i>,
+ tests: &'t Cell,
+ most: u64,
+}
+
+impl<'a, 'i, 't> Element<'a, 'i, 't> {
+ /// Counts `n` tests: false past `most`.
+ fn test(&self, n: u64) -> bool {
+ let tests = self.tests.get().saturating_add(n);
+ self.tests.set(tests);
+ #[cfg(test)]
+ USVG_TESTS.set(tests);
+ tests <= self.most
+ }
+
+ fn of(&self, node: Option>) -> Option {
+ node.filter(|_| self.test(1)).map(|node| Element { node, tests: self.tests, most: self.most })
+ }
+}
+
+impl simplecss::Element for Element<'_, '_, '_> {
fn parent_element(&self) -> Option {
- self.0.parent_element().map(Self)
+ self.of(self.node.parent_element())
}
fn prev_sibling_element(&self) -> Option {
- self.0.prev_sibling_element().map(Self)
+ self.of(self.node.prev_sibling_element())
}
fn has_local_name(&self, name: &str) -> bool {
- self.0.tag_name().name() == name
+ self.test(1) && self.node.tag_name().name() == name
}
fn attribute_matches(&self, name: &str, operator: simplecss::AttributeOperator<'_>) -> bool {
- self.0.attribute(name).is_some_and(|value| operator.matches(value))
+ // The lookup scans the element's attributes, and the match the value.
+ let value = self.node.attribute(name);
+ let scanned = css::scan_tests(self.node.attributes().len()).saturating_add(value.map_or(0, |v| css::scan_tests(v.len())));
+ self.test(scanned) && value.is_some_and(|value| operator.matches(value))
}
fn pseudo_class_matches(&self, class: simplecss::PseudoClass<'_>) -> bool {
- matches!(class, simplecss::PseudoClass::FirstChild) && self.0.prev_sibling_element().is_none()
+ self.test(1) && matches!(class, simplecss::PseudoClass::FirstChild) && self.node.prev_sibling_element().is_none()
}
}
@@ -153,16 +198,34 @@ fn copied(declaration: &simplecss::Declaration) -> u64 {
}
}
-/// What usvg makes of one element: elements (text nodes included) and bytes of copied styles.
-#[derive(Clone, Copy, Default)]
-struct Cost {
- elements: u64,
- bytes: u64,
+/// What usvg makes of an element or an SVG: elements (text nodes included), bytes of copied
+/// styles and selector tests.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub(crate) struct Cost {
+ pub(crate) elements: u64,
+ pub(crate) bytes: u64,
+ pub(crate) tests: u64,
}
impl Cost {
- fn add(self, other: Cost) -> Cost {
- Cost { elements: self.elements.saturating_add(other.elements), bytes: self.bytes.saturating_add(other.bytes) }
+ /// The most an SVG and the SVG images it shows may cost together.
+ pub(crate) const LIMITS: Cost = Cost { elements: MAX_SVG_ELEMENTS as u64, bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS };
+
+ pub(crate) fn add(self, other: Cost) -> Cost {
+ Cost {
+ elements: self.elements.saturating_add(other.elements),
+ bytes: self.bytes.saturating_add(other.bytes),
+ tests: self.tests.saturating_add(other.tests),
+ }
+ }
+
+ /// What is left of `self` after `spent`.
+ pub(crate) fn less(self, spent: Cost) -> Cost {
+ Cost {
+ elements: self.elements.saturating_sub(spent.elements),
+ bytes: self.bytes.saturating_sub(spent.bytes),
+ tests: self.tests.saturating_sub(spent.tests),
+ }
}
}
@@ -178,6 +241,14 @@ struct Measure<'a, 'i> {
/// The first element of each id.
ids: HashMap<&'a str, XNode<'a, 'i>>,
sheet: simplecss::StyleSheet<'a>,
+ /// The selector tests made of `sheet` so far, each element once.
+ tests: Cell,
+ /// The most selector tests of `sheet` that are left: matching stops past them.
+ most_tests: u64,
+ /// The selector tests the import's own cascade made ([`Measure::cascade`]).
+ cascade_tests: Cell,
+ /// The import's own style cascade of the same style sheets.
+ cascade: css::Styles,
/// The elements that hold a `` of themselves.
holds_use_of_itself: HashSet,
/// The ``s of each element, by the element.
@@ -204,7 +275,17 @@ impl<'a, 'i> Measure<'a, 'i> {
sheet.parse_more(text);
}
}
- let mut m = Measure { ids, sheet, holds_use_of_itself: HashSet::new(), used_by: HashMap::new(), tref_text: HashMap::new() };
+ let mut m = Measure {
+ ids,
+ sheet,
+ tests: Cell::new(0),
+ most_tests: MAX_SELECTOR_TESTS,
+ cascade_tests: Cell::new(0),
+ cascade: css::Styles::new(xml),
+ holds_use_of_itself: HashSet::new(),
+ used_by: HashMap::new(),
+ tref_text: HashMap::new(),
+ };
for u in xml.descendants().filter(|n| n.has_tag_name((SVG_NS, "use"))) {
let Some(target) = m.target(u) else { continue };
if u.ancestors().skip(1).any(|a| a == target) {
@@ -241,21 +322,51 @@ impl<'a, 'i> Measure<'a, 'i> {
Shows::All(link)
}
- /// The bytes of style values usvg copies into one copy of element `n`.
- fn styles(&self, n: XNode) -> u64 {
+ /// Element `n` alone, as usvg makes one copy of it: the bytes of style values it copies into
+ /// it, and the selector tests usvg makes to find them (each rule tested counts as one too).
+ fn own(&self, n: XNode) -> Cost {
+ let before = self.tests.get();
let mut bytes = 0u64;
- for rule in self.sheet.rules.iter().filter(|r| r.selector.matches(&Element(n))) {
- bytes = rule.declarations.iter().map(copied).fold(bytes, u64::saturating_add);
+ for rule in &self.sheet.rules {
+ self.tests.set(self.tests.get().saturating_add(1));
+ if rule.selector.matches(&Element { node: n, tests: &self.tests, most: self.most_tests }) {
+ bytes = rule.declarations.iter().map(copied).fold(bytes, u64::saturating_add);
+ }
}
if let Some(style) = n.attribute("style") {
bytes = simplecss::DeclarationTokenizer::from(style).map(|d| copied(&d)).fold(bytes, u64::saturating_add);
}
- bytes
+ Cost { elements: 1, bytes, tests: self.tests.get().saturating_sub(before) }
}
- /// Element `n` alone.
- fn own(&self, n: XNode) -> Cost {
- Cost { elements: 1, bytes: self.styles(n) }
+ /// Have the selector tests made so far passed what is left of them?
+ fn tests_past(&self) -> bool {
+ self.tests.get() > self.most_tests
+ }
+
+ /// What the import's own style cascade keeps for the elements of `xml`, each once, up to
+ /// `left`: the bytes of the declarations of the rules that match it, and the tests it makes to
+ /// find them.
+ /// The tests it makes are kept in `cascade_tests`, as far as it gets.
+ fn cascade(&self, xml: &roxmltree::Document, left: Cost) -> Result {
+ let mut cost = Cost::default();
+ if !self.cascade.has_rules() {
+ return Ok(cost);
+ }
+ let mut result = Ok(());
+ for n in xml.descendants().filter(XNode::is_element) {
+ let Some(bytes) = self.cascade.matched_bytes(n, COPY, &mut cost.tests, left.tests) else {
+ result = Err(Past::Tests);
+ break;
+ };
+ cost.bytes = cost.bytes.saturating_add(bytes);
+ if cost.bytes > left.bytes {
+ result = Err(Past::Bytes);
+ break;
+ }
+ }
+ self.cascade_tests.set(cost.tests);
+ result.map(|()| cost)
}
/// `` `t` and what usvg makes of what it holds: at most an element of each element, and
@@ -265,11 +376,11 @@ impl<'a, 'i> Measure<'a, 'i> {
for d in t.descendants().skip(1) {
if d.is_text() {
let len = d.text().map_or(0, str::len) as u64;
- cost = cost.add(Cost { elements: 1, bytes: COPY + len });
+ cost = cost.add(Cost { elements: 1, bytes: COPY + len, tests: 0 });
} else if svg_name(d).is_some() {
cost = cost.add(self.own(d));
if svg_name(d) == Some("tref") {
- cost = cost.add(Cost { elements: 1, bytes: COPY + self.tref(d) });
+ cost = cost.add(Cost { elements: 1, bytes: COPY + self.tref(d), tests: 0 });
}
}
}
@@ -286,16 +397,23 @@ impl<'a, 'i> Measure<'a, 'i> {
}
}
-/// The bytes of style values usvg would copy into the elements of `xml`, when that is no more
-/// than `bytes_left` and it makes no more than [`MAX_SVG_ELEMENTS`] elements of it, nested no
-/// deeper than `depth` (counted as `depth::height` counts, which finds at least as much).
-pub(super) fn check(xml: &roxmltree::Document, bytes_left: u64, depth: usize) -> Result {
- match measure(xml, MAX_SVG_ELEMENTS as u64, bytes_left, depth) {
- Ok(cost) => Ok(cost.bytes),
- Err(Past::Elements) => Err(SvgError::TooLarge(MAX_SVG_ELEMENTS)),
- Err(Past::Bytes) => Err(SvgError::StylesTooLarge((MAX_COPIED_STYLES >> 20) as usize)),
- Err(Past::Depth) => Err(SvgError::TooDeep(MAX_ELEMENT_DEPTH)),
- }
+/// What usvg would make of `xml`, with what the import's own style cascade keeps of it and the
+/// selector tests it makes, when that is no more than `left` and nested no deeper than `depth`
+/// (counted as `depth::height` counts, which finds at least as much).
+pub(super) fn check(xml: &roxmltree::Document, left: Cost, depth: usize) -> Result {
+ check_spending(xml, left, depth).0
+}
+
+/// [`check`], with the selector tests it made, as far as it got.
+pub(super) fn check_spending(xml: &roxmltree::Document, left: Cost, depth: usize) -> (Result, u64) {
+ let (result, tests) = measure_spending(xml, left, depth);
+ let result = result.map_err(|past| match past {
+ Past::Elements => SvgError::TooLarge(MAX_SVG_ELEMENTS),
+ Past::Bytes => SvgError::StylesTooLarge((MAX_COPIED_STYLES >> 20) as usize),
+ Past::Tests => SvgError::StylesTooComplex,
+ Past::Depth => SvgError::TooDeep(MAX_ELEMENT_DEPTH),
+ });
+ (result, tests)
}
/// The limit [`measure`] stopped at.
@@ -303,14 +421,32 @@ pub(super) fn check(xml: &roxmltree::Document, bytes_left: u64, depth: usize) ->
enum Past {
Elements,
Bytes,
+ Tests,
Depth,
}
-/// What usvg makes of `xml`, up to `elements` elements and `bytes` bytes of copied styles, its
-/// elements and the copies ``s show nested up to `depth` deep. Without recursion; each
-/// element is measured once.
-fn measure(xml: &roxmltree::Document, elements: u64, bytes: u64, depth: usize) -> Result {
+/// What usvg makes of `xml` with what the import's own style cascade keeps of it and its tests,
+/// up to `left`, its elements and the copies ``s show nested up to `depth` deep. Without
+/// recursion; each element is measured once.
+#[cfg(test)]
+fn measure(xml: &roxmltree::Document, left: Cost, depth: usize) -> Result {
+ measure_spending(xml, left, depth).0
+}
+
+/// [`measure`], with the selector tests it made, as far as it got.
+fn measure_spending(xml: &roxmltree::Document, left: Cost, depth: usize) -> (Result, u64) {
let mut m = Measure::new(xml);
+ let result = walk(&mut m, xml, left, depth);
+ (result, m.cascade_tests.get().saturating_add(m.tests.get()))
+}
+
+/// [`measure`] with `m`, made of `xml`.
+fn walk<'a, 'i>(m: &mut Measure<'a, 'i>, xml: &'a roxmltree::Document<'i>, left: Cost, depth: usize) -> Result {
+ // First: its tests are bounded by what it finds, usvg's are not.
+ let cascade = m.cascade(xml, left)?;
+ let left = left.less(cascade);
+ m.most_tests = left.tests;
+ let (elements, bytes) = (left.elements, left.bytes);
let mut costs: HashMap = HashMap::new();
// The elements entered and not yet left: one entered again is a loop.
let mut open: HashSet = HashSet::new();
@@ -366,11 +502,15 @@ fn measure(xml: &roxmltree::Document, elements: u64, bytes: u64, depth: usize) -
if cost.bytes > bytes {
return Err(Past::Bytes);
}
+ if m.tests_past() || cost.tests > left.tests {
+ return Err(Past::Tests);
+ }
costs.insert(n.id(), cost);
}
}
}
- Ok(costs.get(&root.id()).copied().unwrap_or_default())
+ let usvg = costs.get(&root.id()).copied().unwrap_or_default();
+ Ok(usvg.add(cascade))
}
#[cfg(test)]
@@ -381,15 +521,17 @@ mod tests {
format!(r#"{body} "#)
}
+ const NO_LIMITS: Cost = Cost { elements: u64::MAX, bytes: u64::MAX, tests: u64::MAX };
+
/// What [`measure`] makes of `text` with no limits, as (elements, bytes).
fn cost(text: &str) -> (u64, u64) {
let xml = roxmltree::Document::parse(text).unwrap();
- let c = measure(&xml, u64::MAX, u64::MAX, usize::MAX).unwrap_or_else(|p| panic!("{p:?}"));
+ let c = measure(&xml, NO_LIMITS, usize::MAX).unwrap_or_else(|p| panic!("{p:?}"));
(c.elements, c.bytes)
}
fn past(text: &str, elements: u64, bytes: u64) -> Option {
- measure(&roxmltree::Document::parse(text).unwrap(), elements, bytes, usize::MAX).err()
+ measure(&roxmltree::Document::parse(text).unwrap(), Cost { elements, bytes, tests: u64::MAX }, usize::MAX).err()
}
/// Groups `g0` to `g{levels}`: `g0` a rectangle styled `style`, each other two ``s of the
@@ -423,9 +565,12 @@ mod tests {
#[test]
fn style_sheet_rules_count_where_they_match() {
let groups = " ".repeat(4);
- // `g` matches the four groups (16 + 3 each), `.b` none, `svg` the root (16 + 4).
+ // `g` matches the four groups (16 + 3 each), `.b` none, `svg` the root (16 + 4); the
+ // import's own cascade keeps the same, names included (16 + 4 + 3 and 16 + 4 + 4).
let (_, bytes) = cost(&svg(&format!("{groups}")));
- assert_eq!(bytes, 4 * 19 + 20);
+ assert_eq!(bytes, 4 * 19 + 20 + 4 * 23 + 24);
+ // usvg drops a `:not()` rule; the cascade keeps it for each group it matches.
+ assert_eq!(cost(&svg(&format!("{groups}"))).1, 4 * 23);
// A style sheet of another type is not read; the style element itself makes nothing.
assert_eq!(cost(&svg(&format!("{groups}"))), (5, 0));
// `marker` sets three properties; `font` resets twelve and sets six from its text.
@@ -467,13 +612,13 @@ mod tests {
let links: String = (0..3000).map(|i| format!(" ", i + 1)).collect();
let deep = svg(&format!("{links} "));
let xml = roxmltree::Document::parse(&deep).unwrap();
- assert_eq!(measure(&xml, u64::MAX, u64::MAX, MAX_ELEMENT_DEPTH).err(), Some(Past::Depth));
+ assert_eq!(measure(&xml, NO_LIMITS, MAX_ELEMENT_DEPTH).err(), Some(Past::Depth));
assert!(super::super::depth::height(&xml, MAX_ELEMENT_DEPTH).is_none());
- assert!(matches!(check(&xml, MAX_COPIED_STYLES, MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_))));
+ assert!(matches!(check(&xml, Cost::LIMITS, MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_))));
for text in [chain(5, ""), svg(" ")] {
let xml = roxmltree::Document::parse(&text).unwrap();
let height = super::super::depth::height(&xml, usize::MAX).unwrap_or(0);
- assert!(measure(&xml, u64::MAX, u64::MAX, height).is_ok(), "{height} {text}");
+ assert!(measure(&xml, NO_LIMITS, height).is_ok(), "{height} {text}");
}
}
@@ -492,11 +637,110 @@ mod tests {
fn a_long_rule_on_many_elements_is_refused_before_the_cascade_reads_it() {
let groups = svg(&format!("{}", "a".repeat(100_000), " ".repeat(1000)));
let image = svg(&format!(r#" "#, crate::base64_encode(groups.as_bytes())));
- for text in [groups, image] {
+ // usvg drops a `:not()` rule, which the import's own cascade reads.
+ let not = svg(&format!("{}", "a".repeat(100_000), " ".repeat(1000)));
+ for text in [groups, image, not] {
let before = super::super::css::selector_tests();
let err = super::super::import(&text, &crate::ImportOptions::default(), MAX_NODES).err();
assert!(matches!(err, Some(SvgError::StylesTooLarge(64))), "{err:?}");
assert_eq!(super::super::css::selector_tests(), before);
}
}
+
+ /// A linked SVG file with such a rule, and an `` of its own whose link the import reads,
+ /// is refused before the cascade reads it too.
+ #[test]
+ fn a_linked_svg_with_a_long_rule_is_refused_before_the_cascade_reads_it() {
+ let linked =
+ svg(&format!("{} ", "a".repeat(100_000), " ".repeat(1000)));
+ let read = |path: &str| path.ends_with("a.svg").then(|| (linked.clone().into_bytes(), vectorcraft_doc::LinkInfo::new(path)));
+ let folder = std::env::temp_dir().join("vectorcraft-svg-budget");
+ let folder = folder.to_string_lossy();
+ let opts = crate::ImportOptions { folder: Some(&folder), read: Some(&read) };
+ let before = super::super::css::selector_tests();
+ let err = super::super::import(&svg(" "), &opts, MAX_NODES).err();
+ assert!(matches!(err, Some(SvgError::StylesTooLarge(64))), "{err:?}");
+ assert_eq!(super::super::css::selector_tests(), before);
+ }
+
+ /// `depth` groups in one another, each of class `a`, around a rectangle, with `sheet`.
+ fn nested(depth: usize, sheet: &str) -> String {
+ svg(&format!("{} {}", "".repeat(depth), " ".repeat(depth)))
+ }
+
+ /// A selector whose leftmost part matches nothing makes usvg test every set of ancestors in
+ /// turn: the tests stop at the limit and the SVG is refused, before usvg or the cascade runs.
+ #[test]
+ fn a_selector_that_never_matches_stops_at_the_test_limit() {
+ let never = nested(60, &format!(".missing{} {{fill:red}}", " g".repeat(20)));
+ let xml = roxmltree::Document::parse(&never).unwrap();
+ assert_eq!(measure(&xml, Cost::LIMITS, usize::MAX).err(), Some(Past::Tests));
+ let before = super::super::css::selector_tests();
+ let err = super::super::import(&never, &crate::ImportOptions::default(), MAX_NODES).err();
+ assert!(matches!(err, Some(SvgError::StylesTooComplex)), "{err:?}");
+ assert_eq!(super::super::css::selector_tests(), before);
+ // The same selector without its leftmost part matches at once, and imports.
+ let matching = nested(60, &format!("g{} {{fill:red}}", " g".repeat(19)));
+ assert!(super::super::import(&matching, &crate::ImportOptions::default(), MAX_NODES).is_ok());
+ }
+
+ /// usvg tests the rules against each copy a `` shows: the tests add up as the copies do,
+ /// and the cascade's tests count once for each element.
+ #[test]
+ fn selector_tests_count_for_each_copy() {
+ let tests = |levels: usize| {
+ let text = chain(levels, "").replacen("", "", 1);
+ let xml = roxmltree::Document::parse(&text).unwrap();
+ measure(&xml, NO_LIMITS, usize::MAX).unwrap_or_else(|p| panic!("{p:?}")).tests
+ };
+ let (ten, eleven) = (tests(10), tests(11));
+ assert!(eleven > 2 * ten - 100, "{ten} {eleven}");
+ let text = chain(11, "").replacen("", "", 1);
+ let xml = roxmltree::Document::parse(&text).unwrap();
+ assert_eq!(measure(&xml, Cost { tests: eleven - 1, ..NO_LIMITS }, usize::MAX).err(), Some(Past::Tests));
+ assert!(measure(&xml, Cost { tests: eleven, ..NO_LIMITS }, usize::MAX).is_ok());
+ }
+
+ /// Each alternative of a `:not()` counts as a test of the cascade, for each element.
+ #[test]
+ fn not_alternatives_count_as_tests() {
+ let alternatives: Vec = (0..1000).map(|i| format!(".m{i}")).collect();
+ let text = svg(&format!("{}", alternatives.join(","), " ".repeat(1000)));
+ let xml = roxmltree::Document::parse(&text).unwrap();
+ let tests = measure(&xml, NO_LIMITS, usize::MAX).unwrap_or_else(|p| panic!("{p:?}")).tests;
+ assert!(tests > 1000 * 1000, "{tests}");
+ assert_eq!(measure(&xml, Cost { tests: 1000 * 1000, ..NO_LIMITS }, usize::MAX).err(), Some(Past::Tests));
+ }
+
+ /// Matching as usvg matches stops once its tests pass what the limits have left, as when an
+ /// SVG image gets what the SVG showing it left.
+ #[test]
+ fn usvg_matching_stops_at_what_is_left() {
+ let never = nested(60, &format!(".missing{} {{fill:red}}", " g".repeat(20)));
+ let xml = roxmltree::Document::parse(&never).unwrap();
+ let cascade = Measure::new(&xml).cascade(&xml, NO_LIMITS).unwrap_or_else(|p| panic!("{p:?}")).tests;
+ assert_eq!(measure(&xml, Cost { tests: cascade + 1000, ..NO_LIMITS }, usize::MAX).err(), Some(Past::Tests));
+ let made = USVG_TESTS.get();
+ assert!((1000..1100).contains(&made), "{made}");
+ }
+
+ /// Each class of a compound is looked for in the element's class list, so the tests grow with
+ /// the list's length: in the import's own cascade (a `:not()` rule, which usvg drops) and as
+ /// usvg matches.
+ #[test]
+ fn class_tests_grow_with_the_class_list() {
+ let list = (0..1000).map(|i| format!("c{i}")).collect::>().join(" ");
+ let classes: String = (0..100).map(|i| format!(".c{i}")).collect();
+ let scans = 100 * css::scan_tests(list.len());
+ let tests = |rule: &str| {
+ let text = svg(&format!(" "));
+ let xml = roxmltree::Document::parse(&text).unwrap();
+ measure(&xml, NO_LIMITS, usize::MAX).unwrap_or_else(|p| panic!("{p:?}")).tests
+ };
+ let cascade = tests(&format!("g:not(.x{classes})"));
+ assert!(cascade >= scans, "{cascade} {scans}");
+ tests(&format!("g{classes}"));
+ let usvg = USVG_TESTS.get();
+ assert!(usvg >= scans, "{usvg} {scans}");
+ }
}
diff --git a/crates/svg/src/import/css.rs b/crates/svg/src/import/css.rs
index 7ddfb1bbd5..b5f1d80320 100644
--- a/crates/svg/src/import/css.rs
+++ b/crates/svg/src/import/css.rs
@@ -103,6 +103,24 @@ impl Compound {
&& self.attrs.iter().all(|(a, v)| n.attribute(a.as_str()).is_some_and(|x| v.as_deref().is_none_or(|v| x == v)))
&& !self.nots.iter().any(|c| c.matches(n))
}
+
+ /// The tests [`Compound::matches`] makes of `n` at most, its `:not()`s' included: one for the
+ /// compound, [`scan_tests`] of `n`'s attributes for each attribute it looks up, and for each
+ /// of its classes, [`scan_tests`] of `n`'s class list.
+ fn tests(&self, n: XNode) -> u64 {
+ let lookups = u64::from(self.id.is_some()) + u64::from(!self.classes.is_empty()) + self.attrs.len() as u64;
+ let mut tests = lookups.saturating_mul(scan_tests(n.attributes().len())).saturating_add(1);
+ if !self.classes.is_empty() {
+ let list = scan_tests(n.attribute("class").map_or(0, str::len));
+ tests = tests.saturating_add((self.classes.len() as u64).saturating_mul(list));
+ }
+ self.nots.iter().map(|c| c.tests(n)).fold(tests, u64::saturating_add)
+ }
+}
+
+/// The tests a scan of `len` attributes or bytes counts as: one, and one more for every 16.
+pub(super) fn scan_tests(len: usize) -> u64 {
+ 1 + len as u64 / 16
}
/// A complex selector, rightmost compound first; each compound's flag says whether it must be the
@@ -260,14 +278,35 @@ impl Selector {
}
fn matches(&self, n: XNode) -> bool {
+ #[cfg(test)]
+ SELECTOR_TESTS.set(SELECTOR_TESTS.get().saturating_add(1));
+ self.matches_counting(n, &mut 0, None)
+ }
+
+ /// [`Self::matches`], counting the tests of each compound tested against an element in
+ /// `steps` ([`Compound::tests`]), those of its `:not()`s included. Once `steps` passes `most`,
+ /// no compound matches any more.
+ fn matches_within(&self, n: XNode, steps: &mut u64, most: u64) -> bool {
+ self.matches_counting(n, steps, Some(most))
+ }
+
+ /// [`Self::matches_within`] when `most` is given; [`Self::matches`], counting nothing, when not.
+ fn matches_counting(&self, n: XNode, steps: &mut u64, most: Option) -> bool {
// The result of matching a selector suffix from a node depends only on the suffix and
// the node, so memoize it: without this, every descendant step retries every matching
// ancestor and a selector whose leftmost compound never matches makes the search
// enumerate ancestor combinations (#1703). A suffix of `parts` is identified by its
// length, so (suffix length, node id) is a complete key and the visited states are
// bounded by parts × ancestors.
- fn go(parts: &[(Compound, bool)], n: XNode, memo: &mut HashMap<(usize, roxmltree::NodeId), bool>) -> bool {
+ type Memo = HashMap<(usize, roxmltree::NodeId), bool>;
+ fn go(parts: &[(Compound, bool)], n: XNode, memo: &mut Memo, steps: &mut u64, most: Option) -> bool {
let Some(((c, child), rest)) = parts.split_first() else { return true };
+ if let Some(most) = most {
+ *steps = steps.saturating_add(c.tests(n));
+ if *steps > most {
+ return false;
+ }
+ }
if !c.matches(n) {
return false;
}
@@ -279,16 +318,14 @@ impl Selector {
return hit;
}
let hit = if *child {
- n.parent_element().is_some_and(|p| go(rest, p, memo))
+ n.parent_element().is_some_and(|p| go(rest, p, memo, steps, most))
} else {
- n.ancestors().skip(1).filter(|a| a.is_element()).any(|a| go(rest, a, memo))
+ n.ancestors().skip(1).filter(|a| a.is_element()).any(|a| go(rest, a, memo, steps, most))
};
memo.insert(key, hit);
hit
}
- #[cfg(test)]
- SELECTOR_TESTS.set(SELECTOR_TESTS.get().saturating_add(1));
- go(&self.parts, n, &mut HashMap::new())
+ go(&self.parts, n, &mut HashMap::new(), steps, most)
}
}
@@ -495,6 +532,24 @@ impl Styles {
m
}
+ /// The bytes the declarations of the rules that match `n` take, names and values, each with
+ /// `per_declaration` more: at least what [`Styles::declared`] keeps of them for `n`. Nothing
+ /// is kept. `steps` counts the rules and compounds tested; `None` once it passes `most`.
+ pub(super) fn matched_bytes(&self, n: XNode, per_declaration: u64, steps: &mut u64, most: u64) -> Option {
+ let mut bytes = 0u64;
+ for r in self.index.candidates(n).into_iter().filter_map(|i| self.rules.get(i)) {
+ *steps = steps.saturating_add(1);
+ if r.selector.matches_within(n, steps, most) {
+ let size = |(k, v, _): &(String, String, bool)| per_declaration.saturating_add((k.len() + v.len()) as u64);
+ bytes = r.decls.iter().map(size).fold(bytes, u64::saturating_add);
+ }
+ if *steps > most {
+ return None;
+ }
+ }
+ Some(bytes)
+ }
+
/// Are there rules with a `:not()` (which usvg's style sheets drop)?
pub(super) fn has_not_rules(&self) -> bool {
self.rules.iter().any(|r| r.selector.has_not())
diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs
index 691ea950f1..fe3335fb4e 100644
--- a/crates/svg/src/import/files.rs
+++ b/crates/svg/src/import/files.rs
@@ -74,9 +74,9 @@ pub(in crate::import) struct Files {
/// The CMYK TIFF stored in place of a turned CMYK image, by the address of the PNG usvg got
/// (kept here too, so the address stays its own).
cmyk: Mutex>,
- /// The bytes of style values usvg copies into the elements of the SVG and of the SVG images
- /// read so far ([`budget`]).
- styles: AtomicU64,
+ /// What usvg makes of the SVG and of the SVG images read so far, all together ([`budget`]):
+ /// elements, bytes of copied style values and selector tests.
+ spent: Mutex,
/// Why an SVG image refused the whole SVG: what usvg would make of it is past [`budget`]'s
/// limits. The first one.
refused: Mutex>,
@@ -134,6 +134,9 @@ struct Reading<'a, 'w> {
/// SVG links to aren't counted.
svg_reads: usize,
svg_text: u64,
+ /// What the linked SVG files measured for their links make, all together ([`budget`]); of one
+ /// past what is left, the selector tests it made.
+ measured: budget::Cost,
}
impl Reading<'_, '_> {
@@ -254,8 +257,17 @@ impl Files {
/// relinked.
pub(in crate::import) fn read(svg: &str, xml: &roxmltree::Document, opts: &ImportOptions, edits: &mut Edits, warnings: &mut Vec) -> Self {
let mut files = Files::default();
- let mut reading =
- Reading { opts, warnings, placeholder: None, by_file: HashMap::new(), active: vec![], placed: false, svg_reads: 0, svg_text: 0 };
+ let mut reading = Reading {
+ opts,
+ warnings,
+ placeholder: None,
+ by_file: HashMap::new(),
+ active: vec![],
+ placed: false,
+ svg_reads: 0,
+ svg_text: 0,
+ measured: budget::Cost::default(),
+ };
files.sources = files.links_of(svg, xml, opts.folder, None, edits, &mut reading);
files
}
@@ -383,6 +395,19 @@ impl Files {
// Read from its own handle: the text stays borrowed while `svg` may be given back.
let text = svg.text.clone();
let Ok(xml) = super::parse(&text) else { return Outcome::shown(Source::Svg(svg)) };
+ // Measured before the style cascade of `depth::height`, as an SVG image is when usvg
+ // reads it ([`Files::svg_tree`]), which then refuses one past the limits, within what the
+ // linked SVG files measured before it left: past it, its links aren't read, and the
+ // selector tests it made still count.
+ let (result, tests) = budget::check_spending(&xml, budget::Cost::LIMITS.less(reading.measured), left);
+ match result {
+ Ok(cost) => reading.measured = reading.measured.add(cost),
+ Err(e) => {
+ reading.measured.tests = reading.measured.tests.saturating_add(tests);
+ reading.placed |= matches!(e, SvgError::TooDeep(_));
+ return Outcome::shown(Source::Svg(svg));
+ }
+ }
let Some(height) = depth::height(&xml, left) else {
reading.placed = true;
return Outcome::shown(Source::Svg(svg));
@@ -485,10 +510,20 @@ impl Files {
notes
}
- /// The SVG holding the images copies `bytes` of style values ([`budget::check`]): its images
- /// copy at most what is left.
- pub(in crate::import) fn copied_styles(&self, bytes: u64) {
- self.styles.store(bytes, Ordering::Relaxed);
+ /// What usvg makes of the SVG holding the images ([`budget::check`]): its images make at most
+ /// what is left of [`budget::Cost::LIMITS`].
+ pub(in crate::import) fn spent_by_svg(&self, spent: budget::Cost) {
+ self.set_spent(spent);
+ }
+
+ fn spent(&self) -> budget::Cost {
+ self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::LIMITS)
+ }
+
+ fn set_spent(&self, spent: budget::Cost) {
+ if let Ok(mut s) = self.spent.lock() {
+ *s = spent;
+ }
}
/// The error of the first SVG image past [`budget`]'s limits, which refuses the SVG holding it.
@@ -588,12 +623,12 @@ impl Files {
}
let xml = super::parse(text).ok()?;
// What usvg would make of it, measured as the SVG holding it is (`import`), before the
- // style cascade of `depth::height`; its copied styles count with theirs while usvg reads
- // it, and only when it decodes. Too deep, it is left out; past the other limits, the whole
- // SVG is refused.
- let spent = self.styles.load(Ordering::Relaxed);
- let bytes = match budget::check(&xml, budget::MAX_COPIED_STYLES.saturating_sub(spent), left) {
- Ok(bytes) => bytes,
+ // style cascade of `depth::height`; its elements, copied styles and selector tests count
+ // with theirs while usvg reads it, and only when it decodes. Too deep, it is left out;
+ // past the other limits, the whole SVG is refused.
+ let spent = self.spent();
+ let cost = match budget::check(&xml, budget::Cost::LIMITS.less(spent), left) {
+ Ok(cost) => cost,
Err(SvgError::TooDeep(_)) => return leave_out(&self.too_deep, true),
Err(e) => {
if let Ok(mut refused) = self.refused.lock() {
@@ -605,7 +640,7 @@ impl Files {
let Some(height) = depth::height(&xml, left) else { return leave_out(&self.too_deep, true) };
// usvg's parser would overflow on it, as on the SVG holding it (`import`).
super::convolve_matrices_ok(&xml).ok()?;
- self.styles.store(spent.saturating_add(bytes), Ordering::Relaxed);
+ self.set_spent(spent.add(cost));
self.depth.store(used + height, Ordering::Relaxed);
let within = self.within.lock().ok().map(|mut w| w.push(file)).is_some();
// usvg's `Tree::from_data_nested`, except that hrefs to files go to the resolver.
@@ -631,7 +666,7 @@ impl Files {
self.depth.store(used, Ordering::Relaxed);
let Ok(tree) = tree else {
// Left out: neither it nor the images inside it count.
- self.styles.store(spent, Ordering::Relaxed);
+ self.set_spent(spent);
return None;
};
self.note_text(text);
@@ -935,12 +970,44 @@ mod tests {
placed: false,
svg_reads: reads,
svg_text: text,
+ measured: budget::Cost::default(),
};
let mut files = Files::default();
files.sources = files.links_of(&svg, &xml, opts.folder, None, &mut Edits::default(), &mut reading);
(log.into_inner().unwrap(), files)
}
+ /// The linked SVG files measured for their links share the limits: each of these keeps about
+ /// 40 MB of declarations in the import's own cascade (its `:not()` rule), so the second one is
+ /// shown without its links, and neither it nor the cascade reads them.
+ #[test]
+ fn linked_svg_files_share_the_limits_for_their_links() {
+ let file = |png: &str| {
+ let groups = " ".repeat(400);
+ let rule = format!("g:not(.x){{font-family:{}}}", "a".repeat(100_000));
+ format!(r#"{groups} "#)
+ .into_bytes()
+ };
+ let served = [("a.svg", file("a.png")), ("b.svg", file("b.png")), ("a.png", png()), ("b.png", png())];
+ let (log, _) = read_links(&["a.svg"], &served, 0, 0);
+ assert_eq!(log, ["a.svg", "a.png"]);
+ let (log, _) = read_links(&["a.svg", "b.svg"], &served, 0, 0);
+ assert_eq!(log, ["a.svg", "a.png", "b.svg"]);
+ }
+
+ /// A linked SVG file past the limits alone (a `` chain past the element limit) is shown
+ /// without its links, and the linked SVG files after it still get what it left.
+ #[test]
+ fn a_linked_svg_file_past_the_limits_leaves_the_others_their_links() {
+ let links: String = (1..=20).map(|i| format!(r##" "##, i - 1)).collect();
+ let chain = format!(
+ r##" {links} "##
+ );
+ let served = [("a.svg", chain.into_bytes()), ("b.svg", linking(&["b.png"])), ("a.png", png()), ("b.png", png())];
+ let (log, _) = read_links(&["a.svg", "b.svg"], &served, 0, 0);
+ assert_eq!(log, ["a.svg", "b.svg", "b.png"]);
+ }
+
fn png() -> Vec {
let mut out = vec![];
image::RgbaImage::new(1, 1).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs
index cbffbfc348..4bb79d6d78 100644
--- a/crates/svg/src/import/text.rs
+++ b/crates/svg/src/import/text.rs
@@ -378,24 +378,29 @@ fn clip_uses(
Some(s) => own_transform(&cx.css, s),
None => t.attribute("transform").unwrap_or("").to_string(),
};
- // One element can carry one clip path. The text's own clip path is in the text's user space
- // and wins; a clip path of the `` is in the ``'s, so the text's transform moves
- // to the importer instead.
- let clipped = |n: XNode| cx.css.own(n, "clip-path").is_some_and(|v| v.trim() != "none");
+ // One element can carry one clip path. The text's own clip path is in the text's user space;
+ // a clip path of the `` is in the ``'s. With only the ``'s, the text's
+ // transform moves to the importer. With both, the placeholder's clip path is one that
+ // holds both ([`both_clips`]).
+ let clipped = |n: XNode| cx.css.own(n, "clip-path").filter(|v| v.trim() != "none");
let id = format!("{}{i}-{k}", slots.prefix);
- let transform = if style_t.is_some_and(clipped) {
- if clipped(style_u) {
- let label = u.attribute("id").map_or_else(|| "a use of a text".to_string(), |id| format!("'{id}'"));
- warnings.push(format!("clip path of {label} in a clip path ignored: the text's own applies"));
- }
- format!("{placed} {text_xf}")
- } else {
- slots.inner.insert(id.clone(), parse_transform(Some(&text_xf)));
- placed
- };
let props = clip_props(&cx.css, style_t, Some(style_u));
let mut out = String::new();
- clip_placeholder(&mut out, q, &id, &transform, &props, u, marker);
+ match (style_t.and_then(clipped), clipped(style_u)) {
+ (Some(text_clip), Some(use_clip)) => {
+ let both = both_clips(&mut out, q, &id, &text_clip, &use_clip, parse_transform(Some(&text_xf)), marker);
+ let props = match (both, props.split_once(';')) {
+ (Some(both), Some((_, rest))) => format!("clip-path:url(#{both});{rest}"),
+ _ => props,
+ };
+ clip_placeholder(&mut out, q, &id, &format!("{placed} {text_xf}"), &props, u, marker);
+ }
+ (Some(_), None) => clip_placeholder(&mut out, q, &id, &format!("{placed} {text_xf}"), &props, u, marker),
+ (None, _) => {
+ slots.inner.insert(id.clone(), parse_transform(Some(&text_xf)));
+ clip_placeholder(&mut out, q, &id, &placed, &props, u, marker);
+ }
+ }
// Another `` can still show this one by its id: a copy of it stays in a ``, which
// the clip path leaves out, with the properties style rules gave it written out.
if u.attribute("id").is_some() {
@@ -654,6 +659,42 @@ fn clip_placeholder(out: &mut String, q: &str, id: &str, transform: &str, props:
let _ = write!(out, " d=\"M{} {}H{}V{}H{}Z\"/>", b.x0, b.y0, b.x1, b.y1, b.x0);
}
+/// Write, in a `` (which a clip path leaves out), a clip path for the placeholder `id` of a
+/// text with bounds `b` and transform `text_xf` shown by a ``, when both have a clip path:
+/// it clips by the text's clip path `text_clip` in the text's user space and by the ``'s
+/// `use_clip` in the ``'s, each on a rectangle over the text's bounds there, so a clip path in
+/// bounding box units measures the text. Its id, or `None` when `text_xf` can't be inverted (the
+/// text then draws nothing).
+fn both_clips(out: &mut String, q: &str, id: &str, text_clip: &str, use_clip: &str, text_xf: Affine, b: Rect) -> Option {
+ let det = text_xf.determinant();
+ if !det.is_finite() || det == 0.0 {
+ return None;
+ }
+ let [a, b2, c, d, e, f] = text_xf.inverse().as_coeffs();
+ let ub = text_xf.transform_rect_bbox(b);
+ let (id_u, id_t) = (format!("{id}-u"), format!("{id}-t"));
+ let rect = |out: &mut String, clip: &str, r: Rect| {
+ let _ = write!(
+ out,
+ "<{q}path style=\"transform:{IDENTITY};clip-path:{};display:inline\" d=\"M{} {}H{}V{}H{}Z\"/>",
+ xml_escape(clip),
+ r.x0,
+ r.y0,
+ r.x1,
+ r.y1,
+ r.x0
+ );
+ };
+ // The ``'s clip path, moved back by the inverse of the text's transform from the
+ // placeholder's user space to the ``'s.
+ let _ = write!(out, "<{q}defs><{q}clipPath id=\"{}\" style=\"transform:matrix({a} {b2} {c} {d} {e} {f})\">", xml_escape(&id_u));
+ rect(out, use_clip, ub);
+ let _ = write!(out, "{q}clipPath><{q}clipPath id=\"{}\" style=\"clip-path:url(#{})\">", xml_escape(&id_t), xml_escape(&id_u));
+ rect(out, text_clip, b);
+ let _ = write!(out, "{q}clipPath>{q}defs>");
+ Some(id_t)
+}
+
/// Write the placeholder group for text `t` (namespace prefix `q`), slot `index`, with the text's
/// id when `with_id`.
#[allow(clippy::too_many_arguments)]
diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs
index daf3288920..3272c999fc 100644
--- a/crates/svg/src/lib.rs
+++ b/crates/svg/src/lib.rs
@@ -370,6 +370,10 @@ pub enum SvgError {
/// copies and SVG images included, add up to more than this many megabytes.
#[error("the SVG's styles expand to more than {0} MB")]
StylesTooLarge(usize),
+ /// Matching the style sheets' selectors against the elements the SVG expands to, ``
+ /// copies and SVG images included, takes more tests than the reader allows.
+ #[error("the SVG's style sheets take too long to match")]
+ StylesTooComplex,
}
/// Export a document as an SVG string (linked images are not returned: see [`export_full`]).
diff --git a/crates/svg/tests/it/clip_text.rs b/crates/svg/tests/it/clip_text.rs
index a2dcb46156..bb92802e60 100644
--- a/crates/svg/tests/it/clip_text.rs
+++ b/crates/svg/tests/it/clip_text.rs
@@ -221,6 +221,27 @@ fn a_clip_path_on_a_use_of_a_text_is_in_the_use_s_user_space() {
assert!(t.xf.translation().to_point().distance(Point::new(200.0, 160.0)) < 1e-9, "{:?}", t.xf);
}
+#[test]
+fn a_use_and_the_text_it_shows_in_a_clip_path_both_clip() {
+ // The text's own clip keeps y < 120 of its user space; the ``'s keeps x < 250 of the
+ // ``'s, which the text's transform doesn't move. The glyphs keep only what both keep.
+ let body = r##"
+
+ HI
+
+ "##;
+ let (d, warnings) = import_with_report(&svg(body)).unwrap();
+ let (clip, _) = clip_group(&top(&d)[0]);
+ let b = clip_bounds(clip);
+ assert!(b.x0 >= 200.0 - 1e-6 && near(b.x1, 250.0, 1e-6), "{b:?}");
+ assert!(near(b.y1, 130.0, 1e-6) && b.y0 > 50.0, "{b:?}");
+ // It clips by the glyphs, not their box: nothing between the stems of the H.
+ let (bp, _) = vectorcraft_effects::clip_outline(clip).unwrap();
+ assert!(bp.contains(Point::new(b.x0 + 2.0, 110.0)), "on a stem");
+ assert!(!bp.contains(Point::new(225.0, 100.0)), "between the stems");
+ assert!(!warnings.iter().any(|w| w.contains("ignored")), "{warnings:?}");
+}
+
#[test]
fn a_css_transform_places_a_text_in_a_clip_path() {
let d = open(
diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs
index 6276f5ee77..4d6606eaa5 100644
--- a/crates/svg/tests/it/import_details.rs
+++ b/crates/svg/tests/it/import_details.rs
@@ -911,6 +911,33 @@ fn svg_images_whose_styles_expand_past_the_limit_refuse_the_svg() {
assert!(!art(&d).is_empty());
}
+/// The SVG images share the element limit with the SVG showing them: each image's `` chain
+/// makes 655,356 elements, so one imports and two together are refused before usvg makes the
+/// second.
+#[test]
+fn svg_images_share_the_element_limit() {
+ let chain = use_chain(16, "");
+ let unshown = chain.replacen(r##" "##, "", 1);
+ assert_ne!(chain, unshown);
+ let image = image_of("image/svg+xml", &unshown);
+ let rect = r#" "#;
+ assert!(import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()).is_ok());
+ let err = import_with(&svg(&format!("{rect}{}", image.repeat(2))), &ImportOptions::default()).unwrap_err();
+ assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}");
+}
+
+/// A `:not()` rule, which only the import's own style cascade reads, counts toward the style limit
+/// the SVG images share: each image's rule gives 400 groups the long style (about 40 MB), so one
+/// imports and two together are refused.
+#[test]
+fn svg_images_share_the_style_limit_with_not_rules() {
+ let groups = svg(&format!(r#"{} "#, long_style(), " ".repeat(400)));
+ let image = image_of("image/svg+xml", &groups);
+ assert!(import_with(&svg(&image), &ImportOptions::default()).is_ok());
+ let err = import_with(&svg(&image.repeat(2)), &ImportOptions::default()).unwrap_err();
+ assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}");
+}
+
/// Nested SVG images exceeding `MAX_NESTED_SVG_IMAGES` are left out with a warning note (#3564).
#[test]
fn nested_svg_images_past_count_cap_are_left_out() {
diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs
index a7d7d1d3f3..d7669f2fe2 100644
--- a/crates/text/src/layout.rs
+++ b/crates/text/src/layout.rs
@@ -336,6 +336,8 @@ impl Ctx<'_> {
tab.kern_shift = 0.0;
tab.aki_shift = 0.0;
tab.aki = 0.0;
+ tab.tsume_shift = 0.0;
+ tab.tsume = 0.0;
tab.tcy = None;
tab.wari = None;
tab.vpal = None;
@@ -653,6 +655,8 @@ impl Ctx<'_> {
k.kern_shift = 0.0;
k.aki_shift = 0.0;
k.aki = 0.0;
+ k.tsume_shift = 0.0;
+ k.tsume = 0.0;
k.len = 0;
k.lead = 0.0;
k.ch = kashida::TATWEEL;
@@ -713,6 +717,8 @@ mod emit_kashida_mark_last {
kern_shift: 0.0,
aki_shift: 0.0,
aki: 0.0,
+ tsume_shift: 0.0,
+ tsume: 0.0,
sx: face.upem.recip() * 48.0,
sy: face.upem.recip() * 48.0,
bshift: 0.0,
@@ -779,6 +785,8 @@ mod emit_kashida_mark_last {
kern_shift: 0.0,
aki_shift: 0.0,
aki: 0.0,
+ tsume_shift: 0.0,
+ tsume: 0.0,
sx: face.upem.recip() * 48.0,
sy: face.upem.recip() * 48.0,
bshift: 0.0,
diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs
index 451e029478..a0a09956bc 100644
--- a/crates/text/src/layout/wrapping_tests.rs
+++ b/crates/text/src/layout/wrapping_tests.rs
@@ -22,6 +22,8 @@ fn synthetic_glyphs(specs: &[(usize, usize, f64, char)]) -> Vec {
kern_shift: 0.0,
aki_shift: 0.0,
aki: 0.0,
+ tsume_shift: 0.0,
+ tsume: 0.0,
sx: 1.0,
sy: 1.0,
bshift: 0.0,
diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs
index 88d40eb1e8..9d36eed28b 100644
--- a/crates/text/src/shape.rs
+++ b/crates/text/src/shape.rs
@@ -49,6 +49,12 @@ pub(crate) struct SGlyph {
/// The Insert Aki Left and Right `adv` holds, in points: on the last glyph of its cluster, 0
/// on the others. Justification does not stretch or narrow it.
pub aki: f64,
+ /// The space Tsume ([`tighten`]) took before the cluster's ink, in points, on every glyph of
+ /// its cluster: `dx` is that much smaller.
+ pub tsume_shift: f64,
+ /// The space Tsume took out of `adv`, in points: on the last glyph of its cluster, 0 on the
+ /// others.
+ pub tsume: f64,
/// Outline scale (font units -> points).
pub sx: f64,
pub sy: f64,
@@ -232,6 +238,8 @@ pub(crate) fn hyphen_glyph(g: &SGlyph) -> SGlyph {
h.kern_shift = 0.0;
h.aki_shift = 0.0;
h.aki = 0.0;
+ h.tsume_shift = 0.0;
+ h.tsume = 0.0;
h.byte = g.byte + g.len;
h.len = 0;
h.ch = '-';
@@ -838,8 +846,8 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range<
let mut cache = HashMap::new();
let mut corrections: HashMap<[u64; 15], Option> = HashMap::new();
let mut references: HashMap> = HashMap::new();
- // The Insert Aki a cluster's last glyph holds does not make a mark its base.
- let shaped_advances: Vec = glyphs.iter().map(|g| g.adv - g.aki).collect();
+ // The Insert Aki and Tsume a cluster's last glyph holds do not make a mark its base.
+ let shaped_advances: Vec = glyphs.iter().map(|g| g.adv - g.aki + g.tsume).collect();
for i in 0..glyphs.len().saturating_sub(1) {
let Some((a, b)) = glyphs.get(i).zip(glyphs.get(i + 1)) else { continue };
if a.level != b.level {
@@ -897,10 +905,10 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range<
continue;
}
// Neither glyph is rotated, so a right-to-left manual kerning shift adds to the offset.
- // Insert Aki is measured as no space: the pair is spaced as it would be without it, and
- // the Aki stays on top of that.
- let left_x = left.dx + left.kern_shift - left.aki_shift;
- let right_x = right.dx + right.kern_shift - right.aki_shift;
+ // Insert Aki is measured as no space, and Tsume as taking none: the pair is spaced as it
+ // would be without them, and they stay on top of that.
+ let left_x = left.dx + left.kern_shift - left.aki_shift + left.tsume_shift;
+ let right_x = right.dx + right.kern_shift - right.aki_shift + right.tsume_shift;
let left_y = left.dy - left.bshift;
let right_y = right.dy - right.bshift;
let Some(left_style) = runs.get(left.run).map(|(_, s)| *s) else { continue };
@@ -909,7 +917,7 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range<
let tracking = left_style.tracking / 1000.0 * em * spacing_scale(left_style, false);
// A manual kerning value on the left glyph is part of its advance and, right to left, of
// its offset too (it spaces the left glyph from its left neighbor): it is not taken off.
- let advance = glyphs[cluster_start..=cluster_end].iter().map(|g| g.adv - g.aki).sum::() - tracking;
+ let advance = glyphs[cluster_start..=cluster_end].iter().map(|g| g.adv - g.aki + g.tsume).sum::() - tracking;
let key = [
u64::from(left.face.id()),
u64::from(left.gid),
@@ -1280,6 +1288,8 @@ fn inline_glyph(
kern_shift: if level.is_rtl() && !vertical { manual_kern } else { before } + aki_shift,
aki_shift,
aki: if adv.is_finite() { aki_left + aki_right } else { 0.0 },
+ tsume_shift: 0.0,
+ tsume: 0.0,
// Not used to draw (the art has its own transform), but they make the glyph's em box
// its run's em: Character Alignment and Top-to-Top leading treat an inline graphic as a
// character of its run's size, whatever its scale (see `layout::glyph_em`).
@@ -1788,6 +1798,8 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe
kern_shift,
aki_shift,
aki: aki_in_adv,
+ tsume_shift: 0.0,
+ tsume: 0.0,
sx: k * hs,
sy: k * vs,
bshift: gst.baseline_shift + pos_shift,
@@ -1826,8 +1838,9 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe
/// drawn along the line, the last one with `own` as its width before the tracking, kerning and
/// Insert Aki its advance holds. `tsume` percent of the blank space between the cluster's own width
/// and its ink, on each side, comes out of the cluster's advance, and its glyphs are drawn the
-/// left side's share earlier. A cluster without ink, such as a space, or with a width that is not
-/// positive, keeps its place and width.
+/// left side's share earlier ([`SGlyph::tsume`] and [`SGlyph::tsume_shift`] hold both, for Optical
+/// kerning to measure the pair without them). A cluster without ink, such as a space, or with a
+/// width that is not positive, keeps its place and width.
fn tighten(glyphs: &mut [SGlyph], own: f64, tsume: f64) {
let Some(last) = glyphs.len().checked_sub(1) else { return };
let share = if tsume.is_nan() { 0.0 } else { tsume.clamp(0.0, MAX_TSUME) / 100.0 };
@@ -1848,9 +1861,11 @@ fn tighten(glyphs: &mut [SGlyph], own: f64, tsume: f64) {
let right = (pen - hi).clamp(0.0, pen) * share;
for g in glyphs.iter_mut() {
g.dx -= left;
+ g.tsume_shift = left;
}
if let Some(g) = glyphs.get_mut(last) {
g.adv -= left + right;
+ g.tsume = left + right;
}
}
diff --git a/crates/text/src/tests/harakat.rs b/crates/text/src/tests/harakat.rs
index ea84bcf346..c8d93d451f 100644
--- a/crates/text/src/tests/harakat.rs
+++ b/crates/text/src/tests/harakat.rs
@@ -381,6 +381,44 @@ fn check_spaced_harakat(db: &FontDb, family: &str) {
assert!((length(&b) - length(&a) - 12.0).abs() < 1e-6, "{family}: {} → {}", length(&a), length(&b));
}
+/// Right to left, with harakat coloured apart, Optical kerning keeps the Tsume of each letter's
+/// cluster as it does in "HOH": the glyphs move as far with Optical kerning as without it.
+#[test]
+fn optical_kerning_keeps_the_tsume_of_a_letter_with_coloured_harakat() {
+ let db = FontDb::with_font_dirs(vec![]);
+ assert_eq!(db.add_font(crate::test_fonts::lam_alef_font(b"rlig").unwrap()), 1);
+ check_optical_tsume(&db, crate::test_fonts::lam_alef_family(b"rlig"));
+ if let Some(face) = arabic_face("optical_kerning_keeps_the_tsume_of_a_letter_with_coloured_harakat") {
+ check_optical_tsume(FontDb::global(), &face.family);
+ }
+}
+
+fn check_optical_tsume(db: &FontDb, family: &str) {
+ const WORD: &str = "بَبَ"; // ب 0, fatha 2, ب 4, fatha 6
+ let set = |optical: bool, letter: Option| {
+ let mut t = text_with_harakat(WORD, family, Some(red()));
+ crate::edit::style_range(&mut t.runs, 0, WORD.len(), |st| st.optical_kerning = optical);
+ if let Some(at) = letter {
+ crate::edit::style_range(&mut t.runs, at, at + 2, |st| st.tsume = 100.0);
+ }
+ t
+ };
+ // Each glyph's place and advance: where a mark's ink leaves no blank space on the left, the
+ // Tsume of the line's first cluster only narrows its advance and moves no glyph.
+ let xs = |t: &TextObject| layout(db, t).glyphs.iter().flat_map(|g| [g.xf.as_coeffs()[4], g.advance]).collect::>();
+ assert!(xs(&set(true, None)).iter().zip(xs(&set(false, None))).any(|(a, b)| (a - b).abs() > 1e-6), "{family}: Optical moves the pair");
+ // Each letter in turn: the first one's cluster ends the pair, the second one's starts it.
+ for letter in [0, 4] {
+ let moved = |optical: bool| xs(&set(optical, Some(letter))).iter().zip(xs(&set(optical, None))).map(|(a, b)| a - b).collect::>();
+ let (without, with_optical) = (moved(false), moved(true));
+ assert!(without.iter().any(|m| m.abs() > 1e-3), "{family} {letter}: Tsume moves or narrows the glyphs: {without:?}");
+ assert!(
+ without.len() == with_optical.len() && without.iter().zip(&with_optical).all(|(a, b)| (a - b).abs() < 1e-6),
+ "{family} {letter}: {without:?} {with_optical:?}"
+ );
+ }
+}
+
#[test]
fn own_chars_need_the_same_setting_and_each_character_in_its_cluster() {
// بَبَب right to left: final beh (cluster 8), fatha and medial beh (cluster 4), fatha and
diff --git a/crates/text/src/tests/tsume.rs b/crates/text/src/tests/tsume.rs
index 72f0d69f19..bd2d7d9ccc 100644
--- a/crates/text/src/tests/tsume.rs
+++ b/crates/text/src/tests/tsume.rs
@@ -112,6 +112,25 @@ fn the_font_kerning_is_added_after_the_tsume() {
assert!(near(&before_kerned, &before_h) && before_h[0] < -10.0, "{before_kerned:?} {before_h:?}");
}
+#[test]
+fn optical_kerning_keeps_the_tsume() {
+ // Optical kerning spaces each pair as without the Tsume, and the Tsume stays on top: the
+ // characters move back as far with Optical kerning as without it.
+ let plain = point("HOH", style(100.0));
+ let optical = point("HOH", CharStyle { optical_kerning: true, ..style(100.0) });
+ let xs = |t: &TextObject| {
+ let l = layout(db(), t);
+ [0, 1, 2].map(|i| drawn_x(&l, i))
+ };
+ // The test font's Optical spacing differs from its own for these pairs.
+ assert!(!near(&xs(&optical), &xs(&plain)), "{:?} {:?}", xs(&optical), xs(&plain));
+ for at in [0, 1, 2] {
+ let without = moves(&plain, &with(&plain, at, |s| s.tsume = 100.0), &[0, 1, 2]);
+ let with_optical = moves(&optical, &with(&optical, at, |s| s.tsume = 100.0), &[0, 1, 2]);
+ assert!(without.iter().any(|m| *m < -1.0) && near(&with_optical, &without), "{at}: {without:?} {with_optical:?}");
+ }
+}
+
#[test]
fn a_letter_with_its_mark_takes_the_tsume_of_the_letter() {
let plain = point("H\u{301}O", style(100.0));
diff --git a/crates/tools/src/addons/corner_tool.rs b/crates/tools/src/addons/corner_tool.rs
index 177926837e..470795579e 100644
--- a/crates/tools/src/addons/corner_tool.rs
+++ b/crates/tools/src/addons/corner_tool.rs
@@ -311,6 +311,7 @@ impl Tool for CornerTool {
None => vec![],
}
}
+ PointerKind::TripleClick => vec![],
}
}
diff --git a/crates/tools/src/addons/extend_path.rs b/crates/tools/src/addons/extend_path.rs
index d1f54861ca..2269396f90 100644
--- a/crates/tools/src/addons/extend_path.rs
+++ b/crates/tools/src/addons/extend_path.rs
@@ -131,7 +131,7 @@ impl Tool for ExtendPathTool {
// Back where it started: nothing to keep.
if length == 0.0 { vec![Action::Cancel] } else { vec![preview, Action::Commit] }
}
- PointerKind::DoubleClick => vec![],
+ PointerKind::DoubleClick | PointerKind::TripleClick => vec![],
}
}
diff --git a/crates/tools/src/addons/parametric_shape.rs b/crates/tools/src/addons/parametric_shape.rs
index 68a42a665f..33700073c7 100644
--- a/crates/tools/src/addons/parametric_shape.rs
+++ b/crates/tools/src/addons/parametric_shape.rs
@@ -326,7 +326,7 @@ impl Tool for ParametricShapeTool {
self.hover(cx, ev.pos);
}
match ev.kind {
- PointerKind::Move => vec![],
+ PointerKind::Move | PointerKind::TripleClick => vec![],
PointerKind::Down => {
let tol = cx.point_tol();
let grip = selected(cx).and_then(|(id, s)| {
diff --git a/crates/tools/src/addons/slide_anchor.rs b/crates/tools/src/addons/slide_anchor.rs
index e24db4c50d..0bec99cf35 100644
--- a/crates/tools/src/addons/slide_anchor.rs
+++ b/crates/tools/src/addons/slide_anchor.rs
@@ -96,7 +96,7 @@ impl Tool for SlideAnchorTool {
// Back where it started: nothing to keep.
if t == 0.0 { vec![Action::Cancel] } else { vec![preview, Action::Commit] }
}
- PointerKind::DoubleClick => vec![],
+ PointerKind::DoubleClick | PointerKind::TripleClick => vec![],
}
}
diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs
index cd72f1dd40..c25ab8f670 100644
--- a/crates/tools/src/addons/smart_pen.rs
+++ b/crates/tools/src/addons/smart_pen.rs
@@ -527,6 +527,7 @@ impl Tool for SmartPenTool {
}
_ => vec![],
},
+ PointerKind::TripleClick => vec![],
}
}
diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs
index 2ad8ade0e4..00005e3c21 100644
--- a/crates/tools/src/builder.rs
+++ b/crates/tools/src/builder.rs
@@ -42,8 +42,8 @@ pub use live_paint::{
use live_paint::{check_live_paint_options, lp_color, lp_rgb_color};
pub use lookup::{
EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, LP_JOIN_TOL, SOURCES_NAME, builder_members, connected_edges, drawn_outlines,
- edge_near, edges, face_at, faces, flood_faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_takes, node_outline, outline_snap,
- path_contains, shape_builder_shapes, shapes_for, sources, visible_edge_near, visible_face_at,
+ edge_near, edges, face_at, faces, flood_faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_takes, lp_stroke_paint, node_outline,
+ outline_snap, path_contains, shape_builder_shapes, shapes_for, sources, visible_edge_near, visible_face_at,
};
pub use map::{
BuilderMap, HATCH, HIGHLIGHT_RED, Hit, MergeGeometry, MergeInput, PreparedMerge, Rest, Touched, hatch, maps_built, merge_geometry, merge_inputs,
diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs
index b5472659d5..235715a0b6 100644
--- a/crates/tools/src/builder/live_paint.rs
+++ b/crates/tools/src/builder/live_paint.rs
@@ -1,12 +1,14 @@
use super::cache::RegionCache;
use super::lookup::{
- connected_edges, flood_faces, is_live_paint, live_paint_at, live_paint_at_where, lp_stroke_paint, visible_edge_near, visible_face_at,
+ connected_edges, flood_faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_at_where, lp_stroke_paint, node_outline, visible_edge_near,
+ visible_face_at,
};
use super::map::{HIGHLIGHT_RED, sorted_roots};
use super::{
Action, Arc, BezPath, CLICK_TOL_PX, Cursor, Document, EDGE_NAME, FACE_NAME, FillRule, Mods, Node, NodeId, Overlay, Point, PointerEvent,
PointerKind, Rect, Tool, ToolContext, ToolKey, Value, color_swatches, json, json_ids, path_contains, pick_swatch, plain, swatch_chips,
};
+use vectorcraft_color::Paint;
// ---------- Live Paint Bucket ----------
@@ -174,6 +176,17 @@ enum LpPaint {
/// highlighted. The cursor is a filled bucket where a click fills a face, a brush where it paints
/// an edge and an empty bucket where it paints nothing; with Alt it is the Eyedropper.
///
+/// A double-click on a face fills it and the faces reached from it across edges that draw no
+/// stroke (`scope: "connected"`); on an edge it paints the edges joined to it that have its stroke.
+/// A triple-click on a face fills every face of the group with the face's fill, and on an edge it
+/// paints every edge of the group with the edge's stroke (`scope: "samePaint"`). Each click of a
+/// double-click or triple-click paints as it arrives, as its own undo step, and the paint compared
+/// is the one the face or edge had before the first of its clicks that painted it. A first click
+/// that made the Live Paint group counts when the face it filled is the clicked face. Shift and the
+/// options choose a face or an edge as for a click; with Alt or Cmd/Ctrl held a double-click or
+/// triple-click paints nothing. With Space held for the view tools, a click, double-click or triple-click paints
+/// nothing and no face or edge is highlighted.
+///
/// The Left and Right arrow keys without Shift, Alt or Cmd/Ctrl set the active paint (the fill,
/// or the stroke when the Stroke proxy is in front) to the color swatch before or after it in the
/// Swatches panel, wrapping around; from a color that is no swatch, Right picks the first swatch
@@ -184,10 +197,13 @@ enum LpPaint {
pub struct LivePaintBucketTool {
pub(super) cache: RegionCache,
pub(super) hover: LpHover,
- /// Where the pointer last moved, and whether Shift and Alt were held.
- at: Option<(Point, bool, bool)>,
+ /// Where the pointer last moved, and the modifiers held there.
+ at: Option<(Point, Mods)>,
/// The fill command and polyline previewed from the press's snapshot.
fill_drag: Option<(Value, Vec>)>,
+ /// The last [`LP_PRESSES`] presses, oldest first: the face or edge each one painted, with its
+ /// paint before that press, or None for a press that painted no face or edge.
+ presses: Vec>,
fills: bool,
strokes: bool,
highlight: bool,
@@ -200,6 +216,40 @@ pub struct LivePaintBucketTool {
picked: [Option; 2],
}
+/// The face or edge a Live Paint Bucket press paints.
+#[derive(Clone, Debug, PartialEq)]
+struct LpPress {
+ /// The face or edge; None for the face of the Live Paint group the press makes.
+ part: Option,
+ /// Where the press was.
+ at: Point,
+ /// Its fill (a face), or the stroke paint it draws with ([`lp_stroke_paint`], an edge), before
+ /// the press.
+ before: Paint,
+ /// The other faces or edges the double-click that followed the press reached, each with its
+ /// fill or drawn stroke paint before the double-click.
+ also: Vec<(NodeId, Paint)>,
+}
+
+/// The fill of the face under `p` in the Live Paint group that `roots` make: the fill of the
+/// front-most of their paths whose closed subpaths hold `p`, else none. Open subpaths bound no face.
+fn made_face_fill(doc: &Document, roots: &[NodeId], p: Point) -> Paint {
+ let mut leaves = vec![];
+ for n in roots.iter().filter_map(|id| doc.node(*id)) {
+ leaf_shapes(n, &mut leaves);
+ }
+ let holds = |l: &Node| {
+ node_outline(l).is_some_and(|(path, rule)| {
+ let closed = vectorcraft_geom::PathData::new(path.subpaths.into_iter().filter(|sp| sp.closed && sp.anchors.len() >= 2).collect());
+ !closed.is_empty() && path_contains(&closed, rule, p)
+ })
+ };
+ leaves.iter().rev().find(|l| holds(l)).map_or(Paint::None, |l| l.appearance.fill_paint())
+}
+
+/// How many presses the Live Paint Bucket keeps: the three of a triple-click.
+const LP_PRESSES: usize = 3;
+
/// Maximum points in one Live Paint fill path chunk.
pub const LP_FILL_CHUNK_POINTS: usize = 4096;
@@ -210,6 +260,7 @@ impl Default for LivePaintBucketTool {
hover: LpHover::None,
at: None,
fill_drag: None,
+ presses: Vec::new(),
fills: true,
strokes: false,
highlight: true,
@@ -274,14 +325,109 @@ impl LivePaintBucketTool {
}
}
- /// The highlight at `p` for a pointer with Shift and Alt held as given: none with Alt or with
- /// Highlight off, else the face or edge a click there paints. With Highlight off the selection's
- /// map is still made, for the cursor ([`Self::paints_at`]).
- fn hover_at(&mut self, cx: &ToolContext, p: Point, shift: bool, alt: bool) -> LpHover {
- if alt {
+ /// Note a press: what it paints, None when it paints no face or edge.
+ fn note_press(&mut self, press: Option) {
+ if self.presses.len() == LP_PRESSES {
+ self.presses.remove(0);
+ }
+ self.presses.push(press);
+ }
+
+ /// Note a press at `at` that paints face or edge (`edge`) `n`.
+ fn note_part(&mut self, n: &Node, edge: bool, at: Point) {
+ let before = if edge { lp_stroke_paint(n) } else { n.appearance.fill_paint() };
+ self.note_press(Some(LpPress { part: Some(n.id), at, before, also: vec![] }));
+ }
+
+ /// Note that the double-click after the last press also reaches `parts` of group `group`, with
+ /// the paint each has now (a face's fill, or an edge's drawn stroke paint with `edge`).
+ fn note_reached(&mut self, group: &Node, parts: Vec, edge: bool) {
+ let Some(Some(last)) = self.presses.last_mut() else { return };
+ let reached: std::collections::HashSet = parts.into_iter().filter(|id| last.part != Some(*id)).collect();
+ last.also = group
+ .children()
+ .into_iter()
+ .flatten()
+ .filter(|c| reached.contains(&c.id))
+ .map(|n| (n.id, if edge { lp_stroke_paint(n) } else { n.appearance.fill_paint() }))
+ .collect();
+ }
+
+ /// The paint `part` had before the first press of a click sequence of `clicks` presses that
+ /// painted `part`, or before the double-click after a press when that double-click reached it
+ /// (the sequence's first press counts when it made the group `part` is in and the face it
+ /// filled there is `part`); `now` when the last press did not paint it.
+ fn before(&self, cx: &ToolContext, part: NodeId, clicks: usize, now: Paint) -> Paint {
+ let Some(run) = self.presses.len().checked_sub(clicks).and_then(|from| self.presses.get(from..)) else { return now };
+ let made_part = |q: &LpPress| live_paint_at(cx.doc, q.at).and_then(|g| visible_face_at(cx.doc.node(g)?, q.at)).is_some_and(|f| f.id == part);
+ let on_part = |i: usize, q: &LpPress| q.part == Some(part) || (i == 0 && q.part.is_none() && made_part(q));
+ if !run.last().and_then(Option::as_ref).is_some_and(|q| on_part(run.len() - 1, q)) {
+ return now;
+ }
+ for (i, q) in run.iter().enumerate() {
+ let Some(q) = q else { continue };
+ if on_part(i, q) {
+ return q.before.clone();
+ }
+ if let Some((_, paint)) = q.also.iter().find(|(id, _)| *id == part) {
+ return paint.clone();
+ }
+ }
+ now
+ }
+
+ /// What a double-click (`scope` "connected", 2 `clicks`) or a triple-click ("samePaint", 3) at
+ /// `p` runs: the command a click there runs, with `scope`, and the paint it compares as `match`.
+ /// A double-click notes the other faces or edges it reaches, for the triple-click's `match`.
+ fn multi_click(&mut self, cx: &ToolContext, p: Point, mods: Mods, scope: &str, clicks: usize) -> Vec {
+ // With Alt held, with Space held for the view tools, or with Cmd/Ctrl held (its presses went
+ // to the selection tool Cmd lends), a double-click or triple-click paints nothing.
+ if mods.alt || mods.space || mods.cmd {
+ return vec![];
+ }
+ let point = json!([p.x, p.y]);
+ let paint = self.paints(mods.shift);
+ if matches!(paint, LpPaint::Strokes | LpPaint::Both)
+ && let Some((g, Some(e))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id))
+ {
+ let mut v = json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0), "scope": scope });
+ let like = self.before(cx, e.id, clicks, lp_stroke_paint(e));
+ if clicks == 2
+ && let Some(group) = cx.doc.node(g)
+ {
+ self.note_reached(group, connected_edges(group, e.id, &like), true);
+ }
+ if let Ok(like) = serde_json::to_value(like) {
+ v["match"] = like;
+ }
+ return vec![Action::Exec("livePaint.strokeEdge".into(), v)];
+ }
+ if !matches!(paint, LpPaint::Fills | LpPaint::Both) {
+ return vec![];
+ }
+ let Some((g, f)) = live_paint_at(cx.doc, p).and_then(|g| Some((g, visible_face_at(cx.doc.node(g)?, p)?))) else { return vec![] };
+ let mut v = json!({ "group": g.0, "point": point, "scope": scope });
+ if clicks == 2
+ && let Some(group) = cx.doc.node(g)
+ {
+ self.note_reached(group, flood_faces(group, f.id), false);
+ }
+ if scope == "samePaint"
+ && let Ok(like) = serde_json::to_value(self.before(cx, f.id, clicks, f.appearance.fill_paint()))
+ {
+ v["match"] = like;
+ }
+ vec![Action::Exec("livePaint.fill".into(), v)]
+ }
+
+ /// The highlight at `p` for a pointer with the modifiers `mods`: none with Alt, with Space held
+ /// for the view tools or with Highlight off, else the face or edge a click there paints. With
+ /// Highlight off the selection's map is still made, for the cursor ([`Self::paints_at`]).
+ fn hover_at(&mut self, cx: &ToolContext, p: Point, mods: Mods) -> LpHover {
+ if mods.alt || mods.space {
return LpHover::None;
}
- let target = self.target_at(cx, p, shift);
+ let target = self.target_at(cx, p, mods.shift);
if self.highlight { target } else { LpHover::None }
}
@@ -356,13 +502,19 @@ impl Tool for LivePaintBucketTool {
}
match ev.kind {
PointerKind::Move => {
- self.at = Some((p, ev.mods.shift, ev.mods.alt));
- self.hover = self.hover_at(cx, p, ev.mods.shift, ev.mods.alt);
+ self.at = Some((p, ev.mods));
+ self.hover = self.hover_at(cx, p, ev.mods);
vec![]
}
PointerKind::Down => {
self.hover = LpHover::None;
+ // With Space held for the view tools, a press paints nothing.
+ if ev.mods.space {
+ self.note_press(None);
+ return vec![];
+ }
if ev.mods.alt {
+ self.note_press(None);
if ev.mods.shift {
return crate::xform::eyedropper::sample_color_at(cx, p).map_or_else(Vec::new, |color| {
vec![Action::Exec("paint.sampleColor".into(), json!({ "color": crate::params::color_json(&color), "ids": [] }))]
@@ -387,36 +539,49 @@ impl Tool for LivePaintBucketTool {
let point = json!([p.x, p.y]);
let paint = self.paints(ev.mods.shift);
if matches!(paint, LpPaint::Strokes | LpPaint::Both)
- && let Some((g, Some(_))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id))
+ && let Some((g, Some(e))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id))
{
+ self.note_part(e, true, p);
return vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0) }))];
}
if !matches!(paint, LpPaint::Fills | LpPaint::Both) {
+ self.note_press(None);
return vec![];
}
if let Some(g) = live_paint_at(cx.doc, p) {
+ match cx.doc.node(g).and_then(|n| visible_face_at(n, p)) {
+ Some(f) => self.note_part(f, false, p),
+ None => self.note_press(None),
+ }
return self.begin_fill(json!({ "group": g.0, "point": point }), p);
}
if self.cache.at(cx, p).is_some() {
let roots = sorted_roots(cx.doc, &cx.selection.objects);
+ self.note_press(Some(LpPress { part: None, at: p, before: made_face_fill(cx.doc, &roots, p), also: vec![] }));
return self.begin_fill(json!({ "ids": json_ids(&roots), "point": point }), p);
}
+ self.note_press(None);
vec![]
}
PointerKind::Drag => self.drag_fill(p),
PointerKind::Up => {
// The swatch preview shows again at the release point.
- self.at = Some((p, ev.mods.shift, ev.mods.alt));
+ self.at = Some((p, ev.mods));
let mut acts = self.drag_fill(p);
if self.fill_drag.take().is_some() {
acts.push(Action::Commit);
}
acts
}
- _ => vec![],
+ PointerKind::DoubleClick => self.multi_click(cx, p, ev.mods, "connected", 2),
+ PointerKind::TripleClick => self.multi_click(cx, p, ev.mods, "samePaint", 3),
}
}
+ fn history_moved(&mut self) {
+ self.presses.clear();
+ }
+
/// Escape during a fill drag cancels it. Left and Right pick the color swatch before or after
/// the active paint, while no drag is on.
fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec {
@@ -455,6 +620,7 @@ impl Tool for LivePaintBucketTool {
}
fn deactivate(&mut self, _cx: &ToolContext) -> Vec {
+ self.presses.clear();
if self.fill_drag.take().is_some() { vec![Action::Commit] } else { vec![] }
}
@@ -469,7 +635,8 @@ impl Tool for LivePaintBucketTool {
// No chips during a fill drag, or while Alt makes the tool sample with the eyedropper.
if self.preview
&& !self.busy()
- && let Some((at, _, false)) = self.at
+ && let Some((at, mods)) = self.at
+ && !mods.alt
{
out.extend(swatch_chips(cx, at, Self::active_paint(cx), self.picked[Self::picked_slot(cx)], true));
}
@@ -520,8 +687,8 @@ impl Tool for LivePaintBucketTool {
// of a Live Paint group the hover takes no map.
loop {
self.cache.settle(wait);
- if let Some((p, shift, alt)) = self.at {
- self.hover = self.hover_at(cx, p, shift, alt);
+ if let Some((p, mods)) = self.at {
+ self.hover = self.hover_at(cx, p, mods);
}
if !wait || !self.cache.waiting() {
break;
@@ -776,6 +943,9 @@ impl Tool for LivePaintSelectionTool {
(false, false) => vec![Action::Exec("select.set".into(), json!({ "ids": json_ids(&ids) }))],
}
}
+ // The tool takes no action on a triple-click; its third press and release select as a
+ // click does.
+ PointerKind::TripleClick => vec![],
}
}
diff --git a/crates/tools/src/builder/lookup.rs b/crates/tools/src/builder/lookup.rs
index 8e17823332..daa9a34f82 100644
--- a/crates/tools/src/builder/lookup.rs
+++ b/crates/tools/src/builder/lookup.rs
@@ -130,7 +130,7 @@ fn lp_cells_around(p: Point) -> impl Iterator- {
/// The stroke paint Live Paint edge `edge` draws with: the paint of its topmost stroke that is shown
/// with a paint, a weight above 0 and an opacity above 0, or [`Paint::None`] when the edge is fully
/// transparent or has no such stroke.
-pub(super) fn lp_stroke_paint(edge: &Node) -> Paint {
+pub fn lp_stroke_paint(edge: &Node) -> Paint {
if edge.opacity <= 0.0 {
return Paint::None;
}
diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs
index 4c9da58425..66db1e550c 100644
--- a/crates/tools/src/builder/tests.rs
+++ b/crates/tools/src/builder/tests.rs
@@ -1124,6 +1124,287 @@ fn bucket_click_fills_face_and_shift_click_strokes_edge() {
assert_eq!(id, "livePaint.strokeEdge");
}
+/// A double-click runs a click's command with `scope: "connected"` and a triple-click with
+/// `"samePaint"`, matching the paint the face or edge had before the first click there.
+#[test]
+fn bucket_double_and_triple_click_widen_what_a_click_paints() {
+ let (d, gid, f2, e) = live_group_doc();
+ let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0));
+ let mut painted = d.clone();
+ painted.node_mut(f2).unwrap().appearance.set_fill(red.clone());
+ painted.node_mut(e).unwrap().appearance.set_stroke(red.clone());
+ let s = Selection::default();
+ let p = paint();
+ let (cx, later) = (cx(&d, &s, &p), cx(&painted, &s, &p));
+ let face_before = serde_json::to_value(d.node(f2).unwrap().appearance.fill_paint()).unwrap();
+ let edge_before = serde_json::to_value(d.node(e).unwrap().appearance.stroke_paint()).unwrap();
+ let red_json = serde_json::to_value(&red).unwrap();
+ assert_ne!(face_before, red_json);
+ assert_ne!(edge_before, red_json);
+ let fill = |scope: &str, like: Option<&Value>| {
+ let mut v = json!({ "group": gid.0, "point": [75.0, 25.0], "scope": scope });
+ if let Some(like) = like {
+ v["match"] = like.clone();
+ }
+ vec![Action::Exec("livePaint.fill".into(), v)]
+ };
+ let click = |t: &mut LivePaintBucketTool, cx: &ToolContext, x: f64, m: Mods| {
+ t.pointer(cx, &ev(PointerKind::Down, x, 25.0).with_mods(m));
+ t.pointer(cx, &ev(PointerKind::Up, x, 25.0).with_mods(m));
+ };
+ let mut t = LivePaintBucketTool::default();
+ // The clicks paint the face as they arrive; the triple-click matches the fill from before them.
+ click(&mut t, &cx, 75.0, Mods::default());
+ click(&mut t, &later, 75.0, Mods::default());
+ assert_eq!(t.pointer(&later, &ev(PointerKind::DoubleClick, 75.0, 25.0)), fill("connected", None));
+ click(&mut t, &later, 75.0, Mods::default());
+ assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), fill("samePaint", Some(&face_before)));
+ // A new click there starts again from the fill it finds.
+ click(&mut t, &later, 75.0, Mods::default());
+ assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), fill("samePaint", Some(&red_json)));
+ // A click before the triple-click's own three is not part of it.
+ let mut t = LivePaintBucketTool::default();
+ click(&mut t, &cx, 75.0, Mods::default());
+ for _ in 0..3 {
+ click(&mut t, &later, 75.0, Mods::default());
+ }
+ assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), fill("samePaint", Some(&red_json)));
+ // Shift: the edge, matching its stroke from before the first click.
+ let shift = Mods { shift: true, ..Default::default() };
+ let stroke = |scope: &str, like: &Value| {
+ vec![Action::Exec(
+ "livePaint.strokeEdge".into(),
+ json!({ "group": gid.0, "point": [51.0, 25.0], "tolerance": 4.0, "scope": scope, "match": like }),
+ )]
+ };
+ click(&mut t, &cx, 51.0, shift);
+ click(&mut t, &later, 51.0, shift);
+ assert_eq!(t.pointer(&later, &ev(PointerKind::DoubleClick, 51.0, 25.0).with_mods(shift)), stroke("connected", &edge_before));
+ click(&mut t, &later, 51.0, shift);
+ assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 51.0, 25.0).with_mods(shift)), stroke("samePaint", &edge_before));
+ // With Alt or Space held, or with both options off, a double-click or triple-click paints nothing.
+ let alt = Mods { alt: true, ..Default::default() };
+ let space = Mods { space: true, ..Default::default() };
+ for k in [PointerKind::DoubleClick, PointerKind::TripleClick] {
+ assert!(t.pointer(&cx, &ev(k, 75.0, 25.0).with_mods(alt)).is_empty(), "{k:?}");
+ assert!(t.pointer(&cx, &ev(k, 75.0, 25.0).with_mods(Mods { cmd: true, ..Default::default() })).is_empty(), "{k:?} with Cmd");
+ assert!(t.pointer(&cx, &ev(k, 75.0, 25.0).with_mods(space)).is_empty(), "{k:?} with Space");
+ assert!(t.pointer(&cx, &ev(k, 51.0, 25.0).with_mods(Mods { shift: true, ..space })).is_empty(), "{k:?} with Shift and Space");
+ }
+ // A press with Space held paints nothing either.
+ for m in [space, Mods { shift: true, ..space }] {
+ for (k, x) in [(PointerKind::Down, 75.0), (PointerKind::Up, 75.0), (PointerKind::Down, 51.0), (PointerKind::Up, 51.0)] {
+ assert!(t.pointer(&cx, &ev(k, x, 25.0).with_mods(m)).is_empty(), "{k:?} at {x} with {m:?}");
+ }
+ }
+ t.set_option("paintFills", &json!(false));
+ for k in [PointerKind::DoubleClick, PointerKind::TripleClick] {
+ assert!(t.pointer(&cx, &ev(k, 75.0, 25.0)).is_empty(), "{k:?}");
+ }
+ // Outside every face, nothing is painted.
+ t.set_option("paintFills", &json!(true));
+ assert!(t.pointer(&cx, &ev(PointerKind::DoubleClick, 400.0, 400.0)).is_empty());
+}
+
+/// A triple-click whose third click lands on a face the double-click's flood filled matches that
+/// face's fill from before the double-click.
+#[test]
+fn bucket_triple_click_on_a_face_the_double_click_flooded_matches_its_earlier_fill() {
+ let (mut d, gid, f2, _) = live_group_doc();
+ let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0));
+ let blue = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0));
+ let f1 = crate::builder::face_at(d.node(gid).unwrap(), Point::new(25.0, 25.0)).unwrap().id;
+ for f in [f1, f2] {
+ d.node_mut(f).unwrap().appearance.set_fill(red.clone());
+ }
+ let mut first = d.clone();
+ first.node_mut(f1).unwrap().appearance.set_fill(blue.clone());
+ let mut flooded = first.clone();
+ flooded.node_mut(f2).unwrap().appearance.set_fill(blue.clone());
+ let s = Selection::default();
+ let p = paint();
+ let (start, first, flooded) = (cx(&d, &s, &p), cx(&first, &s, &p), cx(&flooded, &s, &p));
+ let mut t = LivePaintBucketTool::default();
+ let click = |t: &mut LivePaintBucketTool, cx: &ToolContext, x: f64| {
+ t.pointer(cx, &ev(PointerKind::Down, x, 25.0));
+ t.pointer(cx, &ev(PointerKind::Up, x, 25.0));
+ };
+ click(&mut t, &start, 25.0);
+ click(&mut t, &first, 25.0);
+ t.pointer(&first, &ev(PointerKind::DoubleClick, 25.0, 25.0));
+ click(&mut t, &flooded, 75.0);
+ let like = serde_json::to_value(&red).unwrap();
+ assert_eq!(
+ t.pointer(&flooded, &ev(PointerKind::TripleClick, 75.0, 25.0)),
+ vec![Action::Exec("livePaint.fill".into(), json!({ "group": gid.0, "point": [75.0, 25.0], "scope": "samePaint", "match": like }))]
+ );
+}
+
+/// On an edge that stores a stroke paint but draws none (its stroke hidden, or the edge fully
+/// transparent), a double-click or triple-click matches no paint, with or without the clicks
+/// before it.
+#[test]
+fn bucket_multi_click_on_an_edge_matches_the_paint_it_draws() {
+ let (mut d, gid, _, e) = live_group_doc();
+ d.node_mut(e).unwrap().appearance.set_stroke(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 0.0)));
+ let mut hidden = d.clone();
+ hidden.node_mut(e).unwrap().appearance.stroke_mut().unwrap().visible = false;
+ let mut clear = d.clone();
+ clear.node_mut(e).unwrap().opacity = 0.0;
+ let none = serde_json::to_value(vectorcraft_color::Paint::None).unwrap();
+ let s = Selection::default();
+ let p = paint();
+ let shift = Mods { shift: true, ..Default::default() };
+ let stroke = |scope: &str| {
+ vec![Action::Exec(
+ "livePaint.strokeEdge".into(),
+ json!({ "group": gid.0, "point": [51.0, 25.0], "tolerance": 4.0, "scope": scope, "match": none }),
+ )]
+ };
+ for doc in [&hidden, &clear] {
+ let cx = cx(doc, &s, &p);
+ let mut t = LivePaintBucketTool::default();
+ assert_eq!(t.pointer(&cx, &ev(PointerKind::DoubleClick, 51.0, 25.0).with_mods(shift)), stroke("connected"));
+ for _ in 0..3 {
+ t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(shift));
+ t.pointer(&cx, &ev(PointerKind::Up, 51.0, 25.0).with_mods(shift));
+ }
+ assert_eq!(t.pointer(&cx, &ev(PointerKind::TripleClick, 51.0, 25.0).with_mods(shift)), stroke("samePaint"));
+ }
+}
+
+/// A triple-click whose first click makes the Live Paint group matches the fill of the face the
+/// group makes there: an open path in front, whose outline bounds no face, does not give it.
+#[test]
+fn bucket_triple_click_on_a_made_group_skips_open_paths() {
+ use vectorcraft_color::{Color, Paint};
+ use vectorcraft_geom::{PathData, SubPath};
+ let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
+ let mut d = Document::new(500.0, 500.0);
+ let l = d.layers[0].id;
+ let back = d.alloc_id();
+ let mut look = Appearance::default_art();
+ look.set_fill(red.clone());
+ d.insert(Some(l), 0, Node::path(back, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look)).unwrap();
+ // An open U around (75, 25), filled blue.
+ let u = [Point::new(60.0, 5.0), Point::new(60.0, 45.0), Point::new(90.0, 45.0), Point::new(90.0, 5.0)];
+ let front = d.alloc_id();
+ let mut look = Appearance::default_art();
+ look.set_fill(blue);
+ d.insert(Some(l), 1, Node::path(front, PathData::single(SubPath::polyline(&u, false)), look)).unwrap();
+ // The face the planar map makes there takes its fill from the square, as the group's would.
+ let shapes: Vec
= [back, front]
+ .iter()
+ .enumerate()
+ .filter_map(|(k, id)| node_outline(d.node(*id)?).map(|(path, rule)| vectorcraft_pathops::Shape::new(path, rule, k as u64)))
+ .collect();
+ let (regions, _) = vectorcraft_pathops::live_paint(&shapes);
+ let face = regions.iter().find(|r| r.contains(Point::new(75.0, 25.0))).expect("a face at (75, 25)");
+ assert_eq!(face.top(), Some(0), "the square is the face's top shape");
+ let mut s = Selection::default();
+ s.set([back, front]);
+ let p = paint();
+ let (made, ..) = live_group_doc();
+ let none = Selection::default();
+ let (cx, later) = (cx(&d, &s, &p), cx(&made, &none, &p));
+ let mut t = LivePaintBucketTool::default();
+ t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0));
+ t.pointer(&cx, &ev(PointerKind::Up, 75.0, 25.0));
+ for _ in 0..2 {
+ t.pointer(&later, &ev(PointerKind::Down, 75.0, 25.0));
+ t.pointer(&later, &ev(PointerKind::Up, 75.0, 25.0));
+ }
+ let acts = t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0));
+ let [Action::Exec(id, v)] = acts.as_slice() else { panic!("{acts:?}") };
+ assert_eq!(id, "livePaint.fill");
+ assert_eq!(v["match"], serde_json::to_value(&red).unwrap());
+}
+
+/// A triple-click whose first click makes the Live Paint group on one face and whose other two
+/// clicks fill another face matches the fill the second face had before the first click on it,
+/// not the fill under the first click or the fill the clicks gave it.
+#[test]
+fn bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face() {
+ use vectorcraft_color::{Color, Paint};
+ let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
+ let mut d = Document::new(500.0, 500.0);
+ let l = d.layers[0].id;
+ let square = d.alloc_id();
+ let mut look = Appearance::default_art();
+ look.set_fill(red.clone());
+ d.insert(Some(l), 0, Node::path(square, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), look)).unwrap();
+ let mut s = Selection::default();
+ s.set([square]);
+ let p = paint();
+ let (made, _, f2, _) = live_group_doc();
+ let mut painted = made.clone();
+ painted.node_mut(f2).unwrap().appearance.set_fill(blue.clone());
+ let none = Selection::default();
+ let (cx, later, after) = (cx(&d, &s, &p), cx(&made, &none, &p), cx(&painted, &none, &p));
+ let mut t = LivePaintBucketTool::default();
+ // The first click makes the group and fills the face at (25, 25); the next two fill (75, 25),
+ // the first of them painting it blue.
+ t.pointer(&cx, &ev(PointerKind::Down, 25.0, 25.0));
+ t.pointer(&cx, &ev(PointerKind::Up, 25.0, 25.0));
+ for ctx in [&later, &after] {
+ t.pointer(ctx, &ev(PointerKind::Down, 75.0, 25.0));
+ t.pointer(ctx, &ev(PointerKind::Up, 75.0, 25.0));
+ }
+ let acts = t.pointer(&after, &ev(PointerKind::TripleClick, 75.0, 25.0));
+ let [Action::Exec(id, v)] = acts.as_slice() else { panic!("{acts:?}") };
+ assert_eq!(id, "livePaint.fill");
+ let own = serde_json::to_value(made.node(f2).unwrap().appearance.fill_paint()).unwrap();
+ assert_ne!(own, serde_json::to_value(&red).unwrap());
+ assert_ne!(own, serde_json::to_value(&blue).unwrap());
+ assert_eq!(v["match"], own);
+}
+
+/// A triple-click whose clicks land on one face, another face, then the first face again matches
+/// the fill the first face had before the first click on it, not the fill that click gave it.
+#[test]
+fn bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fill() {
+ use vectorcraft_color::{Color, Paint};
+ let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
+ let (d, gid, f2, _) = live_group_doc();
+ let mut painted = d.clone();
+ painted.node_mut(f2).unwrap().appearance.set_fill(red.clone());
+ let s = Selection::default();
+ let p = paint();
+ let (cx, later) = (cx(&d, &s, &p), cx(&painted, &s, &p));
+ let mut t = LivePaintBucketTool::default();
+ // The first click paints the face at (75, 25) red; the second fills the face at (25, 25).
+ for (ctx, x) in [(&cx, 75.0), (&later, 25.0), (&later, 75.0)] {
+ t.pointer(ctx, &ev(PointerKind::Down, x, 25.0));
+ t.pointer(ctx, &ev(PointerKind::Up, x, 25.0));
+ }
+ let acts = t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0));
+ let own = serde_json::to_value(d.node(f2).unwrap().appearance.fill_paint()).unwrap();
+ assert_ne!(own, serde_json::to_value(&red).unwrap());
+ assert_eq!(
+ acts,
+ vec![Action::Exec("livePaint.fill".into(), json!({ "group": gid.0, "point": [75.0, 25.0], "scope": "samePaint", "match": own }))]
+ );
+}
+
+/// With Space held for the view tools, the pointer outlines no face or edge, as a press there
+/// paints nothing.
+#[test]
+fn bucket_highlights_nothing_with_space_held() {
+ let (d, ..) = live_group_doc();
+ let s = Selection::default();
+ let p = paint();
+ let cx = cx(&d, &s, &p);
+ let mut t = LivePaintBucketTool::default();
+ let outlined = |t: &LivePaintBucketTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Path { .. }));
+ let space = Mods { space: true, ..Default::default() };
+ for (x, m) in [(75.0, space), (51.0, Mods { shift: true, ..space })] {
+ t.pointer(&cx, &ev(PointerKind::Move, x, 25.0).with_mods(m));
+ assert!(!outlined(&t), "at {x} with {m:?}");
+ }
+ t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0));
+ assert!(outlined(&t));
+}
+
/// After a fill drag, the cursor swatch preview shows at the release point, not where the pointer
/// last moved before the press.
#[test]
@@ -2292,6 +2573,22 @@ fn live_paint_selection_double_click_selects_connected_faces_or_edges() {
assert!(dbl(&mut t, 25.0, 1.0, alt).is_empty());
}
+#[test]
+fn live_paint_selection_triple_click_adds_nothing_to_its_clicks() {
+ let mut d = Document::new(500.0, 500.0);
+ let (_, [a, ..], _) = live_strip(&mut d);
+ let s = Selection::default();
+ let p = paint();
+ let cx = cx(&d, &s, &p);
+ let mut t = LivePaintSelectionTool::default();
+ // The third click's press and release select the face under the pointer, as a click does.
+ assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 25.0, 25.0)), vec![Action::Exec("select.set".into(), json!({ "ids": [a.0] }))]);
+ for m in [Mods::default(), Mods { alt: true, ..Default::default() }, Mods { shift: true, ..Default::default() }] {
+ assert!(t.pointer(&cx, &ev(PointerKind::TripleClick, 25.0, 25.0).with_mods(m)).is_empty());
+ assert!(t.pointer(&cx, &ev(PointerKind::TripleClick, 25.0, 1.0).with_mods(m)).is_empty());
+ }
+}
+
#[test]
fn live_paint_selection_double_click_skips_locked_groups_and_art_outside_isolation() {
let mut d = Document::new(500.0, 500.0);
diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs
index ff716bf171..0245f75112 100644
--- a/crates/tools/src/cropimage.rs
+++ b/crates/tools/src/cropimage.rs
@@ -169,6 +169,7 @@ impl Tool for CropImageTool {
PointerKind::Up => self.drag = None,
PointerKind::DoubleClick => return self.apply(cx),
PointerKind::Move => self.last = ev.pos,
+ PointerKind::TripleClick => {}
}
vec![]
}
diff --git a/crates/tools/src/distort/puppet.rs b/crates/tools/src/distort/puppet.rs
index f141378382..2ca6ec0631 100644
--- a/crates/tools/src/distort/puppet.rs
+++ b/crates/tools/src/distort/puppet.rs
@@ -422,7 +422,7 @@ impl Tool for PuppetWarpTool {
}
None => vec![],
},
- PointerKind::DoubleClick => vec![],
+ PointerKind::DoubleClick | PointerKind::TripleClick => vec![],
}
}
/// Delete/Backspace remove the selected pins; with none selected they are the shortcut's
diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs
index e7050d3a79..4ebbac4981 100644
--- a/crates/tools/src/distort/width.rs
+++ b/crates/tools/src/distort/width.rs
@@ -300,6 +300,7 @@ impl Tool for WidthTool {
self.hover = Self::spot_at(cx, p);
vec![]
}
+ PointerKind::TripleClick => vec![],
PointerKind::DoubleClick => {
let Some(spot) = Self::spot_at(cx, p) else { return vec![] };
let Some((w, _)) = Self::hit(cx, &spot, p) else {
diff --git a/crates/tools/src/draw2/curvature.rs b/crates/tools/src/draw2/curvature.rs
index 02087d997a..06ad1c1230 100644
--- a/crates/tools/src/draw2/curvature.rs
+++ b/crates/tools/src/draw2/curvature.rs
@@ -653,6 +653,7 @@ impl Tool for CurvatureTool {
self.pts[i].1 = !self.pts[i].1;
vec![Action::Exec("path.curvature".into(), self.params())]
}
+ PointerKind::TripleClick => vec![],
}
}
fn notify(&mut self, cx: &ToolContext, what: &str) {
diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs
index 9b53d2404c..5362147b97 100644
--- a/crates/tools/src/input.rs
+++ b/crates/tools/src/input.rs
@@ -29,6 +29,9 @@ pub enum PointerKind {
/// Moved with no button (hover).
Move,
DoubleClick,
+ /// The third click of a triple-click, after its press and release (the second click's
+ /// release sends [`PointerKind::DoubleClick`]).
+ TripleClick,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs
index a0ab57ae87..24a21d08ca 100644
--- a/crates/tools/src/pen.rs
+++ b/crates/tools/src/pen.rs
@@ -449,7 +449,7 @@ impl Tool for PenTool {
}
vec![Action::Commit]
}
- PointerKind::DoubleClick => vec![],
+ PointerKind::DoubleClick | PointerKind::TripleClick => vec![],
}
}
fn key(&mut self, cx: &ToolContext, key: ToolKey, _m: Mods) -> Vec {
diff --git a/crates/tools/src/printtiling.rs b/crates/tools/src/printtiling.rs
index b4e0e06d0c..a28382daf8 100644
--- a/crates/tools/src/printtiling.rs
+++ b/crates/tools/src/printtiling.rs
@@ -68,7 +68,7 @@ impl Tool for PrintTilingTool {
self.drag = None;
vec![Action::Exec("print.tiling.set".into(), json!({ "reset": true }))]
}
- PointerKind::Move => vec![],
+ PointerKind::Move | PointerKind::TripleClick => vec![],
}
}
diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs
index dd561bc616..e18754f0ca 100644
--- a/crates/tools/src/text/tool.rs
+++ b/crates/tools/src/text/tool.rs
@@ -113,6 +113,7 @@ impl Tool for TypeTool {
}
vec![]
}
+ PointerKind::TripleClick => vec![],
PointerKind::Move => {
// The type being edited is no target: its guides would only point at itself.
self.snap.hover(cx, ev.pos, self.editing.as_slice(), None);
diff --git a/crates/tools/src/touchtype.rs b/crates/tools/src/touchtype.rs
index 018a65aefc..d195f276e4 100644
--- a/crates/tools/src/touchtype.rs
+++ b/crates/tools/src/touchtype.rs
@@ -387,7 +387,7 @@ impl Tool for TouchTypeTool {
Some(d) if d.began => vec![Action::Commit],
_ => vec![],
},
- PointerKind::DoubleClick | PointerKind::Move => vec![],
+ PointerKind::DoubleClick | PointerKind::TripleClick | PointerKind::Move => vec![],
}
}
diff --git a/crates/tools/src/xform/gradient.rs b/crates/tools/src/xform/gradient.rs
index 9a61c98591..5a3565f3a9 100644
--- a/crates/tools/src/xform/gradient.rs
+++ b/crates/tools/src/xform/gradient.rs
@@ -582,7 +582,7 @@ impl Tool for GradientTool {
let at = a.stop_point(cx, i).unwrap_or(ev.pos);
vec![Self::select_stop(i), Action::Dialog("gradientStop".into(), json!({ "index": i, "x": at.x, "y": at.y }))]
}
- PointerKind::Move => vec![],
+ PointerKind::Move | PointerKind::TripleClick => vec![],
}
}
diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs
index 263c0ea5e4..395b235e4a 100644
--- a/crates/tools/src/xform/transform.rs
+++ b/crates/tools/src/xform/transform.rs
@@ -272,6 +272,7 @@ impl Tool for TransformTool {
None => vec![],
}
}
+ PointerKind::TripleClick => vec![],
PointerKind::Move => {
if self.drag.is_none() {
self.hover = if cx.selection.is_empty() { vec![] } else { snap_pick(cx, p).1 };
diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs
index 286b4d4d02..8c6d669e14 100644
--- a/crates/ui-egui/src/caches.rs
+++ b/crates/ui-egui/src/caches.rs
@@ -164,6 +164,17 @@ pub struct CacheKey {
/// The display profile the frame is converted into ([`crate::display_profile::DisplayProfile::key`]),
/// 0 for none.
pub display: u64,
+ /// The paper under the art that translucent art is blended with before the conversion
+ /// ([`crate::display_profile::convert_over`]). None without a display profile, and in Outline.
+ pub backdrop: Option>,
+}
+
+impl CacheKey {
+ /// [`Self::backdrop`] with the zoom its grid's cells are measured at, as
+ /// [`crate::display_profile::convert_over`] takes it.
+ pub(crate) fn over(&self) -> Option<(&crate::display_profile::Backdrop, f64)> {
+ self.backdrop.as_deref().map(|b| (b, self.zoom))
+ }
}
#[derive(Clone, Copy, Debug, Default)]
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 5c30f96246..9120fe0cff 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -631,6 +631,7 @@ fn cache_key(
trace_source: app.ui.trace_hold_source.clone(),
// Preferences › Performance › Use Monitor Profile for Canvas.
display: app.display_profile.key(app.session.prefs.monitor_profile_display),
+ backdrop: backdrop(app, st, app.outline_view()),
}
}
@@ -895,9 +896,10 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
}
if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) {
let renderer = &mut app.canvas.renderer;
- let mut part =
- effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, Affine::translate((-f64::from(x0), -f64::from(y0))) * view, &opts));
- crate::display_profile::convert(display.as_deref(), &mut part.pixels);
+ let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * view;
+ let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, &opts));
+ let width = part.width;
+ crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over());
let color = color_image(&part);
let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR };
tex.set_partial([x0 as usize, y0 as usize], color, options);
@@ -935,7 +937,8 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
let renderer = &mut app.canvas.renderer;
let mut img = effects.view(|| renderer.render(doc, w, h, view, &opts));
effects.first_view_done();
- crate::display_profile::convert(display.as_deref(), &mut img.pixels);
+ let width = img.width;
+ crate::display_profile::convert_over(display.as_deref(), &mut img.pixels, width, view, key.over());
upload(app, ui.ctx(), img, pixel.is_some());
app.canvas.key = Some(key.clone());
app.canvas.shown = Some((doc.clone(), opts.clone()));
@@ -990,13 +993,11 @@ fn paint_paper(
let on_display = |c: Color32| crate::display_profile::color32(display.as_deref(), c);
if !shows_artboards(app) {
// View › Hide Artboards: no edges and no pasteboard, the whole canvas paper (#4038).
- let setup = &doc.setup;
- painter.rect_filled(rect, 0.0, on_display(if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }));
+ painter.rect_filled(rect, 0.0, on_display(paper_color(&doc.setup)));
} else {
let setup = &doc.setup;
- let grid = (st.transparency_grid && setup.background == vectorcraft_doc::Background::Transparent)
- .then(|| checker_texture(ui.ctx(), setup, display.as_deref()));
- let paper = if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE };
+ let grid = shows_transparency_grid(st).then(|| checker_texture(ui.ctx(), setup, display.as_deref()));
+ let paper = paper_color(setup);
for ab in &doc.artboards {
let q = xf.quad(ab.rect);
// Hard 2 pt drop shadow, right and bottom (measured: #4d4d4d then #565656 on #606060).
@@ -1006,14 +1007,52 @@ fn paint_paper(
match &grid {
Some((tex, cell)) => checker(painter, &q, ab.rect, xf.zoom, tex.id(), *cell),
None => {
- let fill = ab.color.map_or(paper, |c| crate::panels::c32(&c) * paper);
- painter.add(Shape::convex_polygon(q, on_display(fill), Stroke::NONE));
+ painter.add(Shape::convex_polygon(q, on_display(artboard_paper(ab, paper)), Stroke::NONE));
}
}
}
}
}
+/// The color of the paper: Simulate Colored Paper's, else white.
+fn paper_color(setup: &vectorcraft_doc::DocSetup) -> Color32 {
+ if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }
+}
+
+/// The color of artboard `ab`'s paper, the paper `paper`: an artboard with a background color
+/// multiplies it with the paper, each sRGB channel artboard × paper / 255, rounded.
+fn artboard_paper(ab: &vectorcraft_doc::Artboard, paper: Color32) -> Color32 {
+ ab.color.map_or(paper, |c| crate::panels::c32(&c) * paper)
+}
+
+/// The transparency grid covers the artboards of document `st`: it is shown, and the Background
+/// Contents are transparent.
+fn shows_transparency_grid(st: &vectorcraft_engine::DocState) -> bool {
+ st.transparency_grid && st.doc.setup.background == vectorcraft_doc::Background::Transparent
+}
+
+/// The paper [`paint_paper`] draws for document `st`, which translucent art is blended with before
+/// the display profile's conversion. None without a display profile, and in Outline (`outline`),
+/// whose white canvas is the interface's.
+fn backdrop(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, outline: bool) -> Option> {
+ if outline || app.display_profile.transform(app.session.prefs.monitor_profile_display).is_none() {
+ return None;
+ }
+ let rgb = |c: Color32| [c.r(), c.g(), c.b()];
+ let setup = &st.doc.setup;
+ let paper = paper_color(setup);
+ let b = if shows_artboards(app) {
+ crate::display_profile::Backdrop {
+ everywhere: None,
+ artboards: st.doc.artboards.iter().map(|ab| (ab.rect, rgb(artboard_paper(ab, paper)))).collect(),
+ grid: shows_transparency_grid(st).then(|| (setup.grid_colors.map(|c| rgb(crate::panels::c32(&c))), setup.grid_size.cell())),
+ }
+ } else {
+ crate::display_profile::Backdrop { everywhere: Some(rgb(paper)), artboards: vec![], grid: None }
+ };
+ Some(std::sync::Arc::new(b))
+}
+
/// The last rendered frame, placed through the current view while a new one is on its way.
fn reproject_frame(app: &VectorcraftApp, painter: &egui::Painter, xf: &Xf, rect: egui::Rect, (key_doc, rotation): (usize, f64)) {
if let (Some(tex), Some(k)) = (&app.canvas.texture, &app.canvas.key)
diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs
index 57dbef9ff8..88bb262844 100644
--- a/crates/ui-egui/src/canvas/input.rs
+++ b/crates/ui-egui/src/canvas/input.rs
@@ -179,6 +179,12 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo
{
double_click(app, ui, &f, p);
}
+ if resp.triple_clicked()
+ && !f.modal
+ && let Some(p) = at
+ {
+ triple_click(app, ui, &f, p);
+ }
if drag.is_some() || pointer.is_moving() || mods_changed {
ui.ctx().request_repaint();
}
@@ -591,6 +597,23 @@ fn double_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) {
}
}
+/// A triple-click at `p`: the tool gets it, unless it is on an artboard's name.
+fn triple_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) {
+ let Pointing { m, space, xf, view, .. } = *f;
+ if artboard_name_at(app, ui, &xf, p).is_some() {
+ return;
+ }
+ let ev = PointerEvent {
+ kind: PointerKind::TripleClick,
+ pos: xf.to_doc(p),
+ mods: mods(m, space),
+ backquote: ui.input(|i| i.key_down(egui::Key::Backtick)),
+ pressure: 1.0,
+ pen: None,
+ };
+ dispatch(app, &ev, view);
+}
+
/// Where `button` went up in this frame, if it did.
fn release_pos(ui: &Ui, button: egui::PointerButton) -> Option {
ui.input(|i| {
diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs
index 0a26f26843..50fd2c9583 100644
--- a/crates/ui-egui/src/canvas/panes.rs
+++ b/crates/ui-egui/src/canvas/panes.rs
@@ -11,7 +11,7 @@ use super::grid::LineLook;
use super::outline::{c32, node_outline, stroke_path, too_many_anchors};
use super::view::fit_zoom;
use super::{
- Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, cache_key,
+ Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, cache_key,
dim_on_canvas, frame_options, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, rulers,
shows_artboards, textured_quad, vec2, view_rects,
};
@@ -29,7 +29,7 @@ type Slot = (u64, u32);
pub struct Panes {
/// Renders off the UI thread (None: on it, as on wasm).
worker: Option>,
- worker_started: bool,
+ pub(crate) worker_started: bool,
/// Renders on the UI thread when there is no worker.
renderer: Option,
/// By slot: the render shown and what it shows.
@@ -112,11 +112,11 @@ impl Panes {
let cms = vectorcraft_engine::cmd::colormgmt::doc_cms(&doc);
let mut queued = false;
if let Some(worker) = &self.worker {
- let (job_doc, job_opts, job_display, job_cms) = (doc.clone(), opts.clone(), display.clone(), cms.clone());
+ let (job_doc, job_opts, job_display, job_cms, job_key) = (doc.clone(), opts.clone(), display.clone(), cms.clone(), key.clone());
queued = worker.submit(
slot,
(slot, key.clone()),
- Box::new(move |r| Some(render_pane(r, (&job_doc, w, h, view, &job_opts), job_display.as_deref(), job_cms))),
+ Box::new(move |r| Some(render_pane(r, (&job_doc, w, h, view, &job_opts), job_display.as_deref(), job_cms, job_key.over()))),
);
if queued {
self.pending.insert(slot, key.clone());
@@ -126,7 +126,7 @@ impl Panes {
}
if !queued {
let r = self.renderer.get_or_insert_with(vectorcraft_render::Renderer::new);
- let img = render_pane(r, (&doc, w, h, view, &opts), display.as_deref(), cms);
+ let img = render_pane(r, (&doc, w, h, view, &opts), display.as_deref(), cms, key.over());
self.upload(ctx, slot, key, &img);
}
}
@@ -146,15 +146,18 @@ impl Panes {
}
/// Render `doc` (`w` × `h` pixels through `view`, with `opts`) through the color settings `cms`,
-/// then convert it into the display profile `display`.
+/// then convert it into the display profile `display`, blended with the backdrop `over` first
+/// ([`crate::display_profile::convert_over`]).
fn render_pane(
r: &mut vectorcraft_render::Renderer,
(doc, w, h, view, opts): (&vectorcraft_doc::Document, u32, u32, Affine, &vectorcraft_render::RenderOptions),
display: Option<&vectorcraft_color::cms::display::DisplayTransform>,
cms: Arc,
+ over: Option<(&crate::display_profile::Backdrop, f64)>,
) -> vectorcraft_render::Rendered {
let mut img = vectorcraft_color::cms::with_active(cms, || r.render(doc, w, h, view, opts));
- crate::display_profile::convert(display, &mut img.pixels);
+ let width = img.width;
+ crate::display_profile::convert_over(display, &mut img.pixels, width, view, over);
img
}
@@ -348,6 +351,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo
// The current document's drag and Image Trace hold are not this document's, and this view has
// its own Outline or Preview.
(key.dragging, key.trace_source, key.outline) = (false, None, v.outline);
+ key.backdrop = backdrop(app, st, v.outline);
let opts = frame_options(app, &key, st.shown_mask(), smooth_images);
let (fw, fh, view) = frame_view(pixel, (pw, ph), &drawn, ppp);
let doc = st.doc.clone();
diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs
index f57a15a795..2f9a4f981f 100644
--- a/crates/ui-egui/src/canvas/raster.rs
+++ b/crates/ui-egui/src/canvas/raster.rs
@@ -226,7 +226,8 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option
*kept =
keeps.then(|| KeptFrame { key: job.key.clone(), opts: job.opts.clone(), view: job.view, pixels: holds_pixels.then(|| img.pixels.clone()) });
// The kept frame stays sRGB, so the next frame's copied pixels are converted only once.
- crate::display_profile::convert(job.display.as_deref(), &mut img.pixels);
+ let width = img.width;
+ crate::display_profile::convert_over(job.display.as_deref(), &mut img.pixels, width, job.view, job.key.over());
WorkerFrame { img, moved, reused }
}
diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs
index d5dfe4e307..19d575b35b 100644
--- a/crates/ui-egui/src/canvas/tests.rs
+++ b/crates/ui-egui/src/canvas/tests.rs
@@ -2717,6 +2717,140 @@ fn the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on()
assert_eq!(count(&mut app, red), Some(srgb));
}
+/// With a display profile, translucent art and the anti-aliased edges of art over the paper are
+/// blended with the paper in sRGB before the conversion: drawn over the converted paper, each such
+/// pixel shows the converted blend. Opaque art, and art over the pasteboard, convert as before. The
+/// part an edit renders again and the render worker's frame do the same, a change of the
+/// transparency grid renders the art again, and Outline converts the art alone.
+#[test]
+fn translucent_art_over_the_paper_is_blended_before_the_display_profile() {
+ use crate::display_profile::{Found, Reading};
+ let mut app = VectorcraftApp::new(Session::new(), Default::default());
+ app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
+ app.ui.task_bar = false;
+ app.ui.view.rulers = false;
+ app.canvas.worker_started = true; // every frame on this thread
+ let half = app.run("shape.rectangle", json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap()["id"].clone();
+ app.run("paint.setFill", json!({"ids": [half], "color": "#ff0000"})).unwrap();
+ app.run("transparency.set", json!({"ids": [half], "opacity": 50})).unwrap();
+ let disc = app.run("shape.ellipse", json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].clone();
+ app.run("paint.setFill", json!({"ids": [disc], "color": "#2040c0"})).unwrap();
+ // Left of the artboard, over the pasteboard.
+ let outside = app.run("shape.rectangle", json!({"x": -60, "y": 100, "width": 40, "height": 40})).unwrap()["id"].clone();
+ app.run("paint.setFill", json!({"ids": [outside], "color": "#00ff00"})).unwrap();
+ app.run("transparency.set", json!({"ids": [outside], "opacity": 50})).unwrap();
+ app.run("select.none", json!({})).unwrap();
+ let ctx = egui::Context::default();
+ // The art's raster one frame uploads: where it goes ([x, y] for a part), its width and its pixels.
+ let upload = |app: &mut VectorcraftApp| -> Option<(Option<[usize; 2]>, usize, Vec)> {
+ let (_, mut delta) = frame_output(app, &ctx);
+ let art = app.canvas.texture.as_ref()?.id();
+ let up = delta.set.iter().find(|e| e.0.eq(&art)).and_then(|e| e.1.last()).map(|d| {
+ let egui::ImageData::Color(img) = &d.image;
+ (d.pos, img.width(), img.pixels.clone())
+ });
+ delta.clear();
+ up
+ };
+ upload(&mut app).expect("the first frame");
+ let v = app.view_mut().unwrap();
+ (v.zoom, v.center) = (1.0, Point::new(120.0, 150.0));
+ let (_, width, srgb) = upload(&mut app).expect("the view at 100%");
+ let key = app.canvas.key.clone().unwrap();
+ assert!(key.backdrop.is_none(), "no display profile: nothing to blend");
+ let p3 = crate::display_profile::tests::p3();
+ let t = vectorcraft_color::cms::display::DisplayTransform::from_icc(&p3).unwrap();
+ app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } });
+ let (_, _, shown) = upload(&mut app).expect("drawn again, converted");
+ let key = app.canvas.key.clone().unwrap();
+ assert!(key.backdrop.is_some());
+ let white = t.apply8([255; 3]);
+ // What the canvas shows of pixel `c` over the converted paper `under`, as egui blends it.
+ let over = |c: egui::Color32, under: [u8; 3]| {
+ let k = 255 - u32::from(c.a());
+ [0, 1, 2].map(|i| u32::from(c.to_array()[i]) + (u32::from(under[i]) * k + 127) / 255)
+ };
+ let plain = |s: egui::Color32| {
+ let mut px = s.to_array();
+ t.apply_premultiplied(&mut px);
+ egui::Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3])
+ };
+ let (view_w, view_h) = (key.w, key.h);
+ let (_, _, view) = frame_view(
+ None,
+ (view_w, view_h),
+ &View { zoom: key.zoom, center: Point::new(key.cx, key.cy), rotation: key.rot, ..View::default() },
+ key.ppp,
+ );
+ let to_doc = view.inverse();
+ let (mut blended, mut beside) = (0, 0);
+ for (i, (s, c)) in srgb.iter().zip(&shown).enumerate() {
+ let p = to_doc * Point::new((i % width) as f64 + 0.5, (i / width) as f64 + 0.5);
+ if s.a() == 0 || s.a() == 255 {
+ assert_eq!(*c, plain(*s), "opaque and empty pixels convert as before, at {p:?}");
+ } else if (1.0..399.0).contains(&p.x) && (1.0..299.0).contains(&p.y) {
+ let k = 255 - u32::from(s.a());
+ let mix = [0, 1, 2].map(|j| (u32::from(s.to_array()[j]) + (255 * k + 127) / 255).min(255) as u8);
+ let want = t.apply8(mix);
+ let got = over(*c, white);
+ assert!((0..3).all(|j| got[j].abs_diff(u32::from(want[j])) <= 1), "at {p:?}: {got:?} shown, {want:?} wanted");
+ blended += 1;
+ } else if p.x < -1.0 {
+ assert_eq!(*c, plain(*s), "over the pasteboard the art converts alone, at {p:?}");
+ beside += 1;
+ }
+ }
+ assert!(blended > 1000 && beside > 500, "{blended} pixels over the paper, {beside} over the pasteboard");
+ // The test tells the two apart: the fill converted alone, over the converted paper, shows another color.
+ let at = view * Point::new(200.0, 150.0);
+ let at = at.y as usize * width + at.x as usize;
+ let (s, c) = (srgb[at], shown[at]);
+ assert!((50..=205).contains(&s.a()), "the 50% fill at the center: {s:?}");
+ let alone = over(plain(s), white);
+ assert!((0..3).any(|j| alone[j].abs_diff(over(c, white)[j]) > 2), "{alone:?} and {:?}", over(c, white));
+ // The render worker's frame of the same key is the same.
+ let opts = app.canvas.shown.as_ref().unwrap().1.clone();
+ let doc = app.session.active().unwrap().doc.clone();
+ let display = app.display_profile.transform(true);
+ let job = |key: &CacheKey, doc: &std::sync::Arc| crate::render_worker::Job {
+ key: key.clone(),
+ doc: doc.clone(),
+ w: view_w,
+ h: view_h,
+ view,
+ opts: opts.clone(),
+ scope: vectorcraft_engine::file_access::ScopeHandle::capture(),
+ effects: Default::default(),
+ may_copy: false,
+ may_keep: false,
+ display: display.clone(),
+ };
+ let worker = crate::canvas::render_job(&mut vectorcraft_render::Renderer::new(), &mut None, &job(&key, &doc)).img;
+ let near = |a: &[u8], b: egui::Color32| a.iter().zip(b.to_array()).all(|(x, y)| x.abs_diff(y) <= 1);
+ assert!(worker.pixels.as_chunks::<4>().0.iter().zip(&shown).all(|(a, b)| near(a, *b)), "the worker's frame matches");
+ // An edit renders its part again, blended too.
+ app.run("paint.setFill", json!({"ids": [half], "color": "#0000ff"})).unwrap();
+ let (pos, part_w, part) = upload(&mut app).expect("the edit shows");
+ let [x0, y0] = pos.expect("only its part");
+ let key = app.canvas.key.clone().unwrap();
+ let doc = app.session.active().unwrap().doc.clone();
+ let whole = crate::canvas::render_job(&mut vectorcraft_render::Renderer::new(), &mut None, &job(&key, &doc)).img;
+ let whole = whole.pixels.as_chunks::<4>().0;
+ for (i, c) in part.iter().enumerate() {
+ let at = (y0 + i / part_w) * view_w as usize + x0 + i % part_w;
+ assert!(near(&whole[at], *c), "the part matches the whole frame at {at}: {c:?}, {:?}", whole[at]);
+ }
+ assert!(part.iter().filter(|c| c.a() != 0 && c.a() != 255).count() > 1000, "the blue fill is in the part");
+ // The transparency grid replaces the paper under the art: drawn again.
+ app.run("view.transparencyGrid", json!({"on": true})).unwrap();
+ assert!(upload(&mut app).is_some_and(|(pos, ..)| pos.is_none()), "the grid renders the art again");
+ assert!(app.canvas.key.as_ref().and_then(|k| k.backdrop.as_ref()).is_some_and(|b| b.grid.is_some()));
+ // Outline: the white canvas is the interface's, so the art converts alone.
+ app.run("view.outline", json!({})).unwrap();
+ upload(&mut app).expect("Outline renders again");
+ assert!(app.canvas.key.as_ref().is_some_and(|k| k.outline && k.backdrop.is_none()));
+}
+
/// View › Hide Template (#2000): a template layer's art leaves the canvas, and Show Template
/// draws it again, dimmed as before; each re-renders at once.
#[test]
@@ -5527,6 +5661,74 @@ fn a_pane_draws_its_own_views_outline() {
}
}
+/// With a display profile, a split-view pane or floating window blends translucent art with the
+/// paper before the conversion, as the canvas does, and in its own Outline converts the art alone.
+#[test]
+fn a_pane_blends_translucent_art_before_the_display_profile() {
+ use crate::display_profile::{Found, Reading};
+ let mut app = VectorcraftApp::new(Session::new(), Default::default());
+ app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
+ let half = app.run("shape.rectangle", json!({"x": 50, "y": 25, "width": 100, "height": 50})).unwrap()["id"].clone();
+ app.run("paint.setFill", json!({"ids": [half], "color": "#ff0000"})).unwrap();
+ app.run("transparency.set", json!({"ids": [half], "opacity": 50})).unwrap();
+ app.run("select.none", json!({})).unwrap();
+ crate::doc_windows::new_window(&mut app).unwrap();
+ app.canvas.panes.worker_started = true; // every pane render on this thread
+ let p3 = crate::display_profile::tests::p3();
+ let t = vectorcraft_color::cms::display::DisplayTransform::from_icc(&p3).unwrap();
+ app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } });
+ let ctx = egui::Context::default();
+ let other = (0, 1);
+ let slot = (app.session.documents()[0].uid, 1);
+ // The pane's raster one frame uploads, and the key it was rendered for.
+ let pane = |app: &mut VectorcraftApp| -> (Vec, CacheKey) {
+ let cell = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 400.0));
+ let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() };
+ let mut out = ctx.run_ui(raw, |ui| {
+ panes::pane(app, ui, other, cell);
+ });
+ let (key, tex) = app.canvas.panes.shown.get(&slot).expect("the pane's render");
+ let id = tex.id();
+ let pixels = out.textures_delta.set.iter().find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| {
+ let egui::ImageData::Color(img) = &d.image;
+ img.pixels.clone()
+ });
+ let key = key.clone();
+ out.textures_delta.clear();
+ (pixels.expect("the pane uploads"), key)
+ };
+ app.session.prefs.monitor_profile_display = false;
+ let (srgb, key) = pane(&mut app);
+ assert!(key.backdrop.is_none(), "no display profile: nothing to blend");
+ app.session.prefs.monitor_profile_display = true;
+ let (shown, key) = pane(&mut app);
+ assert!(key.backdrop.is_some(), "the pane's Preview blends with its paper");
+ assert_eq!(srgb.len(), shown.len());
+ let plain = |s: egui::Color32| {
+ let mut px = s.to_array();
+ t.apply_premultiplied(&mut px);
+ egui::Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3])
+ };
+ let mut blended = 0;
+ for (s, c) in srgb.iter().zip(&shown) {
+ if s.a() == 0 || s.a() == 255 {
+ assert_eq!(*c, plain(*s), "opaque and empty pixels convert as before");
+ } else {
+ assert_eq!(c.a(), s.a(), "the alpha is kept");
+ let p = plain(*s);
+ if (0..3).any(|j| c.to_array()[j].abs_diff(p.to_array()[j]) > 2) {
+ blended += 1;
+ }
+ }
+ }
+ assert!(blended > 100, "{blended} translucent pixels blended with the paper");
+ // The pane's own Outline: the art converts alone, while the current view stays in Preview.
+ crate::doc_windows::view_mut(&mut app, other).unwrap().outline = true;
+ app.view_mut().unwrap().outline = false;
+ let (_, key) = pane(&mut app);
+ assert!(key.outline && key.backdrop.is_none(), "the pane's Outline has no paper to blend with");
+}
+
/// While the rulers' origin is dragged out of their corner, its crosshair draws over the canvas in
/// the theme's dim text color in Preview, and in Outline in the dark gray that shows on the white
/// canvas.
@@ -5831,8 +6033,12 @@ fn show_hidden_characters_lays_out_only_type_that_changed() {
let same = |a: &std::sync::Arc, b: &std::sync::Arc| std::sync::Arc::ptr_eq(a, b);
let (before, after) = frames(&mut app, &|_| {});
assert!(before.iter().zip(&after).all(|(a, b)| same(a, b)), "a frame lays out no type");
+ // Each attempt sets different text: text the object already has is no edit, and a second
+ // attempt with the same text would leave the object as it was.
+ let edits = std::cell::Cell::new(0);
let (before, after) = frames(&mut app, &|app| {
- app.session.execute("text.setText", &json!({"id": ids[1].0, "text": "a b c"})).unwrap();
+ edits.set(edits.get() + 1);
+ app.session.execute("text.setText", &json!({"id": ids[1].0, "text": format!("a b c {}", edits.get())})).unwrap();
});
assert!(!same(&before[1], &after[1]), "the edited object is laid out again");
assert!(same(&before[0], &after[0]) && same(&before[2], &after[2]), "the others are not");
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index acc642cc0d..a2c29fadc4 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -9,7 +9,7 @@
//! - `ui.menu.list`: flattened menu tree
//! - `ui.contextMenu.list`: the canvas context menu for the current selection, flattened
//! - `ui.tool.select {tool}`, `ui.tool.list`
-//! - `ui.pointer {events:[{kind: down|drag|up|move|doubleclick, x, y, backquote?, space?: "doc"|"screen"}], mods?, backquote?}`:
+//! - `ui.pointer {events:[{kind: down|drag|up|move|doubleclick|tripleclick, x, y, backquote?, space?: "doc"|"screen"}], mods?, backquote?}`:
//! drive the active tool through the same path as the mouse, after the synthetic input sent
//! before it was applied
//! - `ui.key {key, shift?, alt?, cmd?}` / `ui.text {text}`: synthetic keyboard input
@@ -1895,7 +1895,7 @@ fn rotate_view_pointer(
PointerKind::Up => {
app.control_rotate_press = None;
}
- PointerKind::Move | PointerKind::DoubleClick => {}
+ PointerKind::Move | PointerKind::DoubleClick | PointerKind::TripleClick => {}
}
Ok(())
}
@@ -1963,6 +1963,7 @@ fn pointer_events_inner(app: &mut VectorcraftApp, ctx: &egui::Context, req: &Con
"up" => PointerKind::Up,
"move" => PointerKind::Move,
"doubleclick" | "dblclick" => PointerKind::DoubleClick,
+ "tripleclick" => PointerKind::TripleClick,
other => return Err(format!("unknown pointer kind `{other}`")),
};
PointerEvent::json_check(e)?;
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 04e58d452e..4ac6da2fbe 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -158,9 +158,10 @@ pub use export_as::{export_selection, open as open_export_as};
pub(crate) use export_for_screens::drop_unread_screen_settings;
pub use export_for_screens::open as open_export_for_screens;
pub(crate) use export_for_screens::{
- KIND as EXPORT_FOR_SCREENS, PresetPick as ScreenPresetPick, export_preset as screen_export_preset, formats as screen_formats,
- import_presets as screen_import_presets, open_assets as open_export_for_screens_assets, preset_list as screen_preset_list,
- saved_options as screen_saved_options, saved_rows as screen_saved_rows, settings_format as screen_settings_format,
+ KIND as EXPORT_FOR_SCREENS, PresetPick as ScreenPresetPick, artboard_name_editing as export_artboard_name_editing,
+ export_preset as screen_export_preset, formats as screen_formats, import_presets as screen_import_presets,
+ open_assets as open_export_for_screens_assets, preset_list as screen_preset_list, saved_options as screen_saved_options,
+ saved_rows as screen_saved_rows, settings_format as screen_settings_format,
};
pub(crate) use form::{humanize, number_list_text, plugin_color_button, read_number_list, unit_suffix};
pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document, preset_card};
diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs
index 777c872494..2c2673d468 100644
--- a/crates/ui-egui/src/dialogs/effect.rs
+++ b/crates/ui-egui/src/dialogs/effect.rs
@@ -227,6 +227,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
None if id == TWEAK => tweak_fields(ui, d, app.session.general_unit()),
None if id == DROP_SHADOW => drop_shadow_fields(ui, d, app.session.general_unit()),
None if id == "artistic.filmGrain" => film_grain_fields(ui, d),
+ None if id == RADIAL_BLUR => radial_blur_fields(ui, d, app.session.general_unit()),
None if id == free_distort::FREE_DISTORT => {
free_distort::fields(app, ui, d);
values_changed(d)
@@ -287,6 +288,127 @@ fn film_grain_fields(ui: &mut egui::Ui, d: &mut Dialog) -> bool {
before != d.fields
}
+/// The Radial Blur effect (Effect › Blur › Radial Blur…).
+const RADIAL_BLUR: &str = "blur.radial";
+/// Radial Blur's Blur Center: its parameters (0..1 across and down the object's bounds).
+const BLUR_CENTER: [&str; 2] = ["centerX", "centerY"];
+
+/// Radial Blur: Amount, Blur Method and Quality as the other effects show their parameters, then
+/// the Blur Center box with its Horizontal and Vertical fields. Returns whether the values differ
+/// from those last previewed.
+fn radial_blur_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Unit) -> bool {
+ let before = d.fields.clone();
+ // The center is the box's, not a pair of plain number rows.
+ let center: Vec<(String, Value)> = BLUR_CENTER.iter().filter_map(|k| d.fields.remove(*k).map(|v| (k.to_string(), v))).collect();
+ let doc = vectorcraft_effects::effect_info(RADIAL_BLUR).map(|e| e.params).unwrap_or_default();
+ form::param_fields(ui, d, &|_| false, &|k| choices(RADIAL_BLUR, k), &|k| doc_rank(doc, k), unit);
+ d.fields.extend(center);
+ ui.add_space(6.0);
+ blur_center(ui, d);
+ before != d.fields
+}
+
+/// The Blur Center box's side (points).
+const CENTER_BOX: f32 = 120.0;
+
+/// A Blur Center coordinate kept to a hundredth of a percent of the box.
+fn center_round(x: f64) -> f64 {
+ (x * 1e4).round() / 1e4
+}
+
+/// Radial Blur's Blur Center: a box standing for the object's bounds, with the blur's pattern (rays
+/// for Zoom, rings for Spin) drawn about the center. A press or a drag in the box puts the center
+/// there; with the keyboard focus the arrow keys move it 1 % of the box (10 % with Shift). The
+/// Horizontal and Vertical fields beside it type the same position in percent of the bounds' width
+/// and height. Changes go to `d.fields["centerX"]` and `["centerY"]`.
+fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) {
+ use egui::{Key, Modifiers, Sense, Stroke};
+ let [kx, ky] = BLUR_CENTER;
+ let mut c = [d.f64(kx, 0.5).clamp(0.0, 1.0), d.f64(ky, 0.5).clamp(0.0, 1.0)];
+ let before = c;
+ let t = Tokens::get(ui.ctx());
+ let zoom = d.str("method").eq_ignore_ascii_case("zoom");
+ form::caption(ui, "Blur Center");
+ ui.horizontal(|ui| {
+ let (rect, _) = ui.allocate_exact_size(egui::vec2(CENTER_BOX, CENTER_BOX), Sense::hover());
+ let id = ui.scope_id().with("radial-blur-center");
+ let resp = ui.interact(rect, id, Sense::click_and_drag());
+ let percent = |v: f64| (v * 1000.0).round() / 10.0;
+ let name = tl!("Blur Center").to_string();
+ let value = format!("{}: {}%, {}: {}%", tl!("Horizontal"), percent(c[0]), tl!("Vertical"), percent(c[1]));
+ let enabled = ui.is_enabled();
+ resp.widget_info(|| egui::WidgetInfo {
+ current_text_value: Some(value.clone()),
+ ..egui::WidgetInfo::labeled(egui::Role::Slider, enabled, &name)
+ });
+ if resp.drag_started() || resp.clicked() {
+ resp.request_focus();
+ }
+ if let Some(p) = resp.interact_pointer_pos()
+ && (resp.dragged() || resp.clicked() || resp.drag_started())
+ {
+ let unit = |v: f32, lo: f32| f64::from(((v - lo) / CENTER_BOX).clamp(0.0, 1.0));
+ c = [center_round(unit(p.x, rect.left())), center_round(unit(p.y, rect.top()))];
+ }
+ if resp.has_focus() {
+ ui.memory_mut(|m| {
+ m.set_focus_lock_filter(id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() })
+ });
+ for (key, dx, dy) in [(Key::ArrowLeft, -1.0, 0.0), (Key::ArrowRight, 1.0, 0.0), (Key::ArrowUp, 0.0, -1.0), (Key::ArrowDown, 0.0, 1.0)] {
+ // Shift first: a key without modifiers also matches the key with Shift.
+ for (modifiers, step) in [(Modifiers::SHIFT, 0.1), (Modifiers::NONE, 0.01)] {
+ if ui.input_mut(|i| i.consume_key(modifiers, key)) {
+ c = [center_round((c[0] + dx * step).clamp(0.0, 1.0)), center_round((c[1] + dy * step).clamp(0.0, 1.0))];
+ }
+ }
+ }
+ }
+ if resp.hovered() || resp.dragged() {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
+ }
+ // The box, and the pattern about the center: rays for Zoom, rings for Spin.
+ let painter = ui.painter_at(rect);
+ painter.rect_filled(rect, 2.0, t.input);
+ let at = egui::pos2(rect.left() + c[0] as f32 * CENTER_BOX, rect.top() + c[1] as f32 * CENTER_BOX);
+ let faint = Stroke::new(1.0, t.text_dim.gamma_multiply(0.6));
+ let reach = CENTER_BOX * std::f32::consts::SQRT_2;
+ if zoom {
+ for k in 0..24 {
+ let a = k as f32 * std::f32::consts::TAU / 24.0;
+ let dir = egui::vec2(a.cos(), a.sin());
+ painter.line_segment([at + dir * 6.0, at + dir * reach], faint);
+ }
+ } else {
+ for k in 1..=12 {
+ painter.circle_stroke(at, k as f32 * reach / 12.0, faint);
+ }
+ }
+ painter.circle(at, 3.5, if resp.has_focus() { t.accent } else { t.panel }, Stroke::new(1.5, t.text));
+ let border = if resp.has_focus() { t.accent } else { t.input_border };
+ painter.rect_stroke(rect, 2.0, Stroke::new(1.0, border), egui::StrokeKind::Inside);
+ // The same position typed in percent.
+ ui.vertical(|ui| {
+ egui::Grid::new("blur-center-fields").num_columns(2).spacing([8.0, 8.0]).show(ui, |ui| {
+ for (i, label) in ["Horizontal", "Vertical"].into_iter().enumerate() {
+ let row = ui.label(egui::RichText::new(format!("{}:", tl!(label))).color(t.text));
+ ui.label_inputs_by(row.id, |ui| {
+ if let Some(x) =
+ widgets::range_field_named(ui, ("blur-center", i), None, c[i] * 100.0, 0.0..=100.0, &form::unit_suffix("%"), 1, 72.0)
+ {
+ c[i] = center_round((x / 100.0).clamp(0.0, 1.0));
+ }
+ });
+ ui.end_row();
+ }
+ });
+ });
+ });
+ if c != before {
+ d.fields.insert(kx.into(), json!(c[0]));
+ d.fields.insert(ky.into(), json!(c[1]));
+ }
+}
+
/// The Glass effect (Effect › Distort › Glass…).
const GLASS: &str = "distort.glass";
/// The Texturizer effect (Effect › Texture › Texturizer…).
@@ -1258,4 +1380,69 @@ mod tests {
assert_eq!((param("opacity"), param("blur")), (Some(99.0), Some(0.0)), "{effect}: OK applies them");
}
}
+
+ /// Effect > Blur > Radial Blur: a press in the Blur Center box puts the center there, the
+ /// arrow keys move it 1 % (10 % with Shift) and stop at the edges, screen readers get its
+ /// position, the generic rows leave it to the box, and OK applies it.
+ #[test]
+ fn radial_blur_center_box_sets_the_center_by_pointer_and_keys() {
+ let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
+ app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
+ let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
+ app.run("select.all", json!({})).unwrap();
+ app.run("effect.dialog", json!({"effect": RADIAL_BLUR})).unwrap();
+ let ctx = egui::Context::default();
+ ctx.enable_accesskit();
+ crate::theme::install_fonts(&ctx);
+ crate::theme::apply(&ctx, Default::default());
+ let time = std::cell::Cell::new(0.0);
+ // One frame → the box's screen-reader node (bounds, value) and the labels drawn.
+ let frame = |app: &mut VectorcraftApp, events: Vec| {
+ time.set(time.get() + 0.05);
+ let mut out = ctx.run_ui(egui::RawInput { time: Some(time.get()), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx()));
+ out.textures_delta.clear();
+ let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
+ let labels: Vec = nodes.iter().filter_map(|(_, n)| n.label().map(str::to_string)).collect();
+ let center = nodes.iter().find(|(_, n)| n.label() == Some("Blur Center") && n.role() == egui::accesskit::Role::Slider).map(|(_, n)| {
+ let b = n.bounds().unwrap_or_default();
+ (egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)), n.value().map(str::to_string))
+ });
+ (center, labels)
+ };
+ for _ in 0..6 {
+ frame(&mut app, vec![]);
+ }
+ let (Some((rect, value)), labels) = frame(&mut app, vec![]) else { panic!("the dialog has a Blur Center box") };
+ assert_eq!(value.as_deref(), Some("Horizontal: 50%, Vertical: 50%"), "the default center is the middle");
+ assert!(!labels.iter().any(|l| l.starts_with("Center")), "no plain Center X or Center Y rows: {labels:?}");
+ let field = |app: &VectorcraftApp, k: &str| app.ui.dialog.as_ref().unwrap().fields.get(k).and_then(Value::as_f64);
+ let pos = rect.min + egui::vec2(0.25 * rect.width(), 0.75 * rect.height());
+ let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
+ frame(&mut app, vec![egui::Event::PointerMoved(pos), button(true)]);
+ frame(&mut app, vec![button(false)]);
+ frame(&mut app, vec![]);
+ let at = |app: &VectorcraftApp| (field(app, "centerX").unwrap_or(-1.0), field(app, "centerY").unwrap_or(-1.0));
+ let (x, y) = at(&app);
+ assert!((x - 0.25).abs() < 0.01 && (y - 0.75).abs() < 0.01, "the press puts the center there: {x}, {y}");
+ let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
+ app.ui.dialog.as_mut().unwrap().fields.insert("centerX".into(), json!(0.25));
+ app.ui.dialog.as_mut().unwrap().fields.insert("centerY".into(), json!(0.75));
+ frame(&mut app, vec![key(egui::Key::ArrowRight, egui::Modifiers::NONE)]);
+ frame(&mut app, vec![key(egui::Key::ArrowUp, egui::Modifiers::SHIFT)]);
+ assert_eq!(at(&app), (0.26, 0.65), "the arrow keys move it 1 %, 10 % with Shift");
+ for _ in 0..10 {
+ frame(&mut app, vec![key(egui::Key::ArrowDown, egui::Modifiers::SHIFT)]);
+ }
+ assert_eq!(at(&app), (0.26, 1.0), "it stops at the edge");
+ let (Some((_, value)), _) = frame(&mut app, vec![]) else { panic!("the box is still there") };
+ assert_eq!(value.as_deref(), Some("Horizontal: 26%, Vertical: 100%"));
+ super::super::confirm(&mut app).unwrap();
+ let st = app.session.doc().unwrap();
+ let fx = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0];
+ assert_eq!(
+ (fx.id.as_str(), fx.params["centerX"].as_f64(), fx.params["centerY"].as_f64()),
+ (RADIAL_BLUR, Some(0.26), Some(1.0)),
+ "OK applies it"
+ );
+ }
}
diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs
index 03c862171d..c78854d439 100644
--- a/crates/ui-egui/src/dialogs/effect_gallery.rs
+++ b/crates/ui-egui/src/dialogs/effect_gallery.rs
@@ -271,6 +271,7 @@ fn preview_space(w: usize, h: usize) -> PixelSpace {
to_doc: Affine::IDENTITY,
px: 1.0,
center: Point::new(wf / 2.0, hf / 2.0),
+ size: vectorcraft_geom::Vec2::new(wf, hf),
channels: vectorcraft_effects::pixel::Channels::Rgb,
line: 1.0,
extent: 0.5 * wf.hypot(hf),
diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs
index ecd9ca6996..5b28affa2f 100644
--- a/crates/ui-egui/src/dialogs/export_for_screens.rs
+++ b/crates/ui-egui/src/dialogs/export_for_screens.rs
@@ -392,6 +392,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
ui.vertical(|ui| {
ui.set_width(LEFT_W);
if let Some(i) = widgets::tab_bar(ui, &[tl!("Artboards"), tl!("Assets")], tab) {
+ if i != tab
+ && let Some((board, text, _)) = take_artboard_edit(app, d)
+ {
+ rename_artboard(app, board, &text);
+ }
d.fields.insert("tab".into(), json!(TABS.get(i).copied().unwrap_or("artboards")));
}
ui.add_space(6.0);
@@ -521,23 +526,33 @@ fn select_options(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
fn artboard_tiles(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, list: bool) {
let mut boards = boards(app, d);
let before = boards.clone();
+ let mut editing = take_artboard_edit(app, d);
+ let mut rename = None;
let names: Vec = app.session.active().map(|s| s.doc.artboards.iter().map(|a| a.name.clone()).collect()).unwrap_or_default();
+ let ids: Vec = app.session.active().map(|s| s.doc.artboards.iter().map(|a| a.id).collect()).unwrap_or_default();
ui.add_enabled_ui(d.str("select") != "full", |ui| {
- tiles(ui, "efs-artboards", names.len(), list, |ui, i, r| {
- match artboard_thumb(app, ui.ctx(), i) {
- Some(tex) => {
- let sz = tex.size_vec2();
- let s = (r.width() / sz.x).min(r.height() / sz.y).min(1.0);
- let uv = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0));
- ui.painter().image(tex.id(), egui::Rect::from_center_size(r.center(), sz * s), uv, egui::Color32::WHITE);
+ tiles(
+ ui,
+ "efs-artboards",
+ names.len(),
+ list,
+ |ui, i, r| {
+ match artboard_thumb(app, ui.ctx(), i) {
+ Some(tex) => {
+ let sz = tex.size_vec2();
+ let s = (r.width() / sz.x).min(r.height() / sz.y).min(1.0);
+ let uv = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0));
+ ui.painter().image(tex.id(), egui::Rect::from_center_size(r.center(), sz * s), uv, egui::Color32::WHITE);
+ }
+ None => {
+ ui.painter().rect_filled(r, 2.0, egui::Color32::WHITE);
+ }
}
- None => {
- ui.painter().rect_filled(r, 2.0, egui::Color32::WHITE);
- }
- }
- let name = names.get(i).cloned().unwrap_or_default();
- (format!("{} {name}", i + 1), name, boards.get(i).copied().unwrap_or(false))
- })
+ let name = names.get(i).cloned().unwrap_or_default();
+ (format!("{} {name}", i + 1), name, boards.get(i).copied().unwrap_or(false))
+ },
+ Some(&mut |ui, i, rect, id, name| edit_artboard_name(ui, ids.get(i).copied(), rect, id, name, &mut editing, &mut rename)),
+ )
.into_iter()
.for_each(|i| {
if let Some(b) = boards.get_mut(i) {
@@ -545,6 +560,16 @@ fn artboard_tiles(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, l
}
});
});
+ // A field whose artboard was deleted while it was typed in is closed, so Escape reaches the dialog again.
+ if d.str("select") != "full"
+ && let Some(uid) = app.session.active().map(|s| s.uid)
+ && let Some((board, text, focus)) = editing.filter(|(board, _, _)| ids.contains(board))
+ {
+ d.fields.insert(RENAME_ARTBOARD.into(), json!((uid, board, text, focus)));
+ }
+ if let Some((board, name)) = rename {
+ rename_artboard(app, board, &name);
+ }
if boards != before {
set_select(d, if boards.iter().all(|b| *b) { "all" } else { "range" });
d.fields.insert("range".into(), json!(range_text(&boards)));
@@ -552,6 +577,100 @@ fn artboard_tiles(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, l
}
}
+/// Inline editor state belongs to this dialog, not to the document or its export settings.
+const RENAME_ARTBOARD: &str = "__renameArtboard";
+
+/// Whether an artboard name is being typed in Export for Screens: a field is open for an artboard
+/// of the active document.
+pub(crate) fn artboard_name_editing(app: &VectorcraftApp, d: &Dialog) -> bool {
+ d.kind == KIND
+ && d.fields
+ .get(RENAME_ARTBOARD)
+ .and_then(|value| serde_json::from_value::<(u64, u32, String, bool)>(value.clone()).ok())
+ .zip(app.session.active())
+ .is_some_and(|((uid, board, ..), s)| s.uid == uid && s.doc.artboards.iter().any(|a| a.id == board))
+}
+
+/// The artboard being renamed (its id, so the name goes to the same artboard after the artboards
+/// change order), the name as typed, and whether the field still has to take the focus. A field
+/// opened in another document than the active one is closed.
+fn take_artboard_edit(app: &VectorcraftApp, d: &mut Dialog) -> Option<(u32, String, bool)> {
+ let doc = app.session.active().map(|s| s.uid);
+ d.fields
+ .remove(RENAME_ARTBOARD)
+ .and_then(|value| serde_json::from_value::<(u64, u32, String, bool)>(value).ok())
+ .filter(|(uid, ..)| Some(*uid) == doc)
+ .map(|(_, board, text, focus)| (board, text, focus))
+}
+
+/// The field of the artboard with id `board`, the same wherever its tile is drawn.
+fn artboard_name_field(board: u32) -> egui::Id {
+ egui::Id::unique(("efs-artboard-name", board))
+}
+
+fn rename_artboard(app: &mut VectorcraftApp, board: u32, text: &str) {
+ let name = text.trim();
+ let Some(index) = app.session.active().and_then(|s| s.doc.artboards.iter().position(|a| a.id == board && a.name != name)) else { return };
+ if !name.is_empty()
+ && let Err(err) = app.run("artboard.rename", json!({"indices": [index], "name": name}))
+ {
+ app.status(err);
+ }
+}
+
+/// The caption of the artboard with id `board`: its name field while it is renamed, else a target
+/// for the double-click that opens it → whether the click toggles the artboard's checkbox, and
+/// whether the field was drawn over the caption.
+fn edit_artboard_name(
+ ui: &mut egui::Ui,
+ board: Option,
+ rect: egui::Rect,
+ id: egui::Id,
+ name: &str,
+ editing: &mut Option<(u32, String, bool)>,
+ rename: &mut Option<(u32, String)>,
+) -> (bool, bool) {
+ if let Some((b, text, focus)) = editing.as_mut().filter(|(b, _, _)| Some(*b) == board) {
+ let field = artboard_name_field(*b);
+ let cancel = ui.input(|i| i.key_pressed(egui::Key::Escape));
+ let enter = crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter);
+ if enter {
+ widgets::reject_dialog_commit(ui.ctx());
+ }
+ let response = ui.put(rect, egui::TextEdit::singleline(text).id(field).font(egui::FontId::proportional(11.0)).desired_width(rect.width()));
+ if *focus {
+ widgets::focus_field(ui, field, text);
+ *focus = false;
+ } else if cancel || enter || response.lost_focus() {
+ if !cancel {
+ *rename = Some((*b, std::mem::take(text)));
+ }
+ response.surrender_focus();
+ *editing = None;
+ }
+ (false, true)
+ } else {
+ let response = ui.interact(rect, id, egui::Sense::click());
+ if let Some(board) = board
+ && response.double_clicked()
+ {
+ *editing = Some((board, name.into(), true));
+ ui.ctx().request_repaint();
+ // If both releases arrived this frame, the first click did not toggle the row.
+ // Otherwise, undo the toggle from the first click on this caption.
+ let toggle = !ui.input(|input| {
+ input.events.iter().filter(|event| {
+ matches!(event, egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } if rect.contains(*pos))
+ }).nth(1).is_some()
+ });
+ return (toggle, false);
+ }
+ (response.clicked(), false)
+ }
+}
+
+type CaptionEdit<'a> = dyn FnMut(&mut egui::Ui, usize, egui::Rect, egui::Id, &str) -> (bool, bool) + 'a;
+
/// `count` thumbnails in a grid (or, with `list`, a list) that scrolls: `paint` draws thumbnail `i`
/// into its rect and gives its caption, its checkbox's name and whether it is checked → the
/// thumbnails whose checkbox (or picture) was clicked.
@@ -561,6 +680,7 @@ fn tiles(
count: usize,
list: bool,
mut paint: impl FnMut(&mut egui::Ui, usize, egui::Rect) -> (String, String, bool),
+ mut caption_edit: Option<&mut CaptionEdit<'_>>,
) -> Vec {
let t = Tokens::get(ui.ctx());
let mut toggled = vec![];
@@ -581,11 +701,22 @@ fn tiles(
let label_at = if list { egui::pos2(pic.right() + 8.0, pic.center().y) } else { egui::pos2(pic.left(), pic.bottom() + 9.0) };
let galley =
ui.painter().layout(caption, egui::FontId::proportional(11.0), t.text, if list { cell.x - side - 12.0 } else { side });
- ui.painter().galley(egui::pos2(label_at.x, label_at.y - galley.size().y / 2.0), galley, t.text);
+ let label_pos = egui::pos2(label_at.x, label_at.y - galley.size().y / 2.0);
+ let caption_clicked = if let Some(edit) = &mut caption_edit {
+ let rect = egui::Rect::from_min_max(egui::pos2(label_at.x, r.top().max(label_at.y - 9.0)), r.right_bottom());
+ let (clicked, field) = edit(ui, i, rect, resp.id.with("name"), &name);
+ if !field {
+ ui.painter().galley(label_pos, galley, t.text);
+ }
+ clicked
+ } else {
+ ui.painter().galley(label_pos, galley, t.text);
+ false
+ };
// The checkbox sits on the thumbnail's lower left corner, as Illustrator's.
let bx = egui::Rect::from_min_size(egui::pos2(pic.left() + 4.0, pic.bottom() - 18.0), egui::vec2(14.0, 14.0));
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bx));
- if widgets::check_box(&mut child, &name, checked, true) || resp.clicked() {
+ if widgets::check_box(&mut child, &name, checked, true) || resp.clicked() || caption_clicked {
toggled.push(i);
}
}
@@ -622,18 +753,25 @@ fn assets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, list: bool) {
// Asked for until its row is in view: the dialog's first frame only measures it.
let scroll_to = d.fields.get("__scrollTo").and_then(Value::as_u64).filter(|id| shown.iter().any(|a| a.id == *id));
let mut in_view = scroll_to.is_none();
- let clicked = tiles(ui, "efs-assets", shown.len(), list, |ui, i, r| {
- let Some(a) = shown.get(i) else { return (String::new(), String::new(), false) };
- crate::panels::asset_export::paint_thumb(ui, st, a, r);
- if scroll_to == Some(a.id) {
- if ui.clip_rect().contains_rect(r) {
- in_view = true;
- } else {
- ui.scroll_to_rect(r, Some(egui::Align::Center));
+ let clicked = tiles(
+ ui,
+ "efs-assets",
+ shown.len(),
+ list,
+ |ui, i, r| {
+ let Some(a) = shown.get(i) else { return (String::new(), String::new(), false) };
+ crate::panels::asset_export::paint_thumb(ui, st, a, r);
+ if scroll_to == Some(a.id) {
+ if ui.clip_rect().contains_rect(r) {
+ in_view = true;
+ } else {
+ ui.scroll_to_rect(r, Some(egui::Align::Center));
+ }
}
- }
- (a.name.clone(), a.name.clone(), on.contains(&a.id))
- });
+ (a.name.clone(), a.name.clone(), on.contains(&a.id))
+ },
+ None,
+ );
for i in clicked {
if let Some(a) = shown.get(i) {
if on.contains(&a.id) {
diff --git a/crates/ui-egui/src/dialogs/svg_options.rs b/crates/ui-egui/src/dialogs/svg_options.rs
index b477bb35c0..19737e4c16 100644
--- a/crates/ui-egui/src/dialogs/svg_options.rs
+++ b/crates/ui-egui/src/dialogs/svg_options.rs
@@ -269,30 +269,45 @@ fn artboards(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
});
}
-/// The SVG the current options write for the first chosen artboard (read-only, selectable),
-/// encoded again only when the options or the document change.
+/// The SVG the current options write for the first chosen artboard, or under Export Selection for
+/// the selection alone, cropped to it (read-only, selectable), encoded again only when the
+/// options, the document or the selection change.
fn code_view(app: &VectorcraftApp, ui: &mut egui::Ui, d: &Dialog) {
let t = Tokens::get(ui.ctx());
let Some(st) = app.session.active() else { return };
+ let selection = d.bool(super::export_as::SELECTION_FIELD);
let mut opts = options(d);
- if let Some(o) = opts.as_object_mut()
- && let Some(r) = o.remove("range")
- {
- // The first artboard of the range (or the first one).
- let first = r.as_str().and_then(|r| r.split([',', '-', '\u{2013}']).next()).and_then(|n| n.trim().parse::().ok());
- o.insert("artboard".into(), json!(first.map_or(0, |n| n.saturating_sub(1))));
+ if let Some(o) = opts.as_object_mut() {
+ if selection {
+ // Export Selection writes one crop, without artboards to choose.
+ for k in vectorcraft_engine::cmd::fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]) {
+ o.remove(*k);
+ }
+ } else if let Some(r) = o.remove("range") {
+ // The first artboard of the range (or the first one).
+ let first = r.as_str().and_then(|r| r.split([',', '-', '\u{2013}']).next()).and_then(|n| n.trim().parse::().ok());
+ o.insert("artboard".into(), json!(first.map_or(0, |n| n.saturating_sub(1))));
+ }
}
- // One cached text, replaced when the document or the options change.
+ // One cached text, replaced when the document, the options or the selection change.
let key = egui::Id::unique("svg-code");
// The read roots in force and the document's folder decide whether the text may be shown.
let roots = vectorcraft_engine::file_access::current().map(|r| r.describe());
- let sig = egui::Id::unique((st.uid, st.revision, opts.to_string(), roots, st.path.as_deref())).value();
+ let selected = selection.then(|| st.selection.objects.clone());
+ let sig = egui::Id::unique((st.uid, st.revision, opts.to_string(), roots, st.path.as_deref(), selected)).value();
let code: Arc = match ui.ctx().data(|m| m.get_temp::<(u64, Arc)>(key)).filter(|(s, _)| *s == sig) {
Some((_, c)) => c,
None => {
const MAX: usize = 200_000;
- let encoded = vectorcraft_engine::cmd::fileio::check_linked_scripts("document.export", "svg", st)
- .and_then(|()| vectorcraft_engine::cmd::fileio::encode_all(&st.doc, "svg", &json!({ "svg": opts })));
+ let encoded = vectorcraft_engine::cmd::fileio::check_linked_scripts("document.export", "svg", st).and_then(|()| {
+ let params = json!({ "svg": opts });
+ if selection {
+ let (doc, _) = vectorcraft_engine::cmd::fileio::selection_doc(st, "document.exportSelection", false)?;
+ vectorcraft_engine::cmd::fileio::encode_all(&doc, "svg", ¶ms)
+ } else {
+ vectorcraft_engine::cmd::fileio::encode_all(&st.doc, "svg", ¶ms)
+ }
+ });
let mut text = match encoded {
// Shown as text whatever the file's encoding.
Ok(enc) => enc
@@ -431,6 +446,37 @@ mod tests {
let _ = std::fs::remove_dir_all(root);
}
+ /// Show Code under Export Selection shows the SVG that OK writes: the selection alone, cropped
+ /// to it with what its effects draw, not the whole document.
+ #[test]
+ fn show_code_under_export_selection_shows_the_selection() {
+ let (mut app, written) = app("/tmp/selection.svg");
+ app.run("shape.rectangle", json!({"x": 70, "y": 40, "width": 20, "height": 20})).unwrap();
+ app.run("effect.apply", json!({"effect": "stylize.dropShadow"})).unwrap();
+ app.run("document.exportSelection", Value::Null).unwrap();
+ let d = app.ui.dialog.as_mut().expect("SVG Options opened");
+ assert_eq!(d.kind, KIND);
+ assert!(d.bool(super::super::export_as::SELECTION_FIELD));
+ d.fields.insert("showCode".into(), json!(true));
+ // The text the code view shows after two frames in one context.
+ let ctx = egui::Context::default();
+ theme::install_fonts(&ctx);
+ for _ in 0..2 {
+ let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(&mut app, ui.ctx()));
+ out.textures_delta.clear();
+ }
+ let code = ctx.data(|m| m.get_temp::<(u64, Arc)>(egui::Id::unique("svg-code"))).map(|(_, c)| c.to_string()).unwrap_or_default();
+ super::super::confirm(&mut app).unwrap();
+ let svg = text(&written, 0);
+ assert_eq!(written.borrow()[0].0, "/tmp/selection.svg");
+ assert_eq!(code, svg, "Show Code shows what OK writes");
+ // The shadow reaches past the 21-point square, and the other rectangle is left out.
+ assert!(!svg.contains("viewBox=\"0 0 120 80\"") && !svg.contains("viewBox=\"0 0 21 21\""), "{svg}");
+ assert!(!svg.contains("width=\"40\""), "{svg}");
+ assert_eq!(svg.matches(">();
+ let rename = |h: &mut ScreensFrame, app: &mut VectorcraftApp, label: &str| {
+ let out = h.settle(app);
+ let at = screen_text_at(&out, label);
+ h.frame(app, vec![egui::Event::PointerMoved(at)]);
+ for pressed in [true, false, true, false] {
+ h.frame(
+ app,
+ vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }],
+ );
+ }
+ h.settle(app);
+ assert!(h.ctx.egui_wants_keyboard_input(), "{view}: the double-click opens the name");
+ };
+ let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
+ rename(&mut h, &mut app, "2 Artboard 2");
+ app.run("artboard.reorder", json!({"index": 1, "to": 0})).unwrap();
+ h.frame(&mut app, vec![egui::Event::Text("Hero".into())]);
+ h.frame(&mut app, vec![enter]);
+ h.settle(&mut app);
+ assert_eq!(names(&app), ["Hero", "Artboard 1", "Artboard 3"], "{view}");
+ assert_eq!(kind(&app), Some(export_for_screens::KIND), "{view}");
+ assert!(log.borrow().is_empty(), "{view}: renaming must not export");
+ // The artboard is deleted while its name is typed: the field closes, no other artboard
+ // takes the name, and Escape closes the dialog again.
+ rename(&mut h, &mut app, "2 Artboard 1");
+ h.frame(&mut app, vec![egui::Event::Text("Gone".into())]);
+ app.run("artboard.delete", json!({"indices": [1]})).unwrap();
+ h.settle(&mut app);
+ assert!(!h.ctx.egui_wants_keyboard_input(), "{view}: the field of a deleted artboard closes");
+ assert_eq!(names(&app), ["Hero", "Artboard 3"], "{view}");
+ let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
+ h.time += 0.1;
+ let input = egui::RawInput {
+ events: vec![escape],
+ time: Some(h.time),
+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1100.0, 900.0))),
+ ..Default::default()
+ };
+ let mut out = h.ctx.run_ui(input, |ui| {
+ crate::shortcuts::handle(&mut app, ui.ctx());
+ super::show(&mut app, ui.ctx());
+ });
+ out.textures_delta.clear();
+ h.settle(&mut app);
+ assert_eq!(kind(&app), None, "{view}: Escape closes the dialog");
+ assert_eq!(names(&app), ["Hero", "Artboard 3"], "{view}");
+ assert!(log.borrow().is_empty(), "{view}: renaming must not export");
+ }
+}
+
+/// #7275: a name typed while another document becomes active (a command from the control channel
+/// or MCP) renames no artboard in either document, and Escape closes the dialog.
+#[test]
+fn an_artboard_name_stays_with_its_document() {
+ let (mut app, log) = app(2, true);
+ app.run("file.new", json!({"width": 60, "height": 40, "artboards": 2})).unwrap();
+ app.run("document.activate", json!({"index": 0})).unwrap();
+ open(&mut app);
+ let mut h = ScreensFrame::new();
+ let names = |app: &VectorcraftApp, i: usize| app.session.documents()[i].doc.artboards.iter().map(|a| a.name.clone()).collect::>();
+ let out = h.settle(&mut app);
+ let at = screen_text_at(&out, "2 Artboard 2");
+ h.frame(&mut app, vec![egui::Event::PointerMoved(at)]);
+ for pressed in [true, false, true, false] {
+ h.frame(&mut app, vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }]);
+ }
+ h.settle(&mut app);
+ assert!(h.ctx.egui_wants_keyboard_input(), "the double-click opens the name");
+ h.frame(&mut app, vec![egui::Event::Text("Elsewhere".into())]);
+ app.run("document.activate", json!({"index": 1})).unwrap();
+ let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
+ h.time += 0.1;
+ let input = egui::RawInput {
+ events: vec![escape],
+ time: Some(h.time),
+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1100.0, 900.0))),
+ ..Default::default()
+ };
+ let mut out = h.ctx.run_ui(input, |ui| {
+ crate::shortcuts::handle(&mut app, ui.ctx());
+ super::show(&mut app, ui.ctx());
+ });
+ out.textures_delta.clear();
+ h.settle(&mut app);
+ assert_eq!(kind(&app), None, "Escape closes the dialog");
+ assert_eq!(names(&app, 0), ["Artboard 1", "Artboard 2"]);
+ assert_eq!(names(&app, 1), ["Artboard 1", "Artboard 2"]);
+ assert!(log.borrow().is_empty(), "renaming must not export");
+}
diff --git a/crates/ui-egui/src/display_profile.rs b/crates/ui-egui/src/display_profile.rs
index 486489e6fe..b3f10ab27e 100644
--- a/crates/ui-egui/src/display_profile.rs
+++ b/crates/ui-egui/src/display_profile.rs
@@ -1,6 +1,8 @@
//! Preferences › Performance › Use Monitor Profile for Canvas: the canvas's art, its artboards'
//! paper and the transparency grid are converted from sRGB into the ICC profile of the display
-//! that shows most of the main window, as the last step before they are drawn.
+//! that shows most of the main window, as the last step before they are drawn. Translucent art
+//! and the anti-aliased edges of art over the paper or the grid are blended with it in sRGB first,
+//! and the blend is converted ([`convert_over`]).
//!
//! The desktop app reads the display's profile on a background thread and hands the reading to
//! [`DisplayProfile::report`], which checks the profile and builds its conversion table there.
@@ -14,6 +16,7 @@ use std::sync::{Arc, RwLock};
use serde_json::{Value, json};
use vectorcraft_color::cms::display::DisplayTransform;
pub use vectorcraft_color::cms::display::MAX_PROFILE_BYTES;
+use vectorcraft_geom::{Affine, Point, Rect};
/// What the desktop app read for the display showing the main window.
#[derive(Clone, Debug, PartialEq)]
@@ -221,6 +224,264 @@ pub(crate) fn convert(t: Option<&DisplayTransform>, pixels: &mut [u8]) {
t.apply_premultiplied(pixels);
}
+/// The document's paper under the canvas's art, which the canvas draws converted into the display
+/// profile before the art: [`convert_over`] blends translucent art with it before converting.
+/// The pasteboard and Outline's white canvas are interface colors and are not part of it.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Backdrop {
+ /// View › Hide Artboards: the sRGB color of the paper that covers the whole canvas.
+ pub(crate) everywhere: Option<[u8; 3]>,
+ /// The artboards in the order they are drawn (the last on top), each with its paper's sRGB color.
+ pub(crate) artboards: Vec<(Rect, [u8; 3])>,
+ /// The transparency grid, which covers every artboard's paper: its two sRGB colors, and its cell
+ /// in screen points, counted from each artboard's top left corner.
+ pub(crate) grid: Option<([[u8; 3]; 2], f32)>,
+}
+
+/// A color of the backdrop: in sRGB, and as the canvas shows it, converted.
+#[derive(Clone, Copy, PartialEq)]
+struct Paper {
+ srgb: [u8; 3],
+ shown: [u8; 3],
+}
+
+/// An artboard of the backdrop, as [`Over`] looks it up.
+struct Board {
+ /// Its rectangle in the document, normalized.
+ rect: Rect,
+ /// The corner the transparency grid's cells are counted from.
+ origin: Point,
+ paper: Paper,
+}
+
+/// No artboard at a pixel of a row ([`Over::owners`]).
+const NO_BOARD: u32 = u32::MAX;
+
+/// The first pixel at or after `x` that no artboard has taken yet, in the chain `next` (each
+/// pixel's next candidate; a pixel not taken is its own), shortening the chain on the way.
+fn untaken(next: &mut [u32], x: usize) -> usize {
+ let mut root = x;
+ while next[root] as usize != root {
+ root = next[root] as usize;
+ }
+ let mut at = x;
+ while next[at] as usize != root {
+ let n = next[at] as usize;
+ next[at] = root as u32;
+ at = n;
+ }
+ root
+}
+
+/// [`Backdrop`] converted for a frame: what [`convert_over`] needs for each pixel.
+struct Over<'a> {
+ t: &'a DisplayTransform,
+ /// The frame's pixels → the document.
+ to_doc: Affine,
+ everywhere: Option,
+ boards: Vec,
+ /// The grid's two colors and its cell in document points.
+ grid: Option<([Paper; 2], f64)>,
+}
+
+impl<'a> Over<'a> {
+ /// For a frame of `width` × `height` pixels. None when the backdrop has no paper, or `view`
+ /// (the document → the pixels) can't be undone. The artboards that lie wholly outside the
+ /// frame are left out, so a row looks only at the artboards in view.
+ fn new(t: &'a DisplayTransform, b: &Backdrop, view: Affine, zoom: f64, (width, height): (usize, usize)) -> Option {
+ let det = view.determinant();
+ if (b.everywhere.is_none() && b.artboards.is_empty()) || !det.is_finite() || det.abs() < 1e-12 {
+ return None;
+ }
+ let paper = |srgb: [u8; 3]| Paper { srgb, shown: t.apply8(srgb) };
+ let to_doc = view.inverse();
+ // The frame in the document, a pixel wider on every side than its pixels' centers reach.
+ let frame = to_doc.transform_rect_bbox(Rect::new(-1.0, -1.0, width as f64 + 1.0, height as f64 + 1.0));
+ let in_view = |r: &Rect| r.x0 <= frame.x1 && frame.x0 <= r.x1 && r.y0 <= frame.y1 && frame.y0 <= r.y1;
+ let boards = b
+ .artboards
+ .iter()
+ .map(|&(r, color)| Board { rect: r.abs(), origin: r.origin(), paper: paper(color) })
+ .filter(|b| in_view(&b.rect))
+ .collect();
+ let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { 1.0 };
+ Some(Self {
+ t,
+ to_doc,
+ everywhere: b.everywhere.map(paper),
+ boards,
+ grid: b.grid.map(|([a, c], cell)| ([paper(a), paper(c)], (f64::from(cell) / zoom).max(5e-10))),
+ })
+ }
+
+ /// The pixels `start..end` of the row whose centers lie at height `y` that artboard `b` covers,
+ /// their centers inside its rectangle. None when it covers none of the row's `width` pixels.
+ fn span(&self, b: &Board, y: f64, width: usize) -> Option<(usize, usize)> {
+ let at = self.to_doc * Point::new(0.0, y);
+ let [dx, dy, ..] = self.to_doc.as_coeffs();
+ // Where along the row the document point stays within the rectangle, axis by axis. The
+ // rectangle holds its minimum edge and not its maximum one, so a row that runs toward the
+ // minimum holds its end there and not its start: each bound keeps whether it is held.
+ let (mut lo, mut hi) = ((f64::NEG_INFINITY, true), (f64::INFINITY, true));
+ for (start, slope, min, max) in [(at.x, dx, b.rect.x0, b.rect.x1), (at.y, dy, b.rect.y0, b.rect.y1)] {
+ if slope == 0.0 {
+ if !(min <= start && start < max) {
+ return None;
+ }
+ continue;
+ }
+ let (t0, t1) = ((min - start) / slope, (max - start) / slope);
+ let (from, to) = if slope > 0.0 { ((t0, true), (t1, false)) } else { ((t1, false), (t0, true)) };
+ // The tighter bound wins, and of two equal bounds the one not held.
+ if from.0 > lo.0 || (from.0 == lo.0 && !from.1) {
+ lo = from;
+ }
+ if to.0 < hi.0 || (to.0 == hi.0 && !to.1) {
+ hi = to;
+ }
+ }
+ // Pixel i's center is i + 0.5: the first pixel whose center is past `lo` (or on it, when
+ // held), up to the first one past `hi` (or on it, when not held).
+ let start = if lo.1 { (lo.0 - 0.5).ceil() } else { (lo.0 - 0.5).floor() + 1.0 };
+ let end = if hi.1 { (hi.0 - 0.5).floor() + 1.0 } else { (hi.0 - 0.5).ceil() };
+ let clamp = |v: f64| v.clamp(0.0, width as f64) as usize;
+ let (mut start, mut end) = (clamp(start), clamp(end));
+ end = end.max(start);
+ // Rounding can put a bound a pixel away from where the rectangle's own test of each pixel's
+ // center puts it: move each end until the two agree.
+ let inside = |i: usize| b.rect.contains(self.to_doc * Point::new(i as f64 + 0.5, y));
+ for _ in 0..2 {
+ if start < end && !inside(start) {
+ start += 1;
+ } else if start > 0 && inside(start - 1) {
+ start -= 1;
+ }
+ }
+ for _ in 0..2 {
+ if end > start && !inside(end - 1) {
+ end -= 1;
+ } else if end < width && inside(end) {
+ end += 1;
+ }
+ }
+ (start < end).then_some((start, end))
+ }
+
+ /// `owner` becomes the artboard on top at each of the `width` pixels of the row whose centers
+ /// lie at height `y` ([`NO_BOARD`] where there is none). Each pixel is taken once, by the
+ /// topmost artboard over it, so a row costs its width plus its artboards however they overlap.
+ fn owners(&self, y: f64, width: usize, owner: &mut Vec, next: &mut Vec) {
+ owner.clear();
+ owner.resize(width, NO_BOARD);
+ next.clear();
+ next.extend(0..=width as u32);
+ for (k, b) in self.boards.iter().enumerate().rev() {
+ let Some((start, end)) = self.span(b, y, width) else { continue };
+ let mut x = untaken(next, start);
+ while x < end {
+ owner[x] = k as u32;
+ next[x] = x as u32 + 1;
+ x = untaken(next, x + 1);
+ }
+ }
+ }
+
+ /// The paper at pixel `i` of the row at height `y`, whose artboard on top is `owner`.
+ fn paper_at(&self, owner: u32, i: usize, y: f64) -> Option {
+ let b = self.boards.get(owner as usize)?;
+ Some(match &self.grid {
+ Some((colors, cell)) => {
+ let p = self.to_doc * Point::new(i as f64 + 0.5, y);
+ let cells = ((p.x - b.origin.x) / cell).floor() + ((p.y - b.origin.y) / cell).floor();
+ colors[usize::from(cells.rem_euclid(2.0) >= 1.0)]
+ }
+ None => b.paper,
+ })
+ }
+
+ /// Rows `first_row..` of the frame, `width` pixels each, in `pixels`.
+ fn rows(&self, pixels: &mut [u8], first_row: usize, width: usize) {
+ let mut last_px = ([0u8; 4], [0u8; 4]);
+ let mut last_mix = (([0u8; 4], [0u8; 3]), [0u8; 4]);
+ let (mut owner, mut next) = (Vec::new(), Vec::new());
+ for (j, line) in pixels.chunks_exact_mut(width * 4).enumerate() {
+ let y = (first_row + j) as f64 + 0.5;
+ // Found for the row's first translucent pixel.
+ let mut found = false;
+ for (i, px) in line.as_chunks_mut::<4>().0.iter_mut().enumerate() {
+ let a = px[3];
+ if a == 0 {
+ continue;
+ }
+ let paper = if a == 255 {
+ None
+ } else if self.everywhere.is_some() {
+ self.everywhere
+ } else {
+ if !found {
+ self.owners(y, width, &mut owner, &mut next);
+ found = true;
+ }
+ self.paper_at(owner[i], i, y)
+ };
+ match paper {
+ Some(p) if last_mix.0 == (*px, p.srgb) => *px = last_mix.1,
+ Some(p) => {
+ let input = (*px, p.srgb);
+ // Drawn over the converted paper, the pixel shows `px` over the paper in sRGB, converted.
+ let under = 255 - u32::from(a);
+ let mix = |c: usize| (u32::from(px[c]) + (u32::from(p.srgb[c]) * under + 127) / 255).min(255) as u8;
+ let shown = self.t.apply8([mix(0), mix(1), mix(2)]);
+ for ((o, s), u) in px.iter_mut().zip(shown).zip(p.shown) {
+ let paper_part = ((u32::from(u) * under + 127) / 255) as i32;
+ *o = (i32::from(s) - paper_part).clamp(0, 255) as u8;
+ }
+ last_mix = (input, *px);
+ }
+ None if last_px.0 == *px => *px = last_px.1,
+ None => {
+ let input = *px;
+ self.t.apply_premultiplied(px);
+ last_px = (input, *px);
+ }
+ }
+ }
+ }
+ }
+}
+
+/// [`convert`], with each translucent pixel over the paper or the transparency grid of `backdrop`
+/// blended with it in sRGB before the conversion. The canvas draws the art over the paper
+/// converted: such a pixel keeps its alpha and takes the color that, drawn over the converted
+/// paper, shows the blend converted. Opaque and fully transparent pixels, and pixels over the
+/// pasteboard, convert as [`convert`] converts them. The pixels are rows of `width`; `view` maps the
+/// document to them, and the backdrop's `zoom` is the canvas's screen points per document point,
+/// in which the grid's cells are measured.
+pub(crate) fn convert_over(t: Option<&DisplayTransform>, pixels: &mut [u8], width: u32, view: Affine, backdrop: Option<(&Backdrop, f64)>) {
+ let Some(t) = t else { return };
+ let width = width as usize;
+ let over = backdrop
+ .filter(|_| width > 0 && pixels.len().is_multiple_of(width * 4))
+ .and_then(|(b, zoom)| Over::new(t, b, view, zoom, (width, pixels.len() / (width * 4))));
+ let Some(over) = over else { return convert(Some(t), pixels) };
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ const PIECE: usize = 256 * 1024 * 4;
+ let threads = std::thread::available_parallelism().map_or(1, usize::from).min(16);
+ if threads > 1 && pixels.len() > PIECE {
+ let rows = (pixels.len() / (width * 4)).div_ceil(threads);
+ let over = &over;
+ std::thread::scope(|scope| {
+ for (k, piece) in pixels.chunks_mut(rows * width * 4).enumerate() {
+ scope.spawn(move || over.rows(piece, k * rows, width));
+ }
+ });
+ return;
+ }
+ }
+ over.rows(pixels, 0, width);
+}
+
/// The opaque or translucent color `c` through `t`.
pub(crate) fn color32(t: Option<&DisplayTransform>, c: egui::Color32) -> egui::Color32 {
let Some(t) = t else { return c };
@@ -308,4 +569,211 @@ pub(crate) mod tests {
let [r, g, b] = t.apply8([255, 0, 0]);
assert_eq!(color32(Some(&t), egui::Color32::RED), egui::Color32::from_rgb(r, g, b));
}
+
+ /// What the canvas shows of pixel `px` drawn over the converted paper `under`, as egui blends it.
+ fn shown_over(px: [u8; 4], under: [u8; 3]) -> [u32; 3] {
+ let k = 255 - u32::from(px[3]);
+ [0, 1, 2].map(|i| u32::from(px[i]) + (u32::from(under[i]) * k + 127) / 255)
+ }
+
+ /// `px` blended with the sRGB paper `paper`, converted.
+ fn blended(t: &DisplayTransform, px: [u8; 4], paper: [u8; 3]) -> [u8; 3] {
+ let k = 255 - u32::from(px[3]);
+ t.apply8([0, 1, 2].map(|i| (u32::from(px[i]) + (u32::from(paper[i]) * k + 127) / 255).min(255) as u8))
+ }
+
+ fn assert_near(got: [u32; 3], want: [u8; 3], at: &str) {
+ assert!((0..3).all(|i| got[i].abs_diff(u32::from(want[i])) <= 1), "{at}: {got:?} shown, {want:?} wanted");
+ }
+
+ /// One row of `n` pixels, every one `px`.
+ fn row(n: usize, px: [u8; 4]) -> Vec {
+ px.repeat(n)
+ }
+
+ #[test]
+ fn translucent_pixels_over_the_paper_are_blended_before_they_are_converted() {
+ let t = DisplayTransform::from_icc(&p3()).unwrap();
+ let half_red = [128, 0, 0, 128];
+ let b = Backdrop { everywhere: None, artboards: vec![(Rect::new(0.0, 0.0, 10.0, 1.0), [255; 3])], grid: None };
+ let mut px = row(20, half_red);
+ px[12..16].copy_from_slice(&[255, 0, 0, 255]);
+ px[16..20].copy_from_slice(&[0; 4]);
+ convert_over(Some(&t), &mut px, 20, Affine::IDENTITY, Some((&b, 1.0)));
+ let at = |i: usize| -> [u8; 4] { px[i * 4..i * 4 + 4].try_into().unwrap() };
+ let white = t.apply8([255; 3]);
+ assert_near(shown_over(at(0), white), blended(&t, half_red, [255; 3]), "over the paper");
+ // Converted alone and drawn over the converted paper, the pixel shows another color.
+ let mut alone = half_red;
+ t.apply_premultiplied(&mut alone);
+ let want = blended(&t, half_red, [255; 3]);
+ assert!((0..3).any(|i| shown_over(alone, white)[i].abs_diff(u32::from(want[i])) > 2), "{alone:?}");
+ assert_eq!(at(0)[3], 128, "the alpha is kept");
+ // Opaque and empty pixels, and pixels over the pasteboard, convert as before.
+ let red = t.apply8([255, 0, 0]);
+ assert_eq!((at(3), at(4)), ([red[0], red[1], red[2], 255], [0; 4]));
+ assert_eq!(at(15), alone, "over the pasteboard");
+ // Without a backdrop, and without a profile, as before.
+ let mut plain = row(20, half_red);
+ convert_over(Some(&t), &mut plain, 20, Affine::IDENTITY, None);
+ assert_eq!(plain, row(20, alone));
+ let mut srgb = row(20, half_red);
+ convert_over(None, &mut srgb, 20, Affine::IDENTITY, Some((&b, 1.0)));
+ assert_eq!(srgb, row(20, half_red));
+ }
+
+ #[test]
+ fn the_backdrop_is_found_through_the_view() {
+ let t = DisplayTransform::from_icc(&p3()).unwrap();
+ // Papers far apart: a pixel blended with the wrong one shows a color several levels off.
+ let half = [128, 0, 0, 128];
+ let (light, dark) = ([255, 230, 230], [40, 40, 30]);
+ // A later artboard is drawn over an earlier one.
+ let b = Backdrop {
+ everywhere: None,
+ artboards: vec![(Rect::new(0.0, 0.0, 100.0, 100.0), light), (Rect::new(50.0, 0.0, 100.0, 100.0), dark)],
+ grid: None,
+ };
+ // A view turned a quarter clockwise and moved: pixel x runs down the document's y axis.
+ let view = Affine::translate((10.0, 0.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::translate((-20.0, -60.0));
+ let mut px = row(10, half);
+ convert_over(Some(&t), &mut px, 10, view, Some((&b, 1.0)));
+ // Pixel (2.5, 0.5) is document point (20.5, 67.5): on the first artboard only.
+ let at = |i: usize| -> [u8; 4] { px[i * 4..i * 4 + 4].try_into().unwrap() };
+ assert_near(shown_over(at(2), t.apply8(light)), blended(&t, half, light), "on the first artboard");
+ let view = Affine::translate((-60.0, -5.0));
+ let mut px = row(10, half);
+ convert_over(Some(&t), &mut px, 10, view, Some((&b, 1.0)));
+ let at = |i: usize| -> [u8; 4] { px[i * 4..i * 4 + 4].try_into().unwrap() };
+ assert_near(shown_over(at(0), t.apply8(dark)), blended(&t, half, dark), "where the second covers the first");
+ // View › Hide Artboards: the paper everywhere.
+ let all = Backdrop { everywhere: Some(dark), artboards: vec![], grid: None };
+ let mut px = row(10, half);
+ convert_over(Some(&t), &mut px, 10, Affine::translate((-5000.0, 0.0)), Some((&all, 1.0)));
+ assert_near(shown_over(px[..4].try_into().unwrap(), t.apply8(dark)), blended(&t, half, dark), "Hide Artboards");
+ // Overlapping artboards under a turned and scaled view, against a direct lookup of the
+ // artboard on top whose rectangle holds each pixel's center.
+ let boards: Vec<(Rect, [u8; 3])> = (0..12u8)
+ .map(|k| {
+ let (x, y) = (f64::from(k) * 7.0, f64::from(k % 3) * 9.0);
+ (Rect::new(x, y, x + 15.0, y + 20.0), if k % 2 == 0 { [255, 255, 255 - k] } else { [20 + k, 20, 30] })
+ })
+ .collect();
+ let check = |boards: &[(Rect, [u8; 3])], view: Affine, (w, h): (usize, usize)| {
+ let b = Backdrop { everywhere: None, artboards: boards.to_vec(), grid: None };
+ let mut px = row(w * h, half);
+ convert_over(Some(&t), &mut px, w as u32, view, Some((&b, 1.0)));
+ let to_doc = view.inverse();
+ let mut on_paper = 0;
+ for i in 0..w * h {
+ let p = to_doc * Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5);
+ let mut want = half.to_vec();
+ match boards.iter().rev().find(|(r, _)| r.contains(p)) {
+ Some(&(_, paper)) => {
+ let one = Backdrop { everywhere: Some(paper), artboards: vec![], grid: None };
+ convert_over(Some(&t), &mut want, 1, Affine::IDENTITY, Some((&one, 1.0)));
+ on_paper += 1;
+ }
+ None => t.apply_premultiplied(&mut want),
+ }
+ assert_eq!(&px[i * 4..i * 4 + 4], &want[..], "pixel {i} at {p:?} through {view:?}");
+ }
+ assert!(on_paper > 100 && on_paper < w * h, "{on_paper} pixels on the artboards");
+ };
+ check(&boards, Affine::rotate(0.3) * Affine::scale(1.7) * Affine::translate((5.0, -3.0)), (64, 48));
+ // Rows that run backward across the artboards, with pixel centers on their edges: an edge
+ // at the minimum is on the artboard, one at the maximum is not.
+ check(&boards, Affine::new([-1.0, 0.0, 0.0, 1.0, 92.5, 0.0]), (96, 44));
+ check(&boards, Affine::new([-1.0, 0.0, 0.0, -1.0, 92.5, 40.5]), (96, 44));
+ // A sheared view where a computed bound falls on a pixel center that rounding puts just
+ // outside the artboard: the pixel's own center decides.
+ check(&[(Rect::new(-100.0, -2.0, 100.0, 100.0), [40, 40, 30])], Affine::new([3.0, 1.5, 0.1, 0.5, -0.3, 0.0]), (64, 48));
+ }
+
+ #[test]
+ fn the_transparency_grid_is_blended_cell_by_cell() {
+ let t = DisplayTransform::from_icc(&p3()).unwrap();
+ let half = [128, 0, 0, 128];
+ // Far apart, so that a pixel blended with the other cell's color shows several levels off.
+ let (light, dark) = ([255; 3], [40; 3]);
+ // Cells of 10 points from the artboard's corner at (5, 0), here 1 pixel a point.
+ let b = Backdrop { everywhere: None, artboards: vec![(Rect::new(5.0, 0.0, 65.0, 20.0), [255, 0, 0])], grid: Some(([light, dark], 10.0)) };
+ let check = |zoom: f64, cells: [(usize, [u8; 3]); 3]| {
+ let mut px = row(60, half);
+ convert_over(Some(&t), &mut px, 60, Affine::IDENTITY, Some((&b, zoom)));
+ for (i, paper) in cells {
+ assert_near(
+ shown_over(px[i * 4..i * 4 + 4].try_into().unwrap(), t.apply8(paper)),
+ blended(&t, half, paper),
+ &format!("pixel {i} at {zoom}"),
+ );
+ }
+ };
+ check(1.0, [(6, light), (16, dark), (26, light)]);
+ // At 200% a cell is 5 document points.
+ check(2.0, [(6, light), (11, dark), (16, light)]);
+ }
+
+ #[test]
+ fn large_frames_blend_the_same_on_several_threads() {
+ let t = DisplayTransform::from_icc(&p3()).unwrap();
+ let b = Backdrop {
+ everywhere: None,
+ artboards: vec![(Rect::new(0.0, 0.0, 500.0, 900.0), [240, 230, 220])],
+ grid: Some(([[255; 3], [200; 3]], 8.0)),
+ };
+ let (w, h) = (1000, 1000);
+ let mut big: Vec = (0..w * h * 4).map(|i| (i * 7 % 251) as u8).collect();
+ for px in big.as_chunks_mut::<4>().0 {
+ let a = px[3];
+ for c in &mut px[..3] {
+ *c = (*c).min(a);
+ }
+ }
+ let mut one = big.clone();
+ Over::new(&t, &b, Affine::IDENTITY, 1.0, (w, h)).unwrap().rows(&mut one, 0, w);
+ convert_over(Some(&t), &mut big, w as u32, Affine::IDENTITY, Some((&b, 1.0)));
+ assert_eq!(big, one);
+ }
+
+ #[test]
+ fn artboards_outside_the_frame_are_not_looked_up() {
+ let t = DisplayTransform::from_icc(&p3()).unwrap();
+ let half = [128, 0, 0, 128];
+ // A row of 1,000 artboards 30 points apart, each 20 wide and 40 high.
+ let artboards: Vec<(Rect, [u8; 3])> = (0..1000u32)
+ .map(|k| {
+ let x = f64::from(k) * 30.0;
+ (Rect::new(x, 0.0, x + 20.0, 40.0), [255 - (k % 200) as u8, 240, 230])
+ })
+ .collect();
+ let b = Backdrop { everywhere: None, artboards: artboards.clone(), grid: None };
+ // A turned frame of 64 × 48 pixels over the artboards near x = 15,000.
+ let view = Affine::rotate(0.4) * Affine::translate((-15_000.0, -5.0));
+ let (w, h) = (64, 48);
+ let over = Over::new(&t, &b, view, 1.0, (w, h)).unwrap();
+ assert!((1..=4).contains(&over.boards.len()), "{} artboards kept", over.boards.len());
+ // Each pixel still uses the artboard its center is on.
+ let mut px = row(w * h, half);
+ convert_over(Some(&t), &mut px, w as u32, view, Some((&b, 1.0)));
+ let to_doc = view.inverse();
+ let mut on_paper = 0;
+ for i in 0..w * h {
+ let p = to_doc * Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5);
+ let mut want = half.to_vec();
+ match artboards.iter().rev().find(|(r, _)| r.contains(p)) {
+ Some(&(_, paper)) => {
+ let one = Backdrop { everywhere: Some(paper), artboards: vec![], grid: None };
+ convert_over(Some(&t), &mut want, 1, Affine::IDENTITY, Some((&one, 1.0)));
+ on_paper += 1;
+ }
+ None => t.apply_premultiplied(&mut want),
+ }
+ assert_eq!(&px[i * 4..i * 4 + 4], &want[..], "pixel {i} at {p:?}");
+ }
+ assert!(on_paper > 100 && on_paper < w * h, "{on_paper} pixels on the artboards");
+ // A frame over none of the artboards keeps none, and converts as without a backdrop.
+ let away = Affine::translate((0.0, -500.0));
+ assert_eq!(Over::new(&t, &b, away, 1.0, (w, h)).map(|o| o.boards.len()), Some(0));
+ }
}
diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv
index 115eb9d69a..6191819c85 100644
--- a/crates/ui-egui/src/i18n/bg.tsv
+++ b/crates/ui-egui/src/i18n/bg.tsv
@@ -13,6 +13,7 @@
Edge Brightness Яркост на ръба
Smoothness Гладкост
Radial Blur… Лъчезарно размазване…
+ Blur Center Център на размазването
Smart Blur… Интелигентно размазване…
Sharpen Изостряне
Unsharp Mask… Контурна маска…
@@ -630,6 +631,7 @@ font-technology Variable Променливи
Copy All Styles Копиране на всички стилове
Copy Color Value (Hex) Копиране на цветова стойност (Hex)
Copy Fonts Used in the Document Копиране на шрифтовете, използвани в документа
+ Copy Info Копиране на информация
Copy Links Копиране на връзките
Copy Selected Style Копиране на избрания стил
Copy to User Defined Копиране в потребителски
@@ -4181,6 +4183,7 @@ axis Both И двете
Stop the script and undo what it did? Then quit again. Да се спре ли скриптът и да се отменят ли промените му? След това излезте отново.
This script has added a great many objects. Continue, or stop it and undo what it did? Този скрипт добави изключително много обекти. Да продължи ли, или да се спре и да се отменят промените му?
@msg Copied the script report Копиран е отчетът за скрипта
+@msg Copied the link info Информацията за връзката е копирана
@msg Corners edits the corners of a path Ъглите редактират ъглите на пътя
@msg Couldn't copy to the system clipboard: {e} Неуспешно копиране в системния клипборд: {e}
@msg Couldn't open {name}: {e} Неуспешно отваряне на {name}: {e}
diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv
index ffb73c464e..214979c0cb 100644
--- a/crates/ui-egui/src/i18n/bs.tsv
+++ b/crates/ui-egui/src/i18n/bs.tsv
@@ -971,6 +971,7 @@
Free Transform Slobodna transformacija
Perspective Distort Izobličenje perspektive
Radial Blur… Radijalno zamućenje…
+ Blur Center Središte zamućenja
Smart Blur… Pametno zamućenje…
Sharpen Izoštri
Unsharp Mask… Maska izoštravanja…
@@ -2699,6 +2700,7 @@ digits Malayalam Malajalam
Transparent Background Prozirna pozadina
Choose… Odaberi…
Copy Fonts Used in the Document Kopiraj fontove korištene u dokumentu
+ Copy Info Kopiraj informacije
Copy Links Kopiraj veze
Create Report Kreiraj izvještaj
Fonts whose licence doesn't allow embedding are not copied. Fontovi čija licenca ne dozvoljava ugrađivanje ne kopiraju se.
@@ -4546,6 +4548,7 @@ imageTrace Outline Obris
Stop the script and undo what it did? Then quit again. Zaustaviti skriptu i poništiti ono što je uradila? Zatim ponovo izađite.
This script has added a great many objects. Continue, or stop it and undo what it did? Ova skripta je dodala veoma mnogo objekata. Nastaviti, ili je zaustaviti i poništiti ono što je uradila?
@msg Copied the script report Izvještaj skripte kopiran
+@msg Copied the link info Informacije o vezi kopirane
@msg Corners edits the corners of a path Uglovi uređuje uglove putanje
@msg Couldn't copy to the system clipboard: {e} Nije moguće kopirati u sistemski međuspremnik: {e}
@msg Couldn't open {name}: {e} Nije moguće otvoriti {name}: {e}
diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv
index 8457d0d623..d2317ad67b 100644
--- a/crates/ui-egui/src/i18n/ca.tsv
+++ b/crates/ui-egui/src/i18n/ca.tsv
@@ -930,6 +930,7 @@ antiAlias Sharp Nítid
Copy Guide Copia la guia
Copy in Perspective Copia en perspectiva
Copy into the document's folder Copia a la carpeta del document
+ Copy Info Copia la informació
Copy Links Copia els enllaços
Copy only fonts you own or are licensed to install. Copia només els tipus de lletra que tinguis o que tinguis llicència per instal·lar.
Copy Report Copia l’informe
@@ -3396,6 +3397,7 @@ digits Malayalam Malaiàlam
Radial Radial
Radial Blur Desenfocament radial
Radial Blur… Desenfocament radial…
+ Blur Center Centre del desenfocament
Radial Dividers: Divisors radials:
Radial Glows Resplendors radials
Radial Gradient Degradat radial
@@ -5597,6 +5599,7 @@ digits Malayalam Malaiàlam
@msg there is no script engine named {name} no hi ha cap motor d'scripts anomenat {name}
@msg Running a script S'està executant un script
@msg Copied the script report S’ha copiat l’informe de l’script
+@msg Copied the link info S’ha copiat la informació de l’enllaç
@msg Corners edits the corners of a path Cantonades edita les cantonades d’un traçat
@msg could not decode image: {0} no s’ha pogut descodificar la imatge: {0}
@msg Couldn't copy to the system clipboard: {e} No s’ha pogut copiar al porta-retalls del sistema: {e}
@@ -6350,6 +6353,7 @@ digits Malayalam Malaiàlam
@msg the spine has no segments l’espina no té segments
@msg the stroke has no weight el traç no té gruix
@msg the SVG's elements are nested more than {0} deep els elements de l’SVG estan imbricats a més de {0} nivells de profunditat
+@msg the SVG's style sheets take too long to match fer coincidir els fulls d’estil de l’SVG triga massa
@msg the SVG's styles expand to more than {0} MB els estils de l’SVG s’expandeixen a més de {0} MB
@msg the target layer is locked or hidden la capa de destinació està blocada o amagada
@msg the thumbnail image is malformed la imatge de la miniatura està mal formada
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index e0c7035177..ce93986b39 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -990,6 +990,7 @@
# Photoshop-style raster effects (Effect menu, their dialogs).
Radial Blur… Radiální rozostření…
+ Blur Center Střed rozostření
Smart Blur… Chytré rozostření…
Sharpen Zostření
Unsharp Mask… Maska rozostření…
@@ -2734,6 +2735,7 @@ digits Malayalam Malajálamské
Transparent Background Průhledné pozadí
Choose… Vybrat…
Copy Fonts Used in the Document Kopírovat písma použitá v dokumentu
+ Copy Info Kopírovat informace
Copy Links Kopírovat propojené soubory
Create Report Vytvořit zprávu
Fonts whose licence doesn't allow embedding are not copied. Písma, jejichž licence nepovoluje vkládání, se nekopírují.
@@ -4703,6 +4705,7 @@ imageTrace Outline Obrys
@msg there is no script engine named {name} skriptovací jádro s názvem {name} neexistuje
@msg Running a script Běží skript
@msg Copied the script report Zpráva o skriptu zkopírována
+@msg Copied the link info Informace o propojení zkopírovány
@msg Corners edits the corners of a path Rohy upravuje rohy cesty
@msg Couldn't copy to the system clipboard: {e} Nelze kopírovat do systémové schránky: {e}
@msg Couldn't open {name}: {e} {name} nelze otevřít: {e}
@@ -9032,6 +9035,7 @@ breakText Glyphs Glyfy
@msg the RTF file is too large to place as type (at most {_1} MB) soubor RTF je příliš velký na umístění jako text (nejvýše {_1} MB)
@msg the SVG expands to more than {0} nested SVG images SVG se rozvine na více než {0} vnořených obrázků SVG
@msg the SVG expands to more than {0} objects SVG se rozvine na více než {0} objektů
+@msg the SVG's style sheets take too long to match porovnání šablon stylů SVG trvá příliš dlouho
@msg the SVG's styles expand to more than {0} MB styly SVG se rozvinou na více než {0} MB
@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes soubor SVG je větší než {MAX_IMPORT_BYTES} bajtů
@msg the SVG has no drawable objects SVG nemá žádné vykreslitelné objekty
diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv
index e9061c9278..94c9b3d361 100644
--- a/crates/ui-egui/src/i18n/da.tsv
+++ b/crates/ui-egui/src/i18n/da.tsv
@@ -1522,6 +1522,7 @@
Free Transform Fri transformering
Perspective Distort Perspektivforvrængning
Radial Blur… Radial sløring…
+ Blur Center Sløringens midtpunkt
Smart Blur… Smart sløring…
Sharpen Skarphed
Unsharp Mask… Uskarp maskering…
@@ -3125,6 +3126,7 @@ digits Malayalam Malayalam
Transparent Background Gennemsigtig baggrund
Choose… Vælg…
Copy Fonts Used in the Document Kopiér skrifttyper, der bruges i dokumentet
+ Copy Info Kopiér info
Copy Links Kopiér links
Create Report Opret rapport
Fonts whose licence doesn't allow embedding are not copied. Skrifttyper, hvis licens ikke tillader indlejring, kopieres ikke.
@@ -4907,6 +4909,7 @@ imageTrace Outline Kontur
Stop the script and undo what it did? Then quit again. Stop scriptet og fortryd det, det har gjort? Afslut derefter igen.
This script has added a great many objects. Continue, or stop it and undo what it did? Dette script har tilføjet rigtig mange objekter. Fortsæt, eller stop det og fortryd det, det har gjort?
@msg Copied the script report Kopierede scriptrapporten
+@msg Copied the link info Kopierede linkinfo
@msg Corners edits the corners of a path Hjørner redigerer hjørnerne på en kurve
@msg Couldn't copy to the system clipboard: {e} Kunne ikke kopiere til systemets udklipsholder: {e}
@msg Couldn't open {name}: {e} Kunne ikke åbne {name}: {e}
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 0b06cc8a8d..22118409e0 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -25,6 +25,7 @@
Edge Brightness Kantenhelligkeit
Smoothness Glättung
Radial Blur… Radialer Weichzeichner…
+ Blur Center Mittelpunkt der Weichzeichnung
Smart Blur… Selektiver Weichzeichner…
Sharpen Scharfzeichnen
Unsharp Mask… Unscharf maskieren…
@@ -623,6 +624,7 @@ font-technology Variable Variabel
Copy All Styles Alle Stile kopieren
Copy Color Value (Hex) Farbwert kopieren (Hex)
Copy Fonts Used in the Document Im Dokument verwendete Schriften kopieren
+ Copy Info Informationen kopieren
Copy Links Verknüpfungen kopieren
Copy Selected Style Ausgewählten Stil kopieren
Copy to User Defined In „Benutzerdefiniert“ kopieren
@@ -4315,6 +4317,7 @@ theme Appearance Erscheinungsbild
@msg there is no script engine named {name} es gibt keine Skript-Engine namens {name}
@msg Running a script Skript wird ausgeführt
@msg Copied the script report Skriptbericht kopiert
+@msg Copied the link info Verknüpfungsinformationen kopiert
@msg Corners edits the corners of a path „Ecken“ bearbeitet die Ecken eines Pfads
@msg Couldn't copy to the system clipboard: {e} In die Systemzwischenablage konnte nicht kopiert werden: {e}
@msg Couldn't open {name}: {e} {name} konnte nicht geöffnet werden: {e}
@@ -8597,6 +8600,7 @@ breakText Glyphs Glyphen
@msg the RTF file is too large to place as type (at most {_1} MB) die RTF-Datei ist zu groß, um als Text platziert zu werden (höchstens {_1} MB)
@msg the SVG expands to more than {0} nested SVG images das SVG wird zu mehr als {0} verschachtelten SVG-Bildern erweitert
@msg the SVG expands to more than {0} objects das SVG wird zu mehr als {0} Objekten erweitert
+@msg the SVG's style sheets take too long to match das Abgleichen der Stylesheets des SVG dauert zu lange
@msg the SVG's styles expand to more than {0} MB die Stile des SVG werden auf mehr als {0} MB erweitert
@msg the SVG has no drawable objects das SVG hat keine zeichenbaren Objekte
@msg the SVGZ file unpacks to more than {_1} MB die SVGZ-Datei wird auf mehr als {_1} MB entpackt
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index fa5fca58dd..bd3ed6e1c4 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -10,6 +10,7 @@
Edge Brightness Φωτεινότητα ακμών
Smoothness Ομαλότητα
Radial Blur… Ακτινική θόλωση…
+ Blur Center Κέντρο θόλωσης
Smart Blur… Έξυπνη θόλωση…
Sharpen Όξυνση
Unsharp Mask… Μάσκα όξυνσης…
@@ -604,6 +605,7 @@ font-technology Variable Μεταβλητές
Copy All Styles Αντιγραφή όλων των στυλ
Copy Color Value (Hex) Αντιγραφή τιμής χρώματος (Hex)
Copy Fonts Used in the Document Αντιγραφή γραμματοσειρών που χρησιμοποιούνται στο έγγραφο
+ Copy Info Αντιγραφή πληροφοριών
Copy Links Αντιγραφή συνδέσεων
Copy Selected Style Αντιγραφή επιλεγμένου στυλ
Copy to User Defined Αντιγραφή σε ορισμένα από τον χρήστη
@@ -2448,6 +2450,7 @@ axis Both Και τα δύο
@msg there is no script engine named {name} δεν υπάρχει μηχανή σεναρίων με όνομα {name}
@msg Running a script Εκτελείται σενάριο
@msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε
+@msg Copied the link info Οι πληροφορίες συνδέσμου αντιγράφηκαν
@msg Corners edits the corners of a path Η εντολή Γωνίες επεξεργάζεται τις γωνίες μιας διαδρομής
@msg Couldn't copy to the system clipboard: {e} Δεν ήταν δυνατή η αντιγραφή στο πρόχειρο συστήματος: {e}
@msg Couldn't open {name}: {e} Δεν ήταν δυνατό το άνοιγμα του {name}: {e}
@@ -4820,6 +4823,7 @@ digits Malayalam Μαλαγιάλαμ
@msg result would exceed the canvas (coordinates out of range) το αποτέλεσμα θα υπερέβαινε τον καμβά (συντεταγμένες εκτός εύρους)
@msg objects can't be nested more than 32 deep τα αντικείμενα δεν μπορούν να έχουν ένθεση μεγαλύτερη των 32 επιπέδων
@msg the SVG's elements are nested more than {0} deep τα στοιχεία SVG έχουν ένθεση μεγαλύτερη των {0} επιπέδων
+@msg the SVG's style sheets take too long to match η αντιστοίχιση των φύλλων στυλ του SVG διαρκεί πολύ
@msg the SVG's styles expand to more than {0} MB τα στυλ του SVG επεκτείνονται σε περισσότερα από {0} MB
@msg scale must be a number from {_1} to {_2}, not {_3} το scale πρέπει να είναι αριθμός από {_1} έως {_2}, όχι {_3}
@msg scale must be a number from {_1} to {_2}, not {s} το scale πρέπει να είναι αριθμός από {_1} έως {_2}, όχι {s}
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 59da9db59c..cf59eaece3 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -18,6 +18,7 @@
Edge Brightness Brillo del borde
Smoothness Suavizado
Radial Blur… Desenfoque radial…
+ Blur Center Centro del desenfoque
Smart Blur… Desenfoque inteligente…
Sharpen Enfocar
Unsharp Mask… Máscara de enfoque…
@@ -645,6 +646,7 @@ font-technology Variable Variables
Copy All Styles Copiar todos los estilos
Copy Color Value (Hex) Copiar valor de color (hex)
Copy Fonts Used in the Document Copiar fuentes usadas en el documento
+ Copy Info Copiar información
Copy Links Copiar vínculos
Copy Selected Style Copiar estilo seleccionado
Copy to User Defined Copiar en Definido por el usuario
@@ -4392,6 +4394,7 @@ axis Both Ambos
@msg there is no script engine named {name} no hay ningún motor de scripts llamado {name}
@msg Running a script Ejecutando un script
@msg Copied the script report Se copió el informe del script
+@msg Copied the link info Se copió la información del vínculo
@msg Corners edits the corners of a path Esquinas edita las esquinas de un trazado
@msg Couldn't copy to the system clipboard: {e} No se pudo copiar al portapapeles del sistema: {e}
@msg Couldn't open {name}: {e} No se pudo abrir {name}: {e}
@@ -4864,6 +4867,7 @@ axis Both Ambos
@msg result would exceed the canvas (coordinates out of range) el resultado excedería el lienzo (coordenadas fuera de rango)
@msg objects can't be nested more than 32 deep los objetos no pueden anidarse a más de 32 niveles
@msg the SVG's elements are nested more than {0} deep los elementos del SVG están anidados a más de {0} niveles
+@msg the SVG's style sheets take too long to match la comparación de las hojas de estilo del SVG tarda demasiado
@msg the SVG's styles expand to more than {0} MB los estilos del SVG se expanden a más de {0} MB
@msg scale must be a number from {_1} to {_2}, not {_3} scale debe ser un número de {_1} a {_2}, no {_3}
@msg scale must be a number from {_1} to {_2}, not {s} scale debe ser un número de {_1} a {_2}, no {s}
diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv
index e7f4221a83..10b3e29aec 100644
--- a/crates/ui-egui/src/i18n/fi.tsv
+++ b/crates/ui-egui/src/i18n/fi.tsv
@@ -974,6 +974,7 @@
Free Transform Vapaa muunnos
Perspective Distort Perspektiivivääristys
Radial Blur… Säteittäinen sumennus…
+ Blur Center Sumennuksen keskipiste
Smart Blur… Älykäs sumennus…
Sharpen Terävöitä
Unsharp Mask… Epäterävä maski…
@@ -2678,6 +2679,7 @@ digits Malayalam Malajalam
Transparent Background Läpinäkyvä tausta
Choose… Valitse…
Copy Fonts Used in the Document Kopioi asiakirjassa käytetyt fontit
+ Copy Info Kopioi tiedot
Copy Links Kopioi linkit
Create Report Luo raportti
Fonts whose licence doesn't allow embedding are not copied. Fontteja, joiden lisenssi ei salli upottamista, ei kopioida.
@@ -4617,6 +4619,7 @@ imageTrace Outline Ääriviiva
@msg there is no script engine named {name} skriptimoottoria nimeltä {name} ei ole
@msg Running a script Suoritetaan komentosarjaa
@msg Copied the script report Komentosarjan raportti kopioitiin
+@msg Copied the link info Linkin tiedot kopioitiin
@msg Corners edits the corners of a path Kulmat-toiminto muokkaa polun kulmia
@msg Couldn't copy to the system clipboard: {e} Järjestelmän leikepöydälle ei voitu kopioida: {e}
@msg Couldn't open {name}: {e} Tiedostoa {name} ei voitu avata: {e}
@@ -5079,6 +5082,7 @@ imageTrace Outline Ääriviiva
@msg result would exceed the canvas (coordinates out of range) tulos ylittäisi kankaan (koordinaatit alueen ulkopuolella)
@msg objects can't be nested more than 32 deep objekteja ei voi sisäkkäistää yli 32 tason syvyyteen
@msg the SVG's elements are nested more than {0} deep elementit ovat SVG-tiedostossa sisäkkäin yli {0} tason syvyydessä
+@msg the SVG's style sheets take too long to match SVG-tiedoston tyylisivujen täsmäytys kestää liian kauan
@msg the SVG's styles expand to more than {0} MB SVG-tiedoston tyylit laajenevat yli {0} megatavuksi
@msg scale must be a number from {_1} to {_2}, not {_3} scale-arvon on oltava luku väliltä {_1}–{_2}, ei {_3}
@msg scale must be a number from {_1} to {_2}, not {s} scale-arvon on oltava luku väliltä {_1}–{_2}, ei {s}
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index a7def487ac..9c437c5899 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -19,6 +19,7 @@
Edge Brightness Luminosité du bord
Smoothness Lissage
Radial Blur… Flou radial…
+ Blur Center Centre du flou
Smart Blur… Flou optimisé…
Sharpen Renforcement
Unsharp Mask… Accentuation…
@@ -646,6 +647,7 @@ font-technology Variable Variables
Copy All Styles Copier tous les styles
Copy Color Value (Hex) Copier la valeur de couleur (hex)
Copy Fonts Used in the Document Copier les polices utilisées dans le document
+ Copy Info Copier les informations
Copy Links Copier les liens
Copy Selected Style Copier le style sélectionné
Copy to User Defined Copier dans Défini par l’utilisateur
@@ -4381,6 +4383,7 @@ axis Both Les deux
@msg there is no script engine named {name} il n'y a aucun moteur de script nommé {name}
@msg Running a script Exécution d’un script
@msg Copied the script report Rapport du script copié
+@msg Copied the link info Informations sur le lien copiées
@msg Corners edits the corners of a path Angles modifie les angles d’un tracé
@msg Couldn't copy to the system clipboard: {e} Impossible de copier dans le presse-papiers du système : {e}
@msg Couldn't open {name}: {e} Impossible d’ouvrir {name} : {e}
@@ -8893,6 +8896,7 @@ breakText Glyphs Glyphes
@msg the RTF file is too large to place as type (at most {_1} MB) le fichier RTF est trop volumineux pour être importé comme texte (au plus {_1} Mo)
@msg the SVG expands to more than {0} nested SVG images le SVG se développe en plus de {0} images SVG imbriquées
@msg the SVG expands to more than {0} objects le SVG se développe en plus de {0} objets
+@msg the SVG's style sheets take too long to match la mise en correspondance des feuilles de style du SVG prend trop de temps
@msg the SVG's styles expand to more than {0} MB les styles du SVG se développent en plus de {0} Mo
@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes le fichier SVG dépasse {MAX_IMPORT_BYTES} octets
@msg the SVG has no drawable objects le SVG n’a aucun objet dessinable
diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv
index 2fac5c0999..08ca1ce59c 100644
--- a/crates/ui-egui/src/i18n/gu.tsv
+++ b/crates/ui-egui/src/i18n/gu.tsv
@@ -743,6 +743,7 @@
Copy Artboard આર્ટબોર્ડ નકલ કરો
Copy Color Value (Hex) રંગ મૂલ્યની નકલ કરો (Hex)
Copy Guide ગાઇડ નકલ કરો
+ Copy Info માહિતી નકલ કરો
Copy Report રિપોર્ટ નકલ કરો
Copy Script Console સ્ક્રિપ્ટ કન્સોલ નકલ કરો
Copy Selected પસંદ કરેલું નકલ કરો
@@ -2770,6 +2771,7 @@
Radar Graph Tool રડાર ગ્રાફ ટૂલ
Radial રેડિયલ
Radial Blur… રેડિયલ બ્લર…
+ Blur Center બ્લરનું કેન્દ્ર
Radial Dividers: રેડિયલ વિભાજક:
Radial Glows રેડિયલ ઝગમગાટ
Radial Gradient રેડિયલ ગ્રેડિઅન્ટ
diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv
index eb65028fdd..f7f1552e86 100644
--- a/crates/ui-egui/src/i18n/hi.tsv
+++ b/crates/ui-egui/src/i18n/hi.tsv
@@ -763,8 +763,8 @@ antiAlias Sharp शार्प
Change Case प्रकरण बदलें
Change Panel Layout पैनल लेआउट बदलें
Change Screen Mode (F) स्क्रीन मोड बदलें (F)
- Change to Artboard Rulers आर्टबोर्ड शासकों में परिवर्तन
- Change to Global Rulers वैश्विक शासकों में परिवर्तन
+ Change to Artboard Rulers आर्टबोर्ड रूलर्स में परिवर्तन
+ Change to Global Rulers ग्लोबल रूलर्स में परिवर्तन
Change to Left-to-Right Layout लेफ्ट-टू-राइट लेआउट में परिवर्तन
Change to Right-to-Left Layout राइट-टू-लेफ्ट लेआउट में परिवर्तन
Changed since the last check. आखिरी चेक के बाद से बदल गया।
@@ -780,12 +780,12 @@ antiAlias Sharp शार्प
Channel 4 चैनल 4
Character कैरेक्टर
Character / Paragraph कैरेक्टर / पैराग्राफ
- Character Alignment चरित्र संरेखण
- Character Color चरित्र रंग
- Character Direction चरित्र निर्देशन
- Character options चरित्र ऑप्शन्स
- Character Rotation चरित्र रोटेशन
- Character Set: चरित्र सेट:
+ Character Alignment कैरेक्टर संरेखण
+ Character Color कैरेक्टर रंग
+ Character Direction कैरेक्टर दिशा
+ Character options कैरेक्टर ऑप्शन्स
+ Character Rotation कैरेक्टर रोटेशन
+ Character Set: कैरेक्टर सेट:
Character Style कैरेक्टर स्टाइल
Character Style Options कैरेक्टर स्टाइल ऑप्शन्स
Character Styles कैरेक्टर स्टाइल्स
@@ -975,7 +975,7 @@ antiAlias Sharp शार्प
Compatible Gradient and Gradient Mesh Printing कंपैटिबल ग्रेडिएंट और ग्रेडिएंट मेश प्रिंटिंग
Compiled or not text संकलित या टेक्स्ट नहीं
Compiled script: ask its author for the .jsx file कंपाइल की हुई स्क्रिप्ट: इसके लेखक से .jsx फ़ाइल माँगें
- Complement संगम
+ Complement पूरक
Complementary पूरक
Complementary 2 पूरक 2
Complete पूरा करना
@@ -992,18 +992,18 @@ antiAlias Sharp शार्प
Compression संपीड़न
Compression › Color › Above Ppi संपीड़न › रंग › पीपीआई के ऊपर
Compression: संपीड़न:
- Concave अवतरण
+ Concave अवतल
Concentric Dividers: सांद्रिक विभाजक:
Condition identifier: शर्त पहचानकर्ता:
Configure Shape आकार को कॉन्फ़िगर करें
Conflict {n} of {count} {count} में से विरोध {n}
Connect कनेक्ट
- Connect Selected End Points कनेक्ट सिलेक्टेड अंत अंक
+ Connect Selected End Points सिलेक्टेड एंड पॉइंट्स कनेक्ट करें
Consider Open Filled Paths as Closed बंद के रूप में ओपन भरा पाथ पर विचार करें
Consolidate All Windows सभी विंडो एक साथ लाएँ
- Constrain कंस्ट्रक्शन
- Constrain Angle कंस्ट्रक्शन एंगल
- Constrain Width and Height Proportions कंस्ट्रक्शन चौड़ाई और ऊंचाई के अनुपात
+ Constrain सीमित करें
+ Constrain Angle कंस्ट्रेन एंगल
+ Constrain Width and Height Proportions चौड़ाई और ऊंचाई का अनुपात बनाए रखें
Construction Guides निर्माण गाइड
Conté Crayon कॉन्टे क्रेयॉन
Conté Crayon… कॉन्टे क्रेयॉन…
@@ -1061,6 +1061,7 @@ antiAlias Sharp शार्प
Copy Guide कॉपी गाइड
Copy in Perspective पर्सपेक्टिव में प्रतिलिपि
Copy into the document's folder डॉक्यूमेंट के फ़ोल्डर में कॉपी करें
+ Copy Info जानकारी कॉपी करें
Copy Links कॉपी लिंक
Copy only fonts you own or are licensed to install. केवल उन फ़ॉन्टों को कॉपी करें जिन्हें आप स्वयं करते हैं या इंस्टॉल करने के लिए लाइसेंस प्राप्त हैं।
Copy Report रिपोर्ट कॉपी करें
@@ -1182,7 +1183,7 @@ antiAlias Sharp शार्प
Cut Artboard कट आर्टबोर्ड
Rename Artboards आर्टबोर्ड्स का नाम बदलें
Cut Path कट पाथ
- Cut Path at Selected Anchor Points सिलेक्टेड एंकर अंक पर पाथ काटें
+ Cut Path at Selected Anchor Points सिलेक्टेड एंकर पॉइंट्स पर पाथ काटें
Cutout कटआउट
Cutout… कटआउट…
Cyan सियान
@@ -1326,7 +1327,7 @@ antiAlias Sharp शार्प
Description: विवरण:
Deselect डीसिलेक्ट करें
Design… डिजाइन…
- Desired देसी
+ Desired वांछित
Destination Folder: गंतव्य फ़ोल्डर:
Destination: गंतव्य:
Detail डिटेल
@@ -1355,7 +1356,7 @@ antiAlias Sharp शार्प
Dimensions आयाम
Direct Selection प्रत्यक्ष सिलेक्शन
Direct Selection Tool डायरेक्ट सिलेक्शन टूल
- Direct-select anchor points to edit them. उन्हें संपादित करने के लिए डायरेक्ट-सिलेक्शन एंकर अंक।
+ Direct-select anchor points to edit them. एंकर पॉइंट्स को संपादित करने के लिए उन्हें डायरेक्ट-सिलेक्ट करें।
Direction Balance दिशा संतुलन
Direction Handles निर्देशन हैंडल
Direction: दिशा:
@@ -1686,7 +1687,7 @@ antiAlias Sharp शार्प
Envelope #10 लिफाफाफा #10
Envelope Distort एन्वेलप डिस्टॉर्ट
Envelope DL लिफ़ाफ़ा DL
- Envelope Info लिफाफे की जानकारी
+ Envelope Info एन्वेलप जानकारी
Envelope Mesh एन्वेलप मेश
Envelope Options एन्वेलप ऑप्शन्स
Envelope Options… एन्वेलप ऑप्शन्स…
@@ -1697,7 +1698,7 @@ antiAlias Sharp शार्प
Eraser Tool इरेज़र टूल
Error त्रुटि
Esc Esc
- Even शाम
+ Even बराबर
Even Fields सम फ़ील्ड्स
Even-Numbered Anchors यहां तक कि संख्या वाले एंकर
Event: कार्यक्रम:
@@ -1872,7 +1873,7 @@ antiAlias Sharp शार्प
Fill new strokes नए स्ट्रोक भरें
Fill New Type Objects With Placeholder Text नए टाइप ऑब्जेक्ट्स में प्लेसहोल्डर टेक्स्ट भरें
Fill Pattern पैटर्न भरें
- Fill Rule नियम भरें
+ Fill Rule फ़िल रूल
Fill with Placeholder Text प्लेसहोल्डर टेक्स्ट से भरें
Fill: फ़िल:
Fill: click for swatches, Shift-click for the color mixer फ़िल: स्वॉचेस के लिए क्लिक करें, कलर मिक्सर के लिए Shift-क्लिक करें
@@ -1880,7 +1881,7 @@ antiAlias Sharp शार्प
Filled Open Paths भरा खुला पाथ
Filled Square भरा वर्ग
Filling in form fields and signing फॉर्म फ़ील्ड में भरना और साइन करना
- Fills भरता
+ Fills फ़िल्स
Film & Video फ़िल्म और वीडियो
Film Grain… फ़िल्म ग्रेन…
Filter फ़िल्टर
@@ -1984,7 +1985,7 @@ antiAlias Sharp शार्प
fonts not copied: {fonts} फ़ॉन्ट कॉपी नहीं हुए: {fonts}
Fonts whose licence doesn't allow embedding are not copied. जिन फ़ॉन्ट का लाइसेंस एम्बेडिंग की अनुमति नहीं देता है, उन्हें कॉपी नहीं किया जाता है।
For Fractions: फ्रैक्शन के लिए:
- Force सेना
+ Force बलपूर्वक
Forced Line Break जबरन लाइन ब्रेक
Foreground Level फ़ोरग्राउंड स्तर
Forget Import Matches फॉरगेट आयात मैच
@@ -2023,7 +2024,7 @@ antiAlias Sharp शार्प
Full Width पूर्ण चौड़ाई
Fully Inside पूरी तरह से अंदर
Fully Outside पूरी तरह बाहर
- Function Key: समारोह कुंजी:
+ Function Key: फ़ंक्शन की:
Fuzziness: फ़ज़ीनेस:
Gamma गामा
Gamut Check गैमट जाँच
@@ -2221,8 +2222,8 @@ antiAlias Sharp शार्प
Hide Gradient Annotator ग्रेडिएंट एनोटेटर छिपाएँ
Hide Grid ग्रिड छिपाएँ
Hide Guides गाइड्स छिपाएँ
- Hide Hidden Characters छिपे हुए चरित्र छुपाएं
- Hide Live Paint Gaps छुपा लाइव पेंट गैप
+ Hide Hidden Characters हिडन कैरेक्टर छिपाएँ
+ Hide Live Paint Gaps लाइव पेंट गैप छिपाएँ
Hide Note नोट छिपाएँ
Hide Options ऑप्शन्स छिपाएँ
Hide Others अन्य छिपाएँ
@@ -2234,23 +2235,23 @@ antiAlias Sharp शार्प
Hide Template टेम्पलेट छिपाएँ
Hide Text Threads टेक्स्ट थ्रेड छुपाएं
Hide Thumbnail थंबनेल छिपाएँ
- Hide Thumbnails हिंदुस्तान
+ Hide Thumbnails थंबनेल छिपाएँ
Hide Transparency Grid पारदर्शिता ग्रिड छिपाएँ
Hide Units इकाइयाँ छिपाएँ
Hide VectorCraft VectorCraft छिपाएँ
- Hide Video Rulers वीडियो शासक
+ Hide Video Rulers वीडियो रूलर्स छिपाएँ
High उच्च
High (300 ppi) उच्च (300 ppi)
- High Contrast उच्च न्यायालय
- High Contrast 2 उच्च न्यायालय 2
- High Contrast 3 उच्च न्यायालय 3
+ High Contrast उच्च कंट्रास्ट
+ High Contrast 2 उच्च कंट्रास्ट 2
+ High Contrast 3 उच्च कंट्रास्ट 3
High Fidelity Photo उच्च निष्ठा फोटो
High Performance (discrete) उच्च निष्पादन (डिस्क्रीट)
High Quality Print उच्च गुणवत्ता वाले प्रिंट
High resolution उच्च रिज़ॉल्यूशन
High Resolution उच्च रिज़ॉल्यूशन
Highlight हाइलाइट
- Highlight Alternate Glyphs हाइलाइट अल्टरनेटर ग्लिफ़
+ Highlight Alternate Glyphs अल्टरनेट ग्लिफ़ हाइलाइट करें
Highlight anchors on mouse over माउस ओवर पर हाइलाइट एंकर
Highlight Area हाइलाइट क्षेत्र
Highlight Font Name हाइलाइट फ़ॉन्ट नाम
@@ -2475,7 +2476,7 @@ antiAlias Sharp शार्प
Keep Original मूल रखें
Keep Plain Text प्लेन टेक्स्ट रखें
Keep selected सिलेक्ट करें
- Keep Shared Points Together साझा अंक एक साथ रखें
+ Keep Shared Points Together साझा पॉइंट्स एक साथ रखें
Keep the pasted color as a new swatch with a numbered name. पेस्ट किए गए रंग को क्रमांकित नाम वाले नए स्वॉच के रूप में रखें।
Keep this row's colors (exclude) इस पंक्ति के रंग (बाहर) रखें
Keep visible surfaces only when expanding विस्तार करते समय केवल दृश्यमान सतहों को रखें
@@ -2762,7 +2763,7 @@ antiAlias Sharp शार्प
Manage Workspaces… वर्कस्पेस प्रबंधित करें…
Manually मैन्युअल
Marathi मराठी
- Mark as trapped निशानेबाज़ी
+ Mark as trapped ट्रैप्ड के रूप में चिह्नित करें
Mark Older Files as [Converted] When Opened पुरानी फ़ाइलें ओपन करने पर उन्हें [Converted] चिह्नित करें
Marker… मार्कर…
Marks मार्क्स
@@ -2833,7 +2834,7 @@ antiAlias Sharp शार्प
Minimize छोटा करें
Minimum न्यूनतम
Minimum angle न्यूनतम कोण
- Minimum must not exceed Desired, nor Desired Maximum. न्यूनतम से अधिक नहीं होना चाहिए, न ही अधिकतम होना चाहिए।
+ Minimum must not exceed Desired, nor Desired Maximum. न्यूनतम, वांछित से अधिक नहीं होना चाहिए और वांछित, अधिकतम से अधिक नहीं होना चाहिए।
Minimum: न्यूनतम:
Minus Back पीछे वाला घटाएँ
Minus Front सामने वाला घटाएँ
@@ -3037,7 +3038,7 @@ antiAlias Sharp शार्प
Next Segment अगला खंड
No नहीं
No actions. Press ● to record. कोई कार्रवाई नहीं। प्रेस ● रिकॉर्ड करने के लिए।
- No alternates for the selected character. सिलेक्टेड चरित्र के लिए कोई ऑप्शन नहीं।
+ No alternates for the selected character. सिलेक्टेड कैरेक्टर के लिए कोई अल्टरनेट नहीं।
No artboards match. कोई आर्टबोर्ड मैच नहीं।
No assets कोई संपत्ति नहीं
No assets yet. Collect art with Object › Collect for Export, or drag it into the Asset Export panel. अभी कोई एसेट नहीं है। ऑब्जेक्ट › एक्सपोर्ट के लिए कलेक्ट करें से आर्टवर्क जोड़ें या उसे एसेट एक्सपोर्ट पैनल में ड्रैग करें।
@@ -3120,7 +3121,7 @@ antiAlias Sharp शार्प
Number of Recent Fonts हाल ही में फ़ॉन्ट की संख्या
Number: संख्या:
Numbered List क्रमांकित सूची
- Numbers Without Units Are Points यूनिट्स के बिना नंबर अंक हैं
+ Numbers Without Units Are Points यूनिट्स के बिना संख्याएँ पॉइंट में हैं
Numerator न्यूमेरेटर
Object ऑब्जेक्ट
Object Highlighting ऑब्जेक्ट हाइलाइटिंग
@@ -3294,7 +3295,7 @@ antiAlias Sharp शार्प
Outer Glow… बाहरी ग्लो…
Outline रूपरेखा
Outline Object रूपरेखा ऑब्जेक्ट
- Outline Others अन्य लोग
+ Outline Others अन्य को आउटलाइन व्यू में दिखाएँ
Outline Stroke स्ट्रोक को आउटलाइन में बदलें
Outline Text टेक्स्ट को आउटलाइन में बदलें
Outlined Strokes रेखांकित स्ट्रोक
@@ -3348,7 +3349,7 @@ antiAlias Sharp शार्प
Pages पृष्ठ
Paint Daubs पेंट डॉब्स
Paint Daubs… पेंट डॉब्स…
- Paint Fills पेंट भरता
+ Paint Fills फ़िल्स पेंट करें
Paint Opacity: पेंट ओपेसिटी:
Paint Stops At: पेंट स्टॉप:
Paint Strokes पेंट स्ट्रोक
@@ -3581,7 +3582,7 @@ antiAlias Sharp शार्प
Pointillize पॉइंटिलाइज़
Pointillize… पॉइंटिलाइज़…
Points पॉइंट्स
- Points per segment प्रति खंड अंक
+ Points per segment प्रति सेगमेंट पॉइंट्स
Points: पॉइंट्स:
Points: clicks add free points पॉइंट्स: क्लिक से अलग-अलग पॉइंट जुड़ते हैं
Polar Grid ध्रुवीय ग्रिड
@@ -3732,6 +3733,7 @@ antiAlias Sharp शार्प
Radial रेडियल
Radial Blur रेडियल ब्लर
Radial Blur… रेडियल ब्लर…
+ Blur Center ब्लर का केंद्र
Radial Dividers: रेडियल विभाजक:
Radial Glows रेडियल चमक
Radial Gradient रेडियल ग्रेडिएंट
@@ -3919,7 +3921,7 @@ antiAlias Sharp शार्प
Remove Line Breaks लाइन ब्रेक हटाएँ
Remove Paragraph Breaks पैराग्राफ ब्रेक निकालें
Remove Plug-in प्लग-इन निकालें
- Remove Points, Keep Shape अंक निकालें, आकार रखें
+ Remove Points, Keep Shape पॉइंट्स हटाएँ, शेप रखें
Remove Redundant Points गैरज़रूरी पॉइंट हटाएँ
Remove Selected Assets सिलेक्टेड परिसंपत्तियों को हटा दें
Remove Selected Entry सिलेक्टेड प्रविष्टि निकालें
@@ -4024,7 +4026,7 @@ antiAlias Sharp शार्प
Edit Arrowheads… एरोहेड्स संपादित करें…
Reload Arrowheads एरोहेड्स फिर से लोड करें
Reset Rotate View व्यू घुमाएँ रीसेट करें
- Reset Ruler Origin शासकीय उत्पत्ति रीसेट करें
+ Reset Ruler Origin रूलर ओरिजिन रीसेट करें
Reset Symbol Instance सिंबल इंस्टेंस रीसेट करें
Reset Text Transform टेक्स्ट ट्रांसफॉर्मर को रीसेट करें
Reset Text Transform and Scale टेक्स्ट ट्रांसफॉर्म और स्केल को रीसेट करें
@@ -4098,7 +4100,7 @@ antiAlias Sharp शार्प
RGB: RGB:
Ridges per segment: प्रति खंड रिज:
Right दाएँ
- Right Complement सही पूरक
+ Right Complement राइट कम्प्लीमेंट
Right Diagonal दायाँ विकर्ण
Right Grid: राइट ग्रिड:
Right in Front फ्रंट में राइट
@@ -4157,14 +4159,14 @@ antiAlias Sharp शार्प
Ruby रूबी
Ruby… रूबी…
Rule: नियम:
- Ruler Origin शासकीय उत्पत्ति
+ Ruler Origin रूलर ओरिजिन
Rulers रूलर्स
Rulers & Grids रूलर्स और ग्रिड
Run Length रन लंबाई
Run Plug-in रन प्लग-इन
Runs code the checker can't read रन कोड चेकर को पढ़ा नहीं जा सकता
Russian रूसी
- Same समीर
+ Same समान
Same As Source स्रोत के समान
Same file एक ही फ़ाइल
Same item as a later row बाद में पंक्ति के रूप में समान आइटम
@@ -4307,8 +4309,8 @@ antiAlias Sharp शार्प
Saved Views सेव किया गया दृश्य
Saves the current bars, toolbar and panel layout. वर्तमान बार, टूलबार और पैनल लेआउट को सेव करता है।
Saving सेव किया जा रहा है
- Saving {} बचत {}
- Saving Poster.vectorcraft बचत Poster.vectorcraft
+ Saving {} {} सेव किया जा रहा है
+ Saving Poster.vectorcraft Poster.vectorcraft सेव किया जा रहा है
Saving recovery data for {} {} के लिए रिकवरी डेटा सेव करना
Scale आकार बदलें
Scale Artwork with Artboard आर्टबोर्ड के साथ स्केल आर्टवर्क
@@ -4372,7 +4374,7 @@ antiAlias Sharp शार्प
Select a character with the Type tool to see its alternates. अल्टरनेट ग्लिफ़ देखने के लिए टाइप टूल से कोई कैरेक्टर सिलेक्ट करें।
Select a parametric shape to edit it. With none selected, these set the next shape. एडिट करने के लिए पैरामीट्रिक शेप सिलेक्ट करें। कोई शेप सिलेक्ट न होने पर ये सेटिंग्स अगली शेप पर लागू होंगी।
Select a text object एक टेक्स्ट ऑब्जेक्ट चुनें
- Select a text object to edit its character attributes. अपने चरित्र विशेषताओं को संपादित करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें।
+ Select a text object to edit its character attributes. कैरेक्टर एट्रिब्यूट्स संपादित करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें।
Select a text object to edit its paragraph attributes. अपनी पैराग्राफ विशेषताओं को संपादित करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें।
Select a text object to set its tab stops. अपने टैब स्टॉप सेट करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें।
Select All सभी सिलेक्ट करें
@@ -4401,7 +4403,7 @@ antiAlias Sharp शार्प
Select by Link Status… लिंक स्थिति द्वारा सिलेक्ट करें…
Select Data Set डेटा सेट सिलेक्ट करें
Select Embedded एम्बेडेड सिलेक्ट करें
- Select Fills भरता सिलेक्ट करें
+ Select Fills फ़िल्स सिलेक्ट करें
Select Freeform Point फ़्रीफ़ॉर्म पॉइंट सिलेक्ट करें
Select Gradient Stop ग्रेडिएंट स्टॉप चुनें
Select Guides गाइड्स सिलेक्ट करें
@@ -4648,7 +4650,7 @@ antiAlias Sharp शार्प
Show Tool Tips टूल युक्तियाँ दिखाएँ
Show Toolbar शो टूलबार
Show Transparency Grid पारदर्शिता ग्रिड दिखाएँ
- Show Video Rulers शो वीडियो शासक
+ Show Video Rulers वीडियो रूलर्स दिखाएँ
Show Video Safe Areas वीडियो सुरक्षित क्षेत्र दिखाएं
Show Vivid/Muted चमकीले/मंद दिखाएँ
Show Warm/Cool शो वार्म / कूल
@@ -5114,7 +5116,7 @@ antiAlias Sharp शार्प
The Print Tiling tool placed the pages. प्रिंट टाइलिंग टूल ने पृष्ठों को रखा।
The samples show this brush on a blue stroke. नमूने इस ब्रश को ब्लू स्ट्रोक पर दिखाते हैं।
The search stopped at its limit: search a smaller folder. सर्च अपनी लिमिट तक पहुँच गई: छोटे फ़ोल्डर में सर्च करें।
- The selected character's font is not available. सिलेक्टेड चरित्र का फ़ॉन्ट उपलब्ध नहीं है।
+ The selected character's font is not available. सिलेक्टेड कैरेक्टर का फ़ॉन्ट उपलब्ध नहीं है।
The selected objects have no CSS of their own (see below). सिलेक्टेड ऑब्जेक्ट का अपना CSS नहीं है (नीचे देखें)।
The system's settings of this printer इस प्रिंटर की प्रणाली की सेटिंग
These fonts aren't available. Their text shows in another font. ये फ़ॉन्ट उपलब्ध नहीं हैं। इनका टेक्स्ट दूसरे फ़ॉन्ट में दिखता है।
@@ -5148,7 +5150,7 @@ antiAlias Sharp शार्प
Tile Edge Color टाइल एज रंग
Tile Edge Color… टाइल एज रंग…
Tile Full Pages टाइल पूर्ण पृष्ठ
- Tile Imageable Areas टाइल कल्पनाशील क्षेत्र
+ Tile Imageable Areas इमेजेबल क्षेत्र टाइल करें
Tile Range: टाइल रेंज:
Tile Size टाइल साइज़
Tile Type: टाइल प्रकार:
@@ -5257,9 +5259,9 @@ antiAlias Sharp शार्प
Transverse (the page a quarter turn on the paper) ट्रांसवर्स (पेपर पर एक चौथाई मोड़ पृष्ठ)
Trap ट्रैप
Trap… ट्रैप…
- Traps with Process Color प्रक्रिया रंग के साथ जाल
- Triad त्रिदाद
- Triad 2 त्रिद 2
+ Traps with Process Color प्रोसेस रंग के साथ ट्रैप
+ Triad त्रिक
+ Triad 2 त्रिक 2
Triad 3 त्रिक 3
Triangle त्रिभुज
Triangle (open) त्रिभुज (ओपन)
@@ -5267,7 +5269,7 @@ antiAlias Sharp शार्प
Trim ट्रिम करें
Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. अपीयरेंस एक्सपैंड करने पर ढकी हुई ज्यामिति ट्रिम करें। लाइव प्रीव्यू पूरी सतह रखता है। ट्रांसपेरेंट पेंट और विज़िबिलिटी लिमिट से बड़ी सतहों के सभी फेस बने रहते हैं।
Trim mark weight: ट्रिम मार्क वजन:
- Trim marks ट्रिम अंक
+ Trim marks ट्रिम मार्क्स
Trim View ट्रिम देखें
True Colors असली रंग
True colour needs version 2004 or later: the nearest of 256 colours is written. ट्रू कलर के लिए संस्करण 2004 या बाद का चाहिए: अभी 256 रंगों में सबसे निकट वाला रंग लिखा जाता है।
@@ -5494,7 +5496,7 @@ antiAlias Sharp शार्प
Video 1920×1080 1920 × 1080 वीडियो
Video 3840×2160 वीडियो 3840 × 2160
Video Banner 2560×1440 वीडियो बैनर 2560 × 1440
- Video Ruler Pixel Aspect Ratio: वीडियो शासक पिक्सेल दृष्टि अनुपात:
+ Video Ruler Pixel Aspect Ratio: वीडियो रूलर पिक्सेल आस्पेक्ट रेशियो:
Fade Region Outside Artboard आर्टबोर्ड के बाहर का क्षेत्र धुंधला करें
Update While Dragging खींचते समय अपडेट करें
Video Thumbnail 1280×720 वीडियो थंबनेल 1280 × 720
@@ -5519,7 +5521,7 @@ antiAlias Sharp शार्प
Warp Options वार्प ऑप्शन्स
Warp Tool वार्प टूल
Watch 184×224 घड़ी 184 × 224
- Watch 198×242 देखें 198 × 242
+ Watch 198×242 घड़ी 198 × 242
Water Paper वॉटर पेपर
Water Paper… वॉटर पेपर…
Watercolor वॉटरकलर
@@ -6016,7 +6018,7 @@ antiAlias Sharp शार्प
@msg `{name}` is no recovery entry name `{name}` कोई वसूली प्रविष्टि नाम नहीं है
@msg `{name}` isn't a colour swatch `{name}` रंग स्वॉच नहीं है
@msg `{name}` takes a paint of its own kind (colour, gradient or pattern) `{name}` अपने ही प्रकार का पेंट लेता है (रंग, ग्रेडिएंट या पैटर्न)
-@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: न्यूनतम इच्छा से अधिक नहीं होना चाहिए, न ही इच्छा अधिकतम
+@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: न्यूनतम, वांछित से अधिक नहीं होना चाहिए और वांछित, अधिकतम से अधिक नहीं होना चाहिए
@msg `{other}` doesn't trace an image `{other}` एक इमेज का पता नहीं लगा
@msg `{path}` must be a bool or an object of bools `{path}` एक bool होना चाहिए या एक ऑब्जेक्ट होना चाहिए।
@msg `{s}` is not a colour (#rrggbb or a preset name) `{s}` एक रंग नहीं है (#rrggbb या एक पूर्व निर्धारित नाम)
@@ -6371,7 +6373,7 @@ antiAlias Sharp शार्प
@msg a wraparound group is inside a compound path एक रैपराउंड समूह एक मिश्रित पाथ के अंदर है
@msg action is required action आवश्यक है
@msg add a format to export निर्यात करने के लिए एक फ़ॉर्मैट जोड़ें
-@msg Add Points at Crossings: a path went missing क्रॉसिंग्स में अंक जोड़ें: एक पाथ गायब हो गया
+@msg Add Points at Crossings: a path went missing क्रॉसिंग पर पॉइंट जोड़ें: एक पाथ गायब हो गया
@msg aiVersion {v}: "pdf" (PDF-compatible, the default) or "7" (legacy .ai, version 7) aiVersion {v}: "pdf" (PDF-संगत, डिफ़ॉल्ट) या "7" (पुरानी .ai, संस्करण 7)
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 विरासत .ai फ़ाइलों को लिखते हैं, .ait टेम्पलेट नहीं
@msg All colors are within the CMYK gamut सभी रंग CMYK गामट के भीतर हैं
@@ -6559,7 +6561,7 @@ antiAlias Sharp शार्प
@msg choose at least one status कम से कम एक स्थिति चुनें
@msg Choose original artwork, not a dimension's generated paths मूल आर्टवर्क चुनें, एक आयाम उत्पन्न पाथ नहीं
@msg choose the font files to add जोड़ने के लिए फ़ॉन्ट फ़ाइलों को चुनें
-@msg Choose two different points दो अलग-अलग अंक चुनें
+@msg Choose two different points दो अलग-अलग पॉइंट्स चुनें
@msg Choose two non-parallel straight segments दो गैर-parallel सीधे खंड चुनें
@msg Choose two nonzero angle arms दो nonzero कोण हथियार चुनें
@msg Click in type with a Type tool to split it इसे विभाजित करने के लिए टाइप टूल के साथ टाइप करें
@@ -6709,6 +6711,7 @@ antiAlias Sharp शार्प
@msg there is no script engine named {name} {name} नाम का कोई स्क्रिप्ट इंजन नहीं है
@msg Running a script स्क्रिप्ट चल रही है
@msg Copied the script report Copied स्क्रिप्ट रिपोर्ट
+@msg Copied the link info लिंक जानकारी कॉपी की गई
@msg copy needs path: the file to copy into the document's folder copy के लिए path चाहिए: डॉक्यूमेंट के फ़ोल्डर में कॉपी करने वाली फ़ाइल
@msg copy takes images only: relink placed documents where their files are copy केवल इमेज लेता है: प्लेस किए गए डॉक्यूमेंट्स को वहीं फिर से लिंक करें जहाँ उनकी फ़ाइलें हैं
@msg copying a file isn't available on the web एक फ़ाइल की प्रतिलिपि वेब पर उपलब्ध नहीं है
@@ -6776,7 +6779,7 @@ antiAlias Sharp शार्प
@msg Dimension mode does not match its source आयाम मोड अपने स्रोत से मेल नहीं खाता है
@msg Dimension point is outside the canvas आयाम बिंदु कैनवास के बाहर है
@msg Dimension size is outside its supported range आयाम आकार अपनी समर्थित सीमा से बाहर है
-@msg direct-select anchor points of a path एक पाथ के प्रत्यक्ष सिलेक्शन एंकर अंक
+@msg direct-select anchor points of a path किसी पाथ के एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें
@msg direct-select anchor points to cut at (not the end points of open paths) डायरेक्ट-सिलेक्शन एंकर पॉइंट्स को कट करने के लिए ( ओपन पाथ के अंतिम बिंदु नहीं)
@msg direct-select the anchor points to remove हटाने के लिए एंकर पॉइंट्स सिलेक्ट करें
@msg distance must be > 0 distance > 0 होना चाहिए
@@ -6831,7 +6834,7 @@ antiAlias Sharp शार्प
@msg exit isolation mode first पहले अलगाव मोड से बाहर निकलें
@msg Expand Appearance: the selection has a basic appearance उपस्थिति का विस्तार: सिलेक्शन में एक बुनियादी उपस्थिति है
@msg Expand: no brush strokes selected विस्तार: सिलेक्टेड कोई ब्रश स्ट्रोक नहीं
-@msg Expand: no gradient fills विस्तार: कोई ग्रेडिएंट भरता नहीं
+@msg Expand: no gradient fills एक्सपैंड: कोई ग्रेडिएंट फ़िल नहीं
@msg Expand: nothing to expand विस्तार: विस्तार करने के लिए कुछ नहीं
@msg expanded SVG styles exceed the import size limit विस्तारित SVG स्टाइल्स आयात आकार सीमा से अधिक है
@msg expected {{"dataBase64": "…"}} अपेक्षित: {{"dataBase64": "…"}}
@@ -6964,7 +6967,7 @@ antiAlias Sharp शार्प
@msg Global Edit is off ग्लोबल एडिट बंद है
@msg Global Edit works on paths, compound paths, symbol instances and groups of them ग्लोबल एडिट पाथ, मिश्रित पाथ, सिंबल उदाहरणों और उनके समूहों पर काम करता है
@msg global must be true or false global को true या false होना चाहिए
-@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) Glyph {_1} चरित्र की स्टाइल (जैसे सभी कैप्स, छोटे कैप्स या एक संख्यात्मक प्रणाली) के साथ {ch} के लिए तैयार नहीं है।
+@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) Glyph {_1} कैरेक्टर की स्टाइल (जैसे सभी कैप्स, छोटे कैप्स या एक संख्यात्मक प्रणाली) के साथ {ch} के लिए तैयार नहीं है।
@msg glyph {g} is not an alternate of {ch} in {_1} {_2} Glyph {g} {_1} {_2} में {ch} का एक वैकल्पिक नहीं है।
@msg gradient “{name}” isn't defined in the file: a plain colour stands in for it ग्रेडिएंट "{name}" को फ़ाइल में परिभाषित नहीं किया गया है: इसके लिए एक सादे रंग खड़ा है
@msg gradient must be "objects" or "mesh" gradient "objects" या "mesh" होना चाहिए
@@ -7221,8 +7224,8 @@ antiAlias Sharp शार्प
@msg missing point लापता बिंदु
@msg missing point [x,y] लापता बिंदु [x,y]
@msg missing point `{key}` ([x, y]) लापता बिंदु `{key}` ([x, y])
-@msg missing points लापता अंक
-@msg missing points [[x,y]…] लापता अंक [[x,y]...]
+@msg missing points पॉइंट्स नहीं दिए गए
+@msg missing points [[x,y]…] पॉइंट्स नहीं दिए गए [[x,y]…]
@msg missing segment लापता खंड
@msg missing stops लापता ठहराव
@msg missing subpaths लापता subpaths
@@ -7269,7 +7272,7 @@ antiAlias Sharp शार्प
@msg no active data set कोई सक्रिय डेटा सेट नहीं
@msg no active document कोई सक्रिय डॉक्यूमेंट
@msg no active perspective plane कोई सक्रिय पर्सपेक्टिव विमान नहीं
-@msg no anchor points selected कोई एंकर अंक नहीं चुना गया
+@msg no anchor points selected कोई एंकर पॉइंट सिलेक्ट नहीं है
@msg no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है
@msg no appearance item {index} कोई उपस्थिति आइटम {index}
@msg no artboard कोई आर्टबोर्ड नहीं
@@ -7294,7 +7297,7 @@ antiAlias Sharp शार्प
@msg no brush selected कोई ब्रश नहीं चुना गया
@msg no catalog कोई सूची नहीं
@msg no changes since the last save आखिरी सेव के बाद से कोई बदलाव नहीं
-@msg no character at byte {start} byte {start} पर कोई चरित्र नहीं
+@msg no character at byte {start} byte {start} पर कोई कैरेक्टर नहीं
@msg no character style `{name}` कोई कैरेक्टर स्टाइल `{name}`
@msg no clock to keep a heartbeat by हार्टबीट का समय रखने के लिए कोई घड़ी नहीं
@msg no color group `{name}` in the document (see swatch.list) डॉक्यूमेंट में कोई रंग समूह `{name}` (देखें swatch.list)
@@ -7798,7 +7801,7 @@ antiAlias Sharp शार्प
@msg Saved to User Defined: {_1} उपयोगकर्ता परिभाषित करने के लिए सेव किया गया: {_1}
@msg savedPreset: {e} savedPreset: {e}
@msg Saving सेव किया जा रहा है
-@msg Saving {_1} बचत {_1}
+@msg Saving {_1} {_1} सेव किया जा रहा है
@msg Saving recovery data for {_1} {_1} के लिए रिकवरी डेटा सेव करना
@msg scale `{s}`: a factor such as 2x, a width (100w), a height (100h) or a resolution (72ppi) पैमाने `{s}`: एक कारक जैसे 2x, चौड़ाई (100w), ऊंचाई (100h) या एक रिज़ॉल्यूशन (72ppi)
@msg scale must be a number above 0, at most 64 scale 0 से बड़ी और अधिकतम 64 संख्या होनी चाहिए
@@ -7890,7 +7893,7 @@ antiAlias Sharp शार्प
@msg Select only dimensions केवल आयाम सिलेक्ट करें
@msg select open paths to close बंद करने के लिए खुले रास्ते सिलेक्ट करें
@msg select paths पाथ चुनें
-@msg select paths or anchor points पाथ या एंकर अंक चुनें
+@msg select paths or anchor points पाथ या एंकर पॉइंट्स चुनें
@msg select paths or compound paths पाथ या यौगिक पाथ सिलेक्ट करें
@msg select paths to join जोड़ने के लिए पाथ सिलेक्ट करें
@msg select paths with dashed strokes to expand विस्तृत करने के लिए डैश स्ट्रोक के साथ पाथ सिलेक्ट करें
@@ -7898,7 +7901,7 @@ antiAlias Sharp शार्प
@msg select plain rectangles, ellipses or regular polygons to convert बदलने के लिए सादे आयत, अंडाकार या नियमित बहुभुजों सिलेक्ट करें
@msg Select point type पॉइंट टाइप सिलेक्ट करें
@msg select rows or objects to collect इकट्ठा करने के लिए पंक्तियों या ऑब्जेक्ट्स सिलेक्ट करें
-@msg select segments, or paths, to add points to खंडों, या पाथ का सिलेक्ट करने के लिए, अंक जोड़ने के लिए
+@msg select segments, or paths, to add points to पॉइंट्स जोड़ने के लिए सेगमेंट या पाथ सिलेक्ट करें
@msg select some type first पहले कुछ टाइप सिलेक्ट करें
@msg select something to export निर्यात करने के लिए कुछ का सिलेक्शन
@msg select something to export (or turn off selectedOnly) एक्सपोर्ट करने के लिए कुछ चुनें (या selectedOnly बंद करें)
@@ -8084,7 +8087,7 @@ antiAlias Sharp शार्प
@msg the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size आर्टबोर्ड कैनवास पर फिट नहीं हैं: कम आर्टबोर्ड, कम रिक्ति या छोटे आकार
@msg the background worker stopped पृष्ठभूमि कार्यकर्ता बंद कर दिया
@msg the blend has no spine मिश्रण में कोई रीढ़ नहीं है
-@msg the character's size can't be measured चरित्र का आकार मापा नहीं जा सकता है
+@msg the character's size can't be measured कैरेक्टर का आकार मापा नहीं जा सकता है
@msg the CMYK image couldn't be written CMYK इमेज को नहीं लिखा जा सकता
@msg the Color Picker is not open रंग पिकर खुला नहीं है
@msg the compound shape is too complex to expand मिश्रित आकार का विस्तार करने के लिए बहुत जटिल है
@@ -8137,7 +8140,7 @@ antiAlias Sharp शार्प
@msg the file's variable library couldn't be read: the Variables panel doesn't list it फ़ाइल की वेरिएबल लाइब्रेरी पढ़ी नहीं जा सकी: वेरिएबल्स पैनल उसे सूचीबद्ध नहीं करता
@msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest फ़ाइल की वेरिएबल लाइब्रेरी आंशिक रूप से पढ़ी गई (छोड़ी गई प्रविष्टियाँ: {_1}): वेरिएबल्स पैनल शेष प्रविष्टियाँ दिखाता है
@msg the files come to more than 1 GB: add fewer at a time फ़ाइलों को 1 GB से अधिक करने के लिए आते हैं: एक समय में कम जोड़ें
-@msg the first character of a line has no character before it to kern: it moves only up and down (dy) एक पंक्ति के पहले चरित्र में बर्न से पहले कोई चरित्र नहीं है: यह केवल ऊपर और नीचे चला जाता है (डी)
+@msg the first character of a line has no character before it to kern: it moves only up and down (dy) किसी लाइन के पहले कैरेक्टर से पहले कर्न करने के लिए कोई कैरेक्टर नहीं है: यह केवल ऊपर और नीचे जाता है (dy)
@msg the font {_1} is not available फ़ॉन्ट {_1} उपलब्ध नहीं है
@msg the format has no file extension फ़ॉर्मैट में कोई फ़ाइल एक्सटेंशन नहीं है
@msg the graphic can't be read: {e} ग्राफिक पढ़ा नहीं जा सकता: {e}
@@ -8298,6 +8301,7 @@ antiAlias Sharp शार्प
@msg the subpath is closed or too short to close सबपैथ बंद है या बंद करने के लिए बहुत कम है
@msg the SVG expands to more than {0} nested SVG images SVG {0} नेस्टेड SVG इमेज से अधिक का विस्तार करता है
@msg the SVG expands to more than {0} objects SVG {0} ऑब्जेक्ट्स से अधिक का विस्तार करता है
+@msg the SVG's style sheets take too long to match SVG की स्टाइल शीट का मिलान करने में बहुत अधिक समय लगता है
@msg the SVG's styles expand to more than {0} MB SVG की शैलियाँ {0} MB से अधिक तक विस्तारित होती हैं
@msg the SVG has no drawable objects SVG में कोई आकर्षक ऑब्जेक्ट नहीं है
@msg the SVG's elements are nested more than {0} deep SVG के तत्वों को {0} से अधिक गहरा घोंसला दिया जाता है
@@ -8426,8 +8430,8 @@ antiAlias Sharp शार्प
@msg unknown brush type `{o}` अज्ञात ब्रश प्रकार `{o}`
@msg unknown category `{c}` अज्ञात श्रेणी `{c}`
@msg unknown category `{c}` ({_1}) अज्ञात श्रेणी `{c}` ({_1})
-@msg unknown character `{c}` अज्ञात चरित्र `{c}`
-@msg unknown character style number field अज्ञात चरित्र स्टाइल संख्या क्षेत्र
+@msg unknown character `{c}` अज्ञात कैरेक्टर `{c}`
+@msg unknown character style number field अज्ञात कैरेक्टर स्टाइल संख्या फ़ील्ड
@msg unknown CMYK profile `{name}` अज्ञात CMYK प्रोफ़ाइल `{name}`
@msg unknown command `{0}` अज्ञात आदेश `{0}`
@msg step {step} of “{action}” runs the unknown command `{command}` “{action}” का चरण {step} अज्ञात आदेश `{command}` चलाता है
diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv
index 2db2b2a04e..58e843aae2 100644
--- a/crates/ui-egui/src/i18n/hu.tsv
+++ b/crates/ui-egui/src/i18n/hu.tsv
@@ -838,6 +838,7 @@ font-technology Variable Változó
Copy Artboard Rajztábla másolása
Copy Color Value (Hex) Színérték másolása (hex)
Copy Fonts Used in the Document A dokumentumban használt betűtípusok másolása
+ Copy Info Adatok másolása
Copy Links Csatolások másolása
Copy only fonts you own or are licensed to install. Csak olyan betűtípust másolj, amely a tiéd, vagy amelynek telepítésére licenced van.
Copy Selected Style Kijelölt stílus másolása
@@ -3261,6 +3262,7 @@ mark-style Japanese Japán
Radial Körkörös
Radial Blur Körkörös elmosás
Radial Blur… Körkörös elmosás…
+ Blur Center Elmosás középpontja
Radial Glows Körkörös ragyogások
Organic Fades Organikus áttűnések
Holographic Holografikus
@@ -5204,6 +5206,7 @@ imageTrace Outline Körvonal
@msg there is no script engine named {name} nincs {name} nevű parancsfájlmotor
@msg Running a script Parancsfájl futtatása
@msg Copied the script report Szkriptjelentés másolva
+@msg Copied the link info Csatolás adatai másolva
@msg Corners edits the corners of a path a Sarkok parancs egy útvonal sarkait szerkeszti
@msg could not decode image: {0} a kép nem dekódolható: {0}
@msg Couldn't copy to the system clipboard: {e} Nem sikerült a rendszer vágólapjára másolni: {e}
@@ -8902,6 +8905,7 @@ breakText Glyphs Glifák
@msg the RTF file is too large to place as type (at most {_1} MB) az RTF-fájl túl nagy ahhoz, hogy szövegként elhelyezhető legyen (legfeljebb {_1} MB)
@msg the SVG expands to more than {0} nested SVG images az SVG kibontva több mint {0} beágyazott SVG-képet tartalmaz
@msg the SVG expands to more than {0} objects az SVG kibontva több mint {0} objektumot tartalmaz
+@msg the SVG's style sheets take too long to match az SVG stíluslapjainak illesztése túl sokáig tart
@msg the SVG's styles expand to more than {0} MB az SVG stílusai kibontva több mint {0} MB-ot foglalnak
@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes az SVG-fájl nagyobb, mint {MAX_IMPORT_BYTES} bájt
@msg the SVG has no drawable objects az SVG-ben nincsenek kirajzolható objektumok
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index e3c066b125..3036992f7e 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -913,6 +913,7 @@
Free Transform Transformasi bebas
Perspective Distort Distorsi perspektif
Radial Blur… Kabur radial…
+ Blur Center Pusat kabur
Smart Blur… Kabur cerdas…
Sharpen Pertajam
Unsharp Mask… Unsharp Mask…
@@ -2516,6 +2517,7 @@ digits Malayalam Malayalam
Transparent Background Latar belakang transparan
Choose… Pilih…
Copy Fonts Used in the Document Salin font yang digunakan dalam dokumen
+ Copy Info Salin info
Copy Links Salin tautan
Create Report Buat laporan
Fonts whose licence doesn't allow embedding are not copied. Font yang lisensinya tidak mengizinkan penyematan tidak disalin.
@@ -4298,6 +4300,7 @@ imageTrace Outline Kontur
Stop the script and undo what it did? Then quit again. Hentikan skrip dan batalkan yang telah dilakukannya? Lalu keluar lagi.
This script has added a great many objects. Continue, or stop it and undo what it did? Skrip ini telah menambahkan sangat banyak objek. Lanjutkan, atau hentikan dan batalkan yang telah dilakukannya?
@msg Copied the script report Berhasil menyalin laporan skrip
+@msg Copied the link info Berhasil menyalin info tautan
@msg Corners edits the corners of a path Corners menyunting sudut jalur
@msg Couldn't copy to the system clipboard: {e} Tidak dapat menyalin ke papan klip sistem: {e}
@msg Couldn't open {name}: {e} Tidak dapat membuka {name}: {e}
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 265460fb36..79d6e8329e 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -18,6 +18,7 @@
Edge Brightness Luminosità bordo
Smoothness Uniformità
Radial Blur… Sfocatura radiale…
+ Blur Center Centro della sfocatura
Smart Blur… Sfocatura intelligente…
Sharpen Nitidezza
Unsharp Mask… Maschera di contrasto…
@@ -645,6 +646,7 @@ font-technology Variable Variabili
Copy All Styles Copia tutti gli stili
Copy Color Value (Hex) Copia valore colore (hex)
Copy Fonts Used in the Document Copia i font usati nel documento
+ Copy Info Copia informazioni
Copy Links Copia collegamenti
Copy Selected Style Copia stile selezionato
Copy to User Defined Copia in Definito dall'utente
@@ -4444,6 +4446,7 @@ axis Both Entrambi
@msg there is no script engine named {name} non esiste un motore di script chiamato {name}
@msg Running a script Esecuzione di uno script
@msg Copied the script report Rapporto dello script copiato
+@msg Copied the link info Informazioni collegamento copiate
@msg Corners edits the corners of a path Angoli modifica gli angoli di un tracciato
@msg Couldn't copy to the system clipboard: {e} Impossibile copiare negli appunti di sistema: {e}
@msg Couldn't open {name}: {e} Impossibile aprire {name}: {e}
@@ -8645,6 +8648,7 @@ breakText Glyphs Glifi
@msg the RTF file is too large to place as type (at most {_1} MB) il file RTF è troppo grande per essere inserito come testo (al massimo {_1} MB)
@msg the SVG expands to more than {0} nested SVG images l'SVG si espande in più di {0} immagini SVG annidate
@msg the SVG expands to more than {0} objects l'SVG si espande in più di {0} oggetti
+@msg the SVG's style sheets take too long to match l'abbinamento dei fogli di stile dell'SVG richiede troppo tempo
@msg the SVG's styles expand to more than {0} MB gli stili dell'SVG si espandono a oltre {0} MB
@msg the SVG has no drawable objects l'SVG non ha oggetti disegnabili
@msg the SVGZ file unpacks to more than {_1} MB il file SVGZ si decomprime in più di {_1} MB
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index f4f35c7bbe..8e5843e690 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -3775,6 +3775,7 @@ gradient-kind Radial 円形
Convert To Outlines アウトラインに変換
Copy All Objects すべてのオブジェクトをコピー
Copy Fonts Used in the Document ドキュメントで使用しているフォントをコピー
+ Copy Info 情報をコピー
Copy Links リンクをコピー
Couldn't copy to the system clipboard: {e} システムのクリップボードにコピーできませんでした:{e}
Couldn't paste from the clipboard: {e} クリップボードからペーストできませんでした:{e}
@@ -4265,6 +4266,7 @@ theme Appearance 外観
# Photoshop-style raster effects (Effect menu, their dialogs).
Radial Blur… ぼかし (放射状)…
+ Blur Center ぼかしの中心
Smart Blur… ぼかし (詳細)…
Sharpen シャープ
Unsharp Mask… アンシャープマスク…
@@ -5209,6 +5211,7 @@ swatch Bright Violet ビビッドバイオレット
@msg there is no script engine named {name} {name} という名前のスクリプトエンジンはありません
@msg Running a script スクリプトを実行中
@msg Copied the script report スクリプトのレポートをコピーしました
+@msg Copied the link info リンク情報をコピーしました
@msg Exported {path} {path} を書き出しました
@msg no CSS to copy: select objects with CSS of their own コピーする CSS がありません: 独自の CSS を持つオブジェクトを選択してください
@msg unknown highlight `{h}` `{h}` は不明なハイライトの指定です
@@ -7853,6 +7856,7 @@ axis Y Axis Y 軸
@msg the RTF file is too large to place as type (at most {_1} MB) RTF ファイルが大きすぎて、文字として配置できません (最大 {_1} MB)
@msg the SVG expands to more than {0} nested SVG images SVG を展開すると、入れ子の SVG 画像が {0} 個を超えます
@msg the SVG expands to more than {0} objects SVG を展開すると、オブジェクトが {0} 個を超えます
+@msg the SVG's style sheets take too long to match SVG のスタイルシートの照合に時間がかかりすぎます
@msg the SVG's styles expand to more than {0} MB SVG のスタイルを展開すると {0} MB を超えます
@msg the SVG has no drawable objects SVG に描画できるオブジェクトがありません
@msg the SVGZ file unpacks to more than {_1} MB SVGZ ファイルを展開すると {_1} MB を超えます
diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv
index 327e1da0e2..c6d078b8a2 100644
--- a/crates/ui-egui/src/i18n/ka.tsv
+++ b/crates/ui-egui/src/i18n/ka.tsv
@@ -879,6 +879,7 @@
Free Transform თავისუფალი გარდაქმნა
Perspective Distort პერსპექტიული დეფორმაცია
Radial Blur… რადიალური გაბუნდოვნება…
+ Blur Center გაბუნდოვნების ცენტრი
Smart Blur… ჭკვიანი გაბუნდოვნება…
Sharpen გამკვეთრება
Unsharp Mask… არამკვეთრი ნიღაბი…
@@ -2438,6 +2439,7 @@ digits Malayalam მალაიალამური
Transparent Background გამჭვირვალე ფონი
Choose… არჩევა…
Copy Fonts Used in the Document დოკუმენტში გამოყენებული შრიფტების კოპირება
+ Copy Info ინფორმაციის კოპირება
Copy Links ბმულების კოპირება
Create Report ანგარიშის შექმნა
Fonts whose licence doesn't allow embedding are not copied. შრიფტები, რომელთა ლიცენზია ჩაშენების უფლებას არ იძლევა, არ კოპირდება.
@@ -5616,6 +5618,7 @@ imageTrace Outline კონტური
@msg there is no script engine named {name} სკრიპტის ძრავა სახელით {name} არ არსებობს
@msg Running a script სკრიპტი მუშაობს
@msg Copied the script report კოპირებულია სკრიპტის ანგარიში
+@msg Copied the link info კოპირებულია ბმულის ინფორმაცია
@msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) ტრაექტორიის წანაცვლება: წანაცვლების შემდეგ მონიშნული ტრაექტორიებიდან არაფერი რჩება (შიგნით წანაცვლება ფიგურებზე დიდია)
@msg {path}: not a file {path}: ფაილი არ არის
Load EPS into Clipboard EPS-ის ბუფერში ჩატვირთვა
@@ -5696,6 +5699,7 @@ imageTrace Outline კონტური
@msg object has no weighted stroke ობიექტს ცვლადი სისქის კონტური არ აქვს
@msg objects can't be nested more than 32 deep ობიექტების ჩადგმის სიღრმე 32-ს ვერ გადააჭარბებს
@msg the SVG's elements are nested more than {0} deep SVG-ის ელემენტების ჩადგმის სიღრმე {0}-ს აჭარბებს
+@msg the SVG's style sheets take too long to match SVG-ის სტილის ფურცლების შედარებას ძალიან დიდი დრო სჭირდება
@msg the SVG's styles expand to more than {0} MB SVG-ის სტილები გაშლისას {0} MB-ს აჭარბებს
@msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode უცნობი control `{name}`: fillStroke, coloring, drawMode ან screenMode
@plural agrees with {n} default shortcut|agrees with {n} default shortcuts ემთხვევა ნაგულისხმევ მალსახმობებს: {n}|ემთხვევა ნაგულისხმევ მალსახმობებს: {n}
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 767b352aff..1ff151c804 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -3763,6 +3763,7 @@ gradient-kind Radial 방사형
Convert To Outlines 윤곽선으로 변환
Copy All Objects 모든 개체 복사
Copy Fonts Used in the Document 문서에 사용된 글꼴 복사
+ Copy Info 정보 복사
Copy Links 링크 복사
Couldn't copy to the system clipboard: {e} 시스템 클립보드로 복사할 수 없습니다: {e}
Couldn't paste from the clipboard: {e} 클립보드에서 붙여넣을 수 없습니다: {e}
@@ -4245,6 +4246,7 @@ theme Appearance 외관
Free Transform 자유 변형
Perspective Distort 원근 왜곡
Radial Blur… 방사형 흐림…
+ Blur Center 흐림 중심
Smart Blur… 스마트 흐림…
Sharpen 선명하게
Unsharp Mask… 언샤프 마스크…
@@ -5136,6 +5138,7 @@ theme Appearance 외관
@msg there is no script engine named {name} 이름이 {name}인 스크립트 엔진이 없습니다
@msg Running a script 스크립트 실행 중
@msg Copied the script report 스크립트 보고서를 복사했습니다
+@msg Copied the link info 링크 정보를 복사했습니다
@msg Exported {path} {path}을(를) 내보냈습니다
@msg no CSS to copy: select objects with CSS of their own 복사할 CSS가 없습니다: 자체 CSS가 있는 개체를 선택하세요
@msg unknown highlight `{h}` 알 수 없는 강조 `{h}`
@@ -8629,6 +8632,7 @@ breakText Glyphs 글리프
@msg the RTF file is too large to place as type (at most {_1} MB) RTF 파일이 너무 커서 문자로 가져올 수 없습니다(최대 {_1} MB)
@msg the SVG expands to more than {0} nested SVG images SVG를 확장하면 중첩된 SVG 이미지가 {0}개보다 많아집니다
@msg the SVG expands to more than {0} objects SVG를 확장하면 개체가 {0}개보다 많아집니다
+@msg the SVG's style sheets take too long to match SVG의 스타일 시트를 대조하는 데 시간이 너무 오래 걸립니다
@msg the SVG's styles expand to more than {0} MB SVG의 스타일을 확장하면 {0}MB를 넘습니다
@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes SVG 파일이 {MAX_IMPORT_BYTES}바이트보다 큽니다
@msg the SVG has no drawable objects SVG에 그릴 수 있는 개체가 없습니다
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 581714423f..d2eaeb39a6 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -1431,6 +1431,7 @@
Free Transform Vrij transformeren
Perspective Distort Perspectief vervormen
Radial Blur… Radiaal vervagen…
+ Blur Center Middelpunt van vervaging
Smart Blur… Slim vervagen…
Sharpen Verscherpen
Unsharp Mask… Onscherp maskeren…
@@ -3034,6 +3035,7 @@ digits Malayalam Malayalam
Transparent Background Transparante achtergrond
Choose… Kies…
Copy Fonts Used in the Document In het document gebruikte lettertypen kopiëren
+ Copy Info Info kopiëren
Copy Links Koppelingen kopiëren
Create Report Rapport maken
Fonts whose licence doesn't allow embedding are not copied. Lettertypen waarvan de licentie insluiten niet toestaat, worden niet gekopieerd.
@@ -4816,6 +4818,7 @@ imageTrace Outline Contour
Stop the script and undo what it did? Then quit again. Het script stoppen en de wijzigingen ervan ongedaan maken? Sluit daarna opnieuw af.
This script has added a great many objects. Continue, or stop it and undo what it did? Dit script heeft heel veel objecten toegevoegd. Doorgaan, of het stoppen en de wijzigingen ervan ongedaan maken?
@msg Copied the script report Scriptrapport gekopieerd
+@msg Copied the link info Koppelingsinfo gekopieerd
@msg Corners edits the corners of a path Hoeken bewerkt de hoeken van een pad
@msg Couldn't copy to the system clipboard: {e} Kon niet naar het systeemklembord kopiëren: {e}
@msg Couldn't open {name}: {e} Kon {name} niet openen: {e}
@@ -6975,6 +6978,7 @@ imageTrace Outline Contour
@msg the RTF file is too large to place as type (at most {_1} MB) het RTF-bestand is te groot om als tekst te plaatsen (maximaal {_1} MB)
@msg the SVG expands to more than {0} nested SVG images de SVG wordt uitgevouwen tot meer dan {0} geneste SVG-afbeeldingen
@msg the SVG expands to more than {0} objects de SVG wordt uitgevouwen tot meer dan {0} objecten
+@msg the SVG's style sheets take too long to match het vergelijken van de stijlbladen van de SVG duurt te lang
@msg the SVG's styles expand to more than {0} MB de stijlen van de SVG worden uitgevouwen tot meer dan {0} MB
@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes het SVG-bestand is groter dan {MAX_IMPORT_BYTES} bytes
@msg the SVG has no drawable objects de SVG heeft geen tekenbare objecten
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 832539f18b..e53d6d1074 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -931,6 +931,7 @@
Free Transform Swobodne przekształcanie
Perspective Distort Zniekształcenie perspektywiczne
Radial Blur… Rozmycie promieniste…
+ Blur Center Środek rozmycia
Smart Blur… Inteligentne rozmycie…
Sharpen Wyostrzanie
Unsharp Mask… Maska wyostrzająca…
@@ -2647,6 +2648,7 @@ digits Malayalam Malajalam
Transparent Background Przezroczyste tło
Choose… Wybierz…
Copy Fonts Used in the Document Kopiuj czcionki użyte w dokumencie
+ Copy Info Kopiuj informacje
Copy Links Kopiuj łącza
Create Report Utwórz raport
Fonts whose licence doesn't allow embedding are not copied. Czcionki, których licencja nie zezwala na osadzanie, nie są kopiowane.
@@ -4527,6 +4529,7 @@ imageTrace Outline Kontur
@msg there is no script engine named {name} nie ma silnika skryptów o nazwie {name}
@msg Running a script Uruchamianie skryptu
@msg Copied the script report Skopiowano raport skryptu
+@msg Copied the link info Skopiowano informacje o łączu
@msg Corners edits the corners of a path Narożniki edytuje narożniki ścieżki
@msg Couldn't copy to the system clipboard: {e} Nie udało się skopiować do schowka systemowego: {e}
@msg Couldn't open {name}: {e} Nie udało się otworzyć {name}: {e}
@@ -8883,6 +8886,7 @@ breakText Glyphs Glify
@msg the RTF file is too large to place as type (at most {_1} MB) plik RTF jest zbyt duży, aby umieścić go jako tekst (najwyżej {_1} MB)
@msg the SVG expands to more than {0} nested SVG images SVG rozwija się do ponad {0} zagnieżdżonych obrazów SVG
@msg the SVG expands to more than {0} objects SVG rozwija się do ponad {0} obiektów
+@msg the SVG's style sheets take too long to match dopasowanie arkuszy stylów SVG trwa zbyt długo
@msg the SVG's styles expand to more than {0} MB style SVG rozwijają się do ponad {0} MB
@msg the SVG has no drawable objects SVG nie zawiera obiektów, które można narysować
@msg the SVGZ file unpacks to more than {_1} MB plik SVGZ po rozpakowaniu ma ponad {_1} MB
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index fd8b3ac11c..83b5f42f21 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -3486,6 +3486,7 @@ imageTrace Outline Contorno
Free Transform Transformação Livre
Perspective Distort Distorção de Perspectiva
Radial Blur… Desfoque Radial…
+ Blur Center Centro do Desfoque
Smart Blur… Desfoque Inteligente…
Sharpen Nitidez
Unsharp Mask… Máscara de Nitidez…
@@ -4906,6 +4907,7 @@ axis Both Ambos
Convert To Outlines Converter em Contornos
Copy All Objects Copiar Todos os Objetos
Copy Fonts Used in the Document Copiar Fontes Usadas no Documento
+ Copy Info Copiar Informações
Copy Links Copiar Links
Descender Descendente
Flip Virar
@@ -5425,6 +5427,7 @@ axis Both Ambos
@msg there is no script engine named {name} não há nenhum mecanismo de script chamado {name}
@msg Running a script Executando um script
@msg Copied the script report Relatório do script copiado
+@msg Copied the link info Informações do link copiadas
@msg This shortcut file is in a form VectorCraft can't read. Este arquivo de atalhos está em um formato que o VectorCraft não consegue ler.
@msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis deve ser "vertical", "horizontal" ou um ângulo em graus, não `{v}`
@msg give corners of the path: anchors where its sides meet at an angle informe os cantos do caminho: pontos de ancoragem onde os lados se encontram em ângulo
@@ -9095,6 +9098,7 @@ swatch Yellow Green Verde-amarelado
@msg the RTF file is too large to place as type (at most {_1} MB) o arquivo RTF é grande demais para ser colocado como texto (no máximo {_1} MB)
@msg the SVG expands to more than {0} nested SVG images o SVG se expande em mais de {0} imagens SVG aninhadas
@msg the SVG expands to more than {0} objects o SVG se expande em mais de {0} objetos
+@msg the SVG's style sheets take too long to match a correspondência das folhas de estilo do SVG demora demais
@msg the SVG's styles expand to more than {0} MB os estilos do SVG se expandem para mais de {0} MB
@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes o arquivo SVG tem mais de {MAX_IMPORT_BYTES} bytes
@msg the SVG has no drawable objects o SVG não tem objetos desenháveis
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 43320b5b86..6859f72430 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -16,6 +16,7 @@
Edge Brightness Яркость края
Smoothness Сглаживание
Radial Blur… Радиальное размытие…
+ Blur Center Центр размытия
Smart Blur… Умное размытие…
Sharpen Резкость
Unsharp Mask… Нерезкая маска…
@@ -643,6 +644,7 @@ font-technology Variable Вариативные
Copy All Styles Копировать все стили
Copy Color Value (Hex) Копировать значение цвета (hex)
Copy Fonts Used in the Document Копировать шрифты, использованные в документе
+ Copy Info Копировать сведения
Copy Links Копировать связи
Copy Selected Style Копировать выбранный стиль
Copy to User Defined Копировать в «Пользовательский»
@@ -4429,6 +4431,7 @@ axis Both Оба
@msg there is no script engine named {name} движка скриптов с именем {name} нет
@msg Running a script Выполняется скрипт
@msg Copied the script report Отчёт о сценарии скопирован
+@msg Copied the link info Сведения о связи скопированы
@msg Corners edits the corners of a path «Углы» редактирует углы контура
@msg Couldn't copy to the system clipboard: {e} Не удалось скопировать в системный буфер обмена: {e}
@msg Couldn't open {name}: {e} Не удалось открыть {name}: {e}
@@ -4901,6 +4904,7 @@ axis Both Оба
@msg result would exceed the canvas (coordinates out of range) результат превысил бы холст (координаты вне диапазона)
@msg objects can't be nested more than 32 deep объекты нельзя вкладывать глубже 32 уровней
@msg the SVG's elements are nested more than {0} deep элементы SVG вложены глубже {0} уровней
+@msg the SVG's style sheets take too long to match сопоставление таблиц стилей SVG занимает слишком много времени
@msg the SVG's styles expand to more than {0} MB после развёртывания стили SVG занимают более {0} МБ
@msg scale must be a number from {_1} to {_2}, not {_3} scale должен быть числом от {_1} до {_2}, а не {_3}
@msg scale must be a number from {_1} to {_2}, not {s} scale должен быть числом от {_1} до {_2}, а не {s}
diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv
index 8b024a8212..5c4208171e 100644
--- a/crates/ui-egui/src/i18n/sv.tsv
+++ b/crates/ui-egui/src/i18n/sv.tsv
@@ -15,6 +15,7 @@
Edge Brightness Kantljusstyrka
Smoothness Mjukhet
Radial Blur… Radiell oskärpa…
+ Blur Center Oskärpans mittpunkt
Smart Blur… Smart oskärpa…
Sharpen Skärpa
Unsharp Mask… Oskarp mask…
@@ -632,6 +633,7 @@ font-technology Variable Variabla
Copy All Styles Kopiera alla stilar
Copy Color Value (Hex) Kopiera färgvärde (hex)
Copy Fonts Used in the Document Kopiera typsnitt som används i dokumentet
+ Copy Info Kopiera info
Copy Links Kopiera länkar
Copy Selected Style Kopiera markerad stil
Copy to User Defined Kopiera till användardefinierade
@@ -4302,6 +4304,7 @@ axis Both Båda
@msg there is no script engine named {name} det finns ingen skriptmotor med namnet {name}
@msg Running a script Kör ett skript
@msg Copied the script report Kopierade skriptrapporten
+@msg Copied the link info Kopierade länkinfo
@msg Corners edits the corners of a path Hörn redigerar hörnen på en bana
@msg Couldn't copy to the system clipboard: {e} Kunde inte kopiera till systemets urklipp: {e}
@msg Couldn't open {name}: {e} Kunde inte öppna {name}: {e}
@@ -8668,6 +8671,7 @@ digits Hindi Hindi
@msg the subpath has no ends to extend (it is closed or a single point) delbanan har inga ändar att förlänga (den är stängd eller en enkel punkt)
@msg the SVG expands to more than {0} nested SVG images SVG-filen expanderar till fler än {0} kapslade SVG-bilder
@msg the SVG expands to more than {0} objects SVG-filen expanderar till fler än {0} objekt
+@msg the SVG's style sheets take too long to match matchningen av SVG-filens formatmallar tar för lång tid
@msg the SVG's styles expand to more than {0} MB SVG-filens stilar expanderar till mer än {0} MB
@msg the SVG has no drawable objects SVG-filen har inga ritbara objekt
@msg the SVGZ file unpacks to more than {_1} MB SVGZ-filen packas upp till mer än {_1} MB
diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs
index 7fc16807ec..c985f77d6c 100644
--- a/crates/ui-egui/src/i18n/tests.rs
+++ b/crates/ui-egui/src/i18n/tests.rs
@@ -49,6 +49,9 @@ fn hindi_resolves_locales_and_uses_zero_one_plurals() {
/// Every Hindi row uses the terms `docs/localization-hi.md` sets for what its English names:
/// सेव for saving, स्वॉच for a swatch, क्रॉप for cropping, रिज़ॉल्यूशन for a resolution and पाथ for
/// a path, never पाठ (a reading), and a number of points is a number (संख्या) in points (पॉइंट).
+/// Rows also never use a word's unrelated sense: a ruler is not शासक (a sovereign), a text character
+/// is not चरित्र (a personality), a vector point or a printer's mark is not अंक (a digit), fills are
+/// not भरता (the verb), Desired is not देसी (local), Even is not शाम (evening), and so on.
#[test]
fn hindi_rows_use_the_glossary_term_for_what_their_english_names() {
let hi = Lang::from_code("hi").expect("hi registered");
@@ -57,15 +60,35 @@ fn hindi_rows_use_the_glossary_term_for_what_their_english_names() {
for (_, src, translation) in &entries {
let english = src.to_lowercase();
let names = |words: &[&str]| english.split(|c: char| !c.is_ascii_alphabetic()).any(|w| words.contains(&w));
- let banned: [(bool, &[&str]); 6] = [
- (names(&["save", "saves", "saved", "saving"]), &["बचा", "सहेज"]),
+ let banned: &[(bool, &[&str])] = &[
+ (names(&["save", "saves", "saved", "saving"]), &["बचा", "बचत", "सहेज"]),
(names(&["swatch", "swatches"]), &["घड़ी"]),
(names(&["crop"]), &["फसल"]),
(names(&["resolution", "resolutions"]), &["संकल्प"]),
(names(&["path", "paths"]), &["पथ"]),
(true, &["पाठ", "कई अंक"]),
+ (names(&["ruler", "rulers"]), &["शासक"]),
+ (names(&["character", "characters"]), &["चरित्र"]),
+ (names(&["point", "points", "mark", "marks"]), &["अंक"]),
+ (names(&["fill", "fills"]), &["भरता"]),
+ (names(&["desired"]), &["देसी", "इच्छा"]),
+ (names(&["even"]), &["शाम"]),
+ (names(&["force", "forced"]), &["सेना"]),
+ (names(&["same"]), &["समीर"]),
+ (names(&["thumbnail", "thumbnails"]), &["हिंदुस्तान"]),
+ (names(&["contrast"]), &["न्यायालय"]),
+ (names(&["function"]), &["समारोह"]),
+ (names(&["kern"]), &["बर्न"]),
+ (names(&["imageable"]), &["कल्पनाशील"]),
+ (names(&["constrain"]), &["कंस्ट्रक्शन"]),
+ (names(&["complement"]), &["संगम"]),
+ (names(&["concave"]), &["अवतरण"]),
+ (names(&["triad"]), &["त्रिद"]),
+ (names(&["trapped", "traps"]), &["निशानेबाज़", "जाल"]),
+ (names(&["alternate", "alternates"]), &["अल्टरनेटर"]),
+ (names(&["highlight"]), &["उच्च प्रकाश"]),
];
- for (applies, words) in banned {
+ for &(applies, words) in banned {
if let Some(word) = words.iter().find(|w| applies && translation.contains(**w)) {
wrong.push(format!("{word} in {src:?} -> {translation:?}"));
}
@@ -135,6 +158,10 @@ fn hindi_rows_keep_the_meaning_of_their_english() {
"पेज थंबनेल RGB पिक्सल का होना चाहिए, हर तरफ़ 1 से 256 (मिला 0 × 4)"
);
assert_eq!(message(hi, "invalid angle"), "अमान्य कोण");
+ assert_eq!(tr(hi, "Desired"), "वांछित");
+ let range = "न्यूनतम, वांछित से अधिक नहीं होना चाहिए और वांछित, अधिकतम से अधिक नहीं होना चाहिए";
+ assert_eq!(tr(hi, "Minimum must not exceed Desired, nor Desired Maximum."), format!("{range}।"));
+ assert_eq!(message(hi, "`wordSpacing`: Minimum must not exceed Desired, nor Desired Maximum"), format!("`wordSpacing`: {range}"));
}
/// Hindi messages keep every `a|b|c` list of accepted values exactly as their English writes it.
diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv
index 4fb138652c..16b6e5bd73 100644
--- a/crates/ui-egui/src/i18n/tr.tsv
+++ b/crates/ui-egui/src/i18n/tr.tsv
@@ -15,6 +15,7 @@
Edge Brightness Kenar Parlaklığı
Smoothness Pürüzsüzlük
Radial Blur… Radyal Bulanıklık…
+ Blur Center Bulanıklık Merkezi
Smart Blur… Akıllı Bulanıklaştırma…
Sharpen Keskinleştir
Unsharp Mask… Keskinliği Azaltma Maskesi…
@@ -624,6 +625,7 @@ font-technology Variable Değişken
Copy All Styles Tüm Stilleri Kopyala
Copy Color Value (Hex) Renk Değerini Kopyala (Hex)
Copy Fonts Used in the Document Belgede Kullanılan Yazı Tiplerini Kopyala
+ Copy Info Bilgiyi Kopyala
Copy Links Bağlantıları Kopyala
Copy Selected Style Seçilen Stili Kopyala
Copy to User Defined Kullanıcı Tanımlıya Kopyala
@@ -4165,6 +4167,7 @@ axis Both Her İkisi
@msg there is no script engine named {name} {name} adlı bir betik motoru yok
@msg Running a script Betik çalıştırılıyor
@msg Copied the script report Komut dosyası raporu kopyalandı
+@msg Copied the link info Bağlantı bilgisi kopyalandı
@msg Corners edits the corners of a path Köşeler bir yolun köşelerini düzenler
@msg Couldn't copy to the system clipboard: {e} Sistem panosuna kopyalanamadı: {e}
@msg Couldn't open {name}: {e} {name} açılamadı: {e}
@@ -4634,6 +4637,7 @@ axis Both Her İkisi
@msg result would exceed the canvas (coordinates out of range) sonuç tuvali aşacaktır (koordinatlar aralık dışındadır)
@msg objects can't be nested more than 32 deep nesneler 32'den fazla derinliğe yerleştirilemez
@msg the SVG's elements are nested more than {0} deep SVG'nin öğeleri {0} derinliğinden daha fazla yuvalanmıştır
+@msg the SVG's style sheets take too long to match SVG'nin stil sayfalarının eşleştirilmesi çok uzun sürüyor
@msg the SVG's styles expand to more than {0} MB SVG'nin stilleri genişletildiğinde {0} MB'tan fazla yer kaplıyor
@msg scale must be a number from {_1} to {_2}, not {_3} scale {_1} ile {_2} arasında bir sayı olmalıdır, {_3} değil
@msg scale must be a number from {_1} to {_2}, not {s} scale {_1} ile {_2} arasında bir sayı olmalıdır, {s} değil
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index e3ed8eb72b..3da82c3f1b 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -17,6 +17,7 @@
Smoothness Згладжування
Radial Blur… Радіальне розмиття…
+ Blur Center Центр розмиття
Smart Blur… Розумне розмиття…
Sharpen Різкість
Unsharp Mask… Нерізка маска…
@@ -639,6 +640,7 @@ font-technology Variable Варіативні
Copy All Styles Копіювати всі стилі
Copy Color Value (Hex) Копіювати значення кольору (hex)
Copy Fonts Used in the Document Копіювати шрифти, використані у документі
+ Copy Info Копіювати відомості
Copy Links Копіювати зв’язки
Copy Selected Style Копіювати вибраний стиль
Copy to User Defined Копіювати в «Користувацькі»
@@ -4428,6 +4430,7 @@ axis Both Обидві
@msg there is no script engine named {name} рушія скриптів з назвою {name} немає
@msg Running a script Виконується скрипт
@msg Copied the script report Звіт про сценарій скопійовано
+@msg Copied the link info Відомості про зв’язок скопійовано
@msg Corners edits the corners of a path «Кути» редагує кути контуру
@msg Couldn't copy to the system clipboard: {e} Не вдалося скопіювати до системного буфера обміну: {e}
@msg Couldn't open {name}: {e} Не вдалося відкрити {name}: {e}
@@ -8627,6 +8630,7 @@ breakText Glyphs Гліфи
@msg the RTF file is too large to place as type (at most {_1} MB) файл RTF завеликий, щоб помістити його як текст (не більше {_1} МБ)
@msg the SVG expands to more than {0} nested SVG images SVG розгортається у понад {0} вкладених зображень SVG
@msg the SVG expands to more than {0} objects SVG розгортається у понад {0} об’єктів
+@msg the SVG's style sheets take too long to match зіставлення таблиць стилів SVG триває надто довго
@msg the SVG's styles expand to more than {0} MB стилі SVG розгортаються у понад {0} МБ
@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes файл SVG більший за {MAX_IMPORT_BYTES} байтів
@msg the SVG has no drawable objects SVG не містить об’єктів, які можна намалювати
diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv
index 7ff754f74a..231ac5e1c7 100644
--- a/crates/ui-egui/src/i18n/vi.tsv
+++ b/crates/ui-egui/src/i18n/vi.tsv
@@ -739,6 +739,7 @@ font-technology Variable Biến thiên
Copy Color Value (Hex) Sao chép giá trị màu (Hex)
Copy Fonts Used in the Document Sao chép phông đã dùng trong tài liệu
Copy into the document's folder Sao chép vào thư mục tài liệu
+ Copy Info Sao chép thông tin
Copy Links Sao chép liên kết
Copy only fonts you own or are licensed to install. Chỉ sao chép phông chữ bạn sở hữu hoặc có giấy phép cài đặt.
Copy Selected Style Sao chép kiểu đã chọn
@@ -3047,6 +3048,7 @@ mark-style Japanese Kiểu Nhật
Radial Hướng tâm
Radial Blur Mờ hướng tâm
Radial Blur… Mờ hướng tâm…
+ Blur Center Tâm làm mờ
Radial Dividers: Đường chia hướng tâm:
Radial Glows Ánh sáng hướng tâm
Organic Fades Mờ dần tự nhiên
@@ -4858,6 +4860,7 @@ theme Appearance Giao diện
@msg there is no script engine named {name} không có bộ máy tập lệnh nào tên {name}
@msg Running a script Đang chạy tập lệnh
@msg Copied the script report Đã sao chép báo cáo script
+@msg Copied the link info Đã sao chép thông tin liên kết
@msg Corners edits the corners of a path Corners chỉnh sửa các góc của đường dẫn
@msg could not decode image: {0} không thể giải mã ảnh: {0}
@msg Couldn't copy to the system clipboard: {e} Không thể sao chép vào khay nhớ tạm hệ thống: {e}
@@ -5275,6 +5278,7 @@ theme Appearance Giao diện
@msg result would exceed the canvas (coordinates out of range) kết quả sẽ vượt quá vùng vẽ (tọa độ ngoài phạm vi)
@msg objects can't be nested more than 32 deep không thể lồng các đối tượng sâu quá 32 cấp
@msg the SVG's elements are nested more than {0} deep các phần tử SVG lồng nhau sâu quá {0} cấp
+@msg the SVG's style sheets take too long to match việc so khớp các biểu định kiểu của SVG mất quá nhiều thời gian
@msg the SVG's styles expand to more than {0} MB các kiểu của SVG khi mở rộng chiếm hơn {0} MB
@msg Save for Web: the image is empty Lưu cho Web: ảnh trống
@msg Save writes {_1}, not {_2}: use document.export for other formats Lưu ghi {_1}, không phải {_2}: dùng document.export cho các định dạng khác
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index c4a64884a1..3904ef4b01 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -591,6 +591,7 @@ antiAlias Sharp 锐利
Copy All Styles 复制所有样式
Copy Color Value (Hex) 复制颜色值 (十六进制)
Copy Fonts Used in the Document 复制文档中使用的字体
+ Copy Info 复制信息
Copy Links 复制链接
Copy Selected Style 复制所选样式
Copy to User Defined 复制到用户定义
@@ -4889,6 +4890,7 @@ imageTrace Outline 轮廓
@msg there is no script engine named {name} 没有名为 {name} 的脚本引擎
@msg Running a script 正在运行脚本
@msg Copied the script report 已复制脚本报告
+@msg Copied the link info 已复制链接信息
@msg Exported {path} 已导出 {path}
@msg no CSS to copy: select objects with CSS of their own 没有可复制的 CSS:请选择带有自身 CSS 的对象
@msg unknown highlight `{h}` 未知的高亮显示 `{h}`
@@ -5575,6 +5577,7 @@ axis Both 两者
# Photoshop-style raster effects (Effect menu, their dialogs).
Radial Blur… 径向模糊…
+ Blur Center 模糊中心
Smart Blur… 智能模糊…
Sharpen 锐化
Unsharp Mask… 反锐化遮罩…
@@ -8869,6 +8872,7 @@ breakText Glyphs 字形
@msg the RTF file is too large to place as type (at most {_1} MB) RTF 文件过大,无法作为文字置入 (最多 {_1} MB)
@msg the SVG expands to more than {0} nested SVG images SVG 展开后的嵌套 SVG 图像超过 {0} 个
@msg the SVG expands to more than {0} objects SVG 展开后的对象超过 {0} 个
+@msg the SVG's style sheets take too long to match 匹配 SVG 的样式表耗时过长
@msg the SVG's styles expand to more than {0} MB SVG 的样式展开后超过 {0} MB
@msg the SVG has no drawable objects SVG 中没有可绘制的对象
@msg the SVGZ file unpacks to more than {_1} MB SVGZ 文件解压后超过 {_1} MB
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 991e6597d1..01c9718f43 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -608,6 +608,7 @@ font-technology Variable 可變
Copy All Styles 複製所有樣式
Copy Color Value (Hex) 複製顏色值 (Hex)
Copy Fonts Used in the Document 複製文件中使用的字體
+ Copy Info 複製資訊
Copy Links 複製連結
Copy Selected Style 複製所選樣式
Copy to User Defined 複製到使用者定義
@@ -2590,6 +2591,7 @@ file-filter Templates 範本
@msg there is no script engine named {name} 沒有名為 {name} 的指令碼引擎
@msg Running a script 正在執行指令碼
@msg Copied the script report 已複製指令碼報告
+@msg Copied the link info 已複製連結資訊
@msg Exported {path} 已匯出 {path}
@msg no CSS to copy: select objects with CSS of their own 沒有可複製的 CSS:請選取有自己 CSS 的物件
@msg unknown highlight `{h}` 未知的反白顯示 `{h}`
@@ -5410,6 +5412,7 @@ axis Both 兩者
# Photoshop-style raster effects (Effect menu, their dialogs).
Radial Blur… 放射狀模糊…
+ Blur Center 模糊中心
Smart Blur… 智慧型模糊…
Sharpen 銳利化
Unsharp Mask… 反銳利化遮罩…
@@ -8797,6 +8800,7 @@ breakText Glyphs 字符
@msg the RTF file is too large to place as type (at most {_1} MB) RTF 檔案過大,無法置入為文字 (最多 {_1} MB)
@msg the SVG expands to more than {0} nested SVG images SVG 展開後超過 {0} 個巢狀 SVG 影像
@msg the SVG expands to more than {0} objects SVG 展開後超過 {0} 個物件
+@msg the SVG's style sheets take too long to match 比對 SVG 的樣式表耗時過長
@msg the SVG's styles expand to more than {0} MB SVG 的樣式展開後超過 {0} MB
@msg the SVG has no drawable objects SVG 中沒有可繪製的物件
@msg the SVGZ file unpacks to more than {_1} MB SVGZ 檔案解壓縮後超過 {_1} MB
diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs
index ee083d7d44..ea27320b52 100644
--- a/crates/ui-egui/src/io.rs
+++ b/crates/ui-egui/src/io.rs
@@ -446,6 +446,31 @@ mod tests {
assert_eq!(&w[1].1[1..4], b"PNG", "PNG from the given path");
}
+ /// An option skips the options dialog, but without `path` the save panel still picks the file.
+ #[test]
+ fn export_selection_with_an_option_and_no_path_asks_for_the_file_only() {
+ let (mut app, written) = app();
+ app.session.execute("file.new", &json!({"width": 60, "height": 40})).unwrap();
+ app.session.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap();
+ let asked = Rc::new(RefCell::new(0));
+ let count = asked.clone();
+ app.services.pick_save = Some(Box::new(move |_: &FilePick| {
+ *count.borrow_mut() += 1;
+ Some("/tmp/sel.png".into())
+ }));
+ let r = app.run("document.exportSelection", json!({"scale": 2})).unwrap();
+ assert_eq!(*asked.borrow(), 1, "the save panel picks the file");
+ assert!(app.ui.dialog.is_none(), "no options dialog follows");
+ assert_eq!(r["path"], "/tmp/sel.png");
+ assert_eq!(&written.borrow()[0].1[1..4], b"PNG");
+ app.run("document.exportSelection", json!({"path": "/tmp/sel2.png", "scale": 2})).unwrap();
+ assert_eq!(*asked.borrow(), 1, "a path writes without the save panel");
+ let w = written.borrow();
+ assert_eq!(w.len(), 2);
+ assert_eq!(w[0].0, "/tmp/sel.png", "the picked file");
+ assert_eq!(w[1].0, "/tmp/sel2.png", "the given path");
+ }
+
#[test]
fn written_files_open_as_file_urls() {
let url = super::file_url("/tmp/My Art #1.pdf");
diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs
index 6e38e8cc63..10fae638c4 100644
--- a/crates/ui-egui/src/io/save.rs
+++ b/crates/ui-egui/src/io/save.rs
@@ -263,7 +263,9 @@ pub(super) fn save_current_in(app: &mut VectorcraftApp, p: &Value, folder: Optio
return Ok(r);
}
let retry = super::read_only_save::Retry::new(&first, folder);
- write_plan(app, first, ("file.save", p.clone()), Some(retry))
+ // Only `path` was asked about: the files written beside it are checked against the file the
+ // document was read from when the save writes them.
+ write_plan(app, plan(app, SaveMode::Save, p)?, ("file.save", p.clone()), Some(retry))
}
/// File → Save, Save As…, Save a Copy…, Save as Template… and the options dialogs' OK. `p` is the
diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs
index 7b7f7a6b21..ff578d81e5 100644
--- a/crates/ui-egui/src/menus/run.rs
+++ b/crates/ui-egui/src/menus/run.rs
@@ -976,6 +976,7 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::links::open_file(app, p, false),
"links.reveal" => crate::panels::links::open_file(app, p, true),
+ "links.copyInfo" => crate::panels::links::copy_info(app, p),
"ui.placementOptionsDialog" => crate::dialogs::placement_options::open(app, p),
"ui.relinkDialog" => crate::dialogs::relink::open(app, p),
"ui.findLinksInFolder" => {
diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs
index 0d5775ffe9..98c13ec06e 100644
--- a/crates/ui-egui/src/menus/state.rs
+++ b/crates/ui-egui/src/menus/state.rs
@@ -310,6 +310,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool {
"ui.dxfOptionsDialog" => app.session.active().is_some(),
"links.editOriginal" | "links.reveal" => selected_image(app, |im| im.link.is_some()) || selected_placed(app),
"ui.placementOptionsDialog" => selected_image(app, |_| true) || selected_placed(app),
+ "links.copyInfo" => !crate::panels::links::selected_rows_of_app(app).is_empty(),
"ui.relinkDialog" => app.services.pick_open.is_some() && (selected_image(app, |_| true) || selected_placed(app)),
"ui.findLinksInFolder" => crate::picks::can(app, &crate::picks::PickRequest::Folder) && app.session.active().is_some(),
"ui.packageDialog" | "docInfo.save" => app.session.active().is_some(),
diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs
index 913dc03abb..4c14966462 100644
--- a/crates/ui-egui/src/menus/ui_commands.rs
+++ b/crates/ui-egui/src/menus/ui_commands.rs
@@ -1456,6 +1456,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{id?} show the file of linked image `id` (default: the selected linked image) in the system's file manager → {path}",
),
+ (
+ "links.copyInfo",
+ "Copy Info",
+ "",
+ "{ids?} copy the file names of images and placed documents `ids` (default: the selected ones and the rows picked in the Links panel, in links.list order) to the clipboard, one per line in that order; an embedded image gives the name its Links panel row shows (Links panel menu) → {text, names}",
+ ),
(
"ui.placementOptionsDialog",
"Placement Options…",
diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs
index 4593ab70c7..611c9e472a 100644
--- a/crates/ui-egui/src/panels/links.rs
+++ b/crates/ui-egui/src/panels/links.rs
@@ -5,8 +5,8 @@
//! Go To, Update and Edit Original act on the selected rows (Relink through its dialog, with the
//! Replace choice: `ui.relinkDialog`); Link Info shows the details of the first. The flyout adds Relink to Folder, Find in Folder (Find Linked Files:
//! `ui.findLinksInFolder`), Embed / Unembed, Placement Options, Select Linked / Embedded / Missing /
-//! Modified (`addon.select.byLinkStatus`, Shift adds), Show filters, Sort, thumbnail size,
-//! Show in Folder and Show DCS Transparency Interactions (a warning on the rows of images placed
+//! Modified (`addon.select.byLinkStatus`, Shift adds), Show filters, Sort, Copy Info (the selected
+//! rows' file names to the clipboard: `links.copyInfo`), thumbnail size, Show in Folder and Show DCS Transparency Interactions (a warning on the rows of images placed
//! from DCS files that are transparent or overlap transparent objects).
//!
//! Images and placed documents in opacity-mask art and in the art of symbols, graph designs and
@@ -218,6 +218,15 @@ fn selected_links(app: &VectorcraftApp, ctx: &egui::Context) -> Vec {
ids
}
+/// [`selected_links`] with the app's window context, for a command run outside the panel (the
+/// selected images and placed documents alone when there is no window).
+pub(crate) fn selected_rows_of_app(app: &VectorcraftApp) -> Vec {
+ match app.ui_ctx.clone() {
+ Some(ctx) => selected_links(app, &ctx),
+ None => selected_images(app),
+ }
+}
+
/// The rows of `list` whose image is selected.
fn selected_rows<'a>(list: &'a Value, selected: &[u64]) -> Vec<&'a Value> {
list["links"].as_array().into_iter().flatten().filter(|r| r["id"].as_u64().is_some_and(|id| selected.contains(&id))).collect()
@@ -357,6 +366,48 @@ pub(crate) fn open_file(app: &mut VectorcraftApp, p: &Value, reveal: bool) -> Re
Ok(json!({ "path": path }))
}
+/// The UI command `links.copyInfo {ids?}` (the panel menu's Copy Info): copy the file names of
+/// images and placed documents `ids` (default: the selected rows, [`selected_rows_of_app`], in the
+/// order `links.list` gives them; `null` counts as left out) to the clipboard, one per line in that
+/// order → `{text, names}`. An embedded image gives the name its row shows.
+pub(crate) fn copy_info(app: &mut VectorcraftApp, p: &Value) -> Result {
+ let key = "ids";
+ let given = match p.get(key) {
+ None | Some(Value::Null) => None,
+ Some(Value::Array(a)) => {
+ let mut out = Vec::with_capacity(a.len());
+ for (index, value) in a.iter().enumerate() {
+ out.push(value.as_u64().ok_or_else(|| format!("`{key}` entry {index} is {value}, not a non-negative integer object id"))?);
+ }
+ Some(out)
+ }
+ Some(_) => return Err(format!("{key} must be an array of non-negative integer object ids")),
+ };
+ let list = app.session.execute("links.list", &json!({})).map_err(|e| e.to_string())?;
+ let rows: Vec<&Value> = list["links"].as_array().into_iter().flatten().collect();
+ let wanted = match given {
+ Some(wanted) => wanted,
+ None => {
+ let sel = selected_rows_of_app(app);
+ ids(&rows, |r| r["id"].as_u64().is_some_and(|id| sel.contains(&id)))
+ }
+ };
+ let by_id: std::collections::HashMap =
+ rows.iter().filter_map(|r| Some((r["id"].as_u64()?, r["name"].as_str().unwrap_or_default()))).collect();
+ let mut names = Vec::with_capacity(wanted.len());
+ for id in &wanted {
+ let name = by_id.get(id).ok_or_else(|| format!("object {} is not an image or a linked file", *id))?;
+ names.push((*name).to_string());
+ }
+ if names.is_empty() {
+ return Err("select the images, or pass ids".into());
+ }
+ let text = names.join("\n");
+ app.clipboard_out = Some(text.clone());
+ app.status("Copied the link info");
+ Ok(json!({ "text": text, "names": names }))
+}
+
/// Whether Edit Original may hand `path` to the system's default app: a regular file (after
/// following links) whose name, and the name it links to, have the extension of a format
/// VectorCraft reads. Anything else (a folder or app bundle, a script, a shortcut) is refused.
@@ -732,7 +783,8 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) {
}
/// The panel's flyout menu: the link commands for the selected rows, Select Linked / Embedded /
-/// Missing / Modified for the whole document, and the Show, Sort and thumbnail options.
+/// Missing / Modified for the whole document, the Show and Sort options, Copy Info and the
+/// thumbnail options.
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
let o = options(ui.ctx());
// The rows the panel shows (the menu opens from it).
@@ -819,6 +871,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
ui.separator();
+ if menu_item(ui, tl!("Copy Info"), any, false) {
+ crate::menus::invoke(app, "links.copyInfo", json!({ "ids": ids(&sel, |_| true) }));
+ }
+ ui.separator();
for (px, label) in THUMBS {
if menu_item(ui, tl!(label), true, o.thumb == px) {
set_options(ui.ctx(), |o| o.thumb = px);
diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs
index 7184135448..2771fe568e 100644
--- a/crates/ui-egui/src/panels/tests_links.rs
+++ b/crates/ui-egui/src/panels/tests_links.rs
@@ -104,6 +104,42 @@ fn the_panel_lists_the_images_with_link_info_for_the_selected_one() {
}
}
+/// Copy Info copies the file names of the selected links, or of `ids` in the order given, one per
+/// line; it is off with nothing selected, and a bad `ids` leaves the clipboard as it was.
+#[test]
+fn copy_info_copies_the_file_names_of_the_links() {
+ let dir = Folder::new("copy-info");
+ let (mut app, linked, embedded) = app(&dir);
+ let menu = painted_text(&mut app, super::links::menu);
+ assert!(menu.contains("Copy Info"), "{menu}");
+ // The selection is the embedded image: its row's name.
+ assert!(crate::menus::enabled(&app, "links.copyInfo"));
+ let r = app.run("links.copyInfo", json!({})).unwrap();
+ assert_eq!(r["names"], json!(["embedded.png"]));
+ assert_eq!(app.clipboard_out.take().as_deref(), Some("embedded.png"));
+ // Both selected: in the order the list gives them (the top image first).
+ app.run("select.set", json!({"ids": [linked, embedded]})).unwrap();
+ assert_eq!(app.run("links.copyInfo", json!({})).unwrap()["text"], "embedded.png\nlinked.png");
+ assert_eq!(app.clipboard_out.take().as_deref(), Some("embedded.png\nlinked.png"));
+ // `ids` in the order given, whatever is selected.
+ app.run("select.none", json!({})).unwrap();
+ let r = app.run("links.copyInfo", json!({"ids": [linked, embedded]})).unwrap();
+ assert_eq!(r["names"], json!(["linked.png", "embedded.png"]));
+ assert_eq!(app.clipboard_out.take().as_deref(), Some("linked.png\nembedded.png"));
+ // Errors copy nothing.
+ let rect = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap();
+ app.run("select.none", json!({})).unwrap();
+ for bad in
+ [json!({"ids": [linked, rect]}), json!({"ids": [linked, 999_999]}), json!({"ids": "all"}), json!({"ids": [linked, -1]}), json!({"ids": []})]
+ {
+ assert!(app.run("links.copyInfo", bad.clone()).is_err(), "{bad}");
+ assert!(app.clipboard_out.is_none(), "{bad}");
+ }
+ assert!(!crate::menus::enabled(&app, "links.copyInfo"));
+ assert!(app.run("links.copyInfo", json!({})).is_err());
+ assert!(app.clipboard_out.is_none());
+}
+
/// Shift-click selects the images of the rows from the last row clicked without Shift; Ctrl/Cmd-click
/// adds or removes one image, and Ctrl/Cmd-Shift-click adds the rows' images to the selection.
#[test]
@@ -168,6 +204,11 @@ fn a_link_inside_a_symbol_is_listed_and_picked_in_the_panel() {
click_row(&mut app, &ctx, "inside.png", egui::Modifiers::NONE, 1.0);
assert!(selected(&app).is_empty(), "the canvas can't select it");
assert!(shown(&mut app, 1.5).iter().any(|t| t == "30 × 20 px"), "Link Info of the symbol's image");
+ // Copy Info without ids copies the row picked in the panel.
+ app.ui_ctx = Some(ctx.clone());
+ assert!(crate::menus::enabled(&app, "links.copyInfo"));
+ assert_eq!(app.run("links.copyInfo", json!({})).unwrap()["text"], "inside.png");
+ assert_eq!(app.clipboard_out.take().as_deref(), Some("inside.png"));
click_row(&mut app, &ctx, "layer.png", egui::Modifiers::COMMAND, 2.0);
assert_eq!(selected(&app), [layer]);
// Both rows are selected until the canvas selection changes: then the panel's pick goes too.
diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs
index a8987855eb..3ab5fc2484 100644
--- a/crates/ui-egui/src/panels/variables.rs
+++ b/crates/ui-egui/src/panels/variables.rs
@@ -268,8 +268,6 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
let highlighted_bound: Vec = highlighted.as_ref().map(|h| bound_objects(st, h)).unwrap_or_default();
let Picked { selected, has_selection, selection_bound, single_type, single_image, selection_graph } = picked(st);
let locked = st.doc.variables.locked;
- // Save Variable Library writes text variables only.
- let has_text = st.doc.variables.variables.iter().any(|v| v.kind == VariableKind::Text);
if widgets::menu_item(ui, tl!("New Variable…"), !locked, false) {
crate::menus::invoke(app, "variable.define", json!({}));
@@ -333,7 +331,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
if widgets::menu_item(ui, tl!("Load Variable Library…"), true, false) {
crate::picks::button(app, load_library);
}
- if widgets::menu_item(ui, tl!("Save Variable Library…"), has_text, false) {
+ if widgets::menu_item(ui, tl!("Save Variable Library…"), !vars.is_empty(), false) {
crate::picks::button(app, save_library);
}
ui.separator();
@@ -494,19 +492,22 @@ mod tests {
assert!(text.contains("Name") && text.contains("Data Set 1"), "{text}");
}
- /// Load Variable Library's warning about variables that aren't text shows in the status bar,
- /// translated in every language but English.
+ /// Load Variable Library defines a library's variables of every kind and gives no warning. The
+ /// warning an SVG's variable data gives about variables that aren't text is translated in every
+ /// language but English.
#[test]
- fn the_variable_library_warning_shows_in_the_status_bar() {
+ fn the_svg_variable_data_warning_is_translated() {
use crate::i18n::{Lang, message};
let mut app = app_with_data();
+ let status = app.ui.status.clone();
let xml = r#" "#;
app.run("variable.loadLibrary", json!({"xml": xml})).unwrap();
- assert_eq!(app.ui.status, "variables that aren't text were left out: other (1)");
+ assert_eq!(app.ui.status, status, "the load gives no warning");
+ let warning = "variables that aren't text were left out: other (1)";
let langs: Vec = Lang::all().filter(|l| l.code() != "en").collect();
assert!(langs.len() >= 23, "{} languages", langs.len());
for l in langs {
- let shown = message(l, &app.ui.status);
+ let shown = message(l, warning);
assert!(!shown.contains("left out") && shown.contains("other") && shown.contains('1'), "{}: {shown}", l.code());
}
}
diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs
index 9029459195..f9939177de 100644
--- a/crates/ui-egui/src/prefs_dialog.rs
+++ b/crates/ui-egui/src/prefs_dialog.rs
@@ -404,7 +404,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
});
});
ui.add_space(14.0);
- ui.horizontal(|ui| {
+ // Export, Import and Reset share one row, which wraps when it is wider than the dialog.
+ ui.horizontal_wrapped(|ui| {
if widgets::secondary_button(ui, tl!("Export Preferences…")).on_hover_text(tl!("Save the applied preferences to a JSON file")).clicked()
{
export_preferences(app, &mut d);
@@ -417,15 +418,15 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
{
import_preferences(app, &mut d);
}
- });
- ui.add_space(8.0);
- ui.horizontal(|ui| {
if widgets::secondary_button(ui, tl!("Reset Preferences"))
.on_hover_text(tl!("Restore every preference to its default (applied on OK)"))
.clicked()
{
reset = true;
}
+ });
+ ui.add_space(8.0);
+ ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if widgets::primary_button(ui, tl!("OK")).clicked() {
ok = true;
diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs
index f45ba93410..5c9356edd9 100644
--- a/crates/ui-egui/src/prefs_dialog/tests.rs
+++ b/crates/ui-egui/src/prefs_dialog/tests.rs
@@ -335,6 +335,74 @@ fn reset_preferences(app: &mut VectorcraftApp) {
crate::dialogs::confirm(app).unwrap();
}
+/// The Preferences dialog drawn in `lang` with the open dialog available: the label and screen
+/// rectangle of each control, from the accessibility tree, and the dialog's content rectangle
+/// (inside its 20 pt margin and frame stroke).
+fn dialog_controls(lang: crate::i18n::Lang) -> (Vec<(String, egui::Rect)>, egui::Rect) {
+ crate::i18n::set_current(lang);
+ let mut a = app();
+ a.services.pick_open = Some(Box::new(|_: &crate::FilePick| None));
+ open(&mut a, Some("General"));
+ let ctx = egui::Context::default();
+ ctx.enable_accesskit();
+ crate::theme::install_fonts(&ctx);
+ let mut v = vec![];
+ for time in [0.0, 0.25, 0.5] {
+ let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0)));
+ let raw = egui::RawInput { screen_rect, time: Some(time), ..Default::default() };
+ let mut out = ctx.run_ui(raw, |ui| show(&mut a, ui.ctx()));
+ out.textures_delta.clear();
+ let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
+ v = nodes
+ .iter()
+ .filter_map(|(_, n)| {
+ let b = n.bounds()?;
+ Some((n.label()?.to_string(), egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))))
+ })
+ .collect();
+ }
+ crate::i18n::set_current(crate::i18n::Lang::EN);
+ let window = ctx.memory(|m| m.area_rect(egui::Id::unique("dialog-preferences"))).expect("the dialog window is shown");
+ let content = window.shrink(20.0 + ctx.global_style().visuals.window_stroke.width);
+ (v, content)
+}
+
+/// Export Preferences…, Import Preferences… and Reset Preferences share one row above OK and
+/// Cancel.
+#[test]
+fn export_import_and_reset_share_one_row() {
+ let (controls, _) = dialog_controls(crate::i18n::Lang::EN);
+ let top = |label: &str| controls.iter().find(|(t, _)| t == label).map(|(_, r)| r.top()).unwrap_or_else(|| panic!("no `{label}` in {controls:?}"));
+ let row = top("Export Preferences…");
+ assert!((top("Import Preferences…") - row).abs() < 0.5, "Import is on Export's row");
+ assert!((top("Reset Preferences") - row).abs() < 0.5, "Reset is on Export's row");
+ assert!(top("OK") > row + 20.0, "OK is on the row below");
+}
+
+/// In every language the dialog keeps its 760 pt content width, and the three buttons above OK
+/// lie inside it and above the row of OK and Cancel.
+#[test]
+fn export_import_and_reset_fit_in_every_language() {
+ for lang in crate::i18n::Lang::all() {
+ let (controls, content) = dialog_controls(lang);
+ assert!(content.width() <= 760.5, "{}: the dialog's content grew to {content:?}", lang.code());
+ let find = |label: &str| {
+ let label = crate::i18n::tr(lang, label);
+ controls.iter().find(|(t, _)| t == label).map(|(_, r)| *r).unwrap_or_else(|| panic!("{}: no `{label}` in {controls:?}", lang.code()))
+ };
+ let ok = find("OK");
+ for label in ["Export Preferences…", "Import Preferences…", "Reset Preferences"] {
+ let r = find(label);
+ assert!(
+ r.right() <= content.right() + 0.5 && r.left() >= content.left() - 0.5,
+ "{}: `{label}` at {r:?} is outside the dialog's content {content:?}",
+ lang.code()
+ );
+ assert!(r.bottom() <= ok.top(), "{}: `{label}` at {r:?} reaches the OK row at {ok:?}", lang.code());
+ }
+ }
+}
+
/// Reset Preferences then OK resets the preferences, General included, and leaves the open
/// document's units, with no undo step in the document.
#[test]
diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs
index ea32f6c078..d102c40d7e 100644
--- a/crates/ui-egui/src/shortcuts.rs
+++ b/crates/ui-egui/src/shortcuts.rs
@@ -226,7 +226,10 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) {
// Escape closes a dropdown list or popover open in the dialog (each closes itself on it) and
// leaves the dialog open.
let popup = app.ui.dialog.as_ref().is_some_and(|d| {
- egui::Popup::is_any_open(ctx) || crate::dialogs::brush_options::tips_open(d) || crate::dialogs::new_document_popup_open(d)
+ egui::Popup::is_any_open(ctx)
+ || crate::dialogs::brush_options::tips_open(d)
+ || crate::dialogs::new_document_popup_open(d)
+ || crate::dialogs::export_artboard_name_editing(app, d)
});
// Escape in Preferences' search field with text clears the field first.
if !popup && pressed_anew(ctx, Key::Escape) && !crate::prefs_dialog::clear_search_on_escape(app, ctx) {
diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs
index ff290952fb..d6a06960bb 100644
--- a/crates/ui-egui/src/tests/picks.rs
+++ b/crates/ui-egui/src/tests/picks.rs
@@ -366,18 +366,17 @@ fn load_variable_library_asks_off_the_ui_thread() {
let _ = std::fs::remove_dir_all(dir);
}
-/// The Variables panel menu's Save Variable Library… is enabled once the document has a text
-/// variable, and then asks off the UI thread: the library is written
-/// to the path the dialog answers, Load Variable Library reads it back, and the warning about the
-/// visibility variable it left out shows in the status bar.
+/// The Variables panel menu's Save Variable Library… is enabled once the document has a variable,
+/// of any kind, and then asks off the UI thread: the library is written to the path the dialog
+/// answers, and Load Variable Library reads back its visibility and text variables.
#[test]
fn save_variable_library_asks_off_the_ui_thread() {
let (mut app, shown, _) = app();
app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
- app.run("variable.define", json!({"name": "Shown", "kind": "visibility"})).unwrap();
- // Without a text variable the item is disabled and asks for no file.
+ // Without a variable the item is disabled and asks for no file.
click(&mut app, "Save Variable Library…", crate::panels::variables::menu);
assert!(shown.requests().is_empty(), "{:?}", shown.requests());
+ app.run("variable.define", json!({"name": "Shown", "kind": "visibility"})).unwrap();
app.run("variable.define", json!({"name": "Name", "kind": "text"})).unwrap();
app.run("dataset.new", json!({"name": "A", "values": {"Name": "x", "Shown": true}})).unwrap();
let dir = vectorcraft_testkit::temp_dir("picks-save-variable-library");
@@ -392,10 +391,11 @@ fn save_variable_library_asks_off_the_ui_thread() {
assert!(!library.exists(), "nothing is written before the dialog answers");
shown.answer(&[&library.to_string_lossy()]);
poll(&mut app);
- assert_eq!(app.ui.status, "variables that aren't text were left out: visibility (1)");
let xml = std::fs::read_to_string(&library).unwrap_or_else(|e| panic!("{e}: {}", app.ui.status));
let loaded = app.run("variable.loadLibrary", json!({"xml": xml})).unwrap();
- assert_eq!((loaded["variables"].clone(), loaded["names"].clone()), (json!(["Name"]), json!(["A"])));
+ assert_eq!((loaded["variables"].clone(), loaded["names"].clone()), (json!(["Shown", "Name"]), json!(["A"])));
+ let values = &app.session.doc().unwrap().doc.variables.datasets[0].values;
+ assert_eq!(values.get("Shown"), Some(&vectorcraft_doc::DataValue::Visible(true)));
let _ = std::fs::remove_dir_all(dir);
}
diff --git a/crates/ui-egui/src/tests/save.rs b/crates/ui-egui/src/tests/save.rs
index 33e6709913..b9b4111516 100644
--- a/crates/ui-egui/src/tests/save.rs
+++ b/crates/ui-egui/src/tests/save.rs
@@ -355,6 +355,37 @@ fn a_save_does_not_replace_the_file_read_from_through_a_file_written_beside_the_
let _ = std::fs::remove_dir_all(d);
}
+#[test]
+fn file_save_does_not_replace_the_file_read_from_through_a_file_written_beside_the_path() {
+ let d = dir("lossy-beside-save");
+ let path = d.join("Art.eps").to_string_lossy().to_string();
+ let mut app = app();
+ checks_files_there(&mut app);
+ app.run("file.new", json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
+ rect(&mut app);
+ let options = json!({"useArtboards": true, "previewFormat": "none", "thumbnails": false});
+ let _ = app.run("file.saveAs", json!({"path": path, "options": options}));
+ crate::background::wait_all(&mut app);
+ let siblings = artboard_files(&d);
+ assert_eq!(siblings.len(), 2, "{siblings:?}");
+ let sibling = siblings[0].clone();
+ let saved = std::fs::read(&sibling).unwrap();
+ std::fs::remove_file(&path).unwrap();
+ let st = app.session.doc_mut().unwrap();
+ st.imported_from = Some(sibling.clone());
+ st.import_losses = vec!["hidden type".into()];
+ rect(&mut app);
+ // File > Save to the document's own file reuses its options, so it writes the artboard files
+ // again; the one the document was read from is refused, as on Save As.
+ let _ = app.run("file.save", json!({}));
+ crate::background::wait_all(&mut app);
+ assert!(app.ui.dialog.as_ref().is_none_or(|d| d.kind != dialogs::confirm::REPLACE_FILES));
+ assert_eq!(std::fs::read(&sibling).unwrap(), saved);
+ assert!(!std::path::Path::new(&path).exists(), "no file of the set is written when one is refused");
+ assert!(app.session.active().unwrap().is_dirty());
+ let _ = std::fs::remove_dir_all(d);
+}
+
/// The app checks for files that are there, as the desktop app does.
fn checks_files_there(app: &mut VectorcraftApp) {
app.services.exists = Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists()));
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index f08e3a010d..115412d241 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -96,7 +96,7 @@ the two can still win that race.
| `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item |
| `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item |
| `ui.tool.select` / `ui.tool.list` | `{tool}` | |
-| `ui.pointer` | `{events:[{kind: down|drag|up|move|doubleclick, x, y, space?: "doc"|"screen", mods?}]}` | drive the active tool exactly like the mouse: `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is), and the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge |
+| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is), and the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge |
| `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | synthetic keyboard input |
| `ui.move` | `{x, y}` | screen-point pointer move |
| `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above |
@@ -123,7 +123,7 @@ the two can still win that race.
| Background Save / Export | `app.save`, `app.export {path}`, `file.save`, `file.saveAs`, `file.saveCopy`, `file.exportForScreens {folder, …}` | with the `backgroundSave` / `backgroundExport` preferences on (the default) the desktop app writes the file from a snapshot on a worker thread: the call returns `{path, background: true, status}` at once (`file.exportForScreens`: `{background: true, status}`, and the files are written into the folder from a snapshot taken at the call; an `app.export` given an option the format doesn't read: also `warnings`, naming the option), `ui.inspect` lists the jobs still running in `background` (labels such as `"Saving a.vectorcraft"`), and the document counts as saved (as of the snapshot) once its file is written. Quit and Close wait for them. A job that fails reports the error in the status bar only (`ui.inspect` → `ui.status`), a path outside `--automation-write-root` included. With the preferences off (`prefs.set`), saves return once written. `app.save {path?, wait: true}` and `app.export {path, wait: true}` wait for the jobs already running, write the file before they reply whatever the preferences are set to, and return its result or the error. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the preferences. A `wait` that is not `true`, `false` or `null` is refused with "`wait` must be true or false", and nothing is written |
| `engine.execute` `file.exportForScreens` | `{}` / `{…document.exportForScreens params}` | without params opens `exportForScreens` on the settings the document last exported with (`document.exportSettings`). While the Artboard tool is in use, the artboards it has selected (its `selected` option, the rows the Artboards panel highlights) are checked instead, and `select` is `range`, or `all` when every artboard is selected. Fields: `tab` (`artboards` \| `assets` \| `layers` \| `selection`; OK reads Export Layer or Export Selection on those), `layers` ([layer id…] checked), `selectionMode` (`one` \| `each`), `name` (the file name pattern of `document.exportForScreens`), `counterStart`, `folders` (`none` \| `rows` \| `format` \| `item` \| `itemFormat`), `exportPreset` (the preset applied last), `__savePreset` (the name typed to save one), `select` (`all` \| `range` \| `full`), `range` ("1-3, 5"), `boards` (a bool per artboard; checking them sets `select` and `range`), `includeBleed`, `folder` (desktop; default the Desktop, else home), `openLocation`, `subfolders`, `prefix`, `preset` (`""` \| `mobile` \| `density`), `formats` (rows `{format, scale: "2x" \| "100w" \| "100h" \| "72ppi", suffix, quality?, folder?}`), `settings` (`{png \| png8 \| jpg \| webp \| gif \| svg \| pdf: {…options}}`, the gear's Format Settings; `__settings` names the format shown). `ui.dialog.confirm` exports (a bad range or no folder keeps it open); on the web OK reads "Download" and the files download (several as one `.zip`). With params it runs `document.exportForScreens`: no `folder` returns the files (or with `zip: true` one zip) as `dataBase64`; with `openLocation` the first file is shown in the file manager. When `warnings` is not empty, an export into a folder or a download shows the first in the status bar as Save As shows a save's notes |
| Export for Screens' Assets tab, Asset Export panel | `ui.dialog.set` `tab: "assets"`, `assets: [asset id…]`; `window.panel {panel: "assetExport"}` | on the Assets tab of `exportForScreens` the `assets` field lists the checked asset ids (all of them when it opens); `ui.dialog.confirm` runs `document.exportForScreens {assets}` (nothing checked keeps it open) and OK reads "Export Asset". The Asset Export panel acts through `assets.*` and shares the format rows with the dialog (`assets.settings.set`). The dialog has the format presets menu (☰). In the dialog, `exportPreset` names the preset applied last (`ui.dialog.set` of it applies the preset it names, as picking it does; a name that is not a preset's is an error and leaves the dialog as it was), `__exportPresets` lists the presets, and `__savePreset` holds the name being typed after Save Preset…. The panel menu applies presets through `assets.settings.set {exportPreset}` and holds Save As Preset…, Save Changes, Delete Preset, Import Preset… and Export Preset…. Import and Export use picked files. Its Create Sub-folders and Open Location after Export run `assets.settings.set {subfolders}` and `{openLocation}`; its Format Settings… opens the dialog on the Assets tab with `__settings` set to the first row's format. |
-| `engine.execute` `file.exportSelection` | `{multiple?}` | File › Export Selection…: collects the selected objects as one asset (`assets.add`; one per object with `multiple: true`) and opens `exportForScreens` on its Assets tab with just them checked → `{assets}`. `document.exportSelection` with params still exports the selection in one go, without the dialog; with no params or `{}` the save panel picks the file and its format's options dialog follows, as after Export As, and the call returns `null` while the dialog is open (OK returns what `file.exportAs` returns, without `format` or `bounds`). `file.exportAs {path, exportSelection: true, …options}` writes the selection without a dialog |
+| `engine.execute` `file.exportSelection` | `{multiple?}` | File › Export Selection…: collects the selected objects as one asset (`assets.add`; one per object with `multiple: true`) and opens `exportForScreens` on its Assets tab with just them checked → `{assets}`. `document.exportSelection` with params still exports the selection in one go, without the options dialog (without `path`, the save panel picks the file first); with no params or `{}` the save panel picks the file and its format's options dialog follows, as after Export As, and the call returns `null` while the dialog is open (OK returns what `file.exportAs` returns, without `format` or `bounds`). `file.exportAs {path, exportSelection: true, …options}` writes the selection without a dialog |
| CSS Properties panel | `window.panel {panel: "cssProperties"}`; `engine.execute` `css.copy` / `css.exportFile` | the panel shows `css.selection` of the selection (after Generate CSS, while nothing is selected, `css.generate`); its menu holds the options the commands take (`units`, `position`, `dimensions`, `unnamed`, `rasterize`). `css.copy {scope?, …options}` copies the CSS to the clipboard → `{css, rules}`; `css.exportFile {path?, scope?, …options}` writes `css.export` to `path` (else a picked file; the web downloads it) with the pictures of rasterized art next to it → `{path, rules, images, warnings}`, and the status bar shows `warnings` as Export As shows an export's notes |
| `ui.dialog.*` on `importPdf` | `{field: "page" \| "allPages" \| "range" \| "cropTo" \| "password", value}` | opening (`app.open`, `file.open`) a PDF, `.ai` or `.ait` with a password, or one with several pages unless it is a `.ai` or `.ait` with its editing data or carries its VectorCraft document (those open whole), or placing (`file.place` without `page`) any of them with several pages or a password, opens the Import PDF dialog (`mode`: `open` or `place`; `pageCount`). While `__locked` is true, set `password` and `ui.dialog.confirm` to unlock it (a one-page file then opens or is placed). Then set `allPages: false` and `range` ("2-3, 5") to open some pages, or `page` to place one, and `cropTo` (`bounding`, `art`, `crop`, `trim`, `bleed`, `media`); `ui.dialog.confirm` opens or places them (placing keeps the other `file.place` params, such as `link`, `template` and `at`, in `__place`). `document.open {pages, cropTo, password}` and `file.place {page, crop, password}` do the same without the dialog |
diff --git a/docs/localization-hi.md b/docs/localization-hi.md
index d73e78676b..743a1697ec 100644
--- a/docs/localization-hi.md
+++ b/docs/localization-hi.md
@@ -32,6 +32,13 @@ every clause such as "all" or "what follows it". Type as a text object is टा
in `crates/ui-egui/src/i18n/tests.rs` checks the save, swatch, crop, resolution and path terms
and the point unit in every row.
+Translate a label by its sense in the interface, not by its first dictionary sense. A ruler is
+रूलर, never शासक (a sovereign); a text character is कैरेक्टर, never चरित्र (a personality); a
+vector point is पॉइंट and a printer's mark is मार्क, never अंक (a digit); fills are फ़िल्स, never
+भरता (the verb). In a minimum, desired and maximum range, Desired is वांछित, never देसी (local),
+and a range message keeps both comparisons: minimum ≤ desired ≤ maximum. The same test rejects
+these senses, and others found in the catalog, in every row whose English names the word.
+
A variable is वेरिएबल (plural वेरिएबल्स) in every sense: a data-merge variable and the
variable library, a variable font, a variable stroke width and an environment variable. It is
never चर, परिवर्तनीय or वैरिएबल. Joining paths, anchor points, point type or the lines of a
@@ -61,7 +68,10 @@ checks every `@msg` row's lists.
| Artwork | आर्टवर्क |
| Path / Anchor point / Handle | पाथ / एंकर पॉइंट / हैंडल |
| File path on disk | फ़ाइल पाथ |
-| Fill / Stroke | फ़िल / स्ट्रोक |
+| Fill / Fills / Stroke | फ़िल / फ़िल्स / स्ट्रोक |
+| Point (vector) / Printer's marks | पॉइंट / मार्क्स |
+| Ruler / Ruler origin | रूलर / रूलर ओरिजिन |
+| Minimum / Desired / Maximum | न्यूनतम / वांछित / अधिकतम |
| Gradient / Mesh / Blend | ग्रेडिएंट / मेश / ब्लेंड |
| Pattern / Swatch | पैटर्न / स्वॉच |
| Type (text object) / Crop / Resolution | टाइप / क्रॉप / रिज़ॉल्यूशन |
@@ -89,7 +99,10 @@ percentage of the application's entire interface.
On 2026-11-13 the catalog has 8,782 rows, including 3,014 `@msg`, 47 `@msgplural` and 41
`@plural` rows. A wording pass on that date corrected 193 rows outside the plug-in
messages for meaning, dropped clauses, English left in place and the save, swatch, crop,
-resolution, path and type terms. It is not a native proofread.
+resolution, path and type terms. A second pass on that date corrected 85 short labels and
+messages that used a word's unrelated sense, such as देसी (local) for Desired, शासक (a
+sovereign) for a ruler and उच्च न्यायालय (a high court) for High Contrast. It is not a native
+proofread.
The comparison covers release `v0.21.1` (`f6aa4309`) and current `main` (`3c7d9e1f`). Their
non-English catalogs have no missing Hindi keys except the names deliberately kept in English.
diff --git a/docs/localization-parity.md b/docs/localization-parity.md
index a83f7b09c2..2fa44a769e 100644
--- a/docs/localization-parity.md
+++ b/docs/localization-parity.md
@@ -31,7 +31,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a
| English | `en` | source, 100% | all | Latin | — | full | — |
| Simplified Chinese (Mandarin) | `zh-hans` | 5,102 rows, 791 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | all (3,554 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate) | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) |
| Spanish | `es` | 4,009 / 4,020 (99.7%) | all (604 messages) | Latin | no | full | — (review) |
-| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; web font still needed | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review, layout and web font |
+| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; web font still needed | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review, layout and web font |
| Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback; no Gujarati face in the pinned CI/release fonts or web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font |
| Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 |
| 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) |
diff --git a/docs/mcp.md b/docs/mcp.md
index 8c43d66974..1185d8e6f6 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -647,8 +647,8 @@ sampler.
| `inspect_document` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | Artboards (with `color`, `#rrggbb`, for one with a background color), layer tree (ids, kinds, bounds, paint), selection, history, tool. A type node's `fill`, `stroke` and `strokeWidth` are the paint its characters show (its first run's); fills and strokes of the type object itself come as `objectFill`, `objectStroke` and `objectStrokeWidth`. Paint comes as a label (`"#ff0000"`, `"None"`, `"G1 40% (#ff9999)"` for a swatch at a tint); `paint.proxies` gives it as an object. |
| `inspect_ui` | `{}` | UI state. Remote mode only. |
| `select_tool` | `{tool}` | `selection`, `directSelection`, `pen`, `rectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, … |
-| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. |
-| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. |
+| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. |
+| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. |
| `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. |
| `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. Polygons and stars take `rotation` in degrees clockwise (0: a corner or point straight up). `line`: `x1,y1,x2,y2`. |
| `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. |
@@ -1127,8 +1127,9 @@ follows as after Export As: Save PDF without its Artboards section, SVG Options
options, EPS Options, DXF Options without Export Selected Art Only, Text Export Options with Selection Only on, or an
exporter plug-in's parameters. Other formats are written at once. OK writes the selection alone, cropped to it, as
`document.exportSelection` writes it, with the chosen options. While a dialog is open the call returns `null`, and
-OK returns what `file.exportAs` returns, which has no `format` or `bounds` (Text Export Options: `{path}`). To
-write without a dialog, pass `path` or any option. `file.exportAs {path, exportSelection: true, …options}` writes the selection the same way.
+OK returns what `file.exportAs` returns, which has no `format` or `bounds` (Text Export Options: `{path}`). Any
+option skips the options dialog, but without `path` the save panel still picks the file. To write without a
+dialog, pass `path`. `file.exportAs {path, exportSelection: true, …options}` writes the selection the same way.
Raster exports default to the document's raster effects resolution. An explicit `scale` sets pixels per
point (72 times that value in ppi); `options.ppi` wins over either scale option. CLI `run --export` and
@@ -1735,6 +1736,16 @@ one opens as before and draws it as `rgb`:
→ invalid parameters for `effect.setParams`: `channel` must be one of rgb, red, green, blue
```
+Radial Blur's Blur Center, `centerX` and `centerY`, must each be a number from 0 to 1: the share of the object's bounds
+across from its left edge and down from its top edge (0.5 each, the object's center, by default). The effect turns or
+zooms about that point, which moves and scales with the object. `effect.apply` and `effect.setParams` refuse any other
+value themselves in the same way, and a document saved with one draws it at the nearest edge:
+
+```json
+{"id": "effect.setParams", "params": {"index": 0, "params": {"centerX": 1.5}}}
+→ invalid parameters for `effect.setParams`: `centerX` must be a number from 0 to 1
+```
+
A number outside the range the effect documents is still stored as given and clamped when the effect draws. A
plug-in effect's parameters are resolved against its manifest instead. `effect.setParams` as a step of
`command.batch` is checked when the step runs, against the effects the steps before it added, and the batch then
@@ -3343,32 +3354,48 @@ already walks Image Trace. Short agent entry points:
`dataset.import`, adds no undo step when it leaves the variables and data sets as they were. The library
is XML whose `variableSets` element holds `variableSet` elements, each with a `variables` element of `variable`
elements (`varName`, `trait`) and a `sampleDataSets` element of `sampleDataSet` elements (`dataSetName`). Every
- data set is deleted, and every variable of the document is deleted with its bindings and values, except a text
- variable the library also declares: it keeps its bindings, so selecting one of the library's data sets changes the
- objects bound to it. Then the library's other variables whose `trait` is `textcontent` are defined as text
- variables, unbound. In each data set, the element named
- after a text variable gives its value: the text of its `p` elements, one paragraph each. An element without a `p`
- element gives no value. Variables of other kinds are left out with their values: the reply lists them in `skipped`
- (`name`, `trait`), and its `warning` names each `trait` with its count. The reply's `deleted` and `deletedDataSets`
+ data set is deleted, and every variable of the document is deleted with its bindings and values, except a variable
+ the library also declares with the same kind: it keeps its bindings, so selecting one of the library's data sets
+ changes the objects bound to it. Then the library's other variables are defined, unbound, with the kind their
+ `trait` gives: `textcontent` is text, `visibility` is visibility, `fileref` (a linked file) is image and
+ `graphdata` is graph. A variable without a `trait`, or with one VectorCraft doesn't know, is defined of unknown
+ kind and takes no values. In each data set, the element named after a variable gives its value:
+ - text: the text of its `p` elements, one paragraph each; an element without a `p` element gives no value;
+ - visibility: `true` or `false`, in any case;
+ - image: a file's absolute path (from `/`, `\\` or a drive's root) or a `file:` URL of one, whose `%XX` escapes
+ are decoded; the file isn't read, so a library can name files that aren't there;
+ - graph: a `data` element. Its optional `propertyRow` holds a corner cell and then the series names, and each `row`
+ of its `values` holds the row's category in a first `value` whose `key` is `name`, then a `value` per series. A
+ value that is empty, marked `type="string"` or not a number is a blank. The data is read as the CSV
+ `graph.setData` takes, at most 256 KiB of it. Graph data with more than 10,000 rows or 256 series, which a
+ graph doesn't hold, is refused, by `variable.saveLibrary` too. `variable.saveLibrary` also refuses graph data
+ with neither rows nor series, which loads back as no value.
+
+ Visibility, image and graph values are read without the white space round them, and an element holding only white
+ space gives no value. The reply's `variables` lists the library's variables, and `deleted` and `deletedDataSets`
list the variables and data sets the load deleted. While the variables are locked, a library that would delete or
- define a variable fails with "variables are locked". The reply is `{variables, deleted, deletedDataSets, names,
- skipped, warning?}`. A library larger than 8 MiB, one whose elements nest more than 256 deep, and one with more
+ define a variable fails with "variables are locked". The reply is `{variables, deleted, deletedDataSets, names}`. A
+ library larger than 8 MiB, one whose elements nest more than 256 deep, and one with more
than 256 variables or 1,000 data sets are refused. Its document type declaration may hold an external identifier,
comments, processing instructions and up to 64 entity declarations whose values are plain text (no `<`, `&` or
`%`). A declaration that holds anything else, and entity references that expand the library past 8 MiB, are
- refused. So are a variable or data set declared twice and a value for a variable the library doesn't declare.
- `variable.saveLibrary {path?}` (the panel menu's Save Variable Library…) writes the document's text variables and
- every data set as a variable library in the layout `variable.loadLibrary` reads: a `variable` element with
- `varName` and `trait="textcontent"` for each text variable, and a `sampleDataSet` element with `dataSetName` for
- each data set, holding an element named after each text variable it has a value for, with one `p` element per line
- of the value. Loading the file gives back the same text variables, data set names and text values. Variables of
- other kinds are left out with their values: the reply lists them in `skipped` (`name`, `kind`), and its `warning`
- names each kind with its count. Saving is refused for a document without a text variable, for a text variable whose
- name isn't an XML name (it starts with a letter or `_` and holds only letters, digits, `-`, `_` and `.`), for a
- data set whose name or text value holds a control character, for a data set name with white space at either end,
- for a name longer than 255 characters or used twice, and past `variable.loadLibrary`'s caps (256 variables, 1,000
- data sets, 8 MiB). Without `path` the reply is `{xml, variables, datasets, skipped, warning?}`;
- with it, the file is written and the reply is `{path, variables, datasets, skipped, warning?}`.
+ refused. So are a variable or data set declared twice, a value for a variable the library doesn't declare, and a
+ value that doesn't fit its variable's kind.
+ `variable.saveLibrary {path?}` (the panel menu's Save Variable Library…) writes the document's variables and every
+ data set as a variable library in the layout `variable.loadLibrary` reads: a `variable` element with `varName` for
+ each variable, with the `trait` and `category` of its kind (`textcontent` and `&ns_flows;`, `visibility` and
+ `&ns_vars;`, `fileref` and `&ns_vars;`, `graphdata` and `&ns_graphs;`; neither for a variable of unknown kind), and
+ a `sampleDataSet` element with `dataSetName` for each data set, holding an element named after each variable it has
+ a value for. A text value is written with one `p` element per line, a visibility value as `true` or `false`, an
+ image value as its path (a path from the root of a Unix file system as a `file:///` URL), and a graph value as a
+ `data` element, with a blank category marked `type="string"`. Loading the file gives back the same variables with their kinds, data set names and values; graph
+ data comes back in the CSV form Graph Data writes. Saving is refused for a document without a variable, for a
+ variable whose name isn't an XML name (it starts with a letter or `_` and holds only letters, digits, `-`, `_` and
+ `.`; a variable of unknown kind has no values, so its name isn't checked), for a name or value that holds a control
+ character, for a name with white space at either end, for a name longer than 255 characters or used twice, for an
+ image value that isn't a file's absolute path, and past `variable.loadLibrary`'s caps (256 variables, 1,000 data
+ sets, 8 MiB). Without `path` the reply is `{xml, variables, datasets}`; with it, the file is written and the reply
+ is `{path, variables, datasets}`.
- Batch: `action.batch {commands, source?: folder|datasets, folder?, destination?: none|saveAndClose|folder,
destinationFolder?, overrideOpen?, overrideSave?, overrideExport?, includeSubdirs?, stopOnError?}` plays an
action on every file in a folder or every data set (the Actions panel menu's Batch…). Override Save and Override
@@ -3745,6 +3772,31 @@ already walks Image Trace. Short agent entry points:
`livePaint.strokeEdge` when an edge is within 4 screen pixels of the pointer and `livePaint.fill` otherwise, and
Shift-click runs `livePaint.fill`. With both off, a click runs nothing. With `highlight` off, the face or edge under
the pointer is not outlined.
+ A double-click runs the command a click there runs with `scope: "connected"`, and a triple-click with
+ `scope: "samePaint"`; Alt held runs nothing, and so does Cmd/Ctrl (`mods.cmd`), whose presses go to the selection
+ tool Cmd lends. With Space held (`mods.space`, the view tools), a press, a
+ double-click or a triple-click runs nothing, and a move outlines no face or edge. On a face, `connected` fills the face and every face reached from it
+ across edges that draw no stroke (an edge that is hidden or fully transparent, or whose strokes are each hidden,
+ without paint, 0 pt wide or fully transparent); a stroked edge, a hidden face, a gap
+ that Gap Detection closes and the group's outside stop it. `samePaint` fills every face
+ of the group, joined to it or not, whose fill is the `match` paint. On an edge, `connected` paints the edge and the
+ edges joined to it end to end that draw with the stroke paint `match`, and `samePaint` paints every edge of the
+ group that draws with that stroke paint; the stroke's weight is not compared. An edge draws with the paint of its
+ topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully
+ transparent or has no such stroke. Each click of a double-click or triple-click runs as it
+ arrives and is its own undo step. `match` is the paint the face or edge had before the first of the double-click's
+ two clicks or the triple-click's three that painted it, or before the double-click when the triple-click's double-click
+ reached it, so the clicks before the last do not change what it matches;
+ a first click that made the Live Paint group counts when the face it filled is the clicked face. Hidden faces and edges are not painted. An edge takes the
+ paint and weight in its topmost stroke that is shown, or in a new stroke above the others when it has none. These rules
+ for what faces and edges join and what paints match are VectorCraft's own. The help page describes the gestures:
+ https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html.
+ `livePaint.fill {scope}` and `livePaint.strokeEdge {scope}` take `scope` as `"one"` (the default), `"connected"` or
+ `"samePaint"`; any other value is an error and changes nothing. `match` is a paint in the model JSON that
+ `document.node {id}` writes for an appearance's paints (`{"type": "none"}` for none), taken only with a scope that compares paints, and
+ defaults to the face's fill or the stroke paint the edge draws with. `livePaint.fill` refuses a `scope` other than `"one"` with
+ `points`. Both replies add `count`, the number of faces or edges the click reaches, including those that already had the
+ paint.
With the Live Paint Bucket selected and no drag in progress, Left and Right without Shift, Alt or Cmd/Ctrl (which
keep their shortcuts) run `paint.setFill {swatch, ids: []}` (or
`paint.setStroke` when the Stroke proxy is in front) with the color swatch before or after the active paint in the
@@ -3761,7 +3813,8 @@ already walks Image Trace. Short agent entry points:
objects; otherwise it returns an error and does not merge the objects.
A Live Paint command that changes nothing records no undo step, keeps the redo steps, leaves a saved document saved
and replies as usual: `livePaint.fill` (a click, or a Bucket drag) when every face it reaches already has the paint,
- `livePaint.strokeEdge` when the edge already has the paint and the width, `livePaint.gapOptions` (and the Gap Options
+ `livePaint.strokeEdge` when the topmost shown stroke of each edge it reaches already has the paint and the width,
+ `livePaint.gapOptions` (and the Gap Options
dialog's OK) when every group already has the options and `closeGaps` finds no gap, and `livePaint.make` or
`livePaint.merge` given one Live Paint group alone, which they select. Such a fill or stroke also leaves the recent
colors and the last color as they are. `livePaint.gapOptions` makes a group's faces again, with new ids, only when it adds a path or when Gap Detection is turned on or off or given a new size while it is on.
@@ -5223,7 +5276,7 @@ The Attributes panel (`window.panel {panel: "attributes"}`, Cmd+F11) reads `attr
objects differ) and `recentUrls`. `attributes.set {overprintFill?, overprintStroke?, showCenter?, imageMap?, url?,
note?, ids?}` sets them in one undo step; `path.setFillRule {rule: "nonZero"|"evenOdd"}` sets the fill rule of the
paths and compound paths, and `path.reverse {reversed?}` makes subpaths run counter-clockwise (true) or clockwise
-(false). When every subpath of a path turns alike, its strokes' width profiles (left and right swapped) and pen
+(false). When every subpath of a path or compound path turns alike, its strokes' width profiles (left and right swapped) and pen
pressure, tilt, bearing and rotation turn with it, so the strokes draw as before. SVG export wraps an object with a URL in ``, and SVG import reads ` ` links back.
```json
@@ -6226,8 +6279,9 @@ Color on (HDR or Automatic Color Management) and macOS windows are converted by
again. In a Wayland session, and where no profile is set or the profile is not an RGB display profile of at most 1 MiB,
the canvas stays sRGB. The app reads the display again every 10 seconds and when the window moves to another display.
Exports, `ui.render`, the document, panels and thumbnails are not converted; with Proof Colors on, the proof is drawn
-first and then converted. The art is converted before it is drawn over the converted paper, so the blend of a
-translucent object or an antialiased edge with the paper can differ slightly from a conversion of the blended color.
+first and then converted. Translucent art and the antialiased edges of art over an artboard's paper or the
+transparency grid are blended with it in sRGB, and the blend is converted; over the pasteboard and in Outline the art
+is converted on its own.
`ui.inspect` returns `displayProfile`: `{enabled, display, source, profile, from, applied, reason,
osManaged}`, where `source` is `profile`, `srgbProfile` (a profile that shows sRGB unchanged), `system`, `none`,
`pending` or `unsupported`, `applied` says whether the canvas is converted, and `reason` says why not.
@@ -7578,6 +7632,12 @@ bounds; `clip` puts it in a clip group of the old bounds when it is larger). The
except for a placed document, which opens in a tab. With the preference `editOriginalSystemDefaults` (Preferences ›
File Handling › Use System Defaults for Edit Original, on by default) off, Edit Original opens a raster image in the app
that made it, PhotoCraft, where it is installed, and anything else in the system's default app (#5236).
+The UI command `links.copyInfo {ids?}` (the panel menu's Copy Info) copies the file names of images and placed
+documents `ids` to the clipboard, one per line in the order given, and returns `{text, names}`. Without `ids` (or with
+`ids: null`, as for the other `ids` commands) it copies the selected ones, and the rows outside the layer tree picked in
+the panel, in the order `links.list` gives them; the panel menu passes the selected rows in the order the panel shows
+them. An embedded image gives the name its row shows. An id that is not an image or a placed document, a
+malformed `ids`, or nothing to copy is an error, and the clipboard is left as it was.
```json
{"name":"run_command","arguments":{"command":"links.list","params":{"show":"missing"}}}
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 1cf18c3ce3..1f89391864 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -159,7 +159,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 |
| M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 |
| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 |
-| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) |
+| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) |
| M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 |
| M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 |
| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 |
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index c6972468cc..cad5851e98 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -743,6 +743,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`.
- **Document Setup › Color:** a Color tab shows the document color mode (RGB Color or CMYK Color), a Convert to CMYK or Convert to RGB box for a mode change (cleared: the colors keep their numbers), and the RGB and CMYK profiles assigned to the document, with a working-space entry for none. OK runs `edit.assignProfile` and then `file.documentColorMode` with the dialog's other changes in one `command.batch`, and the document's changes are one undo step. An unchanged Color tab adds no color commands, and Cancel, or OK with nothing changed, records no undo step. A Color tab field with a value of the wrong kind is an error, and the dialog stays open. The tab is VectorCraft's own layout; File › Document Color Mode and Edit › Assign Profile… stay as they are. Tests in `dialogs/document_setup.rs`.
- **Canvas through the display's profile on Windows and X11:** Preferences › Performance › Use Monitor Profile for Canvas (on by default) converts the canvas's art, artboard paper and transparency grid from sRGB into the ICC profile of the display that shows most of the main window, after any proof, as the help page describes the monitor's profile translating the document's colors for the monitor ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). Windows gives the display's default profile, and a display with Advanced Color on is left to Windows ([Microsoft Learn](https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles)); X11 gives colord's profile for the output or the `_ICC_PROFILE` property. macOS converts the window itself, and a Wayland session stays sRGB. `ui.inspect` reports `displayProfile`. Tests in `color/src/cms/display.rs`, `ui-egui/src/display_profile.rs` and `canvas::tests::the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on`.
+- **Translucent art blended before the display profile:** with Use Monitor Profile for Canvas converting, translucent art and the anti-aliased edges of art over an artboard's paper, a colored artboard or the transparency grid are blended with it in sRGB and the blend is converted, so the monitor's profile translates the document's colors as they are composited ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). The frame rendered whole, the part an edit renders again, the render worker's frame, the pan fill and the other windows' panes do the same; over the pasteboard and in Outline the art is converted on its own, and with no profile to convert into nothing changes. Tests `display_profile::tests::translucent_pixels_over_the_paper_are_blended_before_they_are_converted`, `the_transparency_grid_is_blended_cell_by_cell`, `the_backdrop_is_found_through_the_view` and `canvas::tests::translucent_art_over_the_paper_is_blended_before_the_display_profile`.
- **Out-of-gamut warning after a profile change:** the out-of-gamut warning and its closest-color correction in the Color panel and Color Picker ([the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)) check the color against the document's assigned CMYK profile, else the working CMYK space, and update when Edit › Assign Profile… or Edit › Color Settings… changes that space or a loaded profile changes, without a change of color. Which CMYK space the warning uses is VectorCraft's own rule. Tests: `gamut_warning_follows_a_profile_change` and `gamut_warning_follows_a_profile_loaded_again` in `dialogs/color_picker/tests.rs`.
- **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. With Window › Arrange › Tile or floating document windows, each document behind the front one draws its art, paper and transparency grid through its own assigned profiles, and loading or removing a profile redraws the documents assigned it; placed documents inside it still draw through the front document's profiles. How documents behind the front one draw is VectorCraft's own rule. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`.
- **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both.
@@ -806,6 +807,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set, unless a recorded Save step that Override Save points into the destination folder first makes each data set's file the document's own. A recorded Save, Save a Copy, Save as Template or export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy, template, PDF, EPS, DXF, Save for Web or Save for Office Documents step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. Unless a recorded Save or Save As step writes a file and makes it the document's own first, `action.batch` refuses Save and Close over the data sets of a document that was never saved, was converted from an older version or was restored by Data Recovery.
- Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`).
- Export presets: the Asset Export panel menu lists the export presets of Export for Screens, with Import Preset… and Export Preset…, which read and write `.vcexportpresets` files (`document.exportPresets.import`, `document.exportPresets.export`). An imported preset whose name is taken gets a number. In the panel, a preset applies to the shared export settings (`assets.settings.set {exportPreset}`), and Save Preset… saves them. With Create Sub-folders off, the panel's Export writes every file into the folder itself, mobile and density rows included.
+ - Export for Screens artboard names can be double-clicked to rename them in grid or list view (#7275). Enter, a click outside the field or switching to Assets commits the name; Escape cancels the edit. The dialog stays open, checked artboards stay selected and the rename is undoable. The typed name goes to the artboard that was double-clicked even when the artboards change order while it is typed; the field closes when its artboard is deleted or another document becomes active. Evidence: `dialogs::tests_screens::double_clicking_an_artboard_name_in_export_for_screens_renames_it`, `dialogs::tests_screens::switching_export_tabs_commits_an_artboard_name`, `dialogs::tests_screens::an_artboard_name_follows_its_artboard_while_it_is_typed` and `dialogs::tests_screens::an_artboard_name_stays_with_its_document`.
- Asset Export panel menu: Create Sub-folders (on by default) and Open Location after Export are check items that set the dialog's two checkboxes (`assets.settings.set {subfolders, openLocation}`), and the panel's Export follows them, including a folder per format or item that Export for Screens remembers (3D assets' mesh files go in the folder itself); Format Settings… opens Export for Screens on the first row's format settings ([Asset Export panel](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/collect-and-export-assets-from-asset-export-panel.html)). Tests: `panels::tests_asset_export`.
- Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Include Artboard Fill, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`.
- Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`).
@@ -816,8 +818,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Variables: Import Data Sets… (`dataset.import`) reads a UTF-16 file without a byte-order mark, instead of refusing it, when at least half of its two-byte units hold a NUL byte; it uses the byte order that reads its line breaks.
- Graphs: the Graph Data window's Import Data reads a UTF-16 text file without a byte-order mark by the same rule as Import Data Sets…, instead of filling the cells with NUL characters. It reads a file cut short by one byte, or with an unpaired surrogate, as it reads one after a byte-order mark.
- Variables: Import Data Sets… (`dataset.import`) defines the variables a file's header names that the document lacks, unbound. `#Shown` defines a visibility variable, `@Photo` defines an image variable, and a header without a prefix defines a text variable. A header that is a variable's exact name keeps naming it, and any other `%` header (graph data files) is refused.
- - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every data set is deleted, and every variable is deleted with its bindings and values, except a text variable the library also declares, which stays bound so the library's data sets change its objects (#4136); then the library's other text variables are defined, unbound, and its data sets take the text of each value's `p` elements, one paragraph each. Variables of other kinds are left out with a warning that names their kinds.
- - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's text variables and data sets as a variable library's XML file, which Load Variable Library reads back with the same text variables, data set names and text values. Variables of other kinds are left out with a warning that names their kinds.
+ - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every data set is deleted, and every variable is deleted with its bindings and values, except a variable the library also declares with the same kind, which stays bound so the library's data sets change its objects (#4136); then the library's other variables are defined, unbound: text, visibility, image (linked file) and graph variables, and variables without a known `trait` as unknown. Its data sets take text values from each value's `p` elements, one paragraph each, visibility values from `true` or `false`, image values from a file's absolute path or `file:` URL, and graph values from a `data` element of series names and rows.
+ - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's variables of every kind and its data sets as a variable library's XML file, which Load Variable Library reads back with the same variables, kinds, data set names and values.
- JSON-lines control channel with real egui pointer and keyboard injection.
- Variables: a type object holds one text variable. `variable.bind` and Make Text Dynamic refuse a second one and name the text variable the object has; a visibility variable can still share the object, and a document saved with two text variables on one object opens with both.
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
@@ -909,6 +911,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md).
- Gujarati (2026-11-14, #6613): `gu` has 4,673 catalog rows, zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial; the pinned fonts and web startup list have no Gujarati face, so web selection remains unavailable until one is bundled. Current-head validation is recorded in the PR; scores and estimates unchanged.
- Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged.
+ - Hindi word senses (2026-11-13): 85 labels and messages use the interface sense of their English: Desired is वांछित and the range message keeps both comparisons, rulers are रूलर, text characters कैरेक्टर, vector points पॉइंट, fills फ़िल्स and High Contrast उच्च कंट्रास्ट; the glossary test rejects the unrelated senses in every row; native review remains; scores and estimates unchanged.
- Hindi terms (2026-11-13): every row that names a variable (data merge, variable fonts and widths, environment variables) says वेरिएबल, and joining paths, anchor points, point type and lines says जोड़ें instead of शामिल हों, which stays for joining the community; a test checks both terms in every row; scores and estimates unchanged.
- Hindi English words (2026-11-13): 264 rows no longer keep English words in their sentences, repeat a parameter's name in Hindi or garble them, among them "unknown align", which now names the alignment; lists of accepted values such as `(left|right|top|bottom)` stay as their English writes them; two tests check every row; native review remains; scores and estimates unchanged.
- Message field names and values (2026-11-13): 49 status and error messages in the Hindi, Bulgarian, Danish, Indonesian, Dutch, Brazilian Portuguese, Swedish and Turkish catalogs keep the field names in brackets, such as `[subpath, anchor]`, and the values an `unknown` message lists, such as `(points, lines)`, as their English writes them; a test checks every catalog; scores and estimates unchanged.
@@ -1524,6 +1527,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`.
With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`.
Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). Faces are outlined at the Width and edges at half of it, as the page says faces are highlighted with a thick line and edges with a thin line. With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight, bucket_highlights_an_edge_thinner_than_a_face}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`.
+ Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group with the face's fill, or paints every edge with the edge's stroke (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step, and the paint compared is the one the face or edge had before the first of its clicks that painted it; a first click that made the Live Paint group counts when the face it filled is the clicked face. With Space held for the view tools, a click, double-click or triple-click paints nothing and no face or edge is outlined, and with Cmd/Ctrl held a double-click or triple-click paints nothing. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_scope_and_match_are_checked}`, `builder::tests::{bucket_double_and_triple_click_widen_what_a_click_paints, bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face, bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fill, bucket_highlights_nothing_with_space_held}`, `tests::build::{live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint, live_paint_bucket_cmd_double_and_triple_click_paint_nothing}`, `tests::livepaint::{a_triple_click_fills_every_face_of_the_same_fill, clicks_with_space_held_paint_nothing}` (MCP).
Live Paint Bucket Options has Cursor Swatch Preview, as the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) lists: with the Bucket selected, the active fill or stroke shows above the pointer between the color swatches before and after it in the Swatches panel, and the Left and Right arrow keys pick the swatch before or after it, as the page describes. The selected art keeps its paint. As VectorCraft's own rules, the option is on at first, the arrows step the stroke when the Stroke proxy is in front, they wrap around at the ends and still step with the preview off, a color that is no swatch shows alone until Right picks the first swatch or Left the last, and the arrows do nothing during a fill drag or with no color swatch. Evidence: `tests::build::{live_paint_bucket_arrow_keys_step_the_active_paint_through_the_swatches, live_paint_bucket_arrow_keys_handle_unmatched_paint_few_swatches_and_drags, live_paint_bucket_arrow_keys_pass_swatches_of_the_same_color_for_fill_and_stroke, swatch_arrow_keys_leave_modified_arrows_to_the_shortcuts}`.
Live Paint Make preserves the front-most covering source's fill when compound paths share a curved boundary, and Expand keeps the face fills. Regression evidence: `planar::tests::coincident_curves_keep_their_source_faces` checks source order, winding, fill rules and nearby boundaries; `tests::build::live_paint_make_and_expand_keep_abutting_compound_colors` checks native compound paths, Make, Expand and Undo/Redo. This preserves VectorCraft's source-fill rule without changing arrangement precision.
Object › Live Paint › Expand keeps the faces and edges that draw on the canvas, with all their fill and stroke rows, so the expanded paths look as the painted group did ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)). As VectorCraft's own rule, a face or edge draws when it is shown, its opacity is above 0, and any of its fill or stroke rows is shown, has paint and an opacity above 0 (a stroke also needs a weight above 0), whichever row is on top: a painted lower row under an unpainted top row is kept, and a part whose only painted row is hidden is removed. Merge copies the fill and stroke rows, visibility, opacity and blending mode of each face that draws by this rule, and of each edge, to the rebuilt parts, with their gradients kept at their fit on the old outline and without the strokes' pen pressure, tilt, bearing and rotation. Evidence: `tests::build::{live_paint_expand_keeps_the_faces_and_edges_that_draw, live_paint_merge_carries_the_faces_that_draw, live_paint_merge_leaves_pen_pressure_behind, live_paint_merge_keeps_the_fit_of_carried_gradients, live_paint_merge_keeps_the_visibility_opacity_and_blending_of_carried_parts}`.
@@ -1823,6 +1827,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- 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).
- TIFFs that store each channel as its own plane (PlanarConfiguration 2) place, relink and open as the same image stored pixel by pixel does, 8 and 16 bits: grayscale with an alpha channel or other extra channels, and CMYK with or without them. A planar CMYK TIFF keeps its ink amounts and is stored as a CMYK TIFF with each pixel's inks together, at the file's resolution. A TIFF whose header claims more strips or tiles than can be counted is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`).
- A 16-bit CMYK or grayscale TIFF with an alpha channel is converted from its 16-bit samples, and only the resulting color and alpha are rounded to 8 bits; associated alpha is divided out at 16 bits, and a pixel whose associated alpha is zero has no color. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives extra samples the depth in BitsPerSample, and its Associated Alpha Handling section states the arithmetic and the zero-alpha rule for RGB data; applying them to CMYK and gray samples is VectorCraft's own rule. Each sample was cut to its high byte first, so a faint ink or a low alpha could be lost (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`).
+ - A CMYK or grayscale TIFF whose alpha channel comes after another extra channel places and opens with that alpha, 8 and 16 bits, chunky or planar, and the other extra channels are left out. A channel that the file does not mark as alpha is not read as transparency, even when its ExtraSamples tag has fewer values than the file has extra channels. A CMYK TIFF with two or more extra channels past its ExtraSamples values, or with no ExtraSamples tag, opens opaque when none of them is marked as alpha, and a white-is-zero grayscale TIFF with an alpha channel opens too. A document saved with such a CMYK TIFF as a CMYK image keeps it as one, with its ink amounts. Such a TIFF is read when its samples take more than 256 MiB, as long as its samples, the copy a planar file needs, the row the decoder reads each strip or tile into and the RGBA pixels together fit the decoding allowance; a TIFF whose SamplesPerPixel is more than 64 is not read, which is VectorCraft's own limit, and both checks run on the file's tags before any decoding. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives each extra channel its own ExtraSamples value, in order (pp. 31–32), and tells readers to skip extra channels they do not use (p. 27); reading the first channel marked as alpha is VectorCraft's own rule (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`).
- 1-bit TIFFs compressed with CCITT Group 3 (ITU-T T.4) place, relink and open: Compression 2 (modified Huffman) and Compression 3 with one-dimensional rows or, with T4Options bit 0, two-dimensional ones, with or without fill bits, in strips or tiles, with either FillOrder and either polarity. Rows in T.4's uncompressed mode are not read. A file whose pixels would take more than the decoding allowance as RGBA is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`).
- EPS and PostScript import keeps a CMYK image's ink amounts, as PDF import does: the samples of `image` and `colorimage` in a CMYK color space, and of a CMYK JPEG read through `DCTDecode`, come in as a CMYK TIFF, read through the image's Decode array, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask (`crates/eps/src/import/tests_images.rs`). Such images came in as RGB PNGs.
- EPS and PostScript import reads image data through `CCITTFaxDecode`: Group 4 (ITU-T T.6) and Group 3 one-dimensional and mixed (ITU-T T.4) data, with the filter's `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1` parameters, decodes to 1-bit rows for `image` and `imagemask`. Damaged data keeps the rows decoded before it (damage in the first row is a PostScript `ioerror`), and parameters out of range or past the 256 MiB limit on decoded data are refused (`crates/eps/src/import/tests_images.rs`). Reading such a file stopped at an error naming the filter, and the file opened from a fallback, such as its preview or the art drawn before the image, or did not open.
@@ -1864,7 +1869,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- SVG import shows a raster `` whose EXIF orientation or TIFF Orientation tag turns or flips it upright, linked or as a data URL, and inside an SVG shown as an image: the pixels are stored turned, the width and height swap, and the `` box fits the turned image under `preserveAspectRatio`, as CSS `image-orientation: from-image` describes (). A turned CMYK JPEG or TIFF keeps its inks as a CMYK TIFF, as does a CMYK TIFF that is not turned. TIFF data URLs (`image/tiff`, or untyped TIFF bytes) are read, and TIFFs with an alpha or other extra channel, CCITT Group 3 TIFFs and CMYK TIFFs stored one plane per ink are read as Open and Place read them. The pixels are decoded within the decode allowance, and a TIFF claiming more strips or tiles than the decoder can count is refused before it is decoded (`crates/svg/tests/it/image_orientation.rs`).
- An image that SVG import stores again, as PNG or as a CMYK TIFF, keeps the resolution its PNG, JPEG, TIFF, WebP or BMP file declares, as Open and Place keep it: in a PNG `pHYs` chunk () or the TIFF's resolution tags, with the horizontal and vertical values swapped when the image turns a quarter. An image that declares no resolution is stored without one (`a_turned_raster_keeps_its_resolution`, `an_upright_tiff_keeps_its_resolution` and `a_cmyk_tiff_keeps_its_resolution_turned_or_not` in `crates/svg/tests/it/image_orientation.rs`).
- SVG import leaves out an SVG shown as an image that it can't read (text that isn't XML, an SVG without a size) and goes on with the images after it, as SVG 2's error processing describes (). Only images that decode count toward the 256 nested SVG images an SVG may show, so an image after many broken ones is imported. Every nested SVG image read, decoded or not, counts toward VectorCraft's own limits of 1,024 reads and 512 MB of text per import; past them, nested SVG images are left out with a warning (`crates/svg/tests/it/import_details.rs`).
- - SVG import measures what an SVG expands to before the SVG reader builds it: every copy a `` shows (), chains of ``s included, and the style values each copy gets from its `style` attribute and from the style sheet rules that match it. An SVG that expands to more than 999,999 elements (500,000 on the web) or to more than 64 MB of copied style values is refused with an error, and so is a loop of `` references that would be copied without end; both limits are VectorCraft's own. An SVG shown as an image counts toward the same 64 MB as the SVG showing it, and one past either limit refuses the whole import (`crates/svg/src/import/budget.rs`, `crates/svg/tests/it/import_details.rs`).
+ - SVG import measures what an SVG expands to before the SVG reader builds it: every copy a `` shows (), chains of ``s included, and the style values each copy gets from its `style` attribute and from the style sheet rules that match it. An SVG that expands to more than 999,999 elements (500,000 on the web) or to more than 64 MB of copied style values is refused with an error, and so is a loop of `` references that would be copied without end. The declarations the import's own style cascade keeps count toward the 64 MB too, once for each element a rule matches, including those of rules the reader drops, such as ones with `:not()`. Matching the style sheets' selectors against those elements may take at most 50,000,000 tests; past that the SVG is refused, so a selector that never matches can't keep the import busy. These limits are VectorCraft's own. An SVG shown as an image, from a data URL or a linked SVG file, counts toward the same limits as the SVG showing it, and one past any of them refuses the whole import (`crates/svg/src/import/budget.rs`, `crates/svg/tests/it/import_details.rs`).
- SVG import reads the files that a linked SVG file's own `` elements link to, relative paths from that file's folder (), as it reads the imported SVG's links: a raster stays linked, an SVG file imports as vector art, and one that can't be read gets the placeholder, its link and a warning. SVG 2 tells a viewer not to load these links (); reading them is VectorCraft's own rule. The same href in SVG files of two folders names two files. A link that leads back to an SVG file showing it gets the placeholder and a warning, and reading the links of linked SVG files stops at the nesting depth cap and at 1,024 reads and 512 MB per import, the same limits decoded nested SVG images have, counted separately from them. The text of every linked SVG file read counts, and so does every file read for the links of a linked SVG file, raster or SVG; rasters the imported SVG links to don't. Once either limit is passed, no file linked from a linked SVG file is read and its image is left out with a warning, and an SVG file the imported SVG links to is still shown, without the files its own links name, with a warning. Another href to an SVG file already read, spelled differently or in another SVG file, does not read it again, unless a link back or the depth cap changes what it shows there (`crates/svg/tests/it/import_details.rs`, `crates/svg/src/import/files.rs`).
- File › Place and a file dropped on the canvas refuse a PNG, JPEG, GIF or WebP file whose pixels can't be read, such as one cut short by a download or a sync still running, and the status bar shows "Couldn't place : the image's pixels can't be read". Paste and Relink refuse such an image too, and Update Links, or Open when it reads the file again, counts it as missing. A JPEG cut short still places when its pixels can be decoded (`file.place`, `crates/engine/src/tests_place.rs`).
- On the desktop, Copy and Cut make the system clipboard's formats (text, SVG, PDF, PNG) from a copy of the clipboard on the thread that writes background saves and exports, and write them when they are ready; while that thread has a save, an export, a print or a recovery copy to finish, they are made and written at once. Until they are written, Paste in VectorCraft takes the internal clipboard, and while a text field or the Type tool has the keyboard the app waits for them. Another Copy or Cut, or a copy of text in VectorCraft, drops them.
@@ -1876,6 +1881,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- With Enable Background Export on, an Export for Screens with no folder of its own also writes in the background into the folder its `exportPreset` keeps, with the same progress dialog and Cancel, and the status bar names that folder. When that folder is outside an MCP client's read roots, the reply, its errors and the status bar name it by its own name, as for an export made at once (`dialogs::tests_screens::an_export_into_a_presets_folder_writes_in_the_background`, `fileio::tests_screens::a_prepared_export_into_a_presets_folder_outside_the_read_root_leaves_it_out`). Behavior reference: the help page, https://helpx.adobe.com/illustrator/using/exporting-artwork.html (exports run in the background by default).
- Missing linked files can be looked for in a folder and its subfolders: Find in Folder… in the Linked File Not Found dialog and in the Links panel menu lists the files with each one's name, those with the size and contents saved with the link first, and relinks the files chosen, copying an image's file into the document's folder when asked, without replacing a file there (`links.findFiles`, `links.relink {copy}`). In the Links panel it looks for the selected linked files when any are selected.
- The Links panel's Relink… opens a Relink dialog whose Replace menu picks which links take the new file: Selected Instances (the selected images, as before), All Instances (every image linked to the same file), Missing Links from This Folder (then every other missing link whose file name is in the new file's folder) and Each Link Separately (a file for each selected link in turn). Each relinks as one undo step (`links.relink {scope}`, `ui.relinkDialog`). Relink to Folder… stays as it is.
+ - The Links panel menu's Copy Info ([Links panel](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/links-panel-in-illustrator.html)) copies the selected link's file name to the clipboard (`links.copyInfo`). VectorCraft's own rules: with several rows selected it copies one name per line in the order the panel shows them, an embedded image gives the name its row shows, and the item is off with no row selected.
- Linked files inside symbols, graph designs, patterns and opacity masks are saved with their paths relative to the document, as linked files in the layers are, so they are found after the document and its files move to another folder together; on open each of those links takes the path where its file was found. Update Links, and opening with Update Links: Automatically, read a modified file again for that art too, and saving a document refreshes its placed copies inside symbols and patterns of the other open documents. Evidence: `links_outside_the_layers_find_their_files_after_the_folder_moves`, `update_links_reads_files_again_inside_symbols_patterns_and_masks`, `saving_a_document_refreshes_its_placed_copies_inside_symbols_and_patterns`.
- A linked file that is missing when a moved document is saved keeps the folder its relative path names, instead of a relative path worked out from the out-of-date absolute path, also for a `.ai` file another app wrote (such as `src/`), so the file is found once it is back in that folder. Evidence: `a_missing_link_keeps_its_relative_path_when_the_moved_document_is_saved`, `links_of_an_imported_file_are_found_by_their_relative_folder`, `a_missing_link_of_a_moved_document_keeps_its_relative_place`.
- On Windows, a document opened from a mapped network drive finds its links stored with the share's own path (`\\server\share\…`), as the same document opened from the share does; links on other computers stay missing.
@@ -1997,6 +2003,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Smart Blur modes:** Effect › Blur › Smart Blur… has a Mode menu with Normal, Edge Only and Overlay Edge (`blurMode`: `normal`, `edgeOnly` or `overlayEdge`; an effect saved without it draws as Normal). Edge Only draws the edges in white on black, and Overlay Edge draws them in white over the Normal blur. A pixel is on an edge when one of the pixels the search reads within Radius of it differs from it by more than Threshold in a channel and its channels, alpha included, add up to at least that pixel's. The search reads neighbors as the Normal blur does, kept within Radius, and always the four nearest pixels, so a color step gives a line about as wide as Radius, and at least one pixel wide, on the side with the larger sum (lines on both sides when the sums are equal). The white and the black keep each pixel's coverage. Behavior reference: [Summary of effects](https://helpx.adobe.com/illustrator/using/summary-effects.html).
+- **Radial Blur center:** Effect › Blur › Radial Blur… has a Blur Center box. A press or a drag in the box sets the point the spin or zoom starts from, and the arrow keys move it 1% (10% with Shift). Horizontal and Vertical fields beside the box take the same position in percent. The effect stores the point as `centerX` and `centerY`, from 0 to 1 across and down the object's bounds (0.5 each by default, VectorCraft's own form), so it moves and scales with the object. An effect saved without them draws about the object's center as before, and `effect.apply` and `effect.setParams` refuse a value outside 0 to 1. Tests: `radial_blur_turns_about_its_blur_center` in `crates/effects/src/pixel/tests.rs` and `radial_blur_center_is_stored_drawn_and_checked` in `crates/engine/src/cmd/effectcmd/tests.rs`. Behavior reference: [Summary of effects](https://helpx.adobe.com/illustrator/using/summary-effects.html).
+
- **Dragging objects with raster effects when zoomed in (#2558):** during a drag with a tool on the canvas, the renderer draws filtered content (Gaussian Blur, Feather and the Photoshop-style filters) within 1,000,000 pixels, at a lower resolution where it would need more, unless it can draw the content from an earlier frame's raster. In the desktop app it does the same for drop shadows, outer glows and inner glows. No raster made that way is kept. The frame after the drag renders them as a still frame does, and a dialog's preview, exports and printing render as before. `zoomed_drag_perf` times a drag's frames at 100% to 6400%.
- **Dragging other art over a wide blur (#2558):** an effect raster too large to keep whole (a wide blur, a shadow or glow, or any blur zoomed in) is cropped to what can show in the view, or made at a lower resolution and resampled to the view's pixels, and kept while the view stays the same, so dragging other art over the object draws its effects from the still frame instead of re-rendering them at the drag's lower resolution. A drag stays on the render worker once the worker drew the frame shown, since only that renderer holds the rasters. `tests_viewraster` covers each effect, and `a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame` the canvas on and off the worker. Not yet: a worker frame shows one display frame after the overlays, and the first frame of an interaction can land on the renderer that has not made the rasters yet (follow-up: render every canvas frame on the worker, waiting briefly for fast ones).
- **Opening a heavy document (#4155):** the canvas renders a document's first frame (when it opens, or its tab is chosen) on the render worker, as it renders the frames of a slow document, instead of on the UI thread, where a heavy one froze the window until it was done. The UI thread waits for it up to 16 ms (`FIRST_FRAME_GRACE`), so a light document's art shows in the same frame as before, without a frame of bare paper; otherwise the document's paper and artboards show, the window stays live, and the art shows when it lands. The web build, which has no worker, renders it as before. Measured on an M3 Pro, one run each, from launch with the file: the file of #4155 kept the UI thread busy for 8.7 s at a stretch, now at most 64 ms (its art lands as before, after about 9 s of rendering); a 50,000-path SVG 1.4 s, now 62 ms. `a_documents_first_frame_renders_on_the_worker` and `the_render_worker_waits_for_a_frame_only_as_long_as_asked` (`crates/ui-egui/src/canvas/tests.rs`).