diff --git a/Cargo.lock b/Cargo.lock index f3e85a08a7..32fcfc62ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1043,6 +1043,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-metafile" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2" +dependencies = [ + "encoding_rs", + "image", + "kurbo 0.13.1", + "thiserror 2.0.21", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -6681,6 +6692,7 @@ dependencies = [ name = "vectorcraft-metafile" version = "0.24.1" dependencies = [ + "craft-metafile", "image", "kurbo 0.13.1", "vectorcraft-brush", diff --git a/Cargo.toml b/Cargo.toml index c7856d589e..610e2b462c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,8 @@ craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" } # DXF tags, reader and writer (craft-libs#778, #926, #927). craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" } +# WMF, EMF and EMF+ reader (craft-libs#778). +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" } craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 0b3c59ab7b..0b48f586cd 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -1008,6 +1008,33 @@ pub fn has_brush(n: &Node) -> bool { n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible)) } +/// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest +/// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has +/// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and +/// the exports leave for brush art when they cull. +pub fn reach(n: &Node) -> f64 { + let paints = |i: &AppearanceItem| matches!(i, AppearanceItem::Stroke(s) if s.visible && s.brush.is_some() && !s.paint.is_none()); + if !n.appearance.items.iter().any(paints) { + return 0.0; + } + let w = n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max); + 16.0 * w + 8.0 +} + +/// The largest [`reach`] of `n` and of the objects in it: the members of its groups, layers and +/// live objects. Of a group or layer with a clipping path only the clipping path counts, as the +/// clip keeps its members' brush art inside it. A compound path counts its own strokes only, as +/// it is painted with its own appearance and not its paths'. Symbol art is not looked into +/// ([`vectorcraft_doc::SymbolBoxes::with_brush_art`] measures it). +pub fn reach_within(n: &Node) -> f64 { + let members = match &n.kind { + NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => children.get(..1).unwrap_or_default(), + NodeKind::Compound { .. } => &[], + _ => n.children().map_or(&[][..], |c| &c[..]), + }; + members.iter().map(|c| reach_within(c)).fold(reach(n), f64::max) +} + /// Expand a brushed path: a group of [the path with its fills and unbrushed strokes (if any /// paint remains), the brush art…]. Ids are 0 (the caller re-ids). `None` if not brushed. pub fn expand(doc: &Document, n: &Node) -> Option { 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 8cd3f85a4f..71c6642846 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -56,19 +56,114 @@ fn is_tiff(bytes: &[u8]) -> bool { bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") } -/// The width and height of the first image of TIFF `bytes` when it has more strips or tiles than -/// the `tiff` decoder can count: strips per plane times planes past `u32::MAX`, or tiles per plane -/// times planes past `usize::MAX`. A file that stores one plane per channel (PlanarConfiguration 2) -/// has a plane for each channel; other files have one. The decoder multiplies these counts without -/// a check, which panics where overflow checks are on. Such an image, when it is at least a pixel -/// wide, claims at least 2^32 samples. -/// Where a tag repeats, the value giving the most strips or tiles counts. `None` for other images +/// What [`jpeg_frames`] found in a JPEG's headers. +enum Frames { + /// Every frame header declares a size the check accepts, or there is none. + Fit, + /// The width and height of the first frame header the check refuses. + Misfit(u16, u16), + /// The steps ran past [`MAX_JPEG_HEADER_STEPS`]. + OverBudget, +} + +/// Checks the width and height each 8-bit baseline, extended or progressive frame header in the +/// headers of a JPEG declares with `fits`. The JPEG is the bytes after its start-of-image marker: +/// `parts[0]` followed by `parts[1]`. The headers are read as the decoder reads them, up to the +/// first start-of-scan or end-of-image marker: every other marker is followed by its segment's +/// length, and bytes between segments are passed over, as are fill bytes (0xFF, and 0x00 after +/// one) before a marker. `steps` counts each byte looked at and each segment passed over. +fn jpeg_frames(parts: [&[u8]; 2], steps: &mut u64, fits: impl Fn(u16, u16) -> bool) -> Frames { + let byte = |i: usize| match i.checked_sub(parts[0].len()) { + None => parts[0].get(i).copied(), + Some(j) => parts[1].get(j).copied(), + }; + let u16_at = |i: usize| Some(u16::from_be_bytes([byte(i)?, byte(i.checked_add(1)?)?])); + let mut p = 0usize; + loop { + *steps += 1; + if *steps > MAX_JPEG_HEADER_STEPS { + return Frames::OverBudget; + } + let Some(b) = byte(p) else { return Frames::Fit }; + p += 1; + if b != 0xFF { + continue; + } + while matches!(byte(p), Some(0xFF | 0)) { + p += 1; + *steps += 1; + if *steps > MAX_JPEG_HEADER_STEPS { + return Frames::OverBudget; + } + } + let Some(marker) = byte(p) else { return Frames::Fit }; + p += 1; + if matches!(marker, 0xDA | 0xD9) { + return Frames::Fit; + } + // Length (2 bytes), then for a frame header its precision, height and width. + let Some(len) = u16_at(p) else { return Frames::Fit }; + if matches!(marker, 0xC0..=0xC2) + && byte(p.saturating_add(2)) == Some(8) + && let (Some(h), Some(w)) = (u16_at(p.saturating_add(3)), u16_at(p.saturating_add(5))) + && !fits(w, h) + { + return Frames::Misfit(w, h); + } + if len < 2 { + return Frames::Fit; + } + p = p.saturating_add(usize::from(len)); + } +} + +/// Most strips or tiles the first image of a TIFF may have: VectorCraft's own limit, 1/1024 of +/// [`crate::MAX_RASTER_ALLOC`] (524,288 in the web app, 2,097,152 on the desktop). The decoder +/// reads an offset and a byte count of 8 bytes each for every one into memory before anything else. +pub const MAX_TIFF_CHUNKS: u64 = crate::MAX_RASTER_ALLOC / 1024; + +/// Most pixels the JPEG of a JPEG-compressed TIFF tile may declare when it declares more pixels +/// than the whole image has: VectorCraft's own limit (2048 × 2048, 16 MB as CMYK). +pub const MAX_JPEG_TILE_PIXELS: u64 = 1 << 22; + +/// Most steps reading the JPEG headers of a TIFF's strips or tiles may take (a byte looked at, a +/// segment passed over or a strip offset read): VectorCraft's own limit. +const MAX_JPEG_HEADER_STEPS: u64 = 1 << 24; + +/// The width and height of the first image of TIFF or BigTIFF `bytes` when it has more strips or +/// tiles than the `tiff` decoder can count: strips per plane times planes past `u32::MAX`, or tiles +/// per plane times planes past `usize::MAX`. A file that stores one plane per channel +/// (PlanarConfiguration 2) has a plane for each channel; other files have one. The decoder +/// multiplies these counts without a check, which panics where overflow checks are on. Such an +/// image, when it is at least a pixel wide, claims at least 2^32 samples. +/// It also gives them for an image with more than [`MAX_TIFF_CHUNKS`] strips or tiles, counted from +/// its size or from the number of values its StripOffsets and StripByteCounts tags hold, or its +/// TileOffsets and TileByteCounts tags for a tiled image. An image the decoder reads as strips (it +/// has both strip tables and neither tile table) counts strips, and one it reads as tiles counts +/// tiles; the decoder refuses an image with any other mix of these tags before it reads a table. +/// For a JPEG-compressed image (Compression 7) it gives the width and height a strip's or tile's +/// JPEG declares in a frame header (in the JPEGTables, or in the strip or tile before its first +/// scan) when they are wider or taller than the strip or tile, or, for a tile, when they make more +/// than [`MAX_JPEG_TILE_PIXELS`] pixels and more than the image has. The decoder allocates the +/// pixels the JPEG declares. It gives the image's width and height when reading those headers +/// takes more than 16,777,216 steps (a byte looked at, a segment passed over or a strip offset +/// read), when the strip or tile offsets are of a type other than BYTE, UNDEFINED, SHORT, LONG, +/// IFD, LONG8 or IFD8, and when the image's width and height, a striped image's RowsPerStrip or a +/// tiled image's tile size isn't a single value of one of those types. +/// Where a tag repeats, the value giving the most strips or tiles counts, and the JPEG check uses +/// the last entry of a field type the decoder knows, as the decoder does. `None` for other images /// and for bytes that aren't a TIFF. pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { - let le = bytes.starts_with(b"II*\0"); - if !le && !bytes.starts_with(b"MM\0*") { + let le = bytes.starts_with(b"II"); + let head = bytes.get(..4)?; + // A BigTIFF counts and points with 8 bytes where a TIFF uses 4, so its entries are 20 bytes. + let big = if head == b"II*\0" || head == b"MM\0*" { + false + } else if head == b"II+\0" || head == b"MM\0+" { + true + } else { return None; - } + }; let u16_at = |at: usize| -> Option { let b: [u8; 2] = bytes.get(at..at.checked_add(2)?)?.try_into().ok()?; Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) @@ -77,32 +172,71 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?; Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) }; - let ifd = usize::try_from(u32_at(4)?).ok()?; - // (tag, the entry's single BYTE, SHORT, LONG or IFD value, which sits in the entry, or its - // single LONG8 or IFD8 value that fits in 32 bits, which sits where the entry points) - let entry = |i: usize| -> Option<(u16, Option)> { - let e = ifd.checked_add(i.checked_mul(12)?.checked_add(2)?)?; - let (ty, count, at) = (u16_at(e.checked_add(2)?)?, u32_at(e.checked_add(4)?)?, e.checked_add(8)?); - let value = match (ty, count) { - (1, 1) => bytes.get(at).map(|&b| u32::from(b)), - (3, 1) => u16_at(at).map(u32::from), - (4 | 13, 1) => u32_at(at), - (16 | 18, 1) => { - let at = usize::try_from(u32_at(at)?).ok()?; - let (lo, hi) = (u32_at(at)?, u32_at(at.checked_add(4)?)?); - let wide = if le { u64::from(hi) << 32 | u64::from(lo) } else { u64::from(lo) << 32 | u64::from(hi) }; - u32::try_from(wide).ok() - } + let u64_at = |at: usize| -> Option { + let b: [u8; 8] = bytes.get(at..at.checked_add(8)?)?.try_into().ok()?; + Some(if le { u64::from_le_bytes(b) } else { u64::from_be_bytes(b) }) + }; + let word_len: usize = if big { 8 } else { 4 }; + let word = |at: usize| if big { u64_at(at) } else { u32_at(at).map(u64::from) }; + // The bytes one value of each field type takes; 0 for types the decoder doesn't know. + let width_of = |ty: u16| -> usize { + match ty { + 1 | 2 | 6 | 7 => 1, + 3 | 8 => 2, + 4 | 9 | 11 | 13 => 4, + 5 | 10 | 12 | 16..=18 => 8, + _ => 0, + } + }; + let ifd = usize::try_from(word(if big { 8 } else { 4 })?).ok()?; + let entries = if big { u64_at(ifd)? } else { u64::from(u16_at(ifd)?) }; + let first = ifd.checked_add(if big { 8 } else { 2 })?; + // (tag, field type, number of values, where the values are: in the entry when they fit in its + // last word, otherwise where that word points) + let entry = |i: usize| -> Option<(u16, u16, u64, Option)> { + let e = first.checked_add(i.checked_mul(4 + 2 * word_len)?)?; + let (tag, ty, count) = (u16_at(e)?, u16_at(e.checked_add(2)?)?, word(e.checked_add(4)?)?); + let at = e.checked_add(4 + word_len)?; + let fits = u64::try_from(width_of(ty)).ok()?.checked_mul(count).is_some_and(|n| n <= word_len as u64); + let values = if fits { Some(at) } else { word(at).and_then(|p| usize::try_from(p).ok()) }; + Some((tag, ty, count, values)) + }; + // Value `i` of an entry's BYTE, UNDEFINED, SHORT, LONG, IFD, LONG8 or IFD8 values at `at`. + let nth = |ty: u16, at: usize, i: u64| -> Option { + let p = at.checked_add(usize::try_from(i).ok()?.checked_mul(width_of(ty))?)?; + match ty { + 1 | 7 => bytes.get(p).map(|&b| u64::from(b)), + 3 => u16_at(p).map(u64::from), + 4 | 13 => u32_at(p).map(u64::from), + 16 | 18 => u64_at(p), _ => None, - }; - Some((u16_at(e)?, value)) + } }; let (mut width, mut height, mut planes, mut planar) = (0u32, 0u32, 1u32, false); let (mut rows, mut tile_w, mut tile_h) = (None::, None::, None::); + // The most values a strip table and a tile table hold. + let (mut strip_chunks, mut tile_chunks) = (0u64, 0u64); + // The decoder keeps the last entry of a tag whose field type it knows. These are the last such + // entries (type, count, where) of the tags `LAST` lists. + const LAST: [u16; 11] = [256, 257, 259, 278, 322, 323, 273, 279, 324, 325, 347]; + let mut last = [None::<(u16, u64, Option)>; LAST.len()]; let least = |was: Option, v: u32| Some(was.map_or(v, |w| w.min(v))); - for i in 0..usize::from(u16_at(ifd)?) { - let Some((tag, value)) = entry(i) else { break }; - let Some(v) = value else { continue }; + // The entry's single BYTE, UNDEFINED, SHORT, LONG or IFD value, or its single LONG8 or IFD8 + // value when that fits in 32 bits. + let single = |ty: u16, count: u64, at: Option| at.filter(|_| count == 1).and_then(|at| nth(ty, at, 0)).and_then(|v| u32::try_from(v).ok()); + for i in 0..usize::try_from(entries).unwrap_or(usize::MAX) { + let Some((tag, ty, count, at)) = entry(i) else { break }; + match tag { + 273 | 279 => strip_chunks = strip_chunks.max(count), + 324 | 325 => tile_chunks = tile_chunks.max(count), + _ => {} + } + if width_of(ty) > 0 + && let Some(slot) = LAST.iter().position(|&t| t == tag).and_then(|k| last.get_mut(k)) + { + *slot = Some((ty, count, at)); + } + let Some(v) = single(ty, count, at) else { continue }; match tag { 256 => width = width.max(v), 257 => height = height.max(v), @@ -115,29 +249,107 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { } } let planes = if planar { u128::from(planes) } else { 1 }; - let tiles = match (tile_w, tile_h) { - (Some(tw @ 1..), Some(th @ 1..)) => u128::from(width.div_ceil(tw)) * u128::from(height.div_ceil(th)) * planes > usize::MAX as u128, - _ => false, + let tiled = match (tile_w, tile_h) { + (Some(tw @ 1..), Some(th @ 1..)) => u128::from(width.div_ceil(tw)) * u128::from(height.div_ceil(th)) * planes, + _ => 0, }; + let tiles = tiled > usize::MAX as u128; let rows = rows.unwrap_or(height); - let strips = rows > 0 && u128::from(height.saturating_sub(1) / rows + 1) * planes > u128::from(u32::MAX); - (tiles || strips).then_some((width, height)) + let striped = height.saturating_sub(1).checked_div(rows).map_or(0, |n| u128::from(n + 1) * planes); + let strips = striped > u128::from(u32::MAX); + if tiles || strips { + return Some((width, height)); + } + let last_of = |tag: u16| LAST.iter().position(|&t| t == tag).and_then(|k| last.get(k).copied().flatten()); + // The single value the decoder reads from the last entry of `tag`: `None` without one, and + // `Some(None)` when that entry doesn't hold a single value read here. + let value_of = |tag: u16| last_of(tag).map(|(ty, count, at)| single(ty, count, at)); + // The decoder reads strips when the image has both strip tables and neither tile table, tiles + // in the opposite case, and refuses every other image before it reads a table. + let layout = match [273, 279, 324, 325].map(|tag| last_of(tag).is_some()) { + [true, true, false, false] => Some((273, striped.max(u128::from(strip_chunks)))), + [false, false, true, true] => Some((324, tiled.max(u128::from(tile_chunks)))), + _ => None, + }; + let (offsets_tag, chunks) = layout?; + if chunks > u128::from(MAX_TIFF_CHUNKS) { + return Some((width, height)); + } + if value_of(259) != Some(Some(7)) { + return None; + } + // The JPEG check uses the sizes the decoder reads. A size it needs that isn't a single value + // read here refuses the image. + let (Some(Some(w_img)), Some(Some(h_img))) = (value_of(256), value_of(257)) else { return Some((width, height)) }; + let tile = offsets_tag == 324; + // RowsPerStrip, which the decoder reads only for strips. + let rows = if tile { Some(h_img) } else { value_of(278).unwrap_or(Some(h_img)) }; + let Some(rows) = rows else { return Some((width, height)) }; + let (tw, th) = match (value_of(322).flatten(), value_of(323).flatten()) { + (Some(tw), Some(th)) => (tw, th), + _ if tile => return Some((width, height)), + _ => (0, 0), + }; + // A strip is as wide as the image and RowsPerStrip tall (at most the image's height); a tile's + // JPEG may be as large as the tile, which the edge tiles of the image overhang. + let fits = |w: u16, h: u16| { + let (w, h) = (u32::from(w), u32::from(h)); + if tile { + let pixels = u64::from(w) * u64::from(h); + w <= tw && h <= th && (pixels <= MAX_JPEG_TILE_PIXELS || pixels <= u64::from(w_img) * u64::from(h_img)) + } else { + w <= w_img && h <= rows.min(h_img) + } + }; + // The decoder reads the JPEGTables after their start-of-image marker and without their last two + // bytes, followed by each strip or tile after its first two bytes; without JPEGTables, each + // strip or tile after its start-of-image marker. + let tables = last_of(347) + .and_then(|(_, count, at)| { + let at = at?; + let end = at.checked_add(usize::try_from(count).ok()?)?.min(bytes.len()); + bytes.get(at.checked_add(2)?..end.checked_sub(2)?) + }) + .unwrap_or_default(); + let (ty, count, at) = last_of(offsets_tag)?; + let at = at?; + // The decoder also takes offsets of other types (a RATIONAL or ASCII value), which aren't read + // here: such an image is refused. + if !matches!(ty, 1 | 3 | 4 | 7 | 13 | 16 | 18) { + return Some((width, height)); + } + let mut steps = 0u64; + for i in 0..count { + steps += 1; + let Some(at) = nth(ty, at, i).and_then(|o| usize::try_from(o).ok()) else { break }; + let part = bytes.get(at.saturating_add(2)..).unwrap_or_default(); + match jpeg_frames([tables, part], &mut steps, fits) { + Frames::Fit => {} + Frames::Misfit(w, h) => return Some((u32::from(w), u32::from(h))), + Frames::OverBudget => return Some((width, height)), + } + } + None +} + +/// The 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; + } + 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>)> { - if !is_tiff(bytes) || oversized_tiff(bytes).is_some() { - return None; - } - let mut d = tiff::decoder::Decoder::new(Cursor::new(bytes)).ok()?; + 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 @@ -155,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) } @@ -164,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, @@ -196,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 { @@ -207,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; @@ -219,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 @@ -265,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()?; @@ -479,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()?; @@ -493,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)?; @@ -508,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. @@ -527,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), @@ -564,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, } }; @@ -875,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] @@ -891,7 +1690,7 @@ mod tests { f }; assert_eq!(oversized_tiff(&header(2)), Some((u32::MAX, u32::MAX))); - assert_eq!(oversized_tiff(&header(1)), None, "one plane: (2^32 − 1)² tiles can be counted in 64 bits"); + assert_eq!(oversized_tiff(&header(1)), Some((u32::MAX, u32::MAX)), "one plane: countable, but past MAX_TIFF_CHUNKS"); assert!(tiff(&header(2)).is_none(), "not decoded"); } @@ -933,6 +1732,227 @@ mod tests { } } + /// A little-endian TIFF, or BigTIFF when `big`, holding `data` right after its header (from + /// byte 8, or 16 in a BigTIFF), then one directory of `entries` (tag, field type, values). An + /// entry's values sit in the entry when they fit, otherwise after the directory. + fn tiff_file(big: bool, entries: &[(u16, u16, Vec)], data: &[u8]) -> Vec { + let (word, head) = if big { (8, 16) } else { (4, 8) }; + let put = |f: &mut Vec, v: u64, n: usize| f.extend(&v.to_le_bytes()[..n]); + let mut f = if big { b"II+\0\x08\0\0\0".to_vec() } else { b"II*\0".to_vec() }; + let ifd = head + data.len(); + put(&mut f, ifd as u64, word); + f.extend(data); + put(&mut f, entries.len() as u64, if big { 8 } else { 2 }); + let after = f.len() + entries.len() * (4 + 2 * word) + word; + let mut tail = vec![]; + for (tag, ty, values) in entries { + let width = match ty { + 1 | 7 => 1, + 3 => 2, + 4 => 4, + _ => 8, + }; + f.extend([tag.to_le_bytes(), ty.to_le_bytes()].concat()); + put(&mut f, values.len() as u64, word); + let mut v = vec![]; + for &x in values { + put(&mut v, x, width); + } + if v.len() <= word { + v.resize(word, 0); + f.extend(v); + } else { + put(&mut f, (after + tail.len()) as u64, word); + tail.extend(v); + } + } + put(&mut f, 0, word); + f.extend(tail); + f + } + + /// A JPEG of four components whose progressive frame header declares `w` × `h` pixels, with a + /// scan header and no scan data. + fn jpeg_header(w: u16, h: u16) -> Vec { + let mut j = vec![0xFF, 0xD8, 0xFF, 0xC2, 0, 20, 8]; + j.extend(h.to_be_bytes()); + j.extend(w.to_be_bytes()); + j.push(4); + for id in 1..=4 { + j.extend([id, 0x11, 0]); + } + j.extend([0xFF, 0xDA, 0, 14, 4, 1, 0, 2, 0, 3, 0, 4, 0, 0, 63, 0, 0xFF, 0xD9]); + j + } + + /// The directory of a 1 × 1 CMYK image with alpha, JPEG-compressed in one strip of `len` bytes + /// at byte `at`. + fn jpeg_strip_entries(at: u64, len: u64) -> Vec<(u16, u16, Vec)> { + vec![ + (256, 4, vec![1]), + (257, 4, vec![1]), + (258, 3, vec![8; 5]), + (259, 3, vec![7]), + (262, 3, vec![5]), + (273, 4, vec![at]), + (277, 3, vec![5]), + (278, 4, vec![1]), + (279, 4, vec![len]), + (338, 3, vec![2]), + ] + } + + /// A strip's JPEG that declares more pixels than the strip holds would have the decoder + /// allocate them: a 1 × 1 image whose JPEG claims 16384 × 16384 is refused before any decoder + /// opens it, in a TIFF or a BigTIFF, with fill bytes or other bytes before the frame header, + /// and with the frame header in the JPEGTables. + #[test] + fn a_jpeg_strip_declaring_more_than_its_strip_is_refused() { + let big = jpeg_header(16384, 16384); + let file = tiff_file(false, &jpeg_strip_entries(8, big.len() as u64), &big); + assert_eq!(oversized_tiff(&file), Some((16384, 16384))); + assert!(tiff(&file).is_none(), "not decoded"); + let bigtiff = tiff_file(true, &jpeg_strip_entries(16, big.len() as u64), &big); + assert_eq!(oversized_tiff(&bigtiff), Some((16384, 16384)), "BigTIFF"); + // The decoder reads the last ImageWidth and ImageLength: 1 × 1 after 16384 × 16384, in one + // strip without RowsPerStrip. + let mut entries = jpeg_strip_entries(8, big.len() as u64); + entries.retain(|e| e.0 != 278); + entries.splice(0..0, [(256, 4, vec![16384]), (257, 4, vec![16384])]); + assert_eq!(oversized_tiff(&tiff_file(false, &entries, &big)), Some((16384, 16384)), "repeated sizes"); + // StripOffsets as a BYTE, which the decoder reads, and as a RATIONAL, which it reads as two + // offsets. + for (ty, expected) in [(1, (16384, 16384)), (5, (1, 1))] { + let mut entries = jpeg_strip_entries(8, big.len() as u64); + for e in &mut entries { + if e.0 == 273 { + e.1 = ty; + } + } + assert_eq!(oversized_tiff(&tiff_file(false, &entries, &big)), Some(expected), "StripOffsets of type {ty}"); + } + let one = jpeg_header(1, 1); + assert_eq!(oversized_tiff(&tiff_file(false, &jpeg_strip_entries(8, one.len() as u64), &one)), None, "a JPEG as large as its strip"); + let wide = jpeg_header(2, 1); + assert_eq!(oversized_tiff(&tiff_file(false, &jpeg_strip_entries(8, wide.len() as u64), &wide)), Some((2, 1)), "one pixel too wide"); + for (what, prefix) in [("fill bytes", &[0xFF, 0x00, 0xFF][..]), ("other bytes", &[0x12, 0x34][..])] { + let mut j = big[..2].to_vec(); + j.extend(prefix); + j.extend(&big[2..]); + let file = tiff_file(false, &jpeg_strip_entries(8, j.len() as u64), &j); + assert_eq!(oversized_tiff(&file), Some((16384, 16384)), "{what} before the frame header"); + } + // The JPEGTables hold the frame header; the strip holds only the scan. + let tables = [&big[..24], &[0xFF, 0xD9][..]].concat(); + let scan = [&[0xFF, 0xD8][..], &big[24..]].concat(); + let mut entries = jpeg_strip_entries(8 + tables.len() as u64, scan.len() as u64); + entries.push((347, 7, tables.iter().map(|&b| u64::from(b)).collect())); + let file = tiff_file(false, &entries, &[tables, scan].concat()); + assert_eq!(oversized_tiff(&file), Some((16384, 16384)), "frame header in the JPEGTables"); + // An encoder's 8 × 8 RGB JPEG, with its own segments before the frame header, in an + // 8 × 8 image of one strip, and of strips 4 rows tall. + let mut real = Vec::new(); + image::codecs::jpeg::JpegEncoder::new(&mut real).encode(&[90; 8 * 8 * 3], 8, 8, image::ExtendedColorType::Rgb8).unwrap(); + let rgb = |rows: u64| { + let entries = [ + (256, 4, vec![8]), + (257, 4, vec![8]), + (258, 3, vec![8; 3]), + (259, 3, vec![7]), + (262, 3, vec![2]), + (273, 4, vec![8]), + (277, 3, vec![3]), + (278, 4, vec![rows]), + (279, 4, vec![real.len() as u64]), + ]; + oversized_tiff(&tiff_file(false, &entries, &real)) + }; + assert_eq!(rgb(8), None, "an encoder's JPEG as large as its strip"); + assert_eq!(rgb(4), Some((8, 8)), "an encoder's JPEG taller than its strip"); + } + + /// A tile's JPEG may be as large as the tile, which overhangs the image, and when it is more + /// than MAX_JPEG_TILE_PIXELS, no larger than the image. + #[test] + fn a_jpeg_tile_declaring_more_than_its_tile_is_refused() { + let tiled_with = |tile: u64, j: &[u8], rows: Vec| { + let mut entries: Vec<_> = jpeg_strip_entries(0, 0).into_iter().filter(|e| !matches!(e.0, 273 | 278 | 279)).collect(); + if !rows.is_empty() { + entries.push((278, 4, rows)); + } + entries.extend([(322, 4, vec![tile]), (323, 4, vec![tile]), (324, 4, vec![8]), (325, 4, vec![j.len() as u64])]); + oversized_tiff(&tiff_file(false, &entries, j)) + }; + let tiled = |tile: u64, j: &[u8]| tiled_with(tile, j, vec![]); + assert_eq!(tiled_with(16, &jpeg_header(16, 16), vec![1, 1]), None, "RowsPerStrip, unread in a tiled image"); + assert_eq!(tiled(16, &jpeg_header(16, 16)), None, "as large as the tile"); + assert_eq!(tiled(16, &jpeg_header(17, 16)), Some((17, 16)), "wider than the tile"); + assert_eq!(tiled(16, &jpeg_header(16, 17)), Some((16, 17)), "taller than the tile"); + assert_eq!(tiled(4096, &jpeg_header(2048, 2048)), None, "MAX_JPEG_TILE_PIXELS"); + assert_eq!(tiled(4096, &jpeg_header(2048, 2049)), Some((2048, 2049)), "past MAX_JPEG_TILE_PIXELS and the image"); + } + + /// The decoder reads every strip's offset and byte count before anything else: an image with + /// more than MAX_TIFF_CHUNKS strips, counted from its size or from its tables, is refused. + #[test] + fn tiffs_with_more_strips_than_their_tables_may_hold_are_refused() { + let file = |height: u64, count: u32| { + let entries = [ + (256, 4, vec![1]), + (257, 4, vec![height]), + (258, 3, vec![8]), + (262, 3, vec![1]), + (273, 4, vec![8]), + (278, 4, vec![1]), + (279, 4, vec![1]), + ]; + let mut f = tiff_file(false, &entries, &[0]); + // StripOffsets' count, its values left out of the file. + let at = 8 + 1 + 2 + 4 * 12 + 4; + f[at..at + 4].copy_from_slice(&count.to_le_bytes()); + f + }; + let most = MAX_TIFF_CHUNKS; + assert_eq!(oversized_tiff(&file(most, 1)), None, "MAX_TIFF_CHUNKS rows of a strip each"); + assert_eq!(oversized_tiff(&file(most + 1, 1)), Some((1, u32::try_from(most + 1).unwrap())), "one strip more"); + assert_eq!(oversized_tiff(&file(1, u32::try_from(most).unwrap())), None, "MAX_TIFF_CHUNKS offsets"); + assert_eq!(oversized_tiff(&file(1, u32::try_from(most + 1).unwrap())), Some((1, 1)), "one offset more"); + assert!(tiff(&file(1, 1 << 25)).is_none(), "not decoded"); + // Tile sizes without tile tables: the decoder reads the strips and never counts the + // 4,194,304 tiles of a pixel the sizes give. + let strips_with_tile_sizes = |offsets: Option| { + let mut entries = vec![ + (256, 4, vec![2048]), + (257, 4, vec![2048]), + (258, 3, vec![8]), + (262, 3, vec![1]), + (273, 4, vec![8]), + (279, 4, vec![2048 * 2048]), + (322, 4, vec![1]), + (323, 4, vec![1]), + ]; + entries.extend(offsets.map(|tag| (tag, 4, vec![8]))); + entries.sort_by_key(|e| e.0); + oversized_tiff(&tiff_file(false, &entries, &[0])) + }; + assert_eq!(strips_with_tile_sizes(None), None, "a strip image with tile sizes of one pixel"); + assert_eq!(strips_with_tile_sizes(Some(324)), None, "strip and tile tables: the decoder refuses it unread"); + } + + /// Strips whose JPEG headers take more than MAX_JPEG_HEADER_STEPS steps to read refuse the + /// file: here every strip points at the same 1 MB without a marker. + #[test] + fn jpeg_strips_that_take_too_long_to_read_are_refused() { + let file = |strips: u64| { + let mut entries = jpeg_strip_entries(0, 0); + entries.retain(|e| !matches!(e.0, 257 | 273 | 279)); + entries.extend([(257, 4, vec![strips]), (273, 4, vec![8; strips as usize]), (279, 4, vec![1 << 20; strips as usize])]); + tiff_file(false, &entries, &std::iter::repeat_n(0, 1 << 20).collect::>()) + }; + assert_eq!(oversized_tiff(&file(8)), None, "about 8 million steps"); + assert_eq!(oversized_tiff(&file(17)), Some((1, 17)), "about 17 million steps"); + } + fn inks() -> Inks { Inks::new(3, 2, vec![0, 40, 100, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 12, 34, 56, 78]).unwrap() } diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index e9507d25a8..58b52dd651 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -543,7 +543,7 @@ pub struct GraphSpec { /// Bounds of the art when it was last generated (detects moves/scales of the graph group). #[serde(skip_serializing_if = "Option::is_none")] pub placed: Option, - /// Bounds of the art other than type when it was last generated ([`art_bounds`]). Moves and scales of the graph + /// Bounds of the art other than type when it was last generated ([`graph_art_without_type`]). Moves and scales of the graph /// group are measured on these when present; graphs saved without them are measured on [`Self::placed`]. #[serde(skip_serializing_if = "Option::is_none")] pub placed_art: Option, @@ -562,6 +562,43 @@ fn edge_to_edge_before_the_option() -> bool { true } +/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend +/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these. +pub fn graph_art_without_type(children: &[std::sync::Arc]) -> Option { + children.iter().filter_map(|c| without_type(c).0).reduce(|a, b| a.union(b)) +} + +/// The geometric bounds of `n` leaving out the type in it, and whether its own geometric bounds depend on that type. A +/// group without such type gives its own bounds, and a clipping group whose clip does not depend on type gives the +/// bounds of its clip. Objects other than groups, layers and compound paths, blends, envelopes and repeats among them, +/// give their own bounds. +fn without_type(n: &crate::Node) -> (Option, bool) { + use crate::NodeKind::{Compound, Group, Layer, Text}; + if matches!(n.kind, Text(_)) { + return (None, true); + } + let children: &[std::sync::Arc] = match &n.kind { + Group { clip: true, children } | Layer { clip: true, children, .. } => children, + Group { .. } | Layer { .. } | Compound { .. } => n.editing_children(), + _ => return (n.geometric_bounds(), false), + }; + let mut bounds: Option = None; + let mut had_type = false; + let mut clip_has_type = false; + let hidden_layer_member = |c: &crate::Node| !c.visible && matches!(n.kind, Layer { clip: false, .. }); + for (i, c) in children.iter().enumerate().filter(|(_, c)| !hidden_layer_member(c)) { + let (b, t) = without_type(c); + had_type |= t; + clip_has_type |= i == 0 && t; + bounds = match (bounds, b) { + (Some(a), Some(b)) => Some(a.union(b)), + (a, b) => a.or(b), + }; + } + let clip = matches!(n.kind, Group { clip: true, .. } | Layer { clip: true, .. }); + if had_type && (!clip || clip_has_type) { (bounds, true) } else { (n.geometric_bounds(), false) } +} + impl GraphSpec { /// The type series `s` is drawn as: its own type when it combines with the graph's, else the graph's. pub fn series_kind(&self, s: usize) -> GraphKind { @@ -630,32 +667,6 @@ impl GraphSpec { } } -/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend -/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these. -pub fn art_bounds(children: &[std::sync::Arc]) -> Option { - children.iter().filter_map(|c| art_bounds_of(c).0).reduce(|a, b| a.union(b)) -} - -/// The geometric bounds of `n` leaving out the type in it, and whether there was type to leave out. A group without type -/// gives its own bounds, so a clipping group gives the bounds of its clip. -fn art_bounds_of(n: &crate::Node) -> (Option, bool) { - if matches!(n.kind, crate::NodeKind::Text(_)) { - return (None, true); - } - let Some(children) = n.children() else { return (n.geometric_bounds(), false) }; - let mut bounds: Option = None; - let mut had_type = false; - for c in children { - let (b, t) = art_bounds_of(c); - had_type |= t; - bounds = match (bounds, b) { - (Some(a), Some(b)) => Some(a.union(b)), - (a, b) => a.or(b), - }; - } - if had_type { (bounds, true) } else { (n.geometric_bounds(), false) } -} - impl Default for GraphSpec { fn default() -> Self { Self { diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 93b690ccf8..5885a0ff54 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1,7 +1,7 @@ //! Hit testing over the document tree. use std::cell::RefCell; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::sync::{Arc, OnceLock}; @@ -279,13 +279,16 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: & return false; } // How a click reaches it, if one does. + let start = opt; let Some(opt) = path_options(&nodes, &chain, opt) else { return false }; - // Hidden by a mask: one of the containers around it clips, and not to `p`. - let masked = nodes - .iter() - .rev() - .skip(1) - .any(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p))); + // Hidden by a mask: one of the containers around it clips, and not to `p`. A container + // tests its clipping path in outline from the first layer with Preview off down to it, as + // a click going down to it does ([`path_options`]). + let below = start.scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1); + let masked = nodes.iter().enumerate().rev().skip(1).any(|(k, n)| { + let outline = start.outline || nodes.get(below..=k).is_some_and(|ns| ns.iter().any(|n| previews_off(n))); + n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p, outline)) + }); // A click may reach it there ([`may_hit`]: not a guide while guides are locked or // hidden, nor a Shaper group's hidden part), and its own art is what a click would hit // in it: a group's hidden, locked or masked contents don't count. @@ -359,6 +362,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option, seen: &mut HashSet) -> bool { let Some(children) = layer.children() else { return true }; + let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; if layer.clips() && let Some(clip) = children.first() { @@ -366,11 +370,10 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox if clip_outline_hit(layer, clip, p, opt, symbols, true).is_some() && seen.insert(clip.id) { tops.push(clip.id); } - if !clip_contains(clip, p) { + if !clip_contains(clip, p, opt.outline) { return true; } } - let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; for (i, c) in children.iter().enumerate().rev() { if !may_hit(layer, i, c, p, opt, symbols, true) || seen.contains(&c.id) { continue; @@ -452,7 +455,7 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec) { let Some(children) = parent.children() else { return }; - if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p)) { + if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) { return; } for i in hit_order(parent, children, p) { @@ -561,14 +564,170 @@ fn edits_contents(n: &Node) -> bool { matches!(n.kind, NodeKind::Envelope { editing: true, .. }) } -/// Is `p` inside the region `clip` clips to ([`Node::clip_shapes`])? Text counts by its frame: -/// glyph outlines need the font engine, above this crate. -fn clip_contains(clip: &Node, p: Point) -> bool { - clip_regions(clip).iter().any(|(bp, rule)| fill_contains(bp, *rule, p)) +/// Is `p` inside the region `clip` clips to ([`clip_areas`])? In outline mode ([`HitOptions::outline`]) +/// the canvas draws no effects, so the plain shapes of `clip` ([`clip_regions`]) count. +fn clip_contains(clip: &Node, p: Point, outline: bool) -> bool { + let areas = if outline { clip_regions(clip) } else { clip_areas(clip) }; + areas.iter().any(|(bp, rule)| fill_contains(bp, *rule, p)) } -/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in -/// [`clip_contains`]. +/// The region of a clip group's clipping path as the canvas clips by it, with the live geometry +/// effects of the clipping path and of what it clips by applied, as one path and fill rule +/// (`Some(None)` when nothing is left to clip by). `None` when nothing in the clipping path has a +/// live geometry effect: its plain shapes ([`clip_regions`]) count then. Effects are evaluated +/// above this crate, so the engine registers one with [`set_clip_region`]. +pub type ClipRegion = fn(&Node) -> Option>; + +static CLIP_REGION: OnceLock = OnceLock::new(); + +/// Register how the region of a clipping path with live effects is found (the first registration +/// stays). +pub fn set_clip_region(f: ClipRegion) { + // Already set: the same engine, registered by another session. + let _ = CLIP_REGION.set(f); +} + +/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only +/// then can the registered [`ClipRegion`] find a geometry effect in it. +fn has_effects(clip: &Node) -> bool { + let mut found = false; + clip.walk(&mut |n| { + let visible = |e: &crate::Effect| e.visible; + found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible)); + }); + found +} + +/// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the +/// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its +/// path elements. +struct EvaluatedClip { + clip: Node, + inputs: u64, + region: Option>>, + size: usize, +} + +/// How many regions [`clip_region`] keeps on each thread: every click and every hover over a clip +/// group whose clipping path has live effects asks for its region, and clip groups can be nested. +const CLIPS_KEPT: usize = 16; + +thread_local! { + /// The regions [`clip_region`] keeps, the latest first. + static CLIPS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +thread_local! { + /// How many regions [`clip_region`] evaluated on this thread. + static CLIPS_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The region clipping path `clip` clips to with its live geometry effects applied +/// ([`set_clip_region`]), or `None` when it has none or nothing is registered; its plain shapes +/// ([`clip_regions`]) are the region then. The region is evaluated again when `clip` or the +/// [`LiveInputs`] have changed since. +fn clip_region(clip: &Node) -> Option>> { + let f = CLIP_REGION.get()?; + if !has_effects(clip) { + return None; + } + let inputs = live_inputs(); + let kept = CLIPS.with_borrow_mut(|kept| { + let i = kept.iter().position(|e| e.inputs == inputs && e.clip == *clip)?; + let e = kept.remove(i); + let region = e.region.clone(); + kept.insert(0, e); + Some(region) + }); + if let Some(region) = kept { + return region; + } + #[cfg(test)] + CLIPS_EVALUATED.with(|c| c.set(c.get() + 1)); + let region = f(clip).map(Rc::new); + let elements = region.as_deref().and_then(Option::as_ref).map_or(0, |(bp, _)| bp.elements().len()); + let size = elements.saturating_add(art_size(std::slice::from_ref(clip))); + if size <= LIVE_KEPT_SIZE { + let e = EvaluatedClip { clip: clip.clone(), inputs, region: region.clone(), size }; + CLIPS.with_borrow_mut(|kept| { + kept.insert(0, e); + kept.truncate(CLIPS_KEPT); + let mut total = 0usize; + kept.retain(|e| { + total = total.saturating_add(e.size); + total <= LIVE_KEPT_SIZE + }); + }); + } + region +} + +/// The box of a clipping path's region found by [`reshaped_clip_box`]: the clipping path and the +/// [`LiveInputs`] as they were, the box and the [`art_size`] of the clipping path. +struct ClipBox { + clip: Node, + inputs: u64, + rect: Option, + size: usize, +} + +/// How many boxes [`reshaped_clip_box`] keeps on each thread. Every pointer move measures every clip +/// group it passes, so the boxes of all of a document's clip groups with live effects are kept, not +/// only the latest few as with the regions. +const CLIP_BOXES_KEPT: usize = 4096; + +thread_local! { + /// The boxes [`reshaped_clip_box`] keeps, by clipping path, and the sum of their sizes. + static CLIP_BOXES: RefCell<(HashMap, usize)> = RefCell::new((HashMap::new(), 0)); +} + +/// The box of the region `clip` clips to with its live geometry effects applied ([`clip_region`]), +/// `None` when it has none or no region. The box is kept until `clip` or the [`LiveInputs`] change. +/// When the boxes kept are full, a new box replaces as many others as it needs room for, so the +/// pointer moving over more clip groups than fit still finds most of their boxes. +pub(crate) fn reshaped_clip_box(clip: &Node) -> Option { + use vectorcraft_geom::kurbo::Shape; + CLIP_REGION.get()?; + if !has_effects(clip) { + return None; + } + let inputs = live_inputs(); + let kept = CLIP_BOXES.with_borrow(|(boxes, _)| boxes.get(&clip.id).filter(|b| b.inputs == inputs && b.clip == *clip).map(|b| b.rect)); + if let Some(rect) = kept { + return rect; + } + let rect = clip_region(clip).and_then(|r| r.as_ref().as_ref().filter(|(bp, _)| !bp.elements().is_empty()).map(|(bp, _)| bp.bounding_box())); + let size = art_size(std::slice::from_ref(clip)); + if size <= LIVE_KEPT_SIZE { + CLIP_BOXES.with_borrow_mut(|(boxes, total)| { + if let Some(old) = boxes.remove(&clip.id) { + *total = total.saturating_sub(old.size); + } + while boxes.len() >= CLIP_BOXES_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE { + let Some(other) = boxes.keys().next().copied() else { break }; + if let Some(old) = boxes.remove(&other) { + *total = total.saturating_sub(old.size); + } + } + boxes.insert(clip.id, ClipBox { clip: clip.clone(), inputs, rect, size }); + *total = total.saturating_add(size); + }); + } + rect +} + +/// The regions a click inside a clip group must fall in: those `clip` clips to with its live +/// effects applied, as the canvas clips ([`clip_region`]), else its plain shapes ([`clip_regions`]). +fn clip_areas(clip: &Node) -> Vec<(BezPath, FillRule)> { + match clip_region(clip) { + Some(region) => region.as_ref().iter().cloned().collect(), + None => clip_regions(clip), + } +} + +/// The regions `clip` clips to by its plain shapes ([`Node::clip_shapes`]), without its live +/// effects. Text counts by its frame: glyph outlines need the font engine, above this crate. pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> { let frame = |n: &Node| { let b = n.geometric_bounds()?; @@ -698,7 +857,7 @@ fn hit_children( // Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for // the selection tools in isolation mode within it. let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope); - if !edited && !clip_contains(clip, p) { + if !edited && !clip_contains(clip, p, opt.outline) { return None; } } @@ -960,7 +1119,7 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option match &n.kind { // A clip group only hits inside its clipping path. NodeKind::Group { children, clip } => { - if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) { + if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) { return None; } children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)) @@ -1048,7 +1207,9 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { /// group's original shapes, which the canvas does not draw, and guide paths with /// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice /// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not -/// draw. `None` when `inst` is not a symbol instance or no editable object of its art is under `p`. +/// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a +/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or +/// no editable object of its art is under `p`. pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { struct Find<'a> { art: &'a InstanceArt<'a>, @@ -1057,35 +1218,34 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> symbols: &'a SymbolBoxes<'a>, } impl Find<'_> { - fn hit(&self, n: &Node, whole: Option) -> bool { - self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some()) + fn hit(&self, n: &Node, whole: Option, opt: HitOptions) -> bool { + self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, opt, self.symbols).is_some()) } fn skips_guide(&self, n: &Node) -> bool { self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. }) } - fn find(&self, n: &Node, path: &mut Vec, whole: Option) -> bool { + /// `outline`: the view is in Outline, or a layer around `n` has Preview off. + fn find(&self, n: &Node, path: &mut Vec, whole: Option, outline: bool) -> bool { if !n.visible || n.locked || n.is_template() || self.skips_guide(n) { return false; } - let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole) }; + let outline = outline || previews_off(n); + let opt = HitOptions { outline, ..self.opt }; + let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) }; if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH { - return self.hit(n, whole); + return self.hit(n, whole, opt); } let whole = self.art.whole(n, whole); if n.clips() && let Some(first) = children.first() { let Some(clip) = self.art.place_unclipped(first, whole) else { return false }; - if self.opt.clip_outlines - && first.visible - && !first.locked - && !self.skips_guide(first) - && clip_outline(&clip, self.p, self.opt).is_some() + if self.opt.clip_outlines && first.visible && !first.locked && !self.skips_guide(first) && clip_outline(&clip, self.p, opt).is_some() { path.push(0); return true; } - if !clip_contains(&clip, self.p) { + if !clip_contains(&clip, self.p, outline) { return false; } } @@ -1096,7 +1256,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> } let Ok(i) = u32::try_from(i) else { continue }; path.push(i); - if self.find(c, path, whole) { + if self.find(c, path, whole, outline) { return true; } path.pop(); @@ -1107,7 +1267,17 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> let art = InstanceArt::of(doc, inst)?; let symbols = doc.symbol_boxes(); let mut path = vec![]; - Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path) + let outline = opt.outline || below_preview_off(doc, inst, opt.scope); + Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, outline).then_some(path) +} + +/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks +/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it +/// does not count. +fn below_preview_off(doc: &Document, n: &Node, scope: Option) -> bool { + let Some(chain) = doc.ancestry(n.id) else { return false }; + let below = scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1); + chain.iter().skip(below).any(|a| doc.node(*a).is_some_and(previews_off)) } /// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]), @@ -1116,11 +1286,23 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> /// group per cell) they are cut to the bounds of the group's clip path, which is not outlined. An /// object inside a clip group or a clipping layer of the art, other than its clipping path, is cut /// to the bounds of that clipping path as well, which contain the region where [`symbol_part_at`] -/// picks it. +/// picks it: the bounds of the region its live geometry effects give it ([`clip_region`]) when it +/// has any. /// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies. pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option { + symbol_part_outline_in_view(doc, inst, path, HitOptions::default()) +} + +/// [`symbol_part_outline`] in the view the canvas shows, for the clicks of `opt`: in Outline view +/// ([`HitOptions::outline`]) and below a layer whose Preview is off, in the art or around the +/// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the +/// outlines are cut to the bounds of the plain clipping paths, without their live effects, as +/// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around +/// the object leave no region. +pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option { let art = InstanceArt::of(doc, inst)?; let part = crate::symbol_overrides::part(&art.art, path)?; + let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope); let mut out = BezPath::new(); let mut limit = None; let mut whole = None; @@ -1128,24 +1310,40 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option< for &i in path { let children = n.children()?; whole = art.whole(n, whole); + outline = outline || previews_off(n); if i != 0 && n.clips() && let Some(first) = children.first() - && let Some(clip) = art.place_unclipped(first, whole)?.geometric_bounds() { - match meet(Some(clip), limit) { - Some(r) => limit = Some(r), - None => return Some(out), - } + let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) }; + limit = within; } n = children.get(usize::try_from(i).ok()?)?; } - outline_within(&art.place(part, whole)?, limit, &mut out); + outline_within(&art.place(part, whole)?, limit, outline, &mut out); Some(out) } -/// [`symbol_part_outline`] for placed object `n`, cut to `limit` when there is one. -fn outline_within(n: &Node, limit: Option, out: &mut BezPath) { +/// `limit` cut to the box that the art clipped by `clip` is drawn in: the bounds of the region the +/// live geometry effects of `clip` give it ([`clip_region`]), or the bounds of `clip` when it has no +/// such effects and with `outline`, where the canvas draws no effects. `None` when none of that art +/// is drawn: the effects leave no region, or the box is outside `limit`. +fn limit_within(clip: &Node, limit: Option, outline: bool) -> Option> { + use vectorcraft_geom::kurbo::Shape; + let region = if outline { None } else { clip_region(clip) }; + let bounds = match region.as_deref() { + Some(Some((bp, _))) if !bp.elements().is_empty() => Some(bp.bounding_box()), + Some(_) => return None, + None => clip.geometric_bounds(), + }; + match bounds { + Some(b) => meet(Some(b), limit).map(Some), + None => Some(limit), + } +} + +/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one. +fn outline_within(n: &Node, limit: Option, outline: bool, out: &mut BezPath) { use vectorcraft_geom::kurbo::Shape; if let Some(pd) = n.path_data() { match limit { @@ -1159,20 +1357,15 @@ fn outline_within(n: &Node, limit: Option, out: &mut BezPath) { out.extend(b.to_path(0.1)); } let Some(children) = n.children() else { return }; + let outline = outline || previews_off(n); if n.clips() && let Some((first, rest)) = children.split_first() { - let inner = match first.geometric_bounds() { - Some(c) => match meet(Some(c), limit) { - Some(r) => Some(r), - None => return, - }, - None => limit, - }; - rest.iter().for_each(|c| outline_within(c, inner, out)); + let Some(inner) = limit_within(first, limit, outline) else { return }; + rest.iter().for_each(|c| outline_within(c, inner, outline, out)); return; } - children.iter().for_each(|c| outline_within(c, limit, out)); + children.iter().for_each(|c| outline_within(c, limit, outline, out)); } /// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap. @@ -1248,31 +1441,48 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// or of the parent of the single object isolated, does not limit the marquee, as it does not limit /// the selection tools' clicks. pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> Vec { - marquee_with(doc, r, scope, leaves, false) + marquee_with(doc, r, scope, leaves, false, false) +} + +/// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer +/// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as +/// the clicks of [`HitOptions::outline`] do. +pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option, leaves: bool, outline: bool) -> Vec { + marquee_with(doc, r, scope, leaves, false, outline) } /// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group -/// traversal follow [`marquee`]; compounds contribute the complete path they paint. -pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option) -> Vec { - marquee_with(doc, r, scope, true, true) +/// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint. +pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option, outline: bool) -> Vec { + marquee_with(doc, r, scope, true, true, outline) } -fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool) -> Vec { +/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)? +fn previews_off(n: &Node) -> bool { + matches!(n.kind, NodeKind::Layer { preview: false, .. }) +} + +fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { let mut out = Vec::new(); - // `tops` pairs each object with the part of `r` in which the marquee can touch it. - let tops: Vec<(&std::sync::Arc, Rect)> = match scope.and_then(|s| doc.node(s)) { + // The objects the marquee may touch ([`Top`]). + let tops: Vec = match scope.and_then(|s| doc.node(s)) { // Isolated art whose layer, or a group around it, was locked or hidden afterwards: the // marquee touches none of it, as clicks don't (#5309). Some(s) if !doc.is_editable(s.id) => vec![], Some(s) => match s.children() { - Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(), + Some(c) => c + .iter() + .enumerate() + .filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)) + .map(|(_, c)| (c, Some(r), outline, None)) + .collect(), // A single object isolated: only it. None => doc .parent_of(s.id) .and_then(|p| doc.node(p)) .and_then(|p| p.children()) .into_iter() - .flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, r))) + .flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None))) .collect(), }, // The objects of the layers, looking through sublayers (hidden, locked and template ones @@ -1281,42 +1491,88 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh .layers .iter() .filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id)) - .flat_map(|l| layer_objects(l, r)) + .flat_map(|l| layer_objects(l, r, outline)) .collect(), }; /// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of - /// the sublayers it is in leave. - fn layer_objects(l: &Node, r: Rect) -> Vec<(&std::sync::Arc, Rect)> { + /// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`, + /// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain + /// shapes ([`mask_marquee`]). + fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec> { let mut out = vec![]; - let Some(r) = marquee_in(l, r) else { return out }; - for c in l.children().into_iter().flatten() { + let outline = outline || previews_off(l); + let inner = marquee_in_parent(l, r, outline); + for (i, c) in l.children().into_iter().flatten().enumerate() { if c.is_layer() { - if c.visible && !c.locked && !c.is_template() { - out.extend(layer_objects(c, r)); + if let Some(inner) = inner + && c.visible + && !c.locked + && !c.is_template() + { + out.extend(layer_objects(c, inner, outline)); } } else if !c.is_ruler_guide() { - out.push((c, r)); + if i == 0 && l.clips() { + out.push((c, mask_marquee(l, r), outline, Some(r))); + } else if inner.is_some() { + out.push((c, inner, outline, None)); + } } } out } + /// The part of `r` in which the marquee can touch the clipping path of `parent` by its own + /// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its + /// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to. + fn mask_marquee(parent: &Node, r: Rect) -> Option { + marquee_in_parent(parent, r, true) + } + /// Does the marquee `r` touch `clip`, the clipping path of a clip group or of a layer with a + /// clipping mask, on the edge of the region its live effects give it ([`clip_region`]), where + /// the clip shows? Never in outline, nor without live effects: its own geometry counts then. + fn clip_edge_touches(clip: &Node, r: Rect, outline: bool) -> bool { + if outline { + return false; + } + clip_region(clip).is_some_and(|region| { + region.as_ref().as_ref().is_some_and(|(bp, _)| { + // The edge of the region is its outline with each open subpath closed, as `fill_contains` fills it. + let mut edge = PathData::from_bezpath(bp); + edge.subpaths.iter_mut().for_each(|sp| sp.closed = true); + vectorcraft_geom::hit::intersects_rect(&edge, r) + }) + }) + } + /// Is `n` collected whole by [`collect_leaves`], not by its members? + fn is_leaf(n: &Node) -> bool { + !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. }) + } /// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip /// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched /// by the copies it draws, as clicks hit them. Objects of every other kind except paths, - /// compound paths, layers and groups are touched by their box. - fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool) -> bool { + /// compound paths, layers and groups are touched by their box. A clipping path is touched by + /// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]). + fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool) -> bool { match &n.kind { NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r), NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { - marquee_in(n, r).is_some_and(|r| { - children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope, whole_compounds)) + let outline = outline || previews_off(n); + let inner = marquee_in_parent(n, r, outline); + children.iter().enumerate().any(|(i, c)| { + c.visible + && !shaper_hides(n, i, scope) + && if i == 0 && n.clips() { + mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline) + } else { + inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) + } }) } NodeKind::Compound { children, .. } if whole_compounds => { children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r)) } - NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds)), - NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds)), + NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)), + NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)), // A box with no width or no height (an instance of a symbol that draws a straight // line) is touched where the marquee crosses it. _ => n.geometric_bounds_with(s).is_some_and(|b| { @@ -1325,18 +1581,30 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh }), } } - fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, out: &mut Vec) { + fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool, out: &mut Vec) { match &n.kind { NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { - let Some(r) = marquee_in(n, r) else { return }; + let outline = outline || previews_off(n); + let inner = marquee_in_parent(n, r, outline); for (i, c) in children.iter().enumerate() { - if c.visible && !c.locked && !shaper_hides(n, i, scope) { - collect_leaves(c, s, r, scope, whole_compounds, out); + if !c.visible || c.locked || shaper_hides(n, i, scope) { + continue; + } + if i == 0 && n.clips() { + let before = out.len(); + if let Some(r) = mask_marquee(n, r) { + collect_leaves(c, s, r, scope, whole_compounds, outline, out); + } + if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) { + out.push(c.id); + } + } else if let Some(r) = inner { + collect_leaves(c, s, r, scope, whole_compounds, outline, out); } } } _ => { - if touches(n, s, r, scope, whole_compounds) { + if touches(n, s, r, scope, whole_compounds, outline) { out.push(n.id); } } @@ -1344,36 +1612,56 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh } let symbols = doc.symbol_boxes(); let locks = doc.locked_artboards(); - for (t, r) in tops { + for (t, r, outline, edge) in tops { if !t.visible || t.locked || locks.holds_id(t.id) { continue; } if leaves { - collect_leaves(t, &symbols, r, scope, whole_compounds, &mut out); - } else if touches(t, &symbols, r, scope, whole_compounds) { + let before = out.len(); + if let Some(r) = r { + collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out); + } + if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) { + out.push(t.id); + } + } else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline)) + || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) + { out.push(t.id); } } out } +/// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which +/// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a +/// layer, the marquee whose edge test it also takes (`clip_edge_touches`). +type Top<'a> = (&'a std::sync::Arc, Option, bool, Option); + /// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a -/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None -/// when the marquee misses it); otherwise it is all of `r`. +/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its +/// clipping path ([`clip_regions`]; None when the marquee misses them); otherwise it is all of `r`. pub fn marquee_in(parent: &Node, r: Rect) -> Option { + marquee_in_parent(parent, r, true) +} + +/// The part of a marquee `r` in which it can touch the children of `parent`, by the region its +/// clipping path clips to ([`clip_areas`]), or by that path's plain shapes with `outline` +/// ([`marquee_in_view`]). +fn marquee_in_parent(parent: &Node, r: Rect, outline: bool) -> Option { match parent.children().and_then(|c| c.first()) { - Some(clip) if parent.clips() => marquee_in_clip(clip, r), + Some(clip) if parent.clips() => marquee_in_clip(clip, r, outline), _ => Some(r), } } /// The part of a marquee `r` in which it can touch the art that `clip` clips (the clipping path of /// a clip group or of a layer with a clipping mask): `r` cut to the bounds of the regions `clip` -/// clips to ([`clip_regions`]), or `None` when `r` meets none of those regions. Within those -/// bounds, art outside a region that is not a rectangle still counts. -fn marquee_in_clip(clip: &Node, r: Rect) -> Option { +/// clips to ([`clip_areas`], its plain shapes with `outline`), or `None` when `r` meets none of +/// those regions. Within those bounds, art outside a region that is not a rectangle still counts. +fn marquee_in_clip(clip: &Node, r: Rect, outline: bool) -> Option { use vectorcraft_geom::kurbo::Shape; - let regions = clip_regions(clip); + let regions = if outline { clip_regions(clip) } else { clip_areas(clip) }; // The edge of a region is its outline with each open subpath closed, as `fill_contains` fills it. let meets = |(bp, rule): &(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)| { let mut edge = vectorcraft_geom::PathData::from_bezpath(bp); diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index a4d1cbbf10..dde7365424 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -110,6 +110,252 @@ fn half_clipped(d: &mut Document) -> (Node, Node) { (mask, art) } +/// A stand-in for the engine's [`ClipRegion`]: with an effect named `test.move` in the clipping +/// path, its first shape moved 100 pt right; with one named `test.empty`, no region left to clip +/// by; without either, no geometry effect. +fn moved_clip_region(clip: &Node) -> Option> { + let (mut moves, mut empty) = (false, false); + clip.walk(&mut |n| { + moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move"); + empty |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.empty"); + }); + if empty { + return Some(None); + } + if !moves { + return None; + } + Some(clip_regions(clip).into_iter().next().map(|(mut bp, rule)| { + bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0))); + (bp, rule) + })) +} + +/// A visible effect named `test.move`, which [`moved_clip_region`] reads as moving the region. +fn test_move() -> crate::Effect { + crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true } +} + +/// Clicks inside a clip group whose clipping path has a live effect fall in the region the +/// registered [`ClipRegion`] gives it. The pointer moving over it evaluates the region once, and +/// again after the clipping path changes; a clipping path without effects is not evaluated. +#[test] +fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_changes() { + set_clip_region(moved_clip_region); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + let leaf = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf); + for x in [148.0, 150.0, 152.0] { + assert_eq!(leaf(&d, x), Some(art_id), "in the moved region"); + } + assert_eq!(leaf(&d, 50.0), None, "the clipping path's own place"); + assert_eq!(evaluated(), before + 1); + // Outline mode draws no effects: the art's edge shows within the clipping path's own shape. + let outline = HitOptions { outline: true, ..HitOptions::default() }; + assert_eq!(hit_test(&d, Point::new(50.0, 0.5), outline).map(|h| h.leaf), Some(art_id), "outline mode"); + // So with a marquee across the art's left edge: in the view, only in Outline view. The + // clipping path's own left edge lies there too, and counts in both. + let edge = Rect::new(-5.0, 40.0, 5.0, 60.0); + assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]); + assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]); + // `marquee_in` measures by the plain shapes, as its callers clip by them. + assert!(marquee_in(d.node(g).unwrap(), edge).is_some()); + // Hidden, the effect no longer moves the region. + d.node_mut(mask_id).unwrap().appearance.effects[0].visible = false; + assert_eq!(leaf(&d, 50.0), Some(art_id)); + assert_eq!(leaf(&d, 150.0), None); + assert_eq!(evaluated(), before + 1); + // Shown again and widened, the region is evaluated again. + let mask = d.node_mut(mask_id).unwrap(); + mask.appearance.effects[0].visible = true; + if let NodeKind::Path { path, .. } = &mut mask.kind { + *path = shapes::rectangle(Rect::new(0.0, 0.0, 90.0, 100.0)); + } + assert_eq!(leaf(&d, 180.0), Some(art_id)); + assert_eq!(leaf(&d, 195.0), None); + assert_eq!(evaluated(), before + 2); +} + +/// A marquee around a clipping path that an effect moved into the middle of large art touches the +/// clipping path on the edge of its moved region, in a clip group and in a clipping layer. +#[test] +fn a_marquee_touches_a_moved_clipping_path_on_its_region() { + set_clip_region(moved_clip_region); + let parts = |d: &mut Document| { + let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default()); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 300.0)), Appearance::default_art()); + (mask, art) + }; + // Around the moved region (120..160) and the clipping path's own place, inside the art. + let around = Rect::new(10.0, 10.0, 170.0, 70.0); + let mut d = Document::new(400.0, 400.0); + let l = d.layers[0].id; + let (mask, art) = parts(&mut d); + let (g, mask_id) = (d.alloc_id(), mask.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + assert_eq!(marquee(&d, around, None, false), [g]); + assert_eq!(marquee(&d, around, None, true), [mask_id]); + // Only over the clipping path's own place, the marquee misses the region but touches the + // clipping path's anchors, which a click on its outline also finds. + let own = Rect::new(10.0, 10.0, 70.0, 70.0); + assert_eq!(marquee(&d, own, None, false), [g]); + assert_eq!(marquee(&d, own, None, true), [mask_id]); + // Away from both, nothing. + assert!(marquee(&d, Rect::new(70.0, 10.0, 110.0, 70.0), None, true).is_empty()); + + let mut d = Document::new(400.0, 400.0); + let top = d.layers[0].id; + let (mask, art) = parts(&mut d); + let mask_id = mask.id; + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind { + (*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true); + } + d.insert(Some(top), 0, sublayer).unwrap(); + assert_eq!(marquee(&d, around, None, false), [mask_id]); +} + +/// A clipping layer whose Preview is off draws its art in outline: clicks, the objects at a point +/// and marquees count its clipping path by its plain shape, without the effect that moves it. +#[test] +fn a_clipping_layer_with_preview_off_counts_its_plain_clipping_path() { + set_clip_region(moved_clip_region); + let mut d = Document::new(300.0, 200.0); + let top = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let art_id = art.id; + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, clip, preview, .. } = &mut sublayer.kind { + (*children, *clip, *preview) = (vec![Arc::new(mask), Arc::new(art)], true, false); + } + d.insert(Some(top), 0, sublayer).unwrap(); + // The art's top edge, within the clipping path's own shape. + let p = Point::new(50.0, 0.5); + assert_eq!(hit_test(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art_id)); + assert_eq!(objects_at(&d, p, HitOptions::default(), None).first(), Some(&art_id)); + assert!(marquee(&d, Rect::new(45.0, -5.0, 55.0, 5.0), None, true).contains(&art_id)); +} + +/// The pointer moving over empty canvas past more clip groups with live effects than the regions +/// kept measures each group's box once: the boxes are kept for every clip group. +#[test] +fn hovers_past_many_clip_groups_evaluate_each_clipping_path_once() { + set_clip_region(moved_clip_region); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + for i in 0..(2 * CLIPS_KEPT) { + let x = 20.0 * i as f64; + let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default()); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 10.0)), Appearance::default_art()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + } + let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get); + let empty = Point::new(500.0, 500.0); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let first = evaluated(); + for _ in 0..3 { + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + } + assert_eq!(evaluated(), first); +} + +/// With more clip groups with live effects than the boxes kept, a new box replaces only as many +/// others as it needs room for: the next hover finds most of the boxes and evaluates few regions. +#[test] +fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() { + set_clip_region(moved_clip_region); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let groups = CLIP_BOXES_KEPT + 64; + let mut members = Vec::with_capacity(groups); + for i in 0..groups { + let x = (i % 100) as f64 * 5.0; + let y = (i / 100) as f64 * 5.0; + let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 2.0, y + 2.0)), Appearance::default()); + mask.appearance.effects.push(test_move()); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 2.0)), Appearance::default_art()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + members.push(Arc::new(clip)); + } + if let Some(children) = d.node_mut(l).and_then(|n| n.children_mut()) { + *children = members; + } + let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get); + let empty = Point::new(900.0, 900.0); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let first = evaluated(); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let again = evaluated() - first; + assert!(again < groups / 8, "{again} of {groups} regions evaluated again"); +} + +/// Every test of a clip group by its clipping path follows the region a live effect moved it to: +/// the selected art hidden by the mask, a click into a group holding the clip group, the locked +/// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer +/// whose Preview is off, which is clicked in outline while the layer above clips by its region. +#[test] +fn every_clip_test_follows_the_moved_region() { + set_clip_region(moved_clip_region); + let (moved, own) = (Point::new(150.0, 50.0), Point::new(50.0, 50.0)); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let (g, art_id) = (d.alloc_id(), art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + let outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]); + d.insert(Some(l), 0, outer.clone()).unwrap(); + let opt = HitOptions::default(); + assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id), "hidden at the clipping path's own place"); + assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None, "shown in the moved region"); + let symbols = d.symbol_boxes(); + assert_eq!(hit_any(&outer, moved, opt, &symbols), Some(HitKind::Fill)); + assert_eq!(hit_any(&outer, own, opt, &symbols), None); + d.node_mut(art_id).unwrap().locked = true; + assert_eq!(locked_objects_at(&d, moved, opt), [art_id]); + assert!(locked_objects_at(&d, own, opt).is_empty()); + + // A clipping layer holding the mask and a sublayer whose Preview is off, with the art. + let mut d = Document::new(300.0, 200.0); + let top = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let art_id = art.id; + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, preview, .. } = &mut sublayer.kind { + (*children, *preview) = (vec![Arc::new(art)], false); + } + d.insert(Some(top), 0, sublayer).unwrap(); + d.insert(Some(top), 0, mask).unwrap(); + d.node_mut(top).unwrap().set_clips(true); + // The art's top edge, at the clipping path's own place and in the moved region. + let (own, moved) = (Point::new(50.0, 0.5), Point::new(150.0, 0.5)); + assert!(hit_test(&d, own, opt).is_none()); + assert_eq!(hit_test(&d, moved, opt).map(|h| h.leaf), Some(art_id)); + assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id)); + assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None); +} + /// The art a mask hides counts only for a selected object: there a click hits nothing, and the /// selection tools grab the selection by that art. Not where the art shows (the click hits it), /// beyond the art, for the clip group selected as a whole, nor for art a click can't hit (locked, @@ -1549,6 +1795,63 @@ fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() { assert!((b.x1 - 100.0).abs() < 1e-6, "the layer's outline is cut to the mask: {b:?}"); } +/// In a dynamic symbol's art, an object in a clipping layer whose clipping path has a live effect +/// is picked and outlined in the region the effect gives the clipping path. In Outline view, and +/// when Preview is off for the layer in the art or for the layer the instance is on, the plain +/// clipping path counts, as the canvas draws it. An effect that leaves no region leaves no outline. +#[test] +fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() { + set_clip_region(moved_clip_region); + // The instance of a symbol whose art is a clipping layer; `preview` is the Preview of that + // layer and of the document layer the instance is on. + let instance = |effect: &str, preview: [bool; 2]| { + let mut d = Document::new(300.0, 200.0); + if let NodeKind::Layer { preview: p, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *p = preview[1]; + } + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(crate::Effect { id: effect.into(), ..test_move() }); + let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2)); + if let NodeKind::Layer { children, preview: p, .. } = &mut layer.kind { + (*children, *p) = (vec![Arc::new(mask), Arc::new(art)], preview[0]); + } + layer.set_clips(true); + let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]); + d.symbols.push(crate::Symbol { dynamic: true, name: "Clipped".into(), art: Arc::new(root) }); + let inst = d.alloc_id(); + d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap(); + (d, inst) + }; + let outline_box = |d: &Document, inst: NodeId, opt: HitOptions| { + let o = symbol_part_outline_in_view(d, d.node(inst).unwrap(), &[0, 1], opt).unwrap(); + vectorcraft_geom::kurbo::Shape::bounding_box(&o) + }; + let opt = HitOptions::default(); + let (d, inst) = instance("test.move", [true, true]); + let n = d.node(inst).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), Some(vec![0, 1]), "in the moved region"); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None, "where the clipping path was"); + let b = outline_box(&d, inst, opt); + assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 200.0).abs() < 1e-6, "the outline is cut to the moved region: {b:?}"); + let b = outline_box(&d, inst, HitOptions { outline: true, ..opt }); + assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "in Outline view, to the plain clipping path: {b:?}"); + // With Preview off, the art's top edge counts within the plain clipping path. + for (preview, what) in [([false, true], "the layer in the art"), ([true, false], "the layer the instance is on")] { + let (d, inst) = instance("test.move", preview); + let n = d.node(inst).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 0.5), opt), Some(vec![0, 1]), "on the edge the canvas draws, Preview off for {what}"); + assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 0.5), opt), None, "past the plain clipping path, Preview off for {what}"); + let b = outline_box(&d, inst, opt); + assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "Preview off for {what}: the plain clipping path: {b:?}"); + } + // An effect that leaves the clipping path no region hides the art: no pick and no outline. + let (d, inst) = instance("test.empty", [true, true]); + let n = d.node(inst).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None); + assert!(symbol_part_outline(&d, n, &[0, 1]).unwrap().elements().is_empty(), "nothing is drawn, so nothing is outlined"); +} + /// In a dynamic symbol's art that placing through its 9-slice guides could make more than /// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the /// canvas draws nothing of it. At the art's natural size the same art is picked. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 8507b50754..d6b797a371 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -119,6 +119,7 @@ pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOption pub use style_libs::StyleLibrary; pub use text::FontHeightReference; pub use text::GlyphChoice; +pub use text::GlyphForm; pub use text::WarichuAlign; pub use text::{ AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt, diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index efb006afed..1aad3a27cf 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -211,7 +211,9 @@ impl Node { /// A quick box round everything the object can paint, for culling clicks: paths and compound /// paths grow their geometric bounds by the farthest their strokes can reach from any path - /// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in + /// ([`Appearance::outset`]) instead of measuring along their shape. A clip group's or a + /// clipping layer's box takes in the region that the live geometry effects of its clipping + /// path give it ([`crate::hit::set_clip_region`]). An image's box takes in /// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers /// without a clipping mask and Intertwine groups take in their members' boxes, grown by their /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box @@ -261,6 +263,11 @@ impl Node { NodeKind::Blend { children, spec } => { vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols)) } + // The live geometry effects of a clipping path can move or grow the region it clips to + // past its plain shape ([`crate::hit::set_clip_region`]). + NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => { + vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c))) + } _ => self.visual(symbols), } } diff --git a/crates/doc/src/tests/units.rs b/crates/doc/src/tests/units.rs index 5a9265c702..c53f60a227 100644 --- a/crates/doc/src/tests/units.rs +++ b/crates/doc/src/tests/units.rs @@ -79,6 +79,21 @@ fn odd_text_reads_as_nothing_without_panicking() { } } +/// Text from a command or a file can be any length: a sum of thousands of terms reads as nothing +/// instead of exhausting the stack. Up to 128 `+ - * /` signs read; 129 read as nothing. +#[test] +fn a_very_long_expression_reads_as_nothing() { + let sum = |terms: usize| format!("1{}", "+1".repeat(terms - 1)); + assert_eq!(Unit::Points.parse(&sum(129)), Some(129.0)); + assert_eq!(Unit::Points.parse(&format!("10{} mm", "*1".repeat(128))), Some(Unit::Millimeters.to_pt(10.0))); + // Long text with no signs still reads. + assert_eq!(Unit::Points.parse(&format!("{}5", " ".repeat(2_000))), Some(5.0)); + for text in [sum(200_000), format!("1{}", "*1".repeat(200_000)), sum(130), format!("10{} mm", "*1".repeat(129))] { + assert_eq!(Unit::Points.parse(&text), None, "{} bytes", text.len()); + assert_eq!(crate::parse_number(&text), None, "{} bytes", text.len()); + } +} + proptest! { /// Field text made of digits, operators, `%`, spaces and unit letters reads as a finite value /// or as nothing and does not panic. diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index c3c1464cfc..89388d8598 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -18,8 +18,8 @@ mod wrap; pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape}; use char_style::yes; pub use char_style::{ - CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES, - WARICHU_SCALE, WarichuAlign, + CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, + WARICHU_LINES, WARICHU_SCALE, WarichuAlign, }; pub use composite::{ COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart, diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index ef3cf29dc9..97f744dba8 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -205,6 +205,99 @@ pub struct CharStyle { /// default glyph otherwise. Saved only when set. #[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")] pub glyph_alternate: Option, + /// The East Asian glyph form these characters are drawn in (Glyphs panel menu, with Show East + /// Asian Options): one OpenType feature of the font, such as JIS 78 forms (`jp78`), or the + /// font's default glyphs. The text keeps its characters. Saved only when set. + /// + #[serde(default, rename = "glyphForm", skip_serializing_if = "crate::skip::is_default")] + pub glyph_form: GlyphForm, +} + +/// The East Asian glyph form characters are drawn in ([`CharStyle::glyph_form`]): the font's +/// default glyphs, or the glyphs one OpenType feature substitutes. One form at a time. +/// +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum GlyphForm { + /// The font's default glyphs. + #[default] + Default, + /// Traditional forms (`trad`). + Traditional, + /// Expert forms (`expt`). + Expert, + /// JIS 2004 forms (`jp04`). + Jis04, + /// JIS 90 forms (`jp90`). + Jis90, + /// JIS 78 forms (`jp78`). + Jis78, + /// JIS 83 forms (`jp83`). + Jis83, + /// Monospaced full-width forms (`fwid`). + FullWidth, + /// Monospaced half-width forms (`hwid`). + HalfWidth, + /// Monospaced third-width forms (`twid`). + ThirdWidth, + /// Monospaced quarter-width forms (`qwid`). + QuarterWidth, +} + +impl GlyphForm { + /// Every form, in menu order, the default last. + pub const ALL: [GlyphForm; 11] = [ + GlyphForm::Traditional, + GlyphForm::Expert, + GlyphForm::Jis04, + GlyphForm::Jis90, + GlyphForm::Jis78, + GlyphForm::Jis83, + GlyphForm::FullWidth, + GlyphForm::HalfWidth, + GlyphForm::ThirdWidth, + GlyphForm::QuarterWidth, + GlyphForm::Default, + ]; + + /// The name files and commands give this form (as it is saved). + pub fn id(self) -> &'static str { + match self { + GlyphForm::Default => "default", + GlyphForm::Traditional => "traditional", + GlyphForm::Expert => "expert", + GlyphForm::Jis04 => "jis04", + GlyphForm::Jis90 => "jis90", + GlyphForm::Jis78 => "jis78", + GlyphForm::Jis83 => "jis83", + GlyphForm::FullWidth => "fullWidth", + GlyphForm::HalfWidth => "halfWidth", + GlyphForm::ThirdWidth => "thirdWidth", + GlyphForm::QuarterWidth => "quarterWidth", + } + } + + /// The form [`GlyphForm::id`] names; `None` for any other name. + pub fn from_id(id: &str) -> Option { + GlyphForm::ALL.into_iter().find(|f| f.id() == id) + } + + /// The OpenType feature that draws this form; `None` for the default glyphs. + pub fn feature(self) -> Option<&'static [u8; 4]> { + Some(match self { + GlyphForm::Default => return None, + GlyphForm::Traditional => b"trad", + GlyphForm::Expert => b"expt", + GlyphForm::Jis04 => b"jp04", + GlyphForm::Jis90 => b"jp90", + GlyphForm::Jis78 => b"jp78", + GlyphForm::Jis83 => b"jp83", + GlyphForm::FullWidth => b"fwid", + GlyphForm::HalfWidth => b"hwid", + GlyphForm::ThirdWidth => b"twid", + GlyphForm::QuarterWidth => b"qwid", + }) + } } /// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it @@ -586,6 +679,7 @@ impl Default for CharStyle { no_break: false, language: None, glyph_alternate: None, + glyph_form: GlyphForm::Default, } } } diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 234513df1d..5fabfece65 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -156,7 +156,12 @@ impl Unit { /// before it (`3cm*50%` is 1.5 cm, `3cm/50%` is 6 cm). After `+` or `-`, it adds or takes away /// that share of everything before it (`50pt+25%` is 62.5 pt, `100pt+20pt-50%` is 60 pt). A /// percentage on its own (`50%`) reads as nothing. + /// + /// Text with more than 128 `+ - * /` signs reads as nothing. pub fn parse(self, s: &str) -> Option { + if s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() > MAX_MEASURE_OPERATORS { + return None; + } parse_measure(s, self).filter(|v| v.is_finite()) } /// The value naming this unit in the Units preferences (`points`, `millimeters`, @@ -207,6 +212,9 @@ impl Unit { } } +/// The most `+ - * /` signs [`Unit::parse`] reads in one text. +const MAX_MEASURE_OPERATORS: usize = 128; + fn parse_measure(s: &str, default: Unit) -> Option { let s = s.trim(); // Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2"). diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index d648dd9258..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. @@ -476,14 +513,18 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { /// `m`, art evaluated from an object, with its children baked and then given ids of their own (the /// pieces copied from the source keep the source's ids until then). The pieces are baked with the -/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. +/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. When +/// `m` clips, its clipping path, unless it is type, first takes the geometry effects in it as the +/// canvas clips by it ([`crate::clip::with_clip_effects_applied`]). fn bake_pieces(d: &mut Document, mut m: Node) -> Node { let mut seen = std::collections::HashSet::from([m.id]); + let clip = usize::from(m.clips() && !m.children().and_then(|ch| ch.first()).is_some_and(|c| matches!(c.kind, NodeKind::Text(_)))); let children = m.children().cloned().unwrap_or_default(); let children = children .into_iter() - .map(|c| { - let c = Arc::unwrap_or_clone(c); + .enumerate() + .map(|(i, c)| { + let c = (i < clip).then(|| crate::clip::with_clip_effects_applied(&c)).flatten().unwrap_or_else(|| Arc::unwrap_or_clone(c)); let mut c = one_deeper(|| bake_node(d, &c)).unwrap_or(c); fresh_ids(d, &mut c, &mut seen); Arc::new(c) 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..1c1ca96d9f 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -417,7 +417,7 @@ pub fn effect_catalog() -> Vec { "artistic.roughPastels", "Rough Pastels…", ARTISTIC, - "{strokeLength: 0..40 (6; longer pastel strokes), strokeDetail: 1..20 (10; bristle texture along the strokes), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\" (\"canvas\"), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false)} repaints the object in soft diagonal pastel strokes over a textured surface, keeping its coverage. Slider ranges follow the documented controls; numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults.", + "{strokeLength: 0..40 (6; longer pastel strokes), strokeDetail: 1..20 (10; bristle texture along the strokes), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\"|\"loaded\" (\"canvas\"; \"loaded\" draws the image in textureImage and draws Canvas when there is none; the others are surfaces made in code), textureImage?: {path} | {name?, dataBase64} | string (Load Texture…: an image file that File › Place reads, within the renderer's pixel allowance, stored as its gray levels in a grayscale PNG in base64; a file sets texture to \"loaded\" unless texture is given, and the stored string, as effect.list gives it, is kept as it is), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false)} repaints the object in soft diagonal pastel strokes over a textured surface, keeping its coverage. A loaded texture lies one image pixel per point at 100 %, centered on the object's center and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray. Slider ranges follow the documented controls; numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults.", json!({ "strokeLength": 6.0, "strokeDetail": 10.0, @@ -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/clip.rs b/crates/effects/src/clip.rs index c5e11c648f..cd9d67fc43 100644 --- a/crates/effects/src/clip.rs +++ b/crates/effects/src/clip.rs @@ -12,10 +12,14 @@ use vectorcraft_geom::{BezPath, FillRule, PathData}; /// fills and strokes: the region is then the union of the paths they give, as an export bakes them. /// `None` when there is nothing to clip by (the clipped art is then hidden). pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> { - match clip_effects_applied(clip, true, || true) { - Some(m) => m.clip_outline(Some(&outline_text), &unite), - None => clip.clip_outline(Some(&outline_text), &unite), - } + reshaped_clip_outline(clip).unwrap_or_else(|| clip.clip_outline(Some(&outline_text), &unite)) +} + +/// [`clip_outline`] of a clipping path that a live geometry effect reshapes; `None` when nothing +/// `clip` clips by has a geometry effect of its own or on a fill or stroke. A hidden member of a +/// group or layer does not clip, so its effects are not counted. +pub fn reshaped_clip_outline(clip: &Node) -> Option> { + clip_effects_applied(clip, true, || true).map(|m| m.clip_outline(Some(&outline_text), &unite)) } /// `n`, the clipping path of a clip group, with the live geometry effects of everything it clips by diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 9934ea026e..a326c85cf2 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -72,7 +72,7 @@ pub use bake::{ StrokeArt, WrittenLayers, bake_appearance, bake_document, bake_document_placing_symbols, bake_type_appearance, expand_art, expand_leaf, fresh_ids, needs_bake, }; -pub use clip::{WarpSeams, clip_outline, knockout_silhouette, warp_pieces_translucent}; +pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent}; pub use group::{ OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art, diff --git a/crates/effects/src/pixel.rs b/crates/effects/src/pixel.rs index 89eb541b19..f2c49dadd7 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}; @@ -155,12 +155,14 @@ pub enum PixelFx { /// `texture_coverage` (0..40) says. Underpainting { brush_size: f64, texture_coverage: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool }, /// Artistic › Rough Pastels: diagonal pastel strokes `length` (0..40) long, bristle detail - /// (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. + /// (1..20), then a [`Texture`] surface (a loaded one included) 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 +316,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 @@ -381,7 +386,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { "artistic.roughPastels" => PixelFx::RoughPastels { length: num(p, "strokeLength", 6.0).clamp(0.0, 40.0), detail: num(p, "strokeDetail", 10.0).clamp(1.0, 20.0), - texture: Texture::parse(text(p, "texture", "canvas")), + texture: Texture::parse_with(text(p, "texture", "canvas"), p.get(TEXTURE_IMAGE).and_then(Value::as_str)), scaling: num(p, "scaling", 100.0).clamp(50.0, 200.0) / 100.0, relief: num(p, "relief", 4.0).clamp(0.0, 50.0), light: Light::parse(text(p, "lightDirection", "top")), @@ -421,6 +426,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 +614,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 +792,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..34212ddd66 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"})), @@ -1494,6 +1547,42 @@ fn texturizer_draws_a_loaded_texture_as_relief() { assert_eq!(fx("texture.texturizer", json!({"texture": "LOADED", "textureImage": "not a texture"})), fx("texture.texturizer", json!({}))); } +/// Rough Pastels draws a loaded texture as its surface, and Scaling, Relief, Light Direction and +/// Invert act on it as on the built-in ones. +#[test] +fn rough_pastels_draws_a_loaded_texture_as_its_surface() { + let w = 64; + let mid = grey(150); + let rings = stored(12, 10, |x, y| { + let v = ((x as f64 - 5.5).hypot(y as f64 - 4.5) * 0.9).sin().abs(); + let g = (v * 255.0).round() as u8; + [g, g, g, 255] + }); + let run = |mut p: serde_json::Value| { + p["strokeLength"] = json!(0); + let mut d = flat(w, mid); + fx("artistic.roughPastels", p).apply(&mut d, w, w, &space(w, w)); + d + }; + let relief = run(json!({"texture": "loaded", "textureImage": rings, "relief": 20})); + assert_ne!(relief, flat(w, mid)); + for (_, builtin) in TEXTURES { + assert_ne!(relief, run(json!({"texture": builtin, "relief": 20})), "{builtin}"); + } + for (key, value) in [("invert", json!(true)), ("scaling", json!(200)), ("lightDirection", json!("bottomRight")), ("relief", json!(5))] { + let mut p = json!({"texture": "loaded", "textureImage": rings, "relief": 20}); + p[key] = value; + assert_ne!(run(p), relief, "{key}"); + } + assert_eq!(run(json!({"texture": "loaded", "textureImage": rings, "relief": 0})), flat(w, mid)); + let parsed = fx("artistic.roughPastels", json!({"texture": "Loaded", "textureImage": rings})); + assert!(matches!(parsed, PixelFx::RoughPastels { texture: Texture::Loaded(_), .. }), "{parsed:?}"); + // Without a stored texture, or with one that isn't, Loaded draws Canvas. + for p in [json!({"texture": "loaded"}), json!({"texture": "loaded", "textureImage": "not a texture"})] { + assert_eq!(fx("artistic.roughPastels", p), fx("artistic.roughPastels", json!({}))); + } +} + /// The Texture filters' patterns lie in document space around the object's centre: the same at /// twice the resolution, and moving with the object. #[test] 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.rs b/crates/effects/src/svg_filter.rs index 3877a60ae9..0c4bff0f1d 100644 --- a/crates/effects/src/svg_filter.rs +++ b/crates/effects/src/svg_filter.rs @@ -16,6 +16,7 @@ use vectorcraft_geom::{Affine, Rect, Vec2}; use crate::pixel::PixelSpace; use crate::util::{num, text}; +pub mod defaults; #[cfg(test)] mod tests; diff --git a/crates/effects/src/svg_filter/defaults.rs b/crates/effects/src/svg_filter/defaults.rs new file mode 100644 index 0000000000..95a84ca273 --- /dev/null +++ b/crates/effects/src/svg_filter/defaults.rs @@ -0,0 +1,249 @@ +//! The default SVG filters: the filters Effect › SVG Filters and Apply SVG Filter list in every +//! document. The set, the names and the values are VectorCraft's own, written with the filter +//! primitives of SVG 1.1 (). A default is not part of a +//! document until it is applied or edited there: the document then holds a copy under the +//! default's name, and that copy stands in the default's place in the lists. Every default computes +//! in sRGB (`color-interpolation-filters="sRGB"`), so art a filter passes through keeps its colors. + +use vectorcraft_doc::SvgFilter; + +/// A default SVG filter: its name (the `` element's `id`) and the element's XML. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DefaultFilter { + pub name: &'static str, + pub xml: &'static str, +} + +/// The default filters, in the order the lists show them. +pub const DEFAULT_FILTERS: [DefaultFilter; 14] = [ + DefaultFilter { + name: "Soft Blur", + xml: r#""#, + }, + DefaultFilter { + name: "Heavy Blur", + xml: r#""#, + }, + DefaultFilter { + name: "Soft Shadow", + xml: r#""#, + }, + DefaultFilter { + name: "Hard Shadow", + xml: r#""#, + }, + DefaultFilter { + name: "Glow", + xml: r##""##, + }, + DefaultFilter { + name: "Bevel", + xml: r##""##, + }, + DefaultFilter { + name: "Emboss", + xml: r#""#, + }, + DefaultFilter { + name: "Thicken", + xml: r#""#, + }, + DefaultFilter { + name: "Thin", + xml: r#""#, + }, + DefaultFilter { + name: "Rough Edges", + xml: r#""#, + }, + DefaultFilter { + name: "Grain", + xml: r#""#, + }, + DefaultFilter { + name: "Grayscale", + xml: r#""#, + }, + DefaultFilter { + name: "Invert", + xml: r#""#, + }, + DefaultFilter { + name: "Hue Shift", + xml: r#""#, + }, +]; + +/// The default filter named `name`. +pub fn default_filter(name: &str) -> Option { + DEFAULT_FILTERS.iter().copied().find(|f| f.name == name) +} + +impl DefaultFilter { + /// The filter as a document holds it once it is applied or edited there. + pub fn to_filter(self) -> SvgFilter { + SvgFilter { name: self.name.to_string(), xml: self.xml.to_string() } + } +} + +/// A filter of the lists ([`listed`]), and whether it is a default the document does not hold. +#[derive(Clone, Debug, PartialEq)] +pub struct Listed { + pub filter: SvgFilter, + /// A default the document has no filter named for: applying or editing it adds a copy. + pub default: bool, +} + +/// The filters Effect › SVG Filters and Apply SVG Filter list for a document that holds `held`, +/// and how many of them come first as the defaults: each default in [`DEFAULT_FILTERS`]' order (the +/// document's filter of that name in its place), then the document's other filters in their order. +pub fn listed(held: &[SvgFilter]) -> (Vec, usize) { + let mut out: Vec = DEFAULT_FILTERS + .iter() + .map(|d| match held.iter().find(|f| f.name == d.name) { + Some(f) => Listed { filter: f.clone(), default: false }, + None => Listed { filter: d.to_filter(), default: true }, + }) + .collect(); + let defaults = out.len(); + out.extend(held.iter().filter(|f| default_filter(&f.name).is_none()).map(|f| Listed { filter: f.clone(), default: false })); + (out, defaults) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_doc::Effect; + use vectorcraft_geom::{Affine, Point}; + + use super::*; + use crate::pixel::{Channels, PixelSpace}; + use crate::svg_filter::{SVG_FILTER, SvgFilterFx, check, with_id}; + use crate::{PixelFx, RasterFx, raster_effects}; + + /// A `w` × `w` raster whose pixels are one point wide. + fn space(w: usize) -> PixelSpace { + let wd = w as f64; + PixelSpace { + to_doc: Affine::scale(1.0), + px: 1.0, + center: Point::new(wd / 2.0, wd / 2.0), + size: vectorcraft_geom::Vec2::new(wd, wd), + channels: Channels::Rgb, + line: 1.0, + extent: 0.5 * wd.hypot(wd), + } + } + + /// The default named `name` as the renderer reads it. + fn fx(name: &str) -> SvgFilterFx { + let d = default_filter(name).unwrap_or_else(|| panic!("no default {name}")); + let e = Effect { id: SVG_FILTER.into(), params: json!({"name": d.name, "xml": d.xml}), visible: true }; + match raster_effects(&[e]).first() { + Some(RasterFx::Pixel(PixelFx::Svg(f))) => f.clone(), + other => panic!("{name}: {other:?}"), + } + } + + /// A 40 × 40 raster with an opaque square of `rgb` from 10 to 30, run through default `name`. + fn run(name: &str, rgb: [u8; 3]) -> Vec { + let mut data: Vec = (0..40usize) + .flat_map(|y| (0..40usize).map(move |x| (x, y))) + .flat_map(|(x, y)| if (10..30).contains(&x) && (10..30).contains(&y) { [rgb[0], rgb[1], rgb[2], 255] } else { [0; 4] }) + .collect(); + fx(name).apply(&mut data, 40, 40, &space(40)); + data + } + + fn at(d: &[u8], x: usize, y: usize) -> [u8; 4] { + let i = (y * 40 + x) * 4; + [d[i], d[i + 1], d[i + 2], d[i + 3]] + } + + #[test] + fn every_default_is_a_filter_the_check_takes_under_its_own_name() { + let mut seen = std::collections::BTreeSet::new(); + for d in DEFAULT_FILTERS { + assert_eq!(check(d.xml), Ok(d.name.to_string()), "{}", d.name); + assert!(seen.insert(d.name), "{} is listed twice", d.name); + assert_eq!(d.name, d.name.trim()); + // Edit SVG Filter keeps the name by writing it as the id: a default's code comes back as it is. + assert_eq!(with_id(d.xml, d.name).as_deref(), Some(d.xml), "{}", d.name); + assert_eq!(default_filter(d.name), Some(d)); + assert!(d.xml.contains(r#" color-interpolation-filters="sRGB""#), "{} computes in sRGB", d.name); + } + assert!(DEFAULT_FILTERS.len() <= SvgFilter::MAX); + assert_eq!(default_filter("soft blur"), None, "names match exactly"); + } + + #[test] + fn every_default_draws_and_is_written_to_svg_as_a_filter() { + let plain = { + let mut d = vec![0u8; 40 * 40 * 4]; + for y in 10..30 { + for x in 10..30 { + d[(y * 40 + x) * 4..(y * 40 + x) * 4 + 4].copy_from_slice(&[200, 60, 20, 255]); + } + } + d + }; + for d in DEFAULT_FILTERS { + assert_ne!(run(d.name, [200, 60, 20]), plain, "{} changes what is drawn", d.name); + assert!(fx(d.name).writes_as_svg11(), "{} is written as SVG 1.1", d.name); + } + } + + /// The color defaults against SVG 1.1's own arithmetic, in sRGB as each filter asks. + #[test] + fn the_color_defaults_compute_what_svg_1_1_defines() { + let near = |got: [u8; 4], want: [u8; 4]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 1); + // feComponentTransfer, type="table" with values 1 0: C' = 1 - C (§15.11). + let inv = at(&run("Invert", [200, 60, 20]), 20, 20); + assert!(near(inv, [55, 195, 235, 255]), "{inv:?}"); + // feColorMatrix type="saturate" values="0": every channel is 0.213 R + 0.715 G + 0.072 B (§15.10). + let grey = at(&run("Grayscale", [200, 60, 20]), 20, 20); + let l = (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64).round() as u8; + assert!(near(grey, [l, l, l, 255]), "{grey:?} for {l}"); + // feColorMatrix type="hueRotate" values="180" (§15.10): cos = -1 and sin = 0 leave + // R' = (2·0.213 - 1) R + 2·0.715 G + 2·0.072 B, and likewise for G' and B'. + let hue = at(&run("Hue Shift", [200, 60, 20]), 20, 20); + let lum2 = 2.0 * (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64); + let turned = [lum2 - 200.0, lum2 - 60.0, lum2 - 20.0].map(|v| v.round().clamp(0.0, 255.0) as u8); + assert!(near(hue, [turned[0], turned[1], turned[2], 255]), "{hue:?} for {turned:?}"); + } + + /// The shape defaults against what their primitives define: an offset copy of the alpha behind + /// the art (feOffset, §15.21), and a shape grown or shrunk by its radius (feMorphology, §15.20). + #[test] + fn the_shape_defaults_move_and_resize_the_alpha() { + let shadow = run("Hard Shadow", [200, 60, 20]); + assert_eq!(at(&shadow, 20, 20), [200, 60, 20, 255], "the art is on top"); + // Right of and below the art by up to 3: black at 60% alpha (premultiplied 153). + assert_eq!(at(&shadow, 31, 31), [0, 0, 0, 153]); + assert_eq!(at(&shadow, 34, 34)[3], 0, "past the offset"); + assert_eq!(at(&shadow, 8, 8)[3], 0, "nothing up and left"); + let thick = run("Thicken", [200, 60, 20]); + assert_eq!((at(&thick, 9, 20)[3], at(&thick, 7, 20)[3]), (255, 0), "grown by its radius"); + let thin = run("Thin", [200, 60, 20]); + assert_eq!((at(&thin, 10, 20)[3], at(&thin, 13, 20)[3]), (0, 255), "shrunk by its radius"); + let soft = run("Soft Shadow", [200, 60, 20]); + assert_eq!(at(&soft, 20, 20), [200, 60, 20, 255]); + let below = at(&soft, 33, 33); + assert!(below[3] > 0 && below[3] < 128 && below[0] == 0, "a blurred, half-strength shadow: {below:?}"); + } + + #[test] + fn the_lists_show_the_defaults_first_with_the_documents_copy_in_place() { + let (all, defaults) = listed(&[]); + assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len(), DEFAULT_FILTERS.len())); + assert!(all.iter().all(|l| l.default)); + let mine = SvgFilter { name: "Mine".into(), xml: "".into() }; + let glow = SvgFilter { name: "Glow".into(), xml: "".into() }; + let (all, defaults) = listed(&[mine.clone(), glow.clone()]); + assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len() + 1, DEFAULT_FILTERS.len())); + let at = DEFAULT_FILTERS.iter().position(|d| d.name == "Glow").unwrap(); + assert_eq!(all[at], Listed { filter: glow, default: false }, "the document's Glow where the default was"); + assert_eq!(all.last(), Some(&Listed { filter: mine, default: false })); + assert_eq!(all.iter().filter(|l| l.default).count(), DEFAULT_FILTERS.len() - 1); + } +} 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/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs index 370f32fa81..bf63df61ab 100644 --- a/crates/effects/src/tests/clipfx.rs +++ b/crates/effects/src/tests/clipfx.rs @@ -172,6 +172,48 @@ fn the_clipping_paths_effects_apply_before_the_clip_groups() { assert!((b.x0 - want.x0).abs() < 0.5 && (b.x1 - want.x1).abs() < 0.5, "exported: {b:?} against {want:?}"); } +#[test] +fn a_clip_group_with_a_fill_or_stroke_of_its_own_clips_as_the_canvas_does() { + // A clip group with a fill or a stroke of its own and no effects: the export turns its paint + // into art and still clips by the outline the canvas clips by, Transform copies included. + let items = [ + vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))), + vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 2.0)), + ]; + let copies = || fx("distort.transform", json!({"moveH": 60, "copies": 1})); + let roughen = fx("distort.roughen", json!({"size": 10, "detail": 10, "relative": false})); + // A ring: a compound path of two squares with effects `own`, its hole with effects `hole_fx`. + let ring = |hole_fx: Vec, own: Vec| { + let outer = Node::path(NodeId(3), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), Appearance::default()); + let mut hole = Node::path(NodeId(4), shapes::rectangle(Rect::new(75.0, 75.0, 125.0, 125.0)), Appearance::default()); + hole.appearance.effects = hole_fx; + let mut c = + Node::new(NodeId(2), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: vectorcraft_geom::FillRule::EvenOdd }); + c.appearance.effects = own; + c + }; + let clips = [ + ("copies", clipping_path(2, vec![copies()])), + ("roughen", clipping_path(2, vec![roughen])), + ("a compound path's copies", ring(vec![], vec![copies()])), + ("a compound path member's copies", ring(vec![copies()], vec![])), + ]; + for item in &items { + for (what, clip) in &clips { + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + let live = clip_outline(clip).unwrap(); + let mut group = clip_group(1, clip.clone()); + group.appearance.items.push(item.clone()); + d.insert(Some(layer), 0, group).unwrap(); + let exported = clip_outline(&baked_clip(&d)).unwrap(); + assert_eq!(live, exported, "{what} with {item:?}: the canvas clips by the outline the export writes"); + } + } + let b = bounds(&clips[0].1); + assert!((b.x0 - 50.0).abs() < 1e-6 && (b.x1 - 210.0).abs() < 1e-6, "the clip covers both copies: {b:?}"); +} + #[test] fn nested_effects_apply_before_the_clip_groups() { // The clip group grows its clipping path by 10 (Offset Path). Inside the clipping path a diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index a72075d233..afa232a7ce 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -531,8 +531,13 @@ fn an_anchor_edit_makes_it_a_plain_path_and_transforms_keep_it_editable() { s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "count": 6})).unwrap(); assert_eq!((path(&s, id).anchor_count(), steps(&s)), (12, n + 1)); assert!((shape_of(&s, id).unwrap().rotation + 30.0).abs() < 1e-6, "the turn stays"); - // Stretched across its own axes (it is turned): skewed, so no longer. + // Stretched along its turned bounding box: still the shape, wider along its own axis. s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140]})).unwrap(); + let r = shape_of(&s, id).unwrap(); + assert!((r.width - 300.0).abs() < 1e-6 && (r.height - 200.0).abs() < 1e-6 && (r.rotation + 30.0).abs() < 1e-6, "{r:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + // Stretched across the page's axes (it is turned): skewed, so no longer. + s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140], "basis": "page"})).unwrap(); assert_eq!(shape_of(&s, id), None); s.execute("edit.undo", &json!({})).unwrap(); assert!(shape_of(&s, id).is_some(), "undo brings it back"); diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 6a1f0d6496..f694a2b144 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -14,7 +14,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_color::{Color, Paint}; +use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer}; use vectorcraft_doc::{Appearance, Document, GapOptions, GapSize, LiveShape, Node, NodeId, NodeKind, Selection, TraceView}; use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath}; @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Live Paint"], Some("Cmd+Alt+X"), - "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}", + "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}", has_selection_or_ids, lp_make ), @@ -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 ), @@ -414,22 +414,274 @@ fn source_nodes(n: &Node) -> Vec> { if is_live_paint(n) { b::sources(n).and_then(|g| g.children().cloned()).unwrap_or_default() } else { vec![Arc::new(n.clone())] } } +/// Does appearance row `i` draw: it is shown, has paint and an opacity above 0, and a stroke also +/// has a weight above 0? +fn row_draws(i: &AppearanceItem) -> bool { + match i { + AppearanceItem::Fill(f) => f.visible && !f.paint.is_none() && f.opacity > 0.0, + AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.opacity > 0.0 && s.width > 0.0, + } +} + +/// What a source path gives the faces and edges made from it. +struct SourceStyle { + /// The fill rows that draw, in paint order (none when the path's opacity is 0). + fills: Vec, + /// The stroke rows that draw, in paint order (none when the path's opacity is 0). + strokes: Vec, + /// The top stroke's weight, for an edge given no stroke that draws. + width: f64, + opacity: f32, + blend: BlendMode, +} + +impl SourceStyle { + /// The style of source path `n`: its rows keep their order and settings, gradients fitted to + /// its bounds keep that fit, and the strokes' pen pressure, tilt, bearing and rotation stay + /// with the path. + fn of(n: &Node) -> Self { + let mut a = (*n.appearance).clone().without_pressure(); + if a.has_unplaced_gradient() + && let Some(bounds) = n.geometric_bounds() + { + a.pin_gradients(bounds); + } + let width = a.stroke().map_or(1.0, |s| s.width); + let (mut fills, mut strokes) = (vec![], vec![]); + if n.opacity > 0.0 { + for i in a.items.into_iter().filter(row_draws) { + if i.is_fill() { fills.push(i) } else { strokes.push(i) } + } + } + Self { fills, strokes, width, opacity: n.opacity, blend: n.blend } + } + + /// Give part `n` the rows `rows` of this source with its opacity and blending mode; with no + /// rows, `n` keeps the unpainted row it has. + fn paint(&self, n: &mut Node, rows: &[AppearanceItem]) { + if rows.is_empty() { + return; + } + n.appearance = Appearance { items: rows.to_vec(), ..Default::default() }.into(); + n.opacity = self.opacity; + n.blend = self.blend; + } +} + +/// How far, in points, a place on an edge may be from its source path and still be on it. +const ON_SOURCE: f64 = 0.05; + +/// Does stroke row `i` have settings that depend on where along its path a piece of it lies or +/// which way it runs: dashes, arrowheads, a width profile, a brush, or a gradient along or across +/// the stroke? +fn depends_on_place(i: &AppearanceItem) -> bool { + matches!(i, AppearanceItem::Stroke(s) if s.dash.is_some() || s.start_arrow.is_some() || s.end_arrow.is_some() || s.profile.is_some() || s.brush.is_some() || s.gradient_mode != vectorcraft_doc::StrokeGradientMode::Within) +} + +/// One subpath's segments with the length along it where each starts, then its whole length, and +/// a grid of square cells listing the segments whose bounds, grown by [`ON_SOURCE`], reach into +/// each cell, so finding the segments near a point does not look at every segment. +struct Track { + segs: Vec, + at: Vec, + closed: bool, + cell: f64, + grid: HashMap<(i64, i64), Vec>, + /// Segments that reach into more than [`Track::MAX_CELLS`] cells, or that come after the grid + /// holds [`Track::CELLS_PER_SEGMENT`] entries per segment, looked at for every point. + wide: Vec, +} + +impl Track { + const ACCURACY: f64 = 1e-4; + const MAX_CELLS: i64 = 4096; + const CELLS_PER_SEGMENT: usize = 16; + + fn new(sp: &SubPath) -> Self { + use kurbo::{ParamCurveArclen, Shape as _}; + let mut bp = kurbo::BezPath::new(); + sp.to_bezpath_into(&mut bp); + let segs: Vec = bp.segments().collect(); + let mut at = Vec::with_capacity(segs.len() + 1); + let mut len = 0.0; + for s in &segs { + at.push(len); + len += s.arclen(Self::ACCURACY); + } + at.push(len); + let boxes: Vec = segs.iter().map(|s| s.bounding_box().inflate(ON_SOURCE, ON_SOURCE)).collect(); + // Cells about as wide as an average segment's bounds. + let mean = boxes.iter().map(|b| b.width().max(b.height())).sum::() / boxes.len().max(1) as f64; + let cell = if mean.is_finite() { mean.max(4.0 * ON_SOURCE) } else { 4.0 * ON_SOURCE }; + let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + let mut wide = vec![]; + // The grid holds at most this many entries in all. + let mut budget = boxes.len().saturating_mul(Self::CELLS_PER_SEGMENT); + for (k, b) in boxes.iter().enumerate() { + let (x0, y0) = Self::cell_of(Point::new(b.x0, b.y0), cell); + let (x1, y1) = Self::cell_of(Point::new(b.x1, b.y1), cell); + let cells = x1.saturating_sub(x0).saturating_add(1).saturating_mul(y1.saturating_sub(y0).saturating_add(1)); + let Some(cells) = usize::try_from(cells).ok().filter(|&c| cells <= Self::MAX_CELLS && c <= budget) else { + wide.push(k); + continue; + }; + budget -= cells; + for x in x0..=x1 { + for y in y0..=y1 { + grid.entry((x, y)).or_default().push(k); + } + } + } + Self { segs, at, closed: sp.closed, cell, grid, wide } + } + + fn cell_of(p: Point, cell: f64) -> (i64, i64) { + ((p.x / cell).floor() as i64, (p.y / cell).floor() as i64) + } + + fn len(&self) -> f64 { + self.at.last().copied().unwrap_or(0.0) + } + + /// The lengths along the subpath to each of its segments' places nearest `p` that are within + /// [`ON_SOURCE`] of it (more than one where the subpath passes `p` again). + fn places(&self, p: Point) -> Vec { + use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; + let near = self.grid.get(&Self::cell_of(p, self.cell)).map(Vec::as_slice).unwrap_or_default(); + let mut out = vec![]; + for &k in near.iter().chain(&self.wide) { + let Some(s) = self.segs.get(k) else { continue }; + let n = s.nearest(p, 1e-9); + if n.distance_sq <= ON_SOURCE * ON_SOURCE { + out.push(self.at.get(k).copied().unwrap_or(0.0) + s.subsegment(0.0..n.t).arclen(Self::ACCURACY)); + } + } + out + } + + /// The signed length from `a` to `b` along the subpath (the shorter way round a closed one). + fn step(&self, a: f64, b: f64) -> f64 { + let (d, len) = (b - a, self.len()); + if self.closed && len > 0.0 { d - len * (d / len).round() } else { d } + } + + /// Of `places`, the one nearest along the subpath to `target`. + fn nearest(&self, places: &[f64], target: f64) -> Option { + places.iter().copied().min_by(|x, y| self.step(*x, target).abs().total_cmp(&self.step(*y, target).abs())) + } +} + +/// Where edge `edge` runs along its source path, whose subpaths' tracks are `tracks`: the length +/// along the source subpath to the edge's start, whether the edge starts at that subpath's start and +/// ends at its end (an open subpath), and whether it runs the whole subpath. The middle of the +/// edge's first segment places it, and its ends are taken where they lie that far along the source, +/// so a path that passes a point twice is told apart. An edge that runs against the direction of its +/// source is reversed first, and a closed edge as long as its closed source is started at the anchor +/// where its source starts (one with no anchor there, or a shorter loop cut from a source that +/// crosses itself, does not count as running the whole subpath). `None` when the edge is +/// not a single piece found on the source. +fn edge_run(tracks: &[Track], edge: &mut PathData) -> Option<(f64, bool, bool, bool)> { + use kurbo::{ParamCurve, ParamCurveArclen}; + let [sp] = edge.subpaths.as_slice() else { return None }; + if sp.segment_count() == 0 { + return None; + } + let (a, z) = (sp.anchors.first()?.p, if sp.closed { sp.anchors.first()?.p } else { sp.anchors.last()?.p }); + let first = sp.segment(0); + let mid = first.eval(0.5); + let half = first.subsegment(0.0..0.5).arclen(Track::ACCURACY); + let length = sp.anchor_arc_positions().last().copied().unwrap_or(0.0); + let edge_closed = sp.closed; + // (how far off the fit is, track, start, end, runs forward) for the subpath that fits best. + let mut found: Option<(f64, &Track, f64, f64, bool)> = None; + for track in tracks { + // The start lies half the first segment before its middle along the source, or after it + // when the edge runs the other way: take the place and way that fit best. + let starts_at = track.places(a); + let mut best: Option<(f64, f64, bool)> = None; + for pm in track.places(mid) { + for forward in [true, false] { + let Some(pa) = track.nearest(&starts_at, if forward { pm - half } else { pm + half }) else { continue }; + let miss = (if forward { track.step(pa, pm) } else { track.step(pm, pa) } - half).abs(); + if best.is_none_or(|(m, _, _)| miss < m) { + best = Some((miss, pa, forward)); + } + } + } + let Some((miss, pa, forward)) = best else { continue }; + let target = if forward { pa + length } else { pa - length }; + let Some(pz) = track.nearest(&track.places(z), target) else { continue }; + let miss = miss + track.step(pz, target).abs(); + if found.is_none_or(|(m, ..)| miss < m) { + found = Some((miss, track, pa, pz, forward)); + } + } + let (_, track, pa, pz, forward) = found?; + let (from, to) = if forward { (pa, pz) } else { (pz, pa) }; + if !forward { + edge.reverse(); + } + let open = !track.closed; + let starts = open && from <= ON_SOURCE; + let ends = open && to >= track.len() - ON_SOURCE; + if open { + return Some((from, starts, ends, starts && ends)); + } + // A closed edge runs the whole closed subpath, from the anchor the planar map starts it at. + // Start it at the anchor where the source starts, so settings that follow the path begin there. + let start = track.segs.first().map(|s| s.start())?; + let moved = edge_closed + && (length - track.len()).abs() <= ON_SOURCE.max(track.len() * 1e-4) + && edge.subpaths.first_mut().is_some_and(|sp| match sp.anchors.iter().position(|a| a.p.distance(start) <= ON_SOURCE) { + Some(k) => { + sp.anchors.rotate_left(k); + true + } + None => false, + }); + Some((if moved { 0.0 } else { from }, false, false, moved)) +} + +/// Fit stroke row `row` of a source path to an edge cut from it, which runs as [`edge_run`] says +/// (`None`: not known): its dashes go on from where the edge starts along the source, with the +/// lengths set and without the fit of dashes aligned to corners and path ends, its arrowheads stay only at the source's own ends, and its width profile and brush, which spread +/// over the whole path, stay only on an edge that runs the whole path. +fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) { + let AppearanceItem::Stroke(s) = row else { return }; + let (from, starts, ends, whole) = run.unwrap_or((0.0, false, false, false)); + if !whole { + if let Some(d) = &mut s.dash + && run.is_some() + { + d.offset += from; + d.align_corners = false; + } + s.profile = None; + s.brush = None; + } + if !starts { + s.start_arrow = None; + } + if !ends { + s.end_arrow = None; + } +} + /// The planar map's inputs from `sources` (paths and compound paths, back → front), with the -/// fill, stroke and stroke width of each. -fn source_shapes(sources: &[Arc]) -> (Vec, Vec<(Paint, Paint, f64)>) { +/// style of each. +fn source_shapes(sources: &[Arc]) -> (Vec, Vec) { let mut lv = vec![]; for n in sources { b::leaf_shapes(n, &mut lv); } let mut shapes = vec![]; - let mut styles: Vec<(Paint, Paint, f64)> = vec![]; + let mut styles: Vec = vec![]; for l in lv { if let Some((path, rule)) = b::node_outline(l) && !path.is_empty() { shapes.push(po::Shape::new(path, rule, styles.len() as u64)); - let a = &l.appearance; - styles.push((a.fill_paint(), a.stroke_paint(), a.stroke().map(|s| s.width).unwrap_or(1.0))); + styles.push(SourceStyle::of(l)); } } (shapes, styles) @@ -462,17 +714,35 @@ fn build_children(d: &mut Document, sources: Vec>, max_gap: Option> = HashMap::new(); for e in edges { - let Some((_, stroke, w)) = styles.get(e.key as usize) else { continue }; + let key = e.key as usize; + let Some(s) = styles.get(key) else { continue }; + let mut path = e.path; + let mut rows = s.strokes.clone(); + if rows.iter().any(depends_on_place) { + let source = tracks + .entry(key) + .or_insert_with(|| shapes.get(key).map(|src| src.path.subpaths.iter().map(Track::new).collect()).unwrap_or_default()); + let run = edge_run(source, &mut path); + for r in &mut rows { + fit_to_edge(r, run); + } + } let id = d.alloc_id(); - let mut n = Node::path(id, e.path, stroke_only(stroke.clone(), *w)); + let mut n = Node::path(id, path, stroke_only(Paint::None, s.width)); n.name = Some(EDGE_NAME.into()); + s.paint(&mut n, &rows); children.push(Arc::new(n)); } Ok((children, nfaces, nedges)) @@ -481,8 +751,9 @@ fn build_children(d: &mut Document, sources: Vec>, max_gap: Option = old.subpaths.iter().map(Track::new).collect(); + let run = n.path_data_mut().and_then(|path| edge_run(&tracks, path)); + let mut a = (*n.appearance).clone(); + for r in &mut a.items { + fit_to_edge(r, run); + } + n.appearance = a.into(); +} diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 1554ef7328..8dcd453650 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -1,8 +1,8 @@ use super::{ Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, - PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, - is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, - switch_or, + PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, + fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, + source_nodes, source_shapes, switch_or, }; /// `options` as stored on a Live Paint group: none for the defaults. @@ -85,6 +85,9 @@ pub(super) fn lp_make(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0, "faces": faces, "edges": edges })) } +/// How far, in points, the middle of an edge Merge makes may be from the old edge it lies on. +const ON_OLD_EDGE: f64 = 1e-3; + /// What Merge carries from a face or edge to the part it makes again in its place, another path: /// the appearance, visibility, opacity and blending mode. Gradients fitted to the old outline keep /// that fit, and the strokes' pen pressure, tilt, bearing and rotation stay behind. @@ -125,18 +128,11 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result .ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?; check_live_paint_takes(d, roots)?; let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?; - // Paint to carry over: (point inside face, paint) for faces that draw, and (point on edge, - // paint) for every edge. + // Paint to carry over: (point inside face, paint) for faces that draw; edges are matched to the + // old edges below. let keep_faces: Vec<(Point, Carried)> = b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect(); - let keep_edges: Vec<(Point, Carried)> = b::edges(&old) - .iter() - .filter_map(|e| { - let pd = e.path_data()?; - let sp = pd.subpaths.first().filter(|sp| sp.segment_count() > 0)?; - Some((kurbo::ParamCurve::eval(&sp.segment(0), 0.5), Carried::of(e))) - }) - .collect(); + let old_parts = old.clone(); let mut sources = source_nodes(&old); for r in roots { if *r != target { @@ -162,12 +158,24 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result carried.onto(Arc::make_mut(f)); } } - for (pt, carried) in keep_edges { - if let Some(eid) = edge_near(&g, pt, 0.5).map(|e| e.id) - && let Some(ch) = g.children_mut() - && let Some(e) = ch.iter_mut().find(|c| c.id == eid) - { - carried.onto(Arc::make_mut(e)); + // Each edge whose middle lies on an old edge, every piece of an edge an added path cuts + // included, takes the old edge's paint, with its rows fitted to its part of the old edge. + if let Some(ch) = g.children_mut() { + for c in ch.iter_mut().filter(|c| c.name.as_deref() == Some(EDGE_NAME)) { + let Some(mid) = c + .path_data() + .and_then(|pd| pd.subpaths.first()) + .filter(|sp| sp.segment_count() > 0) + .map(|sp| kurbo::ParamCurve::eval(&sp.segment(0), 0.5)) + else { + continue; + }; + let Some(was) = edge_near(&old_parts, mid, ON_OLD_EDGE) else { continue }; + let e = Arc::make_mut(c); + Carried::of(was).onto(e); + if let Some(outline) = was.path_data() { + fit_to_old_edge(e, outline); + } } } let mut merged = Beside::replacing(d, roots); @@ -363,9 +371,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 +451,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 +460,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 +521,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 +564,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/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 932ef1819a..a117bd453e 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -288,9 +288,10 @@ fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000); } 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 65672f8b6b..6aba8d4ca6 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()); @@ -718,7 +719,7 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result { /// sets its Warp style (`warpStyle`), its 3D type (`threeDType`) or visibility (`visible`), as one /// undo step. They are checked as `effect.apply` checks them, and a visible 3D effect must still /// fit; a hidden one has its given values checked. → `{ids}`. -fn set_params(s: &mut Session, p: &Value) -> Result { +pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.setParams"; let index = index_param(p, "index", C)?; let mut params = p.get("params").cloned().unwrap_or(Value::Null); @@ -740,6 +741,7 @@ 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)?; @@ -833,11 +835,13 @@ fn set_params(s: &mut Session, p: &Value) -> Result { const GLASS: &str = "distort.glass"; /// Effect › Texture › Texturizer. const TEXTURIZER: &str = "texture.texturizer"; +/// Effect › Artistic › Rough Pastels. +const ROUGH_PASTELS: &str = "artistic.roughPastels"; /// Does effect `id` have Load Texture: a `textureImage` that `effect.apply` reads from an image -/// file (Glass, Texturizer)? +/// file (Glass, Texturizer, Rough Pastels)? pub(crate) fn texture_load_effect(id: &str) -> bool { - id == GLASS || id == TEXTURIZER + id == GLASS || id == TEXTURIZER || id == ROUGH_PASTELS } /// Glass's `textureImage` in `params` as Glass stores it: an image file (`{path}`, or `{name?, 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.rs b/crates/engine/src/cmd/fileio.rs index 6995075d2f..6d972beda8 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -39,7 +39,7 @@ pub mod jxlread; mod legacy_ai; mod load; mod mesh3d; -pub(crate) use load::{MAX_RASTER_ALLOC, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, size_note}; mod heifread; mod hpgl; mod jp2read; diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 0bb18483cb..c823b8866f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -2,13 +2,13 @@ //! (unknown keys are ignored, so one params object can carry the options of several formats). use std::borrow::Cow; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use serde::Deserialize; use serde::de::DeserializeOwned; use serde_json::Value; -use vectorcraft_doc::{Artboard, Document, Node, NodeKind}; +use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SymbolOverride}; use vectorcraft_geom::Rect; use vectorcraft_render::AntiAlias; use vectorcraft_render::encode::jpeg::{self, JpegOptions}; @@ -450,31 +450,85 @@ pub fn export_art_bounds(doc: &Document, format: &str) -> Option { /// The bounds of the visible art of `doc` with the objects that `left_out` picks hidden /// ([`hidden_nodes`]) and the ones in the art of the symbols that instances show taken out /// ([`without_nodes`]: symbol art is measured with its hidden objects). An instance of a symbol -/// whose art is all picked or hidden is hidden too. The art of a dynamic symbol is measured whole: -/// an instance can paint its objects, and finds them by their places in the art. +/// whose art is all picked or hidden is hidden too. The drawn instances of a dynamic symbol that +/// make the same appearance changes to its art are measured on a copy of the symbol of their own, +/// in which each object is judged with those changes ([`as_drawn`]); the objects taken out of +/// a dynamic symbol's art leave empty groups in their places, by which instances find the objects +/// they change. fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option { - // The symbols instances show (the first of each name) that aren't dynamic. + // The symbols instances show (the first of each name). let mut names = HashSet::new(); - let shown: Vec<(usize, &vectorcraft_doc::Symbol)> = - doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).filter(|(_, s)| !s.dynamic).collect(); + let shown: Vec = doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).map(|(i, _)| i).collect(); + // The sets of appearance changes the drawn instances of each dynamic symbol make to its art; + // `None` for a symbol with more than `MAX_ART_COPIES`, which is measured whole. + let mut sets: HashMap<&str, Option>>> = + shown.iter().filter_map(|i| doc.symbols.get(*i)).filter(|s| s.dynamic).map(|s| (s.name.as_str(), Some(Vec::new()))).collect(); + if !sets.is_empty() { + let mut walked = HashSet::new(); + for l in &doc.layers { + drawn_changes(doc, l, left_out, true, &mut walked, &mut sets); + } + } + // Each set of changes gets a copy of its symbol, appended after the symbols, which the instances + // that make those changes show instead. + let variant = |symbol: &str, n: &Node| -> Option { + let k = sets.get(symbol)?.as_ref()?.iter().position(|c| *c == own_changes(n))?; + Some(format!("{symbol}\u{0}{k}")) + }; + let mut copies: Vec<(usize, &[&SymbolOverride])> = Vec::new(); + let remapped_doc = sets.values().flatten().any(|v| !v.is_empty()).then(|| { + let mut d = doc.clone(); + for l in &mut d.layers { + if let Some(n) = remapped(l, &variant) { + *l = n; + } + } + for s in &mut d.symbols { + if let Some(n) = remapped(&s.art, &variant) { + s.art = n; + } + } + for i in &shown { + let Some(s) = d.symbols.get(*i).cloned() else { continue }; + for (k, c) in sets.get(s.name.as_str()).into_iter().flatten().flatten().enumerate() { + copies.push((d.symbols.len(), c.as_slice())); + d.symbols.push(vectorcraft_doc::Symbol { name: format!("{}\u{0}{k}", s.name), ..s.clone() }); + } + } + d + }); + let src = remapped_doc.as_ref().unwrap_or(doc); + // The symbols to measure with the changes their instances make (`None` for a static symbol), + // without the dynamic symbols measured whole. + let entries: Vec<(usize, Option<&[&SymbolOverride]>)> = shown + .iter() + .filter_map(|i| src.symbols.get(*i).map(|s| (*i, s))) + .filter(|(_, s)| !s.dynamic || sets.get(s.name.as_str()).is_some_and(Option::is_some)) + .map(|(i, s)| (i, s.dynamic.then_some(&[][..]))) + .chain(copies.iter().map(|(i, c)| (*i, Some(*c)))) + .collect(); // The symbols whose art `left_out` leaves nothing of, those that only hold instances of such // symbols included. let mut empty: HashSet<&str> = HashSet::new(); - while let Some((_, s)) = shown.iter().find(|(_, s)| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty)) { + while let Some(s) = entries.iter().find_map(|(i, c)| { + src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty, *c, &mut Vec::new())) + }) { empty.insert(&s.name); } let left_out = &|n: &Node| left_out(n) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if empty.contains(symbol.as_str()) && !has_effects(n)); - let layers = hidden_nodes(&doc.layers, left_out); - let symbols: Vec<(usize, Arc)> = shown + let layers = hidden_nodes(&src.layers, left_out); + let symbols: Vec<(usize, Arc)> = entries .iter() - .filter(|(_, s)| !empty.contains(s.name.as_str())) - .filter_map(|(i, s)| without_nodes(&s.art, left_out).map(|art| (*i, art))) + .filter_map(|(i, c)| { + let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()))?; + without_nodes(&s.art, left_out, *c, &mut Vec::new()).map(|art| (*i, art)) + }) .collect(); if layers.is_none() && symbols.is_empty() { - return vectorcraft_render::encode::art_bounds(doc); + return vectorcraft_render::encode::art_bounds(src); } - let mut d = doc.clone(); + let mut d = remapped_doc.unwrap_or_else(|| doc.clone()); if let Some(layers) = layers { d.layers = layers; } @@ -486,22 +540,126 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option Vec<&SymbolOverride> { + n.extras().symbol_overrides.iter().filter(|o| !o.is_empty()).collect() +} + +/// `n` with each instance at any depth that `variant` gives another symbol (from the instance's +/// symbol and the instance) made an instance of that symbol; `None` when none is. +fn remapped(n: &Arc, variant: &dyn Fn(&str, &Node) -> Option) -> Option> { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + let name = variant(symbol, n)?; + let mut m = (**n).clone(); + if let NodeKind::SymbolInstance { symbol, .. } = &mut m.kind { + *symbol = name; + } + return Some(Arc::new(m)); + } + let children = n.children()?; + let mut out: Option>> = None; + for (i, c) in children.iter().enumerate() { + if let Some(new) = remapped(c, variant) + && let Some(slot) = out.get_or_insert_with(|| children.clone()).get_mut(i) + { + *slot = new; + } + } + out.map(|c| { + let mut m = (**n).clone(); + if let Some(children) = m.children_mut() { + *children = c; + } + Arc::new(m) + }) +} + /// Whether `n` is hidden, picked by `left_out`, an instance of one of the `empty` symbols, or a /// layer or a group holding only such objects (its clipping path among them when it clips). A /// Shaper group, or a layer, group or instance with effects, fills or strokes of its own, is none -/// of these unless it is hidden or picked. -fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>) -> bool { +/// of these unless it is hidden or picked. In the art of a dynamic symbol (`changed`, the changes +/// an instance makes to it; `n` is at place `at`), each object is judged with those changes +/// ([`as_drawn`]). +fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>, changed: Option<&[&SymbolOverride]>, at: &mut Vec) -> bool { + let m = as_drawn(n, changed, at); !n.visible - || left_out(n) - || !has_effects(n) + || left_out(&m) + || !has_effects(&m) && n.extras().shaper.is_none() && match &n.kind { - NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().all(|c| all_left_out(c, left_out, empty)), + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().enumerate().all(|(i, c)| { + at.push(i as u32); + let out = all_left_out(c, left_out, empty, changed, at); + at.pop(); + out + }), NodeKind::SymbolInstance { symbol, .. } => empty.contains(symbol.as_str()), _ => false, } } +/// Add the sets of appearance changes that the instances in `n` and its subtree make to the art of +/// the symbols `sets` names, each set once, and those of the instances in the art of the symbols the +/// instances show (`walked`, the symbols already looked in). The instances that `left_out` picks or +/// that are in an object it picks are left out, and with `hidden` (in a layer) the hidden ones and +/// those in a hidden object. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`. +fn drawn_changes<'a>( + doc: &'a Document, + n: &'a Node, + left_out: &dyn Fn(&Node) -> bool, + hidden: bool, + walked: &mut HashSet<&'a str>, + sets: &mut HashMap<&'a str, Option>>>, +) { + if hidden && !n.visible || left_out(n) { + return; + } + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + let changes = own_changes(n); + if let Some(entry) = sets.get_mut(symbol.as_str()) + && !changes.is_empty() + { + let full = match entry { + Some(list) if !list.contains(&changes) && list.len() < MAX_ART_COPIES => { + list.push(changes); + false + } + Some(list) => !list.contains(&changes), + None => false, + }; + if full { + *entry = None; + } + } + if walked.insert(symbol.as_str()) + && let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) + { + drawn_changes(doc, &s.art, left_out, false, walked, sets); + } + } + for c in n.children().into_iter().flatten() { + drawn_changes(doc, c, left_out, hidden, walked, sets); + } +} + +/// The most copies of one dynamic symbol's art [`bounds_without`] measures, one for each set of +/// appearance changes its instances make; a symbol whose instances make more sets is measured whole. +const MAX_ART_COPIES: usize = 64; + +/// `n`, the object at place `at` of a symbol's art, with the appearance changes `changed` that an +/// instance makes to it applied in their order; `n` itself for the art of a symbol that is not +/// dynamic (`changed` is `None`) and when no change names `at`. +fn as_drawn<'a>(n: &'a Node, changed: Option<&[&SymbolOverride]>, at: &[u32]) -> Cow<'a, Node> { + let here: Vec = + changed.into_iter().flatten().filter(|o| o.path == at).map(|o| SymbolOverride { path: Vec::new(), ..(*o).clone() }).collect(); + if here.is_empty() { + return Cow::Borrowed(n); + } + let mut m = n.clone(); + vectorcraft_doc::symbol_overrides::apply(&mut m, &here); + Cow::Owned(m) +} + /// Whether `n` has a visible effect, fill or stroke of its own, which the objects it holds can /// take part in. fn has_effects(n: &Node) -> bool { @@ -511,25 +669,32 @@ fn has_effects(n: &Node) -> bool { /// `n` without the objects that `left_out` picks in it, when it is a layer or a group, and in the /// layers and groups in it at any depth; `None` when it picks none of them. A clipping layer or /// group keeps its clipping path, its first object, and a Shaper group and a layer or group with -/// effects, fills or strokes of its own keep all they hold. -fn without_nodes(n: &Arc, left_out: &dyn Fn(&Node) -> bool) -> Option> { +/// effects, fills or strokes of its own keep all they hold. In the art of a dynamic symbol +/// (`changed`, the changes an instance makes to it, as for [`all_left_out`]; `n` is at place +/// `at`), each object is judged with those changes ([`as_drawn`]), and an object taken out leaves +/// an empty group in its place. +fn without_nodes(n: &Arc, left_out: &dyn Fn(&Node) -> bool, changed: Option<&[&SymbolOverride]>, at: &mut Vec) -> Option> { let (NodeKind::Layer { children, clip, .. } | NodeKind::Group { children, clip }) = &n.kind else { return None }; - if has_effects(n) || n.extras().shaper.is_some() { + if has_effects(&as_drawn(n, changed, at)) || n.extras().shaper.is_some() { return None; } - let mut changed = false; + let mut taken = false; let kept: Vec> = children .iter() .enumerate() .filter_map(|(i, c)| { - if left_out(c) && !(*clip && i == 0) { - changed = true; - return None; - } - Some(without_nodes(c, left_out).inspect(|_| changed = true).unwrap_or_else(|| c.clone())) + at.push(i as u32); + let out = if left_out(&as_drawn(c, changed, at)) && !(*clip && i == 0) { + taken = true; + changed.map(|_| Arc::new(Node::group(c.id, Vec::new()))) + } else { + Some(without_nodes(c, left_out, changed, at).inspect(|_| taken = true).unwrap_or_else(|| c.clone())) + }; + at.pop(); + out }) .collect(); - changed.then(|| { + taken.then(|| { let mut new = (**n).clone(); if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut new.kind { *children = kept; diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index ee33f64c41..60aace2351 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 @@ -1072,16 +1074,32 @@ pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { let layer = d.layers[0].id; let id = d.alloc_id(); let xf = Affine::scale_non_uniform(sx, sy); - let mut n = Node::new( + let n = Node::new( id, NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default(), pixels: None })), ); + let mut n = file_clipped(&mut d, n, psdread::clipping_path(bytes)); n.name = Some(name.to_string()); d.images.insert(key, blob); d.insert(Some(layer), 0, n).map_err(err)?; Ok(d) } +/// Image `image` of `d` clipped by `clip`, the clipping path its file names in the image's pixel +/// space (a PSD or PSB file's, [`psdread::clipping_path`]): a clip group of that path (even-odd, +/// with no paint) and the image. Without one the image stays as it is. +pub(crate) fn file_clipped(d: &mut Document, image: Node, clip: Option) -> Node { + let (Some(mut path), NodeKind::Image(im)) = (clip, &image.kind) else { return image }; + path.transform(im.xf); + let none = vectorcraft_color::Paint::None; + let mut clip = Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::basic(none.clone(), none, 0.0)); + if let NodeKind::Path { clipping, rule, .. } = &mut clip.kind { + *clipping = true; + *rule = vectorcraft_geom::FillRule::EvenOdd; + } + Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), std::sync::Arc::new(image)], clip: true }) +} + /// Does this import note say that the file has something the document doesn't? fn is_loss(note: &str) -> bool { note == vectorcraft_pdf::OFF_ARTBOARD_NOTE || vectorcraft_eps::is_loss(note) diff --git a/crates/engine/src/cmd/fileio/psdread.rs b/crates/engine/src/cmd/fileio/psdread.rs index 93e7b61f17..28b44d6197 100644 --- a/crates/engine/src/cmd/fileio/psdread.rs +++ b/crates/engine/src/cmd/fileio/psdread.rs @@ -2,7 +2,8 @@ //! File › Place (#918): the merged image, the flattened picture every PSD carries after its layers, //! as a linked PSD shows. Written from Adobe's public "Photoshop File Formats Specification" //! (). File › Open reads the -//! layers with [`super::psdlayers`], which shares this reader. +//! layers with [`super::psdlayers`], which shares this reader. The clipping path a document names +//! ([`clipping_path`]) clips its merged image where it opens or is placed. //! //! Every mode Photoshop saves a merged image in is read: Bitmap, Grayscale, Duotone (as its //! grayscale data), Indexed, RGB, CMYK and Lab, at 1, 8, 16 and 32 bits per channel, stored raw, @@ -14,6 +15,7 @@ use std::io::Read; use vectorcraft_color::cms::{Lab, lab::lab_to_srgb}; +use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath}; /// Photoshop's colour modes (the header's numbers), as far as the merged image is concerned. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -154,30 +156,113 @@ pub(super) fn header<'a>(r: &mut Reader<'a>) -> Result, String> { pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { let mut r = Reader::new(bytes); let h = header(&mut r).ok()?; - let mut r = Reader::new(h.resources); - while !r.rest().is_empty() { - r.take(4).ok()?; + let (_, _, data) = resources(h.resources, false).find(|(id, _, _)| *id == 0x03ed)?; + let mut d = Reader::new(data); + // Fixed 16.16 values, each with its unit (1: per inch, 2: per centimetre) and the unit the + // size is shown in. + let mut axis = || -> Option { + let v = f64::from(d.u32().ok()?) / 65536.0; + let unit = d.u16().ok()?; + d.u16().ok()?; + Some(if unit == 2 { v * 2.54 } else { v }) + }; + Some((axis()?, axis()?)) +} + +/// The image resource blocks of `resources`, in file order: each one's id, name (the bytes of its +/// Pascal string) and data. Stops at the first block that is cut short. With `signed`, only the +/// blocks whose signature is `8BIM` are given. +fn resources(resources: &[u8], signed: bool) -> impl Iterator { + let mut r = Reader::new(resources); + std::iter::from_fn(move || { + if r.rest().is_empty() { + return None; + } + let ours = r.take(4).ok()? == b"8BIM"; let id = r.u16().ok()?; // A Pascal string padded to an even size, length byte included. - let name = usize::from(r.u8().ok()?); - r.take(name + (name + 1) % 2).ok()?; + let len = usize::from(r.u8().ok()?); + let name = r.take(len).ok()?; + r.take((len + 1) % 2).ok()?; let size = usize::try_from(r.u32().ok()?).ok()?; let data = r.take(size).ok()?; r.take(size % 2).ok()?; - if id == 0x03ed { - let mut d = Reader::new(data); - // Fixed 16.16 values, each with its unit (1: per inch, 2: per centimetre) and the - // unit the size is shown in. - let mut axis = || -> Option { - let v = f64::from(d.u32().ok()?) / 65536.0; - let unit = d.u16().ok()?; - d.u16().ok()?; - Some(if unit == 2 { v * 2.54 } else { v }) - }; - return Some((axis()?, axis()?)); + Some((ours, id, name, data)) + }) + .filter(move |(ours, ..)| *ours || !signed) + .map(|(_, id, name, data)| (id, name, data)) +} + +/// The resource naming the document's clipping path. +const CLIPPING_PATH_NAME: u16 = 2999; + +/// The saved paths' resource ids. +const SAVED_PATHS: std::ops::RangeInclusive = 2000..=2997; + +/// The clipping path a PSD or PSB file names, in its pixel space (x across its width, y down +/// its height): the saved path (resources 2000 to 2997) whose name the clipping path resource +/// (2999) gives, both `8BIM` resources. `None` when the document names none, names a path it doesn't have, or that path +/// has no anchors or more records than [`vectorcraft_geom::path::MAX_READ_ANCHORS`]. Saved paths +/// use the even-odd rule. A path whose initial fill record says the fill starts with all pixels +/// begins with a subpath around the whole image, so its subpaths cut holes in it. +pub fn clipping_path(bytes: &[u8]) -> Option { + let mut r = Reader::new(bytes); + let h = header(&mut r).ok()?; + let (_, _, named) = resources(h.resources, true).find(|(id, _, _)| *id == CLIPPING_PATH_NAME)?; + // A Pascal string, then the flatness and a fill rule, which the specification says is ignored. + let len = usize::from(*named.first()?); + let name = named.get(1..1 + len)?; + let (_, _, data) = resources(h.resources, true).find(|(id, n, _)| SAVED_PATHS.contains(id) && *n == name)?; + // A path of more records than a document may hold anchors is left out before it is built. + if data.len() / PATH_RECORD > vectorcraft_geom::path::MAX_READ_ANCHORS { + return None; + } + let path = saved_path(data, f64::from(h.width), f64::from(h.height)); + (!path.is_empty()).then_some(path) +} + +/// One record of a saved path: a selector, then 24 bytes. +const PATH_RECORD: usize = 26; + +/// The saved path of path records `data`, scaled to an image `width` × `height` pixels. Knot +/// records come after their subpath's length record; one that comes before any, or past the knots +/// a length record counts, is left out, as is a last record cut short. +fn saved_path(data: &[u8], width: f64, height: f64) -> PathData { + // A path point: a vertical, then a horizontal signed 8.24 fixed-point fraction of the image's + // height and width. + let fixed = |b: [u8; 4]| f64::from(i32::from_be_bytes(b)) / f64::from(1 << 24); + let point = |[v0, v1, v2, v3, h0, h1, h2, h3]: [u8; 8]| Point::new(fixed([h0, h1, h2, h3]) * width, fixed([v0, v1, v2, v3]) * height); + let mut subpaths: Vec = vec![]; + let mut all_pixels = false; + // The knots the current subpath still takes. + let mut left = 0usize; + let (records, _) = data.as_chunks::(); + for &[s0, s1, ref body @ ..] in records { + let [c0, c1, ..] = *body; + let (points, _) = body.as_chunks::<8>(); + let [a, b, c] = [0, 1, 2].map(|i| points.get(i).copied().map_or(Point::ZERO, point)); + match u16::from_be_bytes([s0, s1]) { + sel @ (0 | 3) => { + left = usize::from(u16::from_be_bytes([c0, c1])); + // Anchors are added as knots come: a count can claim more than follow. + subpaths.push(SubPath::new(vec![], sel == 0)); + } + sel @ (1 | 2 | 4 | 5) if left > 0 => { + let Some(sp) = subpaths.last_mut() else { continue }; + left -= 1; + let kind = if matches!(sel, 1 | 4) { AnchorKind::Smooth } else { AnchorKind::Corner }; + sp.anchors.push(Anchor { h_in: a, p: b, h_out: c, kind }); + } + 8 => all_pixels = [c0, c1] == [0, 1], + _ => {} } } - None + subpaths.retain(|s| !s.anchors.is_empty()); + if all_pixels && !subpaths.is_empty() { + let all = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, width, height)); + subpaths.splice(0..0, all.subpaths); + } + PathData::new(subpaths) } /// Does the merged image keep its transparency in the first extra channel? Yes when the layer 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/fileio/tests_hpgl.rs b/crates/engine/src/cmd/fileio/tests_hpgl.rs index a7fe16690e..82957468d8 100644 --- a/crates/engine/src/cmd/fileio/tests_hpgl.rs +++ b/crates/engine/src/cmd/fileio/tests_hpgl.rs @@ -254,6 +254,90 @@ fn a_plot_of_the_arts_bounds_leaves_out_images_in_symbol_art() { } } +/// In the art of a dynamic symbol a placed image and a path that paints nothing are left out as +/// well, until an instance paints the path, and a document whose only other visible art is an +/// instance of a dynamic symbol of an image is refused. +#[test] +fn a_plot_of_the_arts_bounds_leaves_out_images_in_dynamic_symbol_art() { + let mut s = two_boards(); + let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v)); + let bounds = |s: &Session| super::export_art_bounds(&s.doc().unwrap().doc, "hpgl").unwrap(); + let same = |a: vectorcraft_geom::Rect, b: vectorcraft_geom::Rect| { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-6) + }; + let printing = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.new", &json!({})).unwrap(); + let mut png = vec![]; + image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone(); + let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].clone(); + let bare = s.execute("shape.rectangle", &json!({"x": 500, "y": -400, "width": 20, "height": 20})).unwrap()["id"].clone(); + s.execute("paint.setStroke", &json!({"ids": [bare], "none": true})).unwrap(); + let before = bounds(&s); + let inst = s.execute("symbol.new", &json!({"name": "Mixed", "ids": [image, square, bare], "type": "dynamic"})).unwrap()["id"].clone(); + let after = bounds(&s); + assert!(same(before, after), "{before:?} {after:?}"); + + // A change of the path's blending mode leaves it painting nothing; once the instance paints the + // path, the path is measured. + let art = s.doc().unwrap().doc.symbols[0].art.clone(); + let x0 = |c: &std::sync::Arc| c.visual_bounds().map_or(f64::MIN, |b| b.x0); + let at = (0..art.children().unwrap().len()).max_by(|a, b| x0(&art.children().unwrap()[*a]).total_cmp(&x0(&art.children().unwrap()[*b]))).unwrap(); + s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "blend": "multiply"})).unwrap(); + let blended = bounds(&s); + assert!(same(before, blended), "{before:?} {blended:?}"); + s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "stroke": "#000000"})).unwrap(); + let painted = bounds(&s); + assert!(painted.x1 > 500.0 && painted.y0 < -390.0, "{painted:?}"); + // A later change to the same object, as a file can hold, takes the paint off again. + { + let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap()); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let n = d.node_mut(id).unwrap(); + let mut overrides = n.extras().symbol_overrides.clone(); + overrides.push(vectorcraft_doc::SymbolOverride { path: vec![at as u32], opacity: Some(0.0), ..Default::default() }); + n.extras_mut().symbol_overrides = overrides.clone(); + let taken_off = bounds(&s); + assert!(same(before, taken_off), "{before:?} {taken_off:?}"); + overrides.pop(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(id).unwrap().extras_mut().symbol_overrides = overrides; + } + // Another instance, far above, that doesn't paint the path is measured without it, whether or + // not the first one paints it. + let other = s.execute("symbol.place", &json!({"name": "Mixed", "x": 0, "y": -5000})).unwrap()["id"].clone(); + let with_paint = bounds(&s); + s.execute("symbol.instance.reset", &json!({"ids": [inst]})).unwrap(); + let without_paint = bounds(&s); + assert!((with_paint.y0 - without_paint.y0).abs() < 1e-6, "{with_paint:?} {without_paint:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + let undone = bounds(&s); + assert!(same(undone, with_paint), "{undone:?} {with_paint:?}"); + s.execute("select.set", &json!({"ids": [other]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + + s.execute("select.set", &json!({"ids": [inst]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap(); + let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone(); + s.execute("symbol.new", &json!({"name": "Image", "ids": [image], "type": "dynamic"})).unwrap(); + let e = plot(&mut s).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); + + // An instance that brings a group at 0% opacity back to full opacity still draws nothing when + // the group holds only an image. + let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone(); + let group = s.execute("object.group", &json!({"ids": [image]})).unwrap()["id"].clone(); + s.execute("transparency.set", &json!({"ids": [group], "opacity": 0})).unwrap(); + let inst = s.execute("symbol.new", &json!({"name": "Clear", "ids": [group], "type": "dynamic"})).unwrap()["id"].clone(); + let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap()); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(id).unwrap().extras_mut().symbol_overrides = + [vec![], vec![0]].into_iter().map(|path| vectorcraft_doc::SymbolOverride { path, opacity: Some(1.0), ..Default::default() }).collect(); + let e = plot(&mut s).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); +} + /// A placed image with a Vector Halftone effect is measured when the effect makes dots, and left /// out when it would take more cells than the effect makes. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 08a46f0e10..4fe5f1e49b 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -1,9 +1,11 @@ //! Reading Photoshop documents (#918): the merged image of every colour mode, depth and -//! compression, PSB files, transparency, the resolution, and damaged files refused without a panic. +//! compression, PSB files, transparency, the resolution, the clipping path, and damaged files +//! refused without a panic. use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind}; -use super::psdread::{decode, is_psd, resolution}; +use super::psdread::{clipping_path, decode, is_psd, resolution}; use super::*; /// A Photoshop document built from its parts: `version` 1 (PSD) or 2 (PSB), the header's fields, @@ -260,6 +262,199 @@ fn pdd_files_open_and_place() { assert!(format_for_name("x.pdd").is_none() && writable_format(None, Some("x.pdd")).is_err(), "an export to .pdd is refused as before"); } +/// An image resource block: `8BIM`, `id`, `name` as a Pascal string padded to an even size, then +/// `data` padded to an even size. +fn resource(id: u16, name: &[u8], data: &[u8]) -> Vec { + let mut r = b"8BIM".to_vec(); + r.extend(id.to_be_bytes()); + r.push(name.len() as u8); + r.extend(name); + if name.len().is_multiple_of(2) { + r.push(0); + } + r.extend((data.len() as u32).to_be_bytes()); + r.extend(data); + if !data.len().is_multiple_of(2) { + r.push(0); + } + r +} + +/// A path point record's 8 bytes: `[x, y]` as fractions of the image's width and height, stored +/// vertical first as signed 8.24 fixed-point numbers. +fn point([x, y]: [f64; 2]) -> Vec { + [y, x].iter().flat_map(|v| ((v * f64::from(1 << 24)).round() as i32).to_be_bytes()).collect() +} + +/// A saved path's records: the fill rule record, an initial fill record saying whether the fill +/// starts with all pixels, then each subpath (closed or not) of corner knots without handles. +fn saved_path(all_pixels: bool, subpaths: &[(bool, &[[f64; 2]])]) -> Vec { + let record = |selector: u16, body: Vec| { + let mut r = selector.to_be_bytes().to_vec(); + r.extend(body); + r.resize(26, 0); + r + }; + let mut d = record(6, vec![]); + d.extend(record(8, vec![0, u8::from(all_pixels)])); + for (closed, knots) in subpaths { + d.extend(record(if *closed { 0 } else { 3 }, (knots.len() as u16).to_be_bytes().to_vec())); + for k in *knots { + d.extend(record(if *closed { 2 } else { 5 }, [point(*k), point(*k), point(*k)].concat())); + } + } + d +} + +/// The clipping path resource (2999) naming the saved path `name`, with a flatness of 0 and the +/// fill rule left as it is. +fn clipping_name(name: &[u8]) -> Vec { + let mut d = vec![name.len() as u8]; + d.extend(name); + d.extend([0; 6]); + resource(2999, b"", &d) +} + +/// A 100 × 50 pixel red RGB document with `resources`, flat or with a layer count of 0. +fn red_psd(resources: &[u8]) -> Vec { + psd(1, 3, (100, 50), 8, 3, &[], resources, &[], &raw(&[&[255; 5000], &[0; 5000], &[0; 5000]])) +} + +/// The triangle saved as "Outline", another path saved as "Other", and the clipping path naming +/// "Outline". +fn triangle_resources() -> Vec { + let other = saved_path(false, &[(true, &[[0.0, 0.0], [0.1, 0.0], [0.1, 0.1]])]); + let outline = saved_path(false, &[(true, &[[0.5, 0.0], [1.0, 1.0], [0.0, 1.0]])]); + [resource(2000, b"Other", &other), resource(2001, b"Outline", &outline), clipping_name(b"Outline")].concat() +} + +/// The clip group a PSD file comes in as: its clipping path's anchors (pt), whether that path +/// uses the even-odd rule, and the image it clips. +fn clip_group(d: &Document, id: NodeId) -> (Vec<[f64; 2]>, bool, NodeId) { + let Some(NodeKind::Group { children, clip: true }) = d.node(id).map(|n| &n.kind) else { panic!("not a clip group: {:?}", d.node(id)) }; + let [path, image] = &children[..] else { panic!("{} children", children.len()) }; + let NodeKind::Path { path: p, rule, clipping: true, .. } = &path.kind else { panic!("not a clipping path") }; + assert!(matches!(image.kind, NodeKind::Image(_))); + let anchors = p.anchors().map(|(_, _, a)| [a.p.x, a.p.y]).collect(); + (anchors, *rule == vectorcraft_geom::FillRule::EvenOdd, image.id) +} + +#[test] +fn the_clipping_path_clips_the_merged_image_on_place_and_open() { + let f = red_psd(&triangle_resources()); + let triangle = vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]]; + let data = vectorcraft_format::base64_encode(&f); + // Place: one clip group of the named path, not the other, at 100 % (72 ppi: a pixel a point). + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let (anchors, even_odd, image) = clip_group(&s.doc().unwrap().doc, id); + assert_eq!((anchors, even_odd), (triangle.clone(), true)); + assert_eq!(r["image"], image.0, "{r}"); + assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(100.0), Some(50.0))); + // Open with layers off, and a flat file opened with layers on, as its merged image. + for params in [json!({"layers": false}), json!({})] { + s.execute("document.open", &merge(json!({"name": "cut.psd", "dataBase64": data}), params.clone())).unwrap(); + let d = &s.doc().unwrap().doc; + let top = d.layers[0].children().unwrap(); + assert_eq!(top.len(), 1, "{params}"); + assert_eq!(top[0].name.as_deref(), Some("cut.psd"), "{params}"); + let group = top[0].id; + let (anchors, even_odd, _) = clip_group(d, group); + assert_eq!((anchors, even_odd), (triangle.clone(), true), "{params}"); + // The corner outside the triangle draws nothing; its middle draws red. + let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8(); + assert_eq!((png.get_pixel(2, 2).0[3], png.get_pixel(50, 40).0), (0, [255, 0, 0, 255]), "{params}"); + // The clipping path is an ordinary path: releasing the clipping mask leaves the image whole. + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.clippingMask.release", &json!({})).unwrap(); + let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8(); + assert_eq!(png.get_pixel(2, 2).0, [255, 0, 0, 255], "{params}"); + } +} + +/// Replace keeps a clipped PSD file's scale, as it keeps an image's. +#[test] +fn replacing_a_clipped_psd_keeps_its_scale() { + let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [200, 200]})).unwrap(); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "replace": true})).unwrap(); + assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(200.0), Some(100.0)), "{r}"); + let (anchors, _, _) = clip_group(&s.doc().unwrap().doc, NodeId(r["ids"][0].as_u64().unwrap())); + assert_eq!(anchors, [[200.0, 150.0], [300.0, 250.0], [100.0, 250.0]]); + // Other art replacing the clip group takes its centre only, as before. + let plain = vectorcraft_format::base64_encode(&red_psd(&[])); + let r = s.execute("file.place", &json!({"name": "plain.psd", "dataBase64": plain, "replace": true})).unwrap(); + assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(100.0), Some(50.0)), "{r}"); +} + +#[test] +fn a_fill_that_starts_with_all_pixels_puts_the_image_around_the_path() { + let hole = saved_path(true, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]); + let f = red_psd(&[resource(2000, b"Hole", &hole), clipping_name(b"Hole")].concat()); + let path = clipping_path(&f).unwrap(); + let starts: Vec<_> = path.subpaths.iter().map(|s| (s.anchors[0].p.x, s.anchors[0].p.y, s.closed)).collect(); + assert_eq!(starts, [(0.0, 0.0, true), (25.0, 12.5, true)], "the image's edges, then the hole"); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "hole.psd", "dataBase64": vectorcraft_format::base64_encode(&f), "layers": false})).unwrap(); + let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8(); + assert_eq!((png.get_pixel(2, 2).0, png.get_pixel(50, 25).0[3]), ([255, 0, 0, 255], 0)); +} + +#[test] +fn files_naming_no_clipping_path_or_a_missing_one_place_a_plain_image() { + let other = saved_path(false, &[(true, &[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]])]); + let empty = saved_path(false, &[]); + for (resources, what) in [ + (resource(2000, b"Other", &other), "saved paths, none named"), + ([resource(2000, b"Other", &other), clipping_name(b"Gone")].concat(), "a name no path has"), + ([resource(2000, b"Empty", &empty), clipping_name(b"Empty")].concat(), "a path with no knots"), + ([resource(3000, b"Other", &other), clipping_name(b"Other")].concat(), "a resource outside the saved paths"), + ([resource(2000, b"Other", &other), [&b"MeSa"[..], &clipping_name(b"Other")[4..]].concat()].concat(), "a block not signed 8BIM"), + (vec![], "no resources"), + ] { + let f = red_psd(&resources); + assert!(clipping_path(&f).is_none(), "{what}"); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("file.place", &json!({"name": "a.psd", "dataBase64": vectorcraft_format::base64_encode(&f)})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + assert!(matches!(s.doc().unwrap().doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(_))), "{what}"); + assert!(r.get("image").is_none(), "{what}: {r}"); + } +} + +#[test] +fn damaged_clipping_paths_are_read_without_a_panic() { + let good = red_psd(&triangle_resources()); + assert!(clipping_path(&good).is_some()); + // The header, the empty colour mode data, then the resources' length and the resources. + let start = 26 + 4; + let end = start + 4 + triangle_resources().len(); + for n in 0..end + 2 { + let _ = clipping_path(&good[..n]); + } + for i in start..end { + for v in [0, 1, 0x7f, 0x80, 0xff] { + let mut f = good.clone(); + f[i] = v; + let _ = clipping_path(&f); + } + } + // Knots before any length record, and more knots than a length record counts, are left out. + let mut extra = saved_path(false, &[(true, &[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]])]); + extra[26 * 2 + 3] = 2; + let mut stray = 2u16.to_be_bytes().to_vec(); + stray.resize(26, 0); + extra.splice(26..26, stray); + let path = clipping_path(&red_psd(&[resource(2000, b"P", &extra), clipping_name(b"P")].concat())).unwrap(); + assert_eq!(path.subpaths.iter().map(|s| s.anchors.len()).collect::>(), [2]); +} + #[test] fn damaged_and_unsupported_files_are_refused_without_a_panic() { let good = psd(2, 4, (3, 2), 8, 3, &[], &[], &layer_count(-1, true), &raw(&[&[1; 6], &[2; 6], &[3; 6], &[4; 6]])); 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/edit.rs b/crates/engine/src/cmd/graph/edit.rs index e1c5c336b3..77ce7a7b2a 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -1,4 +1,4 @@ -use vectorcraft_doc::graph::art_bounds; +use vectorcraft_doc::graph::graph_art_without_type as art_bounds; use super::axis::{MAX_TICK_MARKS, count_given, one_line}; use super::data::apply_data; @@ -21,12 +21,16 @@ fn bound_param(p: &Value, key: &str, cmd: &str) -> Result>> { /// The bounds a redraw of graph `n` measures a move or scale on, as kept at the last generation and as they are now: /// those of its art without type ([`GraphSpec::placed_art`]), or those of all its art when the graph keeps no such -/// bounds with a width and a height, or has no art without type now. +/// bounds with a width and a height. `None` when the art measured has no width or no height now, or the graph keeps +/// bounds of its art without type and has no such art now. fn measured(n: &Node) -> Option<(Rect, Rect)> { let kept = n.extras().graph.as_deref()?; let c = n.children()?; - let art = kept.placed_art.filter(|p| p.width() > 1e-9 && p.height() > 1e-9).zip(art_bounds(c)); - art.or_else(|| kept.placed.zip(children_bounds(c))) + let solid = |r: &Rect| r.width() > 1e-9 && r.height() > 1e-9; + match kept.placed_art.filter(solid) { + Some(placed) => art_bounds(c).filter(solid).map(|now| (placed, now)), + None => kept.placed.zip(children_bounds(c).filter(solid)), + } } /// `r` carried by the change from bounds `from` to bounds `to`: each edge stays at the same place relative to them. @@ -39,14 +43,28 @@ fn carried(r: Rect, from: Rect, to: Rect) -> Option { Some(Rect::new(to.x0 + (r.x0 - from.x0) * sx, to.y0 + (r.y0 - from.y0) * sy, to.x0 + (r.x1 - from.x0) * sx, to.y0 + (r.y1 - from.y0) * sy)) } -/// The graphs holding objects `ids`, each with the bounds of its art without type and of all its art. Give them to -/// [`keep_placed`] after an edit that changes a graph's art without moving the graph. +/// The graphs holding objects `ids`, that are among them or that are inside them, each with the bounds of its art +/// without type and of all its art. Give them to [`keep_placed`] after an edit that changes a graph's art without +/// moving the graph. pub(crate) fn graphs_holding(d: &Document, ids: &[NodeId]) -> Vec<(NodeId, Option, Option)> { - let mut out: Vec<(NodeId, Option, Option)> = vec![]; + let is_graph = |n: &Node| n.extras().graph.is_some(); + let mut found: Vec = vec![]; for id in ids { let Some(chain) = d.ancestry(*id) else { continue }; - let holder = chain.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(|n| n.extras().graph.is_some())); - let Some(gid) = holder.filter(|g| !out.iter().any(|(o, ..)| o == g)) else { continue }; + found.extend(chain.iter().rev().copied().find(|a| d.node(*a).is_some_and(is_graph))); + if let Some(n) = d.node(*id) { + n.walk(&mut |c| { + if is_graph(c) { + found.push(c.id); + } + }); + } + } + let mut out: Vec<(NodeId, Option, Option)> = vec![]; + for gid in found { + if out.iter().any(|(o, ..)| *o == gid) { + continue; + } let children = d.node(gid).and_then(Node::children); out.push((gid, children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c)))); } 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 a66bb34c27..b228341190 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -5977,6 +5977,141 @@ fn outlining_a_graphs_labels_leaves_the_plot_in_place() { let moved = spec(&s, id).rect; assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 15.0)).abs() < 1e-6, "{moved:?}"); assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}"); + // A scale of the graph made before outlining is still followed. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.scale", &json!({"sx": 150, "sy": 50, "origin": [moved.x0, moved.y0]})).unwrap(); + s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q3").0]})).unwrap(); + s.execute("type.createOutlines", &json!({})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let scaled = spec(&s, id).rect; + assert!((scaled.x0 - moved.x0).abs() < 1e-6 && (scaled.y0 - moved.y0).abs() < 1e-6, "{scaled:?}"); + assert!((scaled.width() - 1.5 * rect.width()).abs() < 1e-6 && (scaled.height() - 0.5 * rect.height()).abs() < 1e-6, "{scaled:?}"); +} + +/// Outline Stroke on a graph's strokes leaves the plot where it is when the graph is drawn again, and a move of the +/// graph made before it is still followed. +#[test] +fn outlining_a_graphs_strokes_leaves_the_plot_in_place() { + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 20, "dy": 10})).unwrap(); + s.execute("object.path.outlineStroke", &json!({})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 20.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 10.0)).abs() < 1e-6, "{moved:?}"); + assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}"); +} + +/// A graph left with only its labels, or with its labels and one vertical line, leaves the plot where it is when it is +/// drawn again after a label edit. +#[test] +fn a_graph_left_with_only_its_labels_leaves_the_plot_in_place() { + for keep_a_line in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + let (mut art, mut line) = (vec![], None); + s.doc().unwrap().doc.node(id).unwrap().walk(&mut |n| { + if n.children().is_none() && !matches!(n.kind, NodeKind::Text(_)) { + let vertical = n.geometric_bounds().is_some_and(|b| b.width() < 1e-9 && b.height() > 1.0); + if keep_a_line && vertical && line.is_none() { + line = n.geometric_bounds(); + } else { + art.push(n.id.0); + } + } + }); + assert!(!art.is_empty() && line.is_some() == keep_a_line); + s.execute("select.set", &json!({"ids": art})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let left = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert_eq!(vectorcraft_doc::graph::graph_art_without_type(left.children().unwrap()), line, "{:#?}", left.children()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": 20})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert_eq!(spec(&s, id).rect, rect, "keeping a line: {keep_a_line}"); + } +} + +/// A graph saved without the bounds of its art without type, left with one vertical line, keeps its plot's size when +/// it is drawn again. +#[test] +fn a_graph_saved_with_only_its_whole_bounds_and_left_with_a_line_keeps_its_plot() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + let mut old = spec(&s, id); + old.placed_art = None; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(old)); + let (mut art, mut line) = (vec![], None); + s.doc().unwrap().doc.node(id).unwrap().walk(&mut |n| { + if n.children().is_none() { + let vertical = !matches!(n.kind, NodeKind::Text(_)) && n.geometric_bounds().is_some_and(|b| b.width() < 1e-9 && b.height() > 1.0); + if vertical && line.is_none() { + line = Some(n.id); + } else { + art.push(n.id.0); + } + } + }); + assert!(line.is_some()); + s.execute("select.set", &json!({"ids": art})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert_eq!(spec(&s, id).rect, rect); +} + +/// The bounds a graph measures moves on take a clipping group holding type at the bounds of its clip, so art outside the +/// clip does not change them; a clipping group whose clip is type is measured on its other art. +#[test] +fn a_clipping_group_holding_type_is_measured_on_its_clip() { + use std::sync::Arc; + use vectorcraft_doc::graph::graph_art_without_type as measure; + use vectorcraft_geom::Affine; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let label: Arc = + group(&n, "Legend").children().unwrap().iter().find(|c| matches!(c.kind, NodeKind::Text(_))).unwrap().clone(); + let mut paths = vec![]; + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { .. }) { + paths.push(c.clone()); + } + }); + let (clip, art) = (Arc::new(paths[0].clone()), paths[1].clone()); + let clipped = |dx: f64, first: Arc, second: Arc| { + let mut far = art.clone(); + far.transform(Affine::translate((dx, 0.0)), false); + let mut g = vectorcraft_doc::Node::group(NodeId(999_999), vec![first, second, Arc::new(far)]); + if let NodeKind::Group { clip, .. } = &mut g.kind { + *clip = true; + } + measure(&[Arc::new(g)]) + }; + assert_eq!(clipped(500.0, clip.clone(), label.clone()), clip.geometric_bounds()); + assert_eq!(clipped(500.0, clip.clone(), label.clone()), clipped(900.0, clip.clone(), label.clone())); + // A clip that is type leaves the other art to measure. + assert_ne!(clipped(500.0, label.clone(), clip.clone()), clipped(900.0, label.clone(), clip.clone())); + // A clip that is a clipping group holding type in its clipped art is measured on its own clip. + let mut inner = vectorcraft_doc::Node::group(NodeId(999_998), vec![clip.clone(), label.clone()]); + if let NodeKind::Group { clip, .. } = &mut inner.kind { + *clip = true; + } + let inner = Arc::new(inner); + assert_eq!(clipped(500.0, inner.clone(), label.clone()), clip.geometric_bounds()); + assert_eq!(clipped(500.0, inner.clone(), label.clone()), clipped(900.0, inner.clone(), label.clone())); + // A blend holding type is measured whole, as it is drawn. + let blend = vectorcraft_doc::Node::new(NodeId(999_997), NodeKind::Blend { children: vec![clip.clone(), label.clone()], spec: Box::default() }); + assert_eq!(measure(&[Arc::new(blend.clone())]), blend.geometric_bounds()); } /// A graph whose kept bounds of its art without type have no width follows a move with the bounds of all of its art. @@ -7007,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(); @@ -7200,8 +7372,8 @@ fn graph_commands_refuse_params_of_the_wrong_type() { } /// A `.ai` in PostScript form whose graph's records read whole (version 7 specification, appendix A) -/// opens as a graph whose data can be edited: Graph Data redraws it on its plot. Saving it as `.ai` -/// says its data and settings aren't written, in either form. +/// opens as a graph whose data can be edited: Graph Data redraws it on its plot. Saving it as `.ai`, +/// in either form, writes its records, and the file opens again with the graph's new data. #[test] fn a_graph_opened_from_ai_keeps_its_data_for_editing() { let graph = "%_Gs\n%_100 200 300 100 Gb\n%_5 0 0 14 0 1 0 0 6 44 Gy\n%_10 2 0 0 90 80 0 Gd\n\ @@ -7258,10 +7430,60 @@ fn a_graph_opened_from_ai_keeps_its_data_for_editing() { } let r = s.execute("file.saveAs", &p).unwrap(); let notes = r["warnings"].as_array().cloned().unwrap_or_default(); - assert!(notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}"); + assert!(!notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}"); + let mut again = Session::new(); + again.execute("document.open", &json!({"path": dir.join(name)})).unwrap(); + let mut graphs = vec![]; + again.doc().unwrap().doc.walk(|n| graphs.extend(n.extras().graph.as_deref().cloned())); + assert_eq!(graphs.len(), 1, "{name}"); + let g = &graphs[0]; + assert_eq!( + (g.series.as_slice(), g.categories.as_slice(), g.rows.as_slice()), + (&after.series[..], &after.categories[..], &after.rows[..]), + "{name}" + ); + assert_eq!(g.kind, after.kind, "{name}"); } } +/// A graph the graph tools draw, of each type, saved as `.ai` in either form, opens again as the same +/// graph exactly when the save gives no warning about graphs; a column graph does. +#[test] +fn a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns() { + let dir = vectorcraft_testkit::temp_dir("graph-ai-save"); + let mut live = vec![]; + for ty in ["column", "stackedColumn", "bar", "stackedBar", "line", "area", "scatter", "pie", "radar"] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6"; + let id = s.execute("graph.create", &json!({"type": ty, "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(); + let written = spec(&s, NodeId(id)); + for (name, version) in [("v7.ai", Some("7")), ("pdf.ai", None)] { + let path = dir.join(format!("{ty}-{name}")); + let mut p = json!({"path": path, "format": "ai"}); + if let Some(v) = version { + p["aiVersion"] = json!(v); + } + let r = s.execute("file.saveAs", &p).unwrap(); + let notes = r["warnings"].as_array().cloned().unwrap_or_default(); + let warned = notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))); + let mut again = Session::new(); + again.execute("document.open", &json!({"path": path})).unwrap(); + let mut graphs = vec![]; + again.doc().unwrap().doc.walk(|n| graphs.extend(n.extras().graph.as_deref().cloned())); + assert_eq!(graphs.len(), usize::from(!warned), "{ty} {name}: {r}"); + if let Some(g) = graphs.first() { + assert_eq!((g.kind, g.cells()), (written.kind, written.cells()), "{ty} {name}"); + assert_eq!((g.series.as_slice(), g.categories.as_slice()), (&written.series[..], &written.categories[..]), "{ty} {name}"); + live.push(format!("{ty} {name}")); + } + } + } + assert!(live.contains(&"column v7.ai".to_string()) && live.contains(&"column pdf.ai".to_string()), "{live:?}"); +} + /// A graph opened from a `.ai` keeps the bounds of its art without type, so moving one of its labels on its own /// leaves the plot where it is at the first redraw. #[test] @@ -7294,9 +7516,17 @@ fn a_graph_opened_from_ai_measures_moves_without_its_labels() { assert_eq!((graphs.len(), labels.len()), (1, 1)); let (id, label) = (graphs[0], labels[0]); let before = spec(&s, id); - assert!(before.placed_art.is_some()); s.execute("select.set", &json!({"ids": [label.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": 30})).unwrap(); s.execute("object.move", &json!({"dx": 80, "dy": -40})).unwrap(); s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap(); - assert_eq!(spec(&s, id).rect, before.rect); + let rect = spec(&s, id).rect; + assert_eq!(rect, before.rect, "after restyling and moving a label"); + // A move of the whole opened graph is still followed. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 15, "dy": 25})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 15.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 25.0)).abs() < 1e-6, "{moved:?}"); + assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}"); } diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index b86f260cd8..b8c4199623 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Scale…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), sx: %, sy?: %, origin?: [x,y], copy?, strokes?: bool (Scale Strokes & Effects: stroke weights, dashes and effect distances scale; off keeps them, type strokes included), corners?: bool (Scale Corners: live corner radii scale), objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)} (strokes/corners default to the preferences). With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), sx: % (along the bounding box's width), sy?: % (along its height), origin?: [x,y] (a page point), basis?: \"box\"|\"page\" (box, the default: sx and sy follow the bounding box, turned with rotated objects until Reset Bounding Box; page: the page's axes; a saved step without basis, recorded before it, plays along the page's axes), copy?, strokes?: bool (Scale Strokes & Effects: stroke weights, dashes and effect distances scale; off keeps them, type strokes included), corners?: bool (Scale Corners: live corner radii scale), objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)} (strokes/corners default to the preferences). With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, scale ), @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "Reflect…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical; vertical and horizontal are the bounding box's own axes, deg a line on the page), origin?, basis?: \"box\"|\"page\" (for a named axis; box, the default: the bounding box's axes, turned with rotated objects until Reset Bounding Box; page: the page's axes; a saved step without basis, recorded before it, plays along the page's axes), copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, reflect ), diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index d102068947..88362d7c49 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -1,7 +1,7 @@ use super::align::choice; use super::{ - Affine, Arc, Document, EngineError, LastTransform, Node, NodeId, NodeKind, Point, Result, Scaling, Session, Value, Vec2, bad, bool_or, - check_numbers, check_switches, duplicate_in, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param, + Affine, Arc, Document, EngineError, LastTransform, Node, NodeId, NodeKind, OrientedBox, Point, Rect, Result, Scaling, Session, Value, Vec2, bad, + bool_or, check_numbers, check_switches, duplicate_in, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param, selected_roots_to_transform, }; @@ -358,26 +358,52 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result { if sx == 0.0 || sy == 0.0 { return Err(bad("object.scale", "scale must be non-zero")); } - apply_transform(s, "Scale", ids, about(o, Affine::scale_non_uniform(sx, sy)), p, true) + let frame = basis_frame(s, p, "object.scale", &ids)?; + apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true) +} + +/// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param: +/// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset +/// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with +/// Direct Selection (with no copy and Transform Objects on) transform along the page's axes, as +/// their own box does. The basis joins the journal entry, so a replay acts in the same frame. A +/// saved step without `basis` ([`Session::replay`]) was recorded before Scale and Reflect followed +/// the box, so it acts along the page's axes, as it did when it was recorded. +fn basis_frame(s: &mut Session, p: &Value, cmd: &str, ids: &[NodeId]) -> Result { + let basis = choice(p, cmd, "basis", &["box", "page"])?; + let page = basis == Some("page") || (basis.is_none() && s.replaying()); + let st = s.doc()?; + let anchors = !bool_or(p, "copy", false) + && transforms_objects(p) + && effects::preview::anchor_bounds_with(&st.selection, &st.doc, s.bounds_measure()).is_some(); + let angle = if page || anchors { 0.0 } else { st.doc.bbox_angle(ids) }; + s.note_journal("basis", json!(if page { "page" } else { "box" })); + Ok(OrientedBox { angle, rect: Rect::ZERO }) } pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.reflect")?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let m = match p.get("axis") { - Some(Value::String(a)) if a == "horizontal" => Affine::scale_non_uniform(1.0, -1.0), - Some(Value::Number(n)) => { - let t = -n.as_f64().unwrap_or(90.0).to_radians(); - Affine::rotate(t) * Affine::scale_non_uniform(1.0, -1.0) * Affine::rotate(-t) - } - None | Some(Value::Null) => Affine::scale_non_uniform(-1.0, 1.0), - Some(Value::String(a)) if a == "vertical" => Affine::scale_non_uniform(-1.0, 1.0), + // A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page. + let named = match p.get("axis") { + Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)), + Some(Value::Number(_)) => None, + None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)), + Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)), Some(v) => { let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))); } }; + let m = match named { + Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m), + None => { + choice(p, "object.reflect", "basis", &["box", "page"])?; + let t = -p.get("axis").and_then(Value::as_f64).unwrap_or(90.0).to_radians(); + Affine::rotate(t) * Affine::scale_non_uniform(1.0, -1.0) * Affine::rotate(-t) + } + }; apply_transform(s, "Reflect", ids, about(o, m), p, true) } diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index c6cb4d987d..fa0492c2db 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -617,6 +617,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "standardVerticalRoman", "noBreak", "digits", + "glyphForm", "fontHeightReference", "language", "fontAxes", @@ -651,6 +652,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let char_align = super::textedit::char_align_param(p, C)?; let char_direction = super::textedit::char_direction_param(p, C)?; let digits = super::textedit::digits_param(p, C)?; + let glyph_form = super::textedit::glyph_form_param(p, C)?; let language = super::textedit::language_param(p, C)?; let font_axes = super::textedit::font_axes_param(p, C)?; let font_height_reference = super::textedit::font_height_reference_param(p, C)?; @@ -821,6 +823,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = digits { st.digits = v; } + if let Some(v) = glyph_form { + st.glyph_form = v; + } if let Some(v) = &language { st.language.clone_from(v); } diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 4bb6bcba1d..db1edc98e9 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 @@ -423,9 +424,9 @@ fn check_effect_types(id: &str, effect: &str, params: &Value) -> Result<()> { /// A value of the type effect `effect` reads for `key`, a parameter its params description names /// without a dialog default: the earlier 3D Perspective and light (`perspective`, `lightAzimuth`, /// `lightElevation`) and Scribble `variation` are numbers, an Outline Stroke's `width` is a number -/// and a Gaussian Blur's `linear` is true or false. A Glass or Texturizer `textureImage`, an SVG -/// filter's `name` and `xml`, a Warp's `version` and the `style` of Crop Marks have checks of their -/// own; they aren't listed. +/// and a Gaussian Blur's `linear` is true or false. A Glass, Texturizer or Rough Pastels +/// `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version` and the `style` of Crop +/// Marks have checks of their own; they aren't listed. pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option { use vectorcraft_render::effects; let number = || Some(Value::from(0.0)); @@ -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/pathops.rs b/crates/engine/src/cmd/pathops.rs index 878b3743cf..b5267fa990 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -1188,6 +1188,8 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result { let roots = selected_roots(s)?; let ids = s.edit("Outline Stroke", |d, sel| { let before = d.clone(); + // Outlining the strokes in a graph does not move or scale its plot at the next redraw. + let graphs = super::graph::graphs_holding(d, &roots); // A dimension selected with the art it measures keeps its own lines: it is out of the // document while the art is outlined. let lifted = super::dimension::lift(d, &roots); @@ -1207,6 +1209,7 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result { if changed == 0 || (kept && d.layers == before.layers) { return Err(EngineError::Other("Outline Stroke: no stroked paths selected".into())); } + super::graph::keep_placed(d, &graphs); sel.set(new_sel.iter().copied()); Ok(new_sel) })?; diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index dc95f925b6..8c9a19cb8d 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -75,7 +75,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file placed in a clip group, which the Links commands take}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -113,7 +113,9 @@ pub fn specs() -> Vec { /// A file's art at its natural size, before it joins a document. enum Art { - Image(RasterImage), + /// An image, with the clipping path its file names, in its pixel space (a PSD or PSB file's, + /// [`fileio::psdread::clipping_path`]). + Image(RasterImage, Option), /// A text file's, an RTF file's or a Word document's text, placed as area type filling the /// natural box. Text(text::Story), @@ -241,7 +243,8 @@ fn load(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result(nodes: impl Iterator>) -> Vec { /// The art as one object of `d` (its resources added), at its natural size and position. fn build(d: &mut Document, l: Loaded, link: Option) -> Node { let mut node = match l.art { - Art::Image(img) => { + Art::Image(img, clip) => { let (sx, sy) = pt_per_px(img.ppi); super::links::store_image(d, &img.key, img.blob, link.is_some()); let im = ImageObject { @@ -423,7 +426,8 @@ fn build(d: &mut Document, l: Loaded, link: Option) -> Node { placement: Default::default(), pixels: None, }; - Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))) + let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + fileio::file_clipped(d, image, clip) } Art::Dcs(a) => { let a = *a; @@ -485,9 +489,23 @@ fn at_param(p: &Value) -> Result> { /// The transform that puts new art with the natural box `natural` where `old` is: an image's scale /// and rotation relative to its 100% size (its resolution's) and its centre are kept (with -/// `image_xf`); other objects keep their centre. -fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool) -> Affine { - if image_xf && let NodeKind::Image(im) = &old.kind { +/// `image_xf`), also for an image alone in a clip group when the new art is an image clipped by +/// its file's clipping path (`clipped`); other objects keep their centre. +fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, clipped: bool) -> Affine { + // An image alone in a clip group (as a PSD or PSB file's clipping path places it, + // [`fileio::file_clipped`]) is measured as the image when the new art brings its own clip + // group; a DCS file's plates are not. + let image = match &old.kind { + NodeKind::Group { children, clip: true } if clipped => match &children[..] { + [path, image] if matches!(path.kind, NodeKind::Path { clipping: true, .. }) => match &image.kind { + NodeKind::Image(im) if d.images.get(&im.key).is_none_or(|b| b.separated().is_none()) => image, + _ => old, + }, + _ => old, + }, + _ => old, + }; + if image_xf && let NodeKind::Image(im) = &image.kind { let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes))); let full = Affine::scale_non_uniform(sx, sy); let centre = full * Point::new(im.width as f64 / 2.0, im.height as f64 / 2.0); @@ -541,7 +559,7 @@ impl PlaceJob { let mut loaded = load(&self.params, PLACE, self.target, true)?; let linked = loaded.link.is_some() && bool_or(&self.params, "link", true); match &mut loaded.art { - Art::Image(img) => { + Art::Image(img, _) => { let unread = super::links::kept_unread(&img.blob.bytes); img.blob = super::links::readable_and_kept(img.blob.clone(), unread, linked)?; } @@ -657,7 +675,7 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { } let natural = loaded.natural; let m = match (old_node, rect) { - (Some(o), _) => replace_xf(&st.doc, o, natural, !is_text), + (Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(_, Some(_)))), (None, Some(r)) => fit(natural, r), // Its artboard's bottom-left corner on the target's. (None, None) if let (Some(src), Some(to)) = (loaded.board, target) => Affine::translate((to.x0 - src.x0, to.y1 - src.y1)), @@ -671,7 +689,7 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { let link = loaded.link.take().filter(|_| bool_or(p, "link", true)); let linked = link.is_some(); let (name, format, mut warnings) = (loaded.name.clone(), loaded.format.id, std::mem::take(&mut loaded.warnings)); - let dcs_clipped = matches!(&loaded.art, Art::Dcs(a) if a.clip.is_some()); + let file_clipped = matches!(&loaded.art, Art::Dcs(a) if a.clip.is_some()) || matches!(&loaded.art, Art::Image(_, Some(_))); if let Art::Dcs(a) = &loaded.art { warnings.extend(dcs::swatch_notes(&st.doc, &a.spots)); } @@ -697,8 +715,9 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { Ok((id, size)) })?; let mut out = json!({ "ids": [id.0], "name": name, "format": format, "linked": linked, "width": size.width(), "height": size.height(), "warnings": warnings }); - // A DCS file clipped by its clipping path: its image, which the Links commands take. - if dcs_clipped { + // A DCS, PSD or PSB file clipped by its clipping path: its image, which the Links commands + // take. + if file_clipped { let image = s.doc()?.doc.node(id).and_then(|n| match &n.kind { NodeKind::Group { children, clip: true } => children.get(1).filter(|c| matches!(c.kind, NodeKind::Image(_))).map(|c| c.id), _ => None, @@ -810,7 +829,7 @@ fn read_queue(doc: u64, p: Value, queued: Vec) -> Result { let checked = load(&q, QUEUE, None, false).and_then(|mut l| { let linked = l.link.is_some() && bool_or(&q, "link", true); match &mut l.art { - Art::Image(img) => { + Art::Image(img, _) => { let unread = super::links::kept_unread(&img.blob.bytes); let check = if thumbnail.is_some() { super::links::readable_and_kept } else { super::links::readable }; img.blob = check(img.blob.clone(), unread, linked)?; @@ -932,7 +951,7 @@ pub fn read_info(p: &Value) -> Result { "height": natural.height(), "warnings": std::mem::take(&mut l.warnings), }); - if let Art::Image(img) = &l.art { + if let Art::Image(img, _) = &l.art { let (x, y) = img.ppi.unwrap_or((72.0, 72.0)); out["pixelWidth"] = json!(img.width); out["pixelHeight"] = json!(img.height); diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 867f256b4c..48a6649d77 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -538,8 +538,8 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result /// live-effect plug-in) with parameters it takes, filled in to their defaults. A record the object /// already had stays as it was. An object takes one 3D effect (its fills' and strokes' own /// counted), which must fit it, and the `textureImage` of an effect with Load Texture (Glass, -/// Texturizer) comes as the effect stores it, never as a file to read: a plug-in can't have the -/// host read one. +/// Texturizer, Rough Pastels) comes as the effect stores it, never as a file to read: a plug-in +/// can't have the host read one. fn admit_effects(fx: &[Effect], n: &Node) -> std::result::Result, String> { admit_effects_for("plugin.run", fx, n) } diff --git a/crates/engine/src/cmd/svgfilter.rs b/crates/engine/src/cmd/svgfilter.rs index 98b29a6e27..43af8bce35 100644 --- a/crates/engine/src/cmd/svgfilter.rs +++ b/crates/engine/src/cmd/svgfilter.rs @@ -3,9 +3,14 @@ //! applied effect names the document's filter: editing the filter changes what every object that //! uses it draws, and deleting it leaves their effects in place, drawing nothing, until a filter of //! that name exists again. Each effect holds the definition it draws with, kept in step here. +//! +//! The default filters ([`svg_filter::defaults`]) are listed for every document. Applying or +//! editing one adds a copy to the document under the default's name, and from then on that copy is +//! the filter of that name. Deleting the copy lists the default again. use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, Document, SvgFilter}; +use vectorcraft_render::effects::svg_filter::defaults::{DEFAULT_FILTERS, default_filter}; use vectorcraft_render::effects::{self, svg_filter}; use super::fileio::{absolute_path, read_file_head}; @@ -21,7 +26,7 @@ pub fn specs() -> Vec { "SVG Filters", [], None, - "{} → {filters: [{name, xml}…]} the SVG filters the document holds, in the SVG Filters submenu's order", + "{} → {filters: [{name, xml}…], defaults: [{name, xml, inDocument}…]} filters: the SVG filters the document holds, in the order they were added; defaults: the default filters every document lists (VectorCraft's own set), with inDocument true when the document holds a filter of that name, which then stands in the default's place. The SVG Filters submenu and Apply SVG Filter list the defaults first, then the document's other filters", has_doc, list ), @@ -30,7 +35,7 @@ pub fn specs() -> Vec { "New SVG Filter", [], None, - "{xml: one SVG element (its id is its name; 1..64 primitives; at most 64 KB), replace?: the name of the filter it replaces and keeps (Edit SVG Filter)} add an SVG filter to the document, after the others, or replace one, as one undo step; every object whose svg.filter effect names it draws with the new definition; a name another filter has is refused and a document holds at most 64 filters → {name, filters}", + "{xml: one SVG element (its id is its name; 1..64 primitives; at most 64 KB), replace?: the name of the filter it replaces and keeps (Edit SVG Filter)} add an SVG filter to the document, after the others, or replace one, as one undo step; every object whose svg.filter effect names it draws with the new definition; a name another filter of the document has is refused and a document holds at most 64 filters; replace with the name of a default filter the document does not hold adds the edited copy to the document under that name, and code equal to the default's adds nothing; a new filter may take a default's name, and then stands in its place → {name, filters}", has_doc, define ), @@ -39,7 +44,7 @@ pub fn specs() -> Vec { "Delete SVG Filter", [], None, - "{name} remove an SVG filter from the document, as one undo step; objects whose svg.filter effect names it keep the effect, which draws nothing until a filter of that name is defined or imported again → {filters}", + "{name} remove an SVG filter from the document, as one undo step; objects whose svg.filter effect names it keep the effect, which draws nothing until a filter of that name is defined or imported again, or the default of that name is applied; a default filter the document holds no copy of is refused (the defaults are not deleted), and deleting the document's copy of one lists the default again → {filters}", has_doc, delete ), @@ -57,7 +62,7 @@ pub fn specs() -> Vec { "Apply SVG Filter", [], None, - "{name, ids?|id?, item?} apply the document's SVG filter `name` (svgFilter.list) to ids or the selection as a live svg.filter effect, as one undo step, like effect.apply → {ids, index, item}", + "{name, ids?|id?, item?, index?} apply the document's SVG filter `name`, or the default filter of that name when the document holds none (svgFilter.list), to ids or the selection as a live svg.filter effect, as one undo step, like effect.apply → {ids, index, item}; with index, the filter takes the place of the applied svg.filter effect at index of item, like effect.setParams → {ids}; a default is copied into the document in the same undo step, which is refused when the document already holds 64 filters", has_doc, apply ), @@ -69,7 +74,10 @@ fn filters_json(d: &Document) -> Value { } fn list(s: &mut Session, _: &Value) -> Result { - Ok(json!({ "filters": filters_json(&s.doc()?.doc) })) + let d = &s.doc()?.doc; + let held = |name: &str| d.svg_filters.iter().any(|f| f.name == name); + let defaults: Vec = DEFAULT_FILTERS.iter().map(|f| json!({ "name": f.name, "xml": f.xml, "inDocument": held(f.name) })).collect(); + Ok(json!({ "filters": filters_json(d), "defaults": defaults })) } /// `p`'s `name`, trimmed and not empty. @@ -132,10 +140,12 @@ fn define(s: &mut Session, p: &Value) -> Result { }; svg_filter::check(&xml).map_err(|e| bad(C, e))?; let filters = &s.doc()?.doc.svg_filters; - let at = match &replace { - Some(r) => Some(filters.iter().position(|f| f.name == *r).ok_or_else(|| bad(C, format!("the document has no SVG filter named {r:?}")))?), - None => None, - }; + let at = replace.as_ref().and_then(|r| filters.iter().position(|f| f.name == *r)); + // A default the document does not hold: its edited copy is added under the default's name. + let default = replace.as_ref().filter(|_| at.is_none()).and_then(|r| default_filter(r)); + if let Some(r) = replace.as_ref().filter(|_| at.is_none() && default.is_none()) { + return Err(bad(C, format!("the document has no SVG filter named {r:?}"))); + } // An edited filter keeps its name, whatever id its new code gives it. let xml = match &replace { Some(r) => svg_filter::with_id(&xml, r).ok_or_else(|| bad(C, "give one element"))?, @@ -145,22 +155,28 @@ fn define(s: &mut Session, p: &Value) -> Result { if filters.iter().enumerate().any(|(i, f)| f.name == name && Some(i) != at) { return Err(bad(C, format!("the document already has an SVG filter named {name:?}"))); } + let new = SvgFilter { name: name.clone(), xml }; + // Nothing to record when the filter, and every object that uses it, is already as given: a + // default saved with its own code stays out of the document. + let as_given = match default { + Some(d) => d.to_filter() == new, + None => at.and_then(|i| filters.get(i)) == Some(&new), + }; + if as_given && !out_of_step(&s.doc()?.doc, &new.name, &new.xml) { + return Ok(json!({ "name": name, "filters": filters_json(&s.doc()?.doc) })); + } if at.is_none() && filters.len() >= SvgFilter::MAX { return Err(bad(C, format!("a document holds at most {} SVG filters", SvgFilter::MAX))); } - let new = SvgFilter { name: name.clone(), xml }; - // Nothing to record when the filter, and every object that uses it, is already as given. - if at.and_then(|i| filters.get(i)) != Some(&new) || out_of_step(&s.doc()?.doc, &new.name, &new.xml) { - let label = if at.is_some() { "Edit SVG Filter" } else { "New SVG Filter" }; - s.edit(label, |d, _| { - update_users(d, &new.name, &new.xml); - match at.and_then(|i| d.svg_filters.get_mut(i)) { - Some(f) => *f = new, - None => d.svg_filters.push(new), - } - Ok(()) - })?; - } + let label = if replace.is_some() { "Edit SVG Filter" } else { "New SVG Filter" }; + s.edit(label, |d, _| { + update_users(d, &new.name, &new.xml); + match at.and_then(|i| d.svg_filters.get_mut(i)) { + Some(f) => *f = new, + None => d.svg_filters.push(new), + } + Ok(()) + })?; Ok(json!({ "name": name, "filters": filters_json(&s.doc()?.doc) })) } @@ -168,6 +184,9 @@ fn delete(s: &mut Session, p: &Value) -> Result { const C: &str = "svgFilter.delete"; let name = name_param(p, C)?; if !s.doc()?.doc.svg_filters.iter().any(|f| f.name == name) { + if default_filter(&name).is_some() { + return Err(bad(C, format!("{name:?} is a default SVG filter, and the document holds no copy of it to delete"))); + } return Err(bad(C, format!("the document has no SVG filter named {name:?}"))); } s.edit("Delete SVG Filter", |d, _| { @@ -222,13 +241,79 @@ fn import(s: &mut Session, p: &Value) -> Result { fn apply(s: &mut Session, p: &Value) -> Result { const C: &str = "svgFilter.apply"; let name = name_param(p, C)?; - let f = s.doc()?.doc.svg_filters.iter().find(|f| f.name == name).cloned(); - let f = f.ok_or_else(|| bad(C, format!("the document has no SVG filter named {name:?}")))?; - let mut q = json!({ "effect": effects::SVG_FILTER, "params": { "name": f.name, "xml": f.xml } }); + let filters = &s.doc()?.doc.svg_filters; + // The document's filter of that name, or the default of that name, which the document then takes. + let (f, copied) = match (filters.iter().find(|f| f.name == name), default_filter(&name)) { + (Some(f), _) => (f.clone(), false), + (None, Some(_)) if filters.len() >= SvgFilter::MAX => { + return Err(bad(C, format!("a document holds at most {} SVG filters, and applying a default filter adds it", SvgFilter::MAX))); + } + (None, Some(d)) => (d.to_filter(), true), + (None, None) => return Err(bad(C, format!("the document has no SVG filter named {name:?}"))), + }; + // A given `index`, null included, is checked as an index: only a missing one adds an effect. + let replaces = p.get("index").is_some(); + let mut q = match replaces { + true => json!({ "index": p["index"], "params": { "name": f.name, "xml": f.xml } }), + false => json!({ "effect": effects::SVG_FILTER, "params": { "name": f.name, "xml": f.xml } }), + }; for key in ["ids", "id", "item"] { if let Some(v) = p.get(key) { q[key] = v.clone(); } } - super::effectcmd::apply(s, &q) + if !copied { + return apply_as_given(s, p, &q, replaces, None); + } + // The effect and the copy are two edits joined into one step. The history keeps room for both + // until they are joined, so the application lets one old step go at most, as any edit does. + let limit = s.doc()?.history.limit; + if let Some(st) = s.active_mut() { + st.history.limit = limit.saturating_add(2); + } + let out = apply_as_given(s, p, &q, replaces, Some(f)); + if let Some(st) = s.active_mut() { + st.history.limit = limit; + st.history.trim(); + } + out +} + +/// [`apply`] once the filter is known: the effect added (`q`) or put in the applied filter's place +/// (`replaces`), and `copy`, a default's copy, added to the document in the same undo step. +fn apply_as_given(s: &mut Session, p: &Value, q: &Value, replaces: bool, copy: Option) -> Result { + const C: &str = "svgFilter.apply"; + let newest = s.doc()?.history.step().0; + let out = if replaces { + super::appearance::index_param(p, "index", C)?; + // Only an applied SVG filter gives its place: another effect would take the filter's + // parameters as its own. + let edited = super::effectcmd::set_params_effects(s, q); + if edited.is_empty() || edited.iter().any(|e| e != effects::SVG_FILTER) { + return Err(bad(C, "`index` must be the index of an applied SVG filter")); + } + super::effectcmd::set_params(s, q)? + } else { + super::effectcmd::apply(s, q)? + }; + if let Some(f) = copy { + // The copy joins the step that applied it, under that step's name. That step is found by + // its document, not its place: in an undo group both edits join the group's one step. + let h = &s.doc()?.history; + let applied = h.undo.last().filter(|_| h.step().0 != newest).map(|step| (step.label.clone(), step.doc.clone())); + let label = applied.as_ref().map_or_else(|| "SVG Filter".to_string(), |(l, _)| l.clone()); + s.edit(&label, |d, _| { + update_users(d, &f.name, &f.xml); + d.svg_filters.push(f); + Ok(()) + })?; + let undo = &s.doc()?.history.undo; + let below = undo.len().checked_sub(2); + if let (Some(at), Some((_, doc))) = (below, &applied) + && undo.get(at).is_some_and(|e| std::sync::Arc::ptr_eq(&e.doc, doc)) + { + super::menucmds::squash(s, at, &label); + } + } + Ok(out) } diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 9ed7f3252b..7aed215d3d 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; vertical type keeps the characters' spacing; 0 by default; a value that is not a number or is outside the range is refused), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; vertical type keeps the characters' spacing; 0 by default; a value that is not a number or is outside the range is refused), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -473,6 +473,7 @@ pub(crate) struct CharChange { standard_vertical_roman: Option, no_break: Option, digits: Option, + glyph_form: Option, /// The language to set: a tag, or `None` for the default. language: Option>, font_axes: Option, @@ -571,6 +572,20 @@ pub(crate) fn digits_param(p: &Value, cmd: &str) -> Result Result> { + use vectorcraft_doc::GlyphForm; + let Some(v) = p.get("glyphForm").filter(|v| !v.is_null()) else { return Ok(None) }; + let Some(f) = v.as_str().and_then(GlyphForm::from_id) else { + let ids: Vec = GlyphForm::ALL.iter().map(|f| format!("\"{}\"", f.id())).collect(); + return Err(bad(cmd, format!("`glyphForm` must be one of {}", ids.join(", ")))); + }; + Ok(Some(f)) +} + /// `language: name|tag` (one of Document Setup's languages, case-insensitive) → the language to /// set ([`vectorcraft_doc::CharStyle::language`]: `None` inside for the default). pub(crate) fn language_param(p: &Value, cmd: &str) -> Result>> { @@ -644,7 +659,7 @@ pub(crate) fn features_param(p: &Value, cmd: &str) -> Result> return Err(bad( cmd, format!( - "unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {}, as `salt=2`)", + "unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {}, as `salt=2`)", vectorcraft_text::MAX_FEATURE_VALUE ), )); @@ -840,6 +855,7 @@ impl CharChange { standard_vertical_roman: flag("standardVerticalRoman"), no_break: flag("noBreak"), digits: digits_param(p, cmd)?, + glyph_form: glyph_form_param(p, cmd)?, language: language_param(p, cmd)?, font_axes: font_axes_param(p, cmd)?, font_height_reference: font_height_reference_param(p, cmd)?, @@ -905,6 +921,7 @@ impl CharChange { && self.standard_vertical_roman.is_none() && self.no_break.is_none() && self.digits.is_none() + && self.glyph_form.is_none() && self.language.is_none() && self.font_axes.is_none() && self.font_height_reference.is_none() @@ -1070,6 +1087,9 @@ impl CharChange { if let Some(v) = self.digits { st.digits = v; } + if let Some(v) = self.glyph_form { + st.glyph_form = v; + } if let Some(v) = self.font_height_reference { st.font_height_reference = v; } diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 17d453abf4..18f87d44f7 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -228,6 +228,7 @@ pub fn char_attrs(v: &CharStyle) -> Map { ("digits", json!(v.digits)), ("fontHeightReference", json!(v.font_height_reference)), ("language", json!(v.language)), + ("glyphForm", json!(v.glyph_form)), ] { m.insert(k.into(), x); } diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 31bcad4671..2cc7c3c1d3 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -140,7 +140,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 36a0f965b7..e0e5d8a926 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -1589,6 +1589,40 @@ fn proportional_metrics_is_a_character_attribute_saved_only_when_on() { assert!(!serde_json::from_value::(old).unwrap().proportional_metrics); } +/// H or V Style (`hkna`) and Roman Italics (`ital`, OpenType panel menu, East Asian options) are +/// feature tags of the characters: set on a range and turned off again, kept by a character style +/// and in a saved document, on or off only (`hkna=2` is refused and changes nothing). +#[test] +fn kana_style_and_roman_italics_are_character_features() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "かなAB"})).unwrap()["id"].as_u64().unwrap(); + let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.features.clone())).collect::>(), + _ => panic!("text"), + }; + // か and な are 3 bytes each. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 6, "features": ["hkna"]})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 6, "end": 8, "featureChanges": ["ital"]})).unwrap(); + assert_eq!(runs(&s), [("かな".to_string(), vec!["hkna".to_string()]), ("AB".to_string(), vec!["ital".to_string()])]); + let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &saved.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!(t.runs.iter().map(|r| r.style.features.clone()).collect::>(), [vec!["hkna".to_string()], vec!["ital".to_string()]]); + let before = runs(&s); + for bad in [json!({"id": id, "features": ["hkna=2"]}), json!({"id": id, "featureChanges": ["ital=1"]})] { + let e = s.execute("text.setRangeStyle", &bad).unwrap_err().to_string(); + assert!(e.contains("unknown OpenType feature"), "{e}"); + } + assert_eq!(runs(&s), before); + s.execute("text.setRangeStyle", &json!({"id": id, "featureChanges": ["-hkna", "-ital"]})).unwrap(); + assert!(runs(&s).iter().all(|(_, f)| f.is_empty()), "{:?}", runs(&s)); + s.execute("charStyle.new", &json!({"name": "Kana", "attrs": {"features": ["hkna", "ital"]}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Kana", "id": id})).unwrap(); + assert!(runs(&s).iter().all(|(_, f)| *f == ["hkna", "ital"]), "{:?}", runs(&s)); + let e = s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"features": ["ital=2"]}})).unwrap_err().to_string(); + assert!(e.contains("unknown OpenType feature `ital=2`"), "{e}"); +} + /// Tate-chu-yoko (Character panel menu, East Asian options): a character attribute, saved only /// when on. Documents written before it read as off. #[test] @@ -1925,6 +1959,55 @@ fn standard_vertical_roman_is_a_character_attribute_saved_only_when_on() { assert!(runs(&s).iter().all(|r| !r.style.standard_vertical_roman)); } +/// The East Asian glyph form (Glyphs panel menu) is one character attribute, `glyphForm`: one +/// form replaces another, "default" (Revert To Default Forms) takes it away, and it is saved +/// only when set. A call that changes nothing records no undo step, an unknown form is refused, +/// and character styles carry it. +#[test] +fn glyph_form_is_one_character_attribute_saved_only_when_set() { + use vectorcraft_doc::GlyphForm; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "亜唖芦"})).unwrap()["id"].as_u64().unwrap(); + let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("text"), + }; + let forms = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::>(); + assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("glyphForm").is_none()); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 6, "glyphForm": "jis78"})).unwrap(); + assert_eq!(forms(&s), [("亜".into(), GlyphForm::Default), ("唖".into(), GlyphForm::Jis78), ("芦".into(), GlyphForm::Default)]); + assert_eq!(serde_json::to_value(&runs(&s)[1].style).unwrap()["glyphForm"], "jis78"); + // Saved and reopened as it was. + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!(t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::>(), forms(&s)); + // Another form replaces it: one form at a time. + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"glyphForm": "fullWidth"})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::FullWidth)); + let n = s.doc().unwrap().history.undo.len(); + s.execute("text.setFormat", &json!({"glyphForm": "fullWidth"})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), n, "nothing changed, no undo step"); + for bad in [json!("jis2004"), json!(78), json!(true), json!("Traditional")] { + let e = s.execute("text.setFormat", &json!({"glyphForm": bad})).unwrap_err().to_string(); + assert!(e.contains("`glyphForm` must be one of \"traditional\""), "{bad}: {e}"); + assert!(s.execute("text.setRangeStyle", &json!({"id": id, "glyphForm": bad})).is_err(), "{bad}"); + } + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::FullWidth), "a refused call changes nothing"); + assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style)["glyphForm"], "fullWidth"); + s.execute("text.setFormat", &json!({"glyphForm": "default"})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default)); + assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("glyphForm").is_none()); + // A character style carries the form. + s.execute("charStyle.new", &json!({"name": "Old forms", "attrs": {"glyphForm": "jis83"}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Old forms", "id": id})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Jis83)); + assert!(s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"glyphForm": "jis2004"}})).is_err()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default)); +} + /// No Break is a character attribute, saved only when on. #[test] fn no_break_is_a_character_attribute_saved_only_when_on() { 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"); + 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\n"); } - xml += "

\n"; + DataValue::Visible(shown) => xml += &format!("\t\t\t\t<{var}>{shown}\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}>{}\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/session/documents.rs b/crates/engine/src/session/documents.rs index e25cde77cc..1244b77432 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -24,6 +24,8 @@ impl Session { }); // Clicks find an image's own fills and strokes where their effects draw them. vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint); + // Clicks inside a clip group fall in the region its clipping path's effects give it. + vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline); // Clicks find a blend's steps and an envelope's distorted art where the canvas draws them, // evaluated again when the fonts, the hyphenation exceptions or the plug-ins change. vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3b54a532ef..f89cc98ff8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1293,7 +1293,12 @@ fn a_transform_that_moves_nothing_records_no_undo_step() { for (id, p) in calls { assert_eq!(s.execute(id, &p).unwrap(), json!({"ids": [a.0]}), "{id} {p}"); assert_eq!(history(&s), before, "{id} {p}"); - assert_eq!(s.journal.last().unwrap(), &(id.to_string(), p)); + // The journal adds the frame a scale acted in, so a replay acts in the same one. + let mut recorded = p; + if id == "object.scale" { + recorded["basis"] = json!("box"); + } + assert_eq!(s.journal.last().unwrap(), &(id.to_string(), recorded)); } assert_eq!( s.doc().unwrap().last_transform, 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/bboxrotate.rs b/crates/engine/src/tests/bboxrotate.rs index 6dc1c9b410..dfabb77236 100644 --- a/crates/engine/src/tests/bboxrotate.rs +++ b/crates/engine/src/tests/bboxrotate.rs @@ -666,7 +666,7 @@ fn expanding_a_reflected_symbol_instance_keeps_its_box() { for reset in [false, true] { let (mut s, inst) = turned_instance(0.0); s.execute("object.rotate", &json!({"angle": 150})).unwrap(); - s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap(); + s.execute("object.reflect", &json!({"axis": "horizontal", "basis": "page"})).unwrap(); assert!(near(angle(&s, inst), -170.0), "{}", angle(&s, inst)); if reset { s.execute("object.resetBoundingBox", &json!({})).unwrap(); @@ -719,10 +719,164 @@ fn page_flips_keep_an_upright_box_upright() { s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap(); assert_eq!(angle(&s, a), 0.0); s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + // A named axis is the turned box's own: the box keeps its angle. s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + assert!(near(angle(&s, a), 30.0)); + s.execute("object.reflect", &json!({"axis": "vertical", "basis": "page"})).unwrap(); assert!(near(angle(&s, a), -30.0)); } +fn same_matrix(a: Affine, b: Affine) -> bool { + a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| near(*x, y)) +} + +/// After a rotation, Scale and a named Reflect act along the turned bounding box until Reset +/// Bounding Box; `basis: "page"` keeps the page's axes, and Transform Again repeats the matrix the +/// transform applied on the page. +#[test] +fn scale_and_reflect_follow_the_turned_box() { + let mut s = session(); + let a = turned_rect(&mut s); + let page = |s: &Session, ids: &[NodeId]| s.doc().unwrap().doc.bounds_of(ids, false).unwrap(); + let c = Point::new(200.0, 200.0); + let frame = OrientedBox { angle: 45.0, rect: Rect::ZERO }; + s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap(); + let b = selection_box(&s); + assert!(near(b.angle, 45.0) && near(angle(&s, a), 45.0), "{b:?}"); + assert!(near(b.rect.width(), 200.0) && near(b.rect.height(), 50.0), "{b:?}"); + assert!(b.center().distance(c) < 1e-6, "{b:?}"); + let want = Affine::translate(c.to_vec2()) * frame.conjugate(Affine::scale_non_uniform(2.0, 1.0)) * Affine::translate(-c.to_vec2()); + let Some(LastTransform::Matrix(m, _)) = s.doc().unwrap().last_transform.clone() else { panic!("no transform to repeat") }; + assert!(same_matrix(m, want), "{m:?}"); + // The recorded step names its basis, so a replay acts in the same frame. + let steps = s.journal_for_action(0); + assert!(steps.iter().any(|(id, p)| id == "object.scale" && p["basis"] == "box"), "{steps:?}"); + + // Reflected across the box's vertical axis through its left side: the box keeps its angle and + // size, and its centre moves a width to the left along the box. + let left = b.reference_point(3); + s.execute("object.reflect", &json!({"axis": "vertical", "origin": [left.x, left.y]})).unwrap(); + let r = selection_box(&s); + let moved = c + (frame.to_doc() * Point::new(-200.0, 0.0)).to_vec2(); + assert!(near(r.angle, 45.0) && near(r.rect.width(), 200.0) && near(r.rect.height(), 50.0), "{r:?}"); + assert!(r.center().distance(moved) < 1e-6, "{r:?}"); + // Across its horizontal axis through its centre: the box stays where it is. + s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap(); + assert!(selection_box(&s).center().distance(moved) < 1e-6 && near(angle(&s, a), 45.0)); + + // Unknown bases are errors and change nothing. + let n = undo_len(&s); + assert!(s.execute("object.scale", &json!({"sx": 50, "basis": "turned"})).is_err()); + assert!(s.execute("object.reflect", &json!({"axis": "vertical", "basis": 1})).is_err()); + assert!(s.execute("object.reflect", &json!({"axis": 30, "basis": "turned"})).is_err()); + assert_eq!(undo_len(&s), n); + + // On the page's axes, the box no longer stands at 45°. + s.execute("object.scale", &json!({"sx": 50, "sy": 100, "basis": "page"})).unwrap(); + assert!(!near(angle(&s, a), 45.0)); + // Transform Again repeats the page matrix after Reset Bounding Box too. + s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap(); + let Some(LastTransform::Matrix(m, _)) = s.doc().unwrap().last_transform.clone() else { panic!("no transform to repeat") }; + s.execute("object.resetBoundingBox", &json!({})).unwrap(); + let before = s.doc().unwrap().doc.node(a).unwrap().clone(); + s.execute("object.transformAgain", &json!({})).unwrap(); + let mut want = before; + want.transform(m, false); + let (got, want) = (page(&s, &[a]), want.geometric_bounds_with(&s.doc().unwrap().doc.symbol_boxes()).unwrap()); + assert!([got.x0 - want.x0, got.y0 - want.y0, got.x1 - want.x1, got.y1 - want.y1].iter().all(|d| d.abs() < 1e-6), "{got:?} {want:?}"); +} + +/// A saved step without `basis` was recorded before Scale and Reflect followed the turned box, so a +/// replay of it acts along the page's axes, as it did then, and its new journal entry says so. A +/// step recorded now names its basis and replays along the box. A call without `basis` that is not +/// a replay acts along the box. +#[test] +fn saved_steps_without_a_basis_replay_on_the_page() { + // The turned rectangle after `run` runs on it: its page bounds and its box's angle. + let after = |run: &dyn Fn(&mut Session)| { + let mut s = session(); + let a = turned_rect(&mut s); + run(&mut s); + let st = (s.doc().unwrap().doc.bounds_of(&[a], false).unwrap(), angle(&s, a)); + (st, s.journal.last().unwrap().clone()) + }; + let same = |(r, a): (Rect, f64), (q, b): (Rect, f64)| [r.x0 - q.x0, r.y0 - q.y0, r.x1 - q.x1, r.y1 - q.y1, a - b].iter().all(|d| d.abs() < 1e-6); + for (id, p) in [("object.scale", json!({"sx": 200, "sy": 100})), ("object.reflect", json!({"axis": "vertical"}))] { + let mut on_page = p.clone(); + on_page["basis"] = json!("page"); + let (page, _) = after(&|s| { + s.execute(id, &on_page).unwrap(); + }); + let (old, (_, noted)) = after(&|s| { + s.replay(id, &p).unwrap(); + }); + assert!(same(old, page), "{id}: {old:?} {page:?}"); + assert_eq!(noted["basis"], "page", "{id}"); + + let (boxed, (recorded_id, recorded)) = after(&|s| { + s.execute(id, &p).unwrap(); + }); + assert!(!same(boxed, page) && near(boxed.1, 45.0), "{id}: {boxed:?}"); + assert_eq!(recorded["basis"], "box", "{id}"); + let (replayed, _) = after(&|s| { + s.replay(&recorded_id, &recorded).unwrap(); + }); + assert!(same(replayed, boxed), "{id}: {replayed:?} {boxed:?}"); + } +} + +/// Once Reset Bounding Box squares the box, and for objects standing at different angles, Scale +/// acts along the page's axes. +#[test] +fn scale_follows_the_page_after_a_reset_and_for_mixed_angles() { + let mut s = session(); + let a = turned_rect(&mut s); + s.execute("object.resetBoundingBox", &json!({})).unwrap(); + let page = |s: &Session, ids: &[NodeId]| s.doc().unwrap().doc.bounds_of(ids, false).unwrap(); + let w = page(&s, &[a]); + s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap(); + let r = page(&s, &[a]); + assert!(near(r.width(), 2.0 * w.width()) && near(r.height(), w.height()), "{w:?} {r:?}"); + assert_eq!(angle(&s, a), 0.0); + // A turned rectangle with an upright one: the box is square to the page. + let b = turned_rect(&mut s); + let u = rect(&mut s, 400.0, 100.0, 50.0, 50.0); + sel(&mut s, &[b, u]); + let w = page(&s, &[b, u]); + s.execute("object.scale", &json!({"sx": 100, "sy": 200})).unwrap(); + let r = page(&s, &[b, u]); + assert!(near(r.width(), w.width()) && near(r.height(), 2.0 * w.height()), "{w:?} {r:?}"); +} + +/// With anchors selected, Scale and a named Reflect move the anchors along the page's axes, but +/// with Transform Objects off they move the whole objects' pattern tiles, along the turned box. +#[test] +fn pattern_only_transforms_of_selected_anchors_follow_the_turned_box() { + let c = Point::new(200.0, 200.0); + let frame = OrientedBox { angle: 45.0, rect: Rect::ZERO }; + let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2()); + let last = |s: &Session| match s.doc().unwrap().last_transform.clone() { + Some(LastTransform::Matrix(m, _)) => m, + other => panic!("no matrix to repeat: {other:?}"), + }; + let scale = Affine::scale_non_uniform(2.0, 1.0); + let flip = Affine::scale_non_uniform(-1.0, 1.0); + for (cmd, p, m) in [("object.scale", json!({"sx": 200, "sy": 100}), scale), ("object.reflect", json!({"axis": "vertical"}), flip)] { + for objects in [false, true] { + let mut s = session(); + let a = turned_rect(&mut s); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + let mut p = p.clone(); + p["origin"] = json!([c.x, c.y]); + p["objects"] = json!(objects); + p["patterns"] = json!(true); + s.execute(cmd, &p).unwrap(); + let want = if objects { about(m) } else { about(frame.conjugate(m)) }; + assert!(same_matrix(last(&s), want), "{cmd} objects {objects}: {:?}", last(&s)); + } + } +} + #[test] fn groups_type_and_multiple_selections_keep_their_angle() { let mut s = session(); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 8fd5a3aa45..243dce52e8 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3,7 +3,8 @@ use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_color::{Color, Paint}; +use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_doc::appearance::{Effect, FillLayer, StrokeLayer}; use vectorcraft_doc::{AppearanceItem, ImageBlob, ImageObject, LineCap, LineJoin, Node, NodeKind}; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect}; use vectorcraft_testkit::pdf::{PdfPage, pdf}; @@ -2684,6 +2685,401 @@ fn live_paint_make_and_expand_keep_abutting_compound_colors() { check_colors(&node(&s, group)); } +/// Gives `id` the appearance rows `items` (paint order) and returns them. +fn set_rows(s: &mut Session, id: NodeId, items: Vec) -> Vec { + s.edit("t", |d, _| { + d.node_mut(id).unwrap().appearance = vectorcraft_doc::Appearance { items: items.clone(), ..Default::default() }.into(); + Ok(()) + }) + .unwrap(); + items +} + +/// A fill row of `p`, changed by `f`. +fn fill_row(p: Paint, f: impl FnOnce(&mut FillLayer)) -> AppearanceItem { + let mut l = FillLayer::new(p); + f(&mut l); + AppearanceItem::Fill(l) +} + +/// A stroke row of `p` `width` wide, changed by `f`. +fn stroke_row(p: Paint, width: f64, f: impl FnOnce(&mut StrokeLayer)) -> AppearanceItem { + let mut l = StrokeLayer::new(p, width); + f(&mut l); + AppearanceItem::Stroke(l) +} + +/// The faces and edges of Live Paint group `g` whose bounds lie within x `x0`..`x1`. +fn parts_within(s: &Session, g: NodeId, x0: f64, x1: f64) -> (Vec, Vec) { + let n = node(s, g); + let within = |c: &&Arc| c.geometric_bounds().is_some_and(|b| b.x0 >= x0 - 1e-6 && b.x1 <= x1 + 1e-6); + let faces = vectorcraft_tools::builder::faces(&n).into_iter().filter(within).map(|c| (**c).clone()).collect(); + let edges = vectorcraft_tools::builder::edges(&n).into_iter().filter(within).map(|c| (**c).clone()).collect(); + (faces, edges) +} + +/// Make gives each edge every stroke row of its source that draws, a lower one under an +/// unpainted or hidden top row included, with the rows' settings and the source's opacity and +/// blending mode; rows that draw nothing stay only with the stored source, which Release returns. +#[test] +fn live_paint_make_keeps_lower_drawn_stroke_rows() { + let mut s = session(); + let (a, b) = two_at(&mut s, 200.0); + let black = Paint::solid(Color::BLACK); + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let thick = stroke_row(black.clone(), 3.0, |l| { + l.opacity = 0.5; + l.blend = BlendMode::Multiply; + l.cap = LineCap::Round; + }); + // A: the top stroke has no paint. + let a_rows = + set_rows(&mut s, a, vec![fill_row(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), |_| {}), thick.clone(), stroke_row(Paint::None, 1.0, |_| {})]); + // B: the top stroke is hidden; a zero-weight and a transparent stroke draw nothing either. + set_rows( + &mut s, + b, + vec![ + stroke_row(green.clone(), 2.0, |_| {}), + stroke_row(black.clone(), 0.0, |_| {}), + stroke_row(black, 2.0, |l| l.opacity = 0.0), + stroke_row(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 5.0, |l| l.visible = false), + ], + ); + s.edit("t", |d, _| { + let n = d.node_mut(a).unwrap(); + n.opacity = 0.75; + n.blend = BlendMode::Screen; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let (_, a_edges) = parts_within(&s, g, 0.0, 100.0); + let (_, b_edges) = parts_within(&s, g, 200.0, 300.0); + assert!(!a_edges.is_empty() && !b_edges.is_empty()); + for e in &a_edges { + assert_eq!(e.appearance.items, vec![thick.clone()], "A's edge takes the stroke that draws"); + assert_eq!((e.opacity, e.blend), (0.75, BlendMode::Screen)); + } + for e in &b_edges { + assert_eq!(e.appearance.items, vec![stroke_row(green.clone(), 2.0, |_| {})], "B's edge takes only its green stroke"); + assert_eq!((e.opacity, e.blend), (1.0, BlendMode::Normal)); + } + // Release returns the sources with every row they had. + let released = ids(&s.execute("livePaint.release", &json!({})).unwrap()); + assert!(released.contains(&a)); + assert_eq!(node(&s, a).appearance.items, a_rows); +} + +/// When Make cuts a dashed stroke with arrowheads, a width profile and a brush into edges, each +/// edge's dashes go on from where it starts along the path, the arrowheads stay at the path's own +/// ends, and the profile and brush, which spread over the whole path, are left off the pieces. +#[test] +fn live_paint_make_fits_dashes_and_arrowheads_to_each_edge() { + use vectorcraft_doc::{Arrowhead, Dash}; + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let l = line(&mut s, (-20.0, 50.0), (120.0, 50.0)); + let dash = Dash { pattern: vec![10.0, 5.0], offset: 2.0, align_corners: true }; + let row = stroke_row(Paint::solid(Color::BLACK), 2.0, |st| { + st.dash = Some(dash.clone()); + st.start_arrow = Some(Arrowhead::Triangle); + st.end_arrow = Some(Arrowhead::Circle); + st.brush = Some("Charcoal".into()); + }); + let rows = set_rows(&mut s, l, vec![row]); + s.execute("select.set", &json!({"ids": [a.0, l.0]})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let gn = node(&s, g); + let mut pieces: Vec<(f64, f64, vectorcraft_doc::StrokeLayer)> = vectorcraft_tools::builder::edges(&gn) + .iter() + .filter_map(|e| { + let st = e.appearance.stroke().filter(|st| st.dash.is_some())?.clone(); + let sp = e.path_data()?.subpaths.first()?; + Some((sp.anchors.first()?.p.x, sp.anchors.last()?.p.x, st)) + }) + .collect(); + pieces.sort_by(|p, q| p.0.total_cmp(&q.0)); + let ends: Vec<(f64, f64)> = pieces.iter().map(|p| ((p.0 * 1e3).round() / 1e3, (p.1 * 1e3).round() / 1e3)).collect(); + assert_eq!(ends, vec![(-20.0, 0.0), (0.0, 100.0), (100.0, 120.0)], "each piece runs the way the line does"); + let offsets: Vec = pieces.iter().map(|p| (p.2.dash.as_ref().unwrap().offset * 1e3).round() / 1e3).collect(); + assert_eq!(offsets, vec![2.0, 22.0, 122.0], "the dashes go on along the line"); + assert!(pieces.iter().all(|p| !p.2.dash.as_ref().unwrap().align_corners && p.2.brush.is_none())); + let arrows: Vec<_> = pieces.iter().map(|p| (p.2.start_arrow.clone(), p.2.end_arrow.clone())).collect(); + assert_eq!(arrows, vec![(Some(Arrowhead::Triangle), None), (None, None), (None, Some(Arrowhead::Circle))]); + // A path that crosses itself: the pieces that start at the crossing take their place on the + // path from where they run, not from the first time the path passes that point. + let mut s3 = session(); + let anchors = [(0.0, 0.0), (100.0, 100.0), (100.0, 0.0), (0.0, 100.0)].map(|(x, y)| json!({"x": x, "y": y})); + let z = NodeId(s3.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap()["id"].as_u64().unwrap()); + set_rows(&mut s3, z, rows.clone()); + s3.execute("select.set", &json!({"ids": [z.0]})).unwrap(); + let g3 = NodeId(s3.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let mut cut: Vec<(f64, Option, Option)> = vectorcraft_tools::builder::edges(&node(&s3, g3)) + .iter() + .filter_map(|e| { + let st = e.appearance.stroke()?; + Some(((st.dash.as_ref()?.offset * 1e3).round() / 1e3, st.start_arrow.clone(), st.end_arrow.clone())) + }) + .collect(); + cut.sort_by(|p, q| p.0.total_cmp(&q.0)); + let d = 2.0 + 50.0 * 2f64.sqrt(); + let r = |v: f64| (v * 1e3).round() / 1e3; + assert_eq!( + cut, + vec![(2.0, Some(Arrowhead::Triangle), None), (r(d), None, None), (r(d + 100.0 + 100.0 * 2f64.sqrt()), None, Some(Arrowhead::Circle))] + ); + // An uncut path keeps all of it. + let mut s2 = session(); + let l2 = line(&mut s2, (0.0, 0.0), (50.0, 0.0)); + set_rows(&mut s2, l2, rows.clone()); + s2.execute("select.set", &json!({"ids": [l2.0]})).unwrap(); + let g2 = NodeId(s2.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let edges: Vec<_> = vectorcraft_tools::builder::edges(&node(&s2, g2)).iter().map(|e| e.appearance.items.clone()).collect(); + assert_eq!(edges, vec![rows]); +} + +/// When Gap Options or Merge cuts an edge in two, each piece keeps the edge's dashes going on from +/// where it starts along the edge, an arrowhead only at the end of the edge it ends at, and no brush. +#[test] +fn live_paint_gap_options_and_merge_fit_an_edge_look_to_each_piece() { + use vectorcraft_doc::{Arrowhead, Dash}; + let mut s = session(); + let l = line(&mut s, (0.0, 50.0), (100.0, 50.0)); + let stub = line(&mut s, (50.0, 0.0), (50.0, 48.0)); + let row = stroke_row(Paint::solid(Color::BLACK), 2.0, |st| { + st.dash = Some(Dash { pattern: vec![10.0, 5.0], offset: 2.0, align_corners: false }); + st.start_arrow = Some(Arrowhead::Triangle); + st.end_arrow = Some(Arrowhead::Circle); + st.brush = Some("Charcoal".into()); + }); + let rows = set_rows(&mut s, l, vec![row]); + s.execute("select.set", &json!({"ids": [l.0, stub.0]})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let dashed = |s: &Session, g: NodeId| { + let mut out: Vec<(f64, f64, vectorcraft_doc::StrokeLayer)> = vectorcraft_tools::builder::edges(&node(s, g)) + .iter() + .filter_map(|e| { + let st = e.appearance.stroke().filter(|st| st.dash.is_some())?.clone(); + let sp = e.path_data()?.subpaths.first()?; + Some(((sp.anchors.first()?.p.x * 1e3).round() / 1e3, (sp.anchors.last()?.p.x * 1e3).round() / 1e3, st)) + }) + .collect(); + out.sort_by(|p, q| p.0.total_cmp(&q.0)); + out + }; + let before = dashed(&s, g); + assert_eq!(before.len(), 1, "nothing cuts the line yet"); + assert_eq!(vec![AppearanceItem::Stroke(before[0].2.clone())], rows); + let r = s.execute("livePaint.gapOptions", &json!({"id": g.0, "closeGaps": true})).unwrap(); + assert_eq!(r["closed"], json!(1)); + let pieces = dashed(&s, g); + let ends: Vec<(f64, f64)> = pieces.iter().map(|p| (p.0, p.1)).collect(); + assert_eq!(ends, vec![(0.0, 50.0), (50.0, 100.0)], "the line is cut where the gap closes"); + let offsets: Vec = pieces.iter().map(|p| (p.2.dash.as_ref().unwrap().offset * 1e3).round() / 1e3).collect(); + assert_eq!(offsets, vec![2.0, 52.0], "the dashes go on along the line"); + let arrows: Vec<_> = pieces.iter().map(|p| (p.2.start_arrow.clone(), p.2.end_arrow.clone())).collect(); + assert_eq!(arrows, vec![(Some(Arrowhead::Triangle), None), (None, Some(Arrowhead::Circle))]); + assert!(pieces.iter().all(|p| p.2.brush.is_none()), "a brush spreads over the whole line"); + // Merge: the piece of the edge that an added path cuts off, which takes the edge's look, gets + // it fitted to where it lies along the edge in the same way. + let mut s = session(); + let l = line(&mut s, (0.0, 50.0), (100.0, 50.0)); + set_rows(&mut s, l, rows.clone()); + s.execute("select.set", &json!({"ids": [l.0]})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let cut = line(&mut s, (25.0, 0.0), (25.0, 100.0)); + s.execute("livePaint.merge", &json!({"ids": [g.0, cut.0]})).unwrap(); + let pieces = dashed(&s, g); + let ends: Vec<(f64, f64)> = pieces.iter().map(|p| (p.0, p.1)).collect(); + assert_eq!(ends, vec![(0.0, 25.0), (25.0, 100.0)], "the added line cuts the edge"); + let offsets: Vec = pieces.iter().map(|p| (p.2.dash.as_ref().unwrap().offset * 1e3).round() / 1e3).collect(); + assert_eq!(offsets, vec![2.0, 27.0], "the dashes go on along the line"); + let arrows: Vec<_> = pieces.iter().map(|p| (p.2.start_arrow.clone(), p.2.end_arrow.clone())).collect(); + assert_eq!(arrows, vec![(Some(Arrowhead::Triangle), None), (None, Some(Arrowhead::Circle))]); + assert!(pieces.iter().all(|p| p.2.brush.is_none()), "a brush spreads over the whole line"); + // A repainted edge that Merge cuts keeps its paint on every piece. + let mut s = session(); + let l = line(&mut s, (0.0, 50.0), (100.0, 50.0)); + s.execute("select.set", &json!({"ids": [l.0]})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [50, 50], "color": "#ff0000", "width": 3})).unwrap(); + let cut = line(&mut s, (50.0, 0.0), (50.0, 100.0)); + s.execute("livePaint.merge", &json!({"ids": [g.0, cut.0]})).unwrap(); + let gn = node(&s, g); + let red = Paint::solid(Color::from_hex("#ff0000").unwrap()); + let mut on_line: Vec<(f64, bool)> = vectorcraft_tools::builder::edges(&gn) + .iter() + .filter_map(|e| { + let sp = e.path_data()?.subpaths.first()?; + let (a, z) = (sp.anchors.first()?.p, sp.anchors.last()?.p); + ((a.y - 50.0).abs() < 1e-6 && (z.y - 50.0).abs() < 1e-6) + .then(|| ((a.x.min(z.x) * 1e3).round() / 1e3, e.appearance.stroke().is_some_and(|st| st.paint == red))) + }) + .collect(); + on_line.sort_by(|p, q| p.0.total_cmp(&q.0)); + assert_eq!(on_line, vec![(0.0, true), (50.0, true)], "both pieces keep the edge's paint"); +} + +/// The edge Make builds from a closed path that nothing cuts starts at the anchor the path starts +/// at and runs the way the path does, whichever anchor that is, so its dashes and brush lie where +/// they do on the path, and it keeps the path's stroke row as it is. +#[test] +fn live_paint_make_starts_a_closed_edge_where_its_path_starts() { + use vectorcraft_doc::Dash; + let corners = [(50.0, 0.0), (100.0, 50.0), (50.0, 100.0), (0.0, 50.0)]; + for clockwise in [true, false] { + for start in 0..4 { + let mut s = session(); + let mut pts: Vec<(f64, f64)> = (0..4).map(|k| corners[(k + start) % 4]).collect(); + if !clockwise { + pts.reverse(); + } + let anchors: Vec<_> = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + let z = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap()); + let row = stroke_row(Paint::solid(Color::BLACK), 2.0, |st| { + st.dash = Some(Dash { pattern: vec![10.0, 5.0], offset: 2.0, align_corners: false }); + st.brush = Some("Charcoal".into()); + }); + let rows = set_rows(&mut s, z, vec![row]); + s.execute("select.set", &json!({"ids": [z.0]})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let gn = node(&s, g); + let edges = vectorcraft_tools::builder::edges(&gn); + let [e] = edges.as_slice() else { panic!("one edge, got {}", edges.len()) }; + let sp = e.path_data().unwrap().subpaths.first().unwrap().clone(); + let at: Vec<(f64, f64)> = sp.anchors.iter().map(|a| ((a.p.x * 1e3).round() / 1e3, (a.p.y * 1e3).round() / 1e3)).collect(); + assert!(sp.closed); + assert_eq!(at, pts, "clockwise {clockwise}, start {start}"); + assert_eq!(e.appearance.items, rows, "clockwise {clockwise}, start {start}"); + } + } + // A closed path that crosses itself is cut into loops, and the loop that holds the path's + // first anchor is still only part of the path: it keeps no brush. + let mut s = session(); + let anchors = [(0.0, 0.0), (100.0, 100.0), (100.0, 0.0), (0.0, 100.0)].map(|(x, y)| json!({"x": x, "y": y})); + let z = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap()); + let row = stroke_row(Paint::solid(Color::BLACK), 2.0, |st| { + st.dash = Some(Dash { pattern: vec![10.0, 5.0], offset: 2.0, align_corners: false }); + st.brush = Some("Charcoal".into()); + }); + set_rows(&mut s, z, vec![row]); + s.execute("select.set", &json!({"ids": [z.0]})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let gn = node(&s, g); + let edges = vectorcraft_tools::builder::edges(&gn); + assert!(edges.len() > 1, "the crossing cuts the path, got {} edge", edges.len()); + assert!(edges.iter().all(|e| e.appearance.stroke().is_some_and(|st| st.brush.is_none())), "no loop is the whole path"); +} + +/// When Make cuts a stroke whose only setting that depends on direction is a gradient along or +/// across it, each edge runs the way its source path does, so the gradient keeps its direction. +#[test] +fn live_paint_make_keeps_the_direction_of_gradient_strokes() { + use vectorcraft_doc::StrokeGradientMode; + for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] { + for (x0, x1) in [(-20.0, 120.0), (120.0, -20.0)] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let l = line(&mut s, (x0, 50.0), (x1, 50.0)); + let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()))); + set_rows(&mut s, l, vec![stroke_row(gradient, 2.0, |st| st.gradient_mode = mode)]); + s.execute("select.set", &json!({"ids": [a.0, l.0]})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let pieces: Vec<(f64, f64)> = vectorcraft_tools::builder::edges(&node(&s, g)) + .iter() + .filter_map(|e| { + e.appearance.stroke().filter(|st| st.gradient_mode == mode)?; + let sp = e.path_data()?.subpaths.first()?; + Some((sp.anchors.first()?.p.x, sp.anchors.last()?.p.x)) + }) + .collect(); + assert_eq!(pieces.len(), 3, "{mode:?}, from {x0}"); + assert!( + pieces.iter().all(|&(p, q)| (q - p).signum() == (x1 - x0).signum()), + "{mode:?}, from {x0}: each piece runs the way the line does: {pieces:?}" + ); + } + } +} + +/// Make gives each face every fill row of its source that draws, in order and with their +/// opacity, blending mode, overprint and effects, and the source's gradients keep their fit on +/// the source; Expand keeps the rows, and Undo and Redo bring the group back with them. +#[test] +fn live_paint_make_keeps_all_drawn_fill_rows_and_attributes() { + let mut s = session(); + let (a, b) = two(&mut s); + let lower = fill_row(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), |l| { + l.opacity = 0.4; + l.blend = BlendMode::Multiply; + l.overprint = true; + l.effects.push(Effect { id: "distort.roughen".into(), params: Value::Null, visible: true }); + }); + // A: two fills that draw, with a hidden one between them and an unpainted one above them. + set_rows( + &mut s, + a, + vec![ + lower.clone(), + fill_row(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), |l| l.visible = false), + fill_row(Paint::None, |_| {}), + stroke_row(Paint::None, 1.0, |_| {}), + ], + ); + // The top fill (and the stroke) become a gradient fitted to A's bounds. + let (want_fill, _) = paint_with_gradients(&mut s, a); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let want = vec![lower, fill_row(want_fill, |_| {})]; + let rows_within = |s: &Session, x0: f64, x1: f64| parts_within(s, g, x0, x1).0.iter().map(|f| f.appearance.items.clone()).collect::>(); + assert_eq!(rows_within(&s, 0.0, 50.0), vec![want.clone()], "A's face takes both fills that draw, the gradient at its fit on A"); + let blue = vec![fill_row(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), |_| {})]; + assert_eq!(rows_within(&s, 50.0, 100.0), vec![blue], "B is in front"); + s.execute("livePaint.expand", &json!({})).unwrap(); + let expanded = node(&s, g); + assert!(!vectorcraft_tools::builder::is_live_paint(&expanded)); + let kept = + expanded.children().unwrap().iter().filter(|c| c.geometric_bounds().is_some_and(|b| b.x1 <= 50.0 + 1e-6)).any(|c| c.appearance.items == want); + assert!(kept, "Expand keeps both fills"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(rows_within(&s, 0.0, 50.0), vec![want.clone()]); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(rows_within(&s, 0.0, 50.0), vec![want]); +} + +/// A face takes the fill rows of the front-most covering source whose fill draws: a source in +/// front whose fill is hidden or transparent, or whose opacity is 0, does not hide the paint of the +/// source behind it, and a face that no such source covers has no paint. +#[test] +fn live_paint_make_uses_frontmost_source_with_drawn_fill() { + for front in ["hidden", "clear", "transparent object"] { + let mut s = session(); + let (a, b) = two(&mut s); + s.edit("t", |d, _| { + let n = d.node_mut(b).unwrap(); + let mut app = (*n.appearance).clone(); + match front { + "hidden" => app.fill_mut().unwrap().visible = false, + "clear" => app.fill_mut().unwrap().opacity = 0.0, + _ => n.opacity = 0.0, + } + n.appearance = app.into(); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let rows_within = |x0: f64, x1: f64| parts_within(&s, g, x0, x1).0.iter().map(|f| f.appearance.items.clone()).collect::>(); + let red = vec![fill_row(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), |_| {})]; + assert_eq!(rows_within(50.0, 100.0), vec![red], "{front}: the overlap shows A"); + assert_eq!(rows_within(100.0, 150.0), vec![vec![fill_row(Paint::None, |_| {})]], "{front}: B alone paints nothing"); + assert_eq!(parts_within(&s, g, 100.0, 150.0).0[0].opacity, 1.0, "{front}"); + } +} + #[test] fn live_paint_fill_assigns_the_face_under_the_point() { let mut s = session(); @@ -2781,7 +3177,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 +3246,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 +3444,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/clip.rs b/crates/engine/src/tests/clip.rs index cbba2f36cc..87af67d95d 100644 --- a/crates/engine/src/tests/clip.rs +++ b/crates/engine/src/tests/clip.rs @@ -119,12 +119,80 @@ fn text_on_top_clips_by_its_glyphs() { assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art)); assert!(b.x1 < 95.0, "{b:?}"); assert_eq!(hit(&s, b.x1 + 3.0, (b.y0 + b.y1) / 2.0), None, "beside the text"); + // An effect that does not reshape it, such as a drop shadow, leaves clicks on its frame. + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {}, "ids": [t.0], "item": null})).unwrap(); + assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art), "in the counter, with a drop shadow"); // Release gives the text back. select(&mut s, &[g]); s.execute("object.clippingMask.release", &json!({})).unwrap(); assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_))); } +#[test] +fn a_hidden_member_of_a_clipping_group_leaves_clicks_on_the_type_frame() { + // The clipping path is a group of an "O" and a hidden rectangle with a Transform effect. The + // hidden rectangle does not clip, so clicks inside the clip group still count the type by its + // frame, the counter of the "O" included. + let mut s = session(); + let art = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()); + let t = id_of(&s.execute("text.create", &json!({"x": 5, "y": 80, "text": "O", "size": 90})).unwrap()); + let b = s.doc().unwrap().doc.node(t).unwrap().geometric_bounds().unwrap(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap()); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 20}, "ids": [r.0], "item": null})).unwrap(); + select(&mut s, &[art, t]); + let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + // Make Clipping Mask takes no group on top, so the group goes in place of the type. + let mut d = (*s.doc().unwrap().doc).clone(); + let mut rect = (*d.remove(r).unwrap()).clone(); + rect.visible = false; + let text = d.remove(t).unwrap(); + let group = vectorcraft_doc::Node::group(d.alloc_id(), vec![text, Arc::new(rect)]); + d.insert(Some(g), 0, group).unwrap(); + let leaf = |x: f64, y: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, y), Default::default()).map(|h| h.leaf); + let middle = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0); + assert_eq!(leaf(middle.0, middle.1), Some(art), "in the counter, inside the frame"); + assert_eq!(leaf(b.x1 + 3.0, middle.1), None, "beside the text"); +} + +#[test] +fn clicks_follow_the_region_a_clipping_paths_effects_give_it() { + // Art from 10 to 90 pt, clipped by the artboard's left half, which a Transform effect moves + // 50 pt right: the art shows on the right half, as clicks find it. + let mut s = session(); + let art = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap()); + let clip = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 100})).unwrap()); + select(&mut s, &[art, clip]); + let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 50}, "ids": [clip.0], "item": null})).unwrap(); + let r = render(&s); + assert!(opaque(&r, 75, 50) && !opaque(&r, 25, 50), "the canvas clips by the moved region"); + assert_eq!(hit(&s, 75.0, 50.0), Some(art), "where the effect moved the clipping path"); + assert_eq!(hit(&s, 25.0, 50.0), None, "the clipping path's own place"); + let d = &s.doc().unwrap().doc; + let at = |x: f64| vectorcraft_doc::hit::objects_at(d, vectorcraft_geom::Point::new(x, 50.0), Default::default(), None); + assert_eq!(at(75.0), [g]); + assert!(at(25.0).is_empty()); + // A marquee across the art's edge reaches it within the moved region only. + let marquee = |x0: f64, x1: f64| vectorcraft_doc::hit::marquee(d, vectorcraft_geom::Rect::new(x0, 40.0, x1, 60.0), None, true); + assert_eq!(marquee(85.0, 95.0), [art], "the right edge, in the moved region"); + assert!(marquee(5.0, 15.0).is_empty(), "the left edge, in the clipping path's own place"); + + // The same with a sublayer that clips by its first object. + let mut d = (**d).clone(); + let members: Vec<_> = d.node(g).unwrap().children().unwrap().to_vec(); + let top = d.layers[0].id; + d.remove(g).unwrap(); + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind { + (*children, *clip) = (members, true); + } + d.insert(Some(top), 0, sublayer).unwrap(); + let leaf = |x: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, 50.0), Default::default()).map(|h| h.leaf); + assert_eq!(leaf(75.0), Some(art)); + assert_eq!(leaf(25.0), None); +} + #[test] fn make_refuses_a_top_object_that_cannot_clip() { let mut s = session(); 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/gradient.rs b/crates/engine/src/tests/gradient.rs index b8c8bcd325..9f404b050d 100644 --- a/crates/engine/src/tests/gradient.rs +++ b/crates/engine/src/tests/gradient.rs @@ -219,9 +219,10 @@ fn rotate_reflect_and_scale_carry_unplaced_gradients() { s.execute("object.rotate", &json!({"angle": 90})).unwrap(); let g = fill_geom(&s, id); assert!((g.end.x - g.start.x).abs() < 1e-9 && (g.length() - 100.0).abs() < 1e-9, "vertical after a 90° turn: {g:?}"); - s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap(); + s.execute("object.reflect", &json!({"axis": "horizontal", "basis": "page"})).unwrap(); let r = fill_geom(&s, id); - // The vertical vector is centred on the object, so the reflection swaps its ends. + // The vertical vector is centred on the object, so the reflection across the page's + // horizontal axis swaps its ends. assert!(r.start.distance(g.end) < 1e-9 && r.end.distance(g.start) < 1e-9, "{g:?} → {r:?}"); // A circle's radial gradient becomes an ellipse under a non-uniform scale. diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index 700c17883d..93c2390237 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -406,7 +406,7 @@ fn a_batch_step_records_what_it_took_from_the_preferences() { ]); s.execute("command.batch", &json!({ "commands": steps })).unwrap(); let p = &s.journal.last().unwrap().1; - assert_eq!(p["commands"][2]["params"], json!({"sx": 300, "strokes": true, "corners": false})); + assert_eq!(p["commands"][2]["params"], json!({"sx": 300, "strokes": true, "corners": false, "basis": "box"})); // Replayed with other preferences, the scale still scales the stroke. let r = replayed(&s); assert!(!r.prefs.scale_strokes); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index a294cc9036..1572004d11 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -1700,6 +1700,7 @@ fn filters_set_effects_and_stroke_styles() { ("test.engine.badn", json!([{"id": "plugin.test.engine.fx", "params": {"n": "two"}}]), "`n`"), ("test.engine.file", json!([{"id": "distort.glass", "params": {"textureImage": {"path": "/etc/hosts"}}}]), "textureImage"), ("test.engine.file2", json!([{"id": "texture.texturizer", "params": {"textureImage": {"path": "/etc/hosts"}}}]), "textureImage"), + ("test.engine.file3", json!([{"id": "artistic.roughPastels", "params": {"textureImage": {"path": "/etc/hosts"}}}]), "textureImage"), ("test.engine.two3d", json!([{"id": "threeD.extrude"}, {"id": "threeD.extrude"}]), "one 3D effect"), ] { let e = filter(&mut s, name, fx).unwrap_err().to_string(); diff --git a/crates/engine/src/tests/rasterfilters.rs b/crates/engine/src/tests/rasterfilters.rs index 534f79b1bc..d1075c1207 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); @@ -320,8 +323,7 @@ fn glass_loads_a_texture_saves_it_and_draws_it() { assert_eq!(doc.node(NodeId(g)).unwrap().appearance.effects[0].params, glass_params(&s, g)); assert_eq!(Renderer::new().render_region(&doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true).pixels, loaded.pixels); // The same file by path, through Effect Options, stores the same texture. - let dir = std::env::temp_dir().join(format!("vc-glass-texture-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("glass-texture"); let path = dir.join("rings.png"); std::fs::write(&path, &png).unwrap(); let (mut t, h) = striped(); @@ -331,7 +333,7 @@ fn glass_loads_a_texture_saves_it_and_draws_it() { assert_eq!(glass_params(&t, h)["textureImage"], json!(stored)); assert_eq!(glass_params(&t, h)["texture"], json!("loaded")); assert_eq!(render(&t).pixels, loaded.pixels); - let _ = std::fs::remove_dir_all(&dir); + drop(dir); // The stored string is taken as it is (as effect.list gives it, and a graphic style copies it). t.execute("effect.apply", &json!({"effect": "distort.glass", "ids": [h], "params": {"textureImage": stored, "texture": "frosted"}})).unwrap(); let second = t.doc().unwrap().doc.node(NodeId(h)).unwrap().appearance.effects[1].params.clone(); @@ -388,6 +390,53 @@ fn texturizer_loads_a_texture_and_draws_it() { assert_eq!(Renderer::new().render_region(&doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true).pixels, loaded.pixels); } +/// Effect › Artistic › Rough Pastels › Load Texture: an image file, given as bytes or by path, is +/// stored with the effect and picked; it draws as the surface, a save and open keeps it, a file +/// that isn't an image is refused without a change, and undo takes it away. +#[test] +fn rough_pastels_loads_a_texture_saves_it_and_draws_it() { + let png = rings_png(); + let data = vectorcraft_format::base64_encode(&png); + let (mut s, g) = striped(); + let file = json!({"name": "rings.png", "dataBase64": data}); + s.execute("effect.apply", &json!({"effect": "artistic.roughPastels", "ids": [g], "params": {"relief": 20, "textureImage": file}})).unwrap(); + let p = glass_params(&s, g); + assert_eq!(p["texture"], json!("loaded"), "loading a texture picks it"); + let stored = p["textureImage"].as_str().unwrap().to_string(); + assert_eq!(vectorcraft_render::effects::pixel::texture(&stored).unwrap().size(), (12, 10)); + let loaded = render(&s); + for (_, builtin) in vectorcraft_render::effects::pixel::TEXTURES { + s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"texture": builtin}})).unwrap(); + assert!(mean_diff(&loaded, &render(&s)) > 0.001, "{builtin}"); + } + s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"texture": "loaded"}})).unwrap(); + assert_eq!(render(&s).pixels, loaded.pixels, "the texture stayed with the effect"); + let doc = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!(doc.node(NodeId(g)).unwrap().appearance.effects[0].params, glass_params(&s, g)); + assert_eq!(Renderer::new().render_region(&doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true).pixels, loaded.pixels); + // A file that isn't an image changes nothing. + let junk = vectorcraft_format::base64_encode(b"not an image"); + let before = glass_params(&s, g); + let e = s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"textureImage": {"dataBase64": junk}}})).unwrap_err(); + assert!(e.to_string().contains("textureImage"), "{e}"); + let e = s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"textureImage": 5}})).unwrap_err(); + assert!(e.to_string().contains("textureImage"), "{e}"); + assert_eq!(glass_params(&s, g), before); + // The same file by path, through Effect Options, stores the same texture; undo takes it away. + let dir = vectorcraft_testkit::TempDir::new("rough-pastels-texture"); + let path = dir.join("rings.png"); + std::fs::write(&path, &png).unwrap(); + let (mut t, h) = striped(); + t.execute("effect.apply", &json!({"effect": "artistic.roughPastels", "ids": [h], "params": {"relief": 20}})).unwrap(); + assert!(glass_params(&t, h).get("textureImage").is_none()); + t.execute("effect.setParams", &json!({"index": 0, "ids": [h], "params": {"textureImage": {"path": path.to_string_lossy()}}})).unwrap(); + drop(dir); + assert_eq!((&glass_params(&t, h)["textureImage"], &glass_params(&t, h)["texture"]), (&json!(stored), &json!("loaded"))); + assert_eq!(render(&t).pixels, loaded.pixels); + t.execute("edit.undo", &json!({})).unwrap(); + assert!(glass_params(&t, h).get("textureImage").is_none(), "undone"); +} + #[test] fn spin_blur_reaches_past_the_corners() { let (mut s, g) = striped(); diff --git a/crates/engine/src/tests/scalestrokes.rs b/crates/engine/src/tests/scalestrokes.rs index d03a9ebf8c..4d8349b6a4 100644 --- a/crates/engine/src/tests/scalestrokes.rs +++ b/crates/engine/src/tests/scalestrokes.rs @@ -216,7 +216,7 @@ fn the_journal_records_the_scale_options_used() { run(&mut s, "object.scale", json!({"sx": 150})); let (cmd, p) = s.journal.last().unwrap().clone(); assert_eq!(cmd, "object.scale"); - assert_eq!(p, json!({"sx": 150, "strokes": false, "corners": true})); + assert_eq!(p, json!({"sx": 150, "strokes": false, "corners": true, "basis": "box"})); // An explicit value stays; moves don't scale, so they record nothing. run(&mut s, "object.scale", json!({"sx": 150, "strokes": true})); assert_eq!(s.journal.last().unwrap().1["strokes"], json!(true)); diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index 10f0ad75ca..e42d7f9736 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -715,3 +715,179 @@ fn svg_export_draws_a_filter_svg_1_1_lacks_as_an_image() { assert_eq!((out.contains(" Vec<(String, bool)> { + let listed = run(s, "svgFilter.list", json!({}))["defaults"].as_array().cloned().unwrap_or_default(); + listed.iter().map(|f| (f["name"].as_str().unwrap().to_string(), f["inDocument"].as_bool().unwrap())).collect() +} + +/// Every document lists the default filters without holding them; applying one adds the effect and +/// the document's copy in one undo step. +#[test] +fn a_default_filter_is_listed_and_copied_into_the_document_when_applied() { + use vectorcraft_render::effects::svg_filter::defaults::DEFAULT_FILTERS; + let mut s = session(); + let listed = defaults(&mut s); + assert_eq!(listed.len(), DEFAULT_FILTERS.len()); + assert!(listed.iter().all(|(_, held)| !held), "a new document holds none of them"); + assert!(names(&mut s).is_empty()); + let soft = DEFAULT_FILTERS.iter().find(|f| f.name == "Soft Shadow").unwrap(); + assert_eq!(run(&mut s, "svgFilter.list", json!({}))["defaults"][2], json!({"name": "Soft Shadow", "xml": soft.xml, "inDocument": false})); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 50.0)); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let before = steps(&s); + let r = run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow"})); + assert_eq!((r["ids"].as_array().unwrap().len(), &r["index"]), (2, &json!(0))); + assert_eq!(steps(&s), before + 1, "the effect and the copy are one step"); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter"); + assert_eq!(names(&mut s), ["Soft Shadow"]); + assert_eq!(drawn(&s, a), json!(soft.xml)); + assert!(defaults(&mut s).contains(&("Soft Shadow".to_string(), true))); + // Applied again, the document's copy is the filter: nothing more is added. + run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow", "ids": [a.0]})); + assert_eq!(names(&mut s), ["Soft Shadow"]); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(names(&mut s).is_empty(), "undo takes the copy back with the effect"); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty()); + run(&mut s, "edit.redo", json!({})); + assert_eq!((names(&mut s), drawn(&s, b)), (vec!["Soft Shadow".to_string()], json!(soft.xml))); + // Nothing to apply it to: no copy and no step. + let mut s = session(); + assert!(s.execute("svgFilter.apply", &json!({"name": "Glow"})).is_err(), "nothing selected"); + assert!(names(&mut s).is_empty()); + assert_eq!(steps(&s), 0); + assert!(err(&mut s, "svgFilter.apply", json!({"name": "glow", "ids": []})).contains("no SVG filter named \"glow\""), "names match exactly"); +} + +/// With a full history, applying a default lets one old step go, as any edit does: the copy joins +/// the step that applied it, and one Undo takes both back. +#[test] +fn a_default_applied_with_a_full_history_is_still_one_step() { + let mut s = session(); + s.active_mut().unwrap().history.limit = 3; + let a = rect(&mut s, 10.0); + rect(&mut s, 30.0); + rect(&mut s, 50.0); + assert_eq!(steps(&s), 3); + run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0]})); + // The application takes one place in the history: only the oldest step went. + assert_eq!(steps(&s), 3); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter"); + run(&mut s, "edit.undo", json!({})); + assert!(names(&mut s).is_empty(), "the copy is undone with the effect"); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty()); +} + +/// Edit SVG Filter on a default saves the edited copy in the document under the default's name; +/// the document's filter then stands in the default's place, and deleting it lists the default again. +#[test] +fn an_edited_default_is_saved_in_the_document_and_delete_restores_the_default() { + use vectorcraft_render::effects::svg_filter::defaults::default_filter; + let mut s = session(); + let glow = default_filter("Glow").unwrap(); + // Saved with its own code: nothing to keep, and no undo step. + run(&mut s, "svgFilter.define", json!({"xml": glow.xml, "replace": "Glow"})); + assert_eq!((names(&mut s).len(), steps(&s)), (0, 0)); + let edited = r#""#; + assert_eq!(run(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"}))["name"], "Glow"); + assert_eq!((names(&mut s), steps(&s)), (vec!["Glow".to_string()], 1)); + assert_eq!(s.doc().unwrap().history.undo[0].label, "Edit SVG Filter"); + let kept = r#""#; + assert_eq!(run(&mut s, "svgFilter.list", json!({}))["filters"][0]["xml"], kept, "it keeps the default's name"); + // Applying the name now applies the document's filter. + let a = rect(&mut s, 10.0); + run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]})); + assert_eq!(drawn(&s, a), json!(kept)); + // Deleting the copy leaves the effect drawing nothing, as for any filter, and lists the default. + run(&mut s, "svgFilter.delete", json!({"name": "Glow"})); + assert_eq!(drawn(&s, a), json!("")); + assert!(defaults(&mut s).contains(&("Glow".to_string(), false))); + // The default itself is not deleted. + let before = steps(&s); + assert!(err(&mut s, "svgFilter.delete", json!({"name": "Glow"})).contains("is a default SVG filter")); + assert!(err(&mut s, "svgFilter.delete", json!({"name": "Nope"})).contains("no SVG filter named")); + assert_eq!(steps(&s), before); + // Applied again, the default is copied back, and the object that named it draws with it. + let b = rect(&mut s, 50.0); + run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [b.0]})); + assert_eq!((drawn(&s, a), drawn(&s, b)), (json!(glow.xml), json!(glow.xml))); + assert_eq!(steps(&s), before + 2, "the rectangle and one step for the application"); + // A new filter may take a default's name the document does not hold. + let mut s = session(); + run(&mut s, "svgFilter.define", json!({"xml": r#""#})); + assert!(defaults(&mut s).contains(&("Invert".to_string(), true))); + // An unknown name is still refused. + assert!(err(&mut s, "svgFilter.define", json!({"xml": SHIFT, "replace": "Nope"})).contains("no SVG filter named \"Nope\"")); +} + +/// With `index`, the filter takes the place of an applied SVG filter, a default with its copy in +/// the same undo step; any other effect keeps its place. +#[test] +fn apply_with_an_index_replaces_an_applied_filter() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "svgFilter.define", json!({"xml": SHIFT})); + run(&mut s, "svgFilter.apply", json!({"name": "Shift", "ids": [a.0]})); + run(&mut s, "effect.apply", json!({"effect": "stylize.feather", "ids": [a.0]})); + let before = steps(&s); + let r = run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": 0, "item": null})); + assert_eq!(r["ids"], json!([a.0])); + assert_eq!(steps(&s), before + 1, "one step"); + let fx = s.doc().unwrap().doc.node(a).unwrap().appearance.effects.clone(); + assert_eq!((fx.len(), fx[0].params["name"].as_str(), fx[1].id.as_str()), (2, Some("Invert"), "stylize.feather")); + assert_eq!(names(&mut s), ["Shift", "Invert"]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&mut s), ["Shift"]); + assert_eq!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects[0].params["name"], "Shift"); + // Not an SVG filter, no effect there, or not an index: refused, and the default is not copied. + let before = steps(&s); + for (index, why) in [ + (json!(1), "applied SVG filter"), + (json!(7), "applied SVG filter"), + (json!("x"), "`index`"), + (json!(-1), "`index`"), + (json!(null), "`index`"), + ] { + let e = err(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": index, "item": null})); + assert!(e.contains(why), "{index}: {e}"); + } + assert_eq!((names(&mut s), steps(&s)), (vec!["Shift".to_string()], before)); +} + +/// A default needs room in the document: at 64 filters applying one is refused, and a filter the +/// document holds still applies. +#[test] +fn a_full_document_refuses_a_default_it_does_not_hold() { + let mut s = session(); + let a = rect(&mut s, 10.0); + for i in 0..64 { + run(&mut s, "svgFilter.define", json!({"xml": format!("")})); + } + let before = steps(&s); + assert!(err(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]})).contains("at most 64 SVG filters")); + let edited = r#""#; + assert!(err(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"})).contains("at most 64 SVG filters")); + assert_eq!(steps(&s), before); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty()); + run(&mut s, "svgFilter.apply", json!({"name": "f3", "ids": [a.0]})); +} + +/// A default applied in one document is written to SVG as a filter and read back from the native +/// format with the document's copy. +#[test] +fn an_applied_default_survives_svg_export_and_a_native_round_trip() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "svgFilter.apply", json!({"name": "Grayscale", "ids": [a.0]})); + let out = svg(&mut s); + assert!(out.contains(" String { + "\n\ + ]>\n\ + \ + \ + \ + \ + \ +

Bravo

true\ + \n\t\tfile:////Users/me/Art%20Work/logo%23one.png\n\t\t\ + NorthSouth\ + Q1102.5\ + 2024-4\ + ignored\ + FALSE C:\\Art\\logo.png\ + 78\ + \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\t

x

\n\ \t\t\t\t\t

y < 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\tQ11\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/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 6fd17049d4..fce3742d11 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -752,6 +752,10 @@ fn structured_junk() { )}), ), ("svgFilter.apply", json!({"name": "\u{0}", "ids": [u64::MAX]})), + ("svgFilter.apply", json!({"name": "Glow", "index": u64::MAX, "item": -1})), + ("svgFilter.apply", json!({"name": "Rough Edges", "index": [0], "ids": "x"})), + ("svgFilter.define", json!({"xml": "", "replace": "Glow"})), + ("svgFilter.delete", json!({"name": "Glow"})), ("svgFilter.delete", json!({"name": ["a"]})), ( "effect.apply", diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 7e613460cd..0ade04c72a 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] @@ -1831,6 +1854,80 @@ proptest! { } } +/// A 4 × 2 pixel RGB PSD file whose clipping path resource (2999) names its saved path "P" +/// (resource 2000): a closed subpath of a linked and two unlinked knots, an open subpath, and the +/// initial fill record saying the fill starts with all pixels. +fn clipped_psd() -> Vec { + let record = |selector: u16, body: &[i32]| { + let mut r = selector.to_be_bytes().to_vec(); + r.extend(body.iter().flat_map(|v| v.to_be_bytes())); + r.resize(26, 0); + r + }; + let one = 1 << 24; + let mut path = record(6, &[]); + path.extend(record(8, &[1 << 16])); + path.extend(record(0, &[3 << 16])); + path.extend(record(1, &[0, 0, 0, one / 2, 0, one])); + path.extend(record(2, &[one, one, one, one, one, one])); + path.extend(record(2, &[one, 0, one, 0, one, 0])); + path.extend(record(3, &[2 << 16])); + path.extend(record(5, &[-one, -one, 0, 0, 2 * one, 2 * one])); + path.extend(record(4, &[one / 4, one / 4, one / 4, one / 4, one / 4, one / 4])); + let mut res = b"8BIM\x07\xd0\x01P".to_vec(); + res.extend((path.len() as u32).to_be_bytes()); + res.extend(path); + res.extend(b"8BIM\x0b\xb7\0\0"); + res.extend(8u32.to_be_bytes()); + res.extend([1, b'P', 0, 0, 0, 0, 0, 0]); + let mut f = b"8BPS\0\x01\0\0\0\0\0\0\0\x03\0\0\0\x02\0\0\0\x04\0\x08\0\x03".to_vec(); + f.extend([0; 4]); + f.extend((res.len() as u32).to_be_bytes()); + f.extend(res); + f.extend([0; 4]); + f.extend([0, 0]); + f.extend((0..24u8).map(|v| v * 10)); + f +} + +#[test] +fn the_clipped_psd_sample_places_in_a_clip_group() { + let path = vectorcraft_engine::cmd::fileio::psdread::clipping_path(&clipped_psd()).unwrap(); + assert_eq!(path.subpaths.iter().map(|s| (s.anchors.len(), s.closed)).collect::>(), [(4, true), (3, true), (2, false)]); + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("file.place", &json!({"name": "c.psd", "dataBase64": vectorcraft_format::base64_encode(&clipped_psd())})).unwrap(); + assert!(r["image"].is_u64(), "{r}"); +} + +proptest! { + #![proptest_config(config())] + + /// Mutated copies of a PSD file with a clipping path (its resources: the path records, their + /// selectors, counts and points, and the names) never crash reading the path, placing the file + /// or opening its merged image. + #[test] + fn mutated_psd_clipping_paths_never_panic(cut in 0usize..1000, edits in prop::collection::vec((0usize..300, any::()), 0..12)) { + let mut bytes = clipped_psd(); + let len = bytes.len(); + for (at, b) in edits { + if let Some(x) = bytes.get_mut(at % len) { + *x = b; + } + } + bytes.truncate((cut % (len + 1)).max(8)); + let r = catch_quiet(|| { + let _ = vectorcraft_engine::cmd::fileio::psdread::clipping_path(&bytes); + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let p = json!({"name": "c.psd", "dataBase64": vectorcraft_format::base64_encode(&bytes), "thumbnail": 8}); + let _ = no_panic(s.execute("file.place", &p)); + let _ = no_panic(s.execute("document.open", &json!({"name": "c.psd", "dataBase64": vectorcraft_format::base64_encode(&bytes), "layers": false}))); + }); + prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); + } +} + /// 1-bit TIFFs compressed with CCITT Group 3: modified Huffman (Compression 2) in three strips, T.4 /// (Compression 3) with two-dimensional rows, fill bits, six EOLs at the end and each byte's lowest /// bit first, and T.4 two-dimensional rows in 16 × 16 tiles. @@ -2904,9 +3001,9 @@ fn arb_body() -> impl Strategy> { } /// WMF record functions VectorCraft reads, and one it doesn't. -const WMF_FUNCTIONS: [u16; 33] = [ +const WMF_FUNCTIONS: [u16; 35] = [ 0x0324, 0x0325, 0x0538, 0x041B, 0x0418, 0x061C, 0x0817, 0x081A, 0x0830, 0x0416, 0x0415, 0x02FA, 0x02FC, 0x02FB, 0x012D, 0x01F0, 0x0521, 0x0A32, - 0x0F43, 0x0B41, 0x0940, 0x061D, 0x0213, 0x0214, 0x001E, 0x0127, 0x0106, 0x0209, 0x012E, 0x00F7, 0x01F9, 0x0142, 0x0999, + 0x0F43, 0x0B41, 0x0940, 0x061D, 0x0213, 0x0214, 0x001E, 0x0127, 0x0106, 0x0209, 0x012E, 0x00F7, 0x01F9, 0x0142, 0x0103, 0x0104, 0x0999, ]; proptest! { @@ -2933,6 +3030,30 @@ proptest! { survive_metafile("WMF records", "x.wmf", &wmf_of(&records))?; } + #[test] + fn random_headerless_wmf_records_never_panic(records in prop::collection::vec((prop::sample::select(WMF_FUNCTIONS.to_vec()), arb_body()), 0..32)) { + // Without the placeable header, the map and mix modes the records set decide the scale. + survive_metafile("headerless WMF records", "x.wmf", &wmf_of(&records)[22..])?; + } + + #[test] + fn random_emf_plus_records_never_panic(records in prop::collection::vec((0x4001u16..0x403B, any::(), arb_body()), 0..32)) { + // One comment of EMF+ records (type, flags, data) after an EmfPlusHeader. + let mut plus = vec![]; + let header = (0x4001u16, 0u16, [0xDBC0_1002u32, 0, 96, 96].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + for (kind, flags, data) in std::iter::once(&header).chain(&records) { + plus.extend(kind.to_le_bytes()); + plus.extend(flags.to_le_bytes()); + plus.extend((12 + data.len() as u32).to_le_bytes()); + plus.extend((data.len() as u32).to_le_bytes()); + plus.extend(data); + } + let mut comment = (4 + plus.len() as u32).to_le_bytes().to_vec(); + comment.extend(b"EMF+"); + comment.extend(plus); + survive_metafile("EMF+ records", "x.emf", &emf_of(&[(70, comment)]))?; + } + #[test] fn pasted_metafiles_never_panic(which in 0usize..2, cut in 0usize..200_000, edits in prop::collection::vec((0usize..200_000, any::()), 0..12)) { paste_from_elsewhere("clipboard.importEmf", json!({"dataBase64": mutated_b64(metafile_samples()[which].clone(), cut, &edits)}))?; diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 3df902b97f..609e0aedee 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -143,6 +143,10 @@ //! A path or compound path with a brush the reader reads live is written with an art style whose //! stroke is the brush's filter (`writer::brushes`). A brush is written only when the reader reads //! it back with its settings. +//! - Graphs, as the reader reads them (`read/graph.rs`): a graph on the layers whose records the +//! reader reads back as the same graph ([`crate::ai_graph`]) is written as its group between +//! `%_Gs`, its functional records and `%_GS`, each series' group tagged `Go` right after its end; +//! any other graph, and a graph with art left out, as its art, with a warning. //! //! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at //! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index a67102f5d0..c3e3e3c422 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -4191,6 +4191,57 @@ fn standard_vertical_roman_alignment_comes_back() { assert_eq!(flags(&texts(&read_back(&both))[0])[2], (false, true)); } +/// Insert Aki Left and Right come back on each run, in vertical and horizontal type: a run with +/// either writes it as key 49 or 50 in 1/1000 em, a run without writes neither, and nothing is +/// reported. Each object lays out as it did. A run that also has an attribute the text document +/// leaves out is still reported. +#[test] +fn insert_aki_comes_back() { + use vectorcraft_doc::{CharStyle, TextObject, TextRun}; + let plain = style(14.0, Color::BLACK); + let left = CharStyle { aki_left: 250.0, ..plain.clone() }; + let both = CharStyle { aki_left: 125.5, aki_right: 500.0, ..plain.clone() }; + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + let mut down = TextObject::point(vectorcraft_geom::Point::new(150.0, 20.0), "", plain.clone()); + down.runs = vec![TextRun::new("AB", left.clone()), TextRun::new("CD", plain.clone()), TextRun::new("EF", both.clone())]; + down.vertical = true; + let mut across = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "", plain.clone()); + across.runs = vec![TextRun::new("GH", both.clone()), TextRun::new("IJ", plain.clone())]; + for t in [down, across] { + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + same_lines(&type_lines(&back), &type_lines(&doc)); + let texts = |d: &Document| -> Vec { + d.layers[0].children().unwrap().iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() + }; + let aki = |t: &TextObject| t.runs.iter().map(|r| (r.style.aki_left, r.style.aki_right)).collect::>(); + let (written, read) = (texts(&doc), texts(&back)); + assert_eq!(read.iter().map(aki).collect::>(), [vec![(250.0, 0.0), (0.0, 0.0), (125.5, 500.0)], vec![(125.5, 500.0), (0.0, 0.0)]]); + let origins = |t: &TextObject| { + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.iter().map(|g| (r3(g.origin.x), r3(g.origin.y))).collect::>() + }; + for (w, r) in written.iter().zip(&read) { + assert_eq!(origins(r), origins(w), "vertical={}", w.vertical); + } + let decoded = text_document(&program(&doc)); + for (key, count) in [("/49 250.0", 1), ("/49 125.5", 2), ("/50 500.0", 2)] { + assert_eq!(decoded.matches(key).count(), count, "{key}: {decoded}"); + } + assert_eq!(decoded.matches("/49 ").count() + decoded.matches("/50 ").count(), 5, "{decoded}"); + // Underline is still left out, and reported. + let mut lossy = doc.clone(); + let id = lossy.layers[0].children().unwrap()[0].id; + if let Some(NodeKind::Text(t)) = lossy.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.underline = true; + } + assert_eq!(export_ai_editing(&lossy, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]); +} + /// The text document of program `text` (LF line ends), decoded, with its UTF-16 strings' zero /// bytes left out. fn text_document(text: &str) -> String { @@ -10856,3 +10907,73 @@ fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() { same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]); } } + +/// A graph whose records read back whole is written with them, each series' group tagged before +/// its name, and opens again as the same live graph, also from a PDF-compatible file's first page. +#[test] +fn graphs_are_written_with_their_records_and_open_live() { + use crate::ai_graph::sample; + for (what, doc) in sample::kept() { + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::GRAPHS), "{what}: {:?}", out.warnings); + let text = program(&doc); + assert_eq!((text.matches("%_Gs\n").count(), text.matches("%_GS\n").count()), (1, 1), "{what}: {text}"); + assert!(text.contains("U\n%_2 ") && text.contains(" 0 0 Go\n%_/ArtDictionary :\n"), "{what}: the tag comes before the series' name: {text}"); + let written = sample::graphs(&doc); + let graphs = sample::graphs(&read_back(&doc)); + assert_eq!(graphs.len(), 1, "{what}"); + assert!(sample::same(&written[0].0, &graphs[0].0), "{what}: {:#?}\n{:#?}", written[0].0, graphs[0].0); + assert_eq!(graphs[0].1, written[0].1, "{what}: the members and their series"); + } + let doc = sample::document(sample::spec(vectorcraft_doc::GraphKind::Column)); + let (p, _) = private_data(&doc, &opts()).unwrap(); + let pdf = + vectorcraft_pdf::export(&doc, &vectorcraft_pdf::PdfOptions { private_data: Some(p), ..vectorcraft_pdf::PdfOptions::uncompressed() }).unwrap(); + let (read, _) = crate::ai_alone(&vectorcraft_pdf::illustrator_data(&pdf, None).unwrap()).unwrap(); + let graphs = sample::graphs(&read); + assert_eq!(graphs.len(), 1); + assert!(sample::same(&sample::graphs(&doc)[0].0, &graphs[0].0)); +} + +/// A graph whose records wouldn't read back as it is is written as its art, without records, with +/// the warning. +#[test] +fn graphs_the_records_cant_keep_are_written_as_their_art() { + use crate::ai_graph::sample; + for (what, doc) in sample::unkept() { + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRAPHS), "{what}: {:?}", out.warnings); + let text = program(&doc); + assert!(!text.contains("%_Gs") && !text.contains(" Go\n") && !text.contains("%_GS"), "{what}: {text}"); + let read = read_back(&doc); + assert!(sample::graphs(&read).is_empty(), "{what}"); + let paths = |d: &Document| { + let mut count = 0; + d.walk(|n| count += usize::from(matches!(n.kind, NodeKind::Path { .. }))); + count + }; + assert_eq!(paths(&read), paths(&doc), "{what}: the graph's art is kept"); + } +} + +/// A graph with art left out for the object limit is written as the art there is room for, without +/// records or tags, with the warning; with room for all of it, it is written with its records. +#[test] +fn a_graph_with_art_left_out_is_written_without_records() { + use crate::ai_graph::sample; + let doc = sample::document(sample::spec(vectorcraft_doc::GraphKind::Column)); + let all = export_ai_editing(&doc, &opts()).unwrap(); + let read = crate::import::objects_read(&all.program).unwrap(); + let room = export_within(&doc, &opts(), read).unwrap(); + assert_eq!(room.program, all.program); + for max in [0, 1, read / 2, read - 1] { + let out = export_within(&doc, &opts(), max).unwrap(); + let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + assert!( + out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT) && out.warnings.iter().any(|w| w == writer::GRAPHS), + "{max}: {:?}", + out.warnings + ); + assert!(!text.contains("%_Gs") && !text.contains(" Go\n") && !text.contains("%_GS"), "{max}: {text}"); + } +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 98b027f79d..15bd97d3b5 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -295,6 +295,13 @@ pub(super) struct Writer<'a> { shown: Vec, /// The copy of an image that the last [`Self::image`] wrote as a window, when it did. windowed: Option, + /// Writing a graph's art with its records ([`Self::graph_records`]): a graph inside it is written + /// as its art. + in_graph: bool, + /// The `Go` line the next object, a graph's series group, is followed by. + series_tag: Option, + /// Where the `Go` lines of the graph being written start in [`Self::body`]. + graph_tags: Vec, } impl<'a> Writer<'a> { @@ -367,6 +374,9 @@ impl<'a> Writer<'a> { whole_images: HashMap::new(), shown: vec![], windowed: None, + in_graph: false, + series_tag: None, + graph_tags: vec![], } } @@ -642,6 +652,7 @@ impl<'a> Writer<'a> { /// One object: its state before it, its transparency, and its name and opacity mask after it. fn node(&mut self, n: &Node) { + let tag = self.series_tag.take(); if let NodeKind::Layer { .. } = n.kind { return self.write_layer(n, &[]); } @@ -652,7 +663,8 @@ impl<'a> Writer<'a> { if self.in_symbol { self.wrote_fixed |= symbols::redrawn(n); } - if n.extras().graph.is_some() && !self.in_look { + let graph = if n.extras().graph.is_some() && !self.in_look { self.graph_records(n) } else { None }; + if n.extras().graph.is_some() && !self.in_look && graph.is_none() { self.warn(GRAPHS); } // On the layers or in an opacity mask's art, outside art cut to a clipping object: with its @@ -680,14 +692,18 @@ impl<'a> Writer<'a> { let start = self.body.len(); // An image's copy written as the part that its opacity mask, among other regions, shows. let mut mask_window = None; + let charged = self.charges(); match &n.kind { NodeKind::Layer { .. } => {} NodeKind::Group { children, clip: true } => self.clip_group(children, xy), NodeKind::Group { children, clip: false } => { if self.open_group("u") { + self.in_graph |= graph.is_some(); for c in children { + self.series_tag = graph.as_ref().and_then(|g| g.tags.get(&c.id).cloned()); self.node(c); } + self.in_graph &= graph.is_none(); self.end_group("U", xy); } } @@ -790,6 +806,11 @@ impl<'a> Writer<'a> { // A group's dictionary goes between its end and its state block. let block = (self.block_end == self.body.len() && self.block_start >= start).then(|| self.body.split_off(self.block_start)); self.block_end = usize::MAX; + // A graph's series group is tagged right after its end, before its dictionary. + if let Some(t) = tag { + self.graph_tags.push(self.body.len()); + self.line(&t); + } let mask_written = self.dictionary(n); if let Some(b) = block { self.body.push_str(&b); @@ -803,6 +824,41 @@ impl<'a> Writer<'a> { if deform { self.line(&envelopes::plugin_line()); } + if let Some(g) = graph { + self.graph_end(g, start, charged); + } + } + + /// The records of graph `n` ([`crate::ai_graph::records`]) when it is written as a graph: on the + /// layers, outside art cut to a clipping object, symbols' art, live objects' art and another + /// graph, and without an art style anywhere in it. `None` when it is written as its art. + fn graph_records(&self, n: &Node) -> Option { + fn has_style(n: &Node, styled: &HashMap>) -> bool { + styled.contains_key(&n.id) || n.children().is_some_and(|c| c.iter().any(|c| has_style(c, styled))) + } + let placed = self.hidden == 0 && self.nest == 0 && self.drawn == 0 && self.clip.is_none() && !self.in_symbol && !self.in_graph; + if !placed || has_style(n, &self.styled) { + return None; + } + crate::ai_graph::records(n, self.to_art) + } + + /// The graph whose art was written from `start` on, charged from `charged`, ends: its records go + /// before the art and `%_GS` after it, or, when art in it was left out ([`Self::take_objects`]), + /// its `Go` lines are taken out and it stays its art, with a warning. + fn graph_end(&mut self, records: crate::ai_graph::Records, start: usize, charged: Charges) { + let tags = std::mem::take(&mut self.graph_tags); + if self.body.len() > start && !self.left_out_since(charged) { + self.body.insert_str(start, &records.head); + self.line(crate::ai_graph::END); + return; + } + for at in tags.into_iter().rev() { + if let Some(len) = self.body.get(at..).and_then(|rest| rest.find('\n')) { + self.body.replace_range(at..=at + len, ""); + } + } + self.warn(GRAPHS); } /// Live object `n`, of transparency `xy`, as a group of its art, with `warning` when it is given. diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 885af725b7..2e90817b98 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -20,6 +20,7 @@ use std::fmt::Write; use kurbo::{ParamCurveArclen, PathSeg}; use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::text::MAX_AKI; use vectorcraft_doc::{ AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, LineCap, LineJoin, Mojikumi, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TextKind, TextObject, VerticalAlign, @@ -29,7 +30,7 @@ use vectorcraft_geom::{Affine, PathData, Point}; use crate::ps; /// What the text document holds of type, and what it leaves out. -pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; +pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; /// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it. const STREAM_VERSION: u32 = 14; @@ -326,6 +327,12 @@ fn end_read_as_none(t: &TextObject) -> bool { !closed(&segs) && end < 1.0 - 1e-9 && place_on(&segs, end) >= segs.len() as f64 - 0.02 } +/// Insert Aki Left or Right `v` as the text document holds it: 0 to [`MAX_AKI`] in 1/1000 em, and 0 +/// for a value that is not a number. +fn held_aki(v: f64) -> f64 { + if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) } +} + /// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { // Small capitals are read back at Document Setup's default size. @@ -360,6 +367,8 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { tate_chu_yoko: s.tate_chu_yoko, // Key 35 holds one of the two: a Tate-chu-yoko run is read back without the other. standard_vertical_roman: s.standard_vertical_roman && !s.tate_chu_yoko, + aki_left: held_aki(s.aki_left), + aki_right: held_aki(s.aki_right), ..CharStyle::default() } }; @@ -677,6 +686,14 @@ impl TextDoc { }; d.push((12, V::Int(caps))); d.push((35, V::Int(baseline_direction(st)))); + // Insert Aki Left and Right in 1/1000 em, as the reader reads keys 49 and 50. No key is no + // space added: neither the stories' character attributes nor `[Normal Character Style]` set one. + for (key, v) in [(49, st.aki_left), (50, st.aki_right)] { + let v = held_aki(v); + if v > 0.0 { + d.push((key, real(v))); + } + } let fill = solid(&st.fill).flatten(); // A stroke of no width keeps its paint. let stroke = solid(&st.stroke).flatten(); diff --git a/crates/eps/src/ai_graph.rs b/crates/eps/src/ai_graph.rs new file mode 100644 index 0000000000..3e1cebd9f9 --- /dev/null +++ b/crates/eps/src/ai_graph.rs @@ -0,0 +1,661 @@ +//! A live graph's records, which the legacy `.ai` writer ([`crate::legacy_ai`]) and the editing data +//! writer ([`crate::ai_editing`]) both write around a graph's group (Adobe Illustrator File Format +//! Specification, version 7.0, §17 and appendix A): `%_Gs`, the functional records on `%_` lines +//! (`Gb`, `Gy`, `Gd`, three `Ga` … `GA` axes, `Gz`, `Gc` cells and `GC`), the drawn art in one group +//! with each series' group followed by `%_2 column 0 0 Go`, then `%_GS`. +//! +//! A graph is written so only when the `.ai` reader (`import::ai::read::graph`) reads every record +//! back as the same graph: one of the four graph types it reads (grouped and stacked column, line, +//! area), the settings it keeps, a table it holds, and drawn art it attaches the graph to (each +//! series' group a direct member of the graph's, of paths painted with one solid fill and one plain +//! line, and the plot's left and bottom edges drawn as stroked lines). Any other graph is written as +//! its art, with a warning. + +use std::collections::HashMap; +use std::fmt::Write; + +use kurbo::{PathSeg, Point}; +use vectorcraft_color::{BlendMode, Paint}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, Node, NodeId, NodeKind, PiePosition, + PieSort, TickLength, ValueAxisSide, +}; +use vectorcraft_effects::stroke; +use vectorcraft_geom::{Affine, Rect}; + +use crate::ps; + +/// Most cells of a graph's table, its label row and column included. +const MAX_CELLS: usize = 2_600_000; + +/// Longest cell string, in bytes (appendix A, `Gc`). +const MAX_CELL_TEXT: usize = 255; + +/// Most characters of the text before or after a value axis' numbers (appendix A, `Ga`, `GA`). +const MAX_AFFIX: usize = 9; + +/// Most tick marks per division the reader keeps. +const MAX_TICK_MARKS: usize = 20; + +/// Most divisions of a value axis with set values the reader keeps. +const MAX_DIVISIONS: usize = 100; + +/// How far an axis line may be from the plot's edge, in points. +const EDGE: f64 = 0.01; + +/// Most values one `Gc` takes. +const CELLS_PER_RECORD: usize = 15; + +/// A graph's records: what goes before its group (`%_Gs` to `%_GC`), and the `Go` line that follows +/// each series' group, by the group's id. `%_GS` follows the group. +pub(crate) struct Records { + pub(crate) head: String, + pub(crate) tags: HashMap, +} + +/// The line that ends a graph's records, after its group. +pub(crate) const END: &str = "%_GS"; + +/// The records of graph `n` (a group holding [`vectorcraft_doc::NodeExtras::graph`]), its art written +/// through `to_art`; `None` when the reader would not read them back as the same graph. +pub(crate) fn records(n: &Node, to_art: Affine) -> Option { + let g = n.extras().graph.as_deref()?; + let NodeKind::Group { children, clip: false } = &n.kind else { return None }; + (n.visible && n.extras().mask.is_none() && all_shown(n)).then_some(())?; + let ty = kind_code(g.kind)?; + settings_kept(g).then_some(())?; + let (left_manual, left_min, left_max, left_step) = axis(g.ticks, g.axis_min, g.axis_max)?; + let (right_manual, right_min, right_max, right_step) = axis(g.right_ticks, g.right_axis_min, g.right_axis_max)?; + // The table as the graph draws it: `cells` leaves out rows and series past the model's limits. + let rows = g.rows.len(); + let width = g.rows.iter().map(Vec::len).max().unwrap_or(0); + ((1..=MAX_GRAPH_CATEGORIES).contains(&rows) && (1..=MAX_GRAPH_SERIES).contains(&width)).then_some(())?; + let cells = g.cells(); + cells.iter().flatten().all(|v| v.is_none_or(f64::is_finite)).then_some(())?; + cells.iter().flatten().any(Option::is_some).then_some(())?; + let first_row = usize::from(!g.series.is_empty()); + let first_col = usize::from(!g.categories.is_empty()); + (g.series.is_empty() || g.series.len() == width).then_some(())?; + (g.categories.is_empty() || g.categories.len() == rows).then_some(())?; + let (total_rows, total_cols) = (rows + first_row, width + first_col); + total_rows.checked_mul(total_cols).filter(|c| *c <= MAX_CELLS)?; + g.series.iter().chain(&g.categories).all(|l| l.len() <= MAX_CELL_TEXT && !l.chars().any(char::is_control)).then_some(())?; + [&g.prefix, &g.suffix, &g.right_prefix, &g.right_suffix] + .iter() + .all(|a| a.chars().count() <= MAX_AFFIX && !a.chars().any(char::is_control)) + .then_some(())?; + // The plot, and the art the reader attaches the graph to. + let r = g.rect; + (r.is_finite() && r.width() > 0.0 && r.height() > 0.0).then_some(())?; + let plot = to_art.transform_rect_bbox(r); + (plot.is_finite() && plot.width() > 0.0 && plot.height() > 0.0).then_some(())?; + let tags = series_groups(children, width, first_col, g.kind == GraphKind::Line)?; + draws_axes(n, r).then_some(())?; + let placed = n.geometric_bounds()?; + (r.x0 >= placed.x0 - EDGE && r.y0 >= placed.y0 - EDGE && r.x1 <= placed.x1 + EDGE && r.y1 <= placed.y1 + EDGE).then_some(())?; + + let mut head = String::from("%_Gs\n"); + let _ = writeln!(head, "%_{} {} {} {} Gb", real(plot.x0), real(plot.y1), real(plot.x1), real(plot.y0)); + let flag = |b: bool| u8::from(b); + let _ = writeln!( + head, + "%_{ty} {} {} 14 {} {} 0 {} 6 44 Gy", + flag(g.drop_shadow), + flag(g.first_row_in_front), + flag(g.mark_points), + flag(g.connect_points), + flag(g.legend_across_top) + ); + let _ = + writeln!(head, "%_10 2 {} 0 {} {} {} Gd", flag(g.first_column_in_front), real(g.column_width), real(g.cluster_width), flag(g.edge_to_edge)); + // Tick marks per division: 0 and 1 both mean one, at the labels, and the reader reads 0 as 1. + let (category_marks, left_marks, right_marks) = (g.category_tick_marks.max(1), g.tick_marks.max(1), g.right_tick_marks.max(1)); + let _ = writeln!(head, "%_1 () Ga\n%_0 {} 0 0 0 {category_marks} {} () GA", tick(g.category_tick_length), flag(g.ticks_between_labels)); + let _ = writeln!(head, "%_2 {} Ga", ps::bytes(g.prefix.as_bytes())); + let _ = writeln!( + head, + "%_{} {} {} {} {} {} 0 {} GA", + flag(left_manual), + tick(g.tick_length), + real(left_min), + real(left_max), + real(left_step), + left_marks, + ps::bytes(g.suffix.as_bytes()) + ); + let _ = writeln!(head, "%_4 {} Ga", ps::bytes(g.right_prefix.as_bytes())); + let _ = writeln!( + head, + "%_{} {} {} {} {} {} 0 {} GA", + flag(right_manual), + tick(g.right_tick_length), + real(right_min), + real(right_max), + real(right_step), + right_marks, + ps::bytes(g.right_suffix.as_bytes()) + ); + let _ = writeln!(head, "%_{total_rows} {total_cols} {first_row} {first_col} Gz"); + let mut table = Table::new(&mut head); + if first_row == 1 { + if first_col == 1 { + table.text(""); + } + for s in &g.series { + table.text(s); + } + } + for (i, row) in cells.iter().enumerate() { + if let Some(c) = g.categories.get(i) { + table.text(c); + } + for v in row { + match v { + Some(v) => table.num(*v), + None => table.text(""), + } + } + } + table.finish(); + head.push_str("%_GC\n"); + Some(Records { head, tags }) +} + +/// The `Gc` records of a table, its cells in rows: at most [`CELLS_PER_RECORD`] values each, one +/// string at most. +struct Table<'a> { + out: &'a mut String, + values: usize, + string: bool, +} + +impl<'a> Table<'a> { + fn new(out: &'a mut String) -> Self { + Self { out, values: 0, string: false } + } + + fn start(&mut self, string: bool) { + if self.values == CELLS_PER_RECORD || (string && self.string) { + self.finish(); + } + self.out.push_str(if self.values == 0 { "%_" } else { " " }); + self.values += 1; + self.string |= string; + } + + fn text(&mut self, t: &str) { + self.start(true); + self.out.push_str(&ps::bytes(t.as_bytes())); + } + + fn num(&mut self, v: f64) { + self.start(false); + self.out.push_str(&real(v)); + } + + fn finish(&mut self) { + if self.values > 0 { + self.out.push_str(" Gc\n"); + } + (self.values, self.string) = (0, false); + } +} + +/// `v` as a PostScript number that reads back as the same value. +fn real(v: f64) -> String { + if v == 0.0 { + "0".into() + } else if (1e-4..1e15).contains(&v.abs()) { + format!("{v}") + } else { + format!("{v:e}") + } +} + +/// `graphType`: 5 grouped column, 6 stacked column, 7 line, 10 area; the reader reads no other type. +fn kind_code(k: GraphKind) -> Option { + match k { + GraphKind::Column => Some(5), + GraphKind::StackedColumn => Some(6), + GraphKind::Line => Some(7), + GraphKind::Area => Some(10), + _ => None, + } +} + +/// `tickMarkType`: 13 none, 14 short, 15 the length of the plot. +fn tick(t: TickLength) -> u8 { + match t { + TickLength::None => 13, + TickLength::Short => 14, + TickLength::Full => 15, + } +} + +/// Whether `g`'s settings are ones the records give and the reader keeps: a legend beside or across +/// the top, every series of the graph's type, one value axis on the left, lines not filled, no graph +/// designs, label formatting or pie settings, column and cluster widths of 1% to 1000%, and at most +/// [`MAX_TICK_MARKS`] tick marks a division. +fn settings_kept(g: &GraphSpec) -> bool { + let percent = |p: f64| (1.0..=1000.0).contains(&p); + g.legend + && g.series_kinds.iter().all(|k| k.is_none_or(|k| k == g.kind)) + && g.value_axis == ValueAxisSide::Left + && !g.separate_scales + && g.right_series.is_empty() + && !g.filled_lines + && g.series_markers.iter().all(Option::is_none) + && g.series_columns.iter().all(Option::is_none) + && g.label_styles == LabelStyles::default() + && !g.pie_legend_in_wedges + && g.pie_position == PiePosition::Even + && g.pie_sort == PieSort::None + && percent(g.column_width) + && percent(g.cluster_width) + && [g.tick_marks, g.right_tick_marks, g.category_tick_marks].iter().all(|m| *m <= MAX_TICK_MARKS) +} + +/// A value axis' `useManualValues`, lowest and highest value and `betweenValue`: automatic (no tick +/// count and no values), or a whole number of divisions (1 to [`MAX_DIVISIONS`]) between a lowest +/// and a higher highest value, which the reader reads back as the same count. +fn axis(ticks: usize, min: Option, max: Option) -> Option<(bool, f64, f64, f64)> { + match (ticks, min, max) { + (0, None, None) => Some((false, 0.0, 0.0, 0.0)), + (1..=MAX_DIVISIONS, Some(lo), Some(hi)) if lo.is_finite() && hi.is_finite() && hi > lo => { + let step = (hi - lo) / ticks as f64; + let n = (hi - lo) / step; + let exact = step > 0.0 && step.is_finite() && (n - n.round()).abs() <= 1e-6 * n.round().max(1.0) && n.round() == ticks as f64; + exact.then_some((true, lo, hi, step)) + } + _ => None, + } +} + +/// Whether `n` and everything in it is shown. +fn all_shown(n: &Node) -> bool { + n.visible && n.children().is_none_or(|c| c.iter().all(|c| all_shown(c))) +} + +/// Whether `n` is shown, fully opaque, in Normal mode, not isolated and without an opacity mask or +/// effects: the reader keeps a series' paint only from groups and paths drawn so. +fn as_drawn(n: &Node) -> bool { + n.visible + && n.opacity == 1.0 + && n.blend == BlendMode::Normal + && !n.isolate + && n.extras().mask.is_none() + && !n.appearance.effects.iter().any(|e| e.visible) +} + +/// The visible fill and line `p` is written with as one path object: a solid fill, and a solid +/// plain line with its weight, each opaque, in Normal mode and without effects of its own. `None` +/// when it has other paint, more than one of either, or isn't one path of one subpath. +#[allow(clippy::type_complexity)] +fn plain_paint(p: &Node) -> Option<(Option, Option<(Paint, f64)>)> { + let NodeKind::Path { path, guide: false, clipping: false, .. } = &p.kind else { return None }; + (path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count() == 1).then_some(())?; + let (mut fill, mut line) = (None, None); + for item in &p.appearance.items { + let drawn = match item { + AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(), + AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0 && s.width.is_finite(), + }; + if !drawn { + // The writers leave out what draws nothing; the reader reads nothing in its place. + continue; + } + let plain = + item.opacity() == 1.0 && item.blend() == BlendMode::Normal && item.effects().is_empty() && matches!(item.paint(), Paint::Solid { .. }); + plain.then_some(())?; + match item { + AppearanceItem::Fill(f) if fill.is_none() && line.is_none() => fill = Some(f.paint.clone()), + AppearanceItem::Stroke(s) if line.is_none() && stroke::is_plain(s) => line = Some((s.paint.clone(), s.width)), + _ => return None, + } + } + Some((fill, line)) +} + +/// The `Go` line of each series' group among `children`: a group whose series index is one of the +/// `series` the table has, each once, of paths [`as_drawn`] with one fill and one line alike +/// ([`plain_paint`]), every path filled unless the graph draws lines (`line`). Its column is the +/// table's: after the label column when there is one (`first_col`). `None` when a series has no +/// such group. +fn series_groups(children: &[std::sync::Arc], series: usize, first_col: usize, line: bool) -> Option> { + let mut tags = HashMap::new(); + let mut seen = vec![false; series]; + for c in children { + let Some(s) = c.extras().series_index else { continue }; + let s = usize::try_from(s).ok().filter(|s| *s < series)?; + let slot = seen.get_mut(s)?; + (!*slot).then_some(())?; + *slot = true; + let NodeKind::Group { children: paths, clip: false } = &c.kind else { return None }; + (as_drawn(c) && *c.appearance == Appearance::default() && !paths.is_empty()).then_some(())?; + let mut paints = vec![]; + for p in paths { + as_drawn(p).then_some(())?; + paints.push(plain_paint(p)?); + } + let fill = paints.iter().find_map(|(f, _)| f.clone()); + paints.iter().all(|(f, _)| f.is_none() || *f == fill).then_some(())?; + (line || paints.iter().all(|(f, _)| f.is_some())).then_some(())?; + let stroke = paints.first().and_then(|(_, s)| s.clone()); + paints.iter().all(|(_, s)| *s == stroke).then_some(())?; + tags.insert(c.id, format!("%_2 {} 0 0 Go", s + first_col)); + } + seen.iter().all(|s| *s).then_some(tags) +} + +/// Whether `art` draws plot `plot`'s left edge and its bottom edge (the document's y runs down) as +/// straight lines, each a shown path of one subpath with a plain line ([`plain_paint`]) in a shown +/// group, as the reader finds the axes. +fn draws_axes(art: &Node, plot: Rect) -> bool { + let near = |a: Point, b: Point| (a - b).hypot() <= EDGE; + let on = |s: &PathSeg, a: Point, b: Point| match s { + PathSeg::Line(l) => (near(l.p0, a) && near(l.p1, b)) || (near(l.p0, b) && near(l.p1, a)), + _ => false, + }; + let (top_left, bottom_left, bottom_right) = (Point::new(plot.x0, plot.y0), Point::new(plot.x0, plot.y1), Point::new(plot.x1, plot.y1)); + let (mut left, mut bottom) = (false, false); + let mut stack = vec![art]; + while let Some(n) = stack.pop() { + if !n.visible || n.opacity <= 0.0 || (left && bottom) { + continue; + } + match &n.kind { + NodeKind::Group { children, clip: false } => stack.extend(children.iter().map(|c| &**c)), + NodeKind::Path { path, .. } if plain_paint(n).is_some_and(|(_, line)| line.is_some()) => { + for s in path.to_bezpath().segments() { + left |= on(&s, top_left, bottom_left); + bottom |= on(&s, bottom_left, bottom_right); + } + } + _ => {} + } + } + left && bottom +} + +/// Graphs built as the graph tools draw them, for the writers' tests. +#[cfg(test)] +pub(crate) mod sample { + use std::sync::Arc; + + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Document, GraphKind, GraphSpec, Node, PieSort, TickLength, ValueAxisSide}; + use vectorcraft_geom::{PathData, Point, Rect, shapes}; + + use super::Appearance; + + /// A graph of kind `kind`: series East and West, categories Q1 to Q3, West blank in Q2, on the + /// plot 100 100 300 250. + pub(crate) fn spec(kind: GraphKind) -> GraphSpec { + let mut g = GraphSpec { + kind, + rect: Rect::new(100.0, 100.0, 300.0, 250.0), + series: vec!["East".into(), "West".into()], + categories: vec!["Q1".into(), "Q2".into(), "Q3".into()], + ..GraphSpec::default() + }; + g.set_cells(vec![vec![Some(5.0), Some(3.0)], vec![Some(7.0), None], vec![Some(4.0), Some(6.0)]]); + g + } + + fn path(doc: &mut Document, p: PathData, fill: Paint, stroke: Paint) -> Arc { + Arc::new(Node::path(doc.alloc_id(), p, Appearance::basic(fill, stroke, 1.0))) + } + + /// Graph `g` drawn as a group: a group of each series' marks (a line graph's series as an unfilled + /// line, the others' as filled columns), its axes on the plot's left and bottom edges, and a + /// legend of a swatch for each series; its series groups named after the series. + pub(crate) fn graph(doc: &mut Document, g: GraphSpec) -> Node { + let r = g.rect; + let cells = g.cells(); + let width = cells.first().map_or(0, Vec::len); + let mut members = vec![]; + let axes = vec![ + path(doc, shapes::line(Point::new(r.x0, r.y0), Point::new(r.x0, r.y1)), Paint::None, Paint::solid(Color::BLACK)), + path(doc, shapes::line(Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)), Paint::None, Paint::solid(Color::BLACK)), + ]; + members.push(Arc::new(Node::group(doc.alloc_id(), axes))); + for s in 0..width { + let gray = Paint::solid(Color::gray(0.2 + 0.3 * s as f32)); + let points: Vec = cells + .iter() + .enumerate() + .filter_map(|(c, row)| { + row.get(s).copied().flatten().map(|v| Point::new(r.x0 + 20.0 + 60.0 * c as f64 + 15.0 * s as f64, r.y1 - v * 10.0)) + }) + .collect(); + let marks: Vec> = if g.kind == GraphKind::Line { + let mut bp = kurbo::BezPath::new(); + for (i, p) in points.iter().enumerate() { + if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) } + } + vec![path(doc, PathData::from_bezpath(&bp), Paint::None, gray)] + } else { + points.iter().map(|p| path(doc, shapes::rectangle(Rect::new(p.x, p.y, p.x + 10.0, r.y1)), gray.clone(), Paint::None)).collect() + }; + let mut series = Node::group(doc.alloc_id(), marks); + series.name = Some(g.series.get(s).cloned().unwrap_or_else(|| format!("Series {}", s + 1))); + series.extras_mut().series_index = Some(s as u32); + members.push(Arc::new(series)); + } + let swatches: Vec> = (0..width) + .map(|s| { + let y = r.y0 + 12.0 * s as f64; + path( + doc, + shapes::rectangle(Rect::new(r.x1 + 10.0, y, r.x1 + 18.0, y + 8.0)), + Paint::solid(Color::gray(0.2 + 0.3 * s as f32)), + Paint::None, + ) + }) + .collect(); + members.push(Arc::new(Node::group(doc.alloc_id(), swatches))); + let mut n = Node::group(doc.alloc_id(), members); + n.extras_mut().graph = Some(Box::new(g)); + n + } + + /// A 400 × 300 document holding `g` drawn by [`graph`] on its layer. + pub(crate) fn document(g: GraphSpec) -> Document { + let mut doc = Document::new(400.0, 300.0); + let layer = doc.layers[0].id; + let n = graph(&mut doc, g); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + doc + } + + /// Graphs whose records read back whole: each type the records give, every setting they keep + /// changed, labels with parentheses, backslashes and non-ASCII characters, a label of 255 bytes, + /// and a table without labels. + pub(crate) fn kept() -> Vec<(&'static str, Document)> { + let mut cases = vec![ + ("column", document(spec(GraphKind::Column))), + ("stacked column", document(spec(GraphKind::StackedColumn))), + ("line", document(spec(GraphKind::Line))), + ("area", document(spec(GraphKind::Area))), + ]; + let mut g = spec(GraphKind::Column); + (g.drop_shadow, g.first_row_in_front, g.first_column_in_front, g.legend_across_top) = (true, true, true, true); + (g.mark_points, g.connect_points, g.edge_to_edge) = (false, false, true); + (g.column_width, g.cluster_width) = (120.0, 50.0); + (g.tick_length, g.tick_marks, g.ticks, g.axis_min, g.axis_max) = (TickLength::Full, 3, 4, Some(0.0), Some(20.0)); + (g.right_tick_length, g.right_tick_marks, g.right_ticks, g.right_axis_min, g.right_axis_max) = (TickLength::None, 2, 5, Some(1.0), Some(6.0)); + (g.category_tick_length, g.category_tick_marks, g.ticks_between_labels) = (TickLength::Short, 2, true); + (g.prefix, g.suffix, g.right_prefix, g.right_suffix) = ("($".into(), "\\)".into(), "é".into(), " u".into()); + cases.push(("settings", document(g))); + let mut g = spec(GraphKind::Column); + g.series = vec!["A (1)".into(), "B\\2".into()]; + g.categories = vec![String::new(), "naïve".into(), "a".repeat(255)]; + g.set_cells(vec![vec![Some(1.0 / 3.0), Some(1e-7)], vec![None, Some(2.5)], vec![Some(12.0), None]]); + cases.push(("labels", document(g))); + let mut g = spec(GraphKind::Column); + (g.series, g.categories) = (vec![], vec![]); + cases.push(("no labels", document(g))); + cases + } + + /// Graphs the records can't give as they are, which are written as their art: the five other + /// types, settings the reader doesn't keep, a table it can't hold, and art it can't attach the + /// graph to. + pub(crate) fn unkept() -> Vec<(&'static str, Document)> { + let with = |f: &dyn Fn(&mut GraphSpec)| { + let mut g = spec(GraphKind::Column); + f(&mut g); + document(g) + }; + let mut cases: Vec<(&'static str, Document)> = [GraphKind::Bar, GraphKind::StackedBar, GraphKind::Scatter, GraphKind::Pie, GraphKind::Radar] + .into_iter() + .map(|k| (k.id(), document(spec(k)))) + .collect(); + cases.extend([ + ("no legend", with(&|g| g.legend = false)), + ("filled lines", with(&|g| (g.kind, g.filled_lines) = (GraphKind::Line, true))), + ("a series of another type", with(&|g| g.series_kinds = vec![None, Some(GraphKind::Line)])), + ("a marker design", with(&|g| g.series_markers = vec![Some("Star".into())])), + ("a column design", with(&|g| g.series_columns = vec![Some(Default::default())])), + ("label formatting", with(&|g| g.label_styles.values = Some(Default::default()))), + ("a value axis on both sides", with(&|g| g.value_axis = ValueAxisSide::Both)), + ("a series on the right axis", with(&|g| g.right_series = vec![1])), + ("pie settings", with(&|g| g.pie_sort = PieSort::All)), + ("a manual axis without its values", with(&|g| g.ticks = 4)), + ("values without a tick count", with(&|g| (g.axis_min, g.axis_max) = (Some(0.0), Some(10.0)))), + ("101 divisions", with(&|g| (g.ticks, g.axis_min, g.axis_max) = (101, Some(0.0), Some(101.0)))), + ("too many tick marks", with(&|g| g.tick_marks = 21)), + ("a column width past 1000%", with(&|g| g.column_width = 1001.0)), + ("a long prefix", with(&|g| g.prefix = "0123456789".into())), + ("a line break in a label", with(&|g| g.series[0] = "East\nside".into())), + ("a label of 256 bytes", with(&|g| g.categories[0] = "a".repeat(256))), + ("a value that isn't finite", with(&|g| g.rows[0][0] = f64::NAN)), + ("only blank cells", with(&|g| g.set_cells(vec![vec![None, None]; 3]))), + ("fewer labels than series", with(&|g| g.series.truncate(1))), + ]); + let drawn = |what: &'static str, f: &dyn Fn(&mut Vec>)| { + let mut doc = Document::new(400.0, 300.0); + let mut n = graph(&mut doc, spec(GraphKind::Column)); + if let Some(c) = n.children_mut() { + f(c); + } + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + (what, doc) + }; + cases.extend([ + drawn("a series without its group", &|c| { + c.remove(2); + }), + drawn("no axes", &|c| { + c.remove(0); + }), + drawn("a hidden legend", &|c| { + if let Some(l) = c.last_mut() { + Arc::make_mut(l).visible = false; + } + }), + drawn("a series drawn half opaque", &|c| Arc::make_mut(&mut c[1]).opacity = 0.5), + drawn("a series mark with a gradient", &|c| { + let g = vectorcraft_color::Gradient::new( + vectorcraft_color::GradientKind::Linear, + vec![vectorcraft_color::GradientStop::new(0.0, Color::BLACK), vectorcraft_color::GradientStop::new(1.0, Color::WHITE)], + ); + let series = Arc::make_mut(&mut c[1]); + if let Some(marks) = series.children_mut() { + let mark = Arc::make_mut(&mut marks[0]); + mark.appearance = Appearance::basic(Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g))), Paint::None, 0.0).into(); + } + }), + ]); + cases + } + + /// The graphs in `doc`, each with the series index of its members. + pub(crate) fn graphs(doc: &Document) -> Vec<(GraphSpec, Vec>)> { + let mut out = vec![]; + doc.walk(|n| { + if let Some(g) = n.extras().graph.as_deref() { + out.push((g.clone(), n.children().map(|c| c.iter().map(|c| c.extras().series_index).collect()).unwrap_or_default())); + } + }); + out + } + + /// Whether `read` is the graph `written` was: the same data and settings, the plot in the same + /// place; its series' paint is the art's and its bounds are the art's as read. + pub(crate) fn same(written: &GraphSpec, read: &GraphSpec) -> bool { + let near = |a: Rect, b: Rect| (a.x0 - b.x0).abs() + (a.y0 - b.y0).abs() + (a.x1 - b.x1).abs() + (a.y1 - b.y1).abs() < 1e-6; + let plain = |g: &GraphSpec| GraphSpec { + rect: Rect::ZERO, + rows: vec![], + blanks: vec![], + series_paints: vec![], + placed: None, + placed_art: None, + series_kinds: vec![], + ..g.clone() + }; + near(written.rect, read.rect) && written.cells() == read.cells() && plain(written) == plain(read) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Numbers are written so they read back the same, small and large ones included. + #[test] + fn numbers_read_back_as_written() { + for v in [0.0, 1.0, -2.5, 1.0 / 3.0, 1e-7, 123_456_789_012_345_678.0, f64::MAX, f64::MIN_POSITIVE] { + assert_eq!(real(v).parse::().ok(), Some(v), "{v}"); + } + } + + /// A graph of `categories` rows of `series` values, drawn by [`sample::graph`]. + fn sized(categories: usize, series: usize) -> Node { + let mut g = sample::spec(GraphKind::Column); + (g.series, g.categories) = (vec![], vec![]); + g.set_cells(vec![vec![Some(1.0); series]; categories]); + sample::graph(&mut vectorcraft_doc::Document::new(400.0, 300.0), g) + } + + /// The table the reader holds: up to 10,000 categories and 256 series; past them, the graph is + /// its art. + #[test] + fn tables_up_to_the_readers_limits_are_written() { + assert!(records(&sized(MAX_GRAPH_CATEGORIES, 1), Affine::IDENTITY).is_some_and(|r| r.head.contains("%_10000 1 0 0 Gz\n"))); + assert!(records(&sized(MAX_GRAPH_CATEGORIES + 1, 1), Affine::IDENTITY).is_none()); + assert!(records(&sized(1, MAX_GRAPH_SERIES), Affine::IDENTITY).is_some_and(|r| r.tags.len() == MAX_GRAPH_SERIES)); + assert!(records(&sized(1, MAX_GRAPH_SERIES + 1), Affine::IDENTITY).is_none()); + } + + /// Tick-mark counts of 0, which mean one tick mark as 1 does, are written as 1, the count the + /// reader reads back. + #[test] + fn tick_mark_counts_of_0_are_written_as_1() { + let mut g = sample::spec(GraphKind::Column); + (g.tick_marks, g.right_tick_marks, g.category_tick_marks) = (0, 0, 0); + let n = sample::graph(&mut vectorcraft_doc::Document::new(400.0, 300.0), g); + let head = records(&n, Affine::IDENTITY).map(|r| r.head).unwrap_or_default(); + let marks: Vec<&str> = head.lines().filter(|l| l.ends_with(" GA")).map(|l| l.split(' ').nth(5).unwrap_or("")).collect(); + assert_eq!(marks, ["1", "1", "1"], "{head}"); + } + + /// A table's cells go fifteen to a record, with one string at most in each. + #[test] + fn cells_go_fifteen_to_a_record_with_one_string_each() { + let mut out = String::new(); + let mut t = Table::new(&mut out); + t.text("a"); + t.text("b"); + for v in 0..16 { + t.num(f64::from(v)); + } + t.finish(); + let records: Vec<&str> = out.lines().collect(); + assert_eq!(records[0], "%_(a) Gc"); + assert_eq!(records[1], "%_(b) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 Gc"); + assert_eq!(records[2], "%_14 15 Gc"); + } +} diff --git a/crates/eps/src/import/ai/read/graph.rs b/crates/eps/src/import/ai/read/graph.rs index 9fb60408c7..609713fe16 100644 --- a/crates/eps/src/import/ai/read/graph.rs +++ b/crates/eps/src/import/ai/read/graph.rs @@ -631,7 +631,7 @@ impl<'a> Reader<'a> { let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false }; spec.series_paints = paints; spec.placed = Some(placed); - spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::art_bounds(c)); + spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::graph_art_without_type(c)); tag_series(art, &tags); art.extras_mut().graph = Some(Box::new(spec)); true diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index d160248a2d..22a9833e07 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -10329,23 +10329,48 @@ fn a_brushed_path_with_samples_of_the_pen_keeps_its_drawn_look() { assert_eq!(a.len(), 1, "{a:#?}"); assert!(matches!(a[0].kind, NodeKind::Group { .. }), "the drawn look: {a:#?}"); assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); - // The samples belong to the path before them: a path after them is read as it was. - let after = format!("{path}{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0)); + // The samples belong to the path before them: a path after them with the same brush and no + // samples of its own comes in brushed. + let after = format!("{path}{}", brushed_path()); let a = art(&read_ok(&format!("{def}{style}{}", layer(&after))).doc); assert_eq!(a.len(), 2, "{a:#?}"); - assert!(matches!(a[1].kind, NodeKind::Path { .. }) && a[1].appearance.fill().is_some(), "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "the sampled path's drawn look: {a:#?}"); + assert!(matches!(a[1].kind, NodeKind::Path { .. }), "the path after the samples, brushed: {a:#?}"); + assert_eq!(a[1].appearance.stroke().and_then(|s| s.brush.as_deref()), Some("Six D"), "{a:#?}"); // Samples with no object before them in the layer mark nothing: the path after them is read. let first = format!("{PEN_SAMPLES}{}", brushed_path()); 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/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 28994527a7..a45c203d75 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -25,6 +25,7 @@ use std::collections::{BTreeMap, HashMap}; use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen}; use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::text::MAX_AKI; use vectorcraft_doc::{ Burasagari, CharStyle, HyphenationOptions, JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LineCap, LineJoin, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TabAlign, TabStop, TextKind, TextObject, TextRun, @@ -525,6 +526,17 @@ struct Style { /// Key 35 at 1 (Standard): Standard Vertical Roman Alignment, half-width characters upright in /// a column. Any other value, or no key in the run, its character style or the defaults, is off. standard_vertical_roman: bool, + /// Keys 49 and 50, Insert Aki Left and Right ([`CharStyle::aki_left`]), in 1/1000 em. + aki_left: f64, + aki_right: f64, +} + +/// Insert Aki Left or Right as key `v` of a character style gives it, in 1/1000 em (the unit the +/// scripting reference gives `aki left` and `aki right`), 0 to [`MAX_AKI`]. A negative value, one +/// that is not a finite number, or no key is 0: no space added. A key the run itself carries wins +/// over its styles' even when it is not a number, so a bad value never shows a style's. +fn aki(v: Option<&Val>) -> f64 { + v.and_then(Val::num).filter(|v| v.is_finite() && *v > 0.0).map_or(0.0, |v| v.min(MAX_AKI)) } /// The longest font version string read from a font record: name ID 5 strings are short (`Version @@ -922,6 +934,8 @@ impl Texts { caps: num("12").filter(|v| *v == 1.0 || *v == 2.0).map_or(0, |v| v as u8), tate_chu_yoko: num("35") == Some(3.0), standard_vertical_roman: num("35") == Some(1.0), + aki_left: aki(pick("49")), + aki_right: aki(pick("50")), } } } @@ -1549,6 +1563,9 @@ fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle { small_caps: (s.caps == 1).then(|| vectorcraft_doc::DocSetup::default().small_caps_size), tate_chu_yoko: s.tate_chu_yoko, standard_vertical_roman: s.standard_vertical_roman, + // In ems of the type's own size, so the art's scale does not apply. + aki_left: s.aki_left, + aki_right: s.aki_right, ..CharStyle::default() } } @@ -1922,6 +1939,48 @@ mod tests { assert!(texts(b"/35 3").style(None).tate_chu_yoko && !texts(b"/35 3").style(None).standard_vertical_roman); } + /// Keys 49 and 50 of a character style are Insert Aki Left and Right in 1/1000 em, each from the + /// run, its character style and the styles that is based on, `[Normal Character Style]`, then the + /// document's defaults. A run's own 0 wins over a style's value, a value past 1000 is 1000, and a + /// negative value, one that is not a number or no key at all is 0. + #[test] + fn a_run_keeps_its_insert_aki() { + let texts = |defaults: &[u8], normal: &[u8]| Texts { + stories: vec![], + fonts: vec![], + defaults: read(defaults).unwrap(), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![ + read(&[&b"/0 ([Normal Character Style]) /6 << "[..], normal, b" >>"].concat()).unwrap(), + read(b"/0 (Base) /6 << /49 125.0 >>").unwrap(), + read(b"/0 (Spaced) /5 1 /6 << /50 500.0 >>").unwrap(), + ], + para_sheets: vec![], + frames: vec![], + patterns: HashMap::new(), + kinsoku_sets: vec![], + }; + let aki = |defaults: &[u8], normal: &[u8], run: &[u8]| { + let s = texts(defaults, normal).style(Some(&read(run).unwrap())); + (s.aki_left, s.aki_right) + }; + assert_eq!(aki(b"/0 0", b"", b"/6 << /49 250.0 /50 750.0 >>"), (250.0, 750.0), "the run's own"); + assert_eq!(aki(b"/0 0", b"", b"/5 2 /6 << >>"), (125.0, 500.0), "its style's, and the style that is based on"); + assert_eq!(aki(b"/0 0", b"", b"/5 2 /6 << /49 0.0 /50 0 >>"), (0.0, 0.0), "the run's own zero wins"); + assert_eq!(aki(b"/49 10.0 /50 20.0", b"/49 30.0", b"/6 << >>"), (30.0, 20.0), "Normal, then the document's"); + assert_eq!(aki(b"/49 10.0 /50 20.0", b"", b"/6 << >>"), (10.0, 20.0), "the document's"); + assert_eq!(aki(b"/0 0", b"", b"/6 << >>"), (0.0, 0.0), "no key"); + assert_eq!(aki(b"/0 0", b"", b"/6 << /49 1000.5 /50 1e300 >>"), (MAX_AKI, MAX_AKI), "clamped"); + for bad in [&b"-1.0"[..], b"-250", b"(125)", b"true", b"[ 125 ]", b"1e400", b"-1e400"] { + let run = [&b"/5 2 /6 << /49 "[..], bad, b" /50 ", bad, b" >>"].concat(); + assert_eq!(aki(b"/0 0", b"", &run), (0.0, 0.0), "{}", String::from_utf8_lossy(bad)); + } + // In ems of the type's size: the art's scale leaves it as it is. + let s = texts(b"/0 0", b"").style(Some(&read(b"/6 << /49 250.0 /50 125.0 >>").unwrap())); + let c = char_style(&s, 10.0, Affine::IDENTITY); + assert_eq!((c.aki_left, c.aki_right), (250.0, 125.0)); + } + /// Keys 61, 62 and 64 of a character style are its stroke's cap (0 butt, 1 round, 2 /// projecting), join (0 miter, 1 round, 2 bevel) and miter limit, from the run, its character /// style or the document's defaults. A value that isn't one of theirs keeps the default, a miter @@ -2397,6 +2456,8 @@ mod tests { caps: 0, tate_chu_yoko: false, standard_vertical_roman: false, + aki_left: 0.0, + aki_right: 0.0, }, )], kerns: vec![], diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 7e38b5ba51..779385b82b 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -43,13 +43,17 @@ //! PostScript names in `%%DocumentFonts` and `%%IncludeFont` (§3.1) and re-encoded to //! Windows-1252 (`TE`, then `%AI3_BeginEncoding: _name name`, `TZ`, §3.3), the 8-bit encoding //! strings are in. +//! - Graphs (§17): a graph whose records VectorCraft's reader reads back as the same graph +//! (`crate::ai_graph`) as `%_Gs`, its functional records, its group with each series' group +//! followed by `%_2 column 0 0 Go`, and `%_GS`. //! //! The format has one artboard, no transparency, sublayers, object names, hidden objects (only //! layers hide), live effects, symbols or appearances with several fills and strokes. Callers write //! one file per artboard and expand appearances first; what is left is written as the format can //! hold it, each loss a warning: transparent objects are written opaque, sublayers become groups, -//! live objects and symbols their art, strokes a plain line can't draw their outlines, pattern -//! fills their tiles clipped to the shape, freeform gradients their average colour, elliptical +//! live objects and symbols their art, other graphs their art, strokes a plain line can't draw +//! their outlines, pattern fills their tiles clipped to the shape, freeform gradients their average +//! colour, elliptical //! radial gradients circular (the gradient matrix is relative to a canvas the specification //! doesn't size), transparent image pixels over white. Hidden objects go to a hidden layer of //! their own above their layer, are left out or show, as [`HiddenObjects`] says (in a hidden @@ -101,7 +105,7 @@ const HEX_LINE: usize = 60; pub const SUBLAYERS: &str = "sublayers are written as groups in their top-level layer (legacy .ai files have no sublayers)"; pub const TYPE: &str = "type a legacy .ai can't hold as text (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is written as outlines"; pub const ROTATED_TYPE: &str = "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate characters)"; -pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out"; +pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, Insert Aki, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out"; pub const DYNAMIC_TEXT: &str = "Dynamic Text is written as the sizes the type is drawn at (legacy .ai files don't have it)"; pub const HIDDEN: &str = "hidden objects are left out (hidden layers are kept, hidden)"; pub const HIDDEN_LAYER: &str = "hidden objects are moved to a hidden layer above their own (legacy .ai files can hide only layers)"; diff --git a/crates/eps/src/legacy_ai/encoding.rs b/crates/eps/src/legacy_ai/encoding.rs index 7ebae72123..d971e5249e 100644 --- a/crates/eps/src/legacy_ai/encoding.rs +++ b/crates/eps/src/legacy_ai/encoding.rs @@ -123,6 +123,9 @@ pub(super) fn lost_attributes(t: &TextObject) -> bool { || s.optical_kerning || s.small_caps.is_some() || s.position != CharPosition::Normal + // Its text operators (§15.4) have no Insert Aki. + || s.aki_left != 0.0 + || s.aki_right != 0.0 || !s.features.is_empty() || !s.font_axes.is_empty() }; diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 663e21bec6..056db02074 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -1435,6 +1435,41 @@ fn variable_font_settings_are_warned_as_left_out() { assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text"); } +/// A legacy `.ai` text object has no Insert Aki (§15.4): type with Insert Aki Left or Right is +/// written as text with the warning that it is left out. Written as outlines, the glyphs keep the +/// space it adds, and nothing is reported. +#[test] +fn insert_aki_is_warned_as_left_out_of_text() { + for (left, right) in [(250.0, 0.0), (0.0, 125.0)] { + let mut doc = typed(); + let id = texts(&doc)[0].0.id; + if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.aki_left = left; + t.runs[0].style.aki_right = right; + } + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{left} {right}: {:?}", out.warnings); + assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text"); + } + let width = |aki: f64| { + let mut st = style(20.0, red()); + st.aki_left = aki; + st.aki_right = aki; + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "HH", st); + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = write_with(&doc, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() }); + assert!(!out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{:?}", out.warnings); + let back = crate::import(&out.bytes).unwrap().document; + children(&children(&back.layers[0])[0])[0].visual_bounds().unwrap().width() + }; + // Between the two H's: 0.5 em after the first and 0.5 em before the second, 20 pt. + let (plain, spaced) = (width(0.0), width(500.0)); + assert!((spaced - plain - 20.0).abs() < 0.05, "{plain} {spaced}"); +} + /// Standard Vertical Roman Alignment is written as `Tv` and Tate-chu-yoko in horizontal type as a /// Kumi block recorded for later use, `TY` (§15.3.4), each where it changes: the marks read back /// on the same characters, a block is closed before its text object ends, and type with neither @@ -2122,3 +2157,64 @@ fn a_stained_instance_is_written_in_its_stained_color() { let text = String::from_utf8(write(&doc).bytes).unwrap(); assert!(text.contains("0 0 1 Xa") && !text.contains("1 0 0 Xa"), "{text}"); } + +/// A graph whose records read back whole is written with them (§17), and opens again as the same +/// live graph: its table, type and settings, its series' groups tagged in order, without a warning +/// about graphs. +#[test] +fn graphs_are_written_with_their_records_and_open_live() { + use crate::ai_graph::sample; + for (what, doc) in sample::kept() { + let out = write(&doc); + assert!(!out.warnings.iter().any(|w| w == GRAPHS), "{what}: {:?}", out.warnings); + let text = String::from_utf8(out.bytes.clone()).unwrap(); + assert_eq!((text.matches("%_Gs\n").count(), text.matches("%_GS\n").count()), (1, 1), "{what}: {text}"); + let read = crate::import(&out.bytes).unwrap(); + let written = sample::graphs(&doc); + let graphs = sample::graphs(&read.document); + assert_eq!(graphs.len(), 1, "{what}: {:?}", read.warnings); + assert!(sample::same(&written[0].0, &graphs[0].0), "{what}: {:#?}\n{:#?}", written[0].0, graphs[0].0); + assert_eq!(graphs[0].1, written[0].1, "{what}: the members and their series"); + } +} + +/// A graph inside a group is written with its records too, and opens on its own group. +#[test] +fn a_graph_in_a_group_is_written_with_its_records() { + use crate::ai_graph::sample; + let mut doc = Document::new(400.0, 300.0); + let graph = sample::graph(&mut doc, sample::spec(vectorcraft_doc::GraphKind::Column)); + let frame = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), red(), Paint::None); + let outer = Node::group(doc.alloc_id(), vec![Arc::new(frame), Arc::new(graph)]); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, outer).unwrap(); + let out = write(&doc); + assert!(!out.warnings.iter().any(|w| w == GRAPHS), "{:?}", out.warnings); + let read = crate::import(&out.bytes).unwrap(); + let graphs = sample::graphs(&read.document); + assert_eq!(graphs.len(), 1, "{:?}", read.warnings); + assert!(sample::same(&sample::graphs(&doc)[0].0, &graphs[0].0)); + let layer = children(&read.document.layers[0]); + assert!(layer[0].extras().graph.is_none() && layer[0].children().is_some_and(|c| c.len() == 2), "{layer:#?}"); +} + +/// A graph whose records wouldn't read back as it is is written as its art, without records, with +/// the warning, and opens as that art. +#[test] +fn graphs_the_records_cant_keep_are_written_as_their_art() { + use crate::ai_graph::sample; + for (what, doc) in sample::unkept() { + let out = export_legacy_ai(&doc, &LegacyAiOptions::default()).unwrap(); + assert!(out.warnings.iter().any(|w| w == GRAPHS), "{what}: {:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes).into_owned(); + assert!(!text.contains("%_Gs") && !text.contains(" Go\n") && !text.contains("%_GS"), "{what}: {text}"); + let read = crate::import(&out.bytes).unwrap(); + assert!(sample::graphs(&read.document).is_empty(), "{what}"); + let paths = |d: &Document| { + let mut count = 0; + d.walk(|n| count += usize::from(matches!(n.kind, NodeKind::Path { .. }))); + count + }; + assert_eq!(paths(&read.document), paths(&doc), "{what}: the graph's art is kept"); + } +} diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 0b41c3defa..d8f88e0d0b 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -52,6 +52,8 @@ pub(super) struct Writer<'a> { last_image: Option<(ImageBlob, Option>)>, /// The images written whole so far, by the address of their data (which each entry keeps). whole_images: std::collections::HashMap>>, + /// Writing a graph's art with its records: a graph inside it is written as its art. + in_graph: bool, } impl<'a> Writer<'a> { @@ -78,6 +80,7 @@ impl<'a> Writer<'a> { clips: vec![], last_image: None, whole_images: std::collections::HashMap::new(), + in_graph: false, } } @@ -264,7 +267,12 @@ impl<'a> Writer<'a> { if n.name.as_deref().is_some_and(|s| !s.is_empty()) && !n.is_layer() { self.warn(NAMES); } - if n.extras().graph.is_some() { + // A graph on the layers keeps its data and settings when its records read back whole. + let graph = match n.extras().graph.is_some() { + true if self.nest == 0 && !self.in_graph => crate::ai_graph::records(n, self.to_art), + _ => None, + }; + if n.extras().graph.is_some() && graph.is_none() { self.warn(GRAPHS); } let locked = locked || n.locked; @@ -273,7 +281,10 @@ impl<'a> Writer<'a> { self.warn(SUBLAYERS); self.group(children, *clip, locked); } - NodeKind::Group { children, clip } => self.group(children, *clip, locked), + NodeKind::Group { children, clip } => match &graph { + Some(records) => self.graph(children, locked, records), + None => self.group(children, *clip, locked), + }, NodeKind::Path { path, rule, guide, .. } => { self.lock(locked); if *guide { @@ -352,6 +363,25 @@ impl<'a> Writer<'a> { } } + /// A graph's group (`u` … `U`) between its records (§17): `%_Gs` and its functional records + /// before it, `%_GS` after it, and each series' group followed by its `Go` tag. + fn graph(&mut self, children: &[Arc], locked: bool, records: &crate::ai_graph::Records) { + self.lock(locked); + self.body.push_str(&records.head); + self.line("u"); + self.in_graph = true; + for c in children { + self.node(c, locked); + if let Some(tag) = records.tags.get(&c.id) { + self.line(tag); + } + } + self.in_graph = false; + self.lock(locked); + self.line("U"); + self.line(crate::ai_graph::END); + } + /// A clipping group: its first member's outline clips the others (`h W n`). That member's fills /// paint behind the art, inside the clip, and its strokes over it, outside. fn clip_group(&mut self, children: &[Arc], locked: bool) { diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 534778286a..ada3171e0a 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -31,9 +31,11 @@ //! - `ai_editing`: the editing copy of the art a PDF-compatible `.ai` file carries //! ([`export_ai_editing`], [`ai_private_data`]). //! - `ai_ops`: the path and line style operators those two write. +//! - `ai_graph`: the records of a live graph those two write around its group. //! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing. mod ai_editing; +mod ai_graph; mod ai_ops; pub mod dcs; mod import; diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 299d130f7d..8d147cb2d1 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -489,8 +489,11 @@ impl<'a> Scene<'a> { self.warn(TOO_LARGE); return; } + // Off the region, an object is still written when brush art painted along its brushed + // strokes, or those of the objects in it, can reach the region. + let off = |b: Rect, reach: f64| !overlaps(b.inflate(1.0 + reach, 1.0 + reach), self.o.region); match n.visual_bounds_with(&self.symbols) { - Some(b) if !force && !overlaps(b.inflate(1.0, 1.0), self.o.region) => return, + Some(b) if !force && off(b, 0.0) && off(b, vectorcraft_brush::reach_within(n)) => return, None if !n.is_container() => return, _ => {} } diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 92971cee01..963e78c9ef 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -1654,6 +1654,59 @@ fn an_instance_whose_brush_art_reaches_the_region_is_written() { assert!(page.contains("1 0 0 rg"), "{page}"); } +#[test] +fn a_path_whose_brush_art_reaches_the_region_is_written() { + // A line from (-5, 40) to (-5, 60) with a 1 pt red stroke painted by a 20 pt round nib lies + // left of the artboard, and the nib paints 10 pt either side of it, onto the artboard: alone, in + // a group and as a compound path. Without its brush, or 100 pt left of the artboard, where the + // nib does not reach it, the line is left out. + let red = |x: f64, brushed: bool| { + let mut n = Node::path( + vectorcraft_doc::NodeId(0), + shapes::line((x, 40.0).into(), (x, 60.0).into()), + Appearance::basic(Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0), + ); + if brushed { + n.appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + } + n + }; + let cases: [(&str, f64, bool, bool); 5] = [ + ("path", -5.0, true, true), + ("group", -5.0, true, true), + ("compound path", -5.0, true, true), + ("unbrushed path", -5.0, false, false), + ("far path", -100.0, true, false), + ]; + for (what, x, brushed, written) in cases { + let mut d = Document::new(200.0, 200.0); + let mut lib = vectorcraft_brush::library(&d); + let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else { + panic!("the 3 pt. Round brush") + }; + c.size = 20.0; + vectorcraft_brush::store(&mut d, &lib); + let line = red(x, brushed); + let mut n = match what { + "group" => Node::group(vectorcraft_doc::NodeId(0), vec![Arc::new(line)]), + "compound path" => { + let mut c = Node::new( + vectorcraft_doc::NodeId(0), + NodeKind::Compound { children: vec![Arc::new(red(x, false))], rule: vectorcraft_geom::FillRule::NonZero }, + ); + c.appearance = line.appearance; + c + } + _ => line, + }; + n.id = d.alloc_id(); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, n).unwrap(); + let page = page_of(&d, &opts(&d)); + assert_eq!(page.contains("1 0 0 rg") || page.contains("1 0 0 RG"), written, "{what}: {page}"); + } +} + #[test] fn symbol_art_effects_are_written_where_they_draw() { // The symbol's square at (10, 40), which a Transform effect moves 100 pt right, is drawn from diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 969a9c6094..af41bb7782 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -166,10 +166,11 @@ fn create(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let o = require_object(interp, &arg(args, 0), "defineProperty")?; - let k = interp.to_key(&arg(args, 1))?; - let desc = to_desc(interp, &arg(args, 2))?; - let roots = desc_values(&desc); - interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true))?; + interp.with_key(&arg(args, 1), |interp, k| { + let desc = to_desc(interp, &arg(args, 2))?; + let roots = desc_values(&desc); + interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true)) + })?; Ok(Value::Object(o)) } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index edc5282fe5..aa4a4c5c78 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1779,8 +1779,7 @@ impl Interp { return self.replace(2, v); } self.check_coercible(&base, &[])?; - let name = self.to_key(&k)?; - let v = self.get_value(&base, &name)?; + let v = self.with_key(&k, |i, name| i.get_value(&base, &name))?; self.replace(2, v)?; if with_this { self.push(base) } else { Ok(()) } } @@ -1852,8 +1851,7 @@ impl Interp { return self.replace(2, Value::Number(if prefix { new } else { old })); } self.check_coercible(&base, &[])?; - let name = self.to_key(&k)?; - let r = self.inc_property(&base, name, prefix, dec)?; + let r = self.with_key(&k, |i, name| i.inc_property(&base, name, prefix, dec))?; self.replace(2, r) } @@ -2670,6 +2668,18 @@ impl Interp { } } + /// Runs `f` with the property name [`Self::to_key`] makes from `v`. A name converted from a + /// value that is not a string is kept reachable while `f` runs, so a collection that a getter + /// or setter starts still counts its units. + pub(crate) fn with_key(&mut self, v: &Value, f: impl FnOnce(&mut Self, Key) -> JsResult) -> JsResult { + let name = self.to_key(v)?; + if matches!(v, Value::String(_)) { + return f(self, name); + } + let root = Value::String(Str::from_rc(name.clone())); + self.rooted(&[root], |i| f(i, name)) + } + /// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that /// copy's bytes are reserved and added to the heap first, without taking fuel. The rope stays /// rooted while the copy is reserved; everything else the caller still needs must be diff --git a/crates/js/src/text_tests.rs b/crates/js/src/text_tests.rs index 01fc613cc3..62145b6117 100644 --- a/crates/js/src/text_tests.rs +++ b/crates/js/src/text_tests.rs @@ -434,6 +434,32 @@ fn a_call_keeps_its_operands_while_a_string_receiver_is_boxed() { assert_eq!(realm.run(src), Ok(JsValue::Number(1.0))); } +#[test] +fn a_computed_key_stays_counted_while_its_getter_or_setter_runs() { + // `o` has an accessor named by a flat string of 131,073 units. `key`'s toString returns a new + // rope with the same units, so using `key` as a name makes a second flat copy, which must stay + // counted while an accessor makes a third. The heap has room for one more copy, not two. + let build = "var s = 'x'; for (var i = 0; i < 17; i++) s = s + s; function f(c) { return s + c; } \ + function copy() { var g = f('g'); g[0]; return 1; } var o = {}, name = f('k'); name[0]; \ + Object.defineProperty(o, name, { get: copy, set: copy }); \ + var key = { toString: function () { return f('k'); } }; 0"; + let realm = || { + let mut realm = Realm::with_options(Options::default(), Limits::default()); + assert_eq!(realm.run(build), Ok(JsValue::Number(0.0))); + let interp = realm.interp(); + interp.collect_garbage(); + let copy = crate::heap::string_bytes(131_073); + interp.limits.heap_bytes = interp.heap.bytes + copy + copy / 2; + interp.reset_gc_threshold(); + realm + }; + assert_eq!(realm().run("o[name]"), Ok(JsValue::Number(1.0)), "the accessor's own copy fits"); + for read in ["o[key]", "o[key] = 1", "o[key]++", "Object.defineProperty({}, key, { get value() { return copy(); } })"] { + let result = realm().run(read); + assert!(matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)), "{read}: {result:?}"); + } +} + #[test] fn compiling_a_pattern_counts_against_the_heap() { let src = "var s = '[\\\\s\\\\S]a*'; for (var i = 0; i < 14; i++) s = s + s; new RegExp(s).source.length"; 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..4b55d6aff1 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(), @@ -465,7 +465,7 @@ pub fn tool_definitions() -> Vec { tool( "transform", "Transform", - "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy.", + "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy.", obj( json!({ "ids": {"type": "array", "items": {"type": "integer"}}, 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 { - data: &'a [u8], - pos: usize, -} - -impl<'a> Reader<'a> { - pub fn new(data: &'a [u8]) -> Self { - Self { data, pos: 0 } - } - pub fn bytes(&mut self, n: usize) -> Option<&'a [u8]> { - let b = self.data.get(self.pos..self.pos.checked_add(n)?)?; - self.pos += n; - Some(b) - } - fn array(&mut self) -> Option<[u8; N]> { - self.bytes(N)?.try_into().ok() - } - pub fn u16(&mut self) -> Option { - self.array().map(u16::from_le_bytes) - } - pub fn i16(&mut self) -> Option { - self.array().map(i16::from_le_bytes) - } - pub fn u32(&mut self) -> Option { - self.array().map(u32::from_le_bytes) - } - pub fn i32(&mut self) -> Option { - self.array().map(i32::from_le_bytes) - } - pub fn f32(&mut self) -> Option { - self.array().map(f32::from_le_bytes) - } - pub fn skip(&mut self, n: usize) -> Option<()> { - self.bytes(n).map(drop) - } - /// The bytes not read yet. - pub fn rest(&self) -> &'a [u8] { - self.data.get(self.pos..).unwrap_or_default() - } -} - -/// `len` bytes of `data` from `offset` (record-relative offsets read from untrusted files). -pub(crate) fn slice(data: &[u8], offset: u32, len: u32) -> Option<&[u8]> { - let start = usize::try_from(offset).ok()?; - data.get(start..start.checked_add(usize::try_from(len).ok()?)?) -} diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs index e5b3f5cfcc..a1f1df8cc3 100644 --- a/crates/metafile/src/dib.rs +++ b/crates/metafile/src/dib.rs @@ -1,30 +1,24 @@ //! Device-independent bitmaps (DIBs), the pixels inside image records: written bottom-up as 24-bit -//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source); read from 1, -//! 4, 8, 16, 24 and 32-bit uncompressed and bit-field bitmaps and from embedded JPEG and PNG. +//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source). use std::io::Cursor; use vectorcraft_doc::resample::{Resample, resized}; -use crate::bytes::Reader; - /// Most pixels along a side of an image the writers store (larger ones are scaled down). const MAX_SIDE: u32 = 8192; /// Most pixels an image the writers store holds. const MAX_PIXELS: u64 = 1 << 24; -/// Most pixels along a side, and in all, of a bitmap the reader decodes. +/// Most pixels along a side, and in all, of a bitmap the PICT reader decodes. pub(crate) const MAX_READ_SIDE: u32 = 1 << 15; pub(crate) const MAX_READ_PIXELS: u64 = 1 << 26; /// Most pixels the bitmaps of one file may decode to together (four of the largest one), so a small /// file of many image records can't cost minutes of decoding (#3600). pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28; -/// What [`decode`] says of a bitmap past what is left of the file's budget. +/// What [`charge`] says of a bitmap past what is left of the file's budget. pub(crate) const OVER_BUDGET: &str = "the bitmaps hold more pixels than one file may"; const BI_RGB: u32 = 0; -const BI_BITFIELDS: u32 = 3; -const BI_JPEG: u32 = 4; -const BI_PNG: u32 = 5; /// Pixels with straight (not premultiplied) alpha, row by row from the top. #[derive(Clone, Debug, PartialEq)] @@ -124,48 +118,6 @@ pub(crate) fn bgra32(img: &Rgba, opacity: f32) -> (Vec, Vec) { (header(img.width, img.height, 32, bits.len()), bits) } -/// How the fourth byte of 32-bit pixels reads. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum Alpha { - /// Unused (StretchDIBits and BitBlt ignore it): every pixel opaque. - Ignore, - /// Premultiplied alpha (AlphaBlend with per-pixel alpha). - Premultiplied, -} - -/// A colour channel of `v` under `mask`, scaled to 0–255. -fn channel(v: u32, mask: u32) -> u8 { - if mask == 0 { - return 0; - } - let shift = mask.trailing_zeros(); - let max = u64::from(mask >> shift); - let x = u64::from((v & mask) >> shift); - ((x * 255 + max / 2) / max.max(1)).min(255) as u8 -} - -/// PNG `bytes` without its compressed or text ancillary chunks (`iCCP`, `zTXt`, `iTXt`, `tEXt`), -/// which the pixels don't need and which a decoder expands when it is made. Other bytes, and a PNG -/// whose chunks don't read to the end, are returned as they are. -fn png_without_metadata(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> { - const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n"; - if !bytes.starts_with(SIGNATURE) { - return bytes.into(); - } - let mut out = SIGNATURE.to_vec(); - let mut at = SIGNATURE.len(); - while at < bytes.len() { - let (Some(len), Some(kind)) = (bytes.get(at..at + 4), bytes.get(at + 4..at + 8)) else { return bytes.into() }; - let len = u32::from_be_bytes([len[0], len[1], len[2], len[3]]) as usize; - let Some(end) = at.checked_add(12).and_then(|n| n.checked_add(len)).filter(|end| *end <= bytes.len()) else { return bytes.into() }; - if !matches!(kind, b"iCCP" | b"zTXt" | b"iTXt" | b"tEXt") { - out.extend_from_slice(&bytes[at..end]); - } - at = end; - } - out.into() -} - /// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded. pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { let n = u64::from(w) * u64::from(h); @@ -173,215 +125,24 @@ pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { Ok(()) } -/// Read a DIB from its BITMAPINFO (`bmi`: the header and colour table) and pixel `bits`, taking its -/// pixels from what is `left` of the file's budget ([`MAX_FILE_PIXELS`]). -pub(crate) fn decode(bmi: &[u8], bits: &[u8], alpha: Alpha, left: &mut u64) -> Result { - let bad = || "a bitmap is damaged".to_string(); - let mut r = Reader::new(bmi); - let size = r.u32().ok_or_else(bad)?; - let (width, height, bpp, compression, colors, palette_entry, masks_at) = if size == 12 { - // BITMAPCOREHEADER: 16-bit sizes, RGB triples. - let w = i32::from(r.u16().ok_or_else(bad)?); - let h = i32::from(r.u16().ok_or_else(bad)?); - r.skip(2).ok_or_else(bad)?; - let bpp = r.u16().ok_or_else(bad)?; - (w, h, bpp, BI_RGB, 0, 3, 0) - } else if size >= 40 { - let w = r.i32().ok_or_else(bad)?; - let h = r.i32().ok_or_else(bad)?; - r.skip(2).ok_or_else(bad)?; - let bpp = r.u16().ok_or_else(bad)?; - let c = r.u32().ok_or_else(bad)?; - r.skip(12).ok_or_else(bad)?; - let used = r.u32().ok_or_else(bad)?; - (w, h, bpp, c, used, 4, 40) - } else { - return Err(bad()); - }; - if compression == BI_JPEG || compression == BI_PNG { - // The size comes from the image header, so an over-limit bitmap is refused before any pixels are decoded. - // A PNG's compressed ICC profile and text chunks expand when its decoder is made, and - // nothing here uses them: they are left out before the size is read and the pixels decoded. - let bits = png_without_metadata(bits); - let (w, h) = image::ImageReader::new(Cursor::new(&*bits)).with_guessed_format().map_err(|_| bad())?.into_dimensions().map_err(|_| bad())?; - if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS { - return Err("a bitmap is too large to read".into()); - } - charge(w, h, left)?; - let img = image::load_from_memory(&bits).map_err(|_| bad())?.to_rgba8(); - return Ok(Rgba { width: w, height: h, pixels: img.into_raw() }); - } - if compression != BI_RGB && compression != BI_BITFIELDS { - return Err("compressed (RLE) bitmaps can't be read yet".into()); - } - let top_down = height < 0; - let (w, h) = (width.unsigned_abs(), height.unsigned_abs()); - if w == 0 || h == 0 { - return Err("a bitmap is empty".into()); - } - if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS { - return Err("a bitmap is too large to read".into()); - } - let header_len = size as usize; - // Bit-field masks follow a plain 40-byte header, or sit inside the larger ones. - let fields = compression == BI_BITFIELDS; - let masks: Option<[u32; 4]> = fields.then(|| { - let mut m = Reader::new(bmi.get(masks_at..).unwrap_or_default()); - let rgb = [m.u32().unwrap_or(0), m.u32().unwrap_or(0), m.u32().unwrap_or(0)]; - // An alpha mask comes with BITMAPV3INFOHEADER and later. - let a = if header_len >= 56 { m.u32().unwrap_or(0) } else { 0 }; - [rgb[0], rgb[1], rgb[2], a] - }); - let palette_at = header_len + if fields && header_len == 40 { 12 } else { 0 }; - let bpp_u = u32::from(bpp); - let palette: Vec<[u8; 3]> = if bpp_u <= 8 { - let n = if colors == 0 { 1usize << bpp_u } else { (colors as usize).min(256) }; - bmi.get(palette_at..) - .unwrap_or_default() - .chunks_exact(palette_entry) - .take(n) - .map(|e| [e.get(2).copied().unwrap_or(0), e.get(1).copied().unwrap_or(0), e.first().copied().unwrap_or(0)]) - .collect() - } else { - vec![] - }; - if !matches!(bpp, 1 | 4 | 8 | 16 | 24 | 32) { - return Err(format!("{bpp}-bit bitmaps can't be read")); - } - let row = stride(w, bpp_u).ok_or_else(bad)?; - if bits.len() < row.checked_mul(h as usize).ok_or_else(bad)? { - return Err(bad()); - } - charge(w, h, left)?; - let (mr, mg, mb, ma) = match (masks, bpp) { - (Some([r, g, b, a]), _) => (r, g, b, a), - (None, 16) => (0x7c00, 0x03e0, 0x001f, 0), - _ => (0x00ff_0000, 0x0000_ff00, 0x0000_00ff, 0xff00_0000), - }; - let mut pixels = Vec::with_capacity(w as usize * h as usize * 4); - for y in 0..h as usize { - let src_row = if top_down { y } else { h as usize - 1 - y }; - let line = bits.get(src_row * row..src_row * row + row).ok_or_else(bad)?; - for x in 0..w as usize { - let px: [u8; 4] = match bpp { - 1 | 4 | 8 => { - let bit = x * bpp_u as usize; - let byte = line.get(bit / 8).copied().unwrap_or(0); - let idx = (byte >> (8 - bpp_u as usize - bit % 8)) & ((1u16 << bpp_u) - 1) as u8; - let [r, g, b] = palette.get(idx as usize).copied().unwrap_or([0, 0, 0]); - [r, g, b, 255] - } - 16 => { - let v = u32::from(u16::from_le_bytes([line.get(x * 2).copied().unwrap_or(0), line.get(x * 2 + 1).copied().unwrap_or(0)])); - [channel(v, mr), channel(v, mg), channel(v, mb), 255] - } - 24 => { - let p = line.get(x * 3..x * 3 + 3).unwrap_or(&[0, 0, 0]); - [p[2], p[1], p[0], 255] - } - _ => { - let p = line.get(x * 4..x * 4 + 4).unwrap_or(&[0, 0, 0, 0]); - let v = u32::from_le_bytes([p[0], p[1], p[2], p[3]]); - let a = if alpha == Alpha::Premultiplied && ma != 0 { channel(v, ma) } else { 255 }; - let un = - |c: u8| if alpha == Alpha::Premultiplied && a < 255 { (u32::from(c) * 255 / u32::from(a.max(1))).min(255) as u8 } else { c }; - [un(channel(v, mr)), un(channel(v, mg)), un(channel(v, mb)), if alpha == Alpha::Premultiplied { a } else { 255 }] - } - }; - pixels.extend_from_slice(&px); - } - } - Ok(Rgba { width: w, height: h, pixels }) -} - -/// A packed DIB (a BITMAPINFO and its bits, one after the other, as WMF records hold them) split -/// into the two. -pub(crate) fn split(packed: &[u8]) -> Option<(&[u8], &[u8])> { - let mut r = Reader::new(packed); - let size = r.u32()? as usize; - let (bpp, compression, used, entry) = if size == 12 { - r.skip(6)?; - (r.u16()?, BI_RGB, 0, 3) - } else { - r.skip(10)?; - let bpp = r.u16()?; - let c = r.u32()?; - r.skip(12)?; - (bpp, c, r.u32()? as usize, 4) - }; - let masks = if compression == BI_BITFIELDS && size == 40 { 12 } else { 0 }; - let colors = if used > 0 { - used.min(256) - } else if bpp <= 8 { - 1usize << bpp - } else { - 0 - }; - let len = size.checked_add(masks)?.checked_add(colors * entry)?; - Some((packed.get(..len)?, packed.get(len..)?)) -} - #[cfg(test)] mod tests { use super::*; - #[test] - fn a_pngs_compressed_metadata_is_left_out_before_it_is_decoded() { - use image::ImageEncoder; - let mut png = vec![]; - let mut encoder = image::codecs::png::PngEncoder::new(&mut png); - encoder.set_icc_profile(vec![0; 1 << 20]).unwrap(); - encoder.write_image(&[10, 20, 30], 1, 1, image::ExtendedColorType::Rgb8).unwrap(); - assert!(png.windows(4).any(|w| w == b"iCCP")); - let stripped = png_without_metadata(&png); - assert!(!stripped.windows(4).any(|w| w == b"iCCP") && stripped.len() < png.len()); - let img = image::load_from_memory(&stripped).unwrap().to_rgba8(); - assert_eq!(img.get_pixel(0, 0).0, [10, 20, 30, 255]); - // Not a PNG, or a PNG cut short: unchanged. - assert_eq!(&*png_without_metadata(b"BM...."), b"BM...."); - assert_eq!(&*png_without_metadata(&png[..png.len() - 3]), &png[..png.len() - 3]); - } - fn sample() -> Rgba { // 3 × 2: red, green, blue / half-transparent black, transparent, white. let pixels = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]; Rgba { width: 3, height: 2, pixels } } - /// A whole file's budget. - fn budget() -> u64 { - MAX_FILE_PIXELS - } - - /// A BITMAPINFOHEADER of an embedded PNG. - fn png_header() -> Vec { - let mut bmi = vec![0u8; 40]; - bmi[..4].copy_from_slice(&40u32.to_le_bytes()); - bmi[16..20].copy_from_slice(&BI_PNG.to_le_bytes()); - bmi - } - - #[test] - fn oversized_png_is_refused_from_its_header() { - // A width over the limit in the IHDR chunk: decoding the pixels would fail with a different error. - let png = crate::tests::png_claiming(MAX_READ_SIDE + 1, 1); - let err = decode(&png_header(), &png, Alpha::Ignore, &mut budget()).unwrap_err(); - assert_eq!(err, "a bitmap is too large to read"); - } - #[test] fn bitmaps_share_the_file_budget() { // #3600: each bitmap is charged before it is decoded, and one past what is left is refused. - let (bmi, bits) = rgb24(&sample(), 1.0); let mut left = 6 + 5; - assert!(decode(&bmi, &bits, Alpha::Ignore, &mut left).is_ok()); + assert!(charge(3, 2, &mut left).is_ok()); assert_eq!(left, 5); - assert_eq!(decode(&bmi, &bits, Alpha::Ignore, &mut left).unwrap_err(), OVER_BUDGET); + assert_eq!(charge(3, 2, &mut left).unwrap_err(), OVER_BUDGET); assert_eq!(left, 5, "a refused bitmap costs nothing"); - // An embedded PNG is charged from its header, so one past the budget is never decoded. - let mut left = (1 << 20) - 1; - let png = crate::tests::png_claiming(1 << 10, 1 << 10); - assert_eq!(decode(&png_header(), &png, Alpha::Ignore, &mut left).unwrap_err(), OVER_BUDGET); } #[test] @@ -405,45 +166,6 @@ mod tests { assert_eq!(&half[12..16], &[0, 0, 128, 128]); } - #[test] - fn rgb24_round_trips_over_white() { - let (bmi, bits) = rgb24(&sample(), 1.0); - assert_eq!(bmi.len(), 40); - // Rows of 9 bytes padded to 12. - assert_eq!(bits.len(), 24); - let back = decode(&bmi, &bits, Alpha::Ignore, &mut budget()).unwrap(); - assert_eq!((back.width, back.height), (3, 2)); - assert_eq!(&back.pixels[..12], &[255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]); - // Half-transparent black over white is mid grey; transparent is white. - assert_eq!(&back.pixels[12..16], &[127, 127, 127, 255]); - assert_eq!(&back.pixels[16..20], &[255, 255, 255, 255]); - } - - #[test] - fn bgra32_round_trips_with_alpha() { - let (bmi, bits) = bgra32(&sample(), 1.0); - let back = decode(&bmi, &bits, Alpha::Premultiplied, &mut budget()).unwrap(); - assert_eq!(&back.pixels[..12], &sample().pixels[..12]); - assert_eq!(back.pixels[15], 128); - assert_eq!(back.pixels[19], 0); - // Read as StretchDIBits does, alpha is ignored. - assert!(decode(&bmi, &bits, Alpha::Ignore, &mut budget()).unwrap().opaque()); - } - - #[test] - fn palette_bitmaps_and_damage() { - // A 1-bit 2 × 1 bitmap: black then white. - let mut bmi = header(2, 1, 1, 4); - bmi.extend_from_slice(&[0, 0, 0, 0, 255, 255, 255, 0]); - let back = decode(&bmi, &[0b0100_0000, 0, 0, 0], Alpha::Ignore, &mut budget()).unwrap(); - assert_eq!(back.pixels, vec![0, 0, 0, 255, 255, 255, 255, 255]); - // Too few bits, a silly size, an unknown depth: errors, no panic. - assert!(decode(&bmi, &[0], Alpha::Ignore, &mut budget()).is_err()); - assert!(decode(&header(1 << 20, 1 << 20, 24, 0), &[], Alpha::Ignore, &mut budget()).is_err()); - assert!(decode(&header(1, 1, 7, 0), &[0; 4], Alpha::Ignore, &mut budget()).is_err()); - assert!(decode(&[1, 2], &[], Alpha::Ignore, &mut budget()).is_err()); - } - #[test] fn large_images_are_scaled_to_fit() { let img = image::RgbaImage::new(MAX_SIDE * 2, 4); diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index da7816663e..c87dd83d72 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -1,16 +1,14 @@ -//! The metafile reader: the format parsers (`emf`, `wmf`, and `pict` for QuickDraw pictures) play -//! their records on a [`Player`], a small model of the device context they draw into (objects, -//! transforms, the current position, the path bracket, the clip), which turns what they draw into -//! document objects. +//! The metafile readers. EMF (with its EMF+ records) and WMF files are read by `craft_metafile`, +//! and `picture` turns what they draw into document objects. QuickDraw pictures (`pict`) play their +//! opcodes on a [`Player`], a small model of the drawing state (pen, brush, font, the clip), which +//! turns what they draw into document objects. //! //! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the //! same pen join into one path. Clips become clipping groups around what they clip. Images keep -//! their pixels (as PNG), text becomes point type in the font the file names. Records the reader -//! doesn't know are counted and skipped, with one warning. +//! their pixels (as PNG), text becomes point type in the font the file names. -mod emf; pub(crate) mod pict; -mod wmf; +mod picture; use std::sync::Arc; @@ -20,7 +18,7 @@ use vectorcraft_doc::{ Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeKind, StrokeLayer, TextObject, }; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, Vec2, shapes}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes}; use crate::dib::{self, Rgba}; use crate::{Imported, Kind}; @@ -30,24 +28,13 @@ const MAX_NODES: usize = 1 << 20; /// Objects and clips reaching further than this from the origin (points, well inside the canvas) /// are left out: they come from damaged or hostile coordinates. const LIMIT: f64 = 1e6; -/// Most nested saved device contexts. -const MAX_SAVED: usize = 1024; /// Width of a cosmetic pen (one pixel of a 96 ppi screen), points. const HAIRLINE: f64 = 0.75; -/// Curves made for arcs and ellipses are this close to the true curve (logical units are -/// transformed after, so it is relative). -const ARC_TOLERANCE: f64 = 0.01; /// Raster operations. pub(crate) const SRCCOPY: u32 = 0x00CC_0020; -const PATCOPY: u32 = 0x00F0_0021; -const WHITENESS: u32 = 0x00FF_0062; -const BLACKNESS: u32 = 0x0000_0042; const SKIPPED_ROPS: &str = "images drawn with raster operations other than a plain copy (masks, inversions) were left out"; -const HATCHES: &str = "hatched brushes are filled with their colour"; -const PATTERN_BRUSHES: &str = "pattern brushes are filled grey"; -const EXCLUDED_CLIPS: &str = "clip areas cut out of the clip (excluded rectangles, differences) are ignored"; const BAD_IMAGE: &str = "an image that couldn't be read was left out"; const TOO_MANY_PIXELS: &str = "images past the most pixels one file may hold were left out"; const FAR_AWAY: &str = "objects far outside the picture were left out"; @@ -57,6 +44,58 @@ fn sane(r: Rect) -> bool { [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= LIMIT) } +/// Is `path` one upright rectangle around the whole of `frame`? Writers clip to one first; it clips +/// nothing in the picture. A path of more than one figure is not one rectangle, even when its +/// figures run along the sides of a box. Nor is one figure that runs back over its own edges, so +/// that it encloses less than the whole box. +fn around(path: &BezPath, frame: Rect) -> bool { + if path.elements().len() > 6 { + return false; + } + let b = path.bounding_box(); + let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]; + let near = |p: Point, q: Point| (p - q).hypot() <= 1e-6 * (1.0 + b.width().max(b.height())); + // Each edge, the closing one included, runs along a side: from a corner to itself or to a + // neighbor (corners are in order around the box), never across it. + let along = |i: usize, j: usize| (i + 4 - j) % 4 != 2; + let mut seen = [false; 4]; + let mut points = Vec::with_capacity(6); + let (mut first, mut last) = (None, None); + for e in path.elements() { + let (p, start) = match e { + PathEl::MoveTo(p) => (*p, true), + PathEl::LineTo(p) => (*p, false), + PathEl::ClosePath => continue, + PathEl::QuadTo(..) | PathEl::CurveTo(..) => return false, + }; + let Some(i) = corners.iter().position(|c| near(*c, p)) else { return false }; + if start { + if first.is_some() { + return false; + } + first = Some(i); + } else if last.is_some_and(|l| !along(l, i)) { + return false; + } + last = Some(i); + seen[i] = true; + points.push(corners[i]); + } + if let (Some(f), Some(l)) = (first, last) + && !along(f, l) + { + return false; + } + // Every edge runs along a side, so the figure winds the same number of times around every + // point inside the box: once, when its area is the box's. + let twice_area: f64 = points.iter().zip(points.iter().cycle().skip(1)).map(|(p, q)| (*p - corners[0]).cross(*q - corners[0])).sum(); + if (twice_area.abs() - 2.0 * b.area()).abs() > 1e-6 * (1.0 + 2.0 * b.area()) { + return false; + } + let b = b.inflate(0.5, 0.5); + seen.iter().all(|s| *s) && b.contains(frame.origin()) && b.contains(Point::new(frame.x1, frame.y1)) +} + /// A pen: its style flags (`PS_*`), width in logical units, colour and dash entries. #[derive(Clone, Debug, PartialEq)] pub(crate) struct PenObj { @@ -68,7 +107,6 @@ pub(crate) struct PenObj { } impl PenObj { - pub const NULL: PenObj = PenObj { style: PS_NULL, width: 0.0, color: [0; 3], entries: vec![] }; pub fn solid(color: [u8; 3]) -> Self { Self { style: 0, width: 0.0, color, entries: vec![] } } @@ -77,28 +115,6 @@ impl PenObj { pub(crate) const PS_NULL: u32 = 5; const PS_GEOMETRIC: u32 = 0x0001_0000; -/// A brush. -#[derive(Clone, Debug, PartialEq)] -pub(crate) enum BrushObj { - Null, - Solid([u8; 3]), - Hatched([u8; 3]), - /// A bitmap pattern (written grey). - Pattern, -} - -impl BrushObj { - /// From a LOGBRUSH's style and colour. - pub fn from_log(style: u32, color: [u8; 3]) -> Self { - match style { - 0 => Self::Solid(color), - 1 => Self::Null, - 2 => Self::Hatched(color), - _ => Self::Pattern, - } - } -} - /// A font: its height in logical units (negative: the character height, positive: the cell /// height), escapement (tenths of a degree), weight, italics and face. #[derive(Clone, Debug, Default, PartialEq)] @@ -110,35 +126,17 @@ pub(crate) struct FontObj { pub face: String, } -/// A GDI object. -#[derive(Clone, Debug)] -pub(crate) enum Obj { - Pen(PenObj), - Brush(BrushObj), - Font(FontObj), - /// Palettes, regions, colour spaces: they take a slot but don't change the drawing. - Other, -} - -/// The state records change, saved and restored as a whole. +/// The drawing state. #[derive(Clone, Debug)] struct Dc { pen: PenObj, - brush: BrushObj, + /// The brush's color. + brush: [u8; 3], font: FontObj, text_color: [u8; 3], text_align: u32, fill_rule: FillRule, miter: f64, - /// Arcs run counterclockwise (the default). - arc_ccw: bool, - /// Logical → page (EMF world transform). - world: Affine, - map_mode: u32, - win_org: Vec2, - win_ext: Vec2, - vp_org: Vec2, - vp_ext: Vec2, clips: Vec>, } @@ -146,105 +144,38 @@ impl Default for Dc { fn default() -> Self { Self { pen: PenObj::solid([0; 3]), - brush: BrushObj::Solid([255; 3]), + brush: [255; 3], font: FontObj::default(), text_color: [0; 3], text_align: 0, fill_rule: FillRule::EvenOdd, miter: 10.0, - arc_ccw: true, - world: Affine::IDENTITY, - map_mode: 1, - win_org: Vec2::ZERO, - win_ext: Vec2::new(1.0, 1.0), - vp_org: Vec2::ZERO, - vp_ext: Vec2::new(1.0, 1.0), clips: vec![], } } } -/// How an arc closes. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum ArcKind { - Open, - Chord, - Pie, -} - pub(crate) struct Player { kind: Kind, - /// Device units (EMF) or logical units (WMF) → document points. + /// Picture units → document points. dev_to_doc: Affine, - /// Millimetres per device pixel (EMF's fixed mapping modes). - mm_per_px: f64, dc: Dc, - saved: Vec, - objects: Vec>, - /// The lowest object slot that may be free (WMF numbering). - free_hint: usize, - /// The path being recorded (document space), whether a figure is open in it and where that - /// figure started (logical). - path: Option, - figure: bool, - figure_start: Point, /// The artboard (document space): clips holding all of it clip nothing worth keeping. frame: Rect, - /// The current position (logical). - pos: Point, - /// Lines drawn one after another outside a path bracket, not drawn yet. + /// Lines drawn one after another, not drawn yet. pending: BezPath, out: Drawn, doc: Document, warnings: Vec, - skipped: usize, next_clip: u32, /// Pixels the file's bitmaps may still decode to ([`dib::MAX_FILE_PIXELS`]). pub pixels_left: u64, - /// The file holds EMF+ records (which aren't read). - pub emf_plus: bool, } fn rgb(c: [u8; 3]) -> Paint { Paint::solid(Color::rgb8(c[0], c[1], c[2])) } -/// The arc of the ellipse in `r` from the ray through `start` to the ray through `end`. -pub(crate) fn arc_path(r: Rect, start: Point, end: Point, ccw: bool, kind: ArcKind) -> BezPath { - let r = r.abs(); - let c = r.center(); - let radii = Vec2::new(r.width() / 2.0, r.height() / 2.0); - let mut bp = BezPath::new(); - if radii.x <= 0.0 || radii.y <= 0.0 { - return bp; - } - let angle = |p: Point| ((p.y - c.y) / radii.y).atan2((p.x - c.x) / radii.x); - let (a0, a1) = (angle(start), angle(end)); - let tau = std::f64::consts::TAU; - // Counterclockwise on a y-down device is towards smaller angles. - let sweep = if ccw { - let s = (a0 - a1).rem_euclid(tau); - -(if s == 0.0 { tau } else { s }) - } else { - let s = (a1 - a0).rem_euclid(tau); - if s == 0.0 { tau } else { s } - }; - let arc = kurbo::Arc { center: c, radii, start_angle: a0, sweep_angle: sweep, x_rotation: 0.0 }; - let tol = ARC_TOLERANCE * radii.x.max(radii.y).max(1e-9); - if kind == ArcKind::Pie { - bp.move_to(c); - let first = c + Vec2::new(radii.x * a0.cos(), radii.y * a0.sin()); - bp.line_to(first); - arc.append_iter(tol).for_each(|el| bp.push(el)); - } else { - kurbo::Shape::path_elements(&arc, tol).for_each(|el| bp.push(el)); - } - if kind != ArcKind::Open { - bp.close_path(); - } - bp -} - /// A rectangle with elliptical corners `rx` × `ry`. pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath { let r = r.abs(); @@ -261,7 +192,7 @@ pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath { } impl Player { - fn new(kind: Kind, dev_to_doc: Affine, mm_per_px: f64, artboard: Rect) -> Self { + fn new(kind: Kind, dev_to_doc: Affine, artboard: Rect) -> Self { let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 }; let (w, h) = (side(artboard.width()), side(artboard.height())); let mut doc = Document::new(w, h); @@ -269,24 +200,14 @@ impl Player { Self { kind, dev_to_doc, - mm_per_px, dc: Dc::default(), - saved: vec![], - objects: vec![], - free_hint: 0, - path: None, - figure: false, - figure_start: Point::ZERO, frame: artboard, - pos: Point::ZERO, pending: BezPath::new(), out: vec![], doc, warnings: vec![], - skipped: 0, next_clip: 0, pixels_left: dib::MAX_FILE_PIXELS, - emf_plus: false, } } @@ -296,188 +217,19 @@ impl Player { } } - /// A record of a kind the reader doesn't know. - pub fn skip(&mut self) { - self.skipped += 1; - } - // ---------- mapping ---------- - /// Logical → document. + /// Picture units → document. fn xf(&self) -> Affine { - if self.kind == Kind::Wmf { - return self.dev_to_doc; - } - let d = &self.dc; - let page_to_dev = match d.map_mode { - // Fixed modes: millimetres a unit, y up. - 2..=6 => { - let mm = [0.1, 0.01, 0.254, 0.0254, 25.4 / 1440.0][(d.map_mode - 2) as usize]; - let s = mm / self.mm_per_px.max(1e-12); - Affine::translate(d.vp_org) * Affine::scale_non_uniform(s, -s) * Affine::translate(-d.win_org) - } - 7 | 8 => { - let ratio = |v: f64, w: f64| if w.abs() > 1e-12 && v.is_finite() { v / w } else { 1.0 }; - let (mut sx, mut sy) = (ratio(d.vp_ext.x, d.win_ext.x), ratio(d.vp_ext.y, d.win_ext.y)); - if d.map_mode == 7 { - // Isotropic: the same scale both ways, the smaller one. - let s = sx.abs().min(sy.abs()); - (sx, sy) = (s.copysign(sx), s.copysign(sy)); - } - Affine::translate(d.vp_org) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-d.win_org) - } - _ => Affine::translate(d.vp_org - d.win_org), - }; - self.dev_to_doc * page_to_dev * d.world + self.dev_to_doc } - /// How much logical lengths grow in the document. + /// How much picture lengths grow in the document. fn scale(&self) -> f64 { let s = self.xf().determinant().abs().sqrt(); if s.is_finite() { s } else { 0.0 } } - pub fn set_map_mode(&mut self, m: u32) { - self.dc.map_mode = m; - } - pub fn set_window_org(&mut self, x: f64, y: f64) { - self.dc.win_org = Vec2::new(x, y); - } - pub fn set_window_ext(&mut self, x: f64, y: f64) { - self.dc.win_ext = Vec2::new(x, y); - } - pub fn set_viewport_org(&mut self, x: f64, y: f64) { - self.dc.vp_org = Vec2::new(x, y); - } - pub fn set_viewport_ext(&mut self, x: f64, y: f64) { - self.dc.vp_ext = Vec2::new(x, y); - } - pub fn scale_ext(&mut self, window: bool, x: (f64, f64), y: (f64, f64)) { - let e = if window { &mut self.dc.win_ext } else { &mut self.dc.vp_ext }; - if x.1 != 0.0 && y.1 != 0.0 { - *e = Vec2::new(e.x * x.0 / x.1, e.y * y.0 / y.1); - } - } - /// `SetWorldTransform` / `ModifyWorldTransform` (`mode`: 1 identity, 2 left, 3 right, 4 set). - pub fn world(&mut self, x: Affine, mode: u32) { - if !x.as_coeffs().iter().all(|v| v.is_finite()) { - return; - } - self.dc.world = match mode { - 1 => Affine::IDENTITY, - 2 => self.dc.world * x, - 3 => x * self.dc.world, - _ => x, - }; - } - - // ---------- state ---------- - - pub fn set_fill_mode(&mut self, alternate: bool) { - self.dc.fill_rule = if alternate { FillRule::EvenOdd } else { FillRule::NonZero }; - } - pub fn set_miter(&mut self, m: f64) { - if m.is_finite() && m >= 1.0 { - self.dc.miter = m; - } - } - pub fn set_arc_ccw(&mut self, ccw: bool) { - self.dc.arc_ccw = ccw; - } - pub fn set_text_color(&mut self, c: [u8; 3]) { - self.dc.text_color = c; - } - pub fn set_text_align(&mut self, a: u32) { - self.dc.text_align = a; - } - - pub fn save(&mut self) { - if self.saved.len() < MAX_SAVED { - self.saved.push(self.dc.clone()); - } - } - - /// `RestoreDC(n)`: a negative `n` counts back from the latest save, a positive one is a save's - /// number. - pub fn restore(&mut self, n: i32) { - let len = self.saved.len(); - let keep = if n < 0 { len.checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1).filter(|k| *k < len) }; - if let Some(k) = keep { - self.saved.truncate(k + 1); - if let Some(dc) = self.saved.pop() { - self.dc = dc; - } - } - } - - // ---------- objects ---------- - - /// Put `obj` in slot `index` (EMF numbers its objects). - pub fn create_at(&mut self, index: u32, obj: Obj) { - let i = index as usize; - if i == 0 || i > u16::MAX as usize { - return; - } - if self.objects.len() <= i { - self.objects.resize(i + 1, None); - } - if let Some(s) = self.objects.get_mut(i) { - *s = Some(obj); - } - } - - /// Put `obj` in the lowest free slot (WMF). - pub fn create(&mut self, obj: Obj) { - let start = self.free_hint.min(self.objects.len()); - let i = self.objects.iter().skip(start).position(Option::is_none).map_or(self.objects.len(), |p| p + start); - if i > u16::MAX as usize { - // The table is full past the hint: the next creation looks from the end, not again - // through every slot. - self.free_hint = i; - return; - } - if i == self.objects.len() { - self.objects.push(None); - } - if let Some(s) = self.objects.get_mut(i) { - *s = Some(obj); - } - self.free_hint = i + 1; - } - - pub fn delete(&mut self, index: u32) { - if let Some(s) = self.objects.get_mut(index as usize) { - *s = None; - self.free_hint = self.free_hint.min(index as usize); - } - } - - /// Select object `index`, or a stock object (EMF: the high bit set). - pub fn select(&mut self, index: u32) { - if self.kind == Kind::Emf && index & 0x8000_0000 != 0 { - match index & 0x7fff_ffff { - 0 | 18 => self.dc.brush = BrushObj::Solid([255; 3]), - 1 => self.dc.brush = BrushObj::Solid([0xc0; 3]), - 2 => self.dc.brush = BrushObj::Solid([0x80; 3]), - 3 => self.dc.brush = BrushObj::Solid([0x40; 3]), - 4 => self.dc.brush = BrushObj::Solid([0; 3]), - 5 => self.dc.brush = BrushObj::Null, - 6 => self.dc.pen = PenObj::solid([255; 3]), - 7 | 19 => self.dc.pen = PenObj::solid([0; 3]), - 8 => self.dc.pen = PenObj::NULL, - 10..=17 => self.dc.font = FontObj::default(), - _ => {} - } - return; - } - match self.objects.get(index as usize).cloned().flatten() { - Some(Obj::Pen(p)) => self.dc.pen = p, - Some(Obj::Brush(b)) => self.dc.brush = b, - Some(Obj::Font(f)) => self.dc.font = f, - _ => {} - } - } - // ---------- output ---------- fn push(&mut self, mut node: Node) { @@ -491,19 +243,8 @@ impl Player { self.out.push((self.dc.clips.clone(), node)); } - fn fill_paint(&mut self) -> Option { - match self.dc.brush.clone() { - BrushObj::Null => None, - BrushObj::Solid(c) => Some(rgb(c)), - BrushObj::Hatched(c) => { - self.warn(HATCHES); - Some(rgb(c)) - } - BrushObj::Pattern => { - self.warn(PATTERN_BRUSHES); - Some(rgb([0x80; 3])) - } - } + fn fill_paint(&self) -> Paint { + rgb(self.dc.brush) } fn stroke_layer(&self) -> Option { @@ -549,8 +290,8 @@ impl Player { return; } let mut items = vec![]; - if fill && let Some(p) = self.fill_paint() { - items.push(AppearanceItem::Fill(FillLayer::new(p))); + if fill { + items.push(AppearanceItem::Fill(FillLayer::new(self.fill_paint()))); } if stroke && let Some(st) = self.stroke_layer() { items.push(AppearanceItem::Stroke(st)); @@ -573,124 +314,7 @@ impl Player { } } - /// A figure in logical units: added to the path being recorded, else drawn (filled when it is - /// an area). - pub fn figure(&mut self, mut bp: BezPath, area: bool) { - bp.apply_affine(self.xf()); - match &mut self.path { - Some(path) => { - path.extend(bp); - self.figure = false; - } - None => self.draw(bp, area, true), - } - } - - /// Polygon / Polyline (and Bézier ones): `pts` in logical units. - pub fn poly(&mut self, pts: &[Point], closed: bool, bezier: bool) { - let Some((first, rest)) = pts.split_first() else { return }; - let mut bp = BezPath::new(); - bp.move_to(*first); - if bezier { - for c in rest.as_chunks::<3>().0 { - bp.curve_to(c[0], c[1], c[2]); - } - } else { - rest.iter().for_each(|p| bp.line_to(*p)); - } - if closed { - bp.close_path(); - } - self.figure(bp, closed); - } - - /// Several polygons (one area) or polylines. - pub fn poly_poly(&mut self, polys: &[Vec], closed: bool) { - let mut bp = BezPath::new(); - for p in polys { - let Some((first, rest)) = p.split_first() else { continue }; - bp.move_to(*first); - rest.iter().for_each(|q| bp.line_to(*q)); - if closed { - bp.close_path(); - } - } - self.figure(bp, closed); - } - - pub fn move_to(&mut self, p: Point) { - self.pos = p; - self.figure = false; - } - - /// LineTo / PolylineTo / PolyBezierTo: from the current position through `pts` (logical). - pub fn poly_to(&mut self, pts: &[Point], bezier: bool) { - let Some(last) = pts.last().copied() else { return }; - let xf = self.xf(); - let start = xf * self.pos; - let target = match &mut self.path { - Some(path) => { - if !self.figure { - path.move_to(start); - self.figure = true; - self.figure_start = self.pos; - } - path - } - None => { - if self.pending.elements().last().and_then(|e| e.end_point()) != Some(start) { - self.pending.move_to(start); - } - &mut self.pending - } - }; - if bezier { - for c in pts.as_chunks::<3>().0 { - target.curve_to(xf * c[0], xf * c[1], xf * c[2]); - } - } else { - pts.iter().for_each(|p| target.line_to(xf * *p)); - } - self.pos = last; - } - - pub fn arc(&mut self, r: Rect, start: Point, end: Point, kind: ArcKind) { - let bp = arc_path(r, start, end, self.dc.arc_ccw, kind); - self.figure(bp, kind != ArcKind::Open); - } - - // ---------- paths and clips ---------- - - pub fn begin_path(&mut self) { - self.path = Some(BezPath::new()); - self.figure = false; - } - pub fn end_path(&mut self) { - // The path stays until it is filled, stroked or made the clip. - } - pub fn close_figure(&mut self) { - if let Some(p) = &mut self.path - && self.figure - { - p.close_path(); - self.figure = false; - self.pos = self.figure_start; - } - } - pub fn abort_path(&mut self) { - self.path = None; - } - - /// FillPath / StrokePath / StrokeAndFillPath. - pub fn paint_path(&mut self, fill: bool, stroke: bool) { - if let Some(mut bp) = self.path.take() { - // Filling closes the open figure. - if fill && self.figure { - bp.close_path(); - } - self.draw(bp, fill, stroke); - } - } + // ---------- clips ---------- fn push_clip(&mut self, path: BezPath, rule: FillRule, replace: bool) { if replace { @@ -699,10 +323,7 @@ impl Player { if !sane(path.bounding_box()) { return self.warn(FAR_AWAY); } - // A rectangle around the whole picture (what writers clip to first) clips nothing in it. - let lines = path.elements().iter().all(|e| !matches!(e, PathEl::QuadTo(..) | PathEl::CurveTo(..))); - let around = path.bounding_box().inflate(0.5, 0.5); - if lines && path.elements().len() <= 6 && around.contains(self.frame.origin()) && around.contains(Point::new(self.frame.x1, self.frame.y1)) { + if around(&path, self.frame) { return; } if self.dc.clips.len() >= MAX_NEST { @@ -712,69 +333,10 @@ impl Player { self.dc.clips.push(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) })); } - /// SelectClipPath (`mode`: 1 and, 5 copy; the others cut out, which isn't read). - pub fn clip_path(&mut self, mode: u32) { - let Some(bp) = self.path.take() else { return }; - match mode { - 1 => self.push_clip(bp, self.dc.fill_rule, false), - 5 => self.push_clip(bp, self.dc.fill_rule, true), - _ => self.warn(EXCLUDED_CLIPS), - } - } - - /// IntersectClipRect (logical units). - pub fn clip_rect(&mut self, r: Rect) { - let mut bp = shapes::rectangle(r.abs()).to_bezpath(); - bp.apply_affine(self.xf()); - self.push_clip(bp, FillRule::NonZero, false); - } - - /// A clip region of `rects` in device units (`mode` as [`Self::clip_path`]); none with mode - /// copy removes the clip. - pub fn clip_region(&mut self, rects: &[Rect], mode: u32) { - if rects.is_empty() { - if mode == 5 { - self.dc.clips.clear(); - } - return; - } - let mut bp = BezPath::new(); - for r in rects { - bp.extend(shapes::rectangle(r.abs()).to_bezpath()); - } - bp.apply_affine(self.dev_to_doc); - match mode { - 1 => self.push_clip(bp, FillRule::NonZero, false), - 5 => self.push_clip(bp, FillRule::NonZero, true), - _ => self.warn(EXCLUDED_CLIPS), - } - } - - pub fn exclude_clip(&mut self) { - self.warn(EXCLUDED_CLIPS); - } - - // ---------- blits, images and text ---------- - - /// A raster operation without a source over `dest` (logical): the brush, white or black. - pub fn pattern_blit(&mut self, dest: Rect, rop: u32) { - let brush = match rop { - PATCOPY => self.dc.brush.clone(), - WHITENESS => BrushObj::Solid([255; 3]), - BLACKNESS => BrushObj::Solid([0; 3]), - _ => return self.skip(), - }; - let pen = std::mem::replace(&mut self.dc.pen, PenObj::NULL); - let outer = std::mem::replace(&mut self.dc.brush, brush); - let mut bp = shapes::rectangle(dest.abs()).to_bezpath(); - bp.apply_affine(self.xf()); - self.draw(bp, true, false); - self.dc.pen = pen; - self.dc.brush = outer; - } + // ---------- images and text ---------- /// An image whose source rectangle `src` (pixels, from the top-left) is drawn into `dest` - /// (logical: origin and signed size) with raster operation `rop`, at `opacity`. + /// (picture units: origin and signed size) with raster operation `rop`, at `opacity`. pub fn image(&mut self, img: Result, src: Rect, dest: Rect, rop: u32, opacity: f64) { if rop != SRCCOPY { self.warn(SKIPPED_ROPS); @@ -793,8 +355,8 @@ impl Player { self.image_xf(img, Affine::translate((dest.x0, dest.y0)) * Affine::scale_non_uniform(dest.width() / w, dest.height() / h), opacity); } - /// An image placed by `xf` (its pixels, from the top-left, → logical), at `opacity`. An image - /// that `xf` flattens or sends past finite numbers is left out, and adds nothing to the + /// An image placed by `xf` (its pixels, from the top-left, → picture units), at `opacity`. An + /// image that `xf` flattens or sends past finite numbers is left out, and adds nothing to the /// document's images. pub(crate) fn image_xf(&mut self, img: Rgba, xf: Affine, opacity: f64) { if img.width == 0 || img.height == 0 { @@ -814,14 +376,13 @@ impl Player { self.push(n); } - /// Text at `at` (logical; the current position with TA_UPDATECP) in the current font. + /// Text at `at` (picture units) in the current font. pub fn text(&mut self, at: Point, s: &str) { let s: String = s.chars().filter(|c| *c != '\0').collect(); if s.trim().is_empty() { return; } let align = self.dc.text_align; - let at = if align & 1 != 0 { self.pos } else { at }; let f = self.dc.font.clone(); let k = self.scale(); // A negative height is the em; a positive one the cell (the em and the internal leading). @@ -863,18 +424,7 @@ impl Player { /// The document: what was drawn on one layer, clipped art in clipping groups. fn finish(mut self) -> Imported { self.flush(); - if self.skipped > 0 { - let n = self.skipped; - self.warnings.push(format!( - "{n} record{} of kinds VectorCraft doesn't read {} skipped", - if n == 1 { "" } else { "s" }, - if n == 1 { "was" } else { "were" } - )); - } let out = std::mem::take(&mut self.out); - if out.is_empty() && self.emf_plus { - self.warnings.push("the picture is drawn with EMF+ records, which aren't read yet: nothing was imported".into()); - } let children = nest(&mut self.doc, out); let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); if let Some(c) = layer.children_mut() { @@ -904,33 +454,7 @@ fn crop(img: Rgba, src: Rect) -> Rgba { Rgba { width: x1 - x0, height: y1 - y0, pixels } } -/// Read a metafile. +/// Read an EMF or WMF file. pub(crate) fn import(bytes: &[u8]) -> Result { - match crate::sniff(bytes) { - Some(Kind::Emf) => emf::play(bytes), - Some(Kind::Wmf) => wmf::play(bytes), - None => Err("not an EMF or WMF file".into()), - } -} - -#[cfg(test)] -mod table_tests { - use super::*; - - /// Once the WMF table is full, a rejected creation leaves the hint at its end, so the next - /// ones don't scan every slot again; a freed slot is still found. - #[test] - fn a_full_object_table_is_not_rescanned() { - let mut p = Player::new(Kind::Wmf, Affine::IDENTITY, 1.0, Rect::new(0.0, 0.0, 10.0, 10.0)); - for _ in 0..=u16::MAX as usize + 1 { - p.create(Obj::Other); - } - p.delete(5); - p.create(Obj::Other); - p.create(Obj::Other); - assert!(p.free_hint > u16::MAX as usize); - p.delete(7); - p.create(Obj::Other); - assert!(p.objects[7].is_some()); - } + picture::import(bytes) } diff --git a/crates/metafile/src/import/emf.rs b/crates/metafile/src/import/emf.rs deleted file mode 100644 index ece16c7864..0000000000 --- a/crates/metafile/src/import/emf.rs +++ /dev/null @@ -1,392 +0,0 @@ -//! EMF records (MS-EMF) played on a [`Player`]: the header gives the frame (the artboard) and the -//! reference device (device pixels → millimetres), then every record in turn until EMR_EOF. - -use vectorcraft_geom::{Affine, Point, Rect}; - -use super::{ArcKind, BrushObj, FontObj, Obj, PenObj, Player}; -use crate::bytes::{Reader, slice}; -use crate::dib::{self, Alpha}; -use crate::{Imported, Kind}; - -/// Points per millimetre. -const PT_PER_MM: f64 = 72.0 / 25.4; -/// Most points one record may give (a hostile count can't make a huge allocation). -const MAX_POINTS: usize = 1 << 22; -/// Records that change nothing VectorCraft keeps (background mode and colour, raster modes, -/// palettes, colour management, comments…). -const IGNORED: &[u32] = - &[1, 13, 15, 16, 18, 20, 21, 23, 25, 28, 48, 50, 51, 52, 65, 66, 70, 98, 100, 101, 104, 110, 111, 112, 113, 115, 119, 120, 121]; - -fn rect(r: &mut Reader) -> Option { - Some(Rect::new(f64::from(r.i32()?), f64::from(r.i32()?), f64::from(r.i32()?), f64::from(r.i32()?))) -} - -fn point32(r: &mut Reader) -> Option { - Some(Point::new(f64::from(r.i32()?), f64::from(r.i32()?))) -} - -fn point16(r: &mut Reader) -> Option { - Some(Point::new(f64::from(r.i16()?), f64::from(r.i16()?))) -} - -fn color(r: &mut Reader) -> Option<[u8; 3]> { - let [red, g, b, _] = r.u32()?.to_le_bytes(); - Some([red, g, b]) -} - -fn xform(r: &mut Reader) -> Option { - let mut v = [0.0; 6]; - for x in &mut v { - *x = f64::from(r.f32()?); - } - Some(Affine::new(v)) -} - -/// `n` points (32-bit or 16-bit), `None` when the record is shorter. -fn points(r: &mut Reader, n: u32, wide: bool) -> Option> { - let n = n as usize; - if n > MAX_POINTS || r.rest().len() < n * if wide { 8 } else { 4 } { - return None; - } - (0..n).map(|_| if wide { point32(r) } else { point16(r) }).collect() -} - -/// The polygons of a PolyPolygon / PolyPolyline record. -fn polys(r: &mut Reader, wide: bool) -> Option>> { - r.skip(16)?; - let n = r.u32()? as usize; - let total = r.u32()?; - if n > MAX_POINTS || r.rest().len() < n * 4 { - return None; - } - let counts: Vec = (0..n).map(|_| r.u32()).collect::>()?; - let mut all = points(r, total, wide)?.into_iter(); - Some(counts.iter().map(|c| all.by_ref().take(*c as usize).collect()).collect()) -} - -/// A LOGFONTW → the font. -fn font(r: &mut Reader) -> Option { - let height = f64::from(r.i32()?); - r.skip(4)?; - let escapement = f64::from(r.i32()?); - r.skip(4)?; - let weight = r.i32()?; - let italic = r.bytes(1)?.first().is_some_and(|b| *b != 0); - r.skip(7)?; - let units: Vec = (0..32).map_while(|_| r.u16()).take_while(|c| *c != 0).collect(); - Some(FontObj { height, escapement, weight, italic, face: String::from_utf16_lossy(&units) }) -} - -/// The bitmap of an image record: its BITMAPINFO and bits at the offsets the record gives. -fn bitmap(rec: &[u8], off_bmi: u32, cb_bmi: u32, off_bits: u32, cb_bits: u32, alpha: Alpha, left: &mut u64) -> Result { - let bmi = slice(rec, off_bmi, cb_bmi).ok_or("damaged")?; - let bits = slice(rec, off_bits, cb_bits).ok_or("damaged")?; - dib::decode(bmi, bits, alpha, left) -} - -/// The rows a DIB's source rectangle counts from the bottom in (StretchDIBits on a bottom-up DIB). -fn bottom_up(rec: &[u8], off_bmi: u32) -> bool { - let at = off_bmi as usize; - let size = rec.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); - let height = rec.get(at + 8..at + 12).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes); - size.is_some_and(|s| s >= 40) && height.is_some_and(|h| h > 0) -} - -/// The source rectangle `(x, y, w, h)` of an image of `img`'s height, counted from the top. -fn source(x: i32, y: i32, w: i32, h: i32, img: &Result, from_bottom: bool) -> Rect { - let ih = img.as_ref().map_or(0.0, |i| f64::from(i.height)); - let (x, y, w, h) = (f64::from(x), f64::from(y), f64::from(w), f64::from(h)); - let top = if from_bottom { ih - y - h } else { y }; - Rect::new(x, top, x + w, top + h) -} - -/// The size and placement of the picture: (device → document, millimetres a pixel, the artboard). -fn frame(bytes: &[u8]) -> Option<(Affine, f64, Rect)> { - let mut r = Reader::new(bytes); - r.skip(4)?; - let header_size = r.u32()?; - let bounds = rect(&mut r)?; - let frame = rect(&mut r)?; - // Signature, version, bytes, records, handles, description and palette size. - r.skip(32)?; - let device = (f64::from(r.i32()?), f64::from(r.i32()?)); - let mm = (f64::from(r.i32()?), f64::from(r.i32()?)); - // The device in micrometres (more precise), when the header has it. - let micro = if header_size >= 108 { - r.skip(12)?; - Some((f64::from(r.u32()?), f64::from(r.u32()?))) - } else { - None - }; - let ok = |v: f64| v.is_finite() && v > 0.0; - let mm_per_px = match micro { - Some((mx, _)) if ok(mx) && ok(device.0) => mx / 1000.0 / device.0, - _ if ok(mm.0) && ok(device.0) => mm.0 / device.0, - _ => 25.4 / 96.0, - }; - let mm_per_px = if mm_per_px.is_finite() && mm_per_px > 1e-9 { mm_per_px } else { 25.4 / 96.0 }; - let k = mm_per_px * PT_PER_MM; - // The frame (0.01 mm) in device pixels; an empty frame falls back to the bounds. - let f = frame.abs(); - let (origin, size) = if f.width() > 0.0 && f.height() > 0.0 { - (Point::new(f.x0 / 100.0 / mm_per_px, f.y0 / 100.0 / mm_per_px), (f.width() / 100.0 * PT_PER_MM, f.height() / 100.0 * PT_PER_MM)) - } else { - let b = bounds.abs(); - (b.origin(), ((b.width() + 1.0) * k, (b.height() + 1.0) * k)) - }; - let dev_to_doc = Affine::scale(k) * Affine::translate(-origin.to_vec2()); - let side = |v: f64| if v.is_finite() { v.clamp(1.0, 1e6) } else { 1.0 }; - Some((dev_to_doc, mm_per_px, Rect::new(0.0, 0.0, side(size.0), side(size.1)))) -} - -pub(super) fn play(bytes: &[u8]) -> Result { - let (dev_to_doc, mm_per_px, artboard) = frame(bytes).ok_or("the EMF header is damaged")?; - let mut p = Player::new(Kind::Emf, dev_to_doc, mm_per_px, artboard); - let mut at = 0usize; - let mut ended = false; - while let Some(head) = bytes.get(at..at + 8) { - let kind = u32::from_le_bytes([head[0], head[1], head[2], head[3]]); - let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize; - let Some(rec) = bytes.get(at..at.saturating_add(size)).filter(|_| size >= 8) else { break }; - if kind == 14 { - ended = true; - break; - } - if !matches!(kind, 27 | 54 | 5 | 6 | 88 | 89) { - p.flush(); - } - if record(&mut p, kind, rec).is_none() { - p.skip(); - } - at += size; - } - if !ended { - p.warn("the file ends early: what it held was imported"); - } - Ok(p.finish()) -} - -/// PolyBezier, Polygon, Polyline, PolyBezierTo, PolylineTo and their 16-bit forms. -fn rec_poly(p: &mut Player, kind: u32, r: &mut Reader) -> Option<()> { - let wide = kind < 85; - r.skip(16)?; - let n = r.u32()?; - let pts = points(r, n, wide)?; - match if wide { kind } else { kind - 83 } { - 2 => p.poly(&pts, false, true), - 3 => p.poly(&pts, true, false), - 4 => p.poly(&pts, false, false), - 5 => p.poly_to(&pts, true), - _ => p.poly_to(&pts, false), - } - Some(()) -} - -/// CreatePen (38). -fn rec_create_pen(p: &mut Player, r: &mut Reader) -> Option<()> { - let ih = r.u32()?; - let style = r.u32()?; - let width = f64::from(r.i32()?); - r.skip(4)?; - p.create_at(ih, Obj::Pen(PenObj { style, width, color: color(r)?, entries: vec![] })); - Some(()) -} - -/// ExtCreatePen (95). -fn rec_ext_create_pen(p: &mut Player, r: &mut Reader) -> Option<()> { - let ih = r.u32()?; - r.skip(16)?; - let style = r.u32()?; - let width = f64::from(r.u32()?); - let brush = r.u32()?; - let c = color(r)?; - r.skip(4)?; - let n = (r.u32()? as usize).min(64); - let entries: Vec = (0..n).map_while(|_| r.u32()).map(f64::from).collect(); - // A pen painted with the null brush draws nothing. - let style = if brush == 1 { super::PS_NULL } else { style }; - p.create_at(ih, Obj::Pen(PenObj { style, width, color: c, entries })); - Some(()) -} - -/// GdiComment (70): EMF+ records ride in comments starting "EMF+". -fn rec_comment(p: &mut Player, r: &mut Reader) -> Option<()> { - r.skip(4)?; - p.emf_plus |= r.u32()? == 0x2B46_4D45; - Some(()) -} - -/// ExtSelectClipRgn (75). -fn rec_clip_region(p: &mut Player, r: &mut Reader) -> Option<()> { - let cb = r.u32()?; - let mode = r.u32()?; - let data = r.bytes(cb as usize)?; - let mut d = Reader::new(data); - let rects = if cb >= 32 { - d.skip(8)?; - let n = d.u32()? as usize; - d.skip(20)?; - if n > MAX_POINTS || d.rest().len() < n * 16 { - return None; - } - (0..n).map(|_| rect(&mut d)).collect::>>()? - } else { - vec![] - }; - p.clip_region(&rects, mode); - Some(()) -} - -/// The rectangle at `(x, y)` of size `(w, h)`. -fn at_size(x: i32, y: i32, w: i32, h: i32) -> Rect { - Rect::new(f64::from(x), f64::from(y), f64::from(x) + f64::from(w), f64::from(y) + f64::from(h)) -} - -/// BitBlt (76) and StretchBlt (77). -fn rec_blt(p: &mut Player, kind: u32, rec: &[u8], r: &mut Reader) -> Option<()> { - r.skip(16)?; - let dest = (r.i32()?, r.i32()?, r.i32()?, r.i32()?); - let rop = r.u32()?; - let (xs, ys) = (r.i32()?, r.i32()?); - r.skip(24 + 4 + 4)?; - let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?); - let (ws, hs) = if kind == 77 { (r.i32()?, r.i32()?) } else { (dest.2, dest.3) }; - let d = at_size(dest.0, dest.1, dest.2, dest.3); - if cb_bmi == 0 { - p.pattern_blit(d, rop); - } else { - let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, Alpha::Ignore, &mut p.pixels_left); - let src = source(xs, ys, ws, hs, &img, false); - p.image(img, src, d, rop, 1.0); - } - Some(()) -} - -/// StretchDIBits (81). -fn rec_stretch_dibits(p: &mut Player, rec: &[u8], r: &mut Reader) -> Option<()> { - r.skip(16)?; - let (xd, yd, xs, ys, ws, hs) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?, r.i32()?, r.i32()?); - let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?); - r.skip(4)?; - let rop = r.u32()?; - let (wd, hd) = (r.i32()?, r.i32()?); - let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, Alpha::Ignore, &mut p.pixels_left); - let src = source(xs, ys, ws, hs, &img, bottom_up(rec, off_bmi)); - p.image(img, src, at_size(xd, yd, wd, hd), rop, 1.0); - Some(()) -} - -/// AlphaBlend (114). -fn rec_alpha_blend(p: &mut Player, rec: &[u8], r: &mut Reader) -> Option<()> { - r.skip(16)?; - let (xd, yd, wd, hd) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?); - let blend = r.bytes(4)?; - let (constant, per_pixel) = (blend.get(2).copied().unwrap_or(255), blend.get(3).is_some_and(|f| *f & 1 != 0)); - let (xs, ys) = (r.i32()?, r.i32()?); - r.skip(24 + 4 + 4)?; - let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?); - let (ws, hs) = (r.i32()?, r.i32()?); - let alpha = if per_pixel { Alpha::Premultiplied } else { Alpha::Ignore }; - let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, alpha, &mut p.pixels_left); - let src = source(xs, ys, ws, hs, &img, false); - p.image(img, src, at_size(xd, yd, wd, hd), crate::import::SRCCOPY, f64::from(constant) / 255.0); - Some(()) -} - -/// ExtTextOutA (83) and ExtTextOutW (84). -fn rec_text(p: &mut Player, kind: u32, rec: &[u8], r: &mut Reader) -> Option<()> { - r.skip(16 + 4 + 8)?; - let at = point32(r)?; - let n = r.u32()? as usize; - let off = r.u32()?; - let s = if kind == 84 { - let raw = slice(rec, off, u32::try_from(n.checked_mul(2)?).ok()?)?; - String::from_utf16_lossy(&raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect::>()) - } else { - slice(rec, off, u32::try_from(n).ok()?)?.iter().map(|b| char::from(*b)).collect() - }; - p.text(at, &s); - Some(()) -} - -/// Play one record (`rec`: all of it, with its type and size). `None`: unknown or damaged. -fn record(p: &mut Player, kind: u32, rec: &[u8]) -> Option<()> { - let mut r = Reader::new(rec.get(8..)?); - match kind { - 2..=6 | 85..=89 => rec_poly(p, kind, &mut r)?, - 7 | 90 => p.poly_poly(&polys(&mut r, kind == 7)?, false), - 8 | 91 => p.poly_poly(&polys(&mut r, kind == 8)?, true), - 9 => p.set_window_ext(f64::from(r.i32()?), f64::from(r.i32()?)), - 10 => p.set_window_org(f64::from(r.i32()?), f64::from(r.i32()?)), - 11 => p.set_viewport_ext(f64::from(r.i32()?), f64::from(r.i32()?)), - 12 => p.set_viewport_org(f64::from(r.i32()?), f64::from(r.i32()?)), - 17 => p.set_map_mode(r.u32()?), - 19 => p.set_fill_mode(r.u32()? == 1), - 22 => p.set_text_align(r.u32()?), - 24 => p.set_text_color(color(&mut r)?), - 27 => p.move_to(point32(&mut r)?), - 29 => p.exclude_clip(), - 30 => p.clip_rect(rect(&mut r)?), - 31 | 32 => { - let (xn, xd, yn, yd) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?); - p.scale_ext(kind == 32, (f64::from(xn), f64::from(xd)), (f64::from(yn), f64::from(yd))); - } - 33 => p.save(), - 34 => p.restore(r.i32()?), - 35 => p.world(xform(&mut r)?, 4), - 36 => { - let x = xform(&mut r)?; - p.world(x, r.u32()?); - } - 37 => p.select(r.u32()?), - 38 => rec_create_pen(p, &mut r)?, - 39 => { - let ih = r.u32()?; - let style = r.u32()?; - p.create_at(ih, Obj::Brush(BrushObj::from_log(style, color(&mut r)?))); - } - 40 => p.delete(r.u32()?), - 42 => p.figure(vectorcraft_geom::shapes::ellipse(rect(&mut r)?.abs()).to_bezpath(), true), - 43 => p.figure(vectorcraft_geom::shapes::rectangle(rect(&mut r)?.abs()).to_bezpath(), true), - 44 => { - let b = rect(&mut r)?; - let (cx, cy) = (f64::from(r.i32()?), f64::from(r.i32()?)); - p.figure(super::round_rect(b, cx, cy), true); - } - 45..=47 => { - let b = rect(&mut r)?; - let (s, e) = (point32(&mut r)?, point32(&mut r)?); - p.arc(b, s, e, [ArcKind::Open, ArcKind::Chord, ArcKind::Pie][(kind - 45) as usize]); - } - 49 | 99 | 122 => p.create_at(r.u32()?, Obj::Other), - 54 => { - let pt = point32(&mut r)?; - p.poly_to(&[pt], false); - } - 57 => p.set_arc_ccw(r.u32()? != 2), - 58 => p.set_miter(f64::from(r.u32()?)), - 59 => p.begin_path(), - 60 => p.end_path(), - 61 => p.close_figure(), - 62 => p.paint_path(true, false), - 63 => p.paint_path(true, true), - 64 => p.paint_path(false, true), - 67 => p.clip_path(r.u32()?), - 68 => p.abort_path(), - 70 => rec_comment(p, &mut r)?, - 75 => rec_clip_region(p, &mut r)?, - 76 | 77 => rec_blt(p, kind, rec, &mut r)?, - 81 => rec_stretch_dibits(p, rec, &mut r)?, - 82 => { - let ih = r.u32()?; - p.create_at(ih, Obj::Font(font(&mut r)?)); - } - 83 | 84 => rec_text(p, kind, rec, &mut r)?, - 93 | 94 => p.create_at(r.u32()?, Obj::Brush(BrushObj::Pattern)), - 95 => rec_ext_create_pen(p, &mut r)?, - 114 => rec_alpha_blend(p, rec, &mut r)?, - k if IGNORED.contains(&k) => {} - _ => return None, - } - Some(()) -} diff --git a/crates/metafile/src/import/pict.rs b/crates/metafile/src/import/pict.rs index a9b4cae9da..f6abbc6b83 100644 --- a/crates/metafile/src/import/pict.rs +++ b/crates/metafile/src/import/pict.rs @@ -24,7 +24,7 @@ use std::io::Cursor; use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect, Shape, Vec2, shapes}; -use super::{BAD_IMAGE, BrushObj, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect}; +use super::{BAD_IMAGE, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect}; use crate::dib::{self, Rgba}; use crate::{Imported, Kind}; @@ -600,7 +600,7 @@ impl Pict { let base = Affine::translate(-frame.origin().to_vec2()); let artboard = Rect::new(0.0, 0.0, frame.width(), frame.height()); // A picture's coordinates map straight onto the document, as a WMF's do. - let p = Player::new(Kind::Wmf, base, 25.4 / 72.0, artboard); + let p = Player::new(Kind::Wmf, base, artboard); Self { p, frame, @@ -783,7 +783,7 @@ impl Pict { /// Fill `bp` (picture space) with `color`. fn fill(&mut self, mut bp: BezPath, color: [u8; 3], rule: FillRule) { bp.apply_affine(self.p.xf()); - self.p.dc.brush = BrushObj::Solid(color); + self.p.dc.brush = color; self.p.dc.fill_rule = rule; self.p.draw(bp, true, false); } diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs new file mode 100644 index 0000000000..03a2e5628e --- /dev/null +++ b/crates/metafile/src/import/picture.rs @@ -0,0 +1,658 @@ +//! EMF (with or without EMF+ records) and WMF files: `craft_metafile` plays the records into a +//! picture, and the picture's items become document objects here. +//! +//! - A filled or stroked path becomes a path with a fill and a stroke (caps, joins, miter limit +//! and dashes from the pen). Opaque solid strokes with round caps and round joins drawn one after +//! another, each starting where the last one ended, with the same pen and clip, join into one +//! path. Other strokes stay apart, each with its own caps and its own dashes. +//! - A path filled with a pattern or hatched brush is filled with the average color of the +//! brush's tile. +//! - A bitmap becomes an image (its pixels as PNG) placed where the picture draws it, turned or +//! skewed with it. +//! - Text becomes point type in the font the file names, underlined or struck through as the font +//! is, and clipped to its rectangle when the file clips it. +//! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around +//! the whole picture clips nothing and is left out. +//! +//! A WMF without a placeable header is read at 1440 units an inch, and one whose placeable box is +//! empty or inverted at the units an inch the header gives. Either one that draws in a metric map +//! mode (MM_LOMETRIC to MM_TWIPS) is read at 96 pixels an inch, as `craft_metafile` plays those +//! modes. An EMF without a usable frame is read at its device's pixels a millimetre (96 +//! pixels an inch when the header doesn't say). + +use std::collections::HashMap; +use std::sync::{Arc, Weak}; + +use craft_metafile::{Cap, ClipPath, HAlign, Item, Join, LineStyle, Seg, VAlign}; +use vectorcraft_color::Paint; +use vectorcraft_doc::clipnest::{Clip, Drawn, MAX_NEST, deep_clips, nest}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeId, + NodeKind, StrokeLayer, TextObject, +}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes}; + +use super::{BAD_IMAGE, FAR_AWAY, HAIRLINE, LIMIT, MAX_NODES, around, rgb, sane}; +use crate::dib::Rgba; +use crate::wmf::PLACEABLE_KEY; +use crate::{Imported, Kind}; + +const PATTERNS: &str = "hatched and pattern brushes are filled with their average color"; +const ENDS_EARLY: &str = "the file ends early: what it held was imported"; +const TOO_MANY: &str = "objects past the most one file may hold were left out"; +const AT_LIMIT: &str = "the file reached the most objects one file may hold: any after them were not read"; + +/// The most items `craft_metafile` keeps from one file (its `MAX_ITEMS`). It stops reading at the +/// limit and does not say whether more items followed, so a picture holding this many may have +/// been cut short. +const READER_ITEMS: usize = 200_000; + +/// Points a unit of a WMF without a placeable header (1440 units an inch). +const WMF_UNIT: f64 = 72.0 / 1440.0; +/// The SAVEDC levels `craft_metafile` keeps; it stops reading at a SAVEDC past them. +const SAVED_LEVELS: usize = 1024; +/// Points a pixel at 96 pixels an inch. +const PT_PER_PX: f64 = 72.0 / 96.0; +/// Points a millimetre. +const PT_PER_MM: f64 = 72.0 / 25.4; + +/// WMF records that draw lines and shapes, which `craft_metafile` plays only when the mix mode +/// lets them draw. +const WMF_SHAPES: [u16; 10] = [0x0213, 0x0324, 0x0325, 0x0418, 0x041B, 0x0538, 0x061C, 0x0817, 0x081A, 0x0830]; +/// WMF records that draw text and bitmaps, which `craft_metafile` plays whatever the mix mode. +const WMF_DRAWS: [u16; 5] = [0x0521, 0x0940, 0x0A32, 0x0B41, 0x0F43]; +/// SETROP2 mix modes under which `craft_metafile` draws no lines, shapes or brush fills: R2_XORPEN +/// and R2_NOP. +const WMF_MIX_SKIPS: [u16; 2] = [7, 11]; +/// The mix mode a WMF starts in (R2_COPYPEN). +const WMF_MIX_START: u16 = 13; +/// PATBLT raster operations `craft_metafile` draws: PATCOPY (with the brush, as the mix mode +/// allows), BLACKNESS and WHITENESS. +const PATCOPY: u32 = 0x00F0_0021; +const BLACKNESS: u32 = 0x0000_0042; +const WHITENESS: u32 = 0x00FF_0062; + +/// Does a WMF draw in a metric map mode (MM_LOMETRIC to MM_TWIPS)? `craft_metafile` plays those +/// at 96 pixels an inch, whatever the window. The mode that more drawing records are played in +/// decides, counting only records the reader draws (not lines and shapes under R2_NOP or +/// R2_XORPEN, nor a PATBLT it does not fill); a file that draws nothing goes by its last mode. +/// `start` is where the standard header begins. +fn wmf_metric(bytes: &[u8], start: usize) -> bool { + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let Some(words) = start.checked_add(2).and_then(u16_at) else { return false }; + let mut at = start.saturating_add(usize::from(words) * 2); + let mut mode = 1; + let mut mix = WMF_MIX_START; + let metric = |mode: u16| (2..=6).contains(&mode); + // Drawing records played in a metric mode, and in any other. + let (mut in_metric, mut in_other) = (0usize, 0usize); + // The map and mix modes SAVEDC kept, which RESTOREDC brings back as the reader does. + let mut saved: Vec<(u16, u16)> = Vec::new(); + // The records as the reader walks them: it stops at the end record, a record shorter than its + // header, one that runs past the file and a SAVEDC past its 1,024 levels. + while let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) { + let size = (words as usize).saturating_mul(2); + let Some(next) = at.checked_add(size) else { break }; + if function == 0 || size < 6 || next > bytes.len() { + break; + } + match function { + // SETMAPMODE, when the record holds its mode. + 0x0103 if size >= 8 => mode = u16_at(at + 6).unwrap_or(mode), + // SETROP2, when the record holds its mix mode. + 0x0104 if size >= 8 => mix = u16_at(at + 6).unwrap_or(mix), + // SAVEDC. + 0x001E => { + if saved.len() >= SAVED_LEVELS { + break; + } + saved.push((mode, mix)); + } + // RESTOREDC: a negative count pops that many levels, a positive one goes back to that + // level. One that names no saved level changes nothing. + 0x0127 if size >= 8 => { + let n = u16_at(at + 6).map_or(0, |v| i32::from(i16::from_le_bytes(v.to_le_bytes()))); + let level = if n < 0 { saved.len().checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1) }; + if let Some(level) = level + && let Some((m, x)) = saved.get(level).copied() + { + mode = m; + mix = x; + saved.truncate(level); + } + } + f => { + let draws = match f { + _ if WMF_DRAWS.contains(&f) => true, + _ if WMF_SHAPES.contains(&f) => !WMF_MIX_SKIPS.contains(&mix), + // PATBLT: its raster operation, when the record holds one. + 0x061D => match u32_at(at + 6).filter(|_| size >= 10) { + Some(PATCOPY) => !WMF_MIX_SKIPS.contains(&mix), + Some(rop) => rop == BLACKNESS || rop == WHITENESS, + None => false, + }, + _ => false, + }; + if draws && metric(mode) { + in_metric += 1; + } else if draws { + in_other += 1; + } + } + } + at = next; + } + if in_metric == in_other { metric(mode) } else { in_metric > in_other } +} + +/// Points a picture unit across and down. `craft_metafile` gives a placeable WMF with a box and an +/// EMF with a frame in points, and other files in their logical units (WMF; pixels in a metric map +/// mode) or device units (EMF). +fn unit(bytes: &[u8], kind: Kind) -> (f64, f64) { + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let i16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| i16::from_le_bytes([b[0], b[1]])); + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let i32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let positive = |v: Option| v.filter(|v| *v > 0).map(f64::from); + match kind { + Kind::Wmf => { + let placeable = bytes.get(..4) == Some(&PLACEABLE_KEY.to_le_bytes()[..]); + if placeable + && let (Some(l), Some(t), Some(r), Some(b)) = (i16_at(6), i16_at(8), i16_at(10), i16_at(12)) + && r > l + && b > t + { + return (1.0, 1.0); + } + if wmf_metric(bytes, if placeable { 22 } else { 0 }) { + return (PT_PER_PX, PT_PER_PX); + } + if !placeable { + return (WMF_UNIT, WMF_UNIT); + } + let k = 72.0 / u16_at(14).filter(|v| *v > 0).map_or(1440.0, f64::from); + (k, k) + } + Kind::Emf => { + // Device pixels a millimetre on each axis: szlDevice over szlMicrometers when the header + // has them, else over szlMillimeters (both sizes must be positive). + let device = positive(i32_at(72)).zip(positive(i32_at(76))); + let micro = (u32_at(4).is_some_and(|s| s >= 108)) + .then(|| u32_at(100).zip(u32_at(104)).filter(|(w, h)| *w > 0 && *h > 0).map(|(w, h)| (f64::from(w) / 1000.0, f64::from(h) / 1000.0))) + .flatten(); + let mm = micro.or_else(|| positive(i32_at(80)).zip(positive(i32_at(84)))); + let px_mm = device.zip(mm).map(|((w, h), (mw, mh))| (w / mw, h / mh)); + let frame = matches!((i32_at(24), i32_at(28), i32_at(32), i32_at(36)), (Some(l), Some(t), Some(r), Some(b)) if r > l && b > t); + let ok = |v: f64| v.is_finite() && v > 0.0; + match px_mm { + Some(_) if frame => (1.0, 1.0), + Some((x, y)) if ok(x) && ok(y) => (PT_PER_MM / x, PT_PER_MM / y), + _ => (PT_PER_PX, PT_PER_PX), + } + } + } +} + +/// What a stroke is drawn with, to tell whether two strokes join into one path. +#[derive(Clone, PartialEq)] +struct Pen { + color: [u8; 4], + width: f32, + line: LineStyle, + even_odd: bool, + chain: Vec, +} + +/// Strokes drawn one after another, not added yet: their pen, clips and path (document space). +struct Pending { + pen: Pen, + clips: Vec>, + path: BezPath, +} + +/// Clip paths already made, by address (the `Arc` keeps the address from being reused); None for +/// one that clips nothing in the picture. +type MadeClips = HashMap<*const ClipPath, (Arc, Option>)>; +/// The last clip region and the clip made for it. +type MadeRegion = (Vec<[f32; 4]>, Option>); +/// Brush tiles already averaged, by address: items filled with the same brush share its tile. The +/// `Weak` keeps the address from being reused, and the tile's pixels are freed once the last item +/// that uses it has been read. +type Averaged = HashMap<*const craft_metafile::Tile, (Weak, Option<[u8; 4]>)>; + +struct Mapper { + /// Picture units → points. + xf: Affine, + /// How much lengths (stroke widths, dashes) grow from the picture to points. + k: f64, + frame: Rect, + doc: Document, + out: Drawn, + warnings: Vec, + next_clip: u32, + paths: MadeClips, + region: Option, + pending: Option, + averaged: Averaged, +} + +fn color(c: [u8; 4]) -> Paint { + rgb([c[0], c[1], c[2]]) +} + +/// The average color of a tile's pixels, weighted by their alpha, and their average alpha; None +/// for a clear tile. +fn average(rgba: &[u8]) -> Option<[u8; 4]> { + let pixels = rgba.as_chunks::<4>().0; + let mut sum = [0u64; 4]; + for p in pixels { + let a = u64::from(p[3]); + sum[0] += u64::from(p[0]) * a; + sum[1] += u64::from(p[1]) * a; + sum[2] += u64::from(p[2]) * a; + sum[3] += a; + } + let a = sum[3]; + let alpha = (a / pixels.len().max(1) as u64) as u8; + (a > 0).then(|| [(sum[0] / a) as u8, (sum[1] / a) as u8, (sum[2] / a) as u8, alpha.max(1)]) +} + +impl Mapper { + fn new(width: f64, height: f64, (kx, ky): (f64, f64)) -> Self { + let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 }; + let (w, h) = (side(width * kx), side(height * ky)); + let mut doc = Document::new(w, h); + doc.layers.clear(); + Self { + xf: Affine::scale_non_uniform(kx, ky), + // The mean of the two, as the reader scales stroke lengths. + k: (kx + ky) / 2.0, + frame: Rect::new(0.0, 0.0, w, h), + doc, + out: vec![], + warnings: vec![], + next_clip: 0, + paths: HashMap::new(), + region: None, + pending: None, + averaged: HashMap::new(), + } + } + + fn warn(&mut self, w: &str) { + if !self.warnings.iter().any(|x| x == w) { + self.warnings.push(w.to_string()); + } + } + + fn path(&self, segs: &[Seg]) -> BezPath { + let mut bp = craft_metafile::bez_path(segs); + bp.apply_affine(self.xf); + bp + } + + /// A clip of `path` (document space), or None when it clips nothing in the picture. + fn clip(&mut self, path: BezPath, rule: FillRule) -> Option> { + if around(&path, self.frame) { + return None; + } + self.next_clip += 1; + Some(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) })) + } + + /// The clips an item is drawn under, outermost first; None when it shows nowhere. + fn chain(&mut self, region: Option>, clips: &[Arc]) -> Option>> { + let mut chain = vec![]; + if let Some(rects) = region { + if rects.is_empty() { + return None; + } + let made = match &self.region { + Some((last, made)) if *last == rects => made.clone(), + _ => { + let mut bp = BezPath::new(); + for [x0, y0, x1, y1] in &rects { + bp.extend(shapes::rectangle(Rect::new(f64::from(*x0), f64::from(*y0), f64::from(*x1), f64::from(*y1))).to_bezpath()); + } + bp.apply_affine(self.xf); + if !sane(bp.bounding_box()) { + self.warn(FAR_AWAY); + return None; + } + let made = self.clip(bp, FillRule::NonZero); + self.region = Some((rects, made.clone())); + made + } + }; + chain.extend(made); + } + for c in clips { + let key = Arc::as_ptr(c); + let made = match self.paths.get(&key) { + Some((_, made)) => made.clone(), + None => { + let bp = self.path(&c.segs); + if !sane(bp.bounding_box()) { + self.warn(FAR_AWAY); + return None; + } + let made = self.clip(bp, if c.even_odd { FillRule::EvenOdd } else { FillRule::NonZero }); + self.paths.insert(key, (c.clone(), made.clone())); + made + } + }; + chain.extend(made); + } + if chain.len() > MAX_NEST { + chain.truncate(MAX_NEST); + self.warn(&deep_clips()); + } + Some(chain) + } + + fn push(&mut self, clips: Vec>, mut node: Node) { + if self.out.len() >= MAX_NODES { + return self.warn(TOO_MANY); + } + if !node.visual_bounds().is_none_or(sane) { + return self.warn(FAR_AWAY); + } + node.id = self.doc.alloc_id(); + self.out.push((clips, node)); + } + + /// Add the strokes waiting to be joined. + fn flush(&mut self) { + if let Some(p) = self.pending.take() { + let node = self.path_node(p.path, None, Some((p.pen.color, p.pen.width, &p.pen.line)), p.pen.even_odd); + if let Some(n) = node { + self.push(p.clips, n); + } + } + } + + fn stroke_layer(&self, c: [u8; 4], width: f32, line: &LineStyle) -> StrokeLayer { + let w = f64::from(width) * self.k; + let mut st = StrokeLayer::new(color(c), if w > 0.0 && w.is_finite() { w } else { HAIRLINE }); + st.opacity = f32::from(c[3]) / 255.0; + st.cap = match line.cap { + Cap::Round => LineCap::Round, + Cap::Square => LineCap::Square, + Cap::Flat => LineCap::Butt, + }; + st.join = match line.join { + Join::Round => LineJoin::Round, + Join::Bevel => LineJoin::Bevel, + Join::Miter => LineJoin::Miter, + }; + let miter = f64::from(line.miter_limit); + if miter.is_finite() && miter >= 1.0 { + st.miter_limit = miter; + } + let dash = Dash { pattern: line.dash.iter().map(|d| f64::from(*d) * self.k).collect(), offset: 0.0, align_corners: false }; + st.dash = dash.is_dashed().then_some(dash); + st + } + + /// A path node painted with `fill` and `stroke`; None when neither shows. + fn path_node(&self, bp: BezPath, fill: Option<[u8; 4]>, stroke: Option<([u8; 4], f32, &LineStyle)>, even_odd: bool) -> Option { + if bp.elements().is_empty() { + return None; + } + let mut items = vec![]; + if let Some(c) = fill.filter(|c| c[3] > 0) { + let mut f = FillLayer::new(color(c)); + f.opacity = f32::from(c[3]) / 255.0; + items.push(AppearanceItem::Fill(f)); + } + if let Some((c, w, line)) = stroke.filter(|s| s.0[3] > 0) { + items.push(AppearanceItem::Stroke(self.stroke_layer(c, w, line))); + } + if items.is_empty() { + return None; + } + let mut n = Node::path(NodeId(0), PathData::from_bezpath(&bp), Appearance { items, ..Appearance::default() }); + if let NodeKind::Path { rule, .. } = &mut n.kind { + *rule = if even_odd { FillRule::EvenOdd } else { FillRule::NonZero }; + } + Some(n) + } + + fn item(&mut self, item: Item) { + match item { + Item::Path { segs, fill, stroke, line, even_odd, region, clips } => { + let Some(chain) = self.chain(region, &clips) else { return self.flush() }; + let bp = self.path(&segs); + // An open stroke with nothing filled waits, to join the next one. + if let (None, Some((c, w))) = (fill, stroke) + && !segs.iter().any(|s| matches!(s, Seg::Close)) + { + // A stroke that reaches too far is left out here, before it joins the strokes + // waiting, so they are still added. + let half = f64::from(w) * self.k; + let half = if half > 0.0 && half.is_finite() { half / 2.0 } else { HAIRLINE / 2.0 }; + if !sane(bp.bounding_box().inflate(half, half)) { + self.flush(); + return self.warn(FAR_AWAY); + } + let pen = Pen { color: c, width: w, line, even_odd, chain: chain.iter().map(|c| c.id).collect() }; + let start = bp.elements().first().and_then(|e| match e { + PathEl::MoveTo(p) => Some(*p), + _ => None, + }); + // A translucent stroke stays apart, so where strokes overlap each one shows. So + // does a dashed one, whose dashes start at its own start, and one whose caps + // or joins aren't round: a join where two strokes meet is not their two caps. + if let Some(p) = &mut self.pending + && p.pen == pen + && pen.color[3] == u8::MAX + && pen.line.dash.is_empty() + && matches!((&pen.line.cap, &pen.line.join), (Cap::Round, Join::Round)) + && start.is_some() + && p.path.elements().last().and_then(|e| e.end_point()) == start + { + p.path.extend(bp.elements().iter().skip(1).copied()); + return; + } + self.flush(); + self.pending = Some(Pending { pen, clips: chain, path: bp }); + return; + } + self.flush(); + let stroke = stroke.map(|(c, w)| (c, w, &line)); + if let Some(n) = self.path_node(bp, fill, stroke, even_odd) { + self.push(chain, n); + } + } + Item::Pattern { segs, even_odd, tile, region, clips } => { + self.flush(); + let Some(chain) = self.chain(region, &clips) else { return }; + let Some(c) = self.averaged.entry(Arc::as_ptr(&tile)).or_insert_with(|| (Arc::downgrade(&tile), average(&tile.rgba))).1 else { + return; + }; + self.warn(PATTERNS); + let bp = self.path(&segs); + if let Some(n) = self.path_node(bp, Some(c), None, even_odd) { + self.push(chain, n); + } + } + Item::Bitmap { transform, width, height, rgba, region, clips, .. } => { + self.flush(); + let Some(chain) = self.chain(region, &clips) else { return }; + self.image(Rgba { width, height, pixels: rgba }, Affine::new(transform), chain); + } + Item::Text(t) => { + self.flush(); + let Some(mut chain) = self.chain(t.region.clone(), &t.clips) else { return }; + // The text's own clip rectangle, inside the others. + if let Some([x0, y0, x1, y1]) = t.clip { + let mut bp = shapes::rectangle(Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1)).abs()).to_bezpath(); + bp.apply_affine(self.xf); + if !sane(bp.bounding_box()) { + return self.warn(FAR_AWAY); + } + if let Some(own) = self.clip(bp, FillRule::NonZero) { + // Past the stack, the text's own clip takes the innermost place kept. + if chain.len() >= MAX_NEST { + chain.truncate(MAX_NEST.saturating_sub(1)); + self.warn(&deep_clips()); + } + chain.push(own); + } + } + self.text(&t, chain); + } + } + } + + /// An image whose unit square `unit` places in the picture. + fn image(&mut self, img: Rgba, unit: Affine, chain: Vec>) { + if img.width == 0 || img.height == 0 { + return; + } + let xf = self.xf * unit * Affine::scale_non_uniform(1.0 / f64::from(img.width), 1.0 / f64::from(img.height)); + if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + return; + } + let Ok(png) = img.to_png() else { return self.warn(BAD_IMAGE) }; + let blob = ImageBlob::new("image/png", png); + let key = blob.content_key(); + self.doc.images.entry(key.clone()).or_insert(blob); + let im = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None }; + self.push(chain, Node::new(NodeId(0), NodeKind::Image(Box::new(im)))); + } + + fn text(&mut self, t: &craft_metafile::Text, chain: Vec>) { + let s: String = t.text.chars().filter(|c| *c != '\0').collect(); + if s.trim().is_empty() || t.color[3] == 0 { + return; + } + // Text space → document without the move: its vertical scale gives the type size, and what + // is left of it (a turn, a stretch across) goes on the text object. + let [a, b, c, d, ..] = t.transform; + let linear = self.xf * Affine::new([a, b, c, d, 0.0, 0.0]); + let [_, _, c, d, ..] = linear.as_coeffs(); + let k = c.hypot(d); + let shape = if k > 1e-12 && k.is_finite() && linear.determinant().abs() > 1e-24 { Affine::scale(1.0 / k) * linear } else { Affine::IDENTITY }; + let f = &t.font; + let h = f64::from(f.height); + // A negative height is the em; a positive one the cell (the em and the internal leading). + let em = if h < 0.0 { -h } else { h * 0.85 }; + let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 }; + let mut style = CharStyle { size, fill: color(t.color), stroke: Paint::None, ..CharStyle::default() }; + if !f.family.trim().is_empty() { + style.font_family = f.family.trim().to_string(); + } + style.font_style = match (f.weight >= 600, f.italic) { + (true, true) => "Bold Italic", + (true, false) => "Bold", + (false, true) => "Italic", + (false, false) => "Regular", + } + .into(); + style.underline = f.underline; + style.strikethrough = f.strike; + // Where the baseline is below the reference point. + let drop = match t.v_align { + VAlign::Baseline => 0.0, + VAlign::Bottom => -0.2 * size, + VAlign::Top => 0.8 * size, + }; + let origin = self.xf * Point::new(t.transform[4], t.transform[5]); + let mut text = TextObject::point(Point::ZERO, &s, style); + text.xf = Affine::translate(origin.to_vec2()) * shape * Affine::translate((0.0, drop)); + text.para.justify = match t.h_align { + HAlign::Center => Justify::Center, + HAlign::Right => Justify::Right, + HAlign::Left => Justify::Left, + }; + text.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text).bounds); + let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text))); + n.opacity = f32::from(t.color[3]) / 255.0; + self.push(chain, n); + } + + /// The document: what was drawn on one layer, clipped art in clipping groups. + fn finish(mut self, kind: Kind, skipped: u32) -> Imported { + self.flush(); + if skipped > 0 { + let n = skipped; + self.warnings.push(format!( + "{n} record{} of kinds VectorCraft doesn't read {} skipped", + if n == 1 { "" } else { "s" }, + if n == 1 { "was" } else { "were" } + )); + } + let out = std::mem::take(&mut self.out); + let children = nest(&mut self.doc, out); + let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); + if let Some(c) = layer.children_mut() { + *c = children; + } + self.doc.layers = vec![Arc::new(layer)]; + Imported { document: self.doc, kind, warnings: self.warnings } + } +} + +/// Does the file stop before its end-of-file record? +fn ends_early(bytes: &[u8], kind: Kind) -> bool { + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let mut at = match kind { + Kind::Emf => 0, + Kind::Wmf => { + let start = if u32_at(0) == Some(PLACEABLE_KEY) { 22 } else { 0 }; + let Some(words) = u16_at(start + 2) else { return true }; + start + usize::from(words) * 2 + } + }; + loop { + let size = match kind { + Kind::Emf => { + let (Some(kind), Some(size)) = (u32_at(at), u32_at(at.saturating_add(4))) else { return true }; + if kind == 14 { + return false; + } + // Records are a multiple of 4 bytes long; reading stops at one that isn't. + if !size.is_multiple_of(4) { + return true; + } + size as usize + } + Kind::Wmf => { + let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) else { return true }; + if function == 0 { + return false; + } + (words as usize).saturating_mul(2) + } + }; + if size < 6 { + return true; + } + at = at.saturating_add(size); + } +} + +/// Read an EMF or WMF file. +pub(crate) fn import(bytes: &[u8]) -> Result { + let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?; + let pic = craft_metafile::parse(bytes).map_err(|e| match e { + craft_metafile::Error::NotMetafile => "not an EMF or WMF file".to_string(), + craft_metafile::Error::BadHeader => format!("the {} header is damaged", kind.id().to_uppercase()), + craft_metafile::Error::NoRecords => format!("the {} file holds no records", kind.id().to_uppercase()), + })?; + let k = unit(bytes, kind); + let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), k); + if ends_early(bytes, kind) { + m.warn(ENDS_EARLY); + } + if pic.items.len() >= READER_ITEMS { + m.warn(AT_LIMIT); + } + for item in pic.items { + m.item(item); + } + Ok(m.finish(kind, pic.skipped_records)) +} diff --git a/crates/metafile/src/import/wmf.rs b/crates/metafile/src/import/wmf.rs deleted file mode 100644 index 7a682e59a9..0000000000 --- a/crates/metafile/src/import/wmf.rs +++ /dev/null @@ -1,338 +0,0 @@ -//! WMF records (MS-WMF) played on a [`Player`]. A placeable header gives the picture's box in -//! logical units and the units an inch; without one, the first window origin and extent are the -//! box, at 1440 units an inch. - -use vectorcraft_geom::{Affine, Point, Rect, shapes}; - -use super::{ArcKind, BrushObj, FontObj, Obj, PenObj, Player}; -use crate::bytes::Reader; -use crate::dib::{self, Alpha}; -use crate::wmf::PLACEABLE_KEY; -use crate::{Imported, Kind}; - -/// Units an inch when the file doesn't say (twips). -const DEFAULT_INCH: f64 = 1440.0; -/// Records that change nothing VectorCraft keeps (background, raster and mapping details, palettes, -/// escapes). -const IGNORED: &[u16] = &[ - 0x0102, 0x0103, 0x0104, 0x0105, 0x0107, 0x0108, 0x0201, 0x020A, 0x020B, 0x020C, 0x020D, 0x020E, 0x020F, 0x0211, 0x0410, 0x0412, 0x0231, 0x0234, - 0x0035, 0x0037, 0x0139, 0x0436, 0x0626, -]; - -fn point(r: &mut Reader) -> Option { - Some(Point::new(f64::from(r.i16()?), f64::from(r.i16()?))) -} - -/// A point stored y first. -fn point_yx(r: &mut Reader) -> Option { - let y = f64::from(r.i16()?); - Some(Point::new(f64::from(r.i16()?), y)) -} - -/// A rectangle stored bottom, right, top, left. -fn rect_brtl(r: &mut Reader) -> Option { - let (b, rt, t, l) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - Some(Rect::new(f64::from(l), f64::from(t), f64::from(rt), f64::from(b))) -} - -fn color(r: &mut Reader) -> Option<[u8; 3]> { - let [red, g, b, _] = r.u32()?.to_le_bytes(); - Some([red, g, b]) -} - -fn points(r: &mut Reader, n: usize) -> Option> { - if r.rest().len() < n * 4 { - return None; - } - (0..n).map(|_| point(r)).collect() -} - -/// ANSI text (read as Latin-1). -fn ansi(b: &[u8]) -> String { - b.iter().map(|c| char::from(*c)).collect() -} - -/// The records' start, and the box and units an inch of a placeable header. -fn header(bytes: &[u8]) -> Option<(usize, Option<(Rect, f64)>)> { - let mut r = Reader::new(bytes); - let placeable = if r.u32()? == PLACEABLE_KEY { - r.skip(2)?; - let (l, t, rt, b) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - let inch = r.u16()?; - let inch = if inch == 0 { DEFAULT_INCH } else { f64::from(inch) }; - Some((Rect::new(f64::from(l), f64::from(t), f64::from(rt), f64::from(b)).abs(), inch)) - } else { - None - }; - let start = if placeable.is_some() { 22 } else { 0 }; - let mut h = Reader::new(bytes.get(start..)?); - h.skip(2)?; - let words = usize::from(h.u16()?); - if words < 9 { - return None; - } - Some((start + words * 2, placeable)) -} - -/// The first window origin and extent, as the picture's box when there is no placeable header. -fn window(bytes: &[u8], mut at: usize) -> Option { - let (mut org, mut ext) = (None, None); - while let Some(head) = bytes.get(at..at + 6) { - let words = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize; - let function = u16::from_le_bytes([head[4], head[5]]); - if words < 3 || function == 0 { - break; - } - let mut r = Reader::new(bytes.get(at + 6..).unwrap_or_default()); - match function { - 0x020B if org.is_none() => org = point_yx(&mut r), - 0x020C if ext.is_none() => ext = point_yx(&mut r), - _ => {} - } - if org.is_some() && ext.is_some() { - break; - } - at = at.saturating_add(words.saturating_mul(2)); - } - let o = org.unwrap_or(Point::ZERO); - let e = ext?; - Some(Rect::new(o.x, o.y, o.x + e.x, o.y + e.y).abs()) -} - -/// Logical → document for a placeable file whose window (`org`, `ext`) is mapped onto its box `b`; -/// a negative extent flips that axis, as in GDI. -fn window_map(b: Rect, k: f64, org: Point, ext: Point) -> Affine { - let ratio = |box_len: f64, e: f64| if e.abs() > 1e-12 { box_len / e } else { 1.0 }; - Affine::scale_non_uniform(k * ratio(b.width(), ext.x), k * ratio(b.height(), ext.y)) * Affine::translate(-org.to_vec2()) -} - -pub(super) fn play(bytes: &[u8]) -> Result { - let (start, placeable) = header(bytes).ok_or("the WMF header is damaged")?; - let (frame, inch) = match placeable { - Some((b, inch)) if b.width() > 0.0 && b.height() > 0.0 => (Some(b), inch), - _ => (window(bytes, start).filter(|w| w.width() > 0.0 && w.height() > 0.0), DEFAULT_INCH), - }; - let k = 72.0 / inch; - let origin = frame.map_or(Point::ZERO, |f| f.origin()); - let artboard = frame.map_or(Rect::new(0.0, 0.0, 1.0, 1.0), |f| Rect::new(0.0, 0.0, f.width() * k, f.height() * k)); - let mut p = Player::new(Kind::Wmf, Affine::scale(k) * Affine::translate(-origin.to_vec2()), 25.4 / inch, artboard); - // With a placeable header, the window records map the window onto the box. - let placed = placeable.map(|(b, _)| b).filter(|b| b.width() > 0.0 && b.height() > 0.0); - let mut win = (placed.map_or(Point::ZERO, |b| b.origin()), placed.map_or(Point::ZERO, |b| Point::new(b.width(), b.height()))); - let mut at = start; - let mut ended = false; - while let Some(head) = bytes.get(at..at + 6) { - let words = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize; - let function = u16::from_le_bytes([head[4], head[5]]); - if function == 0 { - ended = true; - break; - } - let Some(rec) = words.checked_mul(2).and_then(|n| bytes.get(at..at.checked_add(n)?)).filter(|_| words >= 3) else { break }; - if !matches!(function, 0x0213 | 0x0214) { - p.flush(); - } - if let (Some(b), 0x020B | 0x020C) = (placed, function) { - if let Some(v) = point_yx(&mut Reader::new(rec.get(6..).unwrap_or_default())) { - if function == 0x020B { - win.0 = v; - } else { - win.1 = v; - } - p.dev_to_doc = window_map(b, k, win.0, win.1); - } - } else if record(&mut p, function, rec.get(6..).unwrap_or_default()).is_none() { - p.skip(); - } - at += rec.len(); - } - if !ended { - p.warn("the file ends early: what it held was imported"); - } - let mut out = p.finish(); - // No box given: the art's bounds. - if frame.is_none() - && let Some(b) = out.document.layers.first().and_then(|l| vectorcraft_doc::live::nodes_bounds(l.children().map_or(&[][..], |c| c.as_slice()))) - && let Some(a) = out.document.artboards.first_mut() - { - a.rect = Rect::from_origin_size(b.origin(), (b.width().max(1.0), b.height().max(1.0))); - } - Ok(out) -} - -/// An image record's source rectangle (from the bottom for a bottom-up DIB) and destination. -fn blit(p: &mut Player, rop: u32, src: (i16, i16, i16, i16), dest: (i16, i16, i16, i16), packed: Option<&[u8]>) { - let (xd, yd, wd, hd) = (f64::from(dest.0), f64::from(dest.1), f64::from(dest.2), f64::from(dest.3)); - let d = Rect::new(xd, yd, xd + wd, yd + hd); - let Some(packed) = packed else { return p.pattern_blit(d, rop) }; - let parts = dib::split(packed); - let img = parts.ok_or_else(|| "damaged".to_string()).and_then(|(bmi, bits)| dib::decode(bmi, bits, Alpha::Ignore, &mut p.pixels_left)); - let bottom_up = parts.and_then(|(bmi, _)| bmi.get(8..12)).is_some_and(|h| i32::from_le_bytes([h[0], h[1], h[2], h[3]]) > 0); - let ih = img.as_ref().map_or(0.0, |i| f64::from(i.height)); - let (xs, ys, ws, hs) = (f64::from(src.0), f64::from(src.1), f64::from(src.2), f64::from(src.3)); - let top = if bottom_up { ih - ys - hs } else { ys }; - p.image(img, Rect::new(xs, top, xs + ws, top + hs), d, rop, 1.0); -} - -/// PolyPolygon (0x0538). -fn rec_poly_polygon(p: &mut Player, r: &mut Reader) -> Option<()> { - let n = usize::from(r.u16()?); - if r.rest().len() < n * 2 { - return None; - } - let counts: Vec = (0..n).map(|_| r.u16().map(usize::from)).collect::>()?; - let mut polys = Vec::with_capacity(n); - for c in counts { - polys.push(points(r, c)?); - } - p.poly_poly(&polys, true); - Some(()) -} - -/// Arc (0x0817), Pie (0x081A) and Chord (0x0830). -fn rec_arc(p: &mut Player, function: u16, r: &mut Reader) -> Option<()> { - let (end, start) = (point_yx(r)?, point_yx(r)?); - let b = rect_brtl(r)?; - let kind = match function { - 0x0817 => ArcKind::Open, - 0x081A => ArcKind::Pie, - _ => ArcKind::Chord, - }; - p.arc(b, start, end, kind); - Some(()) -} - -/// CreateFontIndirect (0x02FB). -fn rec_create_font(p: &mut Player, r: &mut Reader) -> Option<()> { - let height = f64::from(r.i16()?); - r.skip(2)?; - let escapement = f64::from(r.i16()?); - r.skip(2)?; - let weight = i32::from(r.i16()?); - let italic = r.bytes(1)?.first().is_some_and(|b| *b != 0); - r.skip(7)?; - let face: Vec = r.rest().iter().take(32).take_while(|b| **b != 0).copied().collect(); - p.create(Obj::Font(FontObj { height, escapement, weight, italic, face: ansi(&face) })); - Some(()) -} - -/// TextOut (0x0521). -fn rec_text_out(p: &mut Player, r: &mut Reader) -> Option<()> { - let n = usize::try_from(r.i16()?).ok()?; - let s = ansi(r.bytes(n)?); - r.skip(n % 2)?; - let at = point_yx(r)?; - p.text(at, &s); - Some(()) -} - -/// ExtTextOut (0x0A32). -fn rec_ext_text_out(p: &mut Player, r: &mut Reader) -> Option<()> { - let at = point_yx(r)?; - let n = usize::try_from(r.i16()?).ok()?; - let opts = r.u16()?; - // ETO_OPAQUE or ETO_CLIPPED: a rectangle comes first. - if opts & 0x6 != 0 { - r.skip(8)?; - } - let s = ansi(r.bytes(n)?); - p.text(at, &s); - Some(()) -} - -/// StretchDIB (0x0F43). -fn rec_stretch_dib(p: &mut Player, r: &mut Reader) -> Option<()> { - let rop = r.u32()?; - r.skip(2)?; - let (hs, ws, ys, xs) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - let (hd, wd, yd, xd) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - blit(p, rop, (xs, ys, ws, hs), (xd, yd, wd, hd), Some(r.rest())); - Some(()) -} - -/// StretchBlt (0x0B41). -fn rec_stretch_blt(p: &mut Player, body: &[u8], r: &mut Reader) -> Option<()> { - let rop = r.u32()?; - let (hs, ws, ys, xs) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - // Without a bitmap, a reserved word comes before the destination. - let with_bitmap = body.len() > 22; - if !with_bitmap { - r.skip(2)?; - } - let (hd, wd, yd, xd) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - blit(p, rop, (xs, ys, ws, hs), (xd, yd, wd, hd), with_bitmap.then(|| r.rest())); - Some(()) -} - -/// BitBlt (0x0940). -fn rec_bit_blt(p: &mut Player, body: &[u8], r: &mut Reader) -> Option<()> { - let rop = r.u32()?; - let (ys, xs) = (r.i16()?, r.i16()?); - let with_bitmap = body.len() > 20; - if !with_bitmap { - r.skip(2)?; - } - let (h, w, yd, xd) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - blit(p, rop, (xs, ys, w, h), (xd, yd, w, h), with_bitmap.then(|| r.rest())); - Some(()) -} - -/// Play one record (`r`: its parameters). `None`: unknown or damaged. -fn record(p: &mut Player, function: u16, body: &[u8]) -> Option<()> { - let mut r = Reader::new(body); - match function { - 0x001E => p.save(), - 0x0127 => p.restore(i32::from(r.i16()?)), - 0x0106 => p.set_fill_mode(r.u16()? == 1), - 0x0209 => p.set_text_color(color(&mut r)?), - 0x012E => p.set_text_align(u32::from(r.u16()?)), - 0x0214 => p.move_to(point_yx(&mut r)?), - 0x0213 => { - let pt = point_yx(&mut r)?; - p.poly_to(&[pt], false); - } - 0x0324 | 0x0325 => { - let n = usize::try_from(r.i16()?).ok()?; - let pts = points(&mut r, n)?; - p.poly(&pts, function == 0x0324, false); - } - 0x0538 => rec_poly_polygon(p, &mut r)?, - 0x041B => p.figure(shapes::rectangle(rect_brtl(&mut r)?.abs()).to_bezpath(), true), - 0x0418 => p.figure(shapes::ellipse(rect_brtl(&mut r)?.abs()).to_bezpath(), true), - 0x061C => { - let (h, w) = (f64::from(r.i16()?), f64::from(r.i16()?)); - p.figure(super::round_rect(rect_brtl(&mut r)?, w, h), true); - } - 0x0817 | 0x081A | 0x0830 => rec_arc(p, function, &mut r)?, - 0x0416 => p.clip_rect(rect_brtl(&mut r)?), - 0x0415 => p.exclude_clip(), - 0x012D => p.select(u32::from(r.u16()?)), - 0x01F0 => p.delete(u32::from(r.u16()?)), - 0x02FA => { - let style = u32::from(r.u16()?); - let width = f64::from(r.i16()?); - r.skip(2)?; - p.create(Obj::Pen(PenObj { style, width, color: color(&mut r)?, entries: vec![] })); - } - 0x02FC => { - let style = u32::from(r.u16()?); - p.create(Obj::Brush(BrushObj::from_log(style, color(&mut r)?))); - } - 0x02FB => rec_create_font(p, &mut r)?, - 0x00F7 | 0x06FF => p.create(Obj::Other), - 0x01F9 | 0x0142 => p.create(Obj::Brush(BrushObj::Pattern)), - 0x0521 => rec_text_out(p, &mut r)?, - 0x0A32 => rec_ext_text_out(p, &mut r)?, - 0x0F43 => rec_stretch_dib(p, &mut r)?, - 0x0B41 => rec_stretch_blt(p, body, &mut r)?, - 0x0940 => rec_bit_blt(p, body, &mut r)?, - 0x061D => { - let rop = r.u32()?; - let (h, w, y, x) = (f64::from(r.i16()?), f64::from(r.i16()?), f64::from(r.i16()?), f64::from(r.i16()?)); - p.pattern_blit(Rect::new(x, y, x + w, y + h), rop); - } - f if IGNORED.contains(&f) => {} - _ => return None, - } - Some(()) -} diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 0e699236d7..86d268cee1 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -13,13 +13,14 @@ //! lines or gradients, so clipped art is written whole, images over white, dashes as separate //! lines and gradients and patterns as one colour (each loss comes back as a warning). //! -//! [`import`] reads either format back into a document of one artboard (the picture's frame) and -//! one layer: paths with fills and strokes, clipping, images and text. Records it doesn't read are -//! skipped, with one warning. [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) -//! into the same kind of document. +//! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`) +//! into a document of one artboard (the picture's frame) and one layer: paths with fills and +//! strokes, clipping, images and text. Records it doesn't read are skipped, with one warning. +//! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of +//! document. //! -//! - `bytes`: little-endian writing and bounds-checked reading. -//! - `dib`: device-independent bitmaps, both ways. +//! - `bytes`: little-endian writing. +//! - `dib`: device-independent bitmaps for the writers. //! - `scene`: the document walk both writers share. //! - `emf`, `wmf`: the writers. //! - `import`: the readers. diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 1e0ec5671b..f5870c5f95 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -151,13 +151,14 @@ fn dashes_gradients_and_images_round_trip_through_emf() { // ---------- hand-built records ---------- /// An EMF of `records` (type, body) with a frame of `w` × `h` hundredths of a millimetre on a -/// device of 100 pixels a millimetre. +/// device of 100 pixels a millimetre. Bodies are padded to a multiple of 4 bytes. fn hand_emf(w: i32, h: i32, records: &[(u32, Vec)]) -> Vec { let mut o = Out::default(); let rec = |o: &mut Out, kind: u32, body: &[u8]| { o.u32(kind); - o.u32(8 + body.len() as u32); + o.u32(8 + body.len().next_multiple_of(4) as u32); o.bytes(body); + o.pad(4); }; let mut head = Out::default(); head.bytes(&[0; 16]); @@ -336,6 +337,129 @@ fn wmf_window_is_mapped_onto_the_placeable_box() { } } +#[test] +fn wmf_without_a_placeable_header_is_read_at_1440_units_an_inch() { + // The window is 2880 × 1440 units: 2 × 1 inches. The rectangle is its left half. + let records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 2880])), (0x041B, le16(&[1440, 1440, 0, 0]))]; + let plain = hand_wmf(2880, 1440, &records)[22..].to_vec(); + let back = import(&plain).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 144.0, 72.0), 1e-6), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{:?}", p[0].geometric_bounds()); +} + +#[test] +fn wmf_without_a_placeable_box_in_a_metric_map_mode_is_read_at_96_pixels_an_inch() { + // MM_TWIPS (y up) and a window of 1440 twips square: one inch. The rectangle is the whole window. + let records = vec![(0x0103, le16(&[6])), (0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), (0x041B, le16(&[1440, 1440, 0, 0]))]; + let boxed = hand_wmf(1440, 1440, &records); + let plain = boxed[22..].to_vec(); + // The box runs from right to left, so it gives no size. + let mut inverted = boxed; + inverted[6..8].copy_from_slice(&1440i16.to_le_bytes()); + inverted[10..12].copy_from_slice(&0i16.to_le_bytes()); + for bytes in [plain, inverted] { + let back = import(&bytes).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 72.0, 72.0), 1e-4), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-4), "{:?}", p[0].geometric_bounds()); + } +} + +#[test] +fn wmf_whose_metric_map_mode_is_restored_away_is_read_at_1440_units_an_inch() { + // SAVEDC, MM_TWIPS, then RESTOREDC back to MM_TEXT, by a count of levels and by a level; the + // drawing is then the one in `wmf_without_a_placeable_header_is_read_at_1440_units_an_inch`. + for restore in [-1i16, 1] { + let records = vec![ + (0x001E, Vec::new()), + (0x0103, le16(&[6])), + (0x0127, le16(&[restore])), + (0x020B, le16(&[0, 0])), + (0x020C, le16(&[1440, 2880])), + (0x041B, le16(&[1440, 1440, 0, 0])), + ]; + let plain = hand_wmf(2880, 1440, &records)[22..].to_vec(); + let back = import(&plain).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 144.0, 72.0), 1e-6), "{restore}: {:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{restore}: {:?}", p[0].geometric_bounds()); + } +} + +#[test] +fn wmf_that_draws_in_a_metric_map_mode_and_restores_is_read_at_96_pixels_an_inch() { + // SAVEDC, MM_TWIPS, a one-inch rectangle, then RESTOREDC back to MM_TEXT with nothing more drawn. + let records = vec![ + (0x001E, Vec::new()), + (0x0103, le16(&[6])), + (0x020B, le16(&[0, 0])), + (0x020C, le16(&[1440, 1440])), + (0x041B, le16(&[1440, 1440, 0, 0])), + (0x0127, le16(&[-1])), + ]; + let plain = hand_wmf(1440, 1440, &records)[22..].to_vec(); + let back = import(&plain).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + let b = p[0].geometric_bounds().unwrap(); + assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "{b:?}"); +} + +#[test] +fn wmf_records_the_mix_mode_keeps_from_drawing_do_not_set_its_scale() { + // A rectangle of 1440 units in MM_TEXT; then SAVEDC, MM_TWIPS, a mix mode and two records that + // draw nothing under it, and RESTOREDC. + let rect = (0x041B, le16(&[1440, 1440, 0, 0])); + let patblt = |rop: u32| (0x061D, [rop.to_le_bytes().to_vec(), le16(&[100, 100, 0, 0])].concat()); + let cases = [ + // R2_NOP and R2_XORPEN: rectangles draw nothing. + (11i16, [rect.clone(), rect.clone()]), + (7, [rect.clone(), rect.clone()]), + // R2_NOP: PATBLT with PATCOPY fills nothing. + (11, [patblt(0x00F0_0021), patblt(0x00F0_0021)]), + // R2_COPYPEN: PATBLT with DSTINVERT is not drawn. + (13, [patblt(0x0055_0009), patblt(0x0055_0009)]), + ]; + for (mix, hidden) in cases { + let mut records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), rect.clone()]; + records.extend([(0x001E, Vec::new()), (0x0103, le16(&[6])), (0x0104, le16(&[mix]))]); + records.extend(hidden); + records.push((0x0127, le16(&[-1]))); + let plain = hand_wmf(1440, 1440, &records)[22..].to_vec(); + let back = import(&plain).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1, "mix {mix}: {p:?}"); + let b = p[0].geometric_bounds().unwrap(); + assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "mix {mix}: {b:?}"); + } + // R2_NOP, then SAVEDC, R2_COPYPEN and RESTOREDC bring R2_NOP back: the MM_TWIPS rectangle after + // them draws nothing. + let mut records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), rect.clone(), (0x0104, le16(&[11]))]; + records.extend([(0x001E, Vec::new()), (0x0104, le16(&[13])), (0x0127, le16(&[-1])), (0x0103, le16(&[6])), rect]); + let back = import(&hand_wmf(1440, 1440, &records)[22..]).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1, "{p:?}"); + let b = p[0].geometric_bounds().unwrap(); + assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "restored: {b:?}"); +} + +#[test] +fn a_stroke_that_reaches_too_far_leaves_the_strokes_before_it() { + // The black pen draws from (0, 500) to (100, 500), then on to a point far outside the picture. + let records = vec![(37, le(&[0x8000_0007u32 as i32])), (27, le(&[0, 500])), (54, le(&[100, 500])), (54, le(&[100_000_000, 500]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1, "{p:?}"); + let mm = 72.0 / 25.4; + let b = p[0].geometric_bounds().unwrap(); + assert!((b.x0).abs() < 0.01 && (b.x1 - mm).abs() < 0.01 && (b.y0 - 5.0 * mm).abs() < 0.01, "{b:?}"); + assert!(back.warnings.iter().any(|w| w.contains("far outside")), "{:?}", back.warnings); +} + #[test] fn damaged_files_fail_or_import_partly() { let good = emf(&sample()).bytes; @@ -357,6 +481,18 @@ fn damaged_files_fail_or_import_partly() { assert!(import(&huge).is_ok()); } +#[test] +fn a_file_with_more_objects_than_are_read_says_so() { + // RECTANGLE records: 10 more than the reader keeps, then a few under that. + let rect = (43, le(&[0, 0, 100, 100])); + let many = hand_emf(5000, 3000, &vec![rect.clone(); 200_010]); + let back = import(&many).unwrap(); + assert_eq!(paths(&back.document).len(), 200_000); + assert!(back.warnings.iter().any(|w| w.contains("reached the most objects")), "{:?}", back.warnings); + let few = import(&hand_emf(5000, 3000, &vec![rect; 3])).unwrap(); + assert!(few.warnings.is_empty(), "{:?}", few.warnings); +} + /// An EMR_STRETCHDIBITS copying `png` (a BI_PNG bitmap) to a 10 × 10 box. fn png_stretch_dibits(png: &[u8]) -> Vec { // Bounds; destination, source and its size; the BITMAPINFO and the bits (from the record start); @@ -371,19 +507,29 @@ fn png_stretch_dibits(png: &[u8]) -> Vec { } #[test] -fn embedded_bitmaps_share_one_pixel_budget() { - // #3600: each bitmap was bounded but not their total, so many records of the largest one a record - // may hold cost minutes. Those past the file's budget are left out before they're decoded. +fn oversized_embedded_bitmaps_are_left_out_before_decoding() { + // #3600: many records of the largest bitmap a record may hold cost minutes. Each of these claims + // more pixels than one image may have, so the reader leaves it out from its header. (The reader's + // budget for all the images of one file is tested where the reader is.) let records = vec![(81, png_stretch_dibits(&png_claiming(1 << 13, 1 << 13))); 5]; let back = import(&hand_emf(5000, 3000, &records)).unwrap(); - assert!(back.warnings.iter().any(|w| w == "images past the most pixels one file may hold were left out"), "{:?}", back.warnings); + assert!(!all(&back.document).iter().any(|n| matches!(n.kind, NodeKind::Image(_)))); } #[test] fn clips_nest_only_so_deep() { - // Each clip inside the last one used to nest a clipping group one level deeper, past the stack. - let mut records = vec![(30, le(&[0, 0, 1500, 1500])); 200_000]; - records.push((43, le(&[100, 100, 200, 200]))); + // Each clip inside the last one nests a clipping group one level deeper; past the stack they + // are left out with a warning. + let mut records = vec![]; + // As many as the reader keeps: one more than the stack. + for i in 0..32 { + // BEGINPATH, a rectangle a little smaller each time, ENDPATH, SELECTCLIPPATH (RGN_AND). + records.push((59, vec![])); + records.push((43, le(&[100 + i, 100 + i, 2000 - i, 2000 - i]))); + records.push((60, vec![])); + records.push((67, le(&[1]))); + } + records.push((43, le(&[500, 500, 600, 600]))); let back = import(&hand_emf(5000, 3000, &records)).unwrap(); let mut depth = 0; let mut n = back.document.layers[0].children().unwrap()[0].clone(); @@ -393,4 +539,324 @@ fn clips_nest_only_so_deep() { } assert_eq!(depth, vectorcraft_doc::clipnest::MAX_NEST); assert!(back.warnings.iter().any(|w| w.contains("clips nested more than")), "{:?}", back.warnings); + // A hostile count of clip records: each one used to nest a clipping group one level deeper, + // past the stack. They make one clip. + let mut records = vec![(30, le(&[0, 0, 1500, 1500])); 200_000]; + records.push((43, le(&[100, 100, 200, 200]))); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) }; + assert!(children.iter().all(|c| !matches!(c.kind, NodeKind::Group { .. })), "one level"); + assert_eq!(paths(&back.document).len(), 1); +} + +/// An EMR_COMMENT holding EMF+ `records` (type, flags, data). +fn emf_plus(records: &[(u16, u16, Vec)]) -> Vec { + let mut plus = Out::default(); + for (kind, flags, data) in records { + plus.u16(*kind); + plus.u16(*flags); + plus.u32(12 + data.len() as u32); + plus.u32(data.len() as u32); + plus.bytes(data); + } + let mut body = Out::default(); + body.u32(4 + plus.len() as u32); + // "EMF+" + body.u32(0x2B46_4D45); + body.bytes(&plus.0); + body.0 +} + +fn le_f32(values: &[f32]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() +} + +#[test] +fn emf_plus_only_pictures_import_their_drawing() { + // An EMF+ only file: its EMF records draw nothing, so it was imported empty with a warning. + // EmfPlusHeader (version, flags, 96 dpi), FillRects with an inline green color (flag S) and one + // rectangle of 10 × 5 mm at (10, 10) mm in device pixels, EmfPlusEndOfFile. + let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]); + let rects = [le(&[0xFF00_FF00u32 as i32, 1]), le_f32(&[1000.0, 1000.0, 1000.0, 500.0])].concat(); + let comment = emf_plus(&[(0x4001, 0, header), (0x400A, 0x8000, rects), (0x4002, 0, vec![])]); + let back = import(&hand_emf(5000, 3000, &[(70, comment)])).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert_eq!(fill_rgb(&p[0]), Some([0, 255, 0])); + let mm = 72.0 / 25.4; + let b = p[0].geometric_bounds().unwrap(); + assert!(near(b, Rect::new(10.0 * mm, 10.0 * mm, 20.0 * mm, 15.0 * mm), 0.01), "{b:?}"); +} + +#[test] +fn hatched_brushes_fill_with_their_average_color() { + // CREATEBRUSHINDIRECT: a hatched (style 2) blue brush, selected; a null pen; a rectangle. The + // hatch is drawn over the white background, so the average is a light blue. + let records = vec![(39, le(&[1, 2, 0x00ff_0000, 0])), (37, le(&[1])), (37, le(&[0x8000_0008u32 as i32])), (43, le(&[1000, 1000, 2000, 1500]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(back.warnings, vec!["hatched and pattern brushes are filled with their average color".to_string()]); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + let [r, g, b] = fill_rgb(&p[0]).unwrap(); + assert!(b == 255 && r == g && r > 0 && r < 255, "{:?}", [r, g, b]); + // With a transparent background (SETBKMODE 1) the hatch is blue with gaps: a translucent fill. + let mut records = records; + records.insert(0, (18, le(&[1]))); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let p = paths(&back.document); + assert_eq!(fill_rgb(&p[0]), Some([0, 0, 255])); + let AppearanceItem::Fill(f) = &p[0].appearance.items[0] else { panic!("a fill") }; + assert!(f.opacity > 0.0 && f.opacity < 1.0, "{}", f.opacity); +} + +#[test] +fn text_keeps_a_stretch_across() { + // A world transform twice as wide as it is high, a 10 mm font and "Hi". + let mut text = vec![0; 16]; + text.extend(le(&[1, 0, 0])); + text.extend(le(&[1000, 1500, 2, 76, 0, 0, 0, 0, 0, 0])); + text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes)); + let mut font = le(&[2, -1000, 0, 0, 0, 400]); + font.extend([0u8; 8]); + font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes)); + let world = [2.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect(); + let records = vec![(35, world), (82, font), (37, le(&[2])), (84, text)]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let t = all(&back.document) + .into_iter() + .find_map(|n| match n.kind { + NodeKind::Text(t) => Some(t), + _ => None, + }) + .unwrap(); + let mm = 72.0 / 25.4; + assert!((t.runs[0].style.size - 10.0 * mm).abs() < 0.01, "{}", t.runs[0].style.size); + let [a, b, c, d, ..] = t.xf.as_coeffs(); + assert!((a - 2.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6, "{:?}", t.xf); +} + +#[test] +fn a_clip_whose_box_holds_the_picture_still_clips() { + // A diamond around the middle of the picture, whose box holds the whole frame but which cuts + // off its corners: BEGINPATH, POLYGON, ENDPATH, SELECTCLIPPATH (RGN_COPY), then a rectangle. + let mut diamond = le(&[0, 0, 0, 0, 4]); + diamond.extend(le(&[2500, -500, 5500, 1500, 2500, 3500, -500, 1500])); + // A bow tie through the four corners of a box around the picture. + let mut bow_tie = le(&[0, 0, 0, 0, 4]); + bow_tie.extend(le(&[-500, -500, 5500, 3500, 5500, -500, -500, 3500])); + // Two open figures through the four corners, the top edge and the bottom edge, which enclose + // nothing: MOVETOEX, LINETO, MOVETOEX, LINETO. + let edges = vec![(27, le(&[-500, -500])), (54, le(&[5500, -500])), (27, le(&[5500, 3500])), (54, le(&[-500, 3500]))]; + // One figure through the four corners that runs back over its edges and encloses nothing: + // POLYLINE top-left, top-right, top-left, bottom-left, bottom-right, bottom-left. + let mut retraced = le(&[0, 0, 0, 0, 6]); + retraced.extend(le(&[-500, -500, 5500, -500, -500, -500, -500, 3500, 5500, 3500, -500, 3500])); + for clip in [vec![(3, diamond)], vec![(3, bow_tie)], edges, vec![(4, retraced)]] { + let records = [vec![(59, vec![])], clip, vec![(60, vec![]), (67, le(&[5])), (43, le(&[0, 0, 5000, 3000]))]].concat(); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + assert!(matches!(layer[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", layer[0].kind); + } +} + +#[test] +fn dual_emf_plus_files_draw_their_emf_plus_records() { + // A dual file (header flag 1): a translucent red EMF+ fill, and a plain rectangle that is only + // the fallback for readers of plain records. + let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]); + let rects = [le(&[0x80FF_0000u32 as i32, 1]), le_f32(&[1000.0, 1000.0, 1000.0, 500.0])].concat(); + let comment = emf_plus(&[(0x4001, 1, header), (0x400A, 0x8000, rects), (0x4002, 0, vec![])]); + let back = import(&hand_emf(5000, 3000, &[(70, comment), (43, le(&[3000, 1000, 4000, 2000]))])).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert_eq!(fill_rgb(&p[0]), Some([255, 0, 0])); + let AppearanceItem::Fill(f) = &p[0].appearance.items[0] else { panic!("a fill") }; + assert!((f.opacity - 128.0 / 255.0).abs() < 1e-6, "{}", f.opacity); +} + +#[test] +fn translucent_strokes_drawn_one_after_another_stay_apart() { + // EmfPlusObject: pen 0, 1 pixel wide, with a solid brush of `argb`; then two EmfPlusDrawLines + // with it, from A to B and from B back to A. + let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]); + let lines = |argb: u32| { + let pen = [le(&[0xDBC0_1002u32 as i32, 0, 0, 2]), le_f32(&[1.0]), le(&[0xDBC0_1002u32 as i32, 0, argb as i32])].concat(); + let a_to_b = [le(&[2]), le_f32(&[1000.0, 1000.0, 3000.0, 1000.0])].concat(); + let b_to_a = [le(&[2]), le_f32(&[3000.0, 1000.0, 1000.0, 1000.0])].concat(); + let comment = emf_plus(&[(0x4001, 0, header.clone()), (0x4008, 0x0200, pen), (0x400D, 0, a_to_b), (0x400D, 0, b_to_a), (0x4002, 0, vec![])]); + paths(&import(&hand_emf(5000, 3000, &[(70, comment)])).unwrap().document) + }; + // Each translucent stroke keeps its own opacity, so where they overlap both show. + let p = lines(0x80FF_0000); + assert_eq!(p.len(), 2, "{p:?}"); + for n in &p { + let AppearanceItem::Stroke(st) = &n.appearance.items[0] else { panic!("a stroke") }; + assert!((st.opacity - 128.0 / 255.0).abs() < 1e-6, "{}", st.opacity); + } + // Opaque strokes still join into one path. + assert_eq!(lines(0xFFFF_0000).len(), 1); +} + +#[test] +fn strokes_join_only_with_round_caps_round_joins_and_no_dashes() { + // CREATEPENINDIRECT: a 20-unit black pen of `style`, selected; then two lines one after the + // other that meet at a right angle. + let lines = |style: i16| { + let records = vec![ + (0x02FA, [le16(&[style, 20, 0]), 0u32.to_le_bytes().to_vec()].concat()), + (0x012D, le16(&[0])), + (0x0214, le16(&[100, 100])), + (0x0213, le16(&[100, 700])), + (0x0213, le16(&[700, 700])), + ]; + paths(&import(&hand_wmf(1440, 1440, &records)).unwrap().document) + }; + // Round caps and round joins, a solid line: one path, as a round join is the two round caps. + assert_eq!(lines(0).len(), 1); + // Flat caps and miter joins, flat caps alone and miter joins alone: each line keeps its caps. + for style in [0x2200, 0x0200, 0x2000] { + let p = lines(style); + assert_eq!(p.len(), 2, "style {style:#x}: {p:?}"); + } + // PS_DASH: each line's dashes start at its own start. + let p = lines(1); + assert_eq!(p.len(), 2, "{p:?}"); + assert!(p.iter().all(|n| n.appearance.stroke().is_some_and(|st| st.dash.is_some())), "{p:?}"); +} + +#[test] +fn pattern_brushes_fill_with_their_average_color() { + // CREATEDIBPATTERNBRUSHPT: a 2 × 2 tile of 24-bit pixels, two red and two blue (bottom-up rows + // padded to 4 bytes); selected, a null pen, a rectangle. + let mut brush = le(&[1, 0, 32, 40, 72, 16]); + brush.extend(le(&[40, 2, 2, 0x0018_0001, 0, 0, 0, 0, 0, 0])); + brush.extend([0, 0, 255, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0]); + let records = vec![(94, brush), (37, le(&[1])), (37, le(&[0x8000_0008u32 as i32])), (43, le(&[1000, 1000, 2000, 1500]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(back.warnings, vec!["hatched and pattern brushes are filled with their average color".to_string()]); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + let [r, g, b] = fill_rgb(&p[0]).unwrap(); + assert!((126..=128).contains(&r) && g == 0 && (126..=128).contains(&b), "{:?}", [r, g, b]); +} + +#[test] +fn clipped_text_is_clipped_to_its_rectangle() { + // EXTTEXTOUTW with ETO_CLIPPED and a rectangle of 9–12 × 10–16 mm, in an underlined and struck + // through font. + let mut text = vec![0; 16]; + text.extend(le(&[1, 0, 0])); + text.extend(le(&[1000, 1500, 2, 76, 4, 900, 1000, 1200, 1600, 0])); + text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes)); + let mut font = le(&[2, -1000, 0, 0, 0, 400]); + font.extend([0, 1, 1, 0, 0, 0, 0, 0]); + font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes)); + let mut records = vec![(82, font), (37, le(&[2])), (84, text)]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) }; + let mm = 72.0 / 25.4; + let own = Rect::new(9.0 * mm, 10.0 * mm, 12.0 * mm, 16.0 * mm); + assert!(near(children[0].geometric_bounds().unwrap(), own, 0.01)); + let NodeKind::Text(t) = &children[1].kind else { panic!("text") }; + assert!(t.runs[0].style.underline && t.runs[0].style.strikethrough); + // Under clip paths nested as deep as the stack, the text's own clip is still the innermost. + for i in 0..32 { + records.insert(0, (67, le(&[1]))); + records.insert(0, (60, vec![])); + records.insert(0, (43, le(&[100 + i, 100 + i, 4000 - i, 2500 - i]))); + records.insert(0, (59, vec![])); + } + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let mut n = back.document.layers[0].children().unwrap()[0].clone(); + while let NodeKind::Group { children, clip: true } = &n.kind + && matches!(children.last().map(|c| &c.kind), Some(NodeKind::Group { .. })) + { + n = children.last().unwrap().clone(); + } + let NodeKind::Group { children, clip: true } = &n.kind else { panic!("a clipping group: {:?}", n.kind) }; + assert!(near(children[0].geometric_bounds().unwrap(), own, 0.01), "{:?}", children[0].geometric_bounds()); + assert!(matches!(children[1].kind, NodeKind::Text(_))); +} + +#[test] +fn excluded_clip_rectangles_clip() { + // EXCLUDECLIPRECT cuts the top-left of the picture out of the clip; the rectangle crosses it. + // The clip it cuts from is the picture's bounds (5000 × 3000 device pixels). + let records = vec![(29, le(&[0, 0, 1500, 1500])), (43, le(&[1000, 1000, 2000, 1500]))]; + let mut bytes = hand_emf(5000, 3000, &records); + for (i, v) in [0i32, 0, 5000, 3000].iter().enumerate() { + bytes[8 + i * 4..12 + i * 4].copy_from_slice(&v.to_le_bytes()); + } + let back = import(&bytes).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + assert!(matches!(layer[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", layer[0].kind); +} + +#[test] +fn shapes_under_the_same_clip_share_one_clipping_group() { + let records = vec![(30, le(&[0, 0, 1500, 1500])), (43, le(&[100, 100, 200, 200])), (43, le(&[300, 300, 400, 400]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) }; + assert_eq!(children.len(), 3, "the clip and both rectangles"); +} + +#[test] +fn a_record_whose_size_is_not_a_multiple_of_4_ends_the_file() { + let records = vec![(43, le(&[100, 100, 200, 200])), (43, le(&[300, 300, 400, 400])), (43, le(&[500, 500, 600, 600]))]; + let mut bytes = hand_emf(5000, 3000, &records); + // The second rectangle's size, after the header and the first rectangle. + let header = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize; + let first = u32::from_le_bytes(bytes[header + 4..header + 8].try_into().unwrap()) as usize; + let at = header + first + 4; + let size = u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()); + bytes[at..at + 4].copy_from_slice(&(size + 2).to_le_bytes()); + let back = import(&bytes).unwrap(); + assert_eq!(paths(&back.document).len(), 1); + assert_eq!(back.warnings, vec!["the file ends early: what it held was imported".to_string()]); +} + +#[test] +fn wmf_with_an_inverted_placeable_box_is_read_at_its_units_an_inch() { + // The box runs from right to left, so it gives no size: the window (1440 units square, one inch + // at the header's 1440 units an inch) does. The rectangle is its top-left quarter. + let records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), (0x041B, le16(&[720, 720, 0, 0]))]; + let mut bytes = hand_wmf(1440, 1440, &records); + bytes[6..8].copy_from_slice(&1440i16.to_le_bytes()); + bytes[10..12].copy_from_slice(&0i16.to_le_bytes()); + let back = import(&bytes).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 36.0, 36.0), 1e-6), "{:?}", p[0].geometric_bounds()); +} + +#[test] +fn emf_without_a_frame_is_read_at_its_device_resolution() { + // An empty frame, and bounds of 5000 × 3000 device pixels at 100 pixels a millimetre. + let mut bytes = hand_emf(0, 0, &[(43, le(&[1000, 1000, 2000, 1500]))]); + for (i, v) in [0i32, 0, 5000, 3000].iter().enumerate() { + bytes[8 + i * 4..12 + i * 4].copy_from_slice(&v.to_le_bytes()); + } + let back = import(&bytes).unwrap(); + let mm = 72.0 / 25.4; + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 50.0 * mm, 30.0 * mm), 0.01), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(10.0 * mm, 10.0 * mm, 20.0 * mm, 15.0 * mm), 0.01), "{:?}", p[0].geometric_bounds()); + // A device 50 mm high: 200 pixels a millimetre down, so everything is half as tall. + bytes[84..88].copy_from_slice(&50i32.to_le_bytes()); + let back = import(&bytes).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 50.0 * mm, 15.0 * mm), 0.01), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(10.0 * mm, 5.0 * mm, 20.0 * mm, 7.5 * mm), 0.01), "{:?}", p[0].geometric_bounds()); } diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index 6cf8677269..00ac16a3fe 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -45,6 +45,11 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let set = &opts.settings; set.check()?; vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; + // The pages come from the artboards, which baking leaves as they are. The version a long page + // raises the file to decides whether the layers are written, so it is settled before baking. + let pages = pages(doc, opts)?; + let raised = for_long_pages(set, &pages)?; + let set = raised.as_ref().unwrap_or(set); // Live geometry effects export as their result, in symbols' art too; raster effects are // reported below. // Only the layers this export writes place their instances' art (see `ex.non_printing` and @@ -57,9 +62,6 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha // Baking stops early when cancelled, leaving a half-baked copy that must not be written. vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; let doc = baked.as_ref().unwrap_or(doc); - let pages = pages(doc, opts)?; - let raised = for_long_pages(set, &pages)?; - let set = raised.as_ref().unwrap_or(set); // The file's Title is File Info's; the page information names the document, as its tab does. let title = crate::pdfx::title(set.standard, opts.title.clone().unwrap_or_else(|| doc.info_title().to_owned())); diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 78930c7500..403cbc5431 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -14,6 +14,11 @@ struct Measured { members: Vec, } +/// Box `b` grown by `reach`, the room brush art can paint past it; `b` itself when `reach` is 0. +fn brushed(b: Option, reach: f64) -> Option { + if reach > 0.0 { b.map(|b| b.inflate(reach, reach)) } else { b } +} + #[cfg(test)] std::thread_local! { /// The objects this thread has measured for the walk and for the links (tests). @@ -312,15 +317,17 @@ impl Exporter<'_> { krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity) } - /// The box of `n`, and of the members of a plain group or layer. + /// The box of `n`, and of the members of a plain group or layer. A box grows by the room brush + /// art can paint past the brushed strokes of `n` and of the objects in it + /// ([`vectorcraft_brush::reach_within`]), as the renderer culls it. fn measure(&self, n: &Node) -> Measured { if !matches!(n.kind, NodeKind::Layer { clip: false, .. } | NodeKind::Group { clip: false, .. }) { #[cfg(test)] MEASURES.with(|m| m.set(m.get() + 1)); - return Measured { bounds: n.visual_bounds_with(&self.symbols), members: vec![] }; + return Measured { bounds: brushed(n.visual_bounds_with(&self.symbols), vectorcraft_brush::reach_within(n)), members: vec![] }; } let members: Vec<_> = n.editing_children().iter().map(|c| self.measure(c)).collect(); - Measured { bounds: n.visual_of_members(members.iter().map(|m| m.bounds)), members } + Measured { bounds: brushed(n.visual_of_members(members.iter().map(|m| m.bounds)), vectorcraft_brush::reach(n)), members } } pub(super) fn node(&mut self, s: &mut Surface, n: &Node, page: Rect, force: bool) { diff --git a/crates/pdf/src/print/layout.rs b/crates/pdf/src/print/layout.rs index a88dd89950..5d28e9e2b1 100644 --- a/crates/pdf/src/print/layout.rs +++ b/crates/pdf/src/print/layout.rs @@ -71,7 +71,9 @@ pub struct TileGrid { /// Calls `f` with the bounds of each object of `n` that prints: visible, not on a template /// layer and not a guide (layers are already picked by the Print Layers option). Symbol -/// instances are measured by their art from `symbols`. +/// instances are measured by their art from `symbols`. A box grows by the room brush art can +/// paint past the brushed strokes of the object and of the objects in it +/// ([`vectorcraft_brush::reach_within`]). fn printed(n: &Node, symbols: &SymbolBoxes, f: &mut impl FnMut(Rect)) { if !n.visible { return; @@ -85,7 +87,8 @@ fn printed(n: &Node, symbols: &SymbolBoxes, f: &mut impl FnMut(Rect)) { } _ => { if let Some(b) = n.visual_bounds_with(symbols) { - f(b); + let reach = vectorcraft_brush::reach_within(n); + f(if reach > 0.0 { b.inflate(reach, reach) } else { b }); } } } @@ -102,9 +105,10 @@ fn has_art(doc: &Document, r: Rect) -> bool { any } -/// The bounds of all the art that prints. +/// The bounds of all the art that prints, with the brush art it paints. The box of a symbol +/// instance whose art holds brushed strokes grows as in [`has_art`]. fn art_bounds(doc: &Document) -> Option { - let symbols = doc.symbol_boxes(); + let symbols = doc.symbol_boxes().with_brush_art(); let mut all: Option = None; for l in &doc.layers { printed(l, &symbols, &mut |b| all = Some(all.map_or(b, |a| a.union(b)))); diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 5e9796b9b4..b49a033a23 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -246,6 +246,77 @@ fn an_instance_whose_brush_art_reaches_the_page_is_written() { assert!(close(l[0].geometric_bounds().unwrap(), Rect::new(-15.0, 30.0, 5.0, 70.0), 0.01), "{:?}", l[0].geometric_bounds()); } +/// A 200 × 100 pt document whose 3 pt. Round brush paints a 20 pt round nib. +fn doc_with_wide_nib() -> Document { + let mut d = doc(200.0, 100.0); + let mut lib = vectorcraft_brush::library(&d); + let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else { + panic!("the 3 pt. Round brush") + }; + c.size = 20.0; + vectorcraft_brush::store(&mut d, &lib); + d +} + +/// A line from (`x`, 40) to (`x`, 60) with a 1 pt black stroke, painted by the 3 pt. Round brush +/// when `brushed`. +fn nib_line(x: f64, brushed: bool) -> Node { + let mut stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + if brushed { + stroke.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + } + Node::path(NodeId(0), shapes::line((x, 40.0).into(), (x, 60.0).into()), stroke) +} + +#[test] +fn a_path_whose_brush_art_reaches_the_page_is_written() { + // The line at x = -5 lies left of the page, and the 20 pt nib paints 10 pt either side of it, + // onto the page: alone, in a group, in a knockout group and as a compound path. + let compound = |n: Node| { + let mut c = Node::new(NodeId(0), NodeKind::Compound { children: vec![Arc::new(nib_line(-5.0, false))], rule: FillRule::NonZero }); + c.appearance = n.appearance; + c + }; + let knockout = |n: Node| { + let mut g = Node::group(NodeId(0), vec![Arc::new(n), Arc::new(rect_node(Rect::new(150.0, 10.0, 170.0, 30.0), Color::rgb(0.0, 0.0, 1.0)))]); + g.knockout = vectorcraft_doc::Knockout::On; + g + }; + let group = |n: Node| Node::group(NodeId(0), vec![Arc::new(n)]); + let wraps: [(&str, &dyn Fn(Node) -> Node); 4] = + [("path", &|n| n), ("group", &group), ("knockout group", &knockout), ("compound path", &compound)]; + for (what, wrap) in wraps { + let mut d = doc_with_wide_nib(); + add(&mut d, wrap(nib_line(-5.0, true))); + let out = roundtrip(&d); + let nib: Vec = leaves(&out).iter().filter_map(|n| n.geometric_bounds()).filter(|b| b.x1 < 100.0).collect(); + assert_eq!(nib.len(), 1, "{what}: the nib's art, {nib:?}"); + assert!(close(nib[0], Rect::new(-15.0, 30.0, 5.0, 70.0), 0.01), "{what}: {nib:?}"); + } + // Without its brush, or 100 pt left of the page, where the nib does not reach it, the line is + // left out. + for line in [nib_line(-5.0, false), nib_line(-100.0, true)] { + let mut d = doc_with_wide_nib(); + add(&mut d, line); + assert!(leaves(&roundtrip(&d)).is_empty()); + } + // A clipping path left of the page keeps the nib's art off it. + let mut d = doc_with_wide_nib(); + let clip = Node::new( + NodeId(0), + NodeKind::Path { + path: shapes::rectangle(Rect::new(-30.0, 0.0, -2.0, 100.0)), + rule: FillRule::NonZero, + live: None, + clipping: true, + guide: false, + }, + ); + add(&mut d, Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(nib_line(-5.0, true))], clip: true })); + let out = roundtrip(&d); + assert!(leaves(&out).is_empty(), "{:?}", leaves(&out)); +} + /// The live effects in a symbol's art apply where the instance places the art, as on the canvas: /// the symbol's square at (10, 40), which a Transform effect moves 100 pt right, is written at /// (110, 40). diff --git a/crates/pdf/src/tests/layers.rs b/crates/pdf/src/tests/layers.rs index 0650e3f0ef..b11cbc47d8 100644 --- a/crates/pdf/src/tests/layers.rs +++ b/crates/pdf/src/tests/layers.rs @@ -131,6 +131,37 @@ fn pdf_layers_import_back_as_layers() { } } +/// A hidden layer written as a PDF layer places the live effects of its instances' symbol art, +/// also in a PDF/A-2b file at PDF 1.4 whose 17,000 pt page has it written as PDF 1.6: the symbol's +/// square from x = 10 to 40, which a Transform effect moves 100 pt right, is written from x = 110 +/// to 140. +#[test] +fn a_hidden_layer_places_symbol_art_effects_when_a_long_page_raises_the_version() { + let mut d = Document::new(17_000.0, 300.0); + d.layers.clear(); + let mut square = rect(&mut d, 10.0, RED); + square.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: square.into() }); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + let mut l = Node::layer(d.alloc_id(), "Hidden", LayerColor::Preset(0)); + l.visible = false; + if let NodeKind::Layer { children, .. } = &mut l.kind { + children.push(instance.into()); + } + d.layers.push(l.into()); + for compatibility in [Compatibility::Pdf14, Compatibility::Pdf16] { + let settings = PdfSettings { standard: Standard::PdfA2b, compatibility, create_layers: true, ..PdfSettings::default() }; + let r = export_with_report(&d, &PdfOptions { settings, created: Some(1_791_200_000), ..Default::default() }).unwrap(); + assert!(r.bytes.starts_with(b"%PDF-1.6"), "{compatibility:?}"); + let back = import_with_report(&r.bytes, &ImportOptions::default()).unwrap().document; + let hidden = back.layers.iter().find(|l| l.name.as_deref() == Some("Hidden")).expect("the hidden layer"); + let art = hidden.children().unwrap(); + assert_eq!(art.len(), 1, "{compatibility:?}"); + let b = art[0].geometric_bounds().unwrap(); + assert!((b.x0 - 110.0).abs() < 0.1 && (b.x1 - 140.0).abs() < 0.1, "{compatibility:?}: {b:?}"); + } +} + /// The rows of `nodes` in paint order, depth first: `depth name visible` for layers, `depth fill` /// for art. fn tree(nodes: &[std::sync::Arc], depth: usize, out: &mut Vec) { diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 2cb63e374a..ecd1f25ce1 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -451,6 +451,62 @@ fn a_symbol_instances_brush_art_keeps_its_artboard_printed() { assert!(p[0].1.iter().any(|(_, paint)| rgb8(paint) == [255, 0, 0]), "{p:?}"); } +#[test] +fn a_brushed_paths_brush_art_keeps_its_artboard_printed_and_framed() { + // A line from (-5, 40) to (-5, 60) with a 1 pt red stroke painted by a 20 pt round nib, alone, + // in a group or as the art of a symbol instance: the line lies left of the artboard, and the nib + // paints 10 pt either side of it, onto the artboard. + let line = || { + let mut stroke = Appearance::basic(Paint::None, rgb(1.0, 0.0, 0.0), 1.0); + stroke.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + Node::path(vectorcraft_doc::NodeId(0), shapes::line((-5.0, 40.0).into(), (-5.0, 60.0).into()), stroke) + }; + for what in ["path", "group", "symbol instance"] { + let mut d = doc(100.0, 100.0, &[]); + let mut lib = vectorcraft_brush::library(&d); + let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else { + panic!("the 3 pt. Round brush") + }; + c.size = 20.0; + vectorcraft_brush::store(&mut d, &lib); + let mut n = match what { + "path" => line(), + "group" => Node::group(vectorcraft_doc::NodeId(0), vec![Arc::new(line())]), + _ => { + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Nib".into(), art: Arc::new(line()) }); + Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Nib".into(), xf: vectorcraft_geom::Affine::IDENTITY }) + } + }; + n.id = d.alloc_id(); + let layer = d.default_layer().unwrap(); + d.insert(Some(layer), 0, n).unwrap(); + // Skip Blank Artboards keeps the artboard, and its page holds the nib's art. + let p = pages(&job(&d, json!({"skipBlank": true})).bytes); + assert_eq!(p.len(), 1, "{what}"); + assert!(p[0].1.iter().any(|(_, paint)| rgb8(paint) == [255, 0, 0]), "{what}: {p:?}"); + // Ignoring artboards, the page holds all the nib's art, 20 × 40 pt. + let pv = preview(&d, &settings(json!({"artboards": "ignore"}))).unwrap(); + let t = pv.sheets[0].trim; + assert!(t[2] - t[0] >= 20.0 && t[3] - t[1] >= 40.0, "{what}: {t:?}"); + } + // A compound path is painted with its own appearance: the brushed stroke left on its path + // paints nothing, and the artboard stays blank. + let mut d = doc(100.0, 100.0, &[]); + let kind = NodeKind::Compound { children: vec![Arc::new(line())], rule: vectorcraft_geom::FillRule::NonZero }; + let mut compound = Node::new(d.alloc_id(), kind); + compound.appearance = Appearance::basic(Paint::None, rgb(1.0, 0.0, 0.0), 1.0).into(); + let layer = d.default_layer().unwrap(); + d.insert(Some(layer), 0, compound).unwrap(); + assert!(preview(&d, &settings(json!({"skipBlank": true}))).is_err()); + // A brushed stroke without a paint draws no brush art: the artboard stays blank. + let mut d = doc(100.0, 100.0, &[]); + let mut unpainted = line(); + unpainted.id = d.alloc_id(); + unpainted.appearance.stroke_mut().unwrap().paint = Paint::None; + d.insert(Some(layer), 0, unpainted).unwrap(); + assert!(preview(&d, &settings(json!({"skipBlank": true}))).is_err()); +} + #[test] fn symbol_art_effects_print_where_they_draw() { // A red square and the symbol's blue square, each moved 100 pt right by a Transform effect, diff --git a/crates/render/src/brush_fx.rs b/crates/render/src/brush_fx.rs index 3c6ea922d4..5844a2ef7f 100644 --- a/crates/render/src/brush_fx.rs +++ b/crates/render/src/brush_fx.rs @@ -155,19 +155,19 @@ pub(crate) fn path_cull_bounds(symbols: &SymbolBoxes, n: &Node, visual: impl FnO /// How far brush art can paint past `n`'s brushed strokes, or past the brushed strokes in the art /// of symbol instance `n`: `16 × w + 8`, where `w` is the widest stroke (at least 1) of `n` when it -/// has a visible brushed stroke and of the objects in that art that have one +/// has a visible brushed stroke with a paint and of the objects in that art that have one /// ([`SymbolBoxes::brush_width`]) or the pieces live-effect plug-ins paint for them -/// ([`crate::fx::painted_brush_width`]), and 0 when neither has one. +/// ([`crate::fx::painted_brush_width`]), and 0 when neither has one. The room for `n`'s own strokes +/// is [`vectorcraft_brush::reach`], which the exports leave too. pub(crate) fn pad(symbols: &SymbolBoxes, n: &Node) -> f64 { - let own = vectorcraft_brush::has_brush(n) - .then(|| n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max)); + let own = vectorcraft_brush::reach(n); let art = match &n.kind { NodeKind::SymbolInstance { symbol, .. } => { symbols.brush_width(symbol).into_iter().chain(crate::fx::painted_brush_width(symbols, symbol)).reduce(f64::max).map(|w| w.max(1.0)) } _ => None, }; - own.into_iter().chain(art).reduce(f64::max).map_or(0.0, |w| 16.0 * w + 8.0) + art.map_or(own, |w| own.max(16.0 * w + 8.0)) } pub use vectorcraft_brush::instance_art; diff --git a/crates/render/src/fx/entries.rs b/crates/render/src/fx/entries.rs index 7b80677e2c..1d9e21a64e 100644 --- a/crates/render/src/fx/entries.rs +++ b/crates/render/src/fx/entries.rs @@ -14,6 +14,9 @@ pub(super) struct Content<'a> { 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/css.rs b/crates/svg/src/css.rs index f7e067aa30..5b0b921e32 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -194,6 +194,10 @@ pub(crate) fn type_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props { if st.proportional_metrics { v.push("\"palt\" 1".into()); } + // The East Asian glyph form: its one feature. + if let Some(tag) = st.glyph_form.feature().and_then(|t| std::str::from_utf8(t).ok()) { + v.push(format!("\"{tag}\" 1")); + } if !v.is_empty() { p.push(("font-feature-settings", v.join(", "))); } 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 id=\"{}\" style=\"clip-path:url(#{})\">", xml_escape(&id_t), xml_escape(&id_u)); + rect(out, text_clip, b); + let _ = write!(out, ""); + 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/colr.rs b/crates/text/src/colr.rs index 281ef8a65f..637dd9c243 100644 --- a/crates/text/src/colr.rs +++ b/crates/text/src/colr.rs @@ -508,12 +508,17 @@ impl ColorPainter for Tree<'_> { return; }; let Some(clip) = self.groups.get(at).and_then(|g| g.clip.clone()) else { return }; - if at + 1 == self.groups.len() - && let Some(g) = self.groups.last_mut() - { - g.flooded = g.children.is_empty(); - } + let innermost = at + 1 == self.groups.len(); + let before = self.groups.last().map_or(0, |g| g.children.len()); self.fill_path(&clip, &brush); + // Flooded only when this fill added the group's first child. A fill that paints nothing + // adds none and leaves the flag as it was, so the clip stays around what comes after it. + if innermost + && let Some(g) = self.groups.last_mut() + && g.children.len() > before + { + g.flooded = before == 0; + } } /// The glyph's outline filled, the brush moved by `brush_transform` (the glyph stays). diff --git a/crates/text/src/features.rs b/crates/text/src/features.rs index 9f2b555e23..4aabae7b1a 100644 --- a/crates/text/src/features.rs +++ b/crates/text/src/features.rs @@ -43,7 +43,7 @@ pub struct OtFeatures { pub swash: bool, /// The features of [`EXTRA_FEATURES`] turned on, one bit each (off by default): stylistic /// sets, alternates, titling, proportional and lining figures, superscript, subscript, - /// numerators and denominators, `aalt`. + /// numerators and denominators, `aalt`, H or V Style (`hkna`) and Roman Italics (`ital`). pub extra: u32, /// The value of each feature of [`EXTRA_FEATURES`] that is on, as a tag `salt=2` gives it: for /// a feature with alternates, which of them the font draws (the HarfBuzz feature value, 1 for @@ -64,13 +64,20 @@ pub const MAX_STYLE_FEATURES: usize = 256; /// Features beyond the named fields, off unless asked for, each bit `i` of [`OtFeatures::extra`]: /// stylistic sets `ss01`–`ss20`, stylistic alternates `salt`, titling `titl`, proportional `pnum` /// and lining `lnum` figures, superscript `sups`, subscript `subs`, numerators `numr`, -/// denominators `dnom` and access all alternates `aalt`. +/// denominators `dnom`, access all alternates `aalt`, and the OpenType panel menu's H or V Style +/// `hkna` (shaped as `vkna` in vertical type) and Roman Italics `ital`. /// -pub const EXTRA_FEATURES: [&str; 29] = [ +/// +/// +pub const EXTRA_FEATURES: [&str; 31] = [ "ss01", "ss02", "ss03", "ss04", "ss05", "ss06", "ss07", "ss08", "ss09", "ss10", "ss11", "ss12", "ss13", "ss14", "ss15", "ss16", "ss17", "ss18", - "ss19", "ss20", "salt", "titl", "pnum", "lnum", "sups", "subs", "numr", "dnom", "aalt", + "ss19", "ss20", "salt", "titl", "pnum", "lnum", "sups", "subs", "numr", "dnom", "aalt", "hkna", "ital", ]; +/// The features of [`EXTRA_FEATURES`] that are only on or off: they substitute one form for each +/// glyph, so they take no alternate's number (`hkna=2` is refused). +const SWITCH_FEATURES: [&str; 2] = ["hkna", "ital"]; + impl Default for OtFeatures { fn default() -> Self { Self { @@ -107,10 +114,11 @@ struct ParsedTag<'a> { value: u16, } -/// Can feature `name` take a value (`salt=2`)? The features of [`EXTRA_FEATURES`] and `swsh` can: -/// each substitutes glyphs, and the value says which alternate. +/// Can feature `name` take a value (`salt=2`)? The features of [`EXTRA_FEATURES`] but +/// [`SWITCH_FEATURES`], and `swsh`, can: each substitutes glyphs, and the value says which +/// alternate. fn takes_value(name: &str) -> bool { - name == "swsh" || EXTRA_FEATURES.contains(&name) + name == "swsh" || (EXTRA_FEATURES.contains(&name) && !SWITCH_FEATURES.contains(&name)) } /// Read a feature tag: `tag`, `+tag`, `-tag` or, for a feature that takes a value, `tag=N` (`N` @@ -316,9 +324,14 @@ impl OtFeatures { } for (i, tag) in EXTRA_FEATURES.iter().enumerate() { if let (true, Ok(t)) = (s.extra & (1 << i) != 0, <[u8; 4]>::try_from(tag.as_bytes())) { + // H or V Style: the kana forms made for the writing direction, `vkna` in vertical type. + let t = if self.vertical && &t == b"hkna" { *b"vkna" } else { t }; v.push(f(&t, u32::from(s.extra_values.get(i).copied().unwrap_or(0).max(1)))); } } + if let Some(tag) = st.glyph_form.feature() { + v.push(f(tag, true)); + } if self.vertical { // Not `vrt2`: its glyphs are already turned on their side, and the layout turns Latin // and digits itself (they would lie upside down, and tate-chu-yoko break). @@ -431,6 +444,31 @@ mod tests { } } + /// H or V Style (`hkna`) and Roman Italics (`ital`) are known, round-trip through the stored + /// tags and reach the shaper: `hkna` as itself in horizontal type and as `vkna` in vertical + /// type, `ital` in both. Neither takes an alternate's number. + #[test] + fn kana_style_and_roman_italics_are_kept_and_shaped() { + for t in ["hkna", "-hkna", "+ital", "ital"] { + assert!(OtFeatures::known_tag(t), "{t}"); + } + for t in ["hkna=2", "ital=0", "vkna"] { + assert!(!OtFeatures::known_tag(t), "{t}"); + } + assert_eq!(OtFeatures::from_tags(["ital", "hkna", "smcp"]).to_tags(), ["smcp", "hkna", "ital"]); + assert_eq!(OtFeatures::from_tags(["hkna", "ital", "-hkna"]).to_tags(), ["ital"]); + let st = CharStyle { features: vec!["hkna".into(), "ital".into()], ..CharStyle::default() }; + let on = |vertical: bool| -> Vec { + OtFeatures { vertical, ..OtFeatures::default() }.resolve(&st).iter().filter(|f| f.value == 1).map(|f| f.tag.to_string()).collect() + }; + assert_eq!(on(false), ["hkna", "ital"]); + assert_eq!(on(true), ["vkna", "ital", "vert"]); + let plain = |vertical: bool| OtFeatures { vertical, ..OtFeatures::default() }.resolve(&CharStyle::default()); + for vertical in [false, true] { + assert!(!plain(vertical).iter().any(|f| [b"hkna", b"vkna", b"ital"].iter().any(|t| f.tag == Tag::new(t))), "off by default"); + } + } + /// `changes` lists the features a change turns on and off and leaves out the ones it keeps, /// and applying them to any set makes the same change. #[test] diff --git a/crates/text/src/fontdb/gsub.rs b/crates/text/src/fontdb/gsub.rs index 888c89ab09..bcc19f74b0 100644 --- a/crates/text/src/fontdb/gsub.rs +++ b/crates/text/src/fontdb/gsub.rs @@ -304,6 +304,20 @@ impl FontFace { self.gsub.get_or_init(|| GsubIndex::read(self)) } + /// Does the face's `GSUB` table have feature `tag` with at least one lookup? At most + /// [`MAX_FEATURES`] feature records are read; false when the face has no `GSUB` table or it + /// cannot be read. + pub fn has_substitution_feature(&self, tag: [u8; 4]) -> bool { + let Some(font) = self.skrifa() else { return false }; + let Some(features) = font.gsub().ok().and_then(|g| g.feature_list().ok()) else { return false }; + features + .feature_records() + .iter() + .take(MAX_FEATURES) + .filter(|r| r.feature_tag().to_be_bytes() == tag) + .any(|r| r.feature(features.offset_data()).is_ok_and(|f| !f.lookup_list_indices().is_empty())) + } + /// What the features `aalt`, `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99`, `hist`, /// `jalt`, `nalt`, `ornm` and `titl` of the face's `GSUB` table substitute for glyph `gid`, in /// that order of features and within a feature in lookup order: the glyph of each single diff --git a/crates/text/src/harakat.rs b/crates/text/src/harakat.rs index 0f8ce4facd..ab5aa593bd 100644 --- a/crates/text/src/harakat.rs +++ b/crates/text/src/harakat.rs @@ -86,6 +86,7 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool { no_break, language, glyph_alternate, + glyph_form: _, fill, stroke, stroke_width, 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/warichu.rs b/crates/text/src/layout/warichu.rs index dd816599c6..b68b69efd9 100644 --- a/crates/text/src/layout/warichu.rs +++ b/crates/text/src/layout/warichu.rs @@ -287,6 +287,10 @@ fn place_block(g: &mut [SGlyph], s: &WariStyle, (vertical, whole): (bool, bool)) let rtl = !vertical && g.first().is_some_and(|gl| gl.level.is_rtl()); let (inset, outset) = if rtl { (after, before) } else { (before, after) }; let length = inset + block + outset; + // How far the glyphs reach above and below the line's baseline, each from its block line's + // baseline. + let above = g.iter().zip(&places).map(|(gl, p)| gl.ascent - p.1).fold(0.0, f64::max); + let below = g.iter().zip(&places).map(|(gl, p)| gl.descent + p.1).fold(0.0, f64::max); let glyphs = g.len(); for (i, (gl, (along, across, advance))) in g.iter_mut().zip(places).enumerate() { let em = gl.face.units_per_em() * gl.sy / r; @@ -300,9 +304,10 @@ fn place_block(g: &mut [SGlyph], s: &WariStyle, (vertical, whole): (bool, bool)) if i + 1 < glyphs { gl.keeps_next = true; } - // The line keeps the height of the block's own size, and holds the whole stack. - gl.ascent = (ascent / r).max(-top); - gl.descent = (descent / r).max(bottom); + // The line keeps the height of the block's own size, and holds the whole stack with each + // block line's glyphs. + gl.ascent = (ascent / r).max(-top).max(above); + gl.descent = (descent / r).max(bottom).max(below); if s.auto_leading { gl.leading /= r; } 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 befcbed41f..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), @@ -1028,6 +1036,8 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool { no_break, language, glyph_alternate, + // An OpenType feature over its own characters, like `features`. + glyph_form: _, } = a; // Keep PartialEq's non-reflexive behavior for ignored numeric fields, without cloning styles. let offsets = (standard_vertical_roman, tcy_up_down, tcy_left_right); @@ -1096,7 +1106,7 @@ pub(crate) fn warichu_alike(a: &CharStyle, b: &CharStyle) -> bool { /// character style's name, leading, baseline shift, rotation, Character Alignment, Character /// Direction (text is shaped apart where its bidi level changes), Kashidas, the kerning (each glyph takes its /// run's, see [`shape_segment`]), the space before a line's first character ([`space_before`]), -/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the OpenType features (each run's apply to its own characters, as features +/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the OpenType features and the East Asian glyph form (each run's apply to its own characters, as features /// over a range of the one buffer) and the tracking, as long as the tracking keeps or drops /// standard ligatures alike ([`crate::features::ligatures_suppressed_by`]). fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { @@ -1159,6 +1169,8 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { no_break, language, glyph_alternate, + // Applied as a feature over its run's own characters, with `features`. + glyph_form: _, } = a; *font_family == b.font_family && warichu_alike(a, b) @@ -1276,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`). @@ -1442,8 +1456,8 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe let mut ranged = Vec::new(); for (r, run_style) in runs.get(source_runs.clone()).unwrap_or_default() { let (a, b) = (r.start.max(range.start), r.end.min(range.end)); - if run_style.features != base_style.features && a < b { - let own = variant(&CharStyle { features: run_style.features.clone(), ..base_style.clone() }); + if (run_style.features != base_style.features || run_style.glyph_form != base_style.glyph_form) && a < b { + let own = variant(&CharStyle { features: run_style.features.clone(), glyph_form: run_style.glyph_form, ..base_style.clone() }); ranged_features(base, &own, a..b, &mut ranged); } } @@ -1784,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, @@ -1822,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 }; @@ -1844,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/colr.rs b/crates/text/src/tests/colr.rs index c6c4696f16..e59fb390c9 100644 --- a/crates/text/src/tests/colr.rs +++ b/crates/text/src/tests/colr.rs @@ -288,6 +288,49 @@ fn a_glyph_filled_with_one_colour_is_one_path() { assert_eq!(fill(only), Paint::solid(rgb(COLR_RED))); } +/// A fill that paints nothing (a palette index past the palette) followed by another glyph +/// inside the same glyph's clip keeps the clip: the second glyph is drawn clipped to the first, +/// not on its own. +#[test] +fn a_fill_that_paints_nothing_keeps_the_clip_around_the_glyph_after_it() { + use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList}; + use write_fonts::types::GlyphId16; + let bytes = colr_font(false).unwrap(); + let read = skrifa::FontRef::new(&bytes).unwrap(); + let gid = |ch| GlyphId16::new(u16::try_from(read.charmap().map(ch).unwrap().to_u32()).unwrap()); + let mut colr = Colr::new(0, None, None, 0); + let paint = ColrPaint::glyph(ColrPaint::colr_layers(2, 0), gid('O')); + colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(gid(COLOUR_CHAR), paint)])).into(); + colr.layer_list = Some(LayerList::new(2, vec![solid(99), ColrPaint::glyph(solid(0), gid('I'))])).into(); + let font = crate::test_fonts::colr_font_with("Colrtest Empty Fill", &colr).unwrap(); + let root = art(&font, COLOUR_CHAR); + let [clipped] = children(&root) else { panic!("{:?}", children(&root).iter().map(|c| c.kind_label()).collect::>()) }; + assert!(matches!(clipped.kind, NodeKind::Group { clip: true, .. }), "the `O` still clips: {}", clipped.kind_label()); + let [clip, inner] = children(clipped) else { panic!("{:?}", children(clipped).iter().map(|c| c.kind_label()).collect::>()) }; + assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{}", clip.kind_label()); + assert_eq!(fill(inner), Paint::solid(rgb(COLR_RED))); +} + +/// A fill that paints nothing after a colour flooding the glyph leaves it that glyph filled: +/// one path, as without the empty fill. +#[test] +fn a_fill_that_paints_nothing_after_a_flood_keeps_one_path() { + use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList}; + use write_fonts::types::GlyphId16; + let bytes = colr_font(false).unwrap(); + let read = skrifa::FontRef::new(&bytes).unwrap(); + let gid = |ch| GlyphId16::new(u16::try_from(read.charmap().map(ch).unwrap().to_u32()).unwrap()); + let mut colr = Colr::new(0, None, None, 0); + let paint = ColrPaint::glyph(ColrPaint::colr_layers(2, 0), gid('O')); + colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(gid(COLOUR_CHAR), paint)])).into(); + colr.layer_list = Some(LayerList::new(2, vec![solid(0), solid(99)])).into(); + let font = crate::test_fonts::colr_font_with("Colrtest Flood Then Empty", &colr).unwrap(); + let root = art(&font, COLOUR_CHAR); + let [only] = children(&root) else { panic!("{:?}", children(&root).iter().map(|c| c.kind_label()).collect::>()) }; + assert!(matches!(only.kind, NodeKind::Path { .. }), "{}", only.kind_label()); + assert_eq!(fill(only), Paint::solid(rgb(COLR_RED))); +} + /// A sweep glyph in a font without clip boxes, its base glyph without an outline (the space's, /// as COLRv1 fonts make them): its image is as large as what it paints. #[test] 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/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 4790b642af..351c698451 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -2041,3 +2041,40 @@ fn soft_return_breaks_line_even_inside_no_break() { let lay = layout(db(), &t); assert_eq!(lay.lines.len(), 2, "soft return honors line break despite no_break"); } + +/// An East Asian glyph form (the Glyphs panel menu's Traditional Forms, JIS 78 Forms, …) draws +/// the characters with the font's glyphs of that form, and Default with its default glyphs. Needs +/// craft-fonts' BIZ UDMincho, which has traditional, expert, JIS 78, 83 and 90, full-width and +/// half-width forms and no JIS 04 forms (skipped without it). A form on one character of a run +/// changes that character only. +#[test] +fn glyph_forms_draw_the_fonts_east_asian_forms() { + use vectorcraft_doc::GlyphForm; + const FAMILY: &str = "BIZ UDMincho"; + if db().face(FAMILY, "Regular").is_none_or(|f| f.family != FAMILY) { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + } + let st = |form| CharStyle { size: 20.0, font_family: FAMILY.into(), glyph_form: form, ..CharStyle::default() }; + let glyphs = |text: &str, form| layout(db(), &TextObject::point(Point::ZERO, text, st(form))).glyphs; + let gids = |text: &str, form| glyphs(text, form).iter().map(|g| g.gid).collect::>(); + for (form, text) in + [(GlyphForm::Traditional, "亜"), (GlyphForm::Expert, "唖"), (GlyphForm::Jis78, "唖"), (GlyphForm::Jis83, "芦"), (GlyphForm::Jis90, "芦")] + { + assert_ne!(gids(text, form), gids(text, GlyphForm::Default), "{form:?} {text}"); + } + // The font has no JIS 04 forms, so the characters keep their glyphs. + assert_eq!(gids("亜唖芦", GlyphForm::Jis04), gids("亜唖芦", GlyphForm::Default)); + // Full-width Latin takes a whole em, half-width punctuation half of one. + let advance = |text: &str, form| glyphs(text, form).first().map_or(0.0, |g| g.advance); + assert!(advance("A", GlyphForm::Default) < 15.0, "{}", advance("A", GlyphForm::Default)); + assert!((advance("A", GlyphForm::FullWidth) - 20.0).abs() < 0.01, "{}", advance("A", GlyphForm::FullWidth)); + assert!((advance("、", GlyphForm::Default) - 20.0).abs() < 0.01, "{}", advance("、", GlyphForm::Default)); + assert!((advance("、", GlyphForm::HalfWidth) - 10.0).abs() < 0.01, "{}", advance("、", GlyphForm::HalfWidth)); + // Traditional Forms on the middle character only. + let mut t = TextObject::point(Point::ZERO, "亜亜亜", st(GlyphForm::Default)); + edit::style_range(&mut t.runs, 3, 6, |s| s.glyph_form = GlyphForm::Traditional); + let ids: Vec = layout(db(), &t).glyphs.iter().map(|g| g.gid).collect(); + let (plain, traditional) = (gids("亜", GlyphForm::Default), gids("亜", GlyphForm::Traditional)); + assert_eq!(ids, [plain[0], traditional[0], plain[0]]); +} diff --git a/crates/text/src/tests/warichu.rs b/crates/text/src/tests/warichu.rs index 6aee052cbd..cbefb86bb5 100644 --- a/crates/text/src/tests/warichu.rs +++ b/crates/text/src/tests/warichu.rs @@ -626,6 +626,24 @@ fn a_block_of_several_fonts_keeps_the_tallest_of_them() { assert!(first_short.0 >= plain[pair.0].0 - 1e-6 && first_short.1 >= deepest - 1e-6, "{first_short:?} {plain:?}"); } +/// The line holds each block line's characters at their own height: with a wide Line Gap, the +/// ascent of the top block line's characters and the descent of the bottom one's stay inside the +/// line. +#[test] +fn a_wide_line_gap_keeps_the_outer_block_lines_inside_the_line() { + let small = layout(db(), &point("x", style(10.0))); + let (ascent, descent) = (small.lines[0].ascent, small.lines[0].descent); + for lines in [2, 3] { + let l = layout(db(), &with_block("cdefgh", CharStyle { warichu_lines: lines, warichu_gap: 20.0, ..marked(20.0) })); + let line = &l.lines[0]; + let block = &l.glyphs[2..8]; + let top = block.iter().map(|g| g.origin.y).fold(f64::INFINITY, f64::min); + let bottom = block.iter().map(|g| g.origin.y).fold(f64::NEG_INFINITY, f64::max); + assert!(line.baseline - line.ascent <= top - ascent + 1e-6, "{lines}: {} {} {top} {ascent}", line.baseline, line.ascent); + assert!(line.baseline + line.descent >= bottom + descent - 1e-6, "{lines}: {} {} {bottom} {descent}", line.baseline, line.descent); + } +} + /// Warichu Settings on characters not marked Warichu leave their shaping alone: "fi" keeps its /// ligature when only the f has other settings. #[test] 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/enclosing_lasso.rs b/crates/tools/src/addons/enclosing_lasso.rs index 9b92f0833d..0f674aead9 100644 --- a/crates/tools/src/addons/enclosing_lasso.rs +++ b/crates/tools/src/addons/enclosing_lasso.rs @@ -134,7 +134,7 @@ impl Tool for EnclosingLassoTool { let symbols = cx.doc.symbol_boxes(); let region = (points.len() >= 3).then(|| Region::new(polygon(&points, true))).flatten(); let mut ids = if let Some(region) = region { - enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation) + enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline) .into_iter() .filter(|id| cx.doc.node(*id).is_some_and(|n| node_inside(n, &symbols, ®ion))) .collect() diff --git a/crates/tools/src/addons/enclosing_lasso/tests.rs b/crates/tools/src/addons/enclosing_lasso/tests.rs index 836e640306..a8ba79aac7 100644 --- a/crates/tools/src/addons/enclosing_lasso/tests.rs +++ b/crates/tools/src/addons/enclosing_lasso/tests.rs @@ -367,3 +367,25 @@ fn enclosing_lasso_considers_the_geometry_a_visible_compound_paints() { ); } } + +/// A loop around clipped art that the clipping path's own shape holds, but not the region a live +/// effect moved it to, selects the art in Outline view only, which draws the clipping path without +/// its effects. +#[test] +fn outline_view_loops_measure_clipped_art_by_the_plain_clipping_path() { + let (d, _, art) = doc_with_moved_clip_region(); + let s = Selection::default(); + let p = paint(); + let around = [(410.0, 410.0), (490.0, 410.0), (490.0, 490.0), (410.0, 490.0)]; + let gesture = |outline: bool| { + let cx = ToolContext { outline, ..cx(&d, &s, &p) }; + let mut tool = crate::create(ID); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 410.0, 410.0)); + for &(x, y) in &around[1..] { + tool.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)); + } + tool.pointer(&cx, &PointerEvent::new(PointerKind::Up, 410.0, 490.0)) + }; + assert_eq!(gesture(true), vec![Action::Exec("select.set".into(), json!({"ids": [art.0]}))]); + assert_eq!(gesture(false), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); +} 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/direct.rs b/crates/tools/src/direct.rs index 3030414b38..69230dc050 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -55,7 +55,7 @@ use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline}; +use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline_in_view}; use vectorcraft_doc::{AnchorRef, Node, NodeId, NodeKind, Selection, symbol_overrides}; use vectorcraft_geom::{Anchor, PathData, PathSeg, Point, Rect, Vec2}; @@ -1029,7 +1029,7 @@ impl Tool for DirectSelectionTool { out.extend(self.mesh.overlays(cx, &|id| cx.selection.contains(id))); if !self.group { if let Some(sp) = &cx.selection.symbol_part - && let Some(path) = cx.doc.node(sp.instance).and_then(|n| symbol_part_outline(cx.doc, n, &sp.path)) + && let Some(path) = cx.doc.node(sp.instance).and_then(|n| symbol_part_outline_in_view(cx.doc, n, &sp.path, cx.hit_options())) { out.push(Overlay::Path { path, color: cx.doc.layer_color(sp.instance), width: 1.0, dashed: false }); } @@ -1608,7 +1608,7 @@ impl DirectSelectionTool { // (members of groups too), each whole, as a click selects one; with an Alt-marquee, every // object it touches, each whole. if enclosed || whole { - let mut touched = vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true); + let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline); let editable = cx.doc.editable(); touched.retain(|id| editable(*id)); let picked = if enclosed { crate::select::inside(cx, r, touched) } else { touched }; @@ -1680,7 +1680,7 @@ impl DirectSelectionTool { } // Objects without anchors to pick (type, images, symbols…) are selected whole when // the marquee touches them, as with the Selection tool (#927). - for id in vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true) { + for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline) { let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })); if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) { sel.push((id, vec![])); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 7ce48bdc1e..32229158af 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2396,3 +2396,26 @@ fn type_on_a_path_shows_and_drags_its_paths_handles() { assert!((v["x"].as_f64().unwrap() - 400.0).abs() < 1e-9, "Shift keeps it straight above its anchor: {v}"); assert!(handles(&ToolContext { handles_multiple: false, ..cx(&d, &s, &p) }).is_empty()); } + +/// An Alt-marquee across clipped art where the clipping path's own shape, but not the region a +/// live effect moved it to, lets it show selects the art in Outline view only, which draws the +/// clipping path without its effects. +#[test] +fn outline_view_marquees_measure_clipped_art_by_the_plain_clipping_path() { + let (d, _, art) = doc_with_moved_clip_region(); + let s = Selection::default(); + let p = paint(); + let alt = Mods { alt: true, ..Mods::default() }; + let marquee = |outline: bool| { + let c = ToolContext { outline, ..cx(&d, &s, &p) }; + let mut t = DirectSelectionTool::new(false); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 440.0, 410.0).with_mods(alt)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 460.0, 430.0).with_mods(alt)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 460.0, 430.0).with_mods(alt)) + }; + let selects = |a: &[Action]| a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([art.0]))); + let a = marquee(true); + assert!(selects(&a), "outline: {a:?}"); + let a = marquee(false); + assert!(!selects(&a), "preview: {a:?}"); +} 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/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 1bf6a9488b..562654c3c4 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1564,9 +1564,9 @@ impl Tool for GestureTool { }; let mut area = self.area.take().filter(|a| a.fits(key, &self.points)).unwrap_or_else(|| AreaPreview::new(key, self.points[0])); area.step(&self.points, pressures); - for path in area.paths(&self.points) { - o.push(Overlay::Path { path, color, width: 1.0, dashed: false }); - } + let paths = area.paths(&self.points); + o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0 })); + o.extend(paths.live.into_iter().map(|path| Overlay::Path { path, color, width: 1.0, dashed: false })); self.area_pending.set(area.pending(&self.points)); self.area.set(Some(area)); } else if let Some(pressures) = self.size_pressures() { diff --git a/crates/tools/src/draw2/gesture/area.rs b/crates/tools/src/draw2/gesture/area.rs index 0bc0f13f25..a56322db40 100644 --- a/crates/tools/src/draw2/gesture/area.rs +++ b/crates/tools/src/draw2/gesture/area.rs @@ -13,6 +13,7 @@ //! most [`JOIN_PIECES_PER_CALL`] pieces' worth. The grid holds at most [`LISTINGS`] listings. use std::collections::{BTreeSet, HashMap}; +use std::sync::Arc; use vectorcraft_geom::{Affine, BezPath, Line, ParamCurve, PathData, PathEl, PathSeg, Point, SubPath}; use vectorcraft_pathops as po; @@ -84,10 +85,22 @@ pub(super) struct AreaWork { pub joined: usize, } +/// The paths of the outline to show ([`AreaPreview::paths`]). +pub(super) struct AreaPaths { + /// The settled pieces' outlines, joined [`BLOCK_PIECES`] at a time: a block that did not change + /// is the same shared path as in the call before. + pub settled: Vec>, + /// The growing last piece's outline and the thin line over the points not taken yet, drawn + /// over the settled ones. + pub live: Vec, +} + /// The joined outline of up to [`BLOCK_PIECES`] settled pieces. #[derive(Default)] struct Block { - path: BezPath, + /// Shared with the paths [`AreaPreview::paths`] returned: a new one only when the block is + /// joined again. + path: Arc, /// A piece in it changed since `path` was joined. stale: bool, } @@ -227,8 +240,9 @@ impl AreaPreview { /// The paths to show: the settled pieces' outlines, joined [`BLOCK_PIECES`] at a time, the /// growing last piece's and a thin line over the points of `pts` not taken yet. The joined /// paths with a changed piece are joined again, newest first, at most - /// [`JOIN_PIECES_PER_CALL`] pieces a call; the others show the path last joined. - pub(super) fn paths(&mut self, pts: &[Point]) -> Vec { + /// [`JOIN_PIECES_PER_CALL`] pieces a call; the others show the path last joined, the same + /// shared path each call. + pub(super) fn paths(&mut self, pts: &[Point]) -> AreaPaths { let settled = self.settled_count(); for b in (0..self.blocks.len()).rev() { if self.work.joined >= JOIN_PIECES_PER_CALL { @@ -243,9 +257,10 @@ impl AreaPreview { joined.extend(p.shown.elements().iter().copied()); } self.work.joined += pieces.len(); - self.blocks[b] = Block { path: joined, stale: false }; + self.blocks[b] = Block { path: Arc::new(joined), stale: false }; } - let mut out: Vec = self.blocks.iter().filter(|b| !b.path.elements().is_empty()).map(|b| b.path.clone()).collect(); + let settled_paths = self.blocks.iter().filter(|b| !b.path.elements().is_empty()).map(|b| Arc::clone(&b.path)).collect(); + let mut out = vec![]; if let Some(p) = self.pieces.get(settled).filter(|p| !p.shown.elements().is_empty()) { out.push(p.shown.clone()); } @@ -261,7 +276,7 @@ impl AreaPreview { } out.push(guide); } - out + AreaPaths { settled: settled_paths, live: out } } /// How many pieces no longer grow: all of them but a last one with room for more segments. diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index b62226692a..4db9310c79 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -2450,11 +2450,111 @@ fn the_blob_brush_and_the_eraser_outline_a_long_drag_a_bounded_amount_per_frame( } } +/// The settled paths of the outline of a long Blob Brush or Eraser drag (each the outline of up +/// to `BLOCK_PIECES` pieces) come back from one call to the next, at any zoom, as the same shared +/// paths, which the host draws again without copying or flattening them. A step of the drag +/// replaces only the paths of the pieces near it. +#[test] +fn the_settled_outline_of_a_long_drag_is_the_same_shared_path_each_frame() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let settled = |o: &[Overlay]| -> Vec> { + o.iter().filter_map(|o| if let Overlay::SharedPath { path, .. } = o { Some(std::sync::Arc::clone(path)) } else { None }).collect() + }; + let kept = |was: &[std::sync::Arc], now: &[std::sync::Arc]| { + now.iter().filter(|n| was.iter().any(|w| std::sync::Arc::ptr_eq(w, n))).count() + }; + for (id, angle, roundness, pressure) in + [("blobBrush", 0.0, 100.0, false), ("eraser", -60.0, 30.0, false), ("blobBrush", 0.0, 100.0, true), ("eraser", 45.0, 50.0, true)] + { + let mut t = GestureTool::new(id); + t.set_option("size", &json!(10)); + t.set_option("angle", &json!(angle)); + t.set_option("roundness", &json!(roundness)); + if pressure { + t.set_option("sizeMode", &json!("pressure")); + t.set_option("sizeVariation", &json!(4)); + } + let n = if pressure { 3000 } else { 6000 }; + long_area_drag(&mut t, &cx, n, |i| if pressure { 0.3 + 0.6 * ((i % 50) as f32 / 50.0) } else { 1.0 }); + drain_area(&t, &cx); + let first = settled(&t.overlays(&cx)); + assert!(first.len() > 1, "{id}: {} settled paths", first.len()); + for zoom in [1.0, 4.0, 1.0] { + let again = settled(&t.overlays(&ToolContext { zoom, ..cx })); + assert_eq!(again.len(), first.len(), "{id}"); + assert_eq!(kept(&first, &again), first.len(), "{id}: at zoom {zoom}, every settled path is the one shown before"); + } + // One step more along the drag: with Size set to Pressure each path holds 64 one-segment + // pieces, part of one turn of the drag, and the paths far from the step stay the ones shown + // before. (Without it a path holds 64 pieces of 32 segments, many turns round the circle.) + if !pressure { + continue; + } + let s = n as f64; + let r = 150.0 + 100.0 * (s * 0.0071).sin(); + let (x, y) = (300.0 + r * (s * 0.04).cos(), 300.0 + r * (s * 0.04).sin()); + t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, x, y) }); + drain_area(&t, &cx); + let after = settled(&t.overlays(&cx)); + let replaced = after.len() - kept(&first, &after); + assert!((1..=8).contains(&replaced), "{id}: {replaced} of {} settled paths replaced", after.len()); + } +} + +/// The outline a Blob Brush or Eraser drag shows does not change what its release sends: the same +/// drag sends the same command whether or not its outline was drawn along the way. +#[test] +fn drawing_the_outline_of_a_drag_does_not_change_what_its_release_sends() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + for (id, angle, roundness, pressure) in + [("blobBrush", 0.0, 100.0, false), ("blobBrush", 30.0, 40.0, true), ("eraser", -60.0, 30.0, false), ("eraser", 45.0, 50.0, true)] + { + let release = |drawn: bool| { + let mut t = GestureTool::new(id); + t.set_option("size", &json!(10)); + t.set_option("angle", &json!(angle)); + t.set_option("roundness", &json!(roundness)); + if pressure { + t.set_option("sizeMode", &json!("pressure")); + t.set_option("sizeVariation", &json!(4)); + } + for i in 0..800 { + let s = i as f64; + let r = 150.0 + 100.0 * (s * 0.0071).sin(); + let (x, y) = (300.0 + r * (s * 0.04).cos(), 300.0 + r * (s * 0.04).sin()); + let kind = if i == 0 { PointerKind::Down } else { PointerKind::Drag }; + let pressure = if pressure { 0.3 + 0.6 * ((i % 50) as f32 / 50.0) } else { 1.0 }; + t.pointer(&cx, &PointerEvent { pressure, ..PointerEvent::new(kind, x, y) }); + if drawn { + t.overlays(&cx); + } + } + if drawn { + drain_area(&t, &cx); + } + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 300.0, 300.0)) + }; + let (drawn, not_drawn) = (release(true), release(false)); + assert!(matches!(drawn.first(), Some(Action::Exec(..))), "{id}: {drawn:?}"); + assert_eq!(drawn, not_drawn, "{id}"); + } +} + /// Every flattened point of the paths `o` (the outline shown). fn shown_points(o: &[Overlay]) -> Vec<(Point, Point)> { let mut lines = vec![]; for o in o { - let Overlay::Path { path, .. } = o else { continue }; + let path = match o { + Overlay::Path { path, .. } => path, + Overlay::SharedPath { path, .. } => &**path, + _ => continue, + }; let mut pen = Point::ZERO; let mut start = Point::ZERO; vectorcraft_geom::kurbo::flatten(path.elements().iter().copied(), 0.01, |el| match el { @@ -2541,7 +2641,11 @@ fn a_long_jump_in_a_blob_brush_drag_is_outlined_a_bounded_amount_at_a_time() { let o = t.overlays(&cx); let b = o .iter() - .filter_map(|o| if let Overlay::Path { path, .. } = o { Some(vectorcraft_geom::Shape::bounding_box(path)) } else { None }) + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)), + _ => None, + }) .reduce(|a, b| a.union(b)); let Some(b) = b else { panic!("{o:?}") }; assert!((b.x0 + 0.5).abs() < 0.01 && (b.x1 - 20_000.5).abs() < 0.01, "{b:?}"); 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/lib.rs b/crates/tools/src/lib.rs index 29cf0466e1..9edf18e84d 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -71,6 +71,10 @@ pub enum Overlay { SelectionMarquee { rect: Rect, enclosed: bool, pointer: Point }, /// A path preview (e.g. pen rubber band) in a colour (RGB). Path { path: BezPath, color: [u8; 3], width: f32, dashed: bool }, + /// A solid path preview that later calls return again, as the same shared `path`, for as long + /// as it does not change (the settled outline of a long Blob Brush or Eraser drag). The host + /// can keep what it built to draw it while `path` is the same allocation. + SharedPath { path: std::sync::Arc, color: [u8; 3], width: f32 }, /// A line segment (smart guide, handle line). Line { a: Point, b: Point, color: [u8; 3], dashed: bool }, /// An anchor square: filled = selected. @@ -450,6 +454,36 @@ pub(crate) mod testutil { (d, g, clip, art) } + /// A document with the rectangle of [`doc_with_rect`] and a clip group whose clipping path, + /// (400, 400)–(500, 500), has a live effect that moves the region it clips to 100 pt right + /// (registered with [`vectorcraft_doc::hit::set_clip_region`]), over art at (420, 420)–(480, 480), + /// inside the clipping path's own shape and outside the moved region: the document, the clip + /// group and the art. + pub fn doc_with_moved_clip_region() -> (Document, NodeId, NodeId) { + fn moved(clip: &Node) -> Option> { + let mut moves = false; + clip.walk(&mut |n| moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move")); + if !moves { + return None; + } + Some(vectorcraft_doc::hit::clip_regions(clip).into_iter().next().map(|(mut bp, rule)| { + bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0))); + (bp, rule) + })) + } + vectorcraft_doc::hit::set_clip_region(moved); + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut path = Node::path(clip, shapes::rectangle(Rect::new(400.0, 400.0, 500.0, 500.0)), Default::default()); + path.appearance.effects.push(vectorcraft_doc::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let picture = Node::path(art, shapes::rectangle(Rect::new(420.0, 420.0, 480.0, 480.0)), Appearance::default_art()); + let group = + Node::new(g, vectorcraft_doc::NodeKind::Group { children: vec![std::sync::Arc::new(path), std::sync::Arc::new(picture)], clip: true }); + d.insert(Some(l), 1, group).unwrap(); + (d, g, art) + } + /// A new layer of `d`, above the others, with the unpainted rectangle `mask` as its clipping /// mask and `art` clipped by it: the layer and the clipping mask. pub fn add_masked_layer(d: &mut Document, mask: Rect, art: Node) -> (NodeId, NodeId) { 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/select.rs b/crates/tools/src/select.rs index ef8e3d4817..f63be1193e 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -40,7 +40,7 @@ use std::cell::RefCell; use std::collections::HashMap; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee, objects_at, selected_hidden_at}; +use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee_in_view, objects_at, selected_hidden_at}; use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -1157,7 +1157,7 @@ impl Tool for SelectionTool { if r.width() < Self::drag_threshold(cx) && r.height() < Self::drag_threshold(cx) { return if toggle { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] }; } - let touched = marquee(cx.doc, r, cx.isolation, false); + let touched = marquee_in_view(cx.doc, r, cx.isolation, false, cx.outline); let enclosed = marquee_enclosed(cx, enclosed, marquee_direction(cx, start, p, directional_inside)); let ids = if enclosed { inside(cx, r, touched) } else { touched }; let art = Action::Exec(if toggle { "select.toggle" } else { "select.set" }.into(), json!({ "ids": json_ids(&ids) })); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index b7af316571..3a47a9c85e 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2646,3 +2646,22 @@ fn outline_view_click_through_an_image_selects_the_path_behind() { assert!(!selects(&a, back), "preview, {picked:?} selected: {a:?}"); } } + +/// A marquee across clipped art where the clipping path's own shape, but not the region a live +/// effect moved it to, lets it show reaches the clip group in Outline view only, which draws the +/// clipping path without its effects. +#[test] +fn outline_view_marquees_measure_a_clip_group_by_its_plain_clipping_path() { + let (d, g, _) = doc_with_moved_clip_region(); + let s = Selection::default(); + let p = paint(); + let marquee = |outline: bool| { + let cx = ToolContext { outline, ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 440.0, 410.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 460.0, 430.0)); + t.pointer(&cx, &ev(PointerKind::Up, 460.0, 430.0)) + }; + assert_eq!(marquee(true), vec![Action::Exec("select.set".into(), json!({"ids": [g.0]}))]); + assert_eq!(marquee(false), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); +} 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..1cbf1cac53 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -8,10 +8,12 @@ //! while hovering, so transforms pivot exactly on a corner. A drag starts from the point it grabbed //! snapped the same way, and the pointer snaps as a drawn point does (Smart Guides: the other //! objects' anchors, centres and edges; or the grid, pixels, Snap to Point), so a corner dragged -//! onto another object's anchor scales exactly onto it. +//! onto another object's anchor scales exactly onto it. Scale stretches along the bounding box's +//! own width and height, turned with rotated objects until Reset Bounding Box; Reflect's default +//! axis is the box's vertical one, and Shift constrains a drawn axis to 45° steps from the box. use serde_json::{Value, json}; -use vectorcraft_doc::NodeId; +use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use super::target_overlays; @@ -68,9 +70,28 @@ struct Drag { /// Alt was down at the press: a click opens the dialog, a drag transforms a copy. alt: bool, bounds: Rect, + /// The angle of the selection's bounding box: Scale and Reflect act along its axes + /// ([`TransformTool::matrix_in`]). + angle: f64, + /// Anchors are selected with Direct Selection: they transform alone along the page's axes, + /// and a copy or a pattern-only drag transforms the whole objects along the box + /// ([`Drag::angle_for`]). + anchors: bool, + /// The snapped pointer and Shift at the last drag event, to work out the transform again + /// when the Alt state at the release changes what it transforms. + pointer: Point, + shift: bool, last: Affine, } +impl Drag { + /// The angle Scale and Reflect act along, for a drag that copies (`copy`) or not, and that + /// transforms only pattern tiles (`patterns_only`, the backquote key) or not. + fn angle_for(&self, copy: bool, patterns_only: bool) -> f64 { + if self.anchors && !copy && !patterns_only { 0.0 } else { self.angle } + } +} + pub struct TransformTool { kind: TransformKind, /// Custom reference point and the selection it was set for. @@ -125,6 +146,16 @@ impl TransformTool { /// Transform for dragging from `start` to `p` about `o`; returns the matrix and a readout. pub fn matrix_for(&self, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, String) { + self.matrix_in(0.0, o, start, p, shift, bounds) + } + + /// [`TransformTool::matrix_for`] with the bounding box turned by `angle` (counter-clockwise + /// degrees): Scale stretches along the box's own width and height, and Reflect's default axis + /// and Shift's 45° steps start from the box's axes. A Reflect axis drawn by the drag is the + /// line the pointer draws on the page. + pub fn matrix_in(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, String) { + let frame = OrientedBox { angle, rect: Rect::ZERO }; + let local = |v: Vec2| frame.to_doc().inverse() * v.to_point(); match self.kind { TransformKind::Rotate => { let (a, deg) = rotate_for_drag(o, start, p, shift); @@ -132,15 +163,17 @@ impl TransformTool { } TransformKind::Reflect => { let mut v = p - o; - if shift { - v = vectorcraft_geom::constrain_angle(v, 45.0); + if v.hypot() < 1e-9 { + v = (frame.to_doc() * Point::new(0.0, 1.0)).to_vec2(); + } else if shift { + v = (frame.to_doc() * vectorcraft_geom::constrain_angle(local(v).to_vec2(), 45.0).to_point()).to_vec2(); } - let theta = if v.hypot() < 1e-9 { std::f64::consts::FRAC_PI_2 } else { v.y.atan2(v.x) }; + let theta = v.y.atan2(v.x); (reflect_matrix(o, theta), format!("{:.1}°", vectorcraft_geom::normalize_deg(-theta.to_degrees()))) } TransformKind::Scale => { - let d0 = start - o; - let d1 = p - o; + let d0 = local(start - o).to_vec2(); + let d1 = local(p - o).to_vec2(); let ratio = |a: f64, b: f64| if a.abs() > 1e-6 { b / a } else { 1.0 }; let (mut sx, mut sy) = (ratio(d0.x, d1.x), ratio(d0.y, d1.y)); if shift { @@ -151,7 +184,7 @@ impl TransformTool { } let clamp = |s: f64| if s.abs() < 1e-4 { 1e-4f64.copysign(s) } else { s }; let (sx, sy) = (clamp(sx), clamp(sy)); - (about(o, Affine::scale_non_uniform(sx, sy)), format!("W: {:.1}%\nH: {:.1}%", sx * 100.0, sy * 100.0)) + (about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), format!("W: {:.1}%\nH: {:.1}%", sx * 100.0, sy * 100.0)) } TransformKind::Shear => { // The shear axis follows the dominant drag direction. Shift keeps the drag on that @@ -227,7 +260,21 @@ impl Tool for TransformTool { // Alt: decided on release. A click sets the point and opens the dialog; a drag // transforms a copy about the reference point as it was. let origin = self.reference_point(cx).unwrap_or(bounds.center()); - self.drag = Some(Drag { start: p, pick, origin, began: false, alt: ev.mods.alt, bounds, last: Affine::IDENTITY }); + let anchors = vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()).is_some(); + let angle = selection_box(cx).map_or(0.0, |b| b.angle); + self.drag = Some(Drag { + start: p, + pick, + origin, + began: false, + alt: ev.mods.alt, + bounds, + angle, + anchors, + pointer: p, + shift: false, + last: Affine::IDENTITY, + }); vec![] } PointerKind::Drag => { @@ -247,8 +294,8 @@ impl Tool for TransformTool { } let (p, guides) = self.snap.as_ref().map_or((p, vec![]), |s| s.snap(cx, p)); self.hover = guides; - let (m, text) = self.matrix_for(d.origin, d.pick, p, ev.mods.shift, d.bounds); - d.last = m; + let (m, text) = self.matrix_in(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, p, ev.mods.shift, d.bounds); + (d.last, d.pointer, d.shift) = (m, p, ev.mods.shift); self.drag = Some(d); self.measure = Some((p, text)); out.push(preview(m, ev.mods.alt, ev.backquote)); @@ -257,8 +304,15 @@ impl Tool for TransformTool { PointerKind::Up => { let Some(d) = self.end_drag() else { return vec![] }; if d.began { - // The Alt state at release decides whether the result is a copy. - vec![preview(d.last, ev.mods.alt, ev.backquote), Action::Commit] + // The Alt and backquote states at release decide whether the result is a copy + // or moves only pattern tiles, and with anchors selected, whether it acts + // along the box or the page. + let m = if d.anchors { + self.matrix_in(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, d.pointer, d.shift, d.bounds).0 + } else { + d.last + }; + vec![preview(m, ev.mods.alt, ev.backquote), Action::Commit] } else { // A click sets the reference point; with Alt, it opens the dialog too. self.origin = Some((d.pick, cx.selection.objects.clone())); @@ -272,6 +326,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 }; @@ -578,6 +633,70 @@ mod tests { assert!((m * Point::new(100.0, 120.0)).distance(Point::new(200.0, 120.0)) < 1e-9); } + /// With the selection turned by 30°, a Scale drag stretches along the box's own sides, and + /// Reflect's default axis and Shift steps start from the box's axes while a drawn axis stays + /// the line drawn on the page. + #[test] + fn scale_and_reflect_drags_follow_a_turned_bounding_box() { + let (mut d, id) = doc_with_rect(); + let c = Point::new(150.0, 150.0); + d.node_mut(id).unwrap().transform(about(c, Affine::rotate(-30f64.to_radians())), false); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut cx = cx(&d, &s, &p); + (cx.smart_guides, cx.snap_to_point) = (false, false); + let frame = OrientedBox { angle: 30.0, rect: Rect::ZERO }; + let along = |x: f64, y: f64| c + (frame.to_doc() * Point::new(x, y)).to_vec2(); + // The right side's middle dragged out to twice its distance: the width doubles along the + // box, and the height stays. + let mut t = TransformTool::new(TransformKind::Scale); + let (from, to) = (along(50.0, 0.0), along(100.0, 0.0)); + t.pointer(&cx, &ev(PointerKind::Down, from.x, from.y)); + let a = t.pointer(&cx, &ev(PointerKind::Drag, to.x, to.y)); + let m = matrix(&a[1]); + assert!((m * along(50.0, 50.0)).distance(along(100.0, 50.0)) < 1e-9, "{m:?}"); + assert!((m * along(0.0, 50.0)).distance(along(0.0, 50.0)) < 1e-9, "{m:?}"); + assert!(a.iter().any(|x| matches!(x, Action::Preview(..)))); + + let t = TransformTool::new(TransformKind::Reflect); + // No axis drawn: the box's vertical axis. + let (m, _) = t.matrix_in(30.0, c, c, c, false, Rect::ZERO); + assert!((m * along(40.0, 10.0)).distance(along(-40.0, 10.0)) < 1e-9, "{m:?}"); + // Shift: 39° from the box's horizontal axis steps to 45° from it. + let (m, text) = t.matrix_in(30.0, c, c, along(10.0, 8.0), true, Rect::ZERO); + assert!((m * along(10.0, 0.0)).distance(along(0.0, 10.0)) < 1e-9, "{m:?}"); + assert_eq!(text, "-15.0°"); + // A drawn axis is the line on the page. + let (m, _) = t.matrix_in(30.0, c, c, c + Vec2::new(0.0, -50.0), false, Rect::ZERO); + assert!((m * Point::new(100.0, 120.0)).distance(Point::new(200.0, 120.0)) < 1e-9, "{m:?}"); + + // Anchors selected with Direct Selection scale alone along the page's axes; Alt at the + // release copies the whole object, which scales along its box. + let mut s = s.clone(); + s.anchors.insert(id, [(0, 0), (0, 1)].into()); + let mut cx = crate::testutil::cx(&d, &s, &p); + (cx.smart_guides, cx.snap_to_point) = (false, false); + let page_axes = |m: Affine| m.as_coeffs()[1].abs() < 1e-9 && m.as_coeffs()[2].abs() < 1e-9; + let (from, to) = (along(50.0, 0.0), along(100.0, 30.0)); + for copy in [false, true] { + let mut t = TransformTool::new(TransformKind::Scale); + t.pointer(&cx, &ev(PointerKind::Down, from.x, from.y)); + let a = t.pointer(&cx, &ev(PointerKind::Drag, to.x, to.y)); + assert!(page_axes(matrix(&a[1])), "{a:?}"); + let up = t.pointer(&cx, &ev(PointerKind::Up, to.x, to.y).with_mods(if copy { alt() } else { Mods::default() })); + assert_eq!(page_axes(matrix(&up[0])), !copy, "copy {copy}: {up:?}"); + } + // With the backquote key the drag moves only the whole objects' pattern tiles, which + // scale along the box, both while dragging and at the release. + let mut t = TransformTool::new(TransformKind::Scale); + t.pointer(&cx, &ev(PointerKind::Down, from.x, from.y)); + let a = t.pointer(&cx, &PointerEvent { backquote: true, ..ev(PointerKind::Drag, to.x, to.y) }); + assert!(!page_axes(matrix(&a[1])), "{a:?}"); + let up = t.pointer(&cx, &PointerEvent { backquote: true, ..ev(PointerKind::Up, to.x, to.y) }); + assert!(!page_axes(matrix(&up[0])), "{up:?}"); + } + #[test] fn shear_horizontal_keeps_origin_row() { let t = TransformTool::new(TransformKind::Shear); diff --git a/crates/trace/src/params.rs b/crates/trace/src/params.rs index 9c430dd19d..156d6fbef2 100644 --- a/crates/trace/src/params.rs +++ b/crates/trace/src/params.rs @@ -241,19 +241,19 @@ pub fn preset(name: &str) -> Option { // many as its tones need where it is not. // (Color detail 85: a colour on a hundredth of the picture is still one of its colours.) "auto color" => TraceParams { palette: Palette::Automatic, color_detail: 85.0, ..color(6, 65.0, 60.0, 16, Method::Abutting) }, - "high fidelity photo" => color(64, 90.0, 25.0, 4, Method::Overlapping), - "low fidelity photo" => color(20, 60.0, 50.0, 12, Method::Overlapping), - "3 colors" => color(3, 60.0, 60.0, 20, Method::Abutting), - "6 colors" => color(6, 65.0, 60.0, 16, Method::Abutting), - "16 colors" => color(16, 70.0, 55.0, 10, Method::Abutting), - "shades of gray" => TraceParams { mode: Mode::Grayscale, colors: 8, paths: 60.0, corners: 50.0, noise: 10, method: Method::Overlapping, ..d }, - "black and white logo" => bw(128, 95.0, 80.0, 8, true), - "sketched art" => bw(150, 50.0, 50.0, 100, false), - "silhouettes" => bw(200, 40.0, 60.0, 30, false), - "line art" => bw(128, 80.0, 70.0, 10, false), - "technical drawing" => bw(128, 95.0, 90.0, 4, true), + "high fidelity photo" => color(64, 50.0, 50.0, 5, Method::Overlapping), + "low fidelity photo" => color(20, 50.0, 50.0, 10, Method::Overlapping), + "3 colors" => color(3, 50.0, 50.0, 15, Method::Abutting), + "6 colors" => color(6, 50.0, 50.0, 15, Method::Abutting), + "16 colors" => color(16, 50.0, 50.0, 15, Method::Abutting), + "shades of gray" => TraceParams { mode: Mode::Grayscale, colors: 8, paths: 50.0, corners: 50.0, noise: 15, method: Method::Overlapping, ..d }, + "black and white logo" => bw(128, 50.0, 75.0, 25, true), + "sketched art" => bw(150, 50.0, 50.0, 20, false), + "silhouettes" => bw(200, 50.0, 50.0, 90, false), + "line art" => bw(128, 50.0, 75.0, 20, false), + "technical drawing" => bw(128, 50.0, 100.0, 1, true), // Black outlines: lines as stroked centre lines, wider areas as stroked outlines. - "outline" => TraceParams { fills: false, strokes: true, ..bw(128, 80.0, 70.0, 10, false) }, + "outline" => TraceParams { fills: false, strokes: true, ..bw(128, 50.0, 75.0, 20, false) }, // Flat-colour logos: colours found automatically, edges placed to a fraction of a pixel. "flat logo" => TraceParams { mode: Mode::Logo, colors: 8, paths: 60.0, corners: 50.0, noise: 6, snap_curves_to_lines: true, ..d }, _ => return None, diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 59f92021c0..2e24eb80bb 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -892,6 +892,35 @@ fn presets_resolve() { assert!(preset("nope").is_none()); } +#[test] +fn presets_have_their_paths_corners_and_noise() { + let expected: &[(&str, f64, f64, u32)] = &[ + ("Default", 50.0, 75.0, 25), + ("High Fidelity Photo", 50.0, 50.0, 5), + ("Low Fidelity Photo", 50.0, 50.0, 10), + ("3 Colors", 50.0, 50.0, 15), + ("6 Colors", 50.0, 50.0, 15), + ("16 Colors", 50.0, 50.0, 15), + ("Shades of Gray", 50.0, 50.0, 15), + ("Black and White Logo", 50.0, 75.0, 25), + ("Sketched Art", 50.0, 50.0, 20), + ("Silhouettes", 50.0, 50.0, 90), + ("Line Art", 50.0, 75.0, 20), + ("Technical Drawing", 50.0, 100.0, 1), + ("Outline", 50.0, 75.0, 20), + ]; + for &(name, paths, corners, noise) in expected { + let p = preset(name).unwrap(); + assert_eq!((p.paths, p.corners, p.noise), (paths, corners, noise), "{name}"); + } + // The color counts stay as they were. + let colors: Vec = ["High Fidelity Photo", "Low Fidelity Photo", "3 Colors", "6 Colors", "16 Colors", "Shades of Gray"] + .iter() + .map(|n| preset(n).unwrap().colors) + .collect(); + assert_eq!(colors, [64, 20, 3, 6, 16, 8]); +} + #[test] fn params_json_roundtrip_and_partial() { let p = preset("6 Colors").unwrap(); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 412dbcb4ef..658068f79b 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -85,6 +85,7 @@ impl VectorcraftApp { hidden_chars: Default::default(), spelling: Default::default(), selection_marks: Default::default(), + shared_paths: Default::default(), selection_box: None, selection_bounds: None, content_bounds: None, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 286b4d4d02..ae2ddc5dae 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -51,6 +51,9 @@ pub struct CanvasCache { /// The selected objects' outlines, anchors and handles as drawn in the last frame. A frame that /// does not draw them drops them ([`canvas::show`]). pub selection_marks: canvas::SelectionMarks, + /// The meshes the tools' shared paths (a long Blob Brush or Eraser drag's settled outline) were + /// drawn with in the last frame. A frame that does not draw them drops them ([`canvas::show`]). + pub shared_paths: canvas::SharedPaths, /// [`VectorcraftApp::selection_box`] for (document uid, revision, Use Preview Bounds and /// Measure Type by Glyph Bounds). pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option)>, @@ -164,6 +167,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..7095e6a9ed 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -60,6 +60,7 @@ use input::handle_input; use outline::KEY_OUTLINE; #[cfg(test)] use outline::{OVERLAY_MAX_ANCHORS, c32, node_outline, walk_drawn}; +pub use overlays::SharedPaths; #[cfg(test)] use overlays::selected_anchor; use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; @@ -244,6 +245,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let hidden_chars = std::mem::take(&mut app.canvas.hidden_chars); // The selection's kept marks. Likewise, a frame that does not draw them drops them. let selection_marks = std::mem::take(&mut app.canvas.selection_marks); + // The meshes of the tools' shared paths. Likewise, a frame that does not draw the tools' + // overlays drops them. + let mut shared_paths = std::mem::take(&mut app.canvas.shared_paths); // A release ends the Image Trace panel's eye-button hold, also when the panel is no longer // drawn, so a later press elsewhere does not show the source image. if app.ui.trace_hold_source.is_some() && !ui.input(|i| i.pointer.any_down()) { @@ -415,7 +419,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { original_path_overlay(app, &painter, &xf); let overlays = selection_visuals(app, &painter, &xf, (hidden_chars, selection_marks, hover_still), revolve_edit, view_info); - draw_overlays(&painter, &xf, &overlays, &t, HandleLook::of(&app.session.prefs)); + draw_overlays(&painter, &xf, &overlays, &t, HandleLook::of(&app.session.prefs), &mut shared_paths); + app.canvas.shared_paths = shared_paths; if !revolve_edit { shaper_widget_overlay(app, &painter, &xf); crate::panels::three_d::paint_graphic_handles(app, &painter, &xf); @@ -631,6 +636,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 +901,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 +942,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 +998,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 +1012,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/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 119c811d0b..6e222cc405 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -1,8 +1,14 @@ +use std::collections::HashMap; +use std::sync::Arc; + +use egui::Mesh; +use egui::epaint::{TessellationOptions, Tessellator}; + use super::artboards::names_an_artboard; use super::input::marquee_through; use super::outline::{KEY_OUTLINE, c32, node_outline, selection_hit_at, stroke_path, to_screen_path, too_many_anchors}; use super::selection_marks::{MarkOptions, SelectionMarks}; -use super::{Color32, CornerRadius, NodeKind, Overlay, Pos2, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, vec2}; +use super::{BezPath, Color32, CornerRadius, NodeKind, Overlay, Pos2, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, vec2}; pub(super) fn hover_highlight(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { let Some(h) = app.hover_doc else { return }; @@ -351,7 +357,75 @@ pub(super) fn ime_geometry(app: &mut VectorcraftApp, ctx: &egui::Context, xf: &X app.ime_caret_rect = Some((r, r)); } -pub(super) fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t: &Tokens, look: HandleLook) { +/// The meshes the tools' shared paths ([`Overlay::SharedPath`]) were drawn with in the last frame +/// ([`crate::CanvasCache::shared_paths`]). Each is kept with its path, by the path's allocation, and +/// with the view, clip and stroke it was built for: a path that comes back unchanged at the same view +/// is drawn with the same mesh, without flattening or tessellating it again. A frame keeps only the +/// meshes it draws; a frame that draws no overlays drops them all ([`super::show`]). +#[derive(Default)] +pub struct SharedPaths { + pub(super) meshes: HashMap, +} + +pub(super) struct SharedMesh { + /// Held so that the allocation, the key of the map, is not reused while the mesh is kept. + path: Arc, + key: SharedKey, + pub(super) mesh: Arc, +} + +/// What a shared path's mesh depends on besides the path. +#[derive(Clone, Copy, PartialEq)] +struct SharedKey { + /// The view's mapping onto the screen ([`Xf::affine`]). + view: [f64; 6], + /// The painter's clip: the lines of the path outside it have no triangles in the mesh. + clip: egui::Rect, + stroke: Stroke, + pixels_per_point: f32, + tessellation: TessellationOptions, +} + +impl SharedPaths { + /// The mesh that draws `path` with `s` at the view `xf` with the painter `p`: the one kept in + /// this frame or in `last` (the last frame's) when it was built for the same, else a new one. + /// It is kept for the next frame. + fn mesh(&mut self, last: &mut HashMap, path: &Arc, xf: &Xf, s: Stroke, p: &egui::Painter) -> Arc { + let ctx = p.ctx(); + let key = SharedKey { + view: xf.affine().as_coeffs(), + clip: p.clip_rect(), + stroke: s, + pixels_per_point: ctx.pixels_per_point(), + tessellation: ctx.tessellation_options(|o| *o), + }; + let at = Arc::as_ptr(path) as usize; + let fits = |m: &SharedMesh| m.key == key && Arc::ptr_eq(&m.path, path); + if let Some(kept) = self.meshes.get(&at).filter(|m| fits(m)) { + return Arc::clone(&kept.mesh); + } + let kept = match last.remove(&at).filter(|m| fits(m)) { + Some(kept) => kept, + None => { + let font_image_size = ctx.fonts(|f| f.font_image_size()); + let mut tessellator = Tessellator::new(key.pixels_per_point, key.tessellation, font_image_size, vec![]); + tessellator.set_clip_rect(key.clip); + let mut mesh = Mesh::default(); + for line in to_screen_path(path, xf) { + tessellator.tessellate_shape(Shape::line(line, s), &mut mesh); + } + SharedMesh { path: Arc::clone(path), key, mesh: Arc::new(mesh) } + } + }; + let mesh = Arc::clone(&kept.mesh); + self.meshes.insert(at, kept); + mesh + } +} + +pub(super) fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t: &Tokens, look: HandleLook, shared: &mut SharedPaths) { + // The meshes kept from the last frame; those this frame does not draw are dropped. + let mut last = std::mem::take(&mut shared.meshes); for o in overlays { match o { // Where the tools select: the document rectangle, turned with the view. @@ -389,6 +463,12 @@ pub(super) fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t: stroke_path(p, path, xf, s); } } + Overlay::SharedPath { path, color, width } => { + let mesh = shared.mesh(&mut last, path, xf, Stroke::new(*width, c32(*color)), p); + if !mesh.is_empty() { + p.add(Shape::mesh(mesh)); + } + } Overlay::Line { a, b, color, dashed } => { let s = Stroke::new(1.0, c32(*color)); let (a, b) = (xf.to_screen(*a), xf.to_screen(*b)); 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..3e21381cb1 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -17,6 +17,7 @@ fn marquee_feedback_explains_the_rule_and_stays_on_canvas() { &[Overlay::SelectionMarquee { rect: Rect::new(20.0, y - 60.0, 300.0, y), enclosed, pointer: Point::new(315.0, y) }], &t, overlays::HandleLook::of(&prefs), + &mut overlays::SharedPaths::default(), ); } }; @@ -61,6 +62,89 @@ fn marquee_feedback_explains_the_rule_and_stays_on_canvas() { } } +/// A tool's shared path ([`Overlay::SharedPath`], the settled outline of a long Blob Brush or Eraser +/// drag) is drawn with the mesh kept from the last frame while the path and the view stay the same, +/// and that mesh is the one the plain path draws. Another path, even one with the same elements, or +/// a new view builds a new mesh, and a frame keeps only the meshes it draws. +#[test] +fn a_shared_tool_path_is_drawn_with_the_mesh_kept_while_it_and_the_view_stay() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, crate::theme::Brightness::MediumDark); + let prefs = vectorcraft_engine::Prefs::default(); + let mut shared = overlays::SharedPaths::default(); + let frame = |overlays: &[Overlay], zoom: f64, shared: &mut overlays::SharedPaths| { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + let t = Tokens::get(ui.ctx()); + let xf = Xf { rect: ui.max_rect(), zoom, center: Point::new(200.0, 150.0), rot: 0.3 }; + overlays::draw_overlays(ui.painter(), &xf, overlays, &t, overlays::HandleLook::of(&prefs), shared); + }); + out.textures_delta.clear(); + out.shapes + }; + let meshes = |shapes: &[egui::epaint::ClippedShape]| -> Vec> { + shapes.iter().filter_map(|c| if let Shape::Mesh(m) = &c.shape { Some(std::sync::Arc::clone(m)) } else { None }).collect() + }; + let one = |shapes: Vec| { + let found = meshes(&shapes); + assert_eq!(found.len(), 1, "one mesh"); + std::sync::Arc::clone(&found[0]) + }; + let mut path = BezPath::new(); + path.move_to((60.0, 80.0)); + path.curve_to((120.0, 20.0), (220.0, 260.0), (330.0, 120.0)); + path.close_path(); + path.move_to((150.0, 150.0)); + path.line_to((250.0, 160.0)); + let a = std::sync::Arc::new(path.clone()); + let b = std::sync::Arc::new(path.clone()); + let shared_of = |p: &std::sync::Arc| Overlay::SharedPath { path: std::sync::Arc::clone(p), color: [0x80, 0x80, 0x80], width: 1.0 }; + let first = one(frame(&[shared_of(&a)], 1.0, &mut shared)); + assert!(!first.vertices.is_empty()); + let again = one(frame(&[shared_of(&a)], 1.0, &mut shared)); + assert!(std::sync::Arc::ptr_eq(&first, &again), "the same path at the same view is drawn with the kept mesh"); + // The plain path draws the same triangles. + let plain = frame(&[Overlay::Path { path: path.clone(), color: [0x80, 0x80, 0x80], width: 1.0, dashed: false }], 1.0, &mut shared); + assert!(shared.meshes.is_empty(), "a frame that draws no shared path keeps no mesh"); + let lines: Vec<_> = plain.into_iter().filter(|c| matches!(c.shape, Shape::Path(_))).collect(); + assert_eq!(lines.len(), 2, "a line for each subpath"); + let tessellated = ctx.tessellate(lines, ctx.pixels_per_point()); + let triangles: Vec<_> = tessellated + .into_iter() + .filter_map(|c| if let egui::epaint::Primitive::Mesh(m) = c.primitive { Some(m) } else { None }) + .flat_map(|m| m.vertices) + .map(|v| (v.pos, v.color)) + .collect(); + assert_eq!(triangles, first.vertices.iter().map(|v| (v.pos, v.color)).collect::>()); + // A dropped mesh, another allocation of the same path and a new view each build a new mesh. + let rebuilt = one(frame(&[shared_of(&a)], 1.0, &mut shared)); + assert!(!std::sync::Arc::ptr_eq(&first, &rebuilt) && *first == *rebuilt); + let other = one(frame(&[shared_of(&b)], 1.0, &mut shared)); + assert!(!std::sync::Arc::ptr_eq(&rebuilt, &other) && *rebuilt == *other); + let zoomed = one(frame(&[shared_of(&b)], 2.0, &mut shared)); + assert!(!std::sync::Arc::ptr_eq(&other, &zoomed) && *other != *zoomed); + // Two paths in one frame: each keeps its own mesh, and only those two are kept. + let both = meshes(&frame(&[shared_of(&a), shared_of(&b)], 2.0, &mut shared)); + let both_again = meshes(&frame(&[shared_of(&a), shared_of(&b)], 2.0, &mut shared)); + assert_eq!(both.len(), 2); + assert!(both.iter().zip(&both_again).all(|(x, y)| std::sync::Arc::ptr_eq(x, y))); + assert!(std::sync::Arc::ptr_eq(&both[1], &zoomed), "b at zoom 2 was kept from its frame"); + assert_eq!(shared.meshes.len(), 2); + // A path off the canvas gets no triangles and draws nothing, and the lines of one partly off + // it are left out of its mesh. + let mut far = path.clone(); + far.apply_affine(vectorcraft_geom::Affine::translate((5000.0, 5000.0))); + let far = std::sync::Arc::new(far); + assert!(meshes(&frame(&[shared_of(&far)], 1.0, &mut shared)).is_empty()); + assert!(shared.meshes.values().all(|m| m.mesh.is_empty()) && shared.meshes.len() == 1); + let mut half = path.clone(); + half.move_to((5000.0, 5000.0)); + half.line_to((5100.0, 5000.0)); + let half = one(frame(&[shared_of(&std::sync::Arc::new(half))], 1.0, &mut shared)); + assert_eq!(*half, *first, "the subpath off the canvas adds no triangles"); +} + #[test] fn subpixel_dock_layout_does_not_change_pointer_document_coordinates() { let mut observed = Vec::new(); @@ -2717,6 +2801,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 +5745,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 +6117,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/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index e807df7b01..8915c48216 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -48,6 +48,8 @@ const OT_SWITCHES: &[(&str, &str)] = &[ ("ot_titl", "titl"), ("ot_ordn", "ordn"), ("ot_frac", "frac"), + ("ot_hkna", "hkna"), + ("ot_ital", "ital"), ]; /// The feature tags the Figure menu sets. const FIGURE_TAGS: [&str; 4] = ["tnum", "onum", "pnum", "lnum"]; @@ -56,8 +58,21 @@ const FIGURE_VALUES: [&str; 5] = ["default", "tabularLining", "proportionalLinin /// The values of the Position field, in the order of the OpenType panel's Position menu. const POSITION_VALUES: [&str; 5] = ["default", "superscript", "subscript", "numerator", "denominator"]; /// The fields of OpenType Features. -const OT_FIELDS: &[&str] = - &["ot_figure", "ot_position", "ot_liga", "ot_calt", "ot_dlig", "ot_swsh", "ot_salt", "ot_titl", "ot_ordn", "ot_frac", "ot_sets"]; +const OT_FIELDS: &[&str] = &[ + "ot_figure", + "ot_position", + "ot_liga", + "ot_calt", + "ot_dlig", + "ot_swsh", + "ot_salt", + "ot_titl", + "ot_ordn", + "ot_frac", + "ot_hkna", + "ot_ital", + "ot_sets", +]; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Character Style Options").into(), @@ -106,6 +121,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { "ot_titl", "ot_ordn", "ot_frac", + "ot_hkna", + "ot_ital", "ot_sets", "section", ] @@ -926,6 +943,8 @@ pub(crate) fn opentype_body(ui: &mut egui::Ui, d: &mut Dialog) { ("ot_titl", tl!("Titling Alternates")), ("ot_ordn", tl!("Ordinals")), ("ot_frac", tl!("Fractions")), + ("ot_hkna", tl!("H or V Style")), + ("ot_ital", tl!("Roman Italics")), ] { switch(ui, d, key, caption, true); } @@ -2042,6 +2061,23 @@ mod tests { assert_eq!(edited_attrs(&d).unwrap()["features"], json!(["frac"])); } + /// H or V Style and Roman Italics are on, off or unset switches of OpenType Features: they show + /// the style's `hkna` and `ital` tags, a changed switch replaces its tag and keeps the others, an + /// unset one removes it, and a style without them keeps none. + #[test] + fn kana_style_and_roman_italics_are_opentype_switches() { + let mut d = dialog_for(json!({"features": ["hkna", "-ital", "dlig"]})); + assert_eq!((&d.fields["ot_hkna"], &d.fields["ot_ital"]), (&json!(true), &json!(false))); + assert_eq!(edited_attrs(&d).unwrap()["features"], json!(["hkna", "-ital", "dlig"]), "untouched"); + d.fields.insert("ot_ital".into(), json!(true)); + d.fields.insert("ot_hkna".into(), Value::Null); + assert_eq!(edited_attrs(&d).unwrap()["features"], json!(["dlig", "ital"])); + let mut d = dialog_for(json!({})); + assert!(d.fields["ot_hkna"].is_null() && d.fields["ot_ital"].is_null()); + d.fields.insert("ot_hkna".into(), json!(true)); + assert_eq!(edited_attrs(&d).unwrap()["features"], json!(["hkna"])); + } + #[test] fn color_and_opentype_sections_show_their_controls() { let mut d = dialog_for(json!({})); @@ -2066,6 +2102,8 @@ mod tests { "Titling Alternates", "Ordinals", "Fractions", + "H or V Style", + "Roman Italics", "Stylistic Sets", "ss01", "ss20", diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 777c872494..cd089e04bd 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -23,7 +23,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { confirm, preview: true, // Load Texture… adds the texture it reads. - passes: |d, field| field == vectorcraft_effects::pixel::TEXTURE_IMAGE && matches!(d.str("__effect").as_str(), GLASS | TEXTURIZER), + passes: |d, field| field == vectorcraft_effects::pixel::TEXTURE_IMAGE && loads_texture(&d.str("__effect")), // OK could only fail the same way: off, beside the reason the dialog shows (#6140). ok_enabled: Some(|_, d| !(vectorcraft_effects::is_three_d(&d.str("__effect")) && d.fields.contains_key(form::REFUSED))), ..DialogSpec::FORM @@ -220,6 +220,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } None if id == GLASS => glass_fields(app, ui, d, GLASS), None if id == TEXTURIZER => glass_fields(app, ui, d, TEXTURIZER), + None if id == ROUGH_PASTELS => glass_fields(app, ui, d, ROUGH_PASTELS), None if id == TRANSFORM => transform_fields(ui, d, app.session.general_unit()), None if id == SCRIBBLE => scribble_fields(ui, d, app.session.general_unit()), None if id == ZIG_ZAG || id == ROUGHEN => size_fields(ui, d, &id, app.session.general_unit()), @@ -227,6 +228,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,20 +289,148 @@ 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…). const TEXTURIZER: &str = "texture.texturizer"; +/// The Rough Pastels effect (Effect › Artistic › Rough Pastels…). +const ROUGH_PASTELS: &str = "artistic.roughPastels"; -/// Glass and Texturizer: parameters, the Texture menu ending with Loaded Texture once a texture is -/// loaded, and Load Texture… with the loaded texture's size. Returns whether the values differ from -/// those last previewed. +/// Does effect `id` have Load Texture… in its dialog (Glass, Texturizer, Rough Pastels)? +fn loads_texture(id: &str) -> bool { + matches!(id, GLASS | TEXTURIZER | ROUGH_PASTELS) +} + +/// Glass, Texturizer and Rough Pastels: parameters, the Texture menu ending with Loaded Texture +/// once a texture is loaded, and Load Texture… with the loaded texture's size. Returns whether the +/// values differ from those last previewed. fn glass_fields(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: &str) -> bool { use vectorcraft_effects::pixel::{TEXTURE_IMAGE, texture}; // The stored texture is shown as its size, not as a text field. let stored = d.fields.remove(TEXTURE_IMAGE); let size = stored.as_ref().and_then(Value::as_str).and_then(texture).map(|t| t.size()); - let menu = if id == TEXTURIZER { texturizer_textures(size.is_some()) } else { glass_textures(size.is_some()) }; + let menu = if id == GLASS { glass_textures(size.is_some()) } else { texturizer_textures(size.is_some()) }; let doc = vectorcraft_effects::effect_info(id).map(|e| e.params).unwrap_or_default(); let unit = app.session.general_unit(); let pick = |k: &str| if k == "texture" { Some(menu) } else { choices(id, k) }; @@ -316,11 +446,18 @@ fn glass_fields(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: widgets::dim_label(ui, &format!("{w} × {h} px")); } }); - if load - && let Err(e) = crate::picks::in_dialog(app, d, load_texture) - && e != "cancelled" - { - app.status(e); + if load { + // The Effect Gallery's Settings draw in a dialog of their own: its answer goes to the gallery. + let loaded = if d.fields.contains_key(super::effect_gallery::SETTINGS) { + super::effect_gallery::load_texture(app, d) + } else { + crate::picks::in_dialog(app, d, load_texture) + }; + if let Err(e) = loaded + && e != "cancelled" + { + app.status(e); + } } values_changed(d) } @@ -331,7 +468,8 @@ fn glass_textures(loaded: bool) -> form::Choices { if loaded { &GLASS_TEXTURES_LOADED } else { &GLASS_TEXTURES } } -/// Texturizer's Texture menu, ending with Loaded Texture once a texture is `loaded`. +/// Texturizer's and Rough Pastels' Texture menu, ending with Loaded Texture once a texture is +/// `loaded`. fn texturizer_textures(loaded: bool) -> form::Choices { use vectorcraft_effects::pixel::{TEXTURES, TEXTURES_LOADED}; if loaded { &TEXTURES_LOADED } else { &TEXTURES } @@ -339,7 +477,7 @@ fn texturizer_textures(loaded: bool) -> form::Choices { /// Glass's Load Texture…: an image file the user picks, read into `textureImage` as Glass stores /// it and picked in the Texture menu. -fn load_texture(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { +pub(super) fn load_texture(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { use vectorcraft_engine::cmd::fileio; let filters = crate::FilePick::filters(fileio::FORMATS.iter().filter(|f| f.read && f.raster).map(|f| (f.label, fileio::read_extensions(f)))); let path = crate::picks::open(app, &crate::FilePick { filters, ..Default::default() }).ok_or("cancelled")?; @@ -366,8 +504,10 @@ fn choices(effect: &str, key: &str) -> Option { ("sketch.halftonePattern", "patternType") => Some(&vectorcraft_effects::pixel::HALFTONE_TYPES), ("sketch.plaster", "lightDirection") => Some(&vectorcraft_effects::pixel::LIGHT_DIRECTIONS), ("texture.grain", "grainType") => Some(&vectorcraft_effects::pixel::GRAIN_TYPES), - ("texture.texturizer" | "artistic.underpainting" | "sketch.conteCrayon", "texture") => Some(&vectorcraft_effects::pixel::TEXTURES), - ("sketch.basRelief" | "texture.texturizer" | "artistic.underpainting" | "sketch.conteCrayon", "lightDirection") => { + ("texture.texturizer" | "artistic.underpainting" | "artistic.roughPastels" | "sketch.conteCrayon", "texture") => { + Some(&vectorcraft_effects::pixel::TEXTURES) + } + ("sketch.basRelief" | "texture.texturizer" | "artistic.underpainting" | "artistic.roughPastels" | "sketch.conteCrayon", "lightDirection") => { Some(&vectorcraft_effects::pixel::LIGHT_DIRECTIONS) } ("video.deinterlace", "eliminate") => Some(&[("Odd Fields", "odd"), ("Even Fields", "even")]), @@ -425,10 +565,10 @@ pub(super) fn own_choices(effect: &str, key: &str, cmyk: bool) -> Option, cmyk: bool) -> Option> { if let Some(plugin) = vectorcraft_plugins::effect::installed(effect) { return plugin.manifest().param(key).and_then(|p| match &p.spec { @@ -439,7 +579,7 @@ pub(crate) fn shown_choices(effect: &str, key: &str, params: &Map if let Some(own) = own_choices(effect, key, cmyk) { return Some(own.into_iter().map(|(label, value)| (tl!(label).to_string(), value.to_string())).collect()); } - let options = if (effect == GLASS || effect == TEXTURIZER) && key == "texture" { + let options = if loads_texture(effect) && key == "texture" { use vectorcraft_effects::pixel::{TEXTURE_IMAGE, texture}; let loaded = params.get(TEXTURE_IMAGE).and_then(Value::as_str).and_then(texture).is_some(); if effect == GLASS { glass_textures(loaded) } else { texturizer_textures(loaded) } @@ -1063,6 +1203,45 @@ mod tests { assert_eq!((¶ms["texture"], ¶ms["textureImage"]), (&json!("loaded"), &json!(stored))); let _ = std::fs::remove_dir_all(&dir); } + + /// Rough Pastels' Texture and Light Direction are menus, and Load Texture… matches Glass: pick, + /// Loaded Texture in the menu with the texture's size, OK applies, and the Appearance panel's + /// Texture menu lists Loaded Texture too. + #[test] + fn rough_pastels_load_texture_reads_the_picked_image_into_the_effect() { + let dir = std::env::temp_dir().join(format!("vectorcraft-rough-pastels-dialog-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("texture.png"); + image::RgbaImage::from_fn(6, 4, |x, y| image::Rgba([(x * 40) as u8, (y * 60) as u8, 90, 255])).save(&path).unwrap(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let picked = path.to_string_lossy().into_owned(); + app.services.pick_open = Some(Box::new(move |_: &crate::FilePick| Some(picked.clone()))); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + 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": ROUGH_PASTELS})).unwrap(); + let paint = |app: &mut VectorcraftApp| crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())); + let text = paint(&mut app); + assert!(text.lines().any(|l| l == "Load Texture…") && text.lines().any(|l| l == "Canvas") && text.lines().any(|l| l == "Top"), "{text}"); + assert!(!text.contains("Loaded Texture") && !text.contains(" px"), "{text}"); + let mut d = app.ui.dialog.take().unwrap(); + load_texture(&mut app, &mut d).unwrap(); + let stored = d.str(vectorcraft_effects::pixel::TEXTURE_IMAGE); + assert_eq!((d.str("texture"), vectorcraft_effects::pixel::texture(&stored).map(|t| t.size())), ("loaded".to_string(), Some((6, 4)))); + app.ui.dialog = Some(d); + let text = paint(&mut app); + assert!(text.lines().any(|l| l == "Loaded Texture") && text.lines().any(|l| l == "6 × 4 px"), "{text}"); + assert!(!text.contains(&stored[..24]), "the stored text isn't shown"); + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let params = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params; + assert_eq!((¶ms["texture"], ¶ms["textureImage"]), (&json!("loaded"), &json!(stored))); + let shown = shown_choices(ROUGH_PASTELS, "texture", params.as_object().unwrap(), false).unwrap(); + assert_eq!(shown.last().map(|(_, v)| v.as_str()), Some(vectorcraft_effects::pixel::LOADED), "{shown:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + /// Effect > Stylize > Outer Glow: a swatch beside Color shows the effect's colour, typing a /// hex recolours it, and a double-click opens the Color Picker over the dialog; its OK fills /// Color, and the effect applies that colour. @@ -1258,4 +1437,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..fe0de205fc 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -52,6 +52,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { #[derive(Clone)] struct StackEntry { + /// The row's own number, kept while the row moves (a file dialog's late answer finds it). + id: u64, effect: String, visible: bool, params: Map, @@ -63,13 +65,20 @@ pub fn open(app: &mut VectorcraftApp, _p: &Value) -> Result { return Err(tl!("Select artwork to apply effects").into()); } let selected = effects_in_category(0).first().map(|e| e.id).unwrap_or(""); + // Each gallery opened has a number of its own, so a file dialog's late answer for one that + // closed never reaches the next. + static OPENED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let opened = OPENED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); app.ui.dialog = Some(Dialog::new( KIND, - json!({ "category": 0, "selected": selected, "stack": [], "stackSelected": 0, "stackFocus": false, "preview": true }), + json!({ "category": 0, "selected": selected, "stack": [], "stackSelected": 0, "stackFocus": false, "preview": true, OPENED_FIELD: opened }), )); Ok(Value::Null) } +/// Field of the gallery holding the number it was opened with. +const OPENED_FIELD: &str = "opened"; + fn effects_in_category(cat: usize) -> Vec { let path = CATEGORIES.get(cat).map(|(_, p)| *p).unwrap_or(CATEGORIES[0].1); let mut out: Vec = @@ -92,31 +101,48 @@ fn merged_params(id: &str, stored: &Map) -> Map { } } +/// The stack's rows. A row without a number of its own, or with one an earlier row has, gets the +/// next number after the highest one. fn stack_of(d: &Dialog) -> Vec { - d.fields - .get("stack") - .and_then(Value::as_array) - .map(|rows| { - rows.iter() - .filter_map(|row| { - let effect = row.get("effect").and_then(Value::as_str)?; - let visible = row.get("visible").and_then(Value::as_bool).unwrap_or(true); - let params = row - .get("params") - .and_then(Value::as_object) - .cloned() - .map(|m| merged_params(effect, &m)) - .unwrap_or_else(|| default_params(effect)); - Some(StackEntry { effect: effect.to_string(), visible, params }) - }) - .collect() + let rows = d.fields.get("stack").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); + let mut next = rows.iter().filter_map(|row| row.get("id").and_then(Value::as_u64)).max().map_or(0, |m| m.saturating_add(1)); + next = next.max(d.fields.get(NEXT_ROW).and_then(Value::as_u64).unwrap_or(0)); + let mut seen = std::collections::HashSet::new(); + rows.iter() + .filter_map(|row| { + let effect = row.get("effect").and_then(Value::as_str)?; + let visible = row.get("visible").and_then(Value::as_bool).unwrap_or(true); + let params = + row.get("params").and_then(Value::as_object).cloned().map(|m| merged_params(effect, &m)).unwrap_or_else(|| default_params(effect)); + let id = match row.get("id").and_then(Value::as_u64) { + Some(id) if seen.insert(id) => id, + _ => { + let id = next; + next = next.saturating_add(1); + seen.insert(id); + id + } + }; + Some(StackEntry { id, effect: effect.to_string(), visible, params }) }) - .unwrap_or_default() + .collect() +} + +/// Field of the gallery holding the number the next new row takes. +const NEXT_ROW: &str = "nextRowId"; + +/// A number for a new row of `stack` in `d`: after the highest one, and never one that a removed +/// row had. +fn next_row_id(d: &Dialog, stack: &[StackEntry]) -> u64 { + let after = stack.iter().map(|e| e.id).max().map_or(0, |m| m.saturating_add(1)); + after.max(d.fields.get(NEXT_ROW).and_then(Value::as_u64).unwrap_or(0)) } fn write_stack(d: &mut Dialog, stack: &[StackEntry]) { - let rows: Vec = stack.iter().map(|e| json!({ "effect": e.effect, "visible": e.visible, "params": e.params })).collect(); + let rows: Vec = stack.iter().map(|e| json!({ "id": e.id, "effect": e.effect, "visible": e.visible, "params": e.params })).collect(); d.fields.insert("stack".into(), Value::Array(rows)); + let next = next_row_id(d, stack); + d.fields.insert(NEXT_ROW.into(), json!(next)); } fn category_ix(d: &Dialog) -> usize { @@ -177,8 +203,79 @@ fn write_param_target(d: &mut Dialog, stack: &mut [StackEntry], stack_sel: usize } } -/// Reuse the live effect dialog's fields for `effect_id` and `params`. -fn effect_param_fields(app: &mut VectorcraftApp, ui: &mut egui::Ui, effect_id: &str, params: &mut Map) { +/// Field of the effect dialog the gallery's Settings draw in ([`effect_param_fields`]): which +/// values they edit ([`settings_key`]). +pub(super) const SETTINGS: &str = "__gallerySettings"; + +/// Field of the stand-in dialog [`load_texture`] asks the file dialog with. +const ASKING: &str = "__asking"; + +/// The stack row the Settings of `d` edit when the stack has the focus, of `rows` rows. +fn settings_row(d: &Dialog, rows: usize) -> Option { + let row = (d.fields.get("stackSelected").and_then(Value::as_u64).unwrap_or(0) as usize).min(rows.saturating_sub(1)); + stack_focus(d).then_some(row) +} + +/// Which values the Settings of gallery `d` edit: `{opened, row}`, the gallery's number and the +/// number of the stack row, or `null` for the row when they edit the filter being browsed. +fn settings_key(d: &Dialog, stack: &[StackEntry]) -> Value { + let row = settings_row(d, stack.len()).and_then(|row| stack.get(row)).map(|e| e.id); + json!({ "opened": d.fields.get(OPENED_FIELD), "row": row }) +} + +/// Load Texture… in the gallery's Settings (`temp`, for Glass, Texturizer or Rough Pastels): the +/// image picked goes into `temp` when the file dialog answers at once. When it answers later +/// (shown off the UI thread) it goes into the values that asked: the stack row of that number +/// wherever it moved, or the filter being browsed. An answer for a row that was removed, or for a +/// filter no longer browsed, or for a gallery that closed, is dropped. +pub(super) fn load_texture(app: &mut VectorcraftApp, temp: &mut Dialog) -> Result<(), String> { + use vectorcraft_effects::pixel::TEXTURE_IMAGE; + let effect = temp.str("__effect"); + let key = temp.fields.get(SETTINGS).cloned().unwrap_or(Value::Null); + let opened = key.get("opened").cloned().unwrap_or(Value::Null); + let row = key.get("row").and_then(Value::as_u64); + let mut asking = Dialog::new(KIND, json!({ ASKING: true })); + crate::picks::in_dialog(app, &mut asking, move |app, d| { + if d.fields.contains_key(ASKING) { + return effect::load_texture(app, d); + } + let mut picked = Dialog::new(KIND, json!({})); + effect::load_texture(app, &mut picked)?; + if d.fields.get(OPENED_FIELD).unwrap_or(&Value::Null) != &opened { + return Ok(()); + } + match row { + Some(row) => { + let mut stack = stack_of(d); + if let Some(e) = stack.iter_mut().find(|e| e.id == row && e.effect == effect) { + e.params.extend(picked.fields); + write_stack(d, &stack); + } + } + None if selected_id(d) == effect => { + let mut params = if d.fields.get("browseEffect").and_then(Value::as_str) == Some(effect.as_str()) { + browse_params(d) + } else { + default_params(&effect) + }; + params.extend(picked.fields); + set_browse_params(d, &effect, params); + } + None => {} + } + Ok(()) + })?; + for key in [TEXTURE_IMAGE, "texture"] { + if let Some(v) = asking.fields.remove(key) { + temp.fields.insert(key.into(), v); + } + } + Ok(()) +} + +/// Reuse the live effect dialog's fields for `effect_id` and `params`, the values `key` names +/// ([`settings_key`]). +fn effect_param_fields(app: &mut VectorcraftApp, ui: &mut egui::Ui, effect_id: &str, params: &mut Map, key: Value) { if effect_id.is_empty() { return; } @@ -188,6 +285,7 @@ fn effect_param_fields(app: &mut VectorcraftApp, ui: &mut egui::Ui, effect_id: & fields.insert("__effect".into(), json!(effect_id)); fields.insert("__label".into(), json!(label)); fields.insert("preview".into(), json!(false)); + fields.insert(SETTINGS.into(), key); let mut temp = Dialog::new("effect", Value::Object(fields)); (effect::SPEC.body)(app, ui, &mut temp); if let Value::Object(m) = form::params(&temp) { @@ -271,6 +369,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), @@ -474,8 +573,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let (param_effect, mut param_values) = param_target(d, &stack, stack_sel, &sel); if !param_effect.is_empty() { widgets::subheader(ui, tl!("Settings")); + let key = settings_key(d, &stack); egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { - effect_param_fields(app, ui, ¶m_effect, &mut param_values); + effect_param_fields(app, ui, ¶m_effect, &mut param_values, key); }); write_param_target(d, &mut stack, stack_sel, &sel, ¶m_effect, param_values); } @@ -603,7 +703,7 @@ fn add_selected(d: &mut Dialog, id: &str) { let params = if !stack_focus(d) && d.fields.get("browseEffect").and_then(Value::as_str) == Some(id) { browse_params(d) } else { default_params(id) }; let mut stack = stack_of(d); - stack.push(StackEntry { effect: id.to_string(), visible: true, params }); + stack.push(StackEntry { id: next_row_id(d, &stack), effect: id.to_string(), visible: true, params }); write_stack(d, &stack); d.fields.insert("stackSelected".into(), json!(stack.len().saturating_sub(1))); set_stack_focus(d, true); @@ -738,4 +838,88 @@ mod tests { ); assert_ne!(soft, hard, "the preview follows the filter's settings"); } + + /// Load Texture… in the Settings, with the file dialog shown off the UI thread: the image + /// goes into the values whose Settings asked (the filter browsed, or a stack row wherever it + /// moved) when the dialog answers, and an answer for a removed row, or for a filter no longer + /// browsed, is dropped. + #[test] + fn settings_load_texture_answers_into_the_gallery() { + use vectorcraft_effects::pixel::{TEXTURE_IMAGE, texture}; + let dir = std::env::temp_dir().join(format!("vectorcraft-gallery-texture-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("texture.png"); + image::RgbaImage::from_fn(6, 4, |x, y| image::Rgba([(x * 40) as u8, (y * 60) as u8, 90, 255])).save(&path).unwrap(); + let picked = path.to_string_lossy().into_owned(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let (shown, _) = crate::tests_picks::off_the_ui_thread(&mut app.services); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + let effect = "artistic.roughPastels"; + let loaded = |params: &serde_json::Map| { + params.get(TEXTURE_IMAGE).and_then(serde_json::Value::as_str).and_then(texture).map(|t| t.size()) == Some((6, 4)) + && params.get("texture") == Some(&json!("loaded")) + }; + // Asks from the Settings of `row` (None: the filter browsed), then `meanwhile` changes the + // gallery before the dialog answers. + let ask = |app: &mut VectorcraftApp, row: Option, meanwhile: &dyn Fn(&mut crate::state::Dialog)| { + let gallery = app.ui.dialog.as_mut().unwrap(); + gallery.fields.remove("browseEffect"); + gallery.fields.remove("browseParams"); + gallery.fields.insert("selected".into(), json!(effect)); + gallery.fields.remove(super::NEXT_ROW); + gallery.fields.insert("stack".into(), json!([{"effect": effect, "params": {}}, {"effect": effect, "params": {}}])); + let rows = super::stack_of(gallery); + super::write_stack(gallery, &rows); + gallery.fields.insert("stackFocus".into(), json!(row.is_some())); + gallery.fields.insert("stackSelected".into(), json!(row.unwrap_or(0))); + let key = super::settings_key(gallery, &super::stack_of(gallery)); + let mut temp = crate::state::Dialog::new("effect", json!({"__effect": effect, super::SETTINGS: key, "texture": "canvas"})); + assert_eq!(super::load_texture(app, &mut temp), Err("cancelled".to_string()), "asked, not answered yet"); + assert!(temp.fields.get(TEXTURE_IMAGE).is_none()); + meanwhile(app.ui.dialog.as_mut().unwrap()); + shown.answer(&[picked.as_str()]); + crate::picks::poll(app, &egui::Context::default()); + let d = app.ui.dialog.as_ref().expect("the gallery stays open"); + (super::browse_params(d), super::stack_of(d).into_iter().map(|e| loaded(&e.params)).collect::>()) + }; + // The filter browsed gets it, and so does the stack row whose Settings asked. + let (browsed, rows) = ask(&mut app, None, &|_| {}); + assert!(loaded(&browsed) && rows == [false, false], "{browsed:?}"); + let (browsed, rows) = ask(&mut app, Some(1), &|_| {}); + assert!(!loaded(&browsed) && rows == [false, true], "{rows:?}"); + // The row that asked gets it after it moved, or after another row was selected. + let (_, rows) = ask(&mut app, Some(0), &|d| { + let mut stack = super::stack_of(d); + stack.swap(0, 1); + super::write_stack(d, &stack); + }); + assert_eq!(rows, [false, true], "moved down"); + let (_, rows) = ask(&mut app, Some(0), &|d| { + d.fields.insert("stackSelected".into(), json!(1)); + }); + assert_eq!(rows, [true, false], "another row selected"); + // A row removed (and another of the same effect added in its place), or a filter no + // longer browsed: dropped. + let (browsed, rows) = ask(&mut app, Some(1), &|d| { + let mut stack = super::stack_of(d); + stack.pop(); + super::write_stack(d, &stack); + super::add_selected(d, effect); + }); + assert!(!loaded(&browsed) && rows == [false, false], "{rows:?}"); + let (browsed, rows) = ask(&mut app, None, &|d| { + d.fields.insert("selected".into(), json!("artistic.cutout")); + }); + assert!(!loaded(&browsed) && rows == [false, false], "{browsed:?}"); + // The gallery that asked closed and another one opened. + let (browsed, rows) = ask(&mut app, Some(1), &|d| { + let next = d.fields.get(super::OPENED_FIELD).and_then(serde_json::Value::as_u64).unwrap() + 1; + d.fields.insert(super::OPENED_FIELD.into(), json!(next)); + }); + assert!(!loaded(&browsed) && rows == [false, false], "{rows:?}"); + let _ = std::fs::remove_dir_all(&dir); + } } 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_filter.rs b/crates/ui-egui/src/dialogs/svg_filter.rs index af6849de43..f092a55cc4 100644 --- a/crates/ui-egui/src/dialogs/svg_filter.rs +++ b/crates/ui-egui/src/dialogs/svg_filter.rs @@ -1,16 +1,22 @@ -//! Apply SVG Filter (Effect › SVG Filters › Apply SVG Filter…): the document's SVG filters in a -//! list. OK applies the selected one to the selection as a live effect (`svgFilter.apply`), or, -//! opened from the Appearance panel for an applied SVG filter, puts it in that effect's place -//! (`effect.setParams`). New and Edit open the filter's code under the list; Save adds the filter -//! or replaces the one being edited (`svgFilter.define`). Delete removes the selected filter -//! (`svgFilter.delete`) and Import… adds the filters of an SVG file (`svgFilter.import`). Those -//! act at once. Effect › SVG Filters lists the same filters below its first items. +//! Apply SVG Filter (Effect › SVG Filters › Apply SVG Filter…): the default SVG filters and the +//! document's own in a list, the defaults first. OK applies the selected one to the selection as a +//! live effect, or, opened from the Appearance panel for an applied SVG filter, puts it in that +//! effect's place (`svgFilter.apply`, with `index`). New and Edit open the filter's code under the +//! list; Save adds the filter or replaces the one being edited (`svgFilter.define`). Delete +//! removes the selected filter (`svgFilter.delete`) and Import… adds the filters of an SVG file +//! (`svgFilter.import`). Those act at once. Effect › SVG Filters lists the same filters below its +//! first items. +//! +//! A default is not in the document until it is applied or edited: the document then holds a copy +//! under the default's name, which is listed in the default's place. Delete is off for a default +//! the document holds no copy of. //! //! Fields: `selected` (a filter's name), `code` (the code being edited), `editing` (`""`, `"new"` //! or the name of the filter being edited), and with an applied effect `__index`, `__item` and //! `missing` (the name of a deleted filter the effect names). use serde_json::{Value, json}; +use vectorcraft_effects::svg_filter::defaults::{DEFAULT_FILTERS, Listed, default_filter, listed}; use vectorcraft_engine::doc::SvgFilter; use super::DialogSpec; @@ -25,20 +31,21 @@ pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Apply SVG Filter…").trim_end_matches('…').to_string(), body, confirm, - ok_enabled: Some(|app, d| d.str("editing").is_empty() && filters(app).iter().any(|f| f.name == d.str("selected"))), + ok_enabled: Some(|app, d| d.str("editing").is_empty() && filters(app).0.iter().any(|f| f.filter.name == d.str("selected"))), min_width: 440.0, ..DialogSpec::FORM }; -/// The active document's SVG filters. -fn filters(app: &VectorcraftApp) -> Vec { - app.session.active().map(|st| st.doc.svg_filters.clone()).unwrap_or_default() +/// The filters the dialog lists for the active document, and how many come first as the defaults. +fn filters(app: &VectorcraftApp) -> (Vec, usize) { + listed(app.session.active().map(|st| st.doc.svg_filters.as_slice()).unwrap_or_default()) } /// `ui.svgFilterDialog {index?, item?}`: open Apply SVG Filter for the active document; with /// `index`, for the applied SVG filter at `index` of `item` (null: the object's effects): the -/// document's filter of its name selected; when the document has none of its name, the name shown -/// above the list if the filter was deleted, or else its code open as a new filter. +/// document's filter of its name selected, or the default of its name when the effect draws with +/// the default's code or with nothing; when neither has its name, the name shown above the list if +/// the filter was deleted, or else its code open as a new filter. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if app.session.active().is_none() { return Err("no document open".into()); @@ -53,17 +60,19 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let e = applied.get(k as usize).filter(|e| e.id == vectorcraft_effects::SVG_FILTER).ok_or_else(|| format!("no SVG filter at index {k}"))?; let name = e.params.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); let xml = e.params.get("xml").and_then(Value::as_str).unwrap_or_default().to_string(); - let held = filters(app).into_iter().find(|f| f.name == name); - match held { - // The document's filter it names: selected. - Some(_) => fields["selected"] = json!(name), + let held = app.session.active().is_some_and(|st| st.doc.svg_filters.iter().any(|f| f.name == name)); + // A default the document holds no copy of, when the effect draws with its code or with nothing. + let default = default_filter(&name).is_some_and(|d| xml.is_empty() || xml == d.xml); + if held || default { + // The filter it names: selected. + fields["selected"] = json!(name); + } else if xml.is_empty() { // Deleted from the document: shown above the list, not selectable; OK waits for a choice. - None if xml.is_empty() => fields["missing"] = json!(name), + fields["missing"] = json!(name); + } else { // A filter the document doesn't hold (from an opened file): its code, to add it. - None => { - fields["code"] = json!(xml); - fields["editing"] = json!("new"); - } + fields["code"] = json!(xml); + fields["editing"] = json!("new"); } fields["__index"] = json!(k); // As given: `null` is the object's own effects, and none is the active item's. @@ -75,33 +84,39 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } -/// OK: the selected filter to the selection, or in the applied effect's place. +/// OK: the selected filter to the selection, or in the applied effect's place. A default the +/// document holds no copy of is copied into it in the same undo step. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let name = d.str("selected"); - let f = filters(app).into_iter().find(|f| f.name == name).ok_or("select an SVG filter")?; - let r = match d.fields.get("__index").and_then(Value::as_u64) { - Some(k) => { - let mut p = json!({ "index": k, "params": { "name": f.name, "xml": f.xml } }); - if let Some(item) = d.fields.get("__item") { - p["item"] = item.clone(); - } - app.run("effect.setParams", p)? + let f = filters(app).0.into_iter().find(|f| f.filter.name == name).ok_or("select an SVG filter")?; + let mut p = json!({ "name": f.filter.name }); + if let Some(k) = d.fields.get("__index").and_then(Value::as_u64) { + p["index"] = json!(k); + if let Some(item) = d.fields.get("__item") { + p["item"] = item.clone(); } - None => app.run("svgFilter.apply", json!({ "name": f.name }))?, - }; + } + let r = app.run("svgFilter.apply", p)?; app.ui.dialog = None; Ok(r) } -/// The active document's filter names, mirrored for the (static) menu tree ([`sync`]). +/// The names of the active document's filters that are not a default's, mirrored for the (static) +/// menu tree ([`sync`]). fn names_store() -> &'static std::sync::RwLock> { static NAMES: std::sync::OnceLock>> = std::sync::OnceLock::new(); NAMES.get_or_init(Default::default) } -/// Mirror the active document's SVG filter names for the menu tree (cheap when unchanged). +/// The names of `held`, a document's filters, that are not a default's, in their order. +fn own_names(held: &[SvgFilter]) -> Vec { + held.iter().filter(|f| default_filter(&f.name).is_none()).map(|f| f.name.clone()).collect() +} + +/// Mirror the active document's SVG filter names for the menu tree (cheap when unchanged). A +/// filter with a default's name is the menu's entry of that name already. pub fn sync(app: &VectorcraftApp) { - let names: Vec = app.session.active().map(|st| st.doc.svg_filters.iter().map(|f| f.name.clone()).collect()).unwrap_or_default(); + let names: Vec = app.session.active().map(|st| own_names(&st.doc.svg_filters)).unwrap_or_default(); let same = names_store().read().map(|v| v.len() == names.len() && v.iter().zip(&names).all(|(a, b)| *a == b)).unwrap_or(true); if !same { if let Ok(mut v) = names_store().write() { @@ -111,20 +126,23 @@ pub fn sync(app: &VectorcraftApp) { } } -/// Effect › SVG Filters: Apply SVG Filter…, Import SVG Filter… and then the active document's -/// filters, each applying itself to the selection. +/// Effect › SVG Filters: Apply SVG Filter…, Import SVG Filter…, the default filters and then the +/// active document's other filters, each applying itself to the selection. pub fn menu_items() -> Vec { items_for(names_store().read().map(|v| v.clone()).unwrap_or_default()) } -/// [`menu_items`] for filters named `names`. +/// [`menu_items`] for a document whose filters that are not a default's are named `names`. fn items_for(names: Vec<&'static str>) -> Vec { use crate::menus::Item; + let apply = |n: &'static str| Item::Cmd(n, "svgFilter.apply", json!({ "name": n })); let mut v = vec![Item::Cmd("Apply SVG Filter…", "ui.svgFilterDialog", Value::Null), Item::Cmd("Import SVG Filter…", "ui.importSvgFilter", Value::Null)]; + v.push(Item::Sep); + v.extend(DEFAULT_FILTERS.iter().map(|d| apply(d.name))); if !names.is_empty() { v.push(Item::Sep); - v.extend(names.into_iter().map(|n| Item::Cmd(n, "svgFilter.apply", json!({ "name": n })))); + v.extend(names.into_iter().map(apply)); } v } @@ -170,7 +188,8 @@ enum Action { } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let list = filters(app); + let (list, defaults) = filters(app); + let held = list.iter().filter(|f| !f.default).count(); let selected = d.str("selected"); let editing = d.str("editing"); let mut act = None; @@ -184,7 +203,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if !missing.is_empty() { ui.add_enabled_ui(false, |ui| ui.selectable_label(false, missing.as_str())); } - for f in &list { + for (i, Listed { filter: f, .. }) in list.iter().enumerate() { + // The document's other filters follow the defaults, below a line. + if i == defaults && i > 0 { + ui.separator(); + } let r = ui.selectable_label(f.name == selected, f.name.as_str()); if r.double_clicked() && editing.is_empty() { act = Some(Action::Edit(f.name.clone())); @@ -195,17 +218,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); }); ui.add_space(6.0); - let has = list.iter().any(|f| f.name == selected); + let chosen = list.iter().find(|f| f.filter.name == selected); + let has = chosen.is_some(); + // A default the document holds no copy of has nothing to delete. + let deletable = chosen.is_some_and(|f| !f.default); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 4.0; let idle = editing.is_empty(); - if ui.add_enabled_ui(idle && list.len() < SvgFilter::MAX, |ui| widgets::flat_button(ui, tl!("New"), 64.0)).inner.clicked() { + if ui.add_enabled_ui(idle && held < SvgFilter::MAX, |ui| widgets::flat_button(ui, tl!("New"), 64.0)).inner.clicked() { act = Some(Action::New); } if ui.add_enabled_ui(idle && has, |ui| widgets::flat_button(ui, tl!("Edit"), 64.0)).inner.clicked() { act = Some(Action::Edit(selected.clone())); } - if ui.add_enabled_ui(idle && has, |ui| widgets::flat_button(ui, tl!("Delete"), 64.0)).inner.clicked() { + if ui.add_enabled_ui(idle && deletable, |ui| widgets::flat_button(ui, tl!("Delete"), 64.0)).inner.clicked() { act = Some(Action::Delete); } if crate::picks::can(app, &PickRequest::Open(pick())) @@ -245,7 +271,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { Ok(()) } Some(Action::Edit(name)) => { - if let Some(f) = list.iter().find(|f| f.name == name) { + if let Some(f) = list.iter().map(|f| &f.filter).find(|f| f.name == name) { d.fields.insert("selected".into(), json!(f.name)); d.fields.insert("editing".into(), json!(f.name)); d.fields.insert("code".into(), json!(f.xml)); @@ -322,7 +348,9 @@ mod tests { crate::menus::invoke(&mut app, "ui.svgFilterDialog", json!({})); let mut d = app.ui.dialog.clone().unwrap(); assert_eq!(d.kind, KIND); - assert!(frame(&mut app, &mut d).iter().any(|t| t == "Shift"), "the filter's name, as it is"); + // Below the defaults, which fill the rows the list shows at first. + assert_eq!(filters(&app).0.last().map(|f| f.filter.name.as_str()), Some("Shift"), "the filter's name, as it is"); + assert!(!frame(&mut app, &mut d).is_empty()); assert!(!(SPEC.ok_enabled.unwrap())(&app, &d), "nothing selected"); d.fields.insert("selected".into(), json!("Shift")); assert!((SPEC.ok_enabled.unwrap())(&app, &d)); @@ -411,11 +439,30 @@ mod tests { use crate::menus::Item; let ids = |items: &[Item]| items.iter().map(|i| if let Item::Cmd(l, c, p) = i { format!("{l} {c} {p}") } else { "—".into() }).collect::>(); - assert_eq!(ids(&items_for(vec![])), ["Apply SVG Filter… ui.svgFilterDialog null", "Import SVG Filter… ui.importSvgFilter null"]); + // The defaults follow the commands in every document, and with no document. + let plain = ids(&items_for(vec![])); assert_eq!( - ids(&items_for(vec!["Shift", "A (1)"]))[2..], - ["—", "Shift svgFilter.apply {\"name\":\"Shift\"}", "A (1) svgFilter.apply {\"name\":\"A (1)\"}"] + plain[..4], + [ + "Apply SVG Filter… ui.svgFilterDialog null", + "Import SVG Filter… ui.importSvgFilter null", + "—", + "Soft Blur svgFilter.apply {\"name\":\"Soft Blur\"}" + ] ); + assert_eq!(plain.len(), 3 + DEFAULT_FILTERS.len()); + assert_eq!(plain.last().map(String::as_str), Some("Hue Shift svgFilter.apply {\"name\":\"Hue Shift\"}")); + // The document's other filters come below them. + let with = ids(&items_for(vec!["Shift", "A (1)"])); + assert_eq!(with[..plain.len()], plain[..]); + assert_eq!(with[plain.len()..], ["—", "Shift svgFilter.apply {\"name\":\"Shift\"}", "A (1) svgFilter.apply {\"name\":\"A (1)\"}"]); + // A document's filter with a default's name is that default's entry. + let held = [ + SvgFilter { name: "Glow".into(), xml: String::new() }, + SvgFilter { name: "Shift".into(), xml: String::new() }, + SvgFilter { name: "glow".into(), xml: String::new() }, + ]; + assert_eq!(own_names(&held), ["Shift", "glow"]); let mut app = app(); assert!(!crate::menus::enabled(&app, "svgFilter.apply"), "nothing selected"); app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); @@ -423,6 +470,88 @@ mod tests { assert_eq!(crate::menus::display_label(&app, "svgFilter.apply", "Shift"), "Shift", "a filter's name as it is"); } + /// The steps in the active document's undo history. + fn steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() + } + + #[test] + fn a_default_is_listed_first_and_ok_copies_it_into_the_document() { + let mut app = app(); + app.session.execute("svgFilter.define", &json!({"xml": SHIFT})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + open(&mut app, &json!({})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + let (list, defaults) = filters(&app); + let names: Vec<&str> = list.iter().map(|f| f.filter.name.as_str()).collect(); + assert_eq!((defaults, names.len()), (DEFAULT_FILTERS.len(), DEFAULT_FILTERS.len() + 1)); + assert_eq!((names[0], names[defaults - 1], names[defaults]), ("Soft Blur", "Hue Shift", "Shift"), "the defaults, then the document's own"); + assert!(frame(&mut app, &mut d).iter().any(|t| t == "Soft Blur"), "a default's name, as it is"); + d.fields.insert("selected".into(), json!("Soft Shadow")); + assert!((SPEC.ok_enabled.unwrap())(&app, &d), "a default can be applied"); + let before = steps(&app); + confirm(&mut app, &d).unwrap(); + assert_eq!(steps(&app), before + 1, "one undo step"); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.svg_filters.iter().map(|f| f.name.as_str()).collect::>(), ["Shift", "Soft Shadow"]); + let fx = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects; + assert_eq!((fx.len(), fx[0].params["name"].as_str()), (1, Some("Soft Shadow"))); + assert_eq!(fx[0].params["xml"].as_str(), default_filter("Soft Shadow").map(|f| f.xml)); + // Opened for that effect, the document's copy is selected; OK with another default puts it + // in the effect's place and copies it, in one step. + app.run("effect.dialog", json!({"effect": "svg.filter", "index": 0, "item": null})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.str("selected").as_str(), d.str("editing").as_str()), ("Soft Shadow", "")); + d.fields.insert("selected".into(), json!("Invert")); + let before = steps(&app); + confirm(&mut app, &d).unwrap(); + assert_eq!(steps(&app), before + 1); + let doc = &app.session.active().unwrap().doc; + let fx = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects; + assert_eq!((fx.len(), fx[0].params["name"].as_str()), (1, Some("Invert")), "in its place, not added"); + assert_eq!(doc.svg_filters.len(), 3); + } + + /// Edit on a default opens its code, and Save keeps the edited copy in the document under the + /// default's name; an effect that names a default the document no longer holds selects it. + #[test] + fn an_edited_default_is_saved_in_the_document() { + let mut app = app(); + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + // Save, as its button does for the default being edited. + let edited = r#""#; + let r = app.run("svgFilter.define", json!({"xml": edited, "replace": "Thin"})).unwrap(); + assert_eq!(r["name"], "Thin"); + assert_eq!(filters(&app).0.iter().filter(|f| !f.default).map(|f| f.filter.xml.as_str()).collect::>(), [edited]); + assert_eq!(filters(&app).0.len(), DEFAULT_FILTERS.len(), "in the default's place"); + app.session.execute("svgFilter.apply", &json!({"name": "Thin"})).unwrap(); + // Deleted: the default is listed again, and the effect that names it selects the default. + app.session.execute("svgFilter.delete", &json!({"name": "Thin"})).unwrap(); + assert!(filters(&app).0.iter().all(|f| f.default)); + app.run("effect.dialog", json!({"effect": "svg.filter", "index": 0, "item": null})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.str("selected").as_str(), d.str("missing").as_str(), d.str("editing").as_str()), ("Thin", "", "")); + confirm(&mut app, &d).unwrap(); + let doc = &app.session.active().unwrap().doc; + let fx = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects; + assert_eq!(fx[0].params["xml"].as_str(), default_filter("Thin").map(|f| f.xml), "the default again"); + // An applied filter with a default's name and other code opens as code to save. + let e = vectorcraft_doc::Effect { + id: "svg.filter".into(), + params: json!({"name": "Glow", "xml": ""}), + visible: true, + }; + app.session + .edit("Plant", |d, _| { + d.node_mut(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects = vec![e]; + Ok(()) + }) + .unwrap(); + app.run("effect.dialog", json!({"effect": "svg.filter", "index": 0, "item": null})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.str("editing").as_str(), d.str("selected").as_str()), ("new", "")); + } + #[test] fn new_saves_the_code_and_selects_the_filter() { let mut app = app(); 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 fb3080c8c2..e455157e14 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 Копиране в потребителски @@ -2591,6 +2593,8 @@ font-technology Variable Променливи Proof Setup Настройка на пробен печат Properties Свойства Proportional Metrics Пропорционални метрики + H or V Style Хоризонтален или вертикален стил + Roman Italics Римски курсив Insert Aki Left Вмъкване на аки отляво Insert Aki Right Вмъкване на аки отдясно Tsume Цуме @@ -4181,6 +4185,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 118609f801..f126736293 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… @@ -1583,6 +1584,8 @@ lighting Light Svjetlo Leading Prored No Break Bez preloma Proportional Metrics Proporcionalna metrika + H or V Style Horizontalni ili vertikalni stil + Roman Italics Latinični kurziv Insert Aki Left Umetni aki lijevo Insert Aki Right Umetni aki desno Tsume Tsume @@ -2699,6 +2702,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 +4550,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 42ebfba4b1..fb1a4a1702 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 @@ -3361,6 +3362,8 @@ digits Malayalam Malaiàlam Proof Setup Configuració de prova Properties Propietats Proportional Metrics Mètriques proporcionals + H or V Style Estil horitzontal o vertical + Roman Italics Cursiva romana Insert Aki Left Insereix aki a l'esquerra Insert Aki Right Insereix aki a la dreta Tsume Tsume @@ -3396,6 +3399,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 @@ -5608,6 +5612,7 @@ digits Malayalam Malaiàlam @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` només és per a una execució sense ningú a qui preguntar: a l'aplicació, la persona respon cada quadre de diàleg @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} @@ -6361,6 +6366,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 7c286fa6ca..f2c60802b0 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í… @@ -1611,6 +1612,8 @@ lighting Light Světlo Leading Proklad No Break Nezalamovat Proportional Metrics Proporcionální metrika + H or V Style Vodorovný nebo svislý styl + Roman Italics Kurzíva latinky Insert Aki Left Vložit aki vlevo Insert Aki Right Vložit aki vpravo Tsume Tsume @@ -2734,6 +2737,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í. @@ -4704,6 +4708,7 @@ imageTrace Outline Obrys @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` je jen pro běh, kde se nemá koho zeptat: v aplikaci odpovídá na každý dialog uživatel @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} @@ -9033,6 +9038,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 @@ -9255,7 +9261,7 @@ breakText Glyphs Glyfy @msg unexpected resources neočekávané prostředky @msg unknown CMYK profile `{name}` neznámý profil CMYK `{name}` @msg unknown File Info field `{k}` neznámé pole informací o souboru `{k}` -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) neznámá funkce OpenType `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; předpona - funkci vypne; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom a aalt přijímají číslo alternativy jako `tag=N` s N od 0 do {_1}, například `salt=2`) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) neznámá funkce OpenType `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; předpona - funkci vypne; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom a aalt přijímají číslo alternativy jako `tag=N` s N od 0 do {_1}, například `salt=2`) @msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) neznámá funkce OpenType `{t}` ve featureChanges (značky, které přijímá `features`) @msg unknown PDF preset `{name}` (presets: {_1}) neznámé přednastavení PDF `{name}` (přednastavení: {_1}) @msg unknown Warp style neznámý styl deformace diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index de1726ed4c..a465093cc5 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1534,6 +1534,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… @@ -2140,6 +2141,8 @@ lighting Light Lys Leading Linjeafstand No Break Ingen ombrydning Proportional Metrics Proportionale metrikker + H or V Style Vandret eller lodret stil + Roman Italics Romersk kursiv Insert Aki Left Indsæt aki til venstre Insert Aki Right Indsæt aki til højre Tsume Tsume @@ -3137,6 +3140,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. @@ -4919,6 +4923,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 a42133d563..6024a871fb 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 @@ -2635,6 +2637,8 @@ mark-style Japanese Japanisch Proof Setup Proof einrichten Properties Eigenschaften Proportional Metrics Proportionale Metrik + H or V Style Horizontaler oder vertikaler Stil + Roman Italics Lateinische Kursive Insert Aki Left Aki links einfügen Insert Aki Right Aki rechts einfügen Tsume Tsume @@ -4315,6 +4319,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} @@ -7476,7 +7481,7 @@ breakText Glyphs Glyphen @msg toString is not a function toString ist keine Funktion @msg too many arguments zu viele Argumente @msg too many quantifiers zu viele Quantifizierer -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) unbekannte OpenType-Funktion `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; mit vorangestelltem - ausschalten; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom und aalt nehmen die Nummer einer Alternative als `tag=N` mit N von 0 bis {_1}, etwa `salt=2`) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) unbekannte OpenType-Funktion `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; mit vorangestelltem - ausschalten; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom und aalt nehmen die Nummer einer Alternative als `tag=N` mit N von 0 bis {_1}, etwa `salt=2`) @msg unknown dither `{d}` (diffusion, pattern, noise or none) unbekanntes Dithering `{d}` (diffusion, pattern, noise oder none) @msg unknown panel `{panel}` unbekanntes Bedienfeld `{panel}` @msg unknown parameter `{key}` unbekannter Parameter `{key}` @@ -8598,6 +8603,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 90f37905ae..b7858f42e4 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 Αντιγραφή σε ορισμένα από τον χρήστη @@ -2460,6 +2462,7 @@ axis Both Και τα δύο @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog το `answers` είναι μόνο για εκτέλεση χωρίς κανέναν να ερωτηθεί: στην εφαρμογή, το άτομο απαντά σε κάθε παράθυρο διαλόγου @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} @@ -3443,6 +3446,8 @@ theme Appearance Εμφάνιση Profile inclusion: Συμπερίληψη προφίλ: Projecting Cap Προεξέχον άκρο Proportional Metrics Αναλογικές μετρικές + H or V Style Οριζόντιο ή κατακόρυφο στυλ + Roman Italics Λατινικά πλάγια Insert Aki Left Εισαγωγή aki αριστερά Insert Aki Right Εισαγωγή aki δεξιά Tsume Tsume @@ -4832,6 +4837,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 d17e38157f..40a63056e1 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 @@ -2669,6 +2671,8 @@ font-technology Variable Variables Proof Setup Ajuste de prueba Properties Propiedades Proportional Metrics Métrica proporcional + H or V Style Estilo horizontal o vertical + Roman Italics Cursiva romana Insert Aki Left Insertar aki a la izquierda Insert Aki Right Insertar aki a la derecha Tsume Tsume @@ -4403,6 +4407,7 @@ axis Both Ambos @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` solo es para una ejecución sin nadie a quien preguntar: en la aplicación, la persona responde cada cuadro de diálogo @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} @@ -4875,6 +4880,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 691967899a..04a5f84f7d 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… @@ -1586,6 +1587,8 @@ lighting Light Valo Leading Riviväli No Break Ei katkoa Proportional Metrics Suhteelliset metriikat + H or V Style Vaaka- tai pystytyyli + Roman Italics Latinalainen kursiivi Insert Aki Left Lisää aki vasemmalle Insert Aki Right Lisää aki oikealle Tsume Tsume @@ -2678,6 +2681,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. @@ -4628,6 +4632,7 @@ imageTrace Outline Ääriviiva @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` on vain ajolle, jossa ei ole ketään kysyttävää: sovelluksessa henkilö vastaa jokaiseen valintaikkunaan @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} @@ -5090,6 +5095,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 c644688fed..d2ef894666 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 @@ -2661,6 +2663,8 @@ font-technology Variable Variables Proof Setup Format d’épreuve Properties Propriétés Proportional Metrics Métrique proportionnelle + H or V Style Style horizontal ou vertical + Roman Italics Italique des caractères romains Insert Aki Left Insérer un aki à gauche Insert Aki Right Insérer un aki à droite Tsume Tsume @@ -4382,6 +4386,7 @@ axis Both Les deux @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` est réservé à une exécution sans personne à qui demander : dans l'application, la personne répond à chaque boîte de dialogue @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} @@ -8894,6 +8899,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 @@ -9113,7 +9119,7 @@ breakText Glyphs Glyphes @msg unexpected resources ressources inattendues @msg unknown CMYK profile `{name}` profil CMJN inconnu `{name}` @msg unknown File Info field `{k}` champ Informations sur le fichier inconnu `{k}` -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) fonctionnalité OpenType inconnue `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt ; préfixe - pour désactiver ; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom et aalt acceptent un numéro de variante sous la forme `tag=N` avec N de 0 à {_1}, comme `salt=2`) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) fonctionnalité OpenType inconnue `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital ; préfixe - pour désactiver ; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom et aalt acceptent un numéro de variante sous la forme `tag=N` avec N de 0 à {_1}, comme `salt=2`) @msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) fonctionnalité OpenType inconnue `{t}` dans featureChanges (les balises qu’accepte `features`) @msg unknown PDF preset `{name}` (presets: {_1}) paramètre prédéfini PDF inconnu `{name}` (paramètres prédéfinis : {_1}) @msg unknown Warp style style de déformation inconnu diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0e9ed1997e..6d43bfce86 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 પસંદ કરેલું નકલ કરો @@ -2743,6 +2744,8 @@ Proof Setup પ્રૂફ સેટઅપ Properties ગુણધર્મો Proportional Metrics પ્રમાણસર મેટ્રિક્સ + H or V Style આડી અથવા ઊભી શૈલી + Roman Italics રોમન ઇટાલિક Pucker પકર Pucker & Bloat… પકર અને બ્લોટ… Pucker Tool પકર ટૂલ @@ -2770,6 +2773,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 8e10666667..b2c02e2ceb 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 ध्रुवीय ग्रिड @@ -3701,6 +3702,8 @@ antiAlias Sharp शार्प Properties प्रॉपर्टीज़ Proportional Lining आनुपातिक लाइनिंग Proportional Metrics आनुपातिक मीट्रिक + H or V Style क्षैतिज या ऊर्ध्वाधर शैली + Roman Italics रोमन इटैलिक Insert Aki Left बाईं ओर आकी जोड़ें Insert Aki Right दाईं ओर आकी जोड़ें Tsume त्सुमे @@ -3732,6 +3735,7 @@ antiAlias Sharp शार्प Radial रेडियल Radial Blur रेडियल ब्लर Radial Blur… रेडियल ब्लर… + Blur Center ब्लर का केंद्र Radial Dividers: रेडियल विभाजक: Radial Glows रेडियल चमक Radial Gradient रेडियल ग्रेडिएंट @@ -3919,7 +3923,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 +4028,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 +4102,7 @@ antiAlias Sharp शार्प RGB: RGB: Ridges per segment: प्रति खंड रिज: Right दाएँ - Right Complement सही पूरक + Right Complement राइट कम्प्लीमेंट Right Diagonal दायाँ विकर्ण Right Grid: राइट ग्रिड: Right in Front फ्रंट में राइट @@ -4157,14 +4161,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 +4311,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 +4376,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 +4405,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 +4652,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 +5118,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 +5152,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 +5261,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 +5271,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 +5498,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 +5523,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 +6020,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 +6375,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 +6563,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 इसे विभाजित करने के लिए टाइप टूल के साथ टाइप करें @@ -6721,6 +6725,7 @@ antiAlias Sharp शार्प @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` केवल ऐसे रन के लिए है जिसमें पूछने के लिए कोई नहीं है: ऐप में, व्यक्ति हर डायलॉग का उत्तर देता है @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 एक फ़ाइल की प्रतिलिपि वेब पर उपलब्ध नहीं है @@ -6788,7 +6793,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 होना चाहिए @@ -6843,7 +6848,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": "…"}} @@ -6976,7 +6981,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" होना चाहिए @@ -7233,8 +7238,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 @@ -7281,7 +7286,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 कोई आर्टबोर्ड नहीं @@ -7306,7 +7311,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) @@ -7810,7 +7815,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 संख्या होनी चाहिए @@ -7902,7 +7907,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 विस्तृत करने के लिए डैश स्ट्रोक के साथ पाथ सिलेक्ट करें @@ -7910,7 +7915,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 बंद करें) @@ -8096,7 +8101,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 मिश्रित आकार का विस्तार करने के लिए बहुत जटिल है @@ -8149,7 +8154,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} @@ -8310,6 +8315,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} से अधिक गहरा घोंसला दिया जाता है @@ -8438,8 +8444,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 193363e217..e0c087159d 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 @@ -3227,6 +3228,8 @@ mark-style Japanese Japán Proof Setup Színpróba beállítása Properties Tulajdonságok Proportional Metrics Arányos metrika + H or V Style Vízszintes vagy függőleges stílus + Roman Italics Latin betűk dőlt változata Insert Aki Left Aki beszúrása balra Insert Aki Right Aki beszúrása jobbra Tsume Tsume @@ -3261,6 +3264,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 @@ -5206,6 +5210,7 @@ imageTrace Outline Körvonal @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog az `answers` csak olyan futtatáshoz való, ahol nincs kit megkérdezni: az alkalmazásban minden párbeszédpanelre a felhasználó válaszol @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} @@ -8904,6 +8909,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 @@ -9126,7 +9132,7 @@ breakText Glyphs Glifák @msg unexpected resources váratlan erőforrások @msg unknown CMYK profile `{name}` ismeretlen CMYK-profil: `{name}` @msg unknown File Info field `{k}` ismeretlen fájlinformációs mező: `{k}` -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) ismeretlen OpenType-funkció: `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; a - előtag kikapcsolja; a swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom és aalt egy alternatíva számát `tag=N` alakban fogadja, ahol N 0 és {_1} között lehet, például `salt=2`) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) ismeretlen OpenType-funkció: `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; a - előtag kikapcsolja; a swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom és aalt egy alternatíva számát `tag=N` alakban fogadja, ahol N 0 és {_1} között lehet, például `salt=2`) @msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) ismeretlen OpenType-funkció a featureChanges értékben: `{t}` (a `features` által fogadott címkék használhatók) @msg unknown PDF preset `{name}` (presets: {_1}) ismeretlen PDF-előbeállítás: `{name}` (előbeállítások: {_1}) @msg unknown Warp style ismeretlen hajlítási stílus diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index fdf06cc9ee..dc1930ea0a 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… @@ -1519,6 +1520,8 @@ lighting Light Cahaya Leading Leading No Break Tanpa pemenggalan Proportional Metrics Metrik proporsional + H or V Style Gaya horizontal atau vertikal + Roman Italics Miring Romawi Insert Aki Left Sisipkan aki kiri Insert Aki Right Sisipkan aki kanan Tsume Tsume @@ -2516,6 +2519,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 +4302,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 72e6836f50..51f8a0bdbf 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 @@ -2711,6 +2713,8 @@ mark-style Japanese Giapponese Proof Setup Impostazione prova Properties Proprietà Proportional Metrics Metrica proporzionale + H or V Style Stile orizzontale o verticale + Roman Italics Corsivo romano Insert Aki Left Inserisci aki a sinistra Insert Aki Right Inserisci aki a destra Tsume Tsume @@ -4444,6 +4448,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} @@ -7524,7 +7529,7 @@ breakText Glyphs Glifi @msg toString is not a function toString non è una funzione @msg too many arguments troppi argomenti @msg too many quantifiers troppi quantificatori -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) funzione OpenType sconosciuta `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; anteponi - per disattivarla; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom e aalt accettano il numero di un'alternativa come `tag=N` con N da 0 a {_1}, ad esempio `salt=2`) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) funzione OpenType sconosciuta `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; anteponi - per disattivarla; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom e aalt accettano il numero di un'alternativa come `tag=N` con N da 0 a {_1}, ad esempio `salt=2`) @msg unknown dither `{d}` (diffusion, pattern, noise or none) dithering sconosciuto `{d}` (diffusion, pattern, noise o none) @msg unknown panel `{panel}` pannello sconosciuto `{panel}` @msg unknown parameter `{key}` parametro sconosciuto `{key}` @@ -8646,6 +8651,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 18fc1b0c18..b741119325 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -50,6 +50,8 @@ font-technology Variable バリアブル x-Height x ハイト ICF Box 平均字面 Proportional Metrics プロポーショナルメトリクス + H or V Style 横組み・縦組み用かな + Roman Italics 欧文イタリック Insert Aki Left 前にアキを挿入 Insert Aki Right 後ろにアキを挿入 Tsume 文字ツメ @@ -3775,6 +3777,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 +4268,7 @@ theme Appearance 外観 # Photoshop-style raster effects (Effect menu, their dialogs). Radial Blur… ぼかし (放射状)… + Blur Center ぼかしの中心 Smart Blur… ぼかし (詳細)… Sharpen シャープ Unsharp Mask… アンシャープマスク… @@ -5210,6 +5214,7 @@ swatch Bright Violet ビビッドバイオレット @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` は尋ねる相手がいない実行専用です。アプリでは、各ダイアログに本人が回答します @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}` は不明なハイライトの指定です @@ -6731,7 +6736,7 @@ axis Y Axis Y 軸 @msg toString is not a function toString は関数ではありません @msg too many arguments 引数が多すぎます @msg too many quantifiers 量指定子が多すぎます -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) `{t}` は不明な OpenType 機能です (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt。オフにするには先頭に - を付けます。swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt には、`salt=2` のように `tag=N` の形式で代替字形の番号を指定できます。N は 0 から {_1} まで) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) `{t}` は不明な OpenType 機能です (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital。オフにするには先頭に - を付けます。swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt には、`salt=2` のように `tag=N` の形式で代替字形の番号を指定できます。N は 0 から {_1} まで) @msg unknown dither `{d}` (diffusion, pattern, noise or none) `{d}` は不明なディザの指定です (diffusion、pattern、noise、none のいずれか) @msg unknown panel `{panel}` `{panel}` は不明なパネルです @msg unknown parameter `{key}` `{key}` は不明なパラメーターです @@ -7854,6 +7859,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 5a5610bbaa..9c5677a478 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… არამკვეთრი ნიღაბი… @@ -1456,6 +1457,8 @@ lighting Light სინათლე Leading სტრიქონთა დაშორება No Break გადატანის გარეშე Proportional Metrics პროპორციული მეტრიკა + H or V Style ჰორიზონტალური ან ვერტიკალური სტილი + Roman Italics ლათინური კურსივი Insert Aki Left აკის ჩასმა მარცხნივ Insert Aki Right აკის ჩასმა მარჯვნივ Tsume ცუმე @@ -2438,6 +2441,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. შრიფტები, რომელთა ლიცენზია ჩაშენების უფლებას არ იძლევა, არ კოპირდება. @@ -5628,6 +5632,7 @@ imageTrace Outline კონტური @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` მხოლოდ ისეთი გაშვებისთვისაა, სადაც შესაკითხი არავინაა: აპში თითოეულ დიალოგს ადამიანი პასუხობს @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-ის ბუფერში ჩატვირთვა @@ -5708,6 +5713,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 6e5fcded02..5047ee026e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -44,6 +44,8 @@ font-technology Variable 가변 x-Height x 높이 ICF Box ICF 박스 Proportional Metrics 비례 메트릭 + H or V Style 가로 또는 세로 스타일 + Roman Italics 로마자 이탤릭 Insert Aki Left 앞 아키 삽입 Insert Aki Right 뒤 아키 삽입 Tsume 츠메 @@ -3763,6 +3765,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 +4248,7 @@ theme Appearance 외관 Free Transform 자유 변형 Perspective Distort 원근 왜곡 Radial Blur… 방사형 흐림… + Blur Center 흐림 중심 Smart Blur… 스마트 흐림… Sharpen 선명하게 Unsharp Mask… 언샤프 마스크… @@ -5137,6 +5141,7 @@ theme Appearance 외관 @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers`는 물어볼 사람이 없는 실행에만 쓰입니다. 앱에서는 사람이 각 대화 상자에 답합니다 @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}` @@ -8630,6 +8635,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에 그릴 수 있는 개체가 없습니다 @@ -8858,7 +8864,7 @@ breakText Glyphs 글리프 @msg unexpected resources 예상하지 못한 리소스 @msg unknown CMYK profile `{name}` 알 수 없는 CMYK 프로파일 `{name}` @msg unknown File Info field `{k}` 알 수 없는 파일 정보 필드 `{k}` -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) 알 수 없는 OpenType 기능 `{t}`(liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt. 끄려면 앞에 -를 붙이세요. swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt는 대체 글리프 번호를 `tag=N` 형식으로 받으며 N은 0에서 {_1} 사이입니다. 예: `salt=2`) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) 알 수 없는 OpenType 기능 `{t}`(liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital. 끄려면 앞에 -를 붙이세요. swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt는 대체 글리프 번호를 `tag=N` 형식으로 받으며 N은 0에서 {_1} 사이입니다. 예: `salt=2`) @msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) featureChanges의 알 수 없는 OpenType 기능 `{t}`(`features`가 받는 태그를 사용하세요) @msg unknown PDF preset `{name}` (presets: {_1}) 알 수 없는 PDF 프리셋 `{name}`(프리셋: {_1}) @msg unknown Warp style 알 수 없는 왜곡 스타일 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 2f45f25979..0a7f855f3f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1432,6 +1432,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… @@ -2038,6 +2039,8 @@ lighting Light Licht Leading Regelafstand No Break Niet afbreken Proportional Metrics Proportionele metingen + H or V Style Horizontale of verticale stijl + Roman Italics Romeinse cursief Insert Aki Left Aki links invoegen Insert Aki Right Aki rechts invoegen Tsume Tsume @@ -3035,6 +3038,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. @@ -4817,6 +4821,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} @@ -6976,6 +6981,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 @@ -7205,7 +7211,7 @@ imageTrace Outline Contour @msg unexpected resources onverwachte resources @msg unknown CMYK profile `{name}` onbekend CMYK-profiel `{name}` @msg unknown File Info field `{k}` onbekend veld `{k}` van Bestandsinfo -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) onbekende OpenType-functie `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; zet er - voor om uit te schakelen; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom en aalt accepteren het nummer van een alternatief als `tag=N` met N van 0 tot {_1}, zoals `salt=2`) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) onbekende OpenType-functie `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; zet er - voor om uit te schakelen; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom en aalt accepteren het nummer van een alternatief als `tag=N` met N van 0 tot {_1}, zoals `salt=2`) @msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) onbekende OpenType-functie `{t}` in featureChanges (de tags die `features` accepteert) @msg unknown PDF preset `{name}` (presets: {_1}) onbekende PDF-voorinstelling `{name}` (voorinstellingen: {_1}) @msg unknown Warp style onbekende warpstijl diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ce4e822fe5..a76cc38311 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… @@ -1524,6 +1525,8 @@ lighting Light Światło Leading Interlinia No Break Bez podziału Proportional Metrics Metryka proporcjonalna + H or V Style Styl poziomy lub pionowy + Roman Italics Kursywa łacińska Insert Aki Left Wstaw aki z lewej Insert Aki Right Wstaw aki z prawej Tsume Tsume @@ -2647,6 +2650,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 +4531,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} @@ -7765,7 +7770,7 @@ breakText Glyphs Glify @msg too many arguments zbyt wiele argumentów @msg too many quantifiers zbyt wiele kwantyfikatorów @msg turn on at least one side włącz co najmniej jedną stronę -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) nieznana funkcja OpenType `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefiks - wyłącza funkcję; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom i aalt przyjmują numer wariantu w postaci `tag=N`, gdzie N to liczba od 0 do {_1}, na przykład `salt=2`) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) nieznana funkcja OpenType `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefiks - wyłącza funkcję; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom i aalt przyjmują numer wariantu w postaci `tag=N`, gdzie N to liczba od 0 do {_1}, na przykład `salt=2`) @msg unknown dither `{d}` (diffusion, pattern, noise or none) nieznane rozpraszanie `{d}` (diffusion, pattern, noise lub none) @msg unknown panel `{panel}` nieznany panel `{panel}` @msg unknown parameter `{key}` nieznany parametr `{key}` @@ -8884,6 +8889,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 86b6393c8c..a75fe4e977 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2235,6 +2235,8 @@ antiAlias Sharp Nítido Proof Setup Configuração de Prova Properties Propriedades Proportional Metrics Métrica Proporcional + H or V Style Estilo Horizontal ou Vertical + Roman Italics Itálico Romano Insert Aki Left Inserir Aki à Esquerda Insert Aki Right Inserir Aki à Direita Tsume Tsume @@ -3486,6 +3488,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 +4909,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 +5429,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 @@ -9096,6 +9101,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 @@ -9318,7 +9324,7 @@ swatch Yellow Green Verde-amarelado @msg unexpected resources recursos inesperados @msg unknown CMYK profile `{name}` perfil CMYK desconhecido `{name}` @msg unknown File Info field `{k}` campo de Informações do Arquivo desconhecido `{k}` -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) recurso OpenType desconhecido `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefixe com - para desativar; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom e aalt aceitam o número de uma alternativa como `tag=N` com N de 0 a {_1}, como `salt=2`) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) recurso OpenType desconhecido `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefixe com - para desativar; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom e aalt aceitam o número de uma alternativa como `tag=N` com N de 0 a {_1}, como `salt=2`) @msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) recurso OpenType desconhecido `{t}` em featureChanges (as tags que `features` aceita) @msg unknown PDF preset `{name}` (presets: {_1}) predefinição de PDF desconhecida `{name}` (predefinições: {_1}) @msg unknown Warp style estilo de Deformação desconhecido diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 285c44076c..7aca0002f4 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 Копировать в «Пользовательский» @@ -2698,6 +2700,8 @@ mark-style Japanese Японский Proof Setup Настройка цветопробы Properties Свойства Proportional Metrics Пропорциональные метрики + H or V Style Горизонтальный или вертикальный стиль + Roman Italics Римский курсив Insert Aki Left Вставить аки слева Insert Aki Right Вставить аки справа Tsume Цумэ @@ -4440,6 +4444,7 @@ axis Both Оба @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` предназначен только для запуска, в котором некого спросить: в приложении человек сам отвечает на каждое диалоговое окно @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} @@ -4912,6 +4917,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 17f78d0c04..9646720231 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 @@ -2606,6 +2608,8 @@ font-technology Variable Variabla Proof Setup Provtrycksinställningar Properties Egenskaper Proportional Metrics Proportionella mått + H or V Style Vågrät eller lodrät stil + Roman Italics Romersk kursiv Insert Aki Left Infoga aki till vänster Insert Aki Right Infoga aki till höger Tsume Tsume @@ -4314,6 +4318,7 @@ axis Both Båda @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` är bara för en körning utan någon att fråga: i appen svarar personen på varje dialogruta @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} @@ -8680,6 +8685,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 22673b0ba3..c4b5e22148 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. @@ -1887,6 +1914,13 @@ fn uk() -> Lang { Lang::from_code("uk").expect("uk registered") } +/// The Ukrainian Color Library labels use the word for colors (кольорів), not flowers (квітів). +#[test] +fn ukrainian_color_library_labels_name_colors() { + assert_eq!(uk().catalog().plain("Color Library"), Some("Бібліотека кольорів")); + assert_eq!(uk().catalog().plain("Color Library…"), Some("Бібліотека кольорів…")); +} + /// Every Ukrainian plural has all three forms; exercise different endings through real lookups. #[test] fn ukrainian_plurals_have_three_forms() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 4a46d4cdbe..5657c612f5 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 @@ -2453,6 +2455,8 @@ shape Open Açık Proof Setup Prova Kurulumu Properties Özellikler Proportional Metrics Orantılı Metrikler + H or V Style Yatay veya Dikey Stil + Roman Italics Roma İtalik Insert Aki Left Sola Aki Ekle Insert Aki Right Sağa Aki Ekle Tsume Tsume @@ -4176,6 +4180,7 @@ axis Both Her İkisi @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` yalnızca sorulacak kimsenin olmadığı bir çalıştırma içindir: uygulamada her iletişim kutusunu kişi yanıtlar @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} @@ -4645,6 +4650,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 @@ -4823,6 +4829,7 @@ axis Both Her İkisi @msg workspace name can't be empty çalışma alanı adı boş olamaz @msg {C}: no effect at index {from} {C}: {from} endeksinde etkisi yok @msg {_1} failed: {e} {_1} başarısız oldu: {e} +@msg {saving} failed: {e} {saving} başarısız oldu: {e} @msg {_1} files can be opened but not written (see document.formats) {_1} dosyaları açılabilir ancak yazılamaz (bkz. document.formats) @msg {_1} font families available {_1} yazı tipi aileleri mevcut @msg {_1} is a live effect (Effect › Plug-ins) {_1} canlı bir efekttir (Efekt › Eklentiler) @@ -6754,6 +6761,1808 @@ axis Y Axis Y ekseni @msg no menu item that can be inserted runs this command eklenebilen hiçbir menü öğesi bu komutu çalıştırmaz @msg the action already has 10,000 steps eylemde zaten 10.000 adım var @msg the action set would be larger than 8 MiB eylem seti 8 MiB'tan büyük olurdu +# Status and error messages of commands and their parameter checks, scripts, file import and export, printing and plug-ins. +@msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions katı kip işlevlerinde 'caller', 'callee' ve 'arguments' kullanılamaz +@msg Alignment must be one of the choices Hizalama, seçeneklerden biri olmalıdır +@msg Boolean.prototype.{name} was called on a value that is not a Boolean Boolean.prototype.{name}, Boolean olmayan bir değer üzerinde çağrıldı +@msg CMYK images whose samples couldn't be read in CMYK were imported in RGB Örnekleri CMYK olarak okunamayan CMYK görüntüler RGB olarak içe aktarıldı +@msg Cannot write to the location of “{name}”; choose where to save it “{name}” konumuna yazılamıyor; nereye kaydedileceğini seçin +@msg DCS files can only be placed linked: use File › Place with Link on DCS dosyaları yalnızca bağlantılı olarak yerleştirilebilir: Dosya › Yerleştir komutunu Bağlantı açıkken kullanın +@msg Date.prototype method called on a value that is not a Date object Date.prototype yöntemi, Date nesnesi olmayan bir değer üzerinde çağrıldı +@msg Error.prototype.toString was called on a value that is not an object Error.prototype.toString, nesne olmayan bir değer üzerinde çağrıldı +@msg Function.prototype.toString was called on a value that is not a function Function.prototype.toString, işlev olmayan bir değer üzerinde çağrıldı +@msg Import SVG Filter reads SVG files, not SVGZ SVG Filtresini İçe Aktar, SVGZ dosyalarını okumaz; SVG dosyalarını okur +@msg JSON.parse: {why} (at offset {at}) JSON.parse: {why} (konum: {at}) +@msg JSON.stringify cannot write a structure that contains itself JSON.stringify kendini içeren bir yapıyı yazamaz +@msg Line Gap must be a number Satır Boşluğu bir sayı olmalıdır +@msg Namespace.prototype.toString needs a Namespace Namespace.prototype.toString için bir Namespace gerekir +@msg New Document profiles need the preferences folder, which this run doesn't have Yeni Belge profilleri için tercihler klasörü gerekir; bu çalıştırmada o klasör yok +@msg Number.prototype.{name} was called on a value that is not a number Number.prototype.{name}, sayı olmayan bir değer üzerinde çağrıldı +@msg Object.create's prototype must be an object or null Object.create için prototip bir nesne veya null olmalıdır +@msg Object.{function} was given a value that is not an object Object.{function} işlevine nesne olmayan bir değer verildi +@msg QName.prototype.toString needs a QName QName.prototype.toString için bir QName gerekir +@msg RegExp.prototype.{name} was called on a value that is not a RegExp object RegExp.prototype.{name}, RegExp nesnesi olmayan bir değer üzerinde çağrıldı +@msg Stencil Bridges: the selected art is too large or too detailed to bridge Şablon Köprüleri: seçili resim köprülenemeyecek kadar büyük veya ayrıntılı +@msg String.prototype.toString was called on a value that is not a string String.prototype.toString, dize olmayan bir değer üzerinde çağrıldı +@msg The {name} profile could not be read, so the new document has the default settings: {reason} {name} profili okunamadı, bu yüzden yeni belge varsayılan ayarları kullanıyor: {reason} +@msg Trap: more than {_1} pairs of objects lie close enough to trap, or too many objects share a horizontal range; trap fewer objects at a time Tuzak: {_1} çiftten fazla nesne tuzaklanacak kadar yakın duruyor veya çok fazla nesne aynı yatay aralığı paylaşıyor; bir seferde daha az nesne tuzaklayın +@msg Weed Box and Lines: no weeding line fits outside the art, and the weed box is off Ayıklama Kutusu ve Çizgileri: resmin dışına sığan bir ayıklama çizgisi yok ve ayıklama kutusu kapalı +@msg \\ at end of pattern desenin sonunda \\ +@msg `alignOn` cannot be empty `alignOn` boş olamaz +@msg `alignOn` must be a string `alignOn` bir dize olmalıdır +@msg `align` must be a string `align` bir dize olmalıdır +@msg `answer` for this {kind} dialog must be one of: {_1} bu {kind} iletişim kutusu için `answer` şunlardan biri olmalıdır: {_1} +@msg `answers` has more than {MAX_ANSWERS} answers `answers` içinde {MAX_ANSWERS} taneden fazla yanıt var +@msg `answers` is larger than 1 MiB `answers` 1 MiB'tan büyük +@msg `answers` must be a list of answers `answers` bir yanıt listesi olmalıdır +@msg `artboard` must be the index of an artboard of the document `artboard`, belgedeki bir çalışma yüzeyinin dizini olmalıdır +@msg `artboardsAt` must be [x, y] `artboardsAt` [x, y] olmalıdır +@msg `artboards` names an artboard the document does not have `artboards`, belgede olmayan bir çalışma yüzeyini belirtiyor +@msg `artboards` names an artboard twice `artboards` bir çalışma yüzeyini iki kez belirtiyor +@msg `at` must be [x, y] (got {at}) `at` [x, y] olmalıdır (verilen: {at}) +@msg `at` must be a point [x, y] `at` bir [x, y] noktası olmalıdır +@msg `beside` needs `side` `beside` için `side` gerekir +@msg `code` must be a whole number `code` bir tam sayı olmalıdır +@msg `colorMode` must be one of rgb, cmyk `colorMode` şunlardan biri olmalıdır: rgb, cmyk +@msg `colors` does not apply to the {name} reduction `colors`, {name} azaltması için geçerli değildir +@msg `colors` must be a whole number from 2 to 256 `colors` 2 ile 256 arasında bir tam sayı olmalıdır +@msg `colors` must be at least 9 for the uniform reduction tekdüze azaltma için `colors` en az 9 olmalıdır +@msg `colors` must be between 1 and {MAX_THEME_COLORS} (got {n}) `colors` 1 ile {MAX_THEME_COLORS} arasında olmalıdır (verilen: {n}) +@msg `count` must be a whole number from 0 to {MAX_COUNT} `count` 0 ile {MAX_COUNT} arasında bir tam sayı olmalıdır +@msg `ditherAmount` must be a number from 0 to 100 `ditherAmount` 0 ile 100 arasında bir sayı olmalıdır +@msg `fidelity` must be from {lo} to {hi} pt `fidelity` {lo} ile {hi} pt arasında olmalıdır +@msg `focal` and `radius` cannot be used together `focal` ve `radius` birlikte kullanılamaz +@msg `focal` must be an array of [subpath, anchor] pairs `focal`, [subpath, anchor] çiftlerinden oluşan bir dizi olmalıdır +@msg `focal` names [{si}, {ai}], which is not an anchor of the path `focal`, yolun bir bağlantı noktası olmayan [{si}, {ai}] çiftini belirtiyor +@msg `glyphAlternate` takes only null, which takes a glyph choice away (text.setGlyphAlternate makes one) `glyphAlternate` yalnızca null alır; null bir glif seçimini kaldırır (seçimi text.setGlyphAlternate yapar) +@msg `group` must be one of {_1} `group` şunlardan biri olmalıdır: {_1} +@msg `group` must be the Objects on Path group of `member` and `target` `group`, `member` ve `target` nesnelerinin Yol Üzerindeki Nesneler grubu olmalıdır +@msg `id` is an object id, not {v} `id` bir nesne kimliğidir, {v} değil +@msg `item` needs `index` `item` için `index` gerekir +@msg `kerningBefore` belongs to a line's first character, not to a character style (text.setRangeStyle sets it) `kerningBefore` bir karakter stiline değil, satırın ilk karakterine aittir (text.setRangeStyle ayarlar) +@msg `kinsokuType` must be "pushInFirst", "pushOutFirst" or "pushOutOnly" `kinsokuType` "pushInFirst", "pushOutFirst" veya "pushOutOnly" olmalıdır +@msg `leader` must be a string `leader` bir dize olmalıdır +@msg `max` must be 1 to {MAX_SUGGESTIONS} `max` 1 ile {MAX_SUGGESTIONS} arasında olmalıdır +@msg `name` must be a name that is not empty `name` boş olmayan bir ad olmalıdır +@msg `name` must not be empty `name` boş olmamalıdır +@msg `origin` must be [x, y] in points `origin` punto cinsinden [x, y] olmalıdır +@msg `picks` must be an array (got {v}) `picks` bir dizi olmalıdır (verilen: {v}) +@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` 1 ile {MAX_PICKS} arasında seçim içermelidir (verilen: {_1}) +@msg `points` must hold from 2 to 100000 points `points` 2 ile 100000 arasında nokta içermelidir +@msg `radius` must be 0 or more `radius` 0 veya daha büyük olmalıdır +@msg `rect` must be [x, y, width, height] `rect` [x, y, width, height] olmalıdır +@msg `rect` must be [x0, y0, x1, y1] (got {r}) `rect` [x0, y0, x1, y1] olmalıdır (verilen: {r}) +@msg `replace` must be a string `replace` bir dize olmalıdır +@msg `rows` must be lists of numbers or nulls, not {r} `rows`, sayı veya null listeleri olmalıdır, {r} değil +@msg `scale` must be a number from 0.001 to 1000 `scale` 0.001 ile 1000 arasında bir sayı olmalıdır +@msg `scope.{key}` must be a non-empty array `scope.{key}` boş olmayan bir dizi olmalıdır +@msg `scope` must be "document", {artboards} or {layers} `scope` "document", {artboards} veya {layers} olmalıdır +@msg `side` must be "left", "right", "top" or "bottom" `side` "left", "right", "top" veya "bottom" olmalıdır +@msg `side` places the artboard: leave out x, y, width and height `side` çalışma yüzeyini yerleştirir: x, y, width ve height değerlerini vermeyin +@msg `source` is the only path in series group `target` `source`, `target` seri grubundaki tek yoldur +@msg `spacing` makes more than {MAX_COUNT} lines across the box `spacing`, kutu boyunca {MAX_COUNT} taneden fazla çizgi oluşturuyor +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` 0'dan büyük ve en fazla {MAX_DISTANCE} pt olmalıdır +@msg `target` must be an object of the same Objects on Path group as `member` `target`, `member` ile aynı Yol Üzerindeki Nesneler grubundaki bir nesne olmalıdır +@msg `tolerance` must be from 0 to 100 pt `tolerance` 0 ile 100 pt arasında olmalıdır +@msg `version` must be 0 or {_1} `version` 0 veya {_1} olmalıdır +@msg `version` must be 0 or {newest} `version` 0 veya {newest} olmalıdır +@msg `warichuAlign` must be one of {_1} `warichuAlign` şunlardan biri olmalıdır: {_1} +@msg `warichuLines` must be a whole number from {_1} to {_2} `warichuLines` {_1} ile {_2} arasında bir tam sayı olmalıdır +@msg `weight` must be from 0.01 to 1000 pt `weight` 0.01 ile 1000 pt arasında olmalıdır +@msg `weights` must be a list of {_1} numbers, one per row (got {v}) `weights`, her satır için bir tane olmak üzere {_1} sayıdan oluşan bir liste olmalıdır (verilen: {v}) +@msg `xml` must be a string `xml` bir dize olmalıdır +@msg `{KEY}` entry {n} gives the paragraph at byte {start} of {_1} other indents than an entry before it `{KEY}` içindeki {n} numaralı girdi, {_1} nesnesinin {start} numaralı baytındaki paragrafa önceki bir girdiden farklı girintiler veriyor +@msg `{KEY}` entry {n} must be an object `{KEY}` içindeki {n} numaralı girdi bir nesne olmalıdır +@msg `{KEY}` entry {n} sets neither `leftIndent` nor `firstLineIndent` `{KEY}` içindeki {n} numaralı girdi ne `leftIndent` ne de `firstLineIndent` ayarlıyor +@msg `{KEY}` entry {n}: `id` must be an object id `{KEY}` girdi {n}: `id` bir nesne kimliği olmalıdır +@msg `{KEY}` entry {n}: `start` must be a byte offset `{KEY}` girdi {n}: `start` bir bayt konumu olmalıdır +@msg `{KEY}` entry {n}: `{k}` must be a number from -{MAX_PARA} to {MAX_PARA} pt `{KEY}` girdi {n}: `{k}` -{MAX_PARA} ile {MAX_PARA} pt arasında bir sayı olmalıdır +@msg `{KEY}` entry {n}: no paragraph of {_1} starts at byte {start} `{KEY}` girdi {n}: {_1} nesnesinin hiçbir paragrafı {start} numaralı baytta başlamıyor +@msg `{KEY}` entry {n}: unknown key `{k}` `{KEY}` girdi {n}: bilinmeyen anahtar `{k}` +@msg `{KEY}` entry {n}: {_1} is not a type object `{KEY}` girdi {n}: {_1} bir metin nesnesi değil +@msg `{KEY}` is empty `{KEY}` boş +@msg `{KEY}` must be a list `{KEY}` bir liste olmalıdır +@msg `{KEY}` takes at most {MAX_PARAGRAPH_INDENTS} entries (got {_1}) `{KEY}` en fazla {MAX_PARAGRAPH_INDENTS} girdi alır (verilen: {_1}) +@msg `{KEY}` takes no `{other}` beside it `{KEY}` yanında `{other}` alamaz +@msg `{base}` is larger than {_1} MB `{base}` {_1} MB'tan büyük +@msg `{base}` is not in the DCS file's folder `{base}` DCS dosyasının klasöründe değil +@msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` {MAX_EDIT_WORDS} taneden fazla sözcük içeriyor +@msg `{key}` must be 0 or more `{key}` 0 veya daha büyük olmalıdır +@msg `{key}` must be [x, y] numbers `{key}` [x, y] sayıları olmalıdır +@msg `{key}` must be a list of words `{key}` bir sözcük listesi olmalıdır +@msg `{key}` must be a list, not {v} `{key}` bir liste olmalıdır, {v} değil +@msg `{key}` must be a number or null, not {v} `{key}` bir sayı veya null olmalıdır, {v} değil +@msg `{key}` must be a whole number of 0 or more `{key}` 0 veya daha büyük bir tam sayı olmalıdır +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` 0 ile {MAX_DISTANCE} pt arasında olmalıdır +@msg `{key}` must be from {lo} to {hi}, not {v} `{key}` {lo} ile {hi} arasında olmalıdır, {v} değil +@msg `{key}` must be one of auto, always, never `{key}` şunlardan biri olmalıdır: auto, always, never +@msg `{key}` must be one of miter, round, bevel `{key}` şunlardan biri olmalıdır: miter, round, bevel +@msg `{key}` must be one word of at most {_1} characters `{key}` en fazla {_1} karakterlik tek bir sözcük olmalıdır +@msg `{key}` must hold single words of at most {_1} characters `{key}` en fazla {_1} karakterlik tek sözcükler içermelidir +@msg `{key}` must name an object attached to the path of an Objects on Path group `{key}`, bir Yol Üzerindeki Nesneler grubunun yoluna iliştirilmiş bir nesneyi belirtmelidir +@msg `{key}` names an object that is hidden or locked `{key}` gizli veya kilitli bir nesneyi belirtiyor +@msg `{name}` is a file of its own, which can only be found next to the DCS file's path `{name}` ayrı bir dosyadır ve yalnızca DCS dosyasının yolunun yanında bulunabilir +@msg `{name}`: {_1}: {e} `{name}`: {_1}: {e} +@msg `{u}` is no Unicode character `{u}` bir Unicode karakteri değil +@msg `{word}` isn't in the custom dictionary `{word}` özel sözlükte yok +@msg a CMap has too many mappings bir CMap çok fazla eşleme içeriyor +@msg a \\u escape needs four hexadecimal digits bir \\u kaçışı için dört onaltılık basamak gerekir +@msg a comma in an XPath expression must separate function arguments XPath ifadesindeki bir virgül, işlev bağımsız değişkenlerini ayırmalıdır +@msg a document holds at most {_1} SVG filters bir belge en fazla {_1} SVG filtresi içerir +@msg a document with unsaved changes has no recovery copy kaydedilmemiş değişiklikleri olan bir belgenin kurtarma kopyası yok +@msg a font's data is too large bir yazı tipinin verileri çok büyük +@msg a font's subroutines are too large bir yazı tipinin alt yordamları çok büyük +@msg a function declaration without a name adı olmayan bir işlev bildirimi +@msg a host value has too many entries bir ana bilgisayar değeri çok fazla girdi içeriyor +@msg a host value is nested too deep bir ana bilgisayar değeri çok derin iç içe geçmiş +@msg a namespace declaration uses a reserved prefix or URI bir ad alanı bildirimi ayrılmış bir önek veya URI kullanıyor +@msg a namespace qualifier is undefined bir ad alanı niteleyicisi tanımlı değil +@msg a namespace with an empty URI cannot have a prefix URI'si boş olan bir ad alanının öneki olamaz +@msg a number has no digits bir sayının rakamı yok +@msg a number's exponent has no digits bir sayının üssünde rakam yok +@msg a number's fraction has no digits bir sayının kesir kısmında rakam yok +@msg a property descriptor cannot have both a value or writable and a get or set bir özellik tanımlayıcısı hem value veya writable hem de get veya set içeremez +@msg a property descriptor must be an object bir özellik tanımlayıcısı bir nesne olmalıdır +@msg a property's {name} must be a function or undefined bir özelliğin {name} değeri bir işlev veya undefined olmalıdır +@msg a stream in it would decode to more than 256 MB, or its decode parameters can't be applied içindeki bir akışın kodu çözülünce 256 MB'ı aşıyor veya kod çözme parametreleri uygulanamıyor +@msg a string holds a control character bir dize denetim karakteri içeriyor +@msg a string holds an escape sequence JSON does not have bir dize JSON'da olmayan bir kaçış dizisi içeriyor +@msg a string is not closed bir dize kapatılmamış +@msg an SVG filter is named by its id: give `xml` with `name` bir SVG filtresi kimliğiyle adlandırılır: `xml` değerini `name` ile birlikte verin +@msg an XML element has two attributes with the same name bir XML öğesinde aynı ada sahip iki öznitelik var +@msg an XML value cannot be inserted into itself or its descendants bir XML değeri kendisine veya alt öğelerine eklenemez +@msg an XML value's children cannot be assigned by position bir XML değerinin alt öğeleri konuma göre atanamaz +@msg an XML value's children cannot be deleted by position bir XML değerinin alt öğeleri konuma göre silinemez +@msg an XMLList converts to XML only when it has one item bir XMLList yalnızca tek öğesi olduğunda XML'e dönüşür +@msg an XPath node test is missing bir XPath düğüm testi eksik +@msg an XPath operand is missing bir XPath işleneni eksik +@msg an XPath operator is missing bir XPath işleci eksik +@msg an XPath predicate or step cannot follow here burada bir XPath yüklemi veya adımı gelemez +@msg an XPath predicate or step follows a value that is not a node-set bir XPath yüklemi veya adımı, düğüm kümesi olmayan bir değerin ardından geliyor +@msg an XPath step is missing bir XPath adımı eksik +@msg an image couldn't be decoded and is missing from the picture bir görüntünün kodu çözülemedi ve resimde eksik +@msg an image of {w} × {h} pixels is too large to convert (at most {_1} pixels) {w} × {h} piksellik bir görüntü dönüştürülemeyecek kadar büyük (en fazla {_1} piksel) +@msg apply was called on a value that is not a function apply, işlev olmayan bir değer üzerinde çağrıldı +@msg area type in a thread cannot use Dynamic Text: {frames} zincirli metindeki alan metni Dinamik Metin kullanamaz: {frames} +@msg array literal too long dizi değişmezi çok uzun +@msg assignment to a constant binding sabit bir bağlamaya atama +@msg at least one row that isn't excluded needs a weight above 0 hariç tutulmayan en az bir satırın ağırlığı 0'dan büyük olmalıdır +@msg bad point {v}: expected [x, y] hatalı nokta {v}: [x, y] bekleniyordu +@msg blend must be a mode name blend bir mod adı olmalıdır +@msg both sides of an XPath | must select nodes bir XPath | işlecinin iki tarafı da düğüm seçmelidir +@msg canceled iptal edildi +@msg cannot convert the object to a primitive value nesne ilkel bir değere dönüştürülemiyor +@msg cannot convert undefined or null to an object undefined veya null bir nesneye dönüştürülemez +@msg character dimensions cannot be represented with the source text transform karakter boyutları kaynak metin dönüşümüyle ifade edilemiyor +@msg character dimensions cannot be represented with the target text transform karakter boyutları hedef metin dönüşümüyle ifade edilemiyor +@msg continuation must be an array of path chunks continuation, yol parçalarından oluşan bir dizi olmalıdır +@msg continuation requires points continuation için points gerekir +@msg each path chunk must contain 1 to 4096 points her yol parçası 1 ile 4096 arasında nokta içermelidir +@msg each pick is {{at: [x, y]}} or {{rect: [x0, y0, x1, y1]}} (got {v}) her seçim {{at: [x, y]}} veya {{rect: [x0, y0, x1, y1]}} biçimindedir (verilen: {v}) +@msg each weight must be a number of 0 or more (got {v}) her ağırlık 0 veya daha büyük bir sayı olmalıdır (verilen: {v}) +@msg finally table {t} out of range finally tablosu {t} aralık dışında +@msg flags cannot be given with a RegExp object RegExp nesnesiyle birlikte bayrak verilemez +@msg function declaration index out of range işlev bildirimi dizini aralık dışında +@msg give `char`, `text`, `code` or `unicode` `char`, `text`, `code` veya `unicode` verin +@msg give `count` or `spacing`, not both `count` veya `spacing` verin, ikisini birden değil +@msg give `name`, an SVG filter's name bir SVG filtresinin adı olan `name` değerini verin +@msg give `path`, an SVG file, or `svg`, SVG text bir SVG dosyası olan `path` veya SVG metni olan `svg` verin +@msg give `xml`, one SVG element tek bir SVG öğesi olan `xml` değerini verin +@msg give exactly one of `at`, `rect` and `points` `at`, `rect` ve `points` değerlerinden tam olarak birini verin +@msg give exactly one of `path`, `data` and `dataBase64` `path`, `data` ve `dataBase64` değerlerinden tam olarak birini verin +@msg give index or indexes, not both index veya indexes verin, ikisini birden değil +@msg give one element tek bir öğesi verin +@msg give opacity or blend opacity veya blend verin +@msg handler at {_1} expects {_2} values but its range starts with {d} {_1} konumundaki işleyici {_2} değer bekliyor, ancak aralığı {d} ile başlıyor +@msg handler depth too large işleyici derinliği çok büyük +@msg handler range {_1}..{_2} out of range işleyici aralığı {_1}..{_2} aralık dışında +@msg hiddenLayers must be true or false hiddenLayers true veya false olmalıdır +@msg hvcC hvcC +@msg images in a spot ink whose samples couldn't be read were imported in RGB örnekleri okunamayan spot mürekkepli görüntüler RGB olarak içe aktarıldı +@msg images past the most pixels one file may hold were left out bir dosyanın tutabileceği en fazla piksel sayısını aşan görüntüler dışarıda bırakıldı +@msg images too large to read were left out okunamayacak kadar büyük görüntüler dışarıda bırakıldı +@msg indexes may hold at most {MAX_GUIDE_INDEXES} entries indexes en fazla {MAX_GUIDE_INDEXES} girdi içerebilir +@msg indexes must be an array of guide indexes indexes, kılavuz dizinlerinden oluşan bir dizi olmalıdır +@msg instruction out of range yönerge aralık dışında +@msg instruction {pc} ({op}) pops below the stack {pc} numaralı yönerge ({op}) yığının altına iniyor +@msg instruction {pc} reached with stack depths {seen} and {d} {pc} numaralı yönergeye {seen} ve {d} yığın derinlikleriyle ulaşıldı +@msg invalid array length geçersiz dizi uzunluğu +@msg invalid group geçersiz grup +@msg invalid object id {v}: expected a non-negative integer geçersiz nesne kimliği {v}: negatif olmayan bir tam sayı bekleniyordu +@msg invalid regular expression flag '{_1}' geçersiz düzenli ifade bayrağı '{_1}' +@msg invalid regular expression: {m} geçersiz düzenli ifade: {m} +@msg invalid time value geçersiz zaman değeri +@msg is a confirm's answer, whose `value` must be true or false bir confirm yanıtıdır ve `value` değeri true veya false olmalıdır +@msg is a prompt's answer, whose `value` must be a string or null bir prompt yanıtıdır ve `value` değeri bir dize veya null olmalıdır +@msg is an alert's answer, whose `value` must be "ok" bir alert yanıtıdır ve `value` değeri "ok" olmalıdır +@msg is longer than 16 KiB 16 KiB'tan uzun +@msg it draws its image through a clipping path görüntüsünü bir kırpma yolu içinden çiziyor +@msg it draws no image hiçbir görüntü çizmiyor +@msg it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes {MAX_DICTIONARY_FILE_BYTES} bayttan büyük +@msg it isn't a file bir dosya değil +@msg it names {_1} plates, and at most {MAX_PLATES} are read {_1} kalıp belirtiyor ve en fazla {MAX_PLATES} tanesi okunuyor +@msg its art is too long or too detailed for a head resmi bir ok ucu için çok uzun veya çok ayrıntılı +@msg its art paints nothing resmi hiçbir şey boyamıyor +@msg its image is too large to read görüntüsü okunamayacak kadar büyük +@msg its plates are too large: more than {MAX_SAMPLES} pixels together kalıpları çok büyük: toplamda {MAX_SAMPLES} pikselden fazla +@msg its plates are too large: {_1} plates of {w} × {h} pixels kalıpları çok büyük: {w} × {h} piksellik {_1} kalıp +@msg its plates can't be kept together kalıpları bir arada tutulamıyor +@msg its shapes could not be combined into one şekilleri tek bir şekilde birleştirilemedi +@msg jump to {pc}, past the end sonun ötesindeki {pc} konumuna atlama +@msg legacyNameEncoding must be one of {_1} legacyNameEncoding şunlardan biri olmalıdır: {_1} +@msg localize: the first argument must be a localization object or a string localize: ilk bağımsız değişken bir yerelleştirme nesnesi veya bir dize olmalıdır +@msg missing `picks` `picks` eksik +@msg missing `word` `word` eksik +@msg must be an object with `kind` and `value` `kind` ve `value` içeren bir nesne olmalıdır +@msg must have `kind` alert, confirm or prompt `kind` değeri alert, confirm veya prompt olmalıdır +@msg must have exactly `kind` and `value` yalnızca `kind` ve `value` içermelidir +@msg needs a closing quote after the name addan sonra bir kapanış tırnağı gerekir +@msg needs a name bir ad gerekir +@msg needs a name of at most 64 bytes en fazla 64 baytlık bir ad gerekir +@msg needs a name of letters, digits and _, or a quoted name harf, rakam ve _ karakterlerinden oluşan bir ad veya tırnak içinde bir ad gerekir +@msg needs a name without control characters denetim karakteri içermeyen bir ad gerekir +@msg nesting too deep iç içe geçme çok derin +@msg no HP-GL format HP-GL biçimi yok +@msg no New Document profile called `{shown}` ({_1}) `{shown}` adlı bir Yeni Belge profili yok ({_1}) +@msg no SVG filter at index {k} {k} dizininde SVG filtresi yok +@msg no arrowheads file here burada ok uçları dosyası yok +@msg no character has code {code} hiçbir karakterin kodu {code} değil +@msg no custom arrowhead {name} (see stroke.arrowheads.list) {name} adlı özel ok ucu yok (bkz. stroke.arrowheads.list) +@msg no file to open açılacak dosya yok +@msg no instructions yönerge yok +@msg no layer to rename yeniden adlandırılacak katman yok +@msg no random numbers ({e}) rastgele sayı yok ({e}) +@msg no selected or given object has a visible 3D effect seçili veya verilen nesnelerin hiçbirinde görünür bir 3D efekti yok +@msg no such artboard {v} böyle bir çalışma yüzeyi yok: {v} +@msg no symbol named `{_1}` `{_1}` adlı bir sembol yok +@msg node {_1} already has the text variable `{_2}` {_1} düğümünde `{_2}` metin değişkeni zaten var +@msg not a DCS file bir DCS dosyası değil +@msg not a RegExp object bir RegExp nesnesi değil +@msg not a regular expression bir düzenli ifade değil +@msg not an action set: the text doesn't start with /version and a number bir eylem seti değil: metin /version ve bir sayıyla başlamıyor +@msg nothing to repeat yinelenecek bir şey yok +@msg numbers out of order in {_1} quantifier {_1} niceleyicisinde sayılar sırasız +@msg object {_1} needs a 3D effect {_1} nesnesinde bir 3D efekti olmalıdır +@msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic nesne {_1}: içi boş bir Kalıp Çıkarma ve Eğim efektinin kapakları yoktur: bir grafik eşlemek için Kapak seçeneğini açın +@msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front nesne {_1}: derinlik 0 olduğunda nesnenin tek yüzü vardır: grafiklerini ön yüze eşleyin +@msg object {_1}: {_2} nesne {_1}: {_2} +@msg object {_1}: {e} nesne {_1}: {e} +@msg object {_1}: {name} at index {index} has no lighting presets; set its lights with effect.setParams nesne {_1}: {index} dizinindeki {name} için ışık ön ayarı yok; ışıklarını effect.setParams ile ayarlayın +@msg opacity must be a number opacity bir sayı olmalıdır +@msg operand too large işlenen çok büyük +@msg order is a whole number from 0 to {others}, not `{v}` order 0 ile {others} arasında bir tam sayıdır, `{v}` değil +@msg path chunks must share their boundary point yol parçaları sınır noktalarını paylaşmalıdır +@msg pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false pdfCompatible: false, useArtboards false olduğunda düzenlenebilir resmi korumak için çalışma yüzeylerine ihtiyaç duyar +@msg point x must be a number noktanın x değeri bir sayı olmalıdır +@msg point y must be a number noktanın y değeri bir sayı olmalıdır +@msg points must be [x,y] pairs points [x,y] çiftleri olmalıdır +@msg points must be finite canvas points points sonlu tuval noktaları olmalıdır +@msg range out of order in character class karakter sınıfında aralık sırasız +@msg reduce of an empty array with no initial value başlangıç değeri olmadan boş bir dizide reduce +@msg regular expression flag '{_1}' given twice düzenli ifade bayrağı '{_1}' iki kez verildi +@msg sampled text would exceed the canvas (coordinates out of range) örneklenen metin tuvali aşacaktır (koordinatlar aralık dışındadır) +@msg select an SVG filter bir SVG filtresi seçin +@msg select an object with a 3D effect 3D efekti olan bir nesne seçin +@msg select an object with a 3D effect, or give its id in ids 3D efekti olan bir nesne seçin veya kimliğini ids içinde verin +@msg select one layer, group or object to rename yeniden adlandırmak için tek bir katman, grup veya nesne seçin +@msg select the art to weed ayıklanacak resmi seçin +@msg select type on a path or area type yol üzerindeki yazıyı veya alan metnini seçin +@msg side is left or right, not `{v}` side left veya right olur, `{v}` değil +@msg source text transform is collapsed or unrepresentable kaynak metin dönüşümü çökmüş veya ifade edilemiyor +@msg table must be true or false table true veya false olmalıdır +@msg takes one name tek bir ad alır +@msg target text transform is collapsed or unrepresentable hedef metin dönüşümü çökmüş veya ifade edilemiyor +@msg that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer bu çok fazla parça (en fazla 100000) veya kesik çizgi adımı oluşturuyor: çizgi desenini basitleştirin veya kesik çizgileri uzatın +@msg the Layers panel is not shown Katmanlar paneli gösterilmiyor +@msg the Layers panel's search, filter or Show Layers Only hides its row Katmanlar panelinin araması, filtresi veya Yalnızca Katmanları Göster seçeneği bu satırı gizliyor +@msg the Objects on Path group is hidden or locked Yol Üzerindeki Nesneler grubu gizli veya kilitli +@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes SVG dosyası {MAX_IMPORT_BYTES} bayttan büyük +@msg the XML operation needs an XML or XMLList value XML işlemi için bir XML veya XMLList değeri gerekir +@msg the XPath expression does not evaluate to a node-set XPath ifadesinin sonucu bir düğüm kümesi değil +@msg the XPath expression ends early XPath ifadesi erken bitiyor +@msg the XPath expression has an unmatched ) XPath ifadesinde eşleşmeyen bir ) var +@msg the XPath expression has an unmatched ] XPath ifadesinde eşleşmeyen bir ] var +@msg the XPath expression has an unmatched closing bracket XPath ifadesinde eşleşmeyen bir kapanış ayracı var +@msg the XPath expression selects a namespace node, which is not an XML value XPath ifadesi bir ad alanı düğümü seçiyor; bu bir XML değeri değildir +@msg the XPath expression selects the root node, which is not an XML value XPath ifadesi kök düğümü seçiyor; bu bir XML değeri değildir +@msg the XPath function {name} needs a node-set {name} XPath işlevi için bir düğüm kümesi gerekir +@msg the XPath function {name} takes the wrong number of arguments {name} XPath işlevine yanlış sayıda bağımsız değişken verildi +@msg the XPath name functions need a node-set XPath ad işlevleri için bir düğüm kümesi gerekir +@msg the XPath prefix {shown} is not bound to a namespace {shown} XPath öneki bir ad alanına bağlı değil +@msg the XPath variable ${shown} is not bound ${shown} XPath değişkeni bağlı değil +@msg the argument list is not an object bağımsız değişken listesi bir nesne değil +@msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it bir grafik serisindeki grafik tasarımının çizimi tasarımdan yeniden çizilir: değiştirmek için tasarımı düzenleyin +@msg the artwork is too large for EPS: what follows 256 MB of PostScript was left out resim EPS için çok büyük: 256 MB'lık PostScript'ten sonrası dışarıda bırakıldı +@msg the bitmaps hold more pixels than one file may bitmapler bir dosyanın tutabileceğinden fazla piksel içeriyor +@msg the code runs past its last instruction kod son yönergesinin ötesine geçiyor +@msg the curve tolerance must be from 0.01 to 10 points eğri toleransı 0.01 ile 10 punto arasında olmalıdır +@msg the custom dictionary couldn't be saved to {_1}: {e} özel sözlük şuraya kaydedilemedi: {_1}: {e} +@msg the custom dictionary {_1} can't be read ({why}), so it is left as it is özel sözlük {_1} okunamıyor ({why}), bu yüzden olduğu gibi bırakıldı +@msg the document already has an SVG filter named {name} belgede {name} adlı bir SVG filtresi zaten var +@msg the document has another SVG filter named {name}: use svgFilter.apply, or svgFilter.define with `replace` to edit it belgede {name} adlı başka bir SVG filtresi var: svgFilter.apply kullanın veya düzenlemek için svgFilter.define komutunu `replace` ile kullanın +@msg the document has no SVG filter named {name} belgede {name} adlı bir SVG filtresi yok +@msg the document has no SVG filter named {r} belgede {r} adlı bir SVG filtresi yok +@msg the document has no color swatches belgede renk örneği yok +@msg the document's swatches hold {_1} colors; the document reduction takes at most 255 belgenin renk örnekleri {_1} renk içeriyor; belge azaltması en fazla 255 renk alır +@msg the file isn't valid SVG: {e} dosya geçerli bir SVG değil: {e} +@msg the file names no plate dosya hiçbir kalıp belirtmiyor +@msg the function's prototype is not an object işlevin prototipi bir nesne değil +@msg the guide is hidden or locked kılavuz gizli veya kilitli +@msg the library's file is outside the read roots kütüphanenin dosyası okuma köklerinin dışında +@msg a linked JavaScript file is outside the read roots bağlantılı bir JavaScript dosyası okuma köklerinin dışında +@msg the line is too long, or the paths it passes too many, to check çizgi denetlenemeyecek kadar uzun veya geçtiği yollar çok fazla +@msg the method needs an XML value yöntem için bir XML değeri gerekir +@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) boya bir serbest biçimli degrade değil (paint.editGradient {kind} ile bir tane uygulayın) +@msg the parameters or body do not form one function parametreler veya gövde tek bir işlev oluşturmuyor +@msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it yapıştırılan {name} SVG filtresi belgedeki aynı adlı filtreden farklı çiziyor ve ona uyan boş bir ad yok +@msg the paths are too many or too tangled to find where they cross yollar, kesiştikleri yerler bulunamayacak kadar çok veya karışık +@msg the pen table holds more than 255 pens kalem tablosu 255 taneden fazla kalem içeriyor +@msg the plates can't be kept kalıplar korunamıyor +@msg the position table does not match the instructions konum tablosu yönergelerle eşleşmiyor +@msg the prompt's text is longer than {MAX_PROMPT_BYTES} bytes istem metni {MAX_PROMPT_BYTES} bayttan uzun +@msg the radix must be between 2 and 36 taban 2 ile 36 arasında olmalıdır +@msg the rectangle or line reaches too many paths to check dikdörtgen veya çizgi denetlenemeyecek kadar çok yola ulaşıyor +@msg the right side of 'in' is not an object 'in' işlecinin sağ tarafı bir nesne değil +@msg the right side of 'instanceof' is not a function 'instanceof' işlecinin sağ tarafı bir işlev değil +@msg the selected art is nested more than {MAX_DEPTH} levels deep seçili resim {MAX_DEPTH} düzeyden daha derin iç içe geçmiş +@msg the selected art is too large to measure seçili resim ölçülemeyecek kadar büyük +@msg the selection has no outlines to weed around seçimde çevresi ayıklanacak anahat yok +@msg the value bind was called on is not a function bind'ın çağrıldığı değer bir işlev değil +@msg the value is not a constructor değer bir oluşturucu değil +@msg the value is not a function değer bir işlev değil +@msg the value is not a valid XML name değer geçerli bir XML adı değil +@msg the value is not an XML attribute name değer bir XML öznitelik adı değil +@msg the value is not an XML name değer bir XML adı değil +@msg the weeding lines cross the art's outlines too many times to measure; use fewer lines ayıklama çizgileri resmin anahatlarını ölçülemeyecek kadar çok kez kesiyor; daha az çizgi kullanın +@msg the weeding lines pass too close to too many outline segments to measure; use fewer lines or a smaller gap ayıklama çizgileri ölçülemeyecek kadar çok anahat parçasının çok yakınından geçiyor; daha az çizgi veya daha küçük bir boşluk kullanın +@msg the weeding lines would be more than {max_pieces} pieces ayıklama çizgileri {max_pieces} parçadan fazla olurdu +@msg the {_1} plate lies outside the file {_1} kalıbı dosyanın dışında +@msg this is a binary DXF file, which can't be read: save it from the CAD app as an ASCII DXF and open that bu ikili bir DXF dosyası ve okunamıyor: CAD uygulamasından ASCII DXF olarak kaydedip onu açın +@msg this warp's points can't be edited: use Reset with Mesh first bu çarpıtmanın noktaları düzenlenemez: önce Ağ ile Sıfırla komutunu kullanın +@msg toExponential() digits must be between 0 and 20 toExponential() basamak sayısı 0 ile 20 arasında olmalıdır +@msg toFixed() digits must be between 0 and 20 toFixed() basamak sayısı 0 ile 20 arasında olmalıdır +@msg toISOString is not a function toISOString bir işlev değil +@msg toPrecision() argument must be between 1 and 21 toPrecision() bağımsız değişkeni 1 ile 21 arasında olmalıdır +@msg toSource: a getter cannot be written as source toSource: bir alıcı kaynak olarak yazılamaz +@msg toSource: an array with properties besides its elements, a property that is not enumerable or another prototype cannot be written as source toSource: öğelerinin yanında özellikleri, numaralandırılamayan bir özelliği veya başka bir prototipi olan bir dizi kaynak olarak yazılamaz +@msg toSource: an object with a property that is not enumerable, or whose prototype is not Object.prototype, cannot be written as source toSource: numaralandırılamayan bir özelliği olan veya prototipi Object.prototype olmayan bir nesne kaynak olarak yazılamaz +@msg toSource: the source is too long toSource: kaynak çok uzun +@msg toSource: the value contains itself toSource: değer kendini içeriyor +@msg toSource: the value has too many entries toSource: değer çok fazla girdi içeriyor +@msg toSource: the value is nested too deep toSource: değer çok derin iç içe geçmiş +@msg toString is not a function toString bir işlev değil +@msg too many arguments çok fazla bağımsız değişken +@msg too many quantifiers çok fazla niceleyici +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) bilinmeyen OpenType özelliği `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; kapatmak için başına - koyun; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom ve aalt bir alternatifin numarasını `tag=N` biçiminde alır, N 0 ile {_1} arasındadır, örneğin `salt=2`) +@msg unknown dither `{d}` (diffusion, pattern, noise or none) bilinmeyen renk taklidi `{d}` (diffusion, pattern, noise veya none) +@msg unknown panel `{panel}` bilinmeyen panel `{panel}` +@msg unknown parameter `{key}` bilinmeyen parametre `{key}` +@msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) bilinmeyen azaltma `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform veya document) +@msg unmatched ')' eşleşmeyen ')' +@msg unterminated character class sonlandırılmamış karakter sınıfı +@msg unterminated group sonlandırılmamış grup +@msg wordGap and lineGap need area type in the selection wordGap ve lineGap için seçimde alan metni olmalıdır +@msg xpath needs its variables as an object xpath, değişkenlerini bir nesne olarak ister +@msg xpath needs the expression as a string xpath, ifadeyi bir dize olarak ister +@msg {GRANT_NOT_REMOVED}, and its settings and cache can't be moved back from {_1} to {_2}: {e} {GRANT_NOT_REMOVED}; ayrıca ayarları ve önbelleği {_1} konumundan {_2} konumuna geri taşınamıyor: {e} +@msg {_1} is not a folder: {e} {_1} bir klasör değil: {e} +@msg {_1}: {_2} and {_3} are in the way {_1}: {_2} ve {_3} engel oluyor +@msg {code}: {0} {code}: {0} +@msg {dir}: {e} {dir}: {e} +@msg {file} names more than one linked JavaScript file {file} birden fazla bağlantılı JavaScript dosyası belirtiyor +@msg {k}: a custom arrowhead's path needs an area to fill and at most {most} anchors and {most} subpaths, each anchor within {far} head units of its tip {k}: özel bir ok ucunun yolunda doldurulacak bir alan, en fazla {most} bağlantı noktası ve {most} alt yol olmalı, her bağlantı noktası ucundan en fazla {far} ok ucu birimi uzakta bulunmalıdır +@msg {k}: bad custom arrowhead path: {e} {k}: hatalı özel ok ucu yolu: {e} +@msg {k}: bad custom arrowhead: {e} {k}: hatalı özel ok ucu: {e} +@msg {k}: custom must be a name {k}: custom bir ad olmalıdır +@msg {name} must be a number {name} bir sayı olmalıdır +@msg {path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are {path}: copy bir DCS dosyasını yalnızca kalıpları içindeyse alır; kalıp dosyalarının bulunduğu yerde ona yeniden bağlayın +@msg {path}: larger than {_1} MB {path}: {_1} MB'tan büyük +@msg {shown} is not an XPath 1.0 function {shown} bir XPath 1.0 işlevi değil +@msg {v} names no layer or sublayer {v} hiçbir katmanı veya alt katmanı belirtmiyor +@msg {what} is not a function {what} bir işlev değil +@msg {what} would print more than {MAX_COPIES_PER_SHEET} copies on a sheet: scale it up {what} bir yaprağa {MAX_COPIES_PER_SHEET} taneden fazla kopya yazdırırdı: ölçeğini büyütün +@msg {what} {i} out of range {what} {i} aralık dışında +@msg A profile supports one Revolve effect. Edit the existing effect's options instead. Bir profil tek bir Döndürme efektini destekler. Bunun yerine mevcut efektin seçeneklerini düzenleyin. +@msg Add Points at Crossings: a path went missing Kesişimlere Nokta Ekle: bir yol kayboldu +@msg CSS options: {e} CSS seçenekleri: {e} +@msg CSV has a header but no data rows CSV'de bir başlık var ama veri satırı yok +@msg CSV holds NUL bytes: save it as UTF-8, or as UTF-16 with a byte-order mark CSV, NUL baytları içeriyor: UTF-8 olarak veya bayt sırası işaretiyle UTF-16 olarak kaydedin +@msg CSV is empty CSV boş +@msg CSV is larger than {MAX_CSV_BYTES} bytes CSV {MAX_CSV_BYTES} bayttan büyük +@msg CSV is not UTF-16 CSV, UTF-16 değil +@msg CSV is not UTF-8 CSV, UTF-8 değil +@msg CSV would be larger than {MAX_CSV_BYTES} bytes CSV {MAX_CSV_BYTES} bayttan büyük olurdu +@msg Choose original artwork, not a dimension's generated paths Bir boyutun oluşturduğu yolları değil, özgün resmi seçin +@msg Contour: select paths or shapes Kontur: yolları veya şekilleri seçin +@msg Contour: the Offset Path effect is not available Kontur: Ofset Yolu efekti kullanılamıyor +@msg Create needs fills, strokes or both Oluştur için dolgular, konturlar veya her ikisi gerekir +@msg DXF options: {e} DXF seçenekleri: {e} +@msg DXF scale must be a positive number up to {_1}, not {scale} DXF ölçeği en fazla {_1} olan pozitif bir sayı olmalıdır, {scale} değil +@msg DXF {field} `{s}`: {allowed} DXF {field} `{s}`: {allowed} +@msg Dimension is locked or hidden Boyut kilitli veya gizli +@msg Dimension mode does not match its source Boyut modu kaynağıyla eşleşmiyor +@msg Draw Inside needs exactly one selected path, compound path or text İçine Çiz için tam olarak bir seçili yol, bileşik yol veya metin gerekir +@msg EPS Save writes all artwork: use document.export for selected-only EPS EPS Kaydet tüm resmi yazar: yalnızca seçili resmi içeren EPS için document.export kullanın +@msg EPS flattener: {e} EPS düzleştirici: {e} +@msg EPS options: {e} EPS seçenekleri: {e} +@msg EPS {field} `{s}`: {allowed} EPS {field} `{s}`: {allowed} +@msg Export for Screens writes png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai or vectorcraft Ekranlar için Dışa Aktar şunları yazar: png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai veya vectorcraft +@msg Flare click coordinates must be finite numbers Mercek parlaması tıklama koordinatları sonlu sayılar olmalıdır +@msg HTML Text applies to object slices of type only HTML Metni yalnızca metin nesnesi dilimlerine uygulanır +@msg Identify Objects By is XML ID: the name must be a valid XML ID (start with a letter, underscore or colon; no spaces) Nesneleri Tanımlama Ölçütü XML Kimliği: ad geçerli bir XML kimliği olmalıdır (harf, alt çizgi veya iki nokta ile başlar; boşluk içermez) +@msg Image Trace failed: internal error: its thread stopped (please report this bug) Görüntü İzleme başarısız oldu: iç hata: iş parçacığı durdu (lütfen bu hatayı bildirin) +@msg Image Trace failed: {e} Görüntü İzleme başarısız oldu: {e} +@msg Image Trace finished, but its document was closed Görüntü İzleme tamamlandı, ancak belgesi kapatılmıştı +@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Görüntü İzleme tamamlandı, ancak bu sırada görüntü veya ayarları değişti: yeniden izleyin +@msg Invalid dimension offset Geçersiz boyut ofseti +@msg Invalid point Geçersiz nokta +@msg Join: a subpath went missing Birleştir: bir alt yol kayboldu +@msg Lock Workspace is not available in VectorCraft Çalışma Alanını Kilitle, VectorCraft'ta kullanılamaz +@msg Move Panel to New Window is not available: floating panels stay in the main window Paneli Yeni Pencereye Taşı kullanılamaz: yüzen paneller ana pencerede kalır +@msg Offset Path: the path is too complex to offset Ofset Yolu: yol ofsetlenemeyecek kadar karmaşık +@msg Offset Path: {e} Ofset Yolu: {e} +@msg PDF content is incomplete or exceeds the reader's limits; no document was imported PDF içeriği eksik veya okuyucunun sınırlarını aşıyor; hiçbir belge içe aktarılmadı +@msg PDF flattener: {e} PDF düzleştirici: {e} +@msg PDF options: {e} PDF seçenekleri: {e} +@msg Recolor Artwork is no longer open Resmi Yeniden Renklendir artık açık değil +@msg SVG is not UTF-8, UTF-16 or ISO 8859-1 SVG; UTF-8, UTF-16 veya ISO 8859-1 değil +@msg Save writes one artboard: name one, or export several with document.export Kaydet tek bir çalışma yüzeyi yazar: birini belirtin veya birkaçını document.export ile dışa aktarın +@msg Select a dimension first Önce bir boyut seçin +@msg Select dimensions to update Güncellenecek boyutları seçin +@msg Select only dimensions Yalnızca boyutları seçin +@msg Select two or more objects, or a group İki veya daha fazla nesne ya da bir grup seçin +@msg Shaper needs 1–64 source paths Şekillendirici için 1–64 kaynak yol gerekir +@msg Switch x/y is for scatter graphs x/y Değiştir dağılım grafikleri içindir +@msg Text options: {e} Metin seçenekleri: {e} +@msg `align` is start, center or end `align` start, center veya end olur +@msg `anchors` must be an array of [subpath, anchor] pairs `anchors`, [subpath, anchor] çiftlerinden oluşan bir dizi olmalıdır +@msg `anchors` must list anchor indices (0, 1, 2…), not {k} `anchors` bağlantı noktası dizinlerini (0, 1, 2…) listelemelidir, {k} değil +@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` bağlantı noktası dizinlerini (0, 1, 2…) listelemelidir, {v} değil +@msg `artboards` must be a list of artboard indices `artboards` bir çalışma yüzeyi dizinleri listesi olmalıdır +@msg `asset` is the asset id (see assets.list) `asset` varlık kimliğidir (bkz. assets.list) +@msg `at` must be a byte offset `at` bir bayt konumu olmalıdır +@msg `autoLeading` must be a number `autoLeading` bir sayı olmalıdır +@msg `background` must be "", "matte" or #rrggbb `background` "", "matte" veya #rrggbb olmalıdır +@msg `burasagari` must be "none", "standard" or "forced" `burasagari` "none", "standard" veya "forced" olmalıdır +@msg `center` must be [x, y] `center` [x, y] olmalıdır +@msg `charAlign` must be "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" or "icfBottom" `charAlign` "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" veya "icfBottom" olmalıdır +@msg `charDirection` must be "default", "leftToRight" or "rightToLeft" `charDirection` "default", "leftToRight" veya "rightToLeft" olmalıdır +@msg `clearStroke` requires `stroke: false`, `ids: []` and no `stop` `clearStroke` için `stroke: false`, `ids: []` gerekir ve `stop` verilmemelidir +@msg `clear` must be a list of type object ids, not {v} `clear` bir metin nesnesi kimlikleri listesi olmalıdır, {v} değil +@msg `clear` must list type objects; {_1} is not one `clear` metin nesnelerini listelemelidir; {_1} bir metin nesnesi değil +@msg `clear` must not list `id` `clear` içinde `id` yer almamalıdır +@msg `color` needs a `rule` to make the theme from `color` için temanın oluşturulacağı bir `rule` gerekir +@msg `colors` is empty `colors` boş +@msg `columnType` is vertical, uniform, repeating or sliding `columnType` vertical, uniform, repeating veya sliding olur +@msg `columns` must be a whole number 1..50 `columns` 1..50 arasında bir tam sayı olmalıdır +@msg `commands` must not be empty `commands` boş olmamalıdır +@msg `contents` goes with `to` `contents`, `to` ile birlikte kullanılır +@msg `corners` must be sharp, round or square, not `{other}` `corners` sharp, round veya square olmalıdır, `{other}` değil +@msg `corners` must list anchor indices (0, 1, 2…), not {v} `corners` bağlantı noktası dizinlerini (0, 1, 2…) listelemelidir, {v} değil +@msg `count` must be a whole number from 1 to 100 `count` 1 ile 100 arasında bir tam sayı olmalıdır +@msg `dataBase64` is larger than the module limit `dataBase64` modül sınırından büyük +@msg `dataBase64` is not valid base64 `dataBase64` geçerli bir base64 değil +@msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly`; `ids`, `reverse` veya `append` ile birleştirilemez +@msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` ve `childLimit` özeti dilimler: `summary: true` verin +@msg `design` is a design name, or null for plain columns `design` bir tasarım adıdır veya düz sütunlar için null olur +@msg `design` is a design name, or null for the default marker `design` bir tasarım adıdır veya varsayılan işaretçi için null olur +@msg `destinationFolder` is required when destination is `folder` destination `folder` olduğunda `destinationFolder` gereklidir +@msg `destination` must be `none`, `saveAndClose` or `folder` `destination` `none`, `saveAndClose` veya `folder` olmalıdır +@msg `diameter` must be from 0.1 to 2500 pt `diameter` 0.1 ile 2500 pt arasında olmalıdır +@msg `digits` must be one of {_1} `digits` şunlardan biri olmalıdır: {_1} +@msg `dimImages` is a percentage or false `dimImages` bir yüzde veya false olur +@msg `direction` must be "auto", "leftToRight" or "rightToLeft" `direction` "auto", "leftToRight" veya "rightToLeft" olmalıdır +@msg `each` is the value one design stands for, more than 0 `each`, bir tasarımın temsil ettiği değerdir ve 0'dan büyüktür +@msg `end` must be "start" or "end" `end` "start" veya "end" olmalıdır +@msg `ends` applies to joining exactly two paths `ends` tam olarak iki yolun birleştirilmesi için geçerlidir +@msg `event` must be one of {_1} `event` şunlardan biri olmalıdır: {_1} +@msg `every` must be "all", "odd" or "even", not {v} `every` "all", "odd" veya "even" olmalıdır, {v} değil +@msg `expand` must be true or false `expand` true veya false olmalıdır +@msg `files` must be 1 to 1000 paths of font files the last text.findFontFiles search found `files`, son text.findFontFiles aramasının bulduğu yazı tipi dosyalarının 1 ile 1000 arasında yolu olmalıdır +@msg `folder` must be an absolute folder path `folder` mutlak bir klasör yolu olmalıdır +@msg `fontAxes` must be an object of axis tags and values, such as {"wght"} `fontAxes`, eksen etiketleri ve değerlerinden oluşan bir nesne olmalıdır, örneğin {"wght"} +@msg `format` must be a string `format` bir dize olmalıdır +@msg `format` must be one of {_1} `format` şunlardan biri olmalıdır: {_1} +@msg `fractions` is chop or scale `fractions` chop veya scale olur +@msg `from` and `to` must differ `from` ve `to` farklı olmalıdır +@msg `from` has an empty frame `from` boş bir çerçeveye sahip +@msg `from` must be a non-negative integer `from` negatif olmayan bir tam sayı olmalıdır +@msg `from` must be area type or type on a path `from` alan metni veya yol üzerindeki yazı olmalıdır +@msg `gid` must be a glyph id, not {v} `gid` bir glif kimliği olmalıdır, {v} değil +@msg `glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it) `glyphAlternate` bir karakter stiline değil, tek bir karaktere aittir (text.setGlyphAlternate ayarlar) +@msg `guide` must be a guide index (guide.list) `guide` bir kılavuz dizini olmalıdır (guide.list) +@msg `hAlign` must be default, left, center or right `hAlign` default, left, center veya right olmalıdır +@msg `id` must be a node id `id` bir düğüm kimliği olmalıdır +@msg `id` must be an object id, not {v} `id` bir nesne kimliği olmalıdır, {v} değil +@msg `ids` must name Objects on Path groups or objects in them `ids`, Yol Üzerindeki Nesneler gruplarını veya bunların içindeki nesneleri belirtmelidir +@msg `ids` takes at most {MAX_INSPECT_IDS} ids `ids` en fazla {MAX_INSPECT_IDS} kimlik alır +@msg `imageMap` must be none, rectangle or polygon `imageMap` none, rectangle veya polygon olmalıdır +@msg `includeArtboardFill` must be true or false `includeArtboardFill` true veya false olmalıdır +@msg `includeSubdirs` must be true or false `includeSubdirs` true veya false olmalıdır +@msg `index` must be a point index `index` bir nokta dizini olmalıdır +@msg `index` must be a whole number or null `index` bir tam sayı veya null olmalıdır +@msg `indices` must be a non-empty array of item indices `indices`, öğe dizinlerinden oluşan boş olmayan bir dizi olmalıdır +@msg `items` is a list of {kind, item} `items` bir {kind, item} listesidir +@msg `items` is empty `items` boş +@msg `items` must be a list of {id, points} `items` bir {id, points} listesi olmalıdır +@msg `items` must be a list of {{id, anchors?}}, not {v} `items` bir {{id, anchors?}} listesi olmalıdır, {v} değil +@msg `items` must be an array of {id, anchors} `items` bir {id, anchors} dizisi olmalıdır +@msg `items` must be an array of {{id, corners?}}, not {v} `items` bir {{id, corners?}} dizisi olmalıdır, {v} değil +@msg `kashida` must be "none", "short", "medium", "long" or "stylistic" `kashida` "none", "short", "medium", "long" veya "stylistic" olmalıdır +@msg `kind` is one of {_1} `kind` şunlardan biridir: {_1} +@msg `kind` must be "round", "invertedRound" or "chamfer", not {v} `kind` "round", "invertedRound" veya "chamfer" olmalıdır, {v} değil +@msg `kind` must be `text`, `visibility`, `image` or `graph` `kind` `text`, `visibility`, `image` veya `graph` olmalıdır +@msg `kind` must be a string `kind` bir dize olmalıdır +@msg `kind` must be image, noImage or htmlText `kind` image, noImage veya htmlText olmalıdır +@msg `kinsoku` must be "none", "hard" or "soft" `kinsoku` "none", "hard" veya "soft" olmalıdır +@msg `label` must be a non-empty name of at most 200 characters `label` en fazla 200 karakterlik, boş olmayan bir ad olmalıdır +@msg `language` must be a language name or tag, such as "Turkish" or "tr" `language` bir dil adı veya etiketi olmalıdır, örneğin "Turkish" veya "tr" +@msg `leadingModel` must be "romanBaseline" or "emBoxTop" `leadingModel` "romanBaseline" veya "emBoxTop" olmalıdır +@msg `leading` must be from 0.1 to 5000, or null for Auto `leading` 0.1 ile 5000 arasında veya Otomatik için null olmalıdır +@msg `length` must be a number of at most 1000000 pt either way `length` her iki yönde en fazla 1000000 pt olan bir sayı olmalıdır +@msg `line` must be true or false `line` true veya false olmalıdır +@msg `minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°) `minAngle` ({min_angle}°), `maxAngle` ({max_angle}°) değerinden büyük olamaz +@msg `mode` must be "handles", "straight" or "smooth" `mode` "handles", "straight" veya "smooth" olmalıdır +@msg `mode` must be "straight", "bezier" or "arc" `mode` "straight", "bezier" veya "arc" olmalıdır +@msg `mode` must be one of {_1} `mode` şunlardan biri olmalıdır: {_1} +@msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" veya "lineEndHalf" olmalıdır +@msg `names` is a list of preset names `names` bir ön ayar adları listesidir +@msg `names` lists preset names `names` ön ayar adlarını listeler +@msg `names` must be a list of names `names` bir ad listesi olmalıdır +@msg `names` must be a list of swatch names `names` bir renk örneği adları listesi olmalıdır +@msg `names` must be an array of style names `names` bir stil adları dizisi olmalıdır +@msg `new` is a design name, or true `new` bir tasarım adı veya true olur +@msg `path` must be a folder `path` bir klasör olmalıdır +@msg `path` must be a path object `path` bir yol nesnesi olmalıdır +@msg `pivot` must be a whole number from 0 to 8 `pivot` 0 ile 8 arasında bir tam sayı olmalıdır +@msg `points` must be a list of [x, y] points `points` bir [x, y] noktaları listesi olmalıdır +@msg `points` must be a list of point indexes `points` bir nokta dizinleri listesi olmalıdır +@msg `points` must be an array of point indices `points` bir nokta dizinleri dizisi olmalıdır +@msg `points` must be point indexes `points` nokta dizinleri olmalıdır +@msg `port` must be "in" or "out" `port` "in" veya "out" olmalıdır +@msg `position` is above or below `position` above veya below olur +@msg `preset` must be a string `preset` bir dize olmalıdır +@msg `ratio` must be from 0.1 to 0.5 `ratio` 0.1 ile 0.5 arasında olmalıdır +@msg `rect` must be [x, y, width, height] with a positive size `rect` pozitif boyutlu [x, y, width, height] olmalıdır +@msg `relation` must be overlap, inside or outside `relation` overlap, inside veya outside olmalıdır +@msg `reversed` must be true or false `reversed` true veya false olmalıdır +@msg `rotate` must be a finite number `rotate` sonlu bir sayı olmalıdır +@msg `rule` must be nonZero or evenOdd `rule` nonZero veya evenOdd olmalıdır +@msg `scale` must be a number in (0, 100] `scale` (0, 100] aralığında bir sayı olmalıdır +@msg `scope` must be "selection" or "document", not {other} `scope` "selection" veya "document" olmalıdır, {other} değil +@msg `script` must be a string `script` bir dize olmalıdır +@msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes`, seri dizinlerinden oluşan boş olmayan bir listedir +@msg `seriesIndexes` needs a `type` or a `valueAxis` `seriesIndexes` için bir `type` veya bir `valueAxis` gerekir +@msg `shift` must be a number of points `shift` punto cinsinden bir sayı olmalıdır +@msg `showCenter` must be true or false `showCenter` true veya false olmalıdır +@msg `singleWordJustification` must be "fullJustify", "alignLeft", "alignCenter" or "alignRight" `singleWordJustification` "fullJustify", "alignLeft", "alignCenter" veya "alignRight" olmalıdır +@msg `size` is a percentage of the base text's size, 1 to 100 `size`, temel metnin boyutunun yüzdesidir ve 1 ile 100 arasındadır +@msg `source` and `target` are the same object `source` ve `target` aynı nesne +@msg `source` must be `folder` or `datasets` `source` `folder` veya `datasets` olmalıdır +@msg `spacing` must be a number `spacing` bir sayı olmalıdır +@msg `spacing` must be a number of points, 0 or more, or "auto" `spacing` punto cinsinden 0 veya daha büyük bir sayı ya da "auto" olmalıdır +@msg `start` must be a finite number `start` sonlu bir sayı olmalıdır +@msg `starts` must be an array of anchor indices (or nulls) `starts`, bağlantı noktası dizinlerinden (veya null değerlerinden) oluşan bir dizi olmalıdır +@msg `status` must be linked, embedded, missing or modified, or a list of them `status` linked, embedded, missing veya modified ya da bunların bir listesi olmalıdır +@msg `stop` must be a stop index `stop` bir durak dizini olmalıdır +@msg `story` styles the whole story: give no `start` or `end` `story` tüm metin akışına stil verir: `start` veya `end` vermeyin +@msg `story` takes the whole story: give no `start` or `end` `story` tüm metin akışını alır: `start` veya `end` vermeyin +@msg `strokeMode` applies to strokes (stroke: true) `strokeMode` konturlar için geçerlidir (stroke: true) +@msg `style` must be roman or japanese `style` roman veya japanese olmalıdır +@msg `subpaths` must be two integer indices `subpaths` iki tam sayı dizini olmalıdır +@msg `symbol` must be a symbol name `symbol` bir sembol adı olmalıdır +@msg `target` must be "object" or "contents", not {v} `target` "object" veya "contents" olmalıdır, {v} değil +@msg `tint` applies to global and spot colours `tint` genel ve spot renkler için geçerlidir +@msg `tint` goes with a global or spot `swatch` `tint`, genel veya spot bir `swatch` ile birlikte kullanılır +@msg `tint` must be a number (%) `tint` bir sayı (%) olmalıdır +@msg `tint` needs a global or spot colour `tint` için genel veya spot bir renk gerekir +@msg `to` is already threaded `to` zaten zincirlenmiş +@msg `to` is the design's new name `to` tasarımın yeni adıdır +@msg `to` must be [x, y] `to` [x, y] olmalıdır +@msg `to` must be a closed path, area type or type on a path other than `from` `to`, `from` dışında kapalı bir yol, alan metni veya yol üzerindeki yazı olmalıdır +@msg `to` must be a whole number `to` bir tam sayı olmalıdır +@msg `to` takes the rows of one object's stack, not aligned rows `to` hizalanmış satırları değil, tek bir nesnenin yığınındaki satırları alır +@msg `useLab` must be true or false `useLab` true veya false olmalıdır +@msg `vAlign` must be default, top, middle, baseline or bottom `vAlign` default, top, middle, baseline veya bottom olmalıdır +@msg `values` must be a list `values` bir liste olmalıdır +@msg `values` must be an object `values` bir nesne olmalıdır +@msg `values` must name hex, rgb, cmyk, lab or gray `values` hex, rgb, cmyk, lab veya gray belirtmelidir +@msg `values` names a kind twice `values` bir türü iki kez belirtiyor +@msg `{_1}` can't be edited or removed `{_1}` düzenlenemez veya kaldırılamaz +@msg `{_1}` is built in and always listed `{_1}` yerleşiktir ve her zaman listelenir +@msg `{_1}` is not a font file the last text.findFontFiles search found `{_1}`, son text.findFontFiles aramasının bulduğu bir yazı tipi dosyası değil +@msg `{_1}` would be overwritten by the package: choose a different folder or name paket `{_1}` üzerine yazardı: farklı bir klasör veya ad seçin +@msg `{file}` has no art to place `{file}` içinde yerleştirilecek resim yok +@msg `{file}` is over {_1} MB `{file}` {_1} MB'tan büyük +@msg `{f}` belongs to a VectorCraft that is running `{f}` çalışmakta olan bir VectorCraft'a ait +@msg `{f}` is the copy of a document open now `{f}` şu anda açık olan bir belgenin kopyası +@msg `{id}` is no writable format (see document.formats) `{id}` yazılabilir bir biçim değil (bkz. document.formats) +@msg `{id}` isn't a loaded library `{id}` yüklenmiş bir kütüphane değil +@msg `{key}` has no colours `{key}` renk içermiyor +@msg `{key}` is a design name `{key}` bir tasarım adıdır +@msg `{key}` is a design name or a list of them `{key}` bir tasarım adı veya tasarım adları listesidir +@msg `{key}` is longer than {MAX_NAME} characters `{key}` {MAX_NAME} karakterden uzun +@msg `{key}` is out of range `{key}` aralık dışında +@msg `{key}` must be [min, desired, max] or {{min?, desired?, max?}}, in percent `{key}` yüzde cinsinden [min, desired, max] veya {{min?, desired?, max?}} olmalıdır +@msg `{key}` must be a non-negative integer `{key}` negatif olmayan bir tam sayı olmalıdır +@msg `{key}` must be a number {_1}..{_2} `{key}` {_1}..{_2} aralığında bir sayı olmalıdır +@msg `{key}` must be a whole number of at least 0, not {n} `{key}` en az 0 olan bir tam sayı olmalıdır, {n} değil +@msg `{key}` must be an appearance item index (paint order) or null `{key}` bir görünüm öğesi dizini (boyama sırası) veya null olmalıdır +@msg `{key}` must be an array of asset ids (see assets.list) `{key}` bir varlık kimlikleri dizisi olmalıdır (bkz. assets.list) +@msg `{key}` must be from 0 to 180 degrees, not {a} `{key}` 0 ile 180 derece arasında olmalıdır, {a} değil +@msg `{key}` must be from {_1} to {shift_max} `{key}` {_1} ile {shift_max} arasında olmalıdır +@msg `{key}`: not a colour: {v} `{key}`: bir renk değil: {v} +@msg `{k}.family` is required `{k}.family` gereklidir +@msg `{k}` is a number 0..1 `{k}` 0..1 aralığında bir sayıdır +@msg `{k}` is true or false `{k}` true veya false olur +@msg `{k}` isn't an export setting: {_1} `{k}` bir dışa aktarma ayarı değil: {_1} +@msg `{k}` must be a byte offset `{k}` bir bayt konumu olmalıdır +@msg `{k}` must be a number `{k}` bir sayı olmalıdır +@msg `{k}` must be a number of points `{k}` punto cinsinden bir sayı olmalıdır +@msg `{k}` must be a string `{k}` bir dize olmalıdır +@msg `{k}` must be a whole number `{k}` bir tam sayı olmalıdır +@msg `{k}` must be from {lo} to {hi} for {key} {key} için `{k}` {lo} ile {hi} arasında olmalıdır +@msg `{k}` must be {what}, not {v} `{k}` {what} olmalıdır, {v} değil +@msg `{l}` isn't a global or spot colour `{l}` genel veya spot bir renk değil +@msg `{m}` isn't a bitmap: use clipboard.importSvg, importPdf or importText `{m}` bir bitmap değil: clipboard.importSvg, importPdf veya importText kullanın +@msg `{name}` can't be deleted `{name}` silinemez +@msg `{name}` can't be duplicated `{name}` çoğaltılamaz +@msg `{name}` can't be edited `{name}` düzenlenemez +@msg `{name}` can't be edited this way `{name}` bu şekilde düzenlenemez +@msg `{name}` can't be renamed `{name}` yeniden adlandırılamaz +@msg `{name}` can't name a folder `{name}` bir klasörü belirtemez +@msg `{name}` has no art to place `{name}` içinde yerleştirilecek resim yok +@msg `{name}` has no text to place `{name}` içinde yerleştirilecek metin yok +@msg `{name}` in the Word document is not UTF-8 or UTF-16 text Word belgesindeki `{name}`, UTF-8 veya UTF-16 metni değil +@msg `{name}` in the Word document is not well-formed XML: {e} Word belgesindeki `{name}` iyi biçimlendirilmiş bir XML değil: {e} +@msg `{name}` in the Word document nests elements more than {MAX_NESTING} deep Word belgesindeki `{name}`, öğeleri {MAX_NESTING} düzeyden daha derin iç içe yerleştiriyor +@msg `{name}` is a built-in preset and is read-only: save it under another name `{name}` yerleşik bir ön ayardır ve salt okunurdur: başka bir adla kaydedin +@msg `{name}` is a built-in preset: save under another name `{name}` yerleşik bir ön ayardır: başka bir adla kaydedin +@msg `{name}` is a built-in profile and stays `{name}` yerleşik bir profildir ve kalır +@msg `{name}` is a tint of `{base}`: edit `{base}` (a tint swatch only takes a new name) `{name}`, `{base}` renginin bir tonudur: `{base}` örneğini düzenleyin (bir ton renk örneği yalnızca yeni bir ad alır) +@msg `{name}` is a working space: choose another with edit.colorSettings first `{name}` bir çalışma alanıdır: önce edit.colorSettings ile başka birini seçin +@msg `{name}` is built in and stays `{name}` yerleşiktir ve kalır +@msg `{name}` takes a paint of its own kind (colour, gradient or pattern) `{name}` kendi türünde bir boya alır (renk, degrade veya desen) +@msg `{n}` can't be deleted `{n}` silinemez +@msg `{n}` can't be merged `{n}` birleştirilemez +@msg `{n}` can't be moved `{n}` taşınamaz +@msg `{n}` is not a colour swatch `{n}` bir renk örneği değil +@msg `{n}` isn't a solid colour `{n}` düz bir renk değil +@msg `{n}`: colour groups hold solid colours only `{n}`: renk grupları yalnızca düz renkler içerir +@msg `{other}` doesn't trace an image `{other}` bir görüntüyü izlemez +@msg `{s}`: the step's references copy in more than {_1} MB of values `{s}`: adımın başvuruları {_1} MB'tan fazla değer kopyalıyor +@msg `{tag}` is not an axis tag: a tag is four characters, such as "wght" `{tag}` bir eksen etiketi değil: bir etiket dört karakterdir, örneğin "wght" +@msg `{to}` is empty or already used `{to}` boş veya zaten kullanılıyor +@msg `{what}` is longer than {MAX_TEXT} bytes `{what}` {MAX_TEXT} bayttan uzun +@msg `{what}` must be text `{what}` metin olmalıdır +@msg a DXF drawing has one origin: pass useArtboards: true for one drawing per artboard bir DXF çiziminin tek bir başlangıç noktası vardır: çalışma yüzeyi başına bir çizim için useArtboards: true verin +@msg a PDF presets file with over {_1} presets {_1} taneden fazla ön ayar içeren bir PDF ön ayarları dosyası +@msg a batch preview cannot switch documents bir toplu önizleme belge değiştiremez +@msg a brush named `{nn}` exists `{nn}` adlı bir fırça var +@msg a container of the listed objects is gone listelenen nesnelerin bir kapsayıcısı artık yok +@msg a content stream can't be read bir içerik akışı okunamıyor +@msg a content stream isn't a stream bir içerik akışı bir akış değil +@msg a design holds at most {_1} objects bir tasarım en fazla {_1} nesne içerir +@msg a design needs a name bir tasarımın adı olmalıdır +@msg a dictionary grew too large bir sözlük çok büyüdü +@msg a document keeps at most {_1} graph designs bir belge en fazla {_1} grafik tasarımı tutar +@msg a document keeps at most {_1} saved selections bir belge en fazla {_1} kayıtlı seçim tutar +@msg a document keeps at most {_1} views bir belge en fazla {_1} görünüm tutar +@msg a document links at most {MAX_SVG_SCRIPTS} JavaScript files bir belge en fazla {MAX_SVG_SCRIPTS} JavaScript dosyasına bağlanır +@msg a feConvolveMatrix filter's order is {x}×{y}, which overflows the kernel-size multiply usvg makes bir feConvolveMatrix filtresinin order değeri {x}×{y}; bu, usvg'nin yaptığı çekirdek boyutu çarpımını taşırıyor +@msg a gradient preset is already called {n} {n} adlı bir degrade ön ayarı zaten var +@msg a graph has at most {_1} series, so it transposes with at most that many categories bir grafikte en fazla {_1} seri bulunur, bu yüzden en fazla o kadar kategoriyle yer değiştirir +@msg a layer can't be merged into its own sublayer bir katman kendi alt katmanıyla birleştirilemez +@msg a layer's form box isn't an array bir katmanın form kutusu bir dizi değil +@msg a layer's form can't be read bir katmanın formu okunamıyor +@msg a layer's form has no box bir katmanın formunda kutu yok +@msg a layer's form has no dictionary bir katmanın formunda sözlük yok +@msg a legend draws at most {MAX_CHIPS} swatches bir gösterge en fazla {MAX_CHIPS} renk örneği çizer +@msg a name names one asset: give multiple: false, or one object bir ad tek bir varlığı belirtir: multiple: false veya tek bir nesne verin +@msg a page can't be read bir sayfa okunamıyor +@msg a page object is used by something else bir sayfa nesnesi başka bir şey tarafından kullanılıyor +@msg a page thumbnail must be RGB pixels, 1 to {THUMBNAIL_SIZE} a side (got {w} × {h}) bir sayfa küçük resmi, kenar başına 1 ile {THUMBNAIL_SIZE} arasında RGB pikseller olmalıdır (verilen: {w} × {h}) +@msg a pattern layer doesn't end what it starts bir desen katmanı başlattığını bitirmiyor +@msg a pattern layer's colors hold something else bir desen katmanının renkleri başka bir şey içeriyor +@msg a pattern named `{n}` exists `{n}` adlı bir desen var +@msg a plug-in with id {_1} is already installed {_1} kimlikli bir eklenti zaten kurulu +@msg a preset named `{n}` exists `{n}` adlı bir ön ayar var +@msg a print presets file with over {_1} presets {_1} taneden fazla ön ayar içeren bir yazdırma ön ayarları dosyası +@msg a profile is already called {n} {n} adlı bir profil zaten var +@msg a row can't go into itself bir satır kendi içine giremez +@msg a series goes on the left or the right value axis bir seri sol veya sağ değer eksenine yerleşir +@msg a start must be an anchor index ≥ 0 or null bir başlangıç, ≥ 0 olan bir bağlantı noktası dizini veya null olmalıdır +@msg a style named `{name}` already exists `{name}` adlı bir stil zaten var +@msg a style named `{to}` already exists `{to}` adlı bir stil zaten var +@msg a swatch needs a colour, gradient or pattern bir renk örneği için renk, degrade veya desen gerekir +@msg a symbol named `{n}` already exists `{n}` adlı bir sembol zaten var +@msg a theme has 1 to {THEME_SIZE} colours bir temada 1 ile {THEME_SIZE} arasında renk bulunur +@msg a theme is already called {name} (replace: "{name}" overwrites it) {name} adlı bir tema zaten var (replace: "{name}" üzerine yazar) +@msg a toolbar name has at most {MAX_NAME} characters bir araç çubuğu adı en fazla {MAX_NAME} karakter içerir +@msg a view named `{_1}` exists `{_1}` adlı bir görünüm var +@msg a view named `{name}` exists `{name}` adlı bir görünüm var +@msg a workspace keeps at most {MAX} toolbars bir çalışma alanı en fazla {MAX} araç çubuğu tutar +@msg a {_1} series can't go in a {_2} graph {_1} türünde bir seri {_2} türünde bir grafiğe konulamaz +@msg aiVersion {v}: "pdf" (PDF-compatible, the default) or "7" (legacy .ai, version 7) aiVersion {v}: "pdf" (PDF uyumlu, varsayılan) veya "7" (eski .ai, sürüm 7) +@msg already editing an opacity mask zaten bir opaklık maskesi düzenleniyor +@msg already editing another object's opacity mask zaten başka bir nesnenin opaklık maskesi düzenleniyor +@msg already in pattern editing mode zaten desen düzenleme modunda +@msg an artboard is listed twice bir çalışma yüzeyi iki kez listelenmiş +@msg an empty artboard has no width or height to scale to boş bir çalışma yüzeyinin ölçeklenecek genişliği veya yüksekliği yoktur +@msg an image is too large for DXF and was left out bir görüntü DXF için çok büyük olduğundan dışarıda bırakıldı +@msg an image of {_1} MB, at most {_2} MB {_1} MB'lık bir görüntü, en fazla {_2} MB +@msg an image of {declared_w} × {declared_h} pixels is too large to draw {declared_w} × {declared_h} piksellik bir görüntü çizilemeyecek kadar büyük +@msg an image of {width} × {height} pixels is too large to draw {width} × {height} piksellik bir görüntü çizilemeyecek kadar büyük +@msg an index must be a whole number bir dizin tam sayı olmalıdır +@msg an inline graphic has no glyphs satır içi bir grafikte glif yok +@msg an invisible text form can't be read görünmez bir metin formu okunamıyor +@msg an object is missing bir nesne eksik +@msg an object's header is missing bir nesnenin üst bilgisi eksik +@msg an overprinting form can't be read üst baskılı bir form okunamıyor +@msg an unread object has no readable bounds okunmamış bir nesnenin okunabilir sınırları yok +@msg an unread object holds a frame of threaded type okunmamış bir nesne zincirli metnin bir çerçevesini içeriyor +@msg an unread object is missing from its layer okunmamış bir nesne katmanında eksik +@msg anchor `smooth` must be true or false bağlantı noktasının `smooth` değeri true veya false olmalıdır +@msg anchor `{key}` must be [x, y] bağlantı noktasının `{key}` değeri [x, y] olmalıdır +@msg anchor `{key}` must be a number bağlantı noktasının `{key}` değeri bir sayı olmalıdır +@msg angle and roundness must be finite açı ve yuvarlaklık sonlu olmalıdır +@msg angles must be a list as long as pins (degrees or null) angles, pins ile aynı uzunlukta bir liste olmalıdır (derece veya null) +@msg appearance must be flat|center|edge appearance flat|center|edge olmalıdır +@msg apply is "fill" or "stroke", not `{other}` apply "fill" veya "stroke" olur, `{other}` değil +@msg area must be a closed polygon of 3 to 100000 [x, y] points area, 3 ile 100000 arasında [x, y] noktasından oluşan kapalı bir çokgen olmalıdır +@msg area type needs a path that encloses an area alan metni için bir alanı çevreleyen bir yol gerekir +@msg area type {_1} is named twice alan metni {_1} iki kez belirtilmiş +@msg arrowAlign must be extend|tip, got {o} arrowAlign extend|tip olmalıdır, verilen: {o} +@msg arrowScale must be [start, end] arrowScale [start, end] olmalıdır +@msg artboard is a 0-based index artboard 0 tabanlı bir dizindir +@msg artboard must be a 0-based index artboard 0 tabanlı bir dizin olmalıdır +@msg artboard {i} doesn't print {i} numaralı çalışma yüzeyi yazdırılmıyor +@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout {layout?, columns?, spacing?, rightToLeft?} olmalıdır +@msg artboardLayout.columns must be 1 or more artboardLayout.columns 1 veya daha büyük olmalıdır +@msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout gridByRow, gridByColumn, row veya column olmalıdır +@msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft true veya false olmalıdır +@msg artboardLayout.spacing must be 0–{MAX_SPACING} pt artboardLayout.spacing 0–{MAX_SPACING} pt olmalıdır +@msg artboards must be a non-empty list artboards boş olmayan bir liste olmalıdır +@msg artboards must be a number artboards bir sayı olmalıdır +@msg asset `{_1}` has no art to export `{_1}` varlığında dışa aktarılacak resim yok +@msg at most {MAX_KEYWORDS} keywords en fazla {MAX_KEYWORDS} anahtar sözcük +@msg at most {MAX_MATCHES} matches are kept en fazla {MAX_MATCHES} eşleşme tutulur +@msg at most {MAX_POINTS} points en fazla {MAX_POINTS} nokta +@msg at most {MAX_QUEUE} files en fazla {MAX_QUEUE} dosya +@msg at must be [x, y] at [x, y] olmalıdır +@msg at/rect lie outside the canvas at/rect tuvalin dışında kalıyor +@msg attribute must be size|leading|tracking|kerning|baselineShift attribute size|leading|tracking|kerning|baselineShift olmalıdır +@msg attrs must be an object attrs bir nesne olmalıdır +@msg automation path rejected: the folder's name isn't valid text otomasyon yolu reddedildi: klasörün adı geçerli bir metin değil +@msg automation path rejected: {_1} isn't valid text otomasyon yolu reddedildi: {_1} geçerli bir metin değil +@msg automation path rejected: {why}: {path} otomasyon yolu reddedildi: {why}: {path} +@msg axis must be "vertical", "horizontal" or an angle in degrees, not `{given}` axis "vertical", "horizontal" veya derece cinsinden bir açı olmalıdır, `{given}` değil +@msg backgroundContents must be transparent or white backgroundContents transparent veya white olmalıdır +@msg bad AES key hatalı AES anahtarı +@msg bad `runs`: {e} hatalı `runs`: {e} +@msg bad arrowScale hatalı arrowScale +@msg bad base64 hatalı base64 +@msg bad color {c} hatalı renk {c} +@msg bad colour hatalı renk +@msg bad colour in `colors` `colors` içinde hatalı renk +@msg bad colour {v} hatalı renk {v} +@msg bad colour {v} in groupColors groupColors içinde hatalı renk {v} +@msg bad cross-reference entry hatalı çapraz başvuru girdisi +@msg bad cross-reference table hatalı çapraz başvuru tablosu +@msg bad current colour {v} hatalı geçerli renk {v} +@msg bad dataBase64 hatalı dataBase64 +@msg bad edit hatalı düzenleme +@msg bad fill {v} hatalı dolgu {v} +@msg bad fit: {e} hatalı fit: {e} +@msg bad model {other} (keep, new or document) hatalı model {other} (keep, new veya document) +@msg bad new colour {v} hatalı yeni renk {v} +@msg bad object hatalı nesne +@msg bad object number hatalı nesne numarası +@msg bad offset hatalı konum +@msg bad path data: {e} hatalı yol verisi: {e} +@msg bad point {v}: expected [x, y] or [x, y, pressure] hatalı nokta {v}: [x, y] veya [x, y, pressure] bekleniyordu +@msg bad reference hatalı başvuru +@msg bad trailer size hatalı trailer boyutu +@msg bad {k} colour hatalı {k} rengi +@msg batches cannot nest toplu işlemler iç içe olamaz +@msg bind something to a variable first önce bir şeyi bir değişkene bağlayın +@msg bleed must be 0–{MAX_BLEED} pt: a number, [top, bottom, left, right] or {{top, bottom, left, right}} bleed 0–{MAX_BLEED} pt olmalıdır: bir sayı, [top, bottom, left, right] veya {{top, bottom, left, right}} +@msg brush must be a name or null brush bir ad veya null olmalıdır +@msg by must be a number by bir sayı olmalıdır +@msg can't add page thumbnails: {why} sayfa küçük resimleri eklenemiyor: {why} +@msg can't add the editing data for other apps: {why} diğer uygulamalar için düzenleme verileri eklenemiyor: {why} +@msg can't edit the written PDF: {why} yazılan PDF düzenlenemiyor: {why} +@msg can't encrypt the PDF: {why} PDF şifrelenemiyor: {why} +@msg can't linearise the PDF: {why} PDF doğrusallaştırılamıyor: {why} +@msg can't open `{_1}`: {_2} `{_1}` açılamıyor: {_2} +@msg can't open `{_1}`: {e} `{_1}` açılamıyor: {e} +@msg can't open `{name}`: not a format VectorCraft reads (see document.formats) `{name}` açılamıyor: VectorCraft'ın okuduğu bir biçim değil (bkz. document.formats) +@msg can't place `{name}`: not a format VectorCraft reads (see document.formats) `{name}` yerleştirilemiyor: VectorCraft'ın okuduğu bir biçim değil (bkz. document.formats) +@msg can't read back the written PDF: {e} yazılan PDF geri okunamıyor: {e} +@msg can't read this Word document: {why} bu Word belgesi okunamıyor: {why} +@msg can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp .{e} görüntüleri yazılamıyor: .png, .jpg, .gif, .webp, .tif veya .bmp kullanın +@msg can't write PDF layers, overprint or invisible text: {why} PDF katmanları, üst baskı veya görünmez metin yazılamıyor: {why} +@msg can't write the file's copyright: {why} dosyanın telif hakkı yazılamıyor: {why} +@msg can't write the file's modification date: {why} dosyanın değiştirilme tarihi yazılamıyor: {why} +@msg can't write the pages' user units: {why} sayfaların kullanıcı birimleri yazılamıyor: {why} +@msg cannot distort a zero-size or non-finite bounding box sıfır boyutlu veya sonlu olmayan bir sınırlayıcı kutu çarpıtılamaz +@msg cannot move an object into itself bir nesne kendi içine taşınamaz +@msg case must be upper|lower|title|sentence case upper|lower|title|sentence olmalıdır +@msg category `{c}`: one of {_1} kategori `{c}`: şunlardan biri: {_1} +@msg center must be [x, y] center [x, y] olmalıdır +@msg choose at least one artboard en az bir çalışma yüzeyi seçin +@msg choose at least one status en az bir durum seçin +@msg clip must be true or false clip true veya false olmalıdır +@msg clippingMask must be true or false clippingMask true veya false olmalıdır +@msg closed must be a boolean closed bir mantıksal değer olmalıdır +@msg collapsed must be true or false collapsed true veya false olmalıdır +@msg color.profile: no RGB or CMYK profile is called “{profile}” color.profile: “{profile}” adlı bir RGB veya CMYK profili yok +@msg colorMode must be rgb or cmyk, not `{m}` colorMode rgb veya cmyk olmalıdır, `{m}` değil +@msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel {own} (belgenin modu), grayscale veya bitmap olmalıdır +@msg colour groups can't go into colour groups renk grupları renk gruplarının içine konulamaz +@msg colour, mode and spot apply to solid-colour swatches only colour, mode ve spot yalnızca düz renkli renk örnekleri için geçerlidir +@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read sütun {column}: `{cell}`, grafik veri dosyalarının bir `%` sütunudur ve bu dosyalar okunmaz +@msg column {column}: `{cell}` names `{name}`, which is a {_1} variable sütun {column}: `{cell}`, {_1} türünde bir değişken olan `{name}` değişkenini belirtiyor +@msg column {column}: `{cell}` names no variable sütun {column}: `{cell}` hiçbir değişkeni belirtmiyor +@msg column {column}: the variable name is longer than {MAX_NAME} characters sütun {column}: değişken adı {MAX_NAME} karakterden uzun +@msg column: true floats the whole column and takes no onto, above or below column: true tüm sütunu yüzdürür ve onto, above veya below almaz +@msg command must be a shape.* command command bir shape.* komutu olmalıdır +@msg commands[{i}]: missing `command` commands[{i}]: `command` eksik +@msg composer must be "singleLine" or "everyLine" composer "singleLine" veya "everyLine" olmalıdır +@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes bileşik şekiller yolları, bileşik yolları, grupları, bileşik şekilleri, metni, karışımları ve zarfları alır +@msg compound {_1} must contain exactly one open path to join bileşik {_1}, birleştirilecek tam olarak bir açık yol içermelidir +@msg connect needs a path other than the one extended connect için uzatılan yoldan başka bir yol gerekir +@msg connect needs id connect için id gerekir +@msg connect path has no open end connect yolunun açık ucu yok +@msg copy needs path: the file to copy into the document's folder copy için path gerekir: belgenin klasörüne kopyalanacak dosya +@msg copy takes images only: relink placed documents where their files are copy yalnızca görüntüleri alır: yerleştirilmiş belgeleri dosyalarının bulunduğu yerde yeniden bağlayın +@msg copying a file isn't available on the web dosya kopyalama web'de kullanılamaz +@msg copyrightStatus must be unknown, copyrighted or publicDomain copyrightStatus unknown, copyrighted veya publicDomain olmalıdır +@msg copyrightUrl must be a URL (no spaces, at most 2048 characters) copyrightUrl bir URL olmalıdır (boşluksuz, en fazla 2048 karakter) +@msg corners must be 4 [x, y] points (TL, TR, BR, BL) corners 4 adet [x, y] noktası olmalıdır (TL, TR, BR, BL) +@msg counterPer `{c}`: item or file counterPer `{c}`: item veya file +@msg crop `{_1}`: only PDF pages have art, trim, bleed and media boxes; use "crop" or "bounding" crop `{_1}`: yalnızca PDF sayfalarında art, trim, bleed ve media kutuları bulunur; "crop" veya "bounding" kullanın +@msg crop rectangle doesn't overlap the image kırpma dikdörtgeni görüntüyle örtüşmüyor +@msg cross-reference and object streams aren't supported çapraz başvuru ve nesne akışları desteklenmiyor +@msg damaged compressed data: {e} hasarlı sıkıştırılmış veri: {e} +@msg dash lengths must be numbers, got {v} kesik çizgi uzunlukları sayı olmalıdır, verilen: {v} +@msg dash must be a list of lengths or null, got {v} dash bir uzunluk listesi veya null olmalıdır, verilen: {v} +@msg data key `{k}`: letters, digits, -, _ and . (not name or vc-…) veri anahtarı `{k}`: harfler, rakamlar, -, _ ve . (name veya vc-… olamaz) +@msg data must be an object of key: value, not {v} data bir key: value nesnesi olmalıdır, {v} değil +@msg data set `{name}` holds a value for `{var}`, which the library doesn't declare `{name}` veri kümesi, kütüphanenin bildirmediği `{var}` için bir değer içeriyor +@msg data set `{name}` holds two values for `{var}` `{name}` veri kümesi `{var}` için iki değer içeriyor +@msg data set `{name}` is declared twice `{name}` veri kümesi iki kez bildirilmiş +@msg data takes at most {MAX_DATA} keys at once data bir seferde en fazla {MAX_DATA} anahtar alır +@msg dataset `{name}` already exists `{name}` veri kümesi zaten var +@msg dataset `{to}` already exists `{to}` veri kümesi zaten var +@msg date `{d}`: YYYY-MM-DD tarih `{d}`: YYYY-MM-DD +@msg decoded data is too large kodu çözülen veri çok büyük +@msg define a variable first önce bir değişken tanımlayın +@msg detect must be true or false detect true veya false olmalıdır +@msg direct-select anchor points of a path bir yolun bağlantı noktalarını doğrudan seçin +@msg distance must be > 0 distance > 0 olmalıdır +@msg dx and dy give the arrow's direction dx ve dy okun yönünü verir +@msg dx and dy must be numbers dx ve dy sayı olmalıdır +@msg dxf fitTo must be [width, height], positive dxf fitTo pozitif [width, height] olmalıdır +@msg dxf must be an object of DXF import options dxf, DXF içe aktarma seçeneklerinden oluşan bir nesne olmalıdır +@msg dxf scale must be a positive number up to {_1}, not {s} dxf scale en fazla {_1} olan pozitif bir sayı olmalıdır, {s} değil +@msg dxf unit `{u}`: a unit such as mm, cm, in or pt dxf unit `{u}`: mm, cm, in veya pt gibi bir birim +@msg dxf: {e} dxf: {e} +@msg each format is an object {format, scale?, suffix?} her biçim bir {format, scale?, suffix?} nesnesidir +@msg each item needs an id her öğe için bir id gerekir +@msg each match needs `kind` her eşleşme için `kind` gerekir +@msg each match needs a `name` her eşleşme için bir `name` gerekir +@msg each of `fonts` is {family, style?}; 1 to 1000 of them `fonts` öğelerinin her biri {family, style?} biçimindedir; 1 ile 1000 arasında öğe +@msg each of `items` is {kind, item} `items` öğelerinin her biri {kind, item} biçimindedir +@msg each of `items` is {{id, corners?}} with an object id, not {it} `items` öğelerinin her biri nesne kimliği içeren {{id, corners?}} biçimindedir, {it} değil +@msg each row needs `from` her satır için `from` gerekir +@msg each stop needs a position her durak için bir konum gerekir +@msg each subpath needs an anchors array her alt yol için bir anchors dizisi gerekir +@msg easingType must be easeIn, easeOut, easeInOut or easeOutIn easingType easeIn, easeOut, easeInOut veya easeOutIn olmalıdır +@msg editingData must be true or false editingData true veya false olmalıdır +@msg editingData must be true, false or "always" editingData true, false veya "always" olmalıdır +@msg edits overlap düzenlemeler çakışıyor +@msg effects of objects whose appearances differ can't be moved together görünümleri farklı olan nesnelerin efektleri birlikte taşınamaz +@msg empty header in column {_1} {_1} sütununda boş başlık +@msg encoding `{_1}`: utf8 or utf16 encoding `{_1}`: utf8 veya utf16 +@msg ends must be two of "first" and "last" ends, "first" ve "last" değerlerinden iki tane olmalıdır +@msg every numbered name for the result is taken sonuç için numaralı adların tümü kullanılıyor +@msg expanded SVG styles exceed the import size limit genişletilmiş SVG stilleri içe aktarma boyut sınırını aşıyor +@msg export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes dışa aktarma ön ayarları dosyası {MAX_PRESET_FILE_BYTES} bayttan büyük +@msg exportText must be editable or appearance exportText editable veya appearance olmalıdır +@msg exportType must be movieClip or graphic, not `{s}` exportType movieClip veya graphic olmalıdır, `{s}` değil +@msg extend needs id extend için id gerekir +@msg featureChanges lists at most {MAX_FEATURE_CHANGES} tags featureChanges en fazla {MAX_FEATURE_CHANGES} etiket listeler +@msg featureChanges must be a list of tags featureChanges bir etiket listesi olmalıdır +@msg features must be a list of tags features bir etiket listesi olmalıdır +@msg fidelity must be 0..100 fidelity 0..100 olmalıdır +@msg files must be {name, dataBase64} files {name, dataBase64} olmalıdır +@msg fit must be none|autoHeight|shrinkText|block, got {id} fit none|autoHeight|shrinkText|block olmalıdır, verilen: {id} +@msg flattener: {e} düzleştirici: {e} +@msg flattenerPreset `{name}`: high, medium, low or a saved one (see flattener.presets.list) flattenerPreset `{name}`: high, medium, low veya kayıtlı bir ön ayar (bkz. flattener.presets.list) +@msg flipProfile must be along|across, got {o} flipProfile along|across olmalıdır, verilen: {o} +@msg folders `{f}`: none, rows, format, item or itemFormat folders `{f}`: none, rows, format, item veya itemFormat +@msg folders deeper than {MAX_BATCH_DEPTH} levels {MAX_BATCH_DEPTH} düzeyden daha derin klasörler +@msg folders deeper than {MAX_DEPTH} levels {MAX_DEPTH} düzeyden daha derin klasörler +@msg font family `{family}` is not available `{family}` yazı tipi ailesi kullanılamıyor +@msg font family `{tf}` is not available `{tf}` yazı tipi ailesi kullanılamıyor +@msg format `{f}`: pdf or postscript format `{f}`: pdf veya postscript +@msg format `{f}`: text or json format `{f}`: text veya json +@msg format is `{format}` format `{format}` +@msg formats must be an array of rows, not {v} formats bir satır dizisi olmalıdır, {v} değil +@msg frequency must be between 1 and 300 lines per inch frequency inç başına 1 ile 300 çizgi arasında olmalıdır +@msg from and to must be finite from ve to sonlu olmalıdır +@msg from must be [x0, y0, x1, y1] from [x0, y0, x1, y1] olmalıdır +@msg give `before` or `after`, not both `before` veya `after` verin, ikisini birden değil +@msg give `colors`, or `color` and `rule` `colors` verin ya da `color` ve `rule` verin +@msg give `event`, such as onclick onclick gibi bir `event` verin +@msg give `file`, the JavaScript file's path or URL JavaScript dosyasının yolu veya URL'si olan `file` değerini verin +@msg give `fill` and/or `stroke` `fill` ve/veya `stroke` verin +@msg give `fill`, `stroke` or both `fill`, `stroke` veya her ikisini verin +@msg give `folder` `folder` verin +@msg give `fonts`, or open a document `fonts` verin veya bir belge açın +@msg give `from` or `indices`, not both `from` veya `indices` verin, ikisini birden değil +@msg give `id` (no text is being edited) `id` verin (düzenlenen bir metin yok) +@msg give `id` and `anchors`, or `items`, not both `id` ve `anchors` ya da `items` verin, ikisini birden değil +@msg give `id` or `guide`, not both `id` veya `guide` verin, ikisini birden değil +@msg give `length` or `to` `length` veya `to` verin +@msg give `matches`: [{kind, name, target}] `matches` verin: [{kind, name, target}] +@msg give `name` (or edit a pattern) `name` verin (veya bir deseni düzenleyin) +@msg give `name` or `names` `name` veya `names` verin +@msg give `path` (a .wasm file) or `dataBase64` (the module) `path` (bir .wasm dosyası) veya `dataBase64` (modül) verin +@msg give `path`, `data` or `dataBase64` `path`, `data` veya `dataBase64` verin +@msg give `path`, `data`, `dataBase64` or `csv` `path`, `data`, `dataBase64` veya `csv` verin +@msg give `path`, `xml` or `dataBase64` `path`, `xml` veya `dataBase64` verin +@msg give `script`, the JavaScript the event runs ("" removes the event) olayın çalıştırdığı JavaScript olan `script` değerini verin ("" olayı kaldırır) +@msg give `text` (the reading) or `remove` `text` (okunuş) veya `remove` verin +@msg give `x` and `y` (and a `tolerance` of 0 or more) `x` ve `y` verin (ve 0 veya daha büyük bir `tolerance`) +@msg give a mode or r/g/b, c/m/y/k, gray or tint adjustments bir mod ya da r/g/b, c/m/y/k, gray veya tint ayarlamaları verin +@msg give a name, or paint the active proxy with a saved preset bir ad verin veya etkin vekili kayıtlı bir ön ayarla boyayın +@msg give a name, or select a stroke with a saved profile bir ad verin veya kayıtlı profili olan bir kontur seçin +@msg give a pattern name or select an object painted with a pattern bir desen adı verin veya desenle boyanmış bir nesne seçin +@msg give at least one of clip, invert, disabled, linked şunlardan en az birini verin: clip, invert, disabled, linked +@msg give color, none, swatch or gradient color, none, swatch veya gradient verin +@msg give dataBase64 dataBase64 verin +@msg give either at (a click) or area (a path drawn around the overlaps) at (bir tıklama) veya area (çakışmaların çevresine çizilen bir yol) verin +@msg give formats or a preset, not both formats veya bir ön ayar verin, ikisini birden değil +@msg give newName or delete newName veya delete verin +@msg give offset or by offset veya by verin +@msg give one of `to`, `rect` or `at` `to`, `rect` veya `at` değerlerinden birini verin +@msg give one of assets, layers, selection or fullDocument assets, layers, selection veya fullDocument değerlerinden birini verin +@msg give only one of onto, above, below, icon and a column place onto, above, below, icon ve bir sütun yerinden yalnızca birini verin +@msg give origin: [x, y], or reset: true origin: [x, y] veya reset: true verin +@msg give overprintFill, overprintStroke, showCenter, imageMap, url or note overprintFill, overprintStroke, showCenter, imageMap, url veya note verin +@msg give path (a file) or folder path (bir dosya) veya folder verin +@msg give path, or name and dataBase64 path ya da name ve dataBase64 verin +@msg give paths or files paths veya files verin +@msg give rows, rowHeight, columns or columnWidth rows, rowHeight, columns veya columnWidth verin +@msg give svg, or dataBase64 of an SVG or SVGZ file svg ya da bir SVG veya SVGZ dosyasının dataBase64 değerini verin +@msg give text text verin +@msg give the asset a name varlığa bir ad verin +@msg give the preset a `name` ön ayara bir `name` verin +@msg give the preset a name ön ayara bir ad verin +@msg give the preset a name (1–64 characters) ön ayara bir ad verin (1–64 karakter) +@msg give the settings to change, e.g. {"formats"}]} değiştirilecek ayarları verin, örneğin {"formats"}]} +@msg give the style a name stile bir ad verin +@msg give two or more style `names` iki veya daha fazla stil için `names` verin +@msg give two or more swatches iki veya daha fazla renk örneği verin +@msg give x, y, or a handle's length or angle x, y ya da bir tutamacın uzunluğunu veya açısını verin +@msg give {key, value} or {values} {key, value} veya {values} verin +@msg global must be true or false global true veya false olmalıdır +@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) {_1} glifi, karakterin stiliyle (Tümü Büyük Harf, Küçük Büyük Harf veya bir rakam sistemi gibi) {ch} için çizilmiyor +@msg glyph {g} is not an alternate of {ch} in {_1} {_2} {g} glifi, {_1} {_2} içinde {ch} karakterinin bir alternatifi değil +@msg gradient must be "objects" or "mesh" gradient "objects" veya "mesh" olmalıdır +@msg grays must be "profile" or "black", not `{g}` grays "profile" veya "black" olmalıdır, `{g}` değil +@msg gridColors must be a preset name or two colours gridColors bir ön ayar adı veya iki renk olmalıdır +@msg gridSize must be small, medium or large gridSize small, medium veya large olmalıdır +@msg guide {g} is not selected {g} numaralı kılavuz seçili değil +@msg handle must be 0..3 handle 0..3 olmalıdır +@msg hiddenObjects {v}: "layer" (the default), "omit" or "visible" hiddenObjects {v}: "layer" (varsayılan), "omit" veya "visible" +@msg highlight a layer to merge into içine birleştirilecek bir katmanı vurgulayın +@msg highlight two or more rows in one layer or group tek bir katman veya gruptaki iki veya daha fazla satırı vurgulayın +@msg highlight two or more rows to merge birleştirmek için iki veya daha fazla satırı vurgulayın +@msg icon docks a panel in the icon column: use window.panel.dock icon bir paneli simge sütununa yerleştirir: window.panel.dock kullanın +@msg id must be a dimension id id bir boyut kimliği olmalıdır +@msg image has no bounds görüntünün sınırları yok +@msg image {_1} is linked already {_1} görüntüsü zaten bağlantılı +@msg imageMap `{m}`: none, client or server imageMap `{m}`: none, client veya server +@msg index out of range dizin aralık dışında +@msg instances must be 1..1000 instances 1..1000 olmalıdır +@msg invalid `color` geçersiz `color` +@msg invalid anchor index {v}: expected a non-negative integer geçersiz bağlantı noktası dizini {v}: negatif olmayan bir tam sayı bekleniyordu +@msg invalid anchor reference {v}: expected [subpath, anchor] geçersiz bağlantı noktası başvurusu {v}: [subpath, anchor] bekleniyordu +@msg invalid angle geçersiz açı +@msg invalid brush: {e} geçersiz fırça: {e} +@msg invalid color geçersiz renk +@msg invalid colour {c} geçersiz renk {c} +@msg invalid delta geçersiz delta +@msg invalid point geçersiz nokta +@msg invalid size geçersiz boyut +@msg invalid t geçersiz t +@msg invalid tolerance geçersiz tolerans +@msg its artboards all lie beyond the canvas (more than {_1} pt from the origin) çalışma yüzeylerinin tümü tuvalin dışında kalıyor (başlangıç noktasından {_1} pt'den uzak) +@msg its clipping masks are nested too deeply kırpma maskeleri çok derin iç içe geçmiş +@msg its metadata has no description meta verilerinde açıklama yok +@msg its metadata has no direct length meta verilerinde doğrudan bir uzunluk yok +@msg join two different paths iki farklı yolu birleştirin +@msg justify must be auto|left|center|right|justifyAll justify auto|left|center|right|justifyAll olmalıdır +@msg kbps must be a positive number, not {kbps} kbps pozitif bir sayı olmalıdır, {kbps} değil +@msg keywords must be a list of words or a comma-separated string keywords bir sözcük listesi veya virgülle ayrılmış bir dize olmalıdır +@msg keywords must be at most {MAX_KEYWORD} characters, without control characters anahtar sözcükler en fazla {MAX_KEYWORD} karakter olmalı ve denetim karakteri içermemelidir +@msg kind must be 1, 2 or 3, or give a preset `name` (see perspective.presets.list) kind 1, 2 veya 3 olmalıdır ya da bir ön ayar için `name` verin (bkz. perspective.presets.list) +@msg kind must be graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle or paraStyle kind graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle veya paraStyle olmalıdır +@msg knockout must be "on", "off", "neutral" or a bool, not {v} knockout "on", "off", "neutral" veya bir mantıksal değer olmalıdır, {v} değil +@msg layer `{name}` has no art to export `{name}` katmanında dışa aktarılacak resim yok +@msg layer must name a layer or sublayer layer bir katmanı veya alt katmanı belirtmelidir +@msg layers can't be intertwined: select the objects in them katmanlar iç içe geçirilemez: içlerindeki nesneleri seçin +@msg layers go only at the top level or in layers, objects in layers and groups katmanlar yalnızca en üst düzeye veya katmanların içine, nesneler ise katmanların ve grupların içine yerleşir +@msg layers must be true or false layers true veya false olmalıdır +@msg layout must be gridByRow, gridByColumn, row or column layout gridByRow, gridByColumn, row veya column olmalıdır +@msg leading must be a number or "auto" leading bir sayı veya "auto" olmalıdır +@msg left/right must be non-negative widths left/right negatif olmayan genişlikler olmalıdır +@msg level `{t}`: 2 or 3 level `{t}`: 2 veya 3 +@msg line {line}: more than {MAX_CSV_COLS} columns satır {line}: {MAX_CSV_COLS} taneden fazla sütun +@msg line {line}: unclosed quote satır {line}: kapatılmamış tırnak +@msg line {line}: value for `{var}` must match its variable kind satır {line}: `{var}` değeri değişkeninin türüyle eşleşmelidir +@msg lineEndings `{other}`: lf or crlf lineEndings `{other}`: lf veya crlf +@msg loading profiles from disk isn't available in the browser diskten profil yükleme tarayıcıda kullanılamaz +@msg margin: a {m} pt margin leaves no imageable area on the paper margin: {m} pt'lik bir kenar boşluğu kâğıtta yazdırılabilir alan bırakmıyor +@msg matrix must be finite and invertible, depth finite matrix sonlu ve tersinir, depth ise sonlu olmalıdır +@msg matte: {e} matte: {e} +@msg member is for order front, forward, backward or back member; order değeri front, forward, backward veya back olduğunda kullanılır +@msg missing `artboards` `artboards` eksik +@msg missing `at` [x, y] `at` [x, y] eksik +@msg missing `attrs` `attrs` eksik +@msg missing `color` or `opacity` `color` veya `opacity` eksik +@msg missing `colors` `colors` eksik +@msg missing `commands` `commands` eksik +@msg missing `destinationFolder` `destinationFolder` eksik +@msg missing `effect` id `effect` kimliği eksik +@msg missing `family` `family` eksik +@msg missing `find` `find` eksik +@msg missing `gid` (a glyph id, or null for the default glyph) `gid` eksik (bir glif kimliği veya varsayılan glif için null) +@msg missing `group` `group` eksik +@msg missing `id` `id` eksik +@msg missing `id`: give one, or select one type object `id` eksik: bir tane verin veya tek bir metin nesnesi seçin +@msg missing `index` (a point index, or null to clear) `index` eksik (bir nokta dizini veya temizlemek için null) +@msg missing `index` (a stop index, or null to clear) `index` eksik (bir durak dizini veya temizlemek için null) +@msg missing `index` (an item index or null) `index` eksik (bir öğe dizini veya null) +@msg missing `item` `item` eksik +@msg missing `library` `library` eksik +@msg missing `library` (see graphicStyle.libraries) `library` eksik (bkz. graphicStyle.libraries) +@msg missing `library` (see swatch.library.list) `library` eksik (bkz. swatch.library.list) +@msg missing `map` (rows [{from, to}] or {current}) `map` eksik (satırlar [{from, to}] veya {current}) +@msg missing `matrix` [a,b,c,d,e,f] `matrix` [a,b,c,d,e,f] eksik +@msg missing `name` (see gradient.presets.list) `name` eksik (bkz. gradient.presets.list) +@msg missing `offset` (a distance in points) `offset` eksik (punto cinsinden bir uzaklık) +@msg missing `path` `path` eksik +@msg missing `path` (a path object id) `path` eksik (bir yol nesnesi kimliği) +@msg missing `rule` `rule` eksik +@msg missing `source` id `source` kimliği eksik +@msg missing `start` (the byte offset of a character) `start` eksik (bir karakterin bayt konumu) +@msg missing `status`: linked, embedded, missing or modified `status` eksik: linked, embedded, missing veya modified +@msg missing `target` id `target` kimliği eksik +@msg missing `text` `text` eksik +@msg missing `to` `to` eksik +@msg missing `to` (an index) `to` eksik (bir dizin) +@msg missing `to`: a non-negative integer `to` eksik: negatif olmayan bir tam sayı +@msg missing `type` `type` eksik +@msg missing `value` `value` eksik +@msg missing `{key}` `{key}` eksik +@msg missing `{k}` `{k}` eksik +@msg missing anchor bağlantı noktası eksik +@msg missing anchors bağlantı noktaları eksik +@msg missing anchors [[subpath, anchor]…] anchors [[subpath, anchor]…] eksik +@msg missing array `{key}` `{key}` dizisi eksik +@msg missing case case eksik +@msg missing color renk eksik +@msg missing commands komutlar eksik +@msg missing destination folder hedef klasör eksik +@msg missing from from eksik +@msg missing group grup eksik +@msg missing id or ids id veya ids eksik +@msg missing ids ids eksik +@msg missing indexes indexes eksik +@msg missing matrix [a,b,c,d,e,f] matrix [a,b,c,d,e,f] eksik +@msg missing name ad eksik +@msg missing op op eksik +@msg missing or invalid `color` `color` eksik veya geçersiz +@msg missing or unknown `tool` `tool` eksik veya bilinmiyor +@msg missing point nokta eksik +@msg missing point [x,y] [x,y] noktası eksik +@msg missing point `{key}` ([x, y]) `{key}` noktası eksik ([x, y]) +@msg missing points noktalar eksik +@msg missing points [[x,y]…] points [[x,y]…] eksik +@msg missing segment parça eksik +@msg missing stops duraklar eksik +@msg missing subpaths alt yollar eksik +@msg missing target hedef eksik +@msg missing to to eksik +@msg missing x, y x, y eksik +@msg mode is set, add or toggle, not `{other}` mode set, add veya toggle olur, `{other}` değil +@msg mode must be "cmyk" or "rgb" mode "cmyk" veya "rgb" olmalıdır +@msg mode must be area|onPath, got {o} mode area|onPath olmalıdır, verilen: {o} +@msg more than 10000 linked files: package dependencies in smaller parts 10000 taneden fazla bağlantılı dosya: bağımlılıkları daha küçük parçalar hâlinde paketleyin +@msg more than 256 commands 256 taneden fazla komut +@msg more than {MAX_BATCH_FILES} data sets {MAX_BATCH_FILES} taneden fazla veri kümesi +@msg more than {MAX_BATCH_FILES} files {MAX_BATCH_FILES} taneden fazla dosya +@msg more than {MAX_CSV_ROWS} data rows {MAX_CSV_ROWS} taneden fazla veri satırı +@msg more than {MAX_FILES} images {MAX_FILES} taneden fazla görüntü +@msg more than {MAX_IMPORT} presets {MAX_IMPORT} taneden fazla ön ayar +@msg moved must be [[x,y]…] moved [[x,y]…] olmalıdır +@msg name (a toolbar's name) is required name (bir araç çubuğunun adı) gereklidir +@msg name (a toolbar's name) must be a string name (bir araç çubuğunun adı) bir dize olmalıdır +@msg name must be a toolbar's name name bir araç çubuğunun adı olmalıdır +@msg names is empty names boş +@msg names must be an array of symbol names names bir sembol adları dizisi olmalıdır +@msg need `anchor` or `segment` + `t` `anchor` veya `segment` + `t` gerekir +@msg need at least one anchor en az bir bağlantı noktası gerekir +@msg need at least one point en az bir nokta gerekir +@msg need at least two points en az iki nokta gerekir +@msg needs points noktalar gerekir +@msg nineSlice must be true or false nineSlice true veya false olmalıdır +@msg nineSliceGuides must be [left, top, right, bottom], each -16..16, with left + right < 1 and top + bottom < 1 nineSliceGuides, her biri -16..16 aralığında, left + right < 1 ve top + bottom < 1 olacak şekilde [left, top, right, bottom] olmalıdır +@msg no PDF preset named `{n}` `{n}` adlı bir PDF ön ayarı yok +@msg no action set is current geçerli bir eylem seti yok +@msg no active data set etkin veri kümesi yok +@msg no appearance item {index} {index} numaralı görünüm öğesi yok +@msg no artboard {_1} {_1} numaralı çalışma yüzeyi yok +@msg no artboard {artboard} (0-based; the document has {_1}) {artboard} numaralı çalışma yüzeyi yok (0 tabanlı; belgede {_1} tane var) +@msg no asset {id} {id} kimlikli varlık yok +@msg no asset {id} (see assets.list) {id} kimlikli varlık yok (bkz. assets.list) +@msg no assets to export dışa aktarılacak varlık yok +@msg no assets yet: collect art for export first (assets.add) henüz varlık yok: önce dışa aktarılacak resmi toplayın (assets.add) +@msg no brush named `{n}` `{n}` adlı bir fırça yok +@msg no character at byte {start} {start} numaralı baytta karakter yok +@msg no colour renk yok +@msg no colour group `{group}` `{group}` renk grubu yok +@msg no colour group `{name}` `{name}` renk grubu yok +@msg no data sets veri kümesi yok +@msg no dataset named `{from}` `{from}` adlı bir veri kümesi yok +@msg no dataset named `{name}` `{name}` adlı bir veri kümesi yok +@msg no datasets veri kümesi yok +@msg no design named `{name}` `{name}` adlı bir tasarım yok +@msg no design named `{n}` `{n}` adlı bir tasarım yok +@msg no design named `{old}` `{old}` adlı bir tasarım yok +@msg no encoder for {_1} yet {_1} için henüz bir kodlayıcı yok +@msg no export preset `{name}` (see document.exportPresets.list) `{name}` adında dışa aktarma ön ayarı yok (bkz. document.exportPresets.list) +@msg no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder klasör yok: `path` verin veya Tercihler › Eklentiler ve Çalışma Diskleri › Ek Eklentiler Klasörü ayarını yapın +@msg no fonts to look for: they are all available aranacak yazı tipi yok: tümü kullanılabilir +@msg no formats to export dışa aktarılacak biçim yok +@msg no gradient preset `{name}` (see gradient.presets.list) `{name}` degrade ön ayarı yok (bkz. gradient.presets.list) +@msg no graphic style `{n}` in `{_1}` `{_1}` içinde `{n}` grafik stili yok +@msg no graphic style library `{key}` (see graphicStyle.libraries) `{key}` grafik stili kütüphanesi yok (bkz. graphicStyle.libraries) +@msg no guide selected seçili kılavuz yok +@msg no guide selected (or give an index) seçili kılavuz yok (veya bir dizin verin) +@msg no guide {i} {i} numaralı kılavuz yok +@msg no images in the folder klasörde görüntü yok +@msg no item at index {_1} {_1} dizininde öğe yok +@msg no item at index {from} {from} dizininde öğe yok +@msg no item at one of the indices {idx} {idx} dizinlerinden birinde öğe yok +@msg no layer katman yok +@msg no layer {id} (see layer.list) {id} kimlikli katman yok (bkz. layer.list) +@msg no layers to export dışa aktarılacak katman yok +@msg no library `{key}` `{key}` kütüphanesi yok +@msg no metafile format meta dosya biçimi yok +@msg no object {_1} {_1} nesnesi yok +@msg no objects nesne yok +@msg no parent layer üst katman yok +@msg no perspective grid preset named `{b}` (see perspective.presets.list) `{b}` adlı bir perspektif ızgarası ön ayarı yok (bkz. perspective.presets.list) +@msg no perspective grid preset named `{n}` `{n}` adlı bir perspektif ızgarası ön ayarı yok +@msg no point selected (give `index`) seçili nokta yok (`index` verin) +@msg no preset called `{from}` (see file.newPresets) `{from}` adlı bir ön ayar yok (bkz. file.newPresets) +@msg no preset called `{name}` (see file.newPresets) `{name}` adlı bir ön ayar yok (bkz. file.newPresets) +@msg no preset named `{n}` `{n}` adlı bir ön ayar yok +@msg no print preset named `{b}` (see print.presets.list) `{b}` adlı bir yazdırma ön ayarı yok (bkz. print.presets.list) +@msg no print preset named `{name}` (presets: {_1}) `{name}` adlı bir yazdırma ön ayarı yok (ön ayarlar: {_1}) +@msg no print preset named `{n}` `{n}` adlı bir yazdırma ön ayarı yok +@msg no profile named `{name}` `{name}` adlı bir profil yok +@msg no readable files in the folder klasörde okunabilir dosya yok +@msg no recovery copy `{f}` (see file.recovery.list) `{f}` kurtarma kopyası yok (bkz. file.recovery.list) +@msg no rows satır yok +@msg no saved PDF preset named `{name}` `{name}` adlı kayıtlı bir PDF ön ayarı yok +@msg no saved export preset `{name}` `{name}` adlı kayıtlı bir dışa aktarma ön ayarı yok +@msg no saved gradient preset called {name} {name} adlı kayıtlı bir degrade ön ayarı yok +@msg no saved gradient presets kayıtlı degrade ön ayarı yok +@msg no saved preset called `{name}` `{name}` adlı kayıtlı bir ön ayar yok +@msg no saved presets to export (name [Default] in `names` to export it) dışa aktarılacak kayıtlı ön ayar yok ([Default] ön ayarını dışa aktarmak için `names` içinde belirtin) +@msg no saved presets to export (name built-in ones in `names`) dışa aktarılacak kayıtlı ön ayar yok (yerleşik olanları `names` içinde belirtin) +@msg no saved print preset named `{name}` `{name}` adlı kayıtlı bir yazdırma ön ayarı yok +@msg no saved profile called {name} {name} adlı kayıtlı bir profil yok +@msg no saved selection `{name}` `{name}` adlı kayıtlı bir seçim yok +@msg no saved theme called {name} (see colorTheme.list) {name} adlı kayıtlı bir tema yok (bkz. colorTheme.list) +@msg no saved views kayıtlı görünüm yok +@msg no series {i} {i} numaralı seri yok +@msg no slice {n} in the image (see slice.list) görüntüde {n} numaralı dilim yok (bkz. slice.list) +@msg no source art kaynak resim yok +@msg no stop {i} (the gradient has {n}) {i} numaralı durak yok (degradede {n} tane var) +@msg no style `{name}` `{name}` stili yok +@msg no such assets (see assets.list) böyle varlıklar yok (bkz. assets.list) +@msg no such frame anchor, or the frame would reach past the canvas böyle bir çerçeve bağlantı noktası yok veya çerçeve tuvalin dışına taşardı +@msg no such objects böyle nesneler yok +@msg no such path anchor, or the path would reach past the canvas böyle bir yol bağlantı noktası yok veya yol tuvalin dışına taşardı +@msg no such rows böyle satırlar yok +@msg no swatch `{keep}` `{keep}` renk örneği yok +@msg no swatch `{n}` `{n}` renk örneği yok +@msg no swatch `{n}` (swatches and colour groups move separately) `{n}` renk örneği yok (renk örnekleri ve renk grupları ayrı ayrı taşınır) +@msg no swatch library `{key}` (see swatch.library.list) `{key}` renk örneği kütüphanesi yok (bkz. swatch.library.list) +@msg no swatch library `{key}` (see swatch.library.list; "document": the document's swatches) `{key}` renk örneği kütüphanesi yok (bkz. swatch.library.list; "document": belgenin renk örnekleri) +@msg no swatch library `{key}` (see swatch.library.list; "{DOCUMENT_SWATCHES}": the document's swatches) `{key}` renk örneği kütüphanesi yok (bkz. swatch.library.list; "{DOCUMENT_SWATCHES}": belgenin renk örnekleri) +@msg no swatch named `{n}` `{n}` adlı bir renk örneği yok +@msg no swatch or colour group `{n}` `{n}` adlı bir renk örneği veya renk grubu yok +@msg no swatch or colour group `{n}` in `{_1}` `{_1}` içinde `{n}` adlı bir renk örneği veya renk grubu yok +@msg no symbol named `{name}` `{name}` adlı bir sembol yok +@msg no text objects selected seçili metin nesnesi yok +@msg no toolbar named `{_1}` `{_1}` adlı bir araç çubuğu yok +@msg no toolbar named `{name}` `{name}` adlı bir araç çubuğu yok +@msg no tracing preset `{preset}` (see imageTrace.presets) `{preset}` izleme ön ayarı yok (bkz. imageTrace.presets) +@msg no user library folder here (save with a path, or without one to get the data) burada kullanıcı kütüphanesi klasörü yok (bir yolla kaydedin veya verileri almak için yol vermeden kaydedin) +@msg no variable named `{from}` `{from}` adlı bir değişken yok +@msg no variable named `{name}` `{name}` adlı bir değişken yok +@msg no variable named `{var}` `{var}` adlı bir değişken yok +@msg no variable named `{v}` `{v}` adlı bir değişken yok +@msg no view named `{name}` `{name}` adlı bir görünüm yok +@msg node {_1} is not a graph {_1} düğümü bir grafik değil +@msg node {_1} is not an image {_1} düğümü bir görüntü değil +@msg node {_1} is not type {_1} düğümü metin değil +@msg not a PDF presets file (format `{_1}`) bir PDF ön ayarları dosyası değil (biçim `{_1}`) +@msg not a PDF presets file: {e} bir PDF ön ayarları dosyası değil: {e} +@msg not a Word document: its WordDocument stream doesn't start with a file information block bir Word belgesi değil: WordDocument akışı bir dosya bilgi bloğuyla başlamıyor +@msg not a Word document: its compound file has no WordDocument stream bir Word belgesi değil: bileşik dosyasında WordDocument akışı yok +@msg not a Word document: its main part is not a WordprocessingML document bir Word belgesi değil: ana bölümü bir WordprocessingML belgesi değil +@msg not a Word document: its package has no main document part bir Word belgesi değil: paketinde ana belge bölümü yok +@msg not a closed path kapalı bir yol değil +@msg not a flattener presets file (format `{_1}`) bir düzleştirici ön ayarları dosyası değil (biçim `{_1}`) +@msg not a flattener presets file: {e} bir düzleştirici ön ayarları dosyası değil: {e} +@msg not a layer or group bir katman veya grup değil +@msg not a library file: {e} bir kütüphane dosyası değil: {e} +@msg not a mesh envelope point bir ağ zarfı noktası değil +@msg not a perspective grid presets file (format `{_1}`) bir perspektif ızgarası ön ayarları dosyası değil (biçim `{_1}`) +@msg not a perspective grid presets file: {e} bir perspektif ızgarası ön ayarları dosyası değil: {e} +@msg not a print presets file (format `{_1}`) bir yazdırma ön ayarları dosyası değil (biçim `{_1}`) +@msg not a print presets file: {e} bir yazdırma ön ayarları dosyası değil: {e} +@msg not a stored or deflated central record saklanmış veya deflate ile sıkıştırılmış bir merkezi kayıt değil +@msg not a valid SVGZ file: {e} geçerli bir SVGZ dosyası değil: {e} +@msg not an image VectorCraft reads (see document.formats) VectorCraft'ın okuduğu bir görüntü değil (bkz. document.formats) +@msg not area type (text in a frame) outside perspective perspektif dışında alan metni (çerçeve içindeki metin) değil +@msg not editing an opacity mask bir opaklık maskesi düzenlenmiyor +@msg not type on a path outside perspective perspektif dışında yol üzerindeki yazı değil +@msg nothing prints hiçbir şey yazdırılmıyor +@msg nothing to bind bağlanacak bir şey yok +@msg nothing to change değiştirilecek bir şey yok +@msg nothing to change: give dx, dy, hScale, vScale or rotation değiştirilecek bir şey yok: dx, dy, hScale, vScale veya rotation verin +@msg nothing to crop kırpılacak bir şey yok +@msg nothing to export dışa aktarılacak bir şey yok +@msg nothing to export: the document has no visible art dışa aktarılacak bir şey yok: belgede görünür resim yok +@msg nothing to mark işaretlenecek bir şey yok +@msg nothing to print: every artboard picked is blank yazdırılacak bir şey yok: seçilen her çalışma yüzeyi boş +@msg nothing to print: the document has no art that prints yazdırılacak bir şey yok: belgede yazdırılan resim yok +@msg object is not a path nesne bir yol değil +@msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object nesne saydamlığı vurgulanan karakterlere örneklenemez; Damlalık Seçenekleri'nde Saydamlık seçeneğini kapatın veya nesnenin tamamını seçin +@msg object {_1} can't be set as point type {_1} nesnesi nokta metni olarak ayarlanamaz +@msg object {_1} has lost its file's contents: relink it {_1} nesnesi dosyasının içeriğini kaybetti: yeniden bağlayın +@msg object {_1} has no path {_1} nesnesinin yolu yok +@msg object {_1} has no size {_1} nesnesinin boyutu yok +@msg object {_1} is hidden or locked, or on a locked artboard {_1} nesnesi gizli veya kilitli ya da kilitli bir çalışma yüzeyinde +@msg object {_1} is not a placed document {_1} nesnesi yerleştirilmiş bir belge değil +@msg object {_1} is not an Intertwine group {_1} nesnesi bir İç İçe Geçme grubu değil +@msg object {_1} is not an image {_1} nesnesi bir görüntü değil +@msg object {_1} is not an image or a linked file {_1} nesnesi bir görüntü veya bağlantılı bir dosya değil +@msg object {_1} is not an image or a placed document {_1} nesnesi bir görüntü veya yerleştirilmiş bir belge değil +@msg object {_1} is not in this Intertwine group {_1} nesnesi bu İç İçe Geçme grubunda değil +@msg object {_1} needs a 3D effect at index {index} {_1} nesnesinin {index} dizininde bir 3D efekti olmalıdır +@msg object {id} has anchors 0–{_1} for `corners`, not {past} {id} nesnesinde `corners` için 0–{_1} bağlantı noktaları var, {past} yok +@msg object {id} has {n} anchors, so no anchor {past} {id} nesnesinde {n} bağlantı noktası var, bu yüzden {past} numaralı bağlantı noktası yok +@msg objects must be none, move or copy objects none, move veya copy olmalıdır +@msg objects were left out nesneler dışarıda bırakıldı +@msg offset out of range konum aralık dışında +@msg on must be true or false on true veya false olmalıdır +@msg only groups, layers, type and images have a Contents (Characters) row yalnızca grupların, katmanların, metnin ve görüntülerin bir İçerik (Karakterler) satırı vardır +@msg only interior mesh lines can be deleted yalnızca iç ağ çizgileri silinebilir +@msg only solid colours can be added (not gradients or patterns) yalnızca düz renkler eklenebilir (degradeler veya desenler eklenemez) +@msg only solid-colour swatches can be spot colours yalnızca düz renkli renk örnekleri spot renk olabilir +@msg only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first bu Affinity dosyasının yalnızca gömülü önizlemesi okunabildi: uyarısıyla birlikte görmek için Dosya › Aç komutunu kullanın veya önce Affinity'den SVG ya da PDF olarak dışa aktarın +@msg only this Affinity file's embedded preview could be read; use File › Open to see it with its warning bu Affinity dosyasının yalnızca gömülü önizlemesi okunabildi; uyarısıyla birlikte görmek için Dosya › Aç komutunu kullanın +@msg onto, above, below, icon and a column place belong to window.panel.float and window.panel.dock onto, above, below, icon ve bir sütun yeri window.panel.float ve window.panel.dock komutlarına aittir +@msg onto, above, below, icon and a column place take no anchor, side, zone or before onto, above, below, icon ve bir sütun yeri anchor, side, zone veya before almaz +@msg onto, above, below, icon and a column place take no x, y, width or height onto, above, below, icon ve bir sütun yeri x, y, width veya height almaz +@msg open a document to look for its linked files bağlantılı dosyalarını aramak için bir belge açın +@msg options must be an object (see file.formatOptions) options bir nesne olmalıdır (bkz. file.formatOptions) +@msg order must be leftToRight or rightToLeft order leftToRight veya rightToLeft olmalıdır +@msg orientation must be portrait or landscape, not `{o}` orientation portrait veya landscape olmalıdır, `{o}` değil +@msg outlineText {v}: true or false outlineText {v}: true veya false +@msg output intent profile: {e} çıktı amacı profili: {e} +@msg output.destination: no RGB or CMYK profile is called “{name}” output.destination: “{name}” adlı bir RGB veya CMYK profili yok +@msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile output.destination: {_1} dosyaları CMYK'dir ve “{name}” bir RGB profilidir +@msg output.destination: {e} output.destination: {e} +@msg output.inks: no ink is set to print output.inks: yazdırılmak üzere ayarlanmış mürekkep yok +@msg output.outputIntent: no profile is called “{name}”, and a {std} output intent embeds its profile output.outputIntent: “{name}” adlı bir profil yok ve bir {std} çıktı amacı profilini gömer +@msg output.outputIntent: no profile is called “{name}”: a {std} output intent embeds a profile, or names a registered printing condition (outputConditionId and registry) output.outputIntent: “{name}” adlı bir profil yok: bir {std} çıktı amacı bir profil gömer veya kayıtlı bir baskı koşulunu belirtir (outputConditionId ve registry) +@msg output.outputIntent: {std} files print in CMYK, and “{name}” is an RGB profile output.outputIntent: {std} dosyaları CMYK olarak yazdırılır ve “{name}” bir RGB profilidir +@msg output.outputIntent: “{name}” is a grey profile, which can't be a {std} output intent output.outputIntent: “{name}” bir gri profildir ve bir {std} çıktı amacı olamaz +@msg overlap: {o} pt is half a tile or more overlap: {o} pt bir döşemenin yarısı veya daha fazlası +@msg overlapping Shaper paths must be in the same layer or group çakışan Şekillendirici yolları aynı katmanda veya grupta olmalıdır +@msg overlapping edits çakışan düzenlemeler +@msg page art conflicts with image data for {key} sayfa resmi {key} için görüntü verileriyle çakışıyor +@msg page art conflicts with pattern {name} sayfa resmi {name} deseniyle çakışıyor +@msg page art conflicts with swatch {name} sayfa resmi {name} renk örneğiyle çakışıyor +@msg page art is missing image data for {key} sayfa resminde {key} için görüntü verileri eksik +@msg page art is missing pattern {name} sayfa resminde {name} deseni eksik +@msg page art is missing swatch {name} sayfa resminde {name} renk örneği eksik +@msg page must be a whole number from 1 page 1'den başlayan bir tam sayı olmalıdır +@msg page thumbnail: {e} sayfa küçük resmi: {e} +@msg page {page} of the PDF has no objects PDF'nin {page} numaralı sayfasında nesne yok +@msg page {page}: `{file}` has {n} {artboards} sayfa {page}: `{file}` içinde {n} {artboards} var +@msg page {page}: `{name}` has {n} {pages} sayfa {page}: `{name}` içinde {n} {pages} var +@msg pages must be a range such as "2-3" or a page number, not {v} pages "2-3" gibi bir aralık veya bir sayfa numarası olmalıdır, {v} değil +@msg pages: {e} pages: {e} +@msg panel position must be finite panel konumu sonlu olmalıdır +@msg parameters must be an object parametreler bir nesne olmalıdır +@msg params must be an object params bir nesne olmalıdır +@msg passwords can have up to {MAX_PASSWORD} bytes parolalar en fazla {MAX_PASSWORD} bayt olabilir +@msg path has no open end yolun açık ucu yok +@msg paths must be strings paths dizelerden oluşmalıdır +@msg pdfCompatible: false needs every artboard to keep the editable artwork pdfCompatible: false, düzenlenebilir resmi korumak için her çalışma yüzeyine ihtiyaç duyar +@msg pdfs `{m}`: single or multiple pdfs `{m}`: single veya multiple +@msg pickColorFrom is "artwork" or "swatches", not {v} pickColorFrom "artwork" veya "swatches" olur, {v} değil +@msg pins and moved must be non-empty lists of the same length pins ve moved aynı uzunlukta, boş olmayan listeler olmalıdır +@msg pins must be [[x,y]…] pins [[x,y]…] olmalıdır +@msg pins must be finite pins sonlu olmalıdır +@msg place is above, below or inside, not `{other}` place above, below veya inside olur, `{other}` değil +@msg plane must be left|right|ground plane left|right|ground olmalıdır +@msg plane must be left|right|ground|none plane left|right|ground|none olmalıdır +@msg point is outside the mesh nokta ağın dışında +@msg points must be [t, left, right] with non-negative widths points, negatif olmayan genişliklerle [t, left, right] olmalıdır +@msg points must be a non-empty [[x,y,pressure?]…] list points boş olmayan bir [[x,y,pressure?]…] listesi olmalıdır +@msg points must be a non-empty list of finite [x,y] points, sonlu [x,y] değerlerinden oluşan boş olmayan bir liste olmalıdır +@msg points must be an array or null points bir dizi veya null olmalıdır +@msg points must be finite points sonlu olmalıdır +@msg points must be finite [x,y] pairs points sonlu [x,y] çiftleri olmalıdır +@msg points must contain 1–4096 coordinates points 1–4096 koordinat içermelidir +@msg position must be normal, superscript or subscript position normal, superscript veya subscript olmalıdır +@msg position must be topLeft, topRight, bottomLeft or bottomRight position topLeft, topRight, bottomLeft veya bottomRight olmalıdır +@msg positions must be between 0 and 100000 pt konumlar 0 ile 100000 pt arasında olmalıdır +@msg ppi must be a positive number, not {ppi} ppi pozitif bir sayı olmalıdır, {ppi} değil +@msg ppi must be between 1 and 2400 ppi 1 ile 2400 arasında olmalıdır +@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`, transforms|bounds|fileDimensions|fit|fill değerlerinden biri değil +@msg preserveShape must be clippingMask|transparency preserveShape clippingMask|transparency olmalıdır +@msg preset `{id}`: mobile or density preset `{id}`: mobile veya density +@msg preset must be standard, diffuse, topLeft or right preset standard, diffuse, topLeft veya right olmalıdır +@msg preset must be the name of a print preset preset bir yazdırma ön ayarının adı olmalıdır +@msg previewMode must be default, pixel or overprint previewMode default, pixel veya overprint olmalıdır +@msg print settings: {e} yazdırma ayarları: {e} +@msg procedures nest too deeply yordamlar çok derin iç içe geçiyor +@msg procedures nested too deeply yordamlar çok derin iç içe geçmiş +@msg quotes must be {double?, single?} quotes {double?, single?} olmalıdır +@msg quotes.{k} must be an opening and a closing quote, e.g. "“”" quotes.{k} bir açılış ve bir kapanış tırnağı olmalıdır, örneğin "“”" +@msg rasterEffectsPpi must be 1–2400 (72 screen, 150 medium, 300 high) rasterEffectsPpi 1–2400 olmalıdır (72 ekran, 150 orta, 300 yüksek) +@msg rating must be a whole number from 0 to {MAX_RATING} rating 0 ile {MAX_RATING} arasında bir tam sayı olmalıdır +@msg rect and {k} contradict each other: give the area or the artboards rect ve {k} birbiriyle çelişiyor: alanı veya çalışma yüzeylerini verin +@msg rect applies to raster formats, not {_1} rect raster biçimler için geçerlidir, {_1} için değil +@msg rect is [x, y, width, height] in points rect punto cinsinden [x, y, width, height] olur +@msg rect must be [x, y, width, height] rect [x, y, width, height] olmalıdır +@msg rect must be [x, y, width, height] with a positive width and height rect, pozitif genişlik ve yükseklikle [x, y, width, height] olmalıdır +@msg rect needs finite numbers and a positive width and height rect için sonlu sayılar ile pozitif bir genişlik ve yükseklik gerekir +@msg redraw needs id redraw için id gerekir +@msg redraw within must be a finite distance of 0 or more redraw within 0 veya daha büyük sonlu bir uzaklık olmalıdır +@msg registration must be 0..8 registration 0..8 olmalıdır +@msg release a layer or a group bir katmanı veya grubu serbest bırakın +@msg replace keeps the replaced object's place and transform: drop template, at and rect replace, değiştirilen nesnenin yerini ve dönüşümünü korur: template, at ve rect değerlerini çıkarın +@msg replace: select the one object to replace replace: değiştirilecek tek nesneyi seçin +@msg resolution must be a number or screen|medium|high resolution bir sayı veya screen|medium|high olmalıdır +@msg resolution must be between 1 and 2400 ppi resolution 1 ile 2400 ppi arasında olmalıdır +@msg rotation must be a number of degrees rotation derece cinsinden bir sayı olmalıdır +@msg rotation must be finite rotation sonlu olmalıdır +@msg rows and cols must be 1..50 rows ve cols 1..50 olmalıdır +@msg rows and columns must be 1..500 rows ve columns 1..500 olmalıdır +@msg rows of objects whose appearances differ can't be reordered together görünümleri farklı olan nesnelerin satırları birlikte yeniden sıralanamaz +@msg save the document first: Package collects a saved document önce belgeyi kaydedin: Paket kayıtlı bir belgeyi toplar +@msg save the document first: copy puts the file in its folder önce belgeyi kaydedin: copy dosyayı belgenin klasörüne koyar +@msg savedPreset: {e} savedPreset: {e} +@msg scale `{s}`: a factor such as 2x, a width (100w), a height (100h) or a resolution (72ppi) scale `{s}`: 2x gibi bir çarpan, bir genişlik (100w), bir yükseklik (100h) veya bir çözünürlük (72ppi) +@msg scale must be a number above 0, at most 64 scale 0'dan büyük, en fazla 64 olan bir sayı olmalıdır +@msg scale must be non-zero scale sıfırdan farklı olmalıdır +@msg scope must be selection or all (got {other}) scope selection veya all olmalıdır (verilen: {other}) +@msg scribble is too long karalama çok uzun +@msg segment does not exist parça yok +@msg select a Shaper group bir Şekillendirici grubu seçin +@msg select a blend to set easing or color shift yumuşatmayı veya renk kaymasını ayarlamak için bir karışım seçin +@msg select a compound shape bir bileşik şekil seçin +@msg select a graph bir grafik seçin +@msg select a group or layer with visible, unlocked members görünür ve kilitli olmayan üyeleri olan bir grup veya katman seçin +@msg select a layer bir katman seçin +@msg select a text object bir metin nesnesi seçin +@msg select an image (or an Image Trace group) bir görüntü (veya bir Görüntü İzleme grubu) seçin +@msg select an image, or pass id bir görüntü seçin veya id verin +@msg select an object (or pass `id`) bir nesne seçin (veya `id` verin) +@msg select an object with a freeform gradient serbest biçimli degradesi olan bir nesne seçin +@msg select an object with an opacity mask opaklık maskesi olan bir nesne seçin +@msg select area type alan metni seçin +@msg select area type (text in a frame) alan metni (çerçeve içindeki metin) seçin +@msg select area type and closed paths (at least one area type object) alan metni ve kapalı yollar seçin (en az bir alan metni nesnesi) +@msg select area type whose first line can fit its frame ilk satırı çerçevesine sığabilen alan metni seçin +@msg select artwork to add its colours renklerini eklemek için resim seçin +@msg select artwork to make a group of its colours renklerinden bir grup oluşturmak için resim seçin +@msg select artwork to recolour, or give a colour `group` yeniden renklendirilecek resmi seçin veya bir renk için `group` verin +@msg select exactly two path ends to join birleştirmek için tam olarak iki yol ucu seçin +@msg select members of a compound shape bir bileşik şeklin üyelerini seçin +@msg select objects or give ids nesneleri seçin veya ids verin +@msg select objects to align to the guide kılavuza hizalanacak nesneleri seçin +@msg select one Intertwine group tek bir İç İçe Geçme grubu seçin +@msg select one image or pass id tek bir görüntü seçin veya id verin +@msg select paths yolları seçin +@msg select paths or compound paths yolları veya bileşik yolları seçin +@msg select rows or objects to collect toplanacak satırları veya nesneleri seçin +@msg select something to export dışa aktarılacak bir şey seçin +@msg select something to export (or turn off selectedOnly) dışa aktarılacak bir şey seçin (veya selectedOnly seçeneğini kapatın) +@msg select text to redefine the style from stilin yeniden tanımlanacağı metni seçin +@msg select the art and, on top of it, the mask object resmi ve onun üstündeki maske nesnesini seçin +@msg select the art for the design tasarım için resmi seçin +@msg select the art for the pattern tile desen döşemesi için resmi seçin +@msg select the art to add first önce eklenecek resmi seçin +@msg select the art to collect (or give its ids) toplanacak resmi seçin (veya kimliklerini verin) +@msg select the content and a path on top içeriği ve üstteki bir yolu seçin +@msg select the images to relink, or pass ids yeniden bağlanacak görüntüleri seçin veya ids verin +@msg select the images, or pass ids görüntüleri seçin veya ids verin +@msg select the linked images or placed documents, or pass ids bağlantılı görüntüleri veya yerleştirilmiş belgeleri seçin ya da ids verin +@msg select the object to copy from kopyalanacak kaynak nesneyi seçin +@msg select the objects (or give their ids) nesneleri seçin (veya kimliklerini verin) +@msg select the objects to attach to the path yola iliştirilecek nesneleri seçin +@msg select the objects to bind bağlanacak nesneleri seçin +@msg select two or more objects to intertwine iç içe geçirmek için iki veya daha fazla nesne seçin +@msg select two or more slices to combine birleştirmek için iki veya daha fazla dilim seçin +@msg select type on a path yol üzerindeki yazıyı seçin +@msg selection `{m}`: one or each selection `{m}`: one veya each +@msg settings is an object of document.exportForScreens params settings, document.exportForScreens parametrelerinden oluşan bir nesnedir +@msg settings must be an object settings bir nesne olmalıdır +@msg show `{show}`: all, missing, modified or embedded show `{show}`: all, missing, modified veya embedded +@msg show must be true or false show true veya false olmalıdır +@msg size must be "small", "medium", "large" or a number of points over 0 up to {_1} size "small", "medium", "large" veya 0'dan büyük, en fazla {_1} olan punto cinsinden bir sayı olmalıdır +@msg size must be positive size pozitif olmalıdır +@msg sizeMode is "fixed" or "pressure", not `{other}` sizeMode "fixed" veya "pressure" olur, `{other}` değil +@msg sizeMode is "fixed" or "pressure", not {other} sizeMode "fixed" veya "pressure" olur, {other} değil +@msg sizeVariation must be 0 or more sizeVariation 0 veya daha büyük olmalıdır +@msg smallCaps must be true or false smallCaps true veya false olmalıdır +@msg sort `{x}`: name, kind or status sort `{x}`: name, kind veya status +@msg source paths are too large for Shaper kaynak yollar Şekillendirici için çok büyük +@msg spot, mode and group apply to solid colours only spot, mode ve group yalnızca düz renkler için geçerlidir +@msg status `{s}`: linked, embedded, missing or modified status `{s}`: linked, embedded, missing veya modified +@msg steps must be 1..1000 steps 1..1000 olmalıdır +@msg steps must be 1..{MAX_STEPS} steps 1..{MAX_STEPS} olmalıdır +@msg stop {i}: `plates` must be four numbers from 0 to 1 (C, M, Y, K) durak {i}: `plates` 0 ile 1 arasında dört sayı olmalıdır (C, M, Y, K) +@msg stopped before the archive was finished arşiv tamamlanmadan önce durduruldu +@msg strokeMode must be within|along|across, got {m} strokeMode within|along|across olmalıdır, verilen: {m} +@msg strokeOptions must be an object of stroke.set options strokeOptions, stroke.set seçeneklerinden oluşan bir nesne olmalıdır +@msg strokeWidth must be a positive number of pixels strokeWidth piksel cinsinden pozitif bir sayı olmalıdır +@msg subpath {si} is not an open subpath {si} numaralı alt yol açık bir alt yol değil +@msg subpaths required when joining the same path aynı yol birleştirilirken subpaths gereklidir +@msg swatchConflict must be "merge" or "add", not {v} swatchConflict "merge" veya "add" olmalıdır, {v} değil +@msg text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} text {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} olmalıdır +@msg text transform is collapsed or unrepresentable metin dönüşümü çökmüş veya ifade edilemiyor +@msg text.replaceSpaces must be a whole number from 2 to 100 text.replaceSpaces 2 ile 100 arasında bir tam sayı olmalıdır +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: "{_1}" veya "{_2}" kullanın +@msg textureImage: give {path} or {name, dataBase64} of an image file, or a texture as effect.list gives it textureImage: bir görüntü dosyasının {path} veya {name, dataBase64} değerini ya da effect.list'in verdiği biçimde bir doku verin +@msg textureImage: {e} textureImage: {e} +@msg that makes more than {MAX_PIECES} slices bu {MAX_PIECES} taneden fazla dilim oluşturuyor +@msg that object is not in the overlap o nesne çakışmanın içinde değil +@msg the Affinity document has no page with a size Affinity belgesinde boyutu olan bir sayfa yok +@msg the CMYK image couldn't be written CMYK görüntü yazılamadı +@msg the PDF security settings were saved without their passwords: give openPassword or permissionsPassword again, or security without passwordRequired to export unprotected PDF güvenlik ayarları parolaları olmadan kaydedildi: openPassword veya permissionsPassword değerini yeniden verin ya da korumasız dışa aktarmak için passwordRequired olmadan security verin +@msg the RTF file has too many paragraphs or formatting changes to place as type (at most {MAX_PARAGRAPHS} paragraphs and {MAX_RUNS} runs) RTF dosyasında metin olarak yerleştirilemeyecek kadar çok paragraf veya biçimlendirme değişikliği var (en fazla {MAX_PARAGRAPHS} paragraf ve {MAX_RUNS} dizi) +@msg the RTF file is too large to place as type (at most {_1} MB) RTF dosyası metin olarak yerleştirilemeyecek kadar büyük (en fazla {_1} MB) +@msg the SVG expands to more than {0} nested SVG images SVG, {0} taneden fazla iç içe SVG görüntüsüne genişliyor +@msg the SVG expands to more than {0} objects SVG, {0} taneden fazla nesneye genişliyor +@msg the SVG has no drawable objects SVG'de çizilebilir nesne yok +@msg the SVGZ file unpacks to more than {_1} MB SVGZ dosyası açılınca {_1} MB'ı aşıyor +@msg the Word document has more than {MAX_PAGES} pages of properties, too many to place Word belgesinde {MAX_PAGES} sayfadan fazla özellik var; yerleştirilemeyecek kadar çok +@msg the Word document has more than {MAX_RUNS} runs of character or paragraph properties, too many to place Word belgesinde {MAX_RUNS} taneden fazla karakter veya paragraf özelliği dizisi var; yerleştirilemeyecek kadar çok +@msg the Word document has more than {_1} MB of formatting properties, too many to place Word belgesinde {_1} MB'tan fazla biçimlendirme özelliği var; yerleştirilemeyecek kadar çok +@msg the Word document has too much text or formatting to place as type (at most {MAX_PARAGRAPHS} paragraphs, {MAX_RUNS} runs and {_1} MB of text) Word belgesinde metin olarak yerleştirilemeyecek kadar çok metin veya biçimlendirme var (en fazla {MAX_PARAGRAPHS} paragraf, {MAX_RUNS} dizi ve {_1} MB metin) +@msg the Word document has too much text to place as type (at most {_1} MB) Word belgesinde metin olarak yerleştirilemeyecek kadar çok metin var (en fazla {_1} MB) +@msg the Word document is encrypted or protected with a password; save it without one to place it Word belgesi şifrelenmiş veya parolayla korunmuş; yerleştirmek için parolasız kaydedin +@msg the Word document is too large to place (its {name} stream holds more than {_1} MB) Word belgesi yerleştirilemeyecek kadar büyük ({name} akışı {_1} MB'tan fazla veri içeriyor) +@msg the Word document was last saved with fast save, which VectorCraft doesn't read; save it again with fast save turned off Word belgesi son olarak hızlı kaydetme ile kaydedilmiş ve VectorCraft bunu okumaz; hızlı kaydetme kapalıyken yeniden kaydedin +@msg the Word document was saved by Word 6.0 or Word 95, which VectorCraft doesn't read; save it as a Word 97-2003 document Word belgesi Word 6.0 veya Word 95 ile kaydedilmiş ve VectorCraft bunu okumaz; Word 97-2003 belgesi olarak kaydedin +@msg the Word document's text is made of more than {MAX_PIECES} pieces, too many to place Word belgesinin metni {MAX_PIECES} taneden fazla parçadan oluşuyor; yerleştirilemeyecek kadar çok +@msg the action set ids are not a list eylem seti kimlikleri bir liste değil +@msg the active paint is not a gradient etkin boya bir degrade değil +@msg the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size çalışma yüzeyleri tuvale sığmıyor: daha az çalışma yüzeyi, daha az aralık veya daha küçük bir boyut kullanın +@msg the character's size can't be measured karakterin boyutu ölçülemiyor +@msg the compound shape is too complex to expand bileşik şekil genişletilemeyecek kadar karmaşık +@msg the container of the listed objects is gone listelenen nesnelerin kapsayıcısı artık yok +@msg the copy `{user_id}` can't be read as a library `{user_id}` kopyası bir kütüphane olarak okunamıyor +@msg the copy would leave the canvas kopya tuvalin dışına çıkardı +@msg the cut cannot be made on this art: {e} bu resimde kesim yapılamıyor: {e} +@msg the data isn't an EMF or WMF picture veri bir EMF veya WMF resmi değil +@msg the data isn't an EPS or PostScript picture veri bir EPS veya PostScript resmi değil +@msg the deferred paste is no longer available ertelenmiş yapıştırma artık kullanılamıyor +@msg the design is too big to draw at every data point of this graph tasarım bu grafiğin her veri noktasında çizilemeyecek kadar büyük +@msg the design is too big to draw in every column of this graph tasarım bu grafiğin her sütununda çizilemeyecek kadar büyük +@msg the dialog it was opened over is no longer open üzerinde açıldığı iletişim kutusu artık açık değil +@msg the dictionary stack overflowed sözlük yığını taştı +@msg the editing data's hash has no place düzenleme verilerinin karması için yer yok +@msg the entities the document declares expand to too much text belgenin bildirdiği varlıklar çok fazla metne genişliyor +@msg the envelope's content has no bounds zarfın içeriğinin sınırları yok +@msg the envelope's mesh is malformed zarfın ağı hatalı biçimlendirilmiş +@msg the file holds no `variableSets` element dosyada `variableSets` öğesi yok +@msg the file is larger than {_1} MB dosya {_1} MB'tan büyük +@msg the file is too large dosya çok büyük +@msg the file was updated or encrypted already dosya zaten güncellenmiş veya şifrelenmiş +@msg the first character of a line has no character before it to kern: it moves only up and down (dy) bir satırın ilk karakterinden önce aralığı ayarlanacak bir karakter yoktur: yalnızca yukarı ve aşağı hareket eder (dy) +@msg the font {_1} is not available {_1} yazı tipi kullanılamıyor +@msg the format has no file extension biçimin dosya uzantısı yok +@msg the graphic can't be read: {e} grafik okunamıyor: {e} +@msg the graphic is empty grafik boş +@msg the graphic's data is damaged grafiğin verileri hasarlı +@msg the graphic's document has no artboard grafiğin belgesinde çalışma yüzeyi yok +@msg the header `{cell}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` için `{cell}` başlığı `{other}` değişkeni olarak geri okunurdu: birini yeniden adlandırın +@msg the image `{path}` isn't followed: {r} `{path}` görüntüsü izlenmiyor: {r} +@msg the image has no embedded pixels görüntüde gömülü piksel yok +@msg the image is empty görüntü boş +@msg the image is fully transparent görüntü tamamen saydam +@msg the image is not on an artboard; pass rect görüntü bir çalışma yüzeyinde değil; rect verin +@msg the image's pixels are missing görüntünün pikselleri eksik +@msg the image's pixels aren't in the document görüntünün pikselleri belgede değil +@msg the image's pixels can't be read: {e} görüntünün pikselleri okunamıyor: {e} +@msg the image's transparency doesn't fit it görüntünün saydamlığı görüntüye uymuyor +@msg the job would print more than {MAX_PAGES} pages iş {MAX_PAGES} sayfadan fazla yazdırırdı +@msg the job would print more than {_1} pages iş {_1} sayfadan fazla yazdırırdı +@msg the layers hold no art to mask katmanlarda maskelenecek resim yok +@msg the layout moved düzen taşındı +@msg the library has a group `{name}` already kütüphanede `{name}` grubu zaten var +@msg the library has no group `{name}` kütüphanede `{name}` grubu yok +@msg the library has no item `{item}` kütüphanede `{item}` öğesi yok +@msg the library has no item `{other}` kütüphanede `{other}` öğesi yok +@msg the library holds {MAX_GROUPS} groups already kütüphanede zaten {MAX_GROUPS} grup var +@msg the library holds {MAX_ITEMS} items of this kind already kütüphanede bu türden zaten {MAX_ITEMS} öğe var +@msg the name is empty ad boş +@msg the object has no fill, stroke or effect nesnenin dolgusu, konturu veya efekti yok +@msg the object has no graphic style (pass `name`) nesnenin grafik stili yok (`name` verin) +@msg the objects don't match the plan nesneler planla eşleşmiyor +@msg the open and permissions passwords must differ açma ve izin parolaları farklı olmalıdır +@msg the operand stack overflowed işlenen yığını taştı +@msg the page has no area sayfanın alanı yok +@msg the page's type in an unread object's box isn't in its page art okunmamış bir nesnenin kutusundaki sayfa metni, sayfa resminde yok +@msg the paint behind the proxy is not a gradient vekilin arkasındaki boya bir degrade değil +@msg the parent must be a layer or sublayer üst öğe bir katman veya alt katman olmalıdır +@msg the path can't be extended yol uzatılamıyor +@msg the path can't be inside one of the objects to attach yol, iliştirilecek nesnelerden birinin içinde olamaz +@msg the path has no segments to measure yolda ölçülecek parça yok +@msg the path is empty yol boş +@msg the path is too short to shorten that much yol o kadar kısaltılamayacak kadar kısa +@msg the picture has no objects resimde nesne yok +@msg the program runs too long program çok uzun süre çalışıyor +@msg the program uses too much memory program çok fazla bellek kullanıyor +@msg the rectangle must have a width and a height dikdörtgenin bir genişliği ve bir yüksekliği olmalıdır +@msg the rectangle needs a size and must lie on the canvas dikdörtgenin bir boyutu olmalı ve tuvalin üzerinde bulunmalıdır +@msg the selected art has no width seçili resmin genişliği yok +@msg the selection draws nothing seçim hiçbir şey çizmiyor +@msg the selection has no area seçimin alanı yok +@msg the selection has no art to export seçimde dışa aktarılacak resim yok +@msg the selection has no bounds seçimin sınırları yok +@msg the selection has no graphic style seçimin grafik stili yok +@msg the slice would leave the canvas dilim tuvalin dışına çıkardı +@msg the spot colour couldn't be added spot renk eklenemedi +@msg the subpath has no ends to extend (it is closed or a single point) alt yolun uzatılacak ucu yok (kapalı veya tek bir nokta) +@msg the symbols are nested too deeply to expand their instances semboller, örnekleri genişletilemeyecek kadar derin iç içe geçmiş +@msg the text file is too large to place as type (at most {_1} MB) metin dosyası metin olarak yerleştirilemeyecek kadar büyük (en fazla {_1} MB) +@msg the text is empty metin boş +@msg the text is over {_1} MB metin {_1} MB'tan büyük +@msg the top object must be a path üstteki nesne bir yol olmalıdır +@msg the trace was cancelled izleme iptal edildi +@msg the trailer has no size trailer'ın boyutu yok +@msg the type object is flattened to nothing metin nesnesi düzleştirilince hiçbir şey kalmıyor +@msg the value of axis `{tag}` must be a number or null `{tag}` ekseninin değeri bir sayı veya null olmalıdır +@msg the variable library declares more than {MAX_LIBRARY_DATASETS} data sets değişken kütüphanesi {MAX_LIBRARY_DATASETS} taneden fazla veri kümesi bildiriyor +@msg the variable library declares more than {MAX_LIBRARY_ENTITIES} entities değişken kütüphanesi {MAX_LIBRARY_ENTITIES} taneden fazla varlık bildiriyor +@msg the variable library declares more than {MAX_LIBRARY_VARIABLES} variables değişken kütüphanesi {MAX_LIBRARY_VARIABLES} taneden fazla değişken bildiriyor +@msg the variable library declares no variables değişken kütüphanesi hiçbir değişken bildirmiyor +@msg the variable library is larger than {MAX_LIBRARY_BYTES} bytes değişken kütüphanesi {MAX_LIBRARY_BYTES} bayttan büyük +@msg the variable library is not UTF-8 değişken kütüphanesi UTF-8 değil +@msg the variable library is not well-formed XML: {e} değişken kütüphanesi iyi biçimlendirilmiş bir XML değil: {e} +@msg the variable library nests elements more than {MAX_LIBRARY_NESTING} deep değişken kütüphanesi öğeleri {MAX_LIBRARY_NESTING} düzeyden daha derin iç içe yerleştiriyor +@msg the variable library's document type declaration holds something other than entities of plain text değişken kütüphanesinin belge türü bildirimi, düz metin varlıklarından başka bir şey içeriyor +@msg the variable library's entities expand to more than {MAX_LIBRARY_BYTES} bytes değişken kütüphanesinin varlıkları {MAX_LIBRARY_BYTES} bayttan fazlasına genişliyor +@msg the window has no dock pencerede yerleştirme alanı yok +@msg the written PDF has no catalog yazılan PDF'de katalog yok +@msg the written PDF has no cross-reference table yazılan PDF'de çapraz başvuru tablosu yok +@msg the written PDF's metadata can't be edited yazılan PDF'nin meta verileri düzenlenemiyor +@msg there are no colour swatches to draw çizilecek renk örneği yok +@msg there is already a design named `{name}` `{name}` adlı bir tasarım zaten var +@msg there is already a design named `{to}` `{to}` adlı bir tasarım zaten var +@msg there is already a toolbar named `{name}` `{name}` adlı bir araç çubuğu zaten var +@msg there is already a toolbar named `{to}` `{to}` adlı bir araç çubuğu zaten var +@msg there is no library: create one first kütüphane yok: önce bir tane oluşturun +@msg these paths are too degenerate for Shaper bu yollar Şekillendirici için fazla yozlaşmış +@msg thumbnail: no page {v} (the {what} has {count}) thumbnail: {v} numaralı sayfa yok ({what} içinde {count} tane var) +@msg tileRange of {what}: {e} {what} için tileRange: {e} +@msg title can't be empty title boş olamaz +@msg to (the new name) is required to (yeni ad) gereklidir +@msg to must be fill or stroke to fill veya stroke olmalıdır +@msg to must be smooth or corner to smooth veya corner olmalıdır +@msg too large for a zip archive: package to a folder bir zip arşivi için çok büyük: bir klasöre paketleyin +@msg too many Shaper edits çok fazla Şekillendirici düzenlemesi +@msg too many `points` (at most 100000) çok fazla `points` (en fazla 100000) +@msg too many characters: at most {MAX_CHARS} çok fazla karakter: en fazla {MAX_CHARS} +@msg too many dots for this size: lower the frequency bu boyut için çok fazla nokta: frekansı düşürün +@msg too many filters over one file tek bir dosya üzerinde çok fazla filtre +@msg too many overlapping paths for Shaper Şekillendirici için çok fazla çakışan yol +@msg too many saved clips çok fazla kayıtlı kırpma +@msg too many saved graphics states çok fazla kayıtlı grafik durumu +@msg toolbar (a toolbar's name) must be a string toolbar (bir araç çubuğunun adı) bir dize olmalıdır +@msg toolbar name can't be empty araç çubuğu adı boş olamaz +@msg transparentImages {v}: "flatten" (the default) or "omit" transparentImages {v}: "flatten" (varsayılan) veya "omit" +@msg two saved selections would be named `{_1}` iki kayıtlı seçimin adı `{_1}` olurdu +@msg type dimension cannot be represented with this text transform metin boyutu bu metin dönüşümüyle ifade edilemiyor +@msg type dimension must be finite metin boyutu sonlu olmalıdır +@msg unexpected resources beklenmeyen kaynaklar +@msg unknown CMYK profile `{name}` bilinmeyen CMYK profili `{name}` +@msg unknown File Info field `{k}` bilinmeyen Dosya Bilgisi alanı `{k}` +@msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) featureChanges içinde bilinmeyen OpenType özelliği `{t}` (`features` parametresinin aldığı etiketler) +@msg unknown PDF preset `{name}` (presets: {_1}) bilinmeyen PDF ön ayarı `{name}` (ön ayarlar: {_1}) +@msg unknown Warp style bilinmeyen Çarpıtma stili +@msg unknown alignToPath `{a}` bilinmeyen alignToPath `{a}` +@msg unknown arrowhead {v} bilinmeyen ok ucu {v} +@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) bilinmeyen artboardLayout anahtarı `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown attribute `{attribute}` bilinmeyen öznitelik `{attribute}` +@msg unknown attribute `{k}` bilinmeyen öznitelik `{k}` +@msg unknown axis `{other}` (vertical|horizontal|free) bilinmeyen eksen `{other}` (vertical|horizontal|free) +@msg unknown blend mode `{b}` bilinmeyen karıştırma modu `{b}` +@msg unknown blend mode {b} bilinmeyen karıştırma modu {b} +@msg unknown brush type `{o}` bilinmeyen fırça türü `{o}` +@msg unknown category `{c}` bilinmeyen kategori `{c}` +@msg unknown category `{c}` ({_1}) bilinmeyen kategori `{c}` ({_1}) +@msg unknown character `{c}` bilinmeyen karakter `{c}` +@msg unknown character style number field bilinmeyen karakter stili sayı alanı +@msg unknown effect `{e}` bilinmeyen efekt `{e}` +@msg unknown end {e} bilinmeyen uç {e} +@msg unknown flattenerPreset `{name}` (High Resolution, Medium Resolution, Low Resolution or a saved one: see flattener.presets.list) bilinmeyen flattenerPreset `{name}` (High Resolution, Medium Resolution, Low Resolution veya kayıtlı bir ön ayar: bkz. flattener.presets.list) +@msg unknown format `{f}` (vcswatches, gpl, ase or css) bilinmeyen biçim `{f}` (vcswatches, gpl, ase veya css) +@msg unknown from {f} bilinmeyen from {f} +@msg unknown graph type `{t}` bilinmeyen grafik türü `{t}` +@msg unknown grid colours `{name}` (one of {_1}) bilinmeyen ızgara renkleri `{name}` (şunlardan biri: {_1}) +@msg unknown gridType `{t}` bilinmeyen gridType `{t}` +@msg unknown highlight `{v}` bilinmeyen vurgu `{v}` +@msg unknown intent `{i}` bilinmeyen amaç `{i}` +@msg unknown issue kind {id} bilinmeyen sorun türü {id} +@msg unknown issue kind {v} bilinmeyen sorun türü {v} +@msg unknown knockout state {k} bilinmeyen nakavt durumu {k} +@msg unknown language `{language}` (one of {_1}) bilinmeyen dil `{language}` (şunlardan biri: {_1}) +@msg unknown language `{l}` (one of {_1}) bilinmeyen dil `{l}` (şunlardan biri: {_1}) +@msg unknown method `{m}` ({_1}) bilinmeyen yöntem `{m}` ({_1}) +@msg unknown mode `{other}` (gray, rgb, hsb, lab, cmyk or web) bilinmeyen mod `{other}` (gray, rgb, hsb, lab, cmyk veya web) +@msg unknown mode `{other}` (mono|cmyk) bilinmeyen mod `{other}` (mono|cmyk) +@msg unknown mode `{other}` (rgb|cmyk|gray|global) bilinmeyen mod `{other}` (rgb|cmyk|gray|global) +@msg unknown mode `{other}` (set, add, subtract) bilinmeyen mod `{other}` (set, add, subtract) +@msg unknown mode `{o}` bilinmeyen mod `{o}` +@msg unknown mode {m} bilinmeyen mod {m} +@msg unknown model `{other}` bilinmeyen model `{other}` +@msg unknown model `{other}` (keep, new or document) bilinmeyen model `{other}` (keep, new veya document) +@msg unknown op {o} bilinmeyen op {o} +@msg unknown order `{o}`: toggle, front, forward, backward or back bilinmeyen order `{o}`: toggle, front, forward, backward veya back +@msg unknown overprints `{v}` (preserve, simulate or discard) bilinmeyen overprints `{v}` (preserve, simulate veya discard) +@msg unknown panel bilinmeyen panel +@msg unknown pieLegend `{v}` (none, standard or wedges) bilinmeyen pieLegend `{v}` (none, standard veya wedges) +@msg unknown piePosition `{v}` (even, ratio or stacked) bilinmeyen piePosition `{v}` (even, ratio veya stacked) +@msg unknown pieSort `{v}` (none, all or first) bilinmeyen pieSort `{v}` (none, all veya first) +@msg unknown plate `{n}` bilinmeyen kalıp `{n}` +@msg unknown preference `{k}` bilinmeyen tercih `{k}` +@msg unknown profile {id} (see stroke.widthProfile.list) bilinmeyen profil {id} (bkz. stroke.widthProfile.list) +@msg unknown proof target `{t}` bilinmeyen prova hedefi `{t}` +@msg unknown quotes key `{k}` (double, single) bilinmeyen quotes anahtarı `{k}` (double, single) +@msg unknown resolution `{v}` bilinmeyen çözünürlük `{v}` +@msg unknown rule `{rule}` ({_1}) bilinmeyen kural `{rule}` ({_1}) +@msg unknown rule `{r}` (see color.harmony) bilinmeyen kural `{r}` (bkz. color.harmony) +@msg unknown setting `{k}` bilinmeyen ayar `{k}` +@msg unknown shape `{v}` (circle|ellipse|square|diamond|line) bilinmeyen şekil `{v}` (circle|ellipse|square|diamond|line) +@msg unknown spacing `{o}` (smooth|steps|distance) bilinmeyen spacing `{o}` (smooth|steps|distance) +@msg unknown tileType `{t}` ({_1}) bilinmeyen tileType `{t}` ({_1}) +@msg unknown units bilinmeyen birimler +@msg unknown units `{u}` bilinmeyen birimler `{u}` +@msg unknown value axis `{v}` (left, right or both) bilinmeyen değer ekseni `{v}` (left, right veya both) +@msg unknown variation `{v}` (tintsShades|warmCool|vividMuted) bilinmeyen çeşitleme `{v}` (tintsShades|warmCool|vividMuted) +@msg unknown warp style `{s}` bilinmeyen çarpıtma stili `{s}` +@msg unknown {key} `{v}` (none, short or full) bilinmeyen {key} `{v}` (none, short veya full) +@msg unknown {key} profile `{n}` bilinmeyen {key} profili `{n}` +@msg unknown {k} key `{key}` (size, position) bilinmeyen {k} anahtarı `{key}` (size, position) +@msg unreadable object okunamayan nesne +@msg unsafe destination file name güvenli olmayan hedef dosya adı +@msg use paths or compound paths yolları veya bileşik yolları kullanın +@msg useArtboards must be true or false, not {v} useArtboards true veya false olmalıdır, {v} değil +@msg value for `{var}` must match its variable kind `{var}` değeri değişkeninin türüyle eşleşmelidir +@msg variable `{_1}` is already defined `{_1}` değişkeni zaten tanımlı +@msg variable `{name}` has no `trait` `{name}` değişkeninde `trait` yok +@msg variable `{name}` is already defined `{name}` değişkeni zaten tanımlı +@msg variable `{name}` is declared twice `{name}` değişkeni iki kez bildirilmiş +@msg variable `{to}` already exists `{to}` değişkeni zaten var +@msg view is required view gereklidir +@msg view must be one of {_1} view şunlardan biri olmalıdır: {_1} +@msg warpStyle can only edit an applied Warp effect warpStyle yalnızca uygulanmış bir Çarpıtma efektini düzenleyebilir +@msg width and height must be more than 0 and at most {limit} width ve height 0'dan büyük ve en fazla {limit} olmalıdır +@msg width factors must be finite genişlik çarpanları sonlu olmalıdır +@msg width must be positive width pozitif olmalıdır +@msg width out of range genişlik aralık dışında +@msg width/height must be > 0 width/height > 0 olmalıdır +@msg x and y must be finite numbers x ve y sonlu sayılar olmalıdır +@msg x and y must be given together x ve y birlikte verilmelidir +@msg zone needs an anchor: dock beside a panel with anchor, or in a new dock column with side (Start or End) zone için bir anchor gerekir: anchor ile bir panelin yanına veya side (Start ya da End) ile yeni bir yerleştirme sütununa yerleştirin +@msg zoom must be positive zoom pozitif olmalıdır +@msg {C}: no effect at index {list} {C}: {list} dizininde efekt yok +@msg {DEFAULT_PRESET} is protected and stays {DEFAULT_PRESET} korumalıdır ve kalır +@msg {DEFAULT_PRESET} is protected: save the settings under another name {DEFAULT_PRESET} korumalıdır: ayarları başka bir adla kaydedin +@msg {LABEL} produced an empty result {LABEL} boş bir sonuç üretti +@msg {_1} MB of document, at most {_2} MB {_1} MB belge, en fazla {_2} MB +@msg {_1} MB of images, at most {_2} MB {_1} MB görüntü, en fazla {_2} MB +@msg {_1} bytes of RGBA data for a {width} × {height} image {width} × {height} boyutlu bir görüntü için {_1} bayt RGBA verisi +@msg {_1} can't be read, or changed since it was read: relink or update it first {_1} okunamıyor veya okunduktan sonra değişmiş: önce yeniden bağlayın veya güncelleyin +@msg {_1} can't go into {into} {_1}, {into} içine konulamaz +@msg {_1} can't limit printing to low resolution: choose PDF 1.4 or later, or allow high-resolution printing {_1} yazdırmayı düşük çözünürlükle sınırlayamaz: PDF 1.4 veya sonrasını seçin ya da yüksek çözünürlüklü yazdırmaya izin verin +@msg {_1} files can't be opened yet {_1} dosyaları henüz açılamıyor +@msg {_1} files can't be password-protected: remove the passwords or choose no standard {_1} dosyaları parolayla korunamaz: parolaları kaldırın veya standart seçmeyin +@msg {_1} files can't be {_2} {_1} dosyaları için şu yapılamaz: {_2} +@msg {_1} files can't carry editing data: turn off preserveEditing {_1} dosyaları düzenleme verileri taşıyamaz: preserveEditing seçeneğini kapatın +@msg {_1} files can't have PDF layers: turn off createLayers {_1} dosyalarında PDF katmanları olamaz: createLayers seçeneğini kapatın +@msg {_1} files need a creation date, and this platform has no clock to give one {_1} dosyaları için bir oluşturma tarihi gerekir ve bu platformda bunu verecek bir saat yok +@msg {_1} isn't a path {_1} bir yol değil +@msg {_1} options: {e} {_1} seçenekleri: {e} +@msg {_1} paints nothing to rasterize {_1} rasterleştirilecek hiçbir şey boyamıyor +@msg {_1} passwords can have up to {MAX_LEGACY_PASSWORD} ASCII characters (PDF 1.7 and later take any) {_1} parolaları en fazla {MAX_LEGACY_PASSWORD} ASCII karakter içerebilir (PDF 1.7 ve sonrası her karakteri alır) +@msg {_1} with linked images or an image map writes several files: use document.export bağlantılı görüntüler veya bir görüntü eşlemi içeren {_1} birkaç dosya yazar: document.export kullanın +@msg {_1} writes one file per artboard here: use document.export, or name one artboard {_1} burada çalışma yüzeyi başına bir dosya yazar: document.export kullanın veya tek bir çalışma yüzeyi belirtin +@msg {_1} × {_2} pixels is too large for {_3} (at most {max} pixels a side): lower the scale {_1} × {_2} piksel {_3} için çok büyük (kenar başına en fazla {max} piksel): ölçeği düşürün +@msg {_1}: belongs to another account {_1}: başka bir hesaba ait +@msg {_1}: not a folder of its own {_1}: kendine ait bir klasör değil +@msg {_1}: not a plain file {_1}: düz bir dosya değil +@msg {dest}: {e} {dest}: {e} +@msg {doc} has no folder {doc} belgesinin klasörü yok +@msg {file} isn't linked {file} bağlantılı değil +@msg {folder} is not a package folder {folder} bir paket klasörü değil +@msg {folder}: more than {max} files and folders {folder}: {max} taneden fazla dosya ve klasör +@msg {folder}: {e} {folder}: {e} +@msg {g} is not a Live Paint group {g} bir Canlı Boyama grubu değil +@msg {id} is not a slice {id} bir dilim değil +@msg {key} must be 0–{MAX_ADD_AROUND} pt {key} 0–{MAX_ADD_AROUND} pt olmalıdır +@msg {key} must be [x,y] {key} [x,y] olmalıdır +@msg {key} must be a percentage {min}..100 {key} {min}..100 aralığında bir yüzde olmalıdır +@msg {key} must be a positive number, not {n} {key} pozitif bir sayı olmalıdır, {n} değil +@msg {key} must be a positive number, not {v} {key} pozitif bir sayı olmalıdır, {v} değil +@msg {key} must be one of {_1} {key} şunlardan biri olmalıdır: {_1} +@msg {key} must be {_1}, got {s} {key} {_1} olmalıdır, verilen: {s} +@msg {key} must name a floating panel {key} yüzen bir paneli belirtmelidir +@msg {key} must name a panel in another group {key} başka bir gruptaki bir paneli belirtmelidir +@msg {key} must name a panel that shows {key} gösterilen bir paneli belirtmelidir +@msg {key} must name a registered panel {key} kayıtlı bir paneli belirtmelidir +@msg {kind} files have no transparency, and the file would have {what}: flatten it first (object.flattenTransparency) {kind} dosyalarında saydamlık yoktur ve dosyada {what} olurdu: önce düzleştirin (object.flattenTransparency) +@msg {kind} images can't be opened (see document.formats) {kind} görüntüleri açılamıyor (bkz. document.formats) +@msg {k} `{v}` is not one of the choices {k} `{v}` seçeneklerden biri değil +@msg {k} has control characters{_1} {k} denetim karakterleri içeriyor{_1} +@msg {k} is too long (at most {MAX_TEXT} characters) {k} çok uzun (en fazla {MAX_TEXT} karakter) +@msg {k} must be > 0 {k} > 0 olmalıdır +@msg {k} must be a number (pt) or a length such as "210 mm" {k} bir sayı (pt) veya "210 mm" gibi bir uzunluk olmalıdır +@msg {k} must be a number from {min} to {max} {k} {min} ile {max} arasında bir sayı olmalıdır +@msg {k} must be a number or "auto" {k} bir sayı veya "auto" olmalıdır +@msg {k} must be a string {k} bir dize olmalıdır +@msg {k} must be text {k} metin olmalıdır +@msg {k} must be true or false {k} true veya false olmalıdır +@msg {k} must be {{size?, position?}} {k} {{size?, position?}} olmalıdır +@msg {k}: can't read `{s}` as a length {k}: `{s}` bir uzunluk olarak okunamıyor +@msg {label} must be a number at most {max} {label} en fazla {max} olan bir sayı olmalıdır +@msg {label} must be a number from -1296 to 1296 {label} -1296 ile 1296 arasında bir sayı olmalıdır +@msg {label} must be a number from 1 to 10000 {label} 1 ile 10000 arasında bir sayı olmalıdır +@msg {name} `{s}`: {ids} {name} `{s}`: {ids} +@msg {name} is built in and can't be deleted {name} yerleşiktir ve silinemez +@msg {name}: CRC or size mismatch {name}: CRC veya boyut uyuşmazlığı +@msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: bu Affinity dosyasının yalnızca gömülü önizlemesi okunabildi; uyarısıyla birlikte görmek için Dosya › Aç komutunu kullanın veya yerleştirmeden önce Affinity'den SVG ya da PDF olarak dışa aktarın +@msg {name}: {e} {name}: {e} +@msg {native}; its embedded preview can't be read either ({e}) {native}; gömülü önizlemesi de okunamıyor ({e}) +@msg {std} files are CMYK, and the file would have colours in {_1} {std} dosyaları CMYK'dir ve dosyada {_1} renkleri olurdu +@msg {std} files embed their fonts, and the file would have one that isn't {std} dosyaları yazı tiplerini gömer ve dosyada gömülmemiş bir yazı tipi olurdu +@msg {target} is the file this document was read from, and reading it left things out ({what}): writing over it would lose them for good. Write another file instead, or pass acknowledgeLoss: true to replace it anyway {target}, bu belgenin okunduğu dosyadır ve okunurken bazı şeyler dışarıda kaldı ({what}): üzerine yazmak bunları kalıcı olarak kaybettirir. Bunun yerine başka bir dosya yazın veya yine de değiştirmek için acknowledgeLoss: true verin +@msg {ty} brushes need selected art (or params.{k}) {ty} fırçaları için seçili resim (veya params.{k}) gerekir +@msg {v} is not an asset id {v} bir varlık kimliği değil +@msg {what} can't be intertwined {what} iç içe geçirilemez +@msg {what} doesn't fit the paper with its bleed and marks {what}, taşma payı ve işaretleriyle birlikte kâğıda sığmıyor +@msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} {MAX_TILES} taneden fazla döşemeye yazdırılırdı: ölçeğini küçültün Playback Options Oynatma Seçenekleri Accelerated Hızlandırılmış Step by Step Adım Adım @@ -7613,6 +9422,15 @@ breakText Glyphs Glifler Grommets Kuşgözleri Grommet Inset Kuşgözlerinin kenara uzaklığı Diameter Çap +@msg `{key}` must be from 0.01 to 1000 pt `{key}` 0.01 ile 1000 pt arasında olmalıdır +@msg turn on at least one side en az bir kenarı açın +@msg with no hem and no grommets there is nothing to mark kenar kıvırma ve kuşgözü olmadan işaretlenecek bir şey yok +@msg select the banner, or mark every artboard afişi seçin veya her çalışma yüzeyini işaretleyin +@msg there is no banner to mark işaretlenecek afiş yok +@msg the banner has no width or height afişin genişliği veya yüksekliği yok +@msg the hem is too deep for the banner kenar kıvırma afiş için çok derin +@msg the grommet inset is too large for the banner kuşgözlerinin kenara uzaklığı afiş için çok büyük +@msg the spacing makes more than {MAX_GROMMETS} grommets bu aralık {MAX_GROMMETS} taneden fazla kuşgözü oluşturur Nest Shapes… Şekilleri yerleştir… Nest Shapes Şekilleri yerleştir Roll Rulo diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 804a855704..c407a9cb79 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… Нерізка маска… @@ -540,8 +541,8 @@ font-technology Variable Варіативні Color Guide Options Параметри колірного гіда Color Guide Options… Параметри колірного гіда… Color images Кольорові зображення - Color Library Бібліотека квітів - Color Library… Бібліотека квітів… + Color Library Бібліотека кольорів + Color Library… Бібліотека кольорів… Color Management Керування кольором Color Mixer (Shift-click the chip) Змішувач кольорів (Shift+клацання на зразку) Color Mode Колірний режим @@ -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 Копіювати в «Користувацькі» @@ -2703,6 +2705,8 @@ mark-style Japanese Японський Proof Setup Налаштування кольоропроби Properties Властивості Proportional Metrics Пропорційні метрики + H or V Style Горизонтальний або вертикальний стиль + Roman Italics Римський курсив Insert Aki Left Вставити акі ліворуч Insert Aki Right Вставити акі праворуч Tsume Цуме @@ -4428,6 +4432,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} @@ -8628,6 +8633,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 не містить об’єктів, які можна намалювати @@ -8847,7 +8853,7 @@ breakText Glyphs Гліфи @msg unexpected resources неочікувані ресурси @msg unknown CMYK profile `{name}` невідомий профіль CMYK `{name}` @msg unknown File Info field `{k}` невідоме поле відомостей про файл `{k}` -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) невідома функція OpenType `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; префікс - вимикає функцію; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom і aalt приймають номер альтернативи у вигляді `tag=N`, де N від 0 до {_1}, наприклад `salt=2`) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) невідома функція OpenType `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; префікс - вимикає функцію; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom і aalt приймають номер альтернативи у вигляді `tag=N`, де N від 0 до {_1}, наприклад `salt=2`) @msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) невідома функція OpenType `{t}` у featureChanges (допустимі теги, які приймає `features`) @msg unknown PDF preset `{name}` (presets: {_1}) невідомий набір PDF `{name}` (набори: {_1}) @msg unknown Warp style невідомий стиль деформації diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 19560e8b68..c306e6dcd9 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 @@ -3016,6 +3017,8 @@ mark-style Japanese Kiểu Nhật Proof Setup Thiết lập thử nghiệm Properties Thuộc tính Proportional Metrics Số liệu theo tỷ lệ + H or V Style Kiểu ngang hoặc dọc + Roman Italics Nghiêng Roman Insert Aki Left Chèn aki bên trái Insert Aki Right Chèn aki bên phải Tsume Tsume @@ -3047,6 +3050,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 @@ -4869,6 +4873,7 @@ theme Appearance Giao diện @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` chỉ dành cho lần chạy không có ai để hỏi: trong ứng dụng, người dùng trả lời từng hộp thoại @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} @@ -5286,6 +5291,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 52d0df9031..7d0cd92344 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 复制到用户定义 @@ -2566,6 +2567,8 @@ font-script Japanese 汉字 Proof Setup 校样设置 Properties 属性 Proportional Metrics 比例度量 + H or V Style 横排或直排样式 + Roman Italics 西文斜体 Insert Aki Left 在前方插入空白 Insert Aki Right 在后方插入空白 Tsume 比例间距 @@ -4889,6 +4892,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 +5579,7 @@ axis Both 两者 # Photoshop-style raster effects (Effect menu, their dialogs). Radial Blur… 径向模糊… + Blur Center 模糊中心 Smart Blur… 智能模糊… Sharpen 锐化 Unsharp Mask… 反锐化遮罩… @@ -7746,7 +7751,7 @@ breakText Glyphs 字形 @msg too many arguments 参数过多 @msg too many quantifiers 量词过多 @msg turn on at least one side 请至少打开一条边 -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) 未知的 OpenType 特性 `{t}` (liga、calt、dlig、smcp、frac、onum、tnum、ordn、swsh、ss01–ss20、salt、titl、pnum、lnum、sups、subs、numr、dnom、aalt;加前缀 - 表示关闭;swsh、ss01–ss20、salt、titl、pnum、lnum、sups、subs、numr、dnom 和 aalt 可用 `tag=N` 指定替代字形的编号,N 为 0 到 {_1},例如 `salt=2`) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) 未知的 OpenType 特性 `{t}` (liga、calt、dlig、smcp、frac、onum、tnum、ordn、swsh、ss01–ss20、salt、titl、pnum、lnum、sups、subs、numr、dnom、aalt、hkna、ital;加前缀 - 表示关闭;swsh、ss01–ss20、salt、titl、pnum、lnum、sups、subs、numr、dnom 和 aalt 可用 `tag=N` 指定替代字形的编号,N 为 0 到 {_1},例如 `salt=2`) @msg unknown dither `{d}` (diffusion, pattern, noise or none) 未知的仿色 `{d}` (diffusion、pattern、noise 或 none) @msg unknown panel `{panel}` 未知的面板 `{panel}` @msg unknown parameter `{key}` 未知的参数 `{key}` @@ -8870,6 +8875,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 ce7eebd6c3..b99c5d9015 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 複製到使用者定義 @@ -2591,6 +2592,7 @@ file-filter Templates 範本 @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 僅適用於沒有人可詢問的執行:在應用程式中,由使用者回答每個對話框 @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}` @@ -3786,6 +3788,8 @@ font-script Japanese 漢字 Proof Setup 校樣設定 Properties 內容 Proportional Metrics 比例度量 + H or V Style 橫排或直排樣式 + Roman Italics 羅馬字斜體 Insert Aki Left 在前方插入空白 Insert Aki Right 在後方插入空白 Tsume 比例間距 @@ -5411,6 +5415,7 @@ axis Both 兩者 # Photoshop-style raster effects (Effect menu, their dialogs). Radial Blur… 放射狀模糊… + Blur Center 模糊中心 Smart Blur… 智慧型模糊… Sharpen 銳利化 Unsharp Mask… 反銳利化遮罩… @@ -7674,7 +7679,7 @@ breakText Glyphs 字符 @msg too many arguments 引數過多 @msg too many quantifiers 量詞過多 @msg turn on at least one side 請至少開啟一側 -@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) 未知的 OpenType 功能 `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt;加上前置的 - 可關閉;swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom 和 aalt 可用 `tag=N` 指定替代字的編號,N 為 0 到 {_1},例如 `salt=2`) +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) 未知的 OpenType 功能 `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt, hkna, ital;加上前置的 - 可關閉;swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom 和 aalt 可用 `tag=N` 指定替代字的編號,N 為 0 到 {_1},例如 `salt=2`) @msg unknown dither `{d}` (diffusion, pattern, noise or none) 未知的仿色 `{d}` (diffusion、pattern、noise 或 none) @msg unknown panel `{panel}` 未知的面板 `{panel}` @msg unknown parameter `{key}` 未知的參數 `{key}` @@ -8798,6 +8803,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..6efd472675 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -845,6 +845,7 @@ fn run_ui_part8(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::navigator::set_options(app, p), "ui.layersExpand" => crate::panels::layers::expand(app, p), "ui.layersFilter" => crate::panels::layers::set_filter(app, p), + "ui.panelView" => crate::panels::set_view(app, p), "ui.flattenTransparencyDialog" => { crate::dialogs::flatten::open(app); Ok(Value::Null) @@ -976,6 +977,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/tests.rs b/crates/ui-egui/src/menus/tests.rs index d8ca0b79ec..1bb152292e 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -1008,6 +1008,57 @@ fn expand_appearance_is_an_object_menu_item_only() { assert_eq!(paths, [vec!["Object".to_string()]]); } +/// Object › Distribute follows Object › Align and lists the Align panel's Distribute Objects and +/// Distribute Spacing buttons, each item running the button's command: dimmed with nothing +/// selected, spacing three objects evenly, and with a key object sending the Distribute Spacing value. +#[test] +fn object_distribute_runs_the_distribute_buttons() { + let object = menu_tree().into_iter().find(|(t, _)| *t == "Object").map(|(_, items)| items).unwrap_or_default(); + let subs: Vec<&str> = object.iter().filter_map(|it| if let Item::Sub(l, _) = it { Some(*l) } else { None }).collect(); + let align = subs.iter().position(|l| *l == "Align").unwrap_or_else(|| panic!("Object › Align: {subs:?}")); + assert_eq!(subs.get(align + 1), Some(&"Distribute"), "{subs:?}"); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let items = |app: &VectorcraftApp| -> Vec { menu_entries(app).into_iter().filter(|e| e.path == ["Object", "Distribute"]).collect() }; + let listed: Vec<(String, Option)> = items(&app).into_iter().map(|e| (e.label, e.command)).collect(); + let expected: Vec<(String, Option)> = [ + ("Horizontal Distribute Left", "align.distributeHorizontalLeft"), + ("Horizontal Distribute Center", "align.distributeHorizontalCenter"), + ("Horizontal Distribute Right", "align.distributeHorizontalRight"), + ("Vertical Distribute Top", "align.distributeVerticalTop"), + ("Vertical Distribute Center", "align.distributeVerticalCenter"), + ("Vertical Distribute Bottom", "align.distributeVerticalBottom"), + ("Horizontal Distribute Space", "align.distributeHorizontalSpace"), + ("Vertical Distribute Space", "align.distributeVerticalSpace"), + ] + .into_iter() + .map(|(l, id)| (l.to_string(), Some(id.to_string()))) + .collect(); + assert_eq!(listed, expected); + assert!(items(&app).iter().all(|e| !e.enabled), "nothing selected"); + let ids: Vec = [0, 30, 100] + .into_iter() + .map(|x| app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10})).unwrap()["id"].clone()) + .collect(); + app.run("select.set", json!({"ids": ids})).unwrap(); + let lefts = |app: &VectorcraftApp| -> Vec { + let doc = &app.session.active().unwrap().doc; + ids.iter().map(|id| doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap().x0).collect() + }; + let click = |app: &mut VectorcraftApp, label: &str| { + let e = items(app).into_iter().find(|e| e.label == label).unwrap_or_else(|| panic!("{label}")); + assert!(e.enabled, "{label}"); + let (id, p) = click_target(&e.label, e.command.as_deref().unwrap_or_default(), &e.params); + invoke(app, &id, p); + }; + click(&mut app, "Horizontal Distribute Left"); + assert_eq!(lefts(&app), [0.0, 50.0, 100.0], "{}", app.ui.status); + app.ui.align_spacing = 5.0; + app.run("select.key", json!({"id": ids[0]})).unwrap(); + click(&mut app, "Horizontal Distribute Space"); + assert_eq!(lefts(&app), [0.0, 15.0, 30.0], "{}", app.ui.status); +} + /// Isolation keeps the Lock and Hide actions available for selected members. #[test] fn lock_and_hide_menus_are_enabled_in_isolation_mode() { diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index cc63a489cf..b718b24080 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -165,6 +165,23 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { cp("Vertical Align Bottom", "object.align", json!({"vertical": "bottom"})), ], ), + // The Align panel's Distribute Objects and Distribute Spacing buttons: each item runs + // what a click on its button runs (`crate::panels::align::run_button`). + sub( + "Distribute", + vec![ + c("Horizontal Distribute Left", "align.distributeHorizontalLeft"), + c("Horizontal Distribute Center", "align.distributeHorizontalCenter"), + c("Horizontal Distribute Right", "align.distributeHorizontalRight"), + Sep, + c("Vertical Distribute Top", "align.distributeVerticalTop"), + c("Vertical Distribute Center", "align.distributeVerticalCenter"), + c("Vertical Distribute Bottom", "align.distributeVerticalBottom"), + Sep, + c("Horizontal Distribute Space", "align.distributeHorizontalSpace"), + c("Vertical Distribute Space", "align.distributeVerticalSpace"), + ], + ), Sep, c("Group", "object.group"), c("Ungroup", "object.ungroup"), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 21b8795662..24a39c9335 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1088,6 +1088,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{objects?: [paths|shapes|text|images|effects|groups|linkedFiles|guides], layers?: [locked|hidden]} set the Layers panel's Filter (By Object, By Layer): a row stays when it is of a kind in `objects` and in a state in `layers` (its own lock or eye; an empty list takes every row), or when a row inside it stays; Search All narrows the rows further. A key left out keeps its list. The filter lasts the session and does not change the document, its open rows or the selection → {objects, layers}", ), + ( + "ui.panelView", + "Set Panel View", + "", + "{panel: swatches|graphicStyles|symbols, view?} set a panel's view, as the view items of its panel menu do: for swatches smallThumb|mediumThumb (the default)|largeThumb|smallList|largeList, for graphicStyles and symbols thumbnail (the default)|smallList|largeList; without `view`, answer the current one. The view lasts the session and does not change the document; an unknown panel or view is an error and changes nothing → {panel, view}", + ), ( "ui.tileEdgeColor", "Tile Edge Color…", @@ -1253,7 +1259,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.svgFilterDialog", "Apply SVG Filter…", "", - "{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's filters; OK runs svgFilter.apply with selected, or effect.setParams on the applied effect; New and Edit open the code, Save runs svgFilter.define, Delete runs svgFilter.delete and Import… svgFilter.import with a picked SVG file", + "{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's defaults (the document's filter of a default's name in its place) and then the document's other filters; OK runs svgFilter.apply with selected, and with index and item for the applied effect; New and Edit open the code, Save runs svgFilter.define (replace: the filter edited, a default included), Delete runs svgFilter.delete (off for a default the document holds no copy of) and Import… svgFilter.import with a picked SVG file", ), ( "ui.importSvgFilter", @@ -1456,6 +1462,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.rs b/crates/ui-egui/src/panels.rs index bbe91da5a6..a56bcd7128 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -514,6 +514,42 @@ pub(crate) fn set_pstate(ctx: &egui::Context, ctx.data_mut(|d| d.insert_temp(egui::Id::unique(("panel-state", key)), v)); } +/// `ui.panelView {panel, view?}`: set the view of the Swatches, Graphic Styles or Symbols panel +/// (`panel`: swatches, graphicStyles or symbols), as the view items of its panel menu do; without +/// `view`, answer the current one. An unknown panel or view is an error, and then nothing changes. +/// → {panel, view} +pub(crate) fn set_view(app: &mut VectorcraftApp, p: &Value) -> Result { + fn given(p: &Value, err: &str) -> Result, String> { + match p.get("view") { + None | Some(Value::Null) => Ok(None), + Some(v) => serde_json::from_value(v.clone()).map(Some).map_err(|_| err.to_string()), + } + } + let ui = &mut app.ui; + let (panel, view) = match p.get("panel").and_then(Value::as_str) { + Some("swatches") => { + if let Some(v) = given(p, "`view` is smallThumb, mediumThumb, largeThumb, smallList or largeList")? { + ui.swatches_view = v; + } + ("swatches", json!(ui.swatches_view)) + } + Some("graphicStyles") => { + if let Some(v) = given(p, "`view` is thumbnail, smallList or largeList")? { + ui.graphic_styles_view = v; + } + ("graphicStyles", json!(ui.graphic_styles_view)) + } + Some("symbols") => { + if let Some(v) = given(p, "`view` is thumbnail, smallList or largeList")? { + ui.symbols_view = v; + } + ("symbols", json!(ui.symbols_view)) + } + _ => return Err("`panel` is swatches, graphicStyles or symbols".to_string()), + }; + Ok(json!({ "panel": panel, "view": view })) +} + /// Whether the panel whose state is `key` has the keyboard for its rows (Delete and Backspace /// remove its highlighted rows): it took it with a click on a row ([`set_row_keys`]) and kept it in /// every frame since, so it lapses when the panel isn't drawn. diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 4bab22d52e..a7f32611cc 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -312,7 +312,7 @@ pub fn default_sets() -> Vec { Action::new("Center on Artboard", vec![step("object.align", json!({"horizontal": "center", "vertical": "center", "to": "artboard"}))]), Action::new("Outline Text", vec![step("type.createOutlines", json!({}))]), Action::new("Rotate 90° CW", vec![step("object.rotate", json!({"angle": -90}))]), - Action::new("Reflect Horizontal", vec![step("object.reflect", json!({"axis": "vertical"}))]), + Action::new("Reflect Horizontal", vec![step("object.reflect", json!({"axis": "vertical", "basis": "box"}))]), ], )] } @@ -2721,6 +2721,28 @@ mod tests { } } + /// The built-in Reflect Horizontal reflects a rotated object across its bounding box's own axis, + /// as the Reflect dialog does, so the box keeps its angle; a saved step without a basis, recorded + /// before Reflect followed the box, still reflects across the page's axis. + #[test] + fn the_built_in_reflect_follows_the_turned_box() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = vectorcraft_doc::NodeId( + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(), + ); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + app.run("object.rotate", json!({"angle": 30})).unwrap(); + let angle = |app: &VectorcraftApp| app.session.active().unwrap().doc.bbox_angle(&[id]); + let reflect = default_sets()[0].actions.iter().position(|a| a.name == "Reflect Horizontal").unwrap(); + app.ui.action_sets = default_sets(); + play(&mut app, 0, reflect).unwrap(); + assert!((angle(&app) - 30.0).abs() < 1e-6, "{}", angle(&app)); + app.ui.action_sets = vec![ActionSet::new("Old", vec![Action::new("Reflect", vec![("object.reflect".into(), json!({"axis": "vertical"}))])])]; + play(&mut app, 0, 0).unwrap(); + assert!((angle(&app) + 30.0).abs() < 1e-6, "{}", angle(&app)); + } + /// An action recorded with a key its command no longer reads still plays, accelerated and one /// step at a time, though the same command run by itself is refused. #[test] diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index e3c1f68bef..32de20ec95 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -108,6 +108,20 @@ pub(crate) fn shared(app: &VectorcraftApp, f: impl Fn(&CharStyle) shared_styles(app, |_, _, style, _| Some(f(style))) } +/// The fonts (family and style) of the character styles the panels act on ([`shared`]), each +/// once, in the order the runs come. +pub(crate) fn selected_fonts(app: &VectorcraftApp) -> Vec<(String, String)> { + let fonts = std::cell::RefCell::new(Vec::<(String, String)>::new()); + shared_styles(app, |_, _, style, _| { + let mut fonts = fonts.borrow_mut(); + if !fonts.iter().any(|(family, face)| *family == style.font_family && *face == style.font_style) { + fonts.push((style.font_family.clone(), style.font_style.clone())); + } + Some(()) + }); + fonts.into_inner() +} + /// Dimensional controls use document units and tolerate arithmetic roundoff when comparing /// compensated runs. Keep raw styles available to font/paragraph controls and style definitions, /// even if a collapsed affine prevents editing dimensions. diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index 2a3251b012..998b737c09 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -9,12 +9,14 @@ //! that glyph as one of its alternates in its word. A glyph no feature reaches whose name does //! not belong to another letter is applied as a glyph choice, which may not join. Other glyphs //! are drawn dimmed, and their tooltips say why they cannot be applied to the selection. +//! With Show East Asian Options, the panel menu sets the selected characters' East Asian glyph +//! form ([`glyph_form_items`]). use std::collections::HashMap; use egui::{Color32, Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::json; -use vectorcraft_doc::{CharStyle, NodeId, NodeKind}; +use vectorcraft_doc::{CharStyle, GlyphForm, NodeId, NodeKind}; use vectorcraft_geom::{Affine, BezPath, PathEl}; use vectorcraft_text::FontDb; @@ -904,11 +906,115 @@ fn zoom_button(ui: &mut Ui, id: &str, label: &str, tip: &str, enabled: bool) -> resp.on_hover_text(tl!(tip)).clicked() && enabled } -pub fn menu(_app: &mut VectorcraftApp, ui: &mut Ui) { +/// The menu label of East Asian glyph form `form` ([`GlyphForm::ALL`]). +fn glyph_form_label(form: GlyphForm) -> &'static str { + match form { + GlyphForm::Traditional => "Traditional Forms", + GlyphForm::Expert => "Expert Forms", + GlyphForm::Jis04 => "JIS 04 Forms", + GlyphForm::Jis90 => "JIS 90 Forms", + GlyphForm::Jis78 => "JIS 78 Forms", + GlyphForm::Jis83 => "JIS 83 Forms", + GlyphForm::FullWidth => "Monospaced Full-Width Forms", + GlyphForm::HalfWidth => "Monospaced Half-Width Forms", + GlyphForm::ThirdWidth => "Monospaced Third-Width Forms", + GlyphForm::QuarterWidth => "Monospaced Quarter-Width Forms", + GlyphForm::Default => "Revert To Default Forms", + } +} + +/// The ids of the faces that draw the characters [`glyph_form_items`] acts on: the faces the +/// fonts of their styles name, and the faces layout draws them with, fallback faces included: +/// the Type tool's selected range (every frame of its story after Select All in threaded text, +/// the whole text object at a caret), else every frame of the selected stories. Laid out once for +/// each document revision, selection and set of fonts while the menu is open, overflow text +/// included. +fn selection_faces(app: &VectorcraftApp, ui: &Ui) -> Vec { + type Key = (u64, u64, u64, Option<(NodeId, usize, usize)>, Vec); + let editing = super::character::text_editing(app).map(|(id, a, b)| (id, a.min(b), a.max(b))); + let Some(state) = app.session.active() else { return vec![] }; + let story = super::character::text_story(app); + let stories = match editing { + Some(_) => story.clone().unwrap_or_default(), + None => super::character::selected_stories(app), + }; + let db = FontDb::global(); + let key: Key = (state.uid, state.revision, db.generation(), editing, stories); + let slot = ui.scope_id().with("gl-form-faces"); + if let Some((cached, ids)) = ui.ctx().data(|d| d.get_temp::<(Key, Vec)>(slot)) + && cached == key + { + return ids; + } + let mut ids: Vec = + super::character::selected_fonts(app).iter().filter_map(|(family, style)| db.face(family, style)).map(|f| f.id()).collect(); + let mut add = |t: &vectorcraft_doc::TextObject, range: Option<(usize, usize)>| { + // Laid out as point type, so that text overflowing its area or path counts too. + let mut all = t.clone(); + all.kind = vectorcraft_doc::TextKind::Point; + for g in vectorcraft_text::layout(db, &all).glyphs { + // A glyph counts when its characters overlap the range (a ligature may start before it). + if range.is_none_or(|(a, b)| g.byte < b && g.byte + g.len.max(1) > a) && !ids.contains(&g.font_id) { + ids.push(g.font_id); + } + } + }; + let text = |id: NodeId| match state.doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => Some(t), + _ => None, + }; + match (editing, story) { + // After Select All in threaded text: every frame of the story. + (Some(_), Some(frames)) => frames.into_iter().filter_map(text).for_each(|t| add(t, None)), + (Some((id, a, b)), None) => { + if let Some(t) = text(id) { + // A caret applies the form to all the text of the object. + add(t, (a < b).then_some((a, b))); + } + } + (None, _) => super::character::selected_story_texts(app).into_iter().for_each(|t| add(t, None)), + } + ui.ctx().data_mut(|d| d.insert_temp(slot, (key, ids.clone()))); + ids +} + +/// The East Asian glyph forms of the panel menu, with Show East Asian Options: each draws the +/// selected characters (all the text of the selected type objects without a Type tool range) in +/// one form of their font, and is checked when they all have it; a form none of the faces that +/// draw the selected text has a feature for ([`selection_faces`]) is disabled. Revert To Default +/// Forms draws the font's default glyphs. +/// Public behavior: [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) +/// (Replace Asian characters with a different glyph form). +fn glyph_form_items(app: &mut VectorcraftApp, ui: &mut Ui) { + let has = super::character::text_style(app).is_some(); + let db = FontDb::global(); + let faces: Vec<_> = selection_faces(app, ui).into_iter().filter_map(|id| db.face_by_id(id)).collect(); + let current = super::character::shared(app, |s| s.glyph_form); + for form in GlyphForm::ALL { + let enabled = match form.feature() { + Some(tag) => faces.iter().any(|f| f.has_substitution_feature(*tag)), + None => has, + }; + let checked = form != GlyphForm::Default && current == Some(form); + if form == GlyphForm::Default { + ui.separator(); + } + // Choosing the form every selected character already has changes nothing. + if menu_item(ui, tl!(glyph_form_label(form)), enabled, checked) && current != Some(form) { + super::character::format(app, json!({"glyphForm": form.id()})); + } + } +} + +pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Use the Selected Text's Font"), true, false) { set_pstate::>(ui.ctx(), "gl-font", None); } ui.separator(); + if app.session.prefs.show_east_asian_options { + glyph_form_items(app, ui); + ui.separator(); + } for (i, (name, _, _)) in SUBSETS.iter().enumerate() { let cur: usize = pstate(ui.ctx(), "gl-subset"); if menu_item(ui, tl!(name), true, cur == i) { @@ -1102,6 +1208,59 @@ mod tests { text_anchors(&shapes(ctx, app, vec![])).into_iter().map(|(t, _)| t).collect() } + /// With Show East Asian Options, the panel menu lists the East Asian glyph forms; choosing one + /// draws the Type tool's selected characters in it, checks it, and Revert To Default Forms + /// takes it away. A form the font has no feature for is disabled. The second half needs + /// craft-fonts' BIZ UDMincho, which has JIS 78 forms and no JIS 04 forms (skipped without it). + #[test] + fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() { + let (mut app, id) = editing("亜唖"); + let ctx = egui::Context::default(); + let labels = |app: &mut VectorcraftApp| menu_texts(&ctx, app, vec![]).into_iter().map(|(t, _)| t).collect::>(); + let plain = |l: &String| l.trim_start_matches(['✓', ' ']).to_string(); + app.session.prefs.show_east_asian_options = false; + assert!(!labels(&mut app).iter().map(plain).any(|l| l == "JIS 78 Forms"), "hidden without Show East Asian Options"); + app.session.prefs.show_east_asian_options = true; + let shown: Vec = labels(&mut app).iter().map(plain).collect(); + for form in GlyphForm::ALL { + assert!(shown.iter().any(|l| l == glyph_form_label(form)), "{form:?} in {shown:?}"); + } + const FAMILY: &str = "BIZ UDMincho"; + if FontDb::global().face(FAMILY, "Regular").is_none_or(|f| f.family != FAMILY) { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + } + app.run("text.setRangeStyle", json!({"id": id, "font": FAMILY})).unwrap(); + let forms = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap_or(0))).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::>(), + _ => panic!("text"), + }; + select(&mut app, 3, 6); + choose(&ctx, &mut app, "JIS 78 Forms"); + assert_eq!(forms(&app), [("亜".to_string(), GlyphForm::Default), ("唖".to_string(), GlyphForm::Jis78)]); + assert!(labels(&mut app).iter().any(|l| l.starts_with('✓') && l.ends_with("JIS 78 Forms")), "checked"); + // A selection whose first font has no JIS 83 forms, and whose second one does, takes them. + let fallback = vectorcraft_text::FALLBACK_FAMILY; + if FontDb::global().face(fallback, "Regular").is_some_and(|f| !f.has_substitution_feature(*b"jp83")) { + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": fallback})).unwrap(); + select(&mut app, 0, 6); + choose(&ctx, &mut app, "JIS 83 Forms"); + assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Jis83), "{:?}", forms(&app)); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": FAMILY})).unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "glyphForm": "default"})).unwrap(); + select(&mut app, 3, 6); + choose(&ctx, &mut app, "JIS 78 Forms"); + } + // Choosing it again changes nothing, and the font has no JIS 04 forms: that item is disabled. + let n = app.session.active().unwrap().history.undo.len(); + choose(&ctx, &mut app, "JIS 78 Forms"); + choose(&ctx, &mut app, "JIS 04 Forms"); + assert_eq!(app.session.active().unwrap().history.undo.len(), n); + assert_eq!(forms(&app)[1].1, GlyphForm::Jis78); + choose(&ctx, &mut app, "Revert To Default Forms"); + assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Default), "{:?}", forms(&app)); + } + /// Show › Alternates for Current Selection lists the selected character's alternates from the /// font of its text, whatever font the panel browses; a double-click draws the character with /// one. A character without alternates, no selected character and a missing font each show a diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index b87f291e67..d7b622ba77 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -30,9 +30,10 @@ use crate::menus::Item; use crate::theme::Tokens; use crate::widgets::{self, PanelDrag, menu_item}; -/// The panel's views. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -enum View { +/// The panel's views (`ui.panelView {panel: "graphicStyles", view}`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum View { #[default] Thumbnail, SmallList, @@ -463,7 +464,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let looks = look_hashes(ui.ctx(), app); let shown = Shown { d: &doc, looks: &looks, preview: pstate(ui.ctx(), "gs-preview") }; let sel = selected(ui.ctx(), &doc); - let view: View = pstate(ui.ctx(), "gs-view"); + let view = app.ui.graphic_styles_view; let mut ev = Events::default(); // In a sized panel the list fills the space above the footer (#2992), as the Artboards list // does; elsewhere it keeps its 220 pt. @@ -605,10 +606,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { app.run("graphicStyle.sortByName", json!({})).ok(); } ui.separator(); - let view: View = pstate(ui.ctx(), "gs-view"); + let view = app.ui.graphic_styles_view; for (v, label) in View::ALL { - if menu_item(ui, tl!(label), true, view == v) { - set_pstate(ui.ctx(), "gs-view", v); + if menu_item(ui, tl!(label), true, view == v) + && let Err(e) = app.run("ui.panelView", json!({ "panel": "graphicStyles", "view": v })) + { + app.status(e); } } ui.separator(); @@ -865,7 +868,7 @@ mod tests { app.session.execute("graphicStyle.new", &json!({"name": format!("Style {i:02}")})).unwrap(); } let ctx = egui::Context::default(); - set_pstate(&ctx, "gs-view", View::LargeList); + app.ui.graphic_styles_view = View::LargeList; // The clip rect of the first style's name: the list's visible area. let mut list = |bottom: Option| { let mut clip = None; @@ -891,7 +894,7 @@ mod tests { let mut app = app(); app.session.execute("graphicStyle.new", &json!({"name": "Mine"})).unwrap(); let ctx = egui::Context::default(); - set_pstate(&ctx, "gs-view", View::LargeList); + app.ui.graphic_styles_view = View::LargeList; let texts = frame(&ctx, |ui| { show(&mut app, ui); menu(&mut app, ui); @@ -906,7 +909,7 @@ mod tests { let unused: Vec = serde_json::from_value(app.session.execute("graphicStyle.unused", &json!({})).unwrap()["names"].clone()).unwrap(); assert_eq!(unused.len(), 4); set_pstate(&ctx, "gs-sel", unused.clone()); - set_pstate(&ctx, "gs-view", View::SmallList); + app.ui.graphic_styles_view = View::SmallList; frame(&ctx, |ui| show(&mut app, ui)); // Delete asks first; OK deletes, and the panel selection follows. delete(&mut app, &unused, false); @@ -967,7 +970,7 @@ mod tests { // A style dragged onto the top half of the first row lands first (Small List View: rows // of 18 points from the top of the list). - set_pstate(&ctx, "gs-view", View::SmallList); + app.ui.graphic_styles_view = View::SmallList; frame(&ctx, |ui| show(&mut app, ui)); let release = |at: egui::Pos2| { let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; @@ -992,7 +995,7 @@ mod tests { let n = names(&app); assert_eq!(n.len(), 5); let ctx = egui::Context::default(); - set_pstate(&ctx, "gs-view", View::SmallList); + app.ui.graphic_styles_view = View::SmallList; frame(&ctx, |ui| show(&mut app, ui)); // A click on row `i` (Small List View: rows of 18 points, 3 apart) with `modifiers` held, // a second after the last one so that two clicks on a row are not a double-click. diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 244a67ddb8..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 @@ -92,28 +92,29 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option< let mut c: Cache = pstate(ctx, "links-cache"); let stale = c.key != key || now - c.at > RECHECK; if stale { + let same_doc = c.key == key; c.list = app.session.execute("links.list", &json!({ "show": o.show, "sort": o.sort, "dcsTransparency": o.dcs })).ok()?; (c.key, c.at) = (key, now); // One pass over the stored art for the rows outside the layer tree and the objects whose - // opacity masks hold them, not one per frame. - let mut want: std::collections::HashSet = c.list["links"] + // opacity masks hold them, not one per frame. An object in the layer tree is looked up by + // its index when drawn. + let doc = app.session.active().map(|st| &st.doc); + let want: std::collections::HashSet = c.list["links"] .as_array() .into_iter() .flatten() .filter(|r| nested_row(r)) .flat_map(|r| [r["id"].as_u64(), r["owner"]["maskOf"].as_u64()]) .flatten() + .filter(|id| doc.is_some_and(|d| d.node(NodeId(*id)).is_none())) .collect(); - c.nested.clear(); - if !want.is_empty() - && let Some(st) = app.session.active() - { - st.doc.visit_stored_arcs(|n, place| { - if !place.in_layers() && want.remove(&n.id.0) { - c.nested.push((n.id.0, std::sync::Arc::clone(n))); - } - }); - c.nested.sort_by_key(|(id, _)| *id); + // The same revision keeps the objects collected for it, so their thumbnails are not drawn + // again each time the files are looked at. + if !(same_doc && want.iter().all(|id| c.nested_node(*id).is_some())) { + c.nested = match doc { + Some(d) if !want.is_empty() => stored_objects(d, want), + _ => vec![], + }; } } let want = first.filter(|_| o.info); @@ -126,6 +127,44 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option< Some(c) } +/// The objects of `doc` outside the layer tree whose ids are in `want`, sorted by id. The art of +/// the stored brushes is set on `doc` only while a command uses it ([`Document::mounted_art`]), so +/// when an id is not found otherwise that art is set on a copy of `doc`, which gives its objects +/// the ids `links.list` reports for them. +/// +/// [`Document::mounted_art`]: vectorcraft_doc::Document::mounted_art +pub(super) fn stored_objects( + doc: &vectorcraft_doc::Document, + mut want: std::collections::HashSet, +) -> Vec<(u64, std::sync::Arc)> { + let mut out = vec![]; + collect_stored(doc, &mut want, &mut out); + if !want.is_empty() && doc.mounted_art.is_empty() { + let art = vectorcraft_brush::stored_art::StoredArt::read(doc); + if !art.is_empty() { + let mut d = doc.clone(); + art.mount(&mut d); + collect_stored(&d, &mut want, &mut out); + } + } + out.sort_by_key(|(id, _)| *id); + out +} + +/// Adds the objects of `d` outside the layer tree whose ids are in `want` to `out`, taking their +/// ids out of `want`. +fn collect_stored( + d: &vectorcraft_doc::Document, + want: &mut std::collections::HashSet, + out: &mut Vec<(u64, std::sync::Arc)>, +) { + d.visit_stored_arcs(|n, place| { + if !place.in_layers() && want.remove(&n.id.0) { + out.push((n.id.0, std::sync::Arc::clone(n))); + } + }); +} + /// The ids of the selected image objects and placed documents. fn selected_images(app: &VectorcraftApp) -> Vec { let Some(st) = app.session.active() else { return vec![] }; @@ -179,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() @@ -318,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. @@ -693,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). @@ -780,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/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 2d872872ff..5db4cfbd17 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -1,6 +1,7 @@ //! OpenType panel: per-character OpenType features (ligatures, alternates, swashes, small caps, -//! ordinals, fractions, figure style, position) for the selected text (every frame of each -//! selected threaded story) or the Type tool's selected characters. +//! ordinals, fractions, figure style, position, and with the East Asian options the menu's H or V +//! Style and Roman Italics) for the selected text (every frame of each selected threaded story) or +//! the Type tool's selected characters. use egui::Ui; use serde_json::json; @@ -117,10 +118,42 @@ fn shown_figure(app: &VectorcraftApp) -> Option { shared(app, |s| figure(&OtFeatures::from_tags(s.features.iter().map(String::as_str)))) } -/// Whether `flag` is on for every character the panel acts on (`Some(true)`), for none of them -/// (`Some(false)`), or only for some (`None`). +/// Whether `flag` is on for every character a toggle changes (`Some(true)`), for none of them +/// (`Some(false)`), or only for some (`None`). At a Type tool caret, and after Select All in a +/// threaded story, the command styles all the text ([`run_features`]), so every character of it +/// counts, as in [`edit`]. fn shown_flag(app: &VectorcraftApp, flag: Flag) -> Option { - shared(app, |s| flag.get(&OtFeatures::from_tags(s.features.iter().map(String::as_str)))) + let on = |s: &CharStyle| flag.get(&OtFeatures::from_tags(s.features.iter().map(String::as_str))); + if let Some(mut runs) = whole_text_runs(app) { + // A run with no text, such as an empty frame's, counts only when no run has text. + if runs.iter().any(|r| !r.text.is_empty()) { + runs.retain(|r| !r.text.is_empty()); + } + let Some(first) = runs.first() else { + return shared(app, on); + }; + let v = on(&first.style); + return runs.iter().all(|r| on(&r.style) == v).then_some(v); + } + shared(app, on) +} + +/// The runs the panel's commands style as a whole while the Type tool edits text: those of every +/// frame of the story after Select All in threaded text, else at a caret (an empty selection) +/// those of the text object. `None` for a range in one text object, or with no Type tool editing. +fn whole_text_runs(app: &VectorcraftApp) -> Option> { + let (id, a, b) = text_editing(app)?; + let st = app.session.active()?; + let ids = match super::character::text_story(app) { + Some(story) => story, + None if b <= a => vec![id], + None => return None, + }; + let runs = ids.into_iter().filter_map(|id| match &st.doc.node(id)?.kind { + NodeKind::Text(t) => Some(t.runs.iter()), + _ => None, + }); + Some(runs.flatten().collect()) } /// The Figure menu's text for entry `shown`: Mixed when the characters differ. @@ -150,8 +183,9 @@ impl Change { } /// Make `change` to the features of each character the panel acts on, from the character's own -/// features (`featureChanges`), unless it changes none of them. At a Type tool caret the -/// command styles all the text, so every character of the text is checked. +/// features (`featureChanges`), unless it changes none of them. At a Type tool caret, and after +/// Select All in a threaded story, the command styles all the text, so every character of it is +/// checked ([`whole_text_runs`]). fn edit(app: &mut VectorcraftApp, change: Change) { let same = |s: &CharStyle| { let before = OtFeatures::from_tags(s.features.iter().map(String::as_str)); @@ -159,12 +193,9 @@ fn edit(app: &mut VectorcraftApp, change: Change) { change.apply(&mut after); after == before }; - let unchanged = match text_editing(app) { - Some((id, a, b)) if b <= a => match app.session.active().and_then(|st| st.doc.node(id)).map(|n| &n.kind) { - Some(NodeKind::Text(t)) => Some(t.runs.iter().all(|r| same(&r.style))), - _ => None, - }, - _ => shared(app, same), + let unchanged = match whole_text_runs(app) { + Some(runs) => Some(runs.iter().all(|r| same(&r.style))), + None => shared(app, same), }; if unchanged != Some(true) { run_features(app, "featureChanges", OtFeatures::changes(|f| change.apply(f))); @@ -304,10 +335,29 @@ fn rows() -> [Toggle; 9] { ] } +/// The panel menu's East Asian items, with Show East Asian Options: label and the feature each +/// turns on and off. H or V Style sets kana in the forms the font draws for the writing direction +/// (`hkna`, shaped as `vkna` in vertical type), and Roman Italics sets half-width alphanumerics +/// in the font's italic forms (`ital`). +fn east_asian_items() -> [Toggle; 2] { + [(tl!("H or V Style"), Flag::Extra("hkna")), (tl!("Roman Italics"), Flag::Extra("ital"))] +} + pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { - if menu_item(ui, tl!("Reset OpenType Features"), text_style(app).is_some(), false) { + let has = text_style(app).is_some(); + if menu_item(ui, tl!("Reset OpenType Features"), has, false) { set(app, OtFeatures::default()); } + if app.session.prefs.show_east_asian_options { + ui.separator(); + // Checked when every character it changes has it; chosen then, it turns it off. + for (label, flag) in east_asian_items() { + let on = shown_flag(app, flag) == Some(true); + if menu_item(ui, label, has, on) { + edit(app, Change::Toggle(flag, !on)); + } + } + } } #[cfg(test)] @@ -715,4 +765,127 @@ mod tests { edit(&mut app, Change::Position(4)); assert_eq!(undo_steps(&app), undo + 1); } + + /// H or V Style and Roman Italics are in the panel menu with the East Asian options only. + #[test] + fn kana_style_and_roman_italics_show_with_the_east_asian_options() { + let mut app = selected_text(); + let shown = |app: &mut VectorcraftApp| { + let text = crate::tests_labels::painted_text(app, menu); + (text.contains("H or V Style"), text.contains("Roman Italics")) + }; + assert_eq!(shown(&mut app), (false, false)); + app.session.prefs.show_east_asian_options = true; + assert_eq!(shown(&mut app), (true, true)); + } + + /// With the Type tool's characters only partly set, H or V Style and Roman Italics show + /// unchecked; chosen, each turns its feature on for every selected character in one undo step, + /// each run keeping its other features, and shows checked; chosen again, it turns it off. + /// Reset OpenType Features clears both. + #[test] + fn kana_style_and_roman_italics_turn_on_and_off() { + for (label, tag) in [("H or V Style", "hkna"), ("Roman Italics", "ital")] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.prefs.show_east_asian_options = true; + app.session.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "かなAB"})).unwrap()["id"].clone(); + app.session.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 3, "features": [tag, "smcp"]})).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + // "かなAB" is 8 bytes. + app.session.set_tool_option("select", &json!({"start": 0, "end": 8})); + let ctx = egui::Context::default(); + let row = |app: &mut VectorcraftApp, label: &str| { + let texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], menu); + texts.into_iter().find(|(t, _)| t.trim_start_matches(['✓', ' ']) == label).unwrap_or_else(|| panic!("{label} missing")) + }; + let has = |runs: &[(String, Value)], t: &str| runs.iter().all(|(_, f)| f.as_array().is_some_and(|f| f.iter().any(|x| x == t))); + let (text, at) = row(&mut app, label); + assert!(!text.starts_with('✓'), "{label}: {text:?}"); + let undo = undo_steps(&app); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert_eq!(undo_steps(&app), undo + 1, "{label}"); + let runs = run_features(&mut app, &id, 8); + assert!(has(&runs, tag), "{label}: {runs:?}"); + assert!(has(&runs[..1], "smcp") && runs[0].0 == "か", "{label} keeps the other features: {runs:?}"); + let (text, at) = row(&mut app, label); + assert!(text.starts_with('✓'), "{label}: {text:?}"); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert_eq!(run_features(&mut app, &id, 8), [("か".to_string(), json!(["smcp"])), ("なAB".to_string(), Value::Null)], "{label} off"); + app.session.execute("text.setRangeStyle", &json!({"id": id, "features": ["hkna", "ital", "dlig"]})).unwrap(); + let at = row(&mut app, "Reset OpenType Features").1; + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert_eq!(run_features(&mut app, &id, 8), [("かなAB".to_string(), Value::Null)], "{label}: reset"); + } + } + + /// At a Type tool caret after a character that has H or V Style or Roman Italics while the + /// rest of the text does not, the item and the checkbox rows read every character the command + /// styles at a caret (all of them): the item shows unchecked, a Small Caps row set the same way + /// shows a dash, and choosing the item turns its feature on for the whole text. + #[test] + fn caret_items_read_every_character_they_change() { + for (label, tag) in [("H or V Style", "hkna"), ("Roman Italics", "ital")] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.prefs.show_east_asian_options = true; + app.session.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "かなAB"})).unwrap()["id"].clone(); + app.session.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 3, "features": [tag, "smcp"]})).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + // The caret after "か", whose style the next typed character takes. + app.session.set_tool_option("select", &json!({"start": 3, "end": 3})); + assert_eq!(text_editing(&app).map(|(_, a, b)| (a, b)), Some((3, 3))); + assert_eq!(shown_flag(&app, Flag::Field(|f| &mut f.small_caps)), None, "{label}: Small Caps row"); + let ctx = egui::Context::default(); + let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu); + let Some((text, at)) = texts.into_iter().find(|(t, _)| t.trim_start_matches(['✓', ' ']) == label) else { panic!("{label} missing") }; + assert!(!text.starts_with('✓'), "{label}: {text:?}"); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + let runs = run_features(&mut app, &id, 8); + assert!(runs.iter().all(|(_, f)| f.as_array().is_some_and(|f| f.iter().any(|x| x == tag))), "{label}: {runs:?}"); + } + } + + /// After Select All in a threaded story whose edited frame is empty, the item reads the text + /// of every frame the command styles: with the story's text set with H or V Style or Roman + /// Italics it shows checked, and choosing it turns the feature off for that text. + #[test] + fn select_all_from_an_empty_frame_reads_the_whole_story() { + for (label, tag) in [("H or V Style", "hkna"), ("Roman Italics", "ital")] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.prefs.show_east_asian_options = true; + app.run("file.new", json!({"width": 600, "height": 300})).unwrap(); + let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(4); + let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("shape.rectangle", json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("text.thread.create", json!({})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": 0})); + app.run("select.all", json!({})).unwrap(); + // A frame threaded in before the first takes the whole text, leaving the edited frame empty. + let c = app.run("text.thread.add", json!({"from": a, "before": true, "rect": [700, 10, 400, 600]})).unwrap()["id"].as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": c, "features": [tag]})).unwrap(); + assert_eq!(text_editing(&app).map(|(id, a, b)| (id.0, a, b)), Some((a, 0, 0)), "{label}"); + assert_eq!(super::super::character::text_story(&app).map(|frames| frames.len()), Some(3), "{label}"); + // The empty frames' runs, which hold no character, without the feature. + for id in [a, b] { + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let Some(NodeKind::Text(t)) = doc.node_mut(NodeId(id)).map(|n| &mut n.kind) else { panic!("no frame {id}") }; + for r in &mut t.runs { + r.style.features.clear(); + } + } + let ctx = egui::Context::default(); + let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu); + let Some((text, at)) = texts.into_iter().find(|(t, _)| t.trim_start_matches(['✓', ' ']) == label) else { panic!("{label} missing") }; + assert!(text.starts_with('✓'), "{label}: {text:?}"); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + let runs = run_features(&mut app, &json!(c), story.len()); + assert!(runs.iter().all(|(_, f)| !f.as_array().is_some_and(|f| f.iter().any(|x| x == tag))), "{label}: {runs:?}"); + } + } } diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index 06c8935d30..b183787366 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -121,7 +121,7 @@ pub(super) fn new_swatch(app: &mut VectorcraftApp, sel: &[String], m: egui::Modi } pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { - let view: View = pstate(ui.ctx(), "swatch-view"); + let view = app.ui.swatches_view; let selected = selection(app, ui); let del = deletable(&selected); let opts = editable(app, &selected); @@ -174,7 +174,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { ui.separator(); for (v, label) in View::ALL { if menu_item(ui, label, true, v == view) { - set_pstate(ui.ctx(), "swatch-view", v); + app.run("ui.panelView", json!({ "panel": "swatches", "view": v })).ok(); } } ui.separator(); diff --git a/crates/ui-egui/src/panels/swatches/body.rs b/crates/ui-egui/src/panels/swatches/body.rs index ef830c8c43..96e003bcf1 100644 --- a/crates/ui-egui/src/panels/swatches/body.rs +++ b/crates/ui-egui/src/panels/swatches/body.rs @@ -16,17 +16,21 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) { crate::panels::empty_state(ui, "swatch-book", tl!("No document"), tl!("Open a document to see its swatches.")); return; } - let view: View = pstate(ui.ctx(), "swatch-view"); + let view = app.ui.swatches_view; let kind: Kind = pstate(ui.ctx(), "swatch-kind"); // Top row: proxy at left, list / grid view toggles at right. ui.horizontal(|ui| { crate::panels::proxy(app, ui, 34.0); ui.add_space(ui.available_width() - 58.0); + let mut to = None; if widgets::icon_button(ui, "dc-list-view", tl!("Show List View"), view.is_list(), 26.0).clicked() { - set_pstate(ui.ctx(), "swatch-view", View::SmallList); + to = Some(View::SmallList); } if widgets::icon_button(ui, "dc-grid-view", tl!("Show Thumbnail View"), !view.is_list(), 26.0).clicked() { - set_pstate(ui.ctx(), "swatch-view", View::MediumThumb); + to = Some(View::MediumThumb); + } + if let Some(v) = to { + app.run("ui.panelView", json!({ "panel": "swatches", "view": v })).ok(); } }); ui.add_space(4.0); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 2de0dd2a3d..601c8dc627 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -489,7 +489,7 @@ fn find_field_filters_and_shift_extends_over_what_is_shown() { fn list_view_rows_take_double_clicks_and_folder_clicks_select_the_group() { let mut app = app(); let ctx = context(); - set_pstate(&ctx, "swatch-view", View::SmallList); + app.ui.swatches_view = View::SmallList; double_click_tile(&mut app, &ctx, "Red"); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "double-click in a list opens Swatch Options"); let d = &app.session.active().unwrap().doc; @@ -1013,7 +1013,7 @@ fn the_list_fills_a_tall_panel_above_its_footer() { app.run("swatch.new", json!({"name": format!("Tone {i:02}"), "color": format!("#{:02x}3060", i * 4)})).unwrap(); } let ctx = context(); - set_pstate(&ctx, "swatch-view", View::SmallList); + app.ui.swatches_view = View::SmallList; // The clip rect of the first swatch row's name: the list's visible area. let mut list = |bottom: Option| { let mut clip = None; diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index c0abeb9dac..195d6172f4 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -286,7 +286,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let Some((doc, keys)) = app.session.active().map(|d| (d.doc.clone(), document_symbols(d))) else { return }; let names: Vec = doc.symbols.iter().map(|s| s.name.clone()).collect(); - let view: View = pstate(ui.ctx(), VIEW); + let view = app.ui.symbols_view; let sel = current(app); let uid = app.session.active().map(|d| d.uid); let marked = marked(ui.ctx(), uid, &names); @@ -458,10 +458,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { app.status(e); } ui.separator(); - let view: View = pstate(ui.ctx(), VIEW); + let view = app.ui.symbols_view; for (v, label) in View::ALL { - if menu_item(ui, tl!(label), true, view == v) { - set_pstate(ui.ctx(), VIEW, v); + if menu_item(ui, tl!(label), true, view == v) + && let Err(e) = app.run("ui.panelView", json!({ "panel": "symbols", "view": v })) + { + app.status(e); } } ui.separator(); @@ -475,13 +477,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { /// The panel state key of the symbols Select All Unused picked. const MARKED: &str = "sym-unused"; -/// The panel state key of the panel's [`View`]. -const VIEW: &str = "sym-view"; - /// The panel's views: Thumbnail View (the default) and the Small and Large List Views, whose rows -/// show each symbol's thumbnail and name. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -enum View { +/// show each symbol's thumbnail and name (`ui.panelView {panel: "symbols", view}`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum View { #[default] Thumbnail, SmallList, @@ -1170,7 +1170,7 @@ mod tests { // Large List View: the row named Dot. let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); - set_pstate(&ctx, VIEW, View::LargeList); + app.ui.symbols_view = View::LargeList; let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(236.0, 400.0))), ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui)); out.textures_delta.clear(); @@ -1238,7 +1238,6 @@ mod tests { assert_eq!((editing(&app), current(&mut app)), (None, Some("Cat".into())), "{view}"); let ctx2 = egui::Context::default(); crate::theme::install_fonts(&ctx2); - set_pstate(&ctx2, VIEW, pstate::(&ctx, VIEW)); frame(&ctx2, &mut app, vec![]); frame(&ctx2, &mut app, double_click(row)); assert_eq!(editing(&app).as_deref(), Some("Cat"), "{view}"); @@ -1253,6 +1252,49 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), undo); } + /// `ui.panelView` sets the Symbols, Graphic Styles and Swatches panels' views as the view items + /// of their panel menus do, and answers the current view without `view`. An unknown panel or + /// view, or a view of another panel, is an error and changes nothing. + #[test] + fn panel_view_sets_the_view_of_each_panel() { + use super::super::{graphic_styles, swatches}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + for (i, name) in ["ant", "bee"].into_iter().enumerate() { + app.run("shape.rectangle", json!({"x": 10.0 + 40.0 * i as f64, "y": 10, "width": 30, "height": 20})).unwrap(); + app.run("symbol.new", json!({"name": name})).unwrap(); + } + let views = |checked: &str| ["Thumbnail View", "Small List View", "Large List View"].map(|v| (v.to_string(), v == checked)).to_vec(); + assert_eq!(app.run("ui.panelView", json!({"panel": "symbols"})).unwrap(), json!({"panel": "symbols", "view": "thumbnail"})); + assert!(panel_labels(&ctx, &mut app, &["ant", "bee"]).is_empty(), "the thumbnails draw no names"); + let r = app.run("ui.panelView", json!({"panel": "symbols", "view": "largeList"})).unwrap(); + assert_eq!(r, json!({"panel": "symbols", "view": "largeList"})); + assert_eq!(view_items(&ctx, &mut app), views("Large List View"), "the panel menu checks it"); + let names: Vec = panel_labels(&ctx, &mut app, &["ant", "bee"]).into_iter().map(|(t, _)| t).collect(); + assert_eq!(names, ["ant", "bee"], "the list names the symbols"); + click_menu(&ctx, &mut app, "Small List View"); + assert_eq!(app.run("ui.panelView", json!({"panel": "symbols"})).unwrap()["view"], "smallList", "the menu item sets it too"); + for bad in [ + json!({"panel": "symbols", "view": "mediumThumb"}), + json!({"panel": "symbols", "view": 3}), + json!({"panel": "brushes", "view": "smallList"}), + json!({"view": "largeList"}), + ] { + assert!(app.run("ui.panelView", bad.clone()).is_err(), "{bad}"); + } + assert_eq!(app.ui.symbols_view, View::SmallList, "unchanged"); + let r = app.run("ui.panelView", json!({"panel": "graphicStyles", "view": "largeList"})).unwrap(); + assert_eq!(r, json!({"panel": "graphicStyles", "view": "largeList"})); + assert_eq!(app.ui.graphic_styles_view, graphic_styles::View::LargeList); + assert_eq!(app.run("ui.panelView", json!({"panel": "swatches"})).unwrap()["view"], "mediumThumb"); + app.run("ui.panelView", json!({"panel": "swatches", "view": "largeThumb"})).unwrap(); + assert!(app.run("ui.panelView", json!({"panel": "swatches", "view": "thumbnail"})).is_err()); + assert_eq!(app.ui.swatches_view, swatches::View::LargeThumb, "unchanged by the error"); + assert_eq!(app.ui.symbols_view, View::SmallList, "each panel keeps its own view"); + } + /// The panel menu's Edit Symbol edits the selected instance's symbol, and with no instance /// selected the symbol current in the panel. #[test] @@ -1724,7 +1766,7 @@ mod tests { assert!(!symbols(h.state_mut()).contains(&"B".to_string())); // Also test list view - set_pstate(&h.ctx, VIEW, View::SmallList); + h.state_mut().ui.symbols_view = View::SmallList; h.run_steps(2); let node_a = h.get_by_label("A"); let pos_a = node_a.rect().center(); diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 8b3e065a64..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. @@ -238,6 +279,28 @@ fn a_mask_rows_tooltip_names_its_object_inside_a_symbol() { assert!(text.iter().any(|t| t.contains(&want)), "{want} in {text:?}"); } +/// The row of an image in a stored brush's art finds its object for the thumbnail, though that art +/// is set on the document only while a command uses it. +#[test] +fn a_row_in_a_stored_brushs_art_finds_its_object() { + let dir = Folder::new("brush-art"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let leaf = dir.file("leaf.png", &png(30, 20)); + let id = app.run("file.place", json!({"path": leaf, "at": [100, 100]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("brush.new", json!({"type": "scatter", "name": "Leaf", "ids": [id]})).unwrap(); + app.run("edit.clear", json!({"ids": [id]})).unwrap(); + let list = app.run("links.list", json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == "leaf.png").unwrap_or_else(|| panic!("{list}")).clone(); + assert_eq!(row["owner"]["kind"], "brush", "{list}"); + let row = row["id"].as_u64().unwrap(); + let doc = &app.session.active().unwrap().doc; + assert!(doc.mounted_art.is_empty(), "the brush's art is not set on the document"); + let found = super::links::stored_objects(doc, [row].into()); + assert_eq!(found.iter().map(|(id, _)| *id).collect::>(), [row]); + assert!(matches!(found[0].1.kind, vectorcraft_doc::NodeKind::Image(_)), "{:?}", found[0].1.kind); +} + #[test] fn an_empty_document_shows_how_to_add_images() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); 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/state.rs b/crates/ui-egui/src/state.rs index b28e4034a7..8c9956b474 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -838,6 +838,14 @@ pub struct UiState { /// Search All text does. #[serde(skip)] pub layers_filter: crate::panels::layers::Filter, + /// The Swatches, Graphic Styles and Symbols panels' views, chosen in their panel menus + /// (`ui.panelView`). They are not saved and last the session. + #[serde(skip)] + pub swatches_view: crate::panels::swatches::View, + #[serde(skip)] + pub graphic_styles_view: crate::panels::graphic_styles::View, + #[serde(skip)] + pub symbols_view: crate::panels::symbols::View, /// The Image Trace panel's Advanced section is open (as it was last left). #[serde(default = "yes")] pub image_trace_advanced: bool, @@ -1242,6 +1250,9 @@ impl Default for UiState { layers_panel: Default::default(), navigator_panel: Default::default(), layers_filter: Default::default(), + swatches_view: Default::default(), + graphic_styles_view: Default::default(), + symbols_view: Default::default(), image_trace_advanced: true, image_trace_preview: true, glyphs_preview: 0, 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..e6f3621e8e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -96,13 +96,13 @@ 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 | | `ui.wheel` | `{x, y, dy?, dx?, unit?: "line"\|"point", shift?, alt?, cmd?}` | a mouse wheel turn over screen point (x, y): `dy` notches up (+) or down, `dx` sideways. Over the canvas the wheel scrolls, Cmd-wheel (Ctrl on Windows and Linux) scrolls sideways and Alt-wheel (Option on the Mac) zooms about the pointer (with the `ctrlWheelScrollsSideways` preference off, Cmd-wheel zooms too); with the `zoomWithMouseWheel` preference the wheel and Alt-wheel zoom about the pointer, Shift-wheel scrolls up and down and Cmd-wheel (Ctrl on Windows and Linux) sideways. Over a focused numeric field (click it first) each notch steps its value as Up/Down do (Shift: ten, Cmd/Ctrl: a tenth) and the panel stays put; over anything else in a panel the wheel scrolls it. Over the canvas, the wheel preferences in `docs/mcp.md` change what these keys do | | `ui.set` | `{brightness?, panel?, rulers?, outline?, grid?, smartGuides?, boundingBox?, controlBar?, imageTracePreview?}` | `outline`: View › Outline for the active document only (each document has its own, a document opens in Preview, and `ui.inspect` shows it as `view.outline`; an error without a document). `imageTracePreview`: the Image Trace panel's Preview (`ui.inspect` shows it as `ui.image_trace_preview`) | -| `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value, action?}` or `{fields: [{field, value}…], action?}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`) other than its `__` fields, the `__` fields that are controls of the dialog (such as `__section` and `__allArtboards` in Save PDF, `__constrain` in Transform Each and the shape dialogs, and `__search` and `__category` in Preferences; Save PDF's and Print's `__savePresetAs`, the preset name, only while Save Preset… asks for it, since OK then saves a preset), `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass and Texturizer effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was. Any other `__` field, held or not, holds what the dialog's OK acts on (such as the `__command` and `__params` of a `confirm` or `command` dialog) or the dialog's own state: setting it is the error "the `` dialog cannot set protected field ``", and the dialog stays as it was. `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes. `action: "confirm"` or `"cancel"` on `ui.dialog.set` then confirms or cancels the same dialog in the same request, as `ui.dialog.confirm` and `ui.dialog.cancel` do, and the reply is `{dialog, result}`: the dialog after the fields were set and the reply to confirm (`null` for cancel); any other `action` is an error and no field changes | +| `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value, action?}` or `{fields: [{field, value}…], action?}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`) other than its `__` fields, the `__` fields that are controls of the dialog (such as `__section` and `__allArtboards` in Save PDF, `__constrain` in Transform Each and the shape dialogs, and `__search` and `__category` in Preferences; Save PDF's and Print's `__savePresetAs`, the preset name, only while Save Preset… asks for it, since OK then saves a preset), `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass, Texturizer and Rough Pastels effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was. Any other `__` field, held or not, holds what the dialog's OK acts on (such as the `__command` and `__params` of a `confirm` or `command` dialog) or the dialog's own state: setting it is the error "the `` dialog cannot set protected field ``", and the dialog stays as it was. `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes. `action: "confirm"` or `"cancel"` on `ui.dialog.set` then confirms or cancels the same dialog in the same request, as `ui.dialog.confirm` and `ui.dialog.cancel` do, and the reply is `{dialog, result}`: the dialog after the fields were set and the reply to confirm (`null` for cancel); any other `action` is an error and no field changes | | `ui.screenshot` | `{path?, data?}` | capture the window (PNG), written to `path`; `data: true` sends it back as `pngBase64` too. The inline PNG is capped at 64 MiB: with a `path` the file is still written and `pngBase64` is omitted when the image is larger, while a path-less `data: true` request fails if either the raw RGBA image or the encoded PNG exceeds the cap. Needs a presented frame: with the screen locked or the window minimized/covered it fails after ~8 s with an explanatory error | | `ui.render` | `{path?, scale?, artboard?, data?, traceViews?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first; `traceViews: true`: Image Trace objects draw in their View, as on the canvas, instead of their tracing result): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | | `ui.render` | `{path?, scale?, artboard?, data?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | @@ -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/effects-parity.md b/docs/effects-parity.md index 1457e35bc6..342a5171b6 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -27,7 +27,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( | Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own | | Rasterize | Rasterize… (as a live effect) | 1/1 | — | | Stylize | Drop Shadow, Feather, Inner Glow, Outer Glow, Round Corners, Scribble | 6/6 | Scribble Options' Settings presets | -| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists the document's own filters: VectorCraft ships no default filters. A filter that is the object's last effect is written to SVG as a `` element; otherwise SVG export draws the object as an image. A filter on a turned or skewed object in an imported SVG is left out with a warning | +| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists 14 default filters and then the document's own; the public page names no default set, so the set, names and values are VectorCraft's own, and a default is copied into the document when it is applied or edited. A filter that is the object's last effect is written to SVG as a `` element; otherwise SVG export draws the object as an image. A filter on a turned or skewed object in an imported SVG is left out with a warning | | Warp | Arc, Arc Lower, Arc Upper, Arch, Bulge, Shell Lower, Shell Upper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist | 15/15 | warp point editing in envelopes; each style bends the bounds as one Bézier patch (`version` 1), so Arc's edges are cubic curves close to concentric arcs; warps saved without a version keep the earlier map, where Arc is a circular arc in the object's own proportions (#1578) | Document Raster Effects Settings exists. When the 64 million pixel cap on an effect image lowers diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index bf52925f5c..06405fa620 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -245,7 +245,8 @@ private editing data. VectorCraft: group is tagged once and paints its marks with one fill and one stroke, which the graph keeps as that series' paint; Graph Data then edits it. Other graphs (pie and scatter graphs, graphs with designs or customizations, records of later versions) come in as plain groups, paths and type, with a note. Saving a graph to - `.ai`, in either form, writes its art without its data or settings, with a warning. + `.ai`, in either form, writes these records around its art when the reader above reads them back as the same graph, + so the file opens again with its data and settings; any other graph is written as its art, with a warning. Legacy `.ai` patterns in the version 7 form (a list of `@` and `&` layers, `_ &` for the tile's background) open as pattern swatches, with a fill's offset, scale, rotation, reflection and shear applied before its matrix. Legacy `.ai` linked images in @@ -290,8 +291,8 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | -| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability) | placing as layers and a PSD import options dialog missing; the embedded ICC profile's tags are 4-byte aligned (#1584) | -| PSB | open | yes (layers as layers, or the merged image) | no | | +| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability) | placing as layers and a PSD import options dialog missing; the embedded ICC profile's tags are 4-byte aligned (#1584) | +| PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | | | PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | | WebP | export (Export for Screens) | yes | yes (lossless only; lossy written lossless with a warning) | | | JPEG XL `.jxl` | — | yes (first frame; 16-bit and floating-point samples as 8 bits, alpha kept; CMYK refused) | no | decoded with jxl-oxide; the size is checked from the header before decoding; container Exif resolution sizes opened and placed images; tests in `crates/engine/src/cmd/fileio/tests_jxlread.rs` and `crates/engine/tests/import_fuzz.rs` | diff --git a/docs/gaps.md b/docs/gaps.md index 5e31ddee13..d0140731e2 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -522,6 +522,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G2 Photoshop-style raster effects and the Effect Gallery - **Done:** Effect › Texture › Texturizer › Load Texture… (stored grayscale `textureImage`, Loaded Texture in the Texture menu), matching Glass. +- **Done:** Effect › Artistic › Rough Pastels › Load Texture… ([raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html)): the image's gray levels are the paper surface, stored with the effect, listed as Loaded Texture in the Texture menu, with Scaling, Relief, Light Direction and Invert acting on it. - **Done:** the Effect Gallery's filter thumbnails and in-dialog preview ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)). Each thumbnail is an original landscape drawing passed through that filter at its defaults; the preview area shows the same drawing through the visible stack, or through the filter being browsed when the stack is empty. The canvas preview and the one-undo OK are unchanged (`dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`). All 57 Photoshop-style filters are in the catalogue. Measured in [effects-parity.md](effects-parity.md). - **Done:** the Effect Gallery (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step (`dialogs::effect_gallery::tests::stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`). diff --git a/docs/image-trace-adjustments.md b/docs/image-trace-adjustments.md index 52ac7a7848..22557771e2 100644 --- a/docs/image-trace-adjustments.md +++ b/docs/image-trace-adjustments.md @@ -18,6 +18,13 @@ its current location. Opening the controls does not add a document undo step. | Create | Fills / Strokes | Creates filled areas, stroked lines, or both. | | Ignore Color | Color picker | Leaves out the selected color (white by default). | +The built-in presets other than Auto Color and Flat Logo all use Paths 50, and so do their enhanced +versions. Among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White +Logo, Line Art and Outline, and 50 in the other eight. Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo, 10 in Low Fidelity Photo, 15 in 3 Colors, +6 Colors, 16 Colors and Shades of Gray, 20 in Sketched Art, Line Art and Outline, 25 in Default and +Black and White Logo, and 90 in Silhouettes (see +[image-trace-quality.md](image-trace-quality.md#preset-paths-corners-and-noise)). + Sliders apply on release, and their numeric fields can be edited directly. Each committed adjustment re-traces the selected object as one undo step and changes the preset to Custom. While dragging, the preset and Enhanced row stay in place until release so the @@ -142,7 +149,8 @@ further: the factor doubles until at most 150,000 remain or the working copy has most 16,384 pixels (at most six times). A trace that would make more than 8,000,000 anchor points (2,000,000 on the web) is refused to protect memory, with advice: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset. A trace keeps -about 90 bytes an anchor; a 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million. +about 90 bytes an anchor; a 4000 × 3000 photo at Limited 64 colors, Paths 90, Corners 25 and Noise 4 +makes about 1.9 million. **Tracing in the background.** On the desktop a trace runs on a thread of its own, so the window keeps answering while a photo or a large image is traced (#3098). Make, Make and Expand, the task bar's Image Trace and the panel's Trace and presets start it. The status bar says "Tracing the diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index 4765a2d779..dacf436036 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -82,6 +82,9 @@ gradient, texture, sensor noise): (The last two rows were measured without a limit; they are refused now.) The 4000 × 3000 High Fidelity Photo trace was 86,000 anchors under the old limit; a noisier scan of the same size would have been refused. At 8,000,000 anchors a trace keeps about 0.7 GB, with a peak of about 0.9 GB while tracing. +The preset rows were measured with the earlier preset values: High Fidelity Photo at Paths 90, Corners 25 +and Noise 4, Low Fidelity Photo at Paths 60, Noise 12 and 16 Colors at Paths 70, Corners 55 and Noise 10 +(see [Preset Paths, Corners and Noise](#preset-paths-corners-and-noise)). ## Collapsed loops keep few segments A small closed loop (or a piece that returns to its own junction) whose fit collapsed to a single cubic cannot stay as one, so it kept every positioned point as a straight segment. A looser Paths @@ -225,6 +228,47 @@ in a smooth area), `a_staircase_that_runs_on_from_a_smooth_area_into_an_edge_kee `a_staircase_of_mixed_one_pixel_and_longer_steps_is_one_slope_without_a_notch`, `a_run_of_two_steps_keeps_its_corners`, `a_junction_on_a_step_ends_the_staircase_there` and `a_step_whose_cracks_read_as_an_edge_ends_the_staircase_there`. +## Preset Paths, Corners and Noise +Every built-in preset other than Auto Color and Flat Logo traces at Paths 50. Corners and Noise are: + +| preset | Paths | Corners | Noise | before | +|:--|--:|--:|--:|:--| +| Default | 50 | 75 | 25 | unchanged | +| High Fidelity Photo | 50 | 50 | 5 | 90, 25, 4 | +| Low Fidelity Photo | 50 | 50 | 10 | 60, 50, 12 | +| 3 Colors | 50 | 50 | 15 | 60, 60, 20 | +| 6 Colors | 50 | 50 | 15 | 65, 60, 16 | +| 16 Colors | 50 | 50 | 15 | 70, 55, 10 | +| Shades of Gray | 50 | 50 | 15 | 60, 50, 10 | +| Black and White Logo | 50 | 75 | 25 | 95, 80, 8 | +| Sketched Art | 50 | 50 | 20 | 50, 50, 100 | +| Silhouettes | 50 | 50 | 90 | 40, 60, 30 | +| Line Art | 50 | 75 | 20 | 80, 70, 10 | +| Technical Drawing | 50 | 100 | 1 | 95, 90, 4 | +| Outline | 50 | 75 | 20 | 80, 70, 10 | + +The palettes, color counts, thresholds and other options of the presets did not change. The enhanced +versions of these presets use the same Paths, Corners and Noise. + +Measured with the harness below (section 1, each preset on the inputs it is meant for), before and after: +anchors fall in 10 of the 12 changed presets, for example 5,494 to 3,136 (High Fidelity Photo), 33 to 27 +(16 Colors), 27 to 14 (Black and White Logo) and 43 to 28 (Line Art); Silhouettes rises from 13 to 15 and +Sketched Art does not change. Outlines on flat art lie further from the true edge: off mean 0.100 to 0.123 +px (16 Colors), 0.101 to 0.119 (6 Colors), 0.104 to 0.129 (3 Colors), 0.064 to 0.092 (Black and White Logo) +and 0.056 to 0.074 (Line Art), and off max 1.00 to 1.16 px in 6 Colors and 16 Colors. Technical Drawing +leaves 1.4 specks (was 0.5), and Outline's stroked center lines lie 0.095 px off (was 0.086) with 2.7 +anchors a stroke (was 3.0). ΔE changes by 0.01 or less except Line Art and Outline (2.62 and 2.61 to 2.66 +and 2.67); edge ΔE rises in 8 of the 12, for example 4.79 to 5.25 (16 Colors), 3.98 to 4.46 (3 Colors) and 9.46 to 10.03 +(Black and White Logo). On synthetic shapes and photos of 300 to 4,000 px traced outside this harness, +High Fidelity Photo makes 41% fewer anchors and 16 Colors 20% fewer; the mean pixel difference of each +trace changes by −0.23 to +0.26 of a level; 16 Colors leaves 41 staircases of steps of 2 px or more where it left 40, High +Fidelity Photo 440 where it left 391, Low Fidelity Photo 96 where it left 77, Line Art 17 where it left 13, Outline 13 +where it left 10 and 3 Colors 14 where it left 12. On the same images Sketched Art makes 4,084 anchors where it made +3,936 and Silhouettes 1,608 where it made 1,578. The figures for these twelve presets and their enhanced versions in +the other sections of this file, and in the Image Trace entries of +[target-app-parity.md](target-app-parity.md), were measured at the earlier values. +Test: `presets_have_their_paths_corners_and_noise` in `crates/trace/src/tests.rs`. + ## A simpler contour walk `contour::trace_mask` follows each region's outline along the pixel cracks with the inside on the right. It used to build a table of outgoing directions for every pixel corner in a raster pass and 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 1fededbc4e..2fa44a769e 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -31,13 +31,13 @@ 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) | | Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | | Indonesian | `id` | 6,825 rows, 1,036 of them `@msg` and 47 `@msgplural` (counted 2026-11-14 on `main` at `676f0524cc`): the untranslated report lists 60 missing menu strings, 35 `tl!` literals and 13 undo labels for it; not in `COMPLETE_MESSAGES`, and checked against the same scanned messages it lacks 2,508; one plural form | most dialogs and tooltips; status and error messages partial | Latin | no | full | — (review) | -| Japanese | `ja` | 4,004 / 4,020 (99.6%) | all | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) | +| Japanese | `ja` | 4,004 / 4,020 (99.6%) | partial (3,562 `@msg` and 49 `@msgplural` rows, counted 2026-11-14: the untranslated report lists 98 messages without a Japanese row, 77 of which every complete-message language lacks; open #7116 and #7211 translate 35 of them) | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) | | German | `de` | 3,952 / 4,020 (98%; menus, literals and messages complete when counted) | all (3,563 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 52 missing messages for it, which open #7116, #7211 and #7378 translate) | Latin | contributor-written, not reviewed | full | — (review) | | Korean | `ko` | 4,870 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form | all (3,438 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 39 missing messages for it) | Hangul from an installed system font on the desktop (Apple SD Gothic Neo, Malgun Gothic, Noto Sans CJK KR…); the web build has no Korean UI font yet (craft-fonts); IME path exists | no (AI-drafted) | full | — (review; web font) | | Vietnamese | `vi` | 4,886 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form; 4,046 plain + 18 `@plural` + 28 contextual + 794 `@msg` | dialogs and tooltips all; messages partial (1,750 `@msg` and 49 `@msgplural` rows, counted 2026-11-14: the untranslated report lists 1,875 messages without a Vietnamese row, 53 of which open #7211, #7378, #7405 and #7434 translate) | Latin with Vietnamese diacritics (stacked marks attach in precomposed, decomposed and keyboard forms, #4491; glyph tests pass) | contributor is a Vietnamese speaker; AI-assisted draft, further native review welcome | full | — (review) | @@ -67,7 +67,7 @@ plus review. Native-speaker review is human work and isn't in the hours. | Bulgarian | `bg` | 5,245 rows, 763 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial | full; AI-drafted, native review pending | | Greek | `el` | 5,251 rows, 795 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | full; native review welcome | | Georgian | `ka` | 5,200 rows (counted 2026-10-21): menus, panels, dialogs, plurals (one count-neutral form) and messages, tested complete; reviewed by a native speaker | full | -| Turkish | `tr` | 5,558 rows, 880 of them `@msg` (counted 2026-10-28); 6 menu strings and the default swatch names still fall back to English | full | +| Turkish | `tr` | 9,175 rows, 3,446 of them `@msg` and 48 `@msgplural` (counted 2026-11-13); 41 messages, 62 menu strings, 26 `tl!` literals, 13 undo labels and the default swatch names still fall back to English | full | | Catalan | `ca` | 5,626 rows, 881 of them `@msg` (counted 2026-10-28): menus, `tl!` literals and messages complete when counted; one/other plurals; every `ca-*` locale resolves here | full; AI-drafted, native review welcome | Twenty-seven non-English catalogs in all (registry count, 2026-11-06). Illustrator, as its public documentation lists, ships around two dozen diff --git a/docs/mcp.md b/docs/mcp.md index f7606a5b11..9336ea35ca 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. | @@ -878,10 +878,14 @@ leaves room for a legend label's stored indents, spacing and leading. When a graph is drawn again, its plot moves and scales with any move or scale of the graph made since it was last drawn. The graph saves the bounds of its art other than type as `placedArt` (and the bounds of all of its art as -`placed`), and measures the move or scale on those. Changing the size, indents or spacing of the labels, moving a label -on its own and `type.createOutlines` on labels do not move or scale the plot. A graph opened from a `.ai` file saves -`placedArt` too. A graph saved without `placedArt`, or with a `placedArt` that has no width or height, is measured on -`placed`. +`placed`), and measures the move or scale on those. Changing the size or indents of the labels, moving a label on its +own, `type.createOutlines` on labels and `object.path.outlineStroke` on the graph's strokes do not move or scale the +plot. Outlined labels are no longer type: moving one of them on its own, like moving a swatch, an axis or a tick mark on +its own, can move or scale the plot at the next redraw. When all of a graph's art other than type has been deleted, or +the art measured has no width or no height, a redraw leaves the plot where it is and does not follow a move or scale of +the graph. A graph opened from a `.ai` file +saves `placedArt` too. A graph saved without `placedArt`, or with a `placedArt` that has no width or height, is +measured on `placed`. The `appearance.*` commands, `graphicStyle.apply` and `graphicStyle.redefine`, and the paint, stroke, gradient and transparency commands given an `item` (or the Appearance panel's active row) store a graph label's object rows for its @@ -1106,8 +1110,9 @@ way. `document.exportPdf {useArtboards: false}` writes that one page as well, an art's bounds is measured without what the plot leaves out: non-printing layers, objects at 0% opacity, placed images, gradient meshes whose every point is at 0% opacity, and paths without effects whose fills and strokes paint nothing. An image or a mesh with a Crop Marks effect, or with a Vector Halftone effect that makes dots, is measured. -Such objects in the art of a symbol that is not dynamic are left out of its instances too, and an instance whose -symbol holds nothing else is left out. +Such objects in the art of a symbol are left out of its instances too, and an instance whose symbol holds nothing +else is left out. In the art of a dynamic symbol, an object that an instance's fill, stroke or opacity makes +the plot draw is measured. A document whose only visible art is left out is refused, and Export As refuses an HP-GL plot of it before the save dialog. A PDF of that page, from either command, carries no Preserve Editing data; when Preserve Editing is on (as it is in VectorCraft Default), the export comes back with a warning that says so. A `.ai` export with @@ -1122,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 @@ -1730,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 @@ -3222,6 +3238,13 @@ already walks Image Trace. Short agent entry points: unchanged. No undo step is added when the symbols are already in order. The panel menu's Thumbnail View, Small List View and Large List View change only how the panel shows the symbols: thumbnails, or rows with a thumbnail and the name (smaller rows in Small List View). +- Panel views: `ui.panelView {panel, view?}` sets the view of the Swatches, Graphic Styles or Symbols panel, as the + view items of its panel menu (and the Swatches panel's list and thumbnail buttons) do. `panel` is `swatches`, + `graphicStyles` or `symbols`. The Swatches panel takes `smallThumb`, `mediumThumb` (the default), `largeThumb`, + `smallList` or `largeList`; the Graphic Styles and Symbols panels take `thumbnail` (the default), `smallList` or + `largeList`. Without `view` the command answers the current one. Each panel keeps its own view for the session, and + the document does not change. An unknown panel or view is an error, and then nothing changes. It answers + `{panel, view}`. - The Brushes panel menu's Select All Unused: `brush.unused` (a query) lists the brushes no stroke paints with, in library order, and the panel selects them. Strokes in the art (opacity masks included), symbols, graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do the @@ -3338,32 +3361,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 @@ -3666,8 +3705,20 @@ already walks Image Trace. Short agent entry points: `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog. - Live Paint: `livePaint.make`, `livePaint.merge`, `livePaint.fill {group?, point}`, `livePaint.strokeEdge`, `livePaint.info {group?|id?}`, `livePaint.release`, `livePaint.expand`, and `livePaint.gapOptions {ids?, detect?, size?, - color?, closeGaps?}` (Object › Live Paint › Gap Options). Make gives each covered face the fill of its front-most - covering source, including compound paths with shared curved boundaries. Expand keeps those face fills. + color?, closeGaps?}` (Object › Live Paint › Gap Options). Make gives each covered face the fill rows that draw of + its front-most covering source that has one, including compound paths with shared curved boundaries, and each edge + the stroke rows that draw of its source. A row draws when it is shown and has paint and an opacity above 0; a + stroke also needs a weight above 0, and a source whose opacity is 0 has no rows that draw. The rows keep their order + and settings (opacity, blending mode, effects, overprint, and a stroke's weight, caps, joins, dashes and alignment), + gradients keep their fit on the source, and the face or edge takes the source's opacity and blending mode. Where a + path is cut into several edges, each edge runs the way the path does, its dashes go on from where it starts along + the path (Align Dashes to Corners is turned off on it), the arrowheads stay only at the path's own ends, and a width + profile or brush stays only on an edge that runs the whole path. A gradient applied along a stroke starts again on + each cut edge, and an inside or outside stroke is drawn centered on an edge that is an open piece of a closed path. + When `livePaint.gapOptions` or `livePaint.merge` cuts an edge into pieces, each piece takes the edge's paint, with + its rows fitted to its part of the edge in the same way. A face or edge given no such row has one unpainted row. Rows that do not draw stay with the stored sources, which + `livePaint.release` returns unchanged. The source's object effects and the strokes' pen pressure are not carried. + Expand keeps those face fills. `livePaint.expand` keeps each face and edge that draws, with all its fill and stroke rows: it is shown, its opacity is above 0, and a fill or stroke row is shown, has paint and an opacity above 0 (a stroke also a weight above 0), whichever row is on top. A painted lower row under an unpainted top row keeps the part; a part whose only painted @@ -3740,6 +3791,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 @@ -3756,7 +3832,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. @@ -5133,8 +5210,12 @@ when its symbol or a symbol nested in its art holds an instance of itself, and w nest 32 deep in its art. PDF and EPS export and the SVG of an artboard leave out art outside the page or artboard, and Skip Blank Artboards skips an artboard with no art on it. For both, the box of an instance whose art holds brushed strokes grows by 16 times the widest stroke (at least 1 pt) of the objects in its art that have a brushed stroke, -plus 8 pt. The SVG of an artboard also keeps an object whose effects paint onto the artboard, and an object that holds -an instance when the effects in the symbol's art, or the instance's own, paint onto it. +plus 8 pt. PDF and EPS export and Skip Blank Artboards grow the box of an object with a visible, painted brushed stroke the +same way, by its own widest stroke, and the box of an object that holds one by the largest such room among them (of a +clip group, only its clipping path counts). Print with Ignore Artboards frames the page around the art with the same +room for brushed objects and for instances whose art holds brushed strokes. The SVG of an artboard also keeps an +object whose effects paint onto the artboard, and an object that holds an instance when the effects in the symbol's +art, or the instance's own, paint onto it. ## Expand @@ -5214,7 +5295,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 @@ -5252,8 +5333,19 @@ it. The native format keeps the events and the files. ## SVG filters -Effect › SVG Filters lists the document's SVG filters below Apply SVG Filter… and Import SVG Filter…; choosing one -applies it to the selection. `svgFilter.list {}` returns them as `filters: [{name, xml}]`. Each is one `` +Effect › SVG Filters lists the default SVG filters and then the document's other filters below Apply SVG Filter… and +Import SVG Filter…; choosing one applies it to the selection +([apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html)). +The 14 defaults are VectorCraft's own set, written with [SVG 1.1 filter primitives](https://www.w3.org/TR/SVG11/filters.html): +Soft Blur, Heavy Blur, Soft Shadow, Hard Shadow, Glow, Bevel, Emboss, Thicken, Thin, Rough Edges, Grain, Grayscale, +Invert and Hue Shift. Every document lists them, and a document holds none of them until one is applied or edited +there. `svgFilter.apply` with a default's name copies the default into the document in the same undo step (refused +when the document already holds 64 filters), and `svgFilter.define` with `replace` naming a default adds the edited +copy under that name (code equal to the default's adds nothing). The document's filter of a default's name is then +listed in the default's place. `svgFilter.delete` refuses a default the document holds no copy of; deleting the copy +lists the default again, and applying the default again makes the effects that still name it draw with it. +`svgFilter.list {}` returns the document's filters as `filters: [{name, xml}]` and the defaults as +`defaults: [{name, xml, inDocument}]`. Each filter is one `` element whose `id` is its name, with 1 to 64 primitives and at most 64 KB of XML (`feTurbulence` octaves up to 10, `feConvolveMatrix` kernels up to 9 cells a side, `feMorphology` radii and `kernelUnitLength` up to 100 and `stdDeviation` up to 500 user units, elements nested at most 16 deep). It holds only filter primitives, @@ -5264,8 +5356,9 @@ a filter after the others, or with `replace` replaces the filter of that name, w filter has is refused, and the same filter again records no undo step. `svgFilter.delete {name}` removes one, and `svgFilter.import {path?|svg?}` adds the `` elements of an SVG file (at most 16 MB, not SVGZ, the first 256 filters) or of SVG text, leaving out the names the document already has and the filters `svgFilter.define` would refuse (`{added, skipped}`). Each change is one undo -step. `svgFilter.apply {name, ids?|id?, item?}` applies one as the live effect `svg.filter`, as `effect.apply` does, -in one undo step. The effect (`{name, xml, scale, origin}`) names the document's filter: editing the filter changes +step. `svgFilter.apply {name, ids?|id?, item?, index?}` applies one as the live effect `svg.filter`, as `effect.apply` does, +in one undo step; with `index` it puts the filter in the place of the applied `svg.filter` effect at that index of +`item`, as `effect.setParams` does, and an index that is not an applied SVG filter is an error. The effect (`{name, xml, scale, origin}`) names the document's filter: editing the filter changes what every object that uses it draws, in the edit's one undo step, and an application after an edit takes the edited filter. Deleting a filter that objects use leaves their effects in place, still named, drawing nothing (their `xml` empty) until a filter of that name is defined or imported again. A pasted effect that names one of the document's @@ -5625,6 +5718,25 @@ used, as a transform's does. {"name":"run_command","arguments":{"command":"object.transformEach","params":{"scaleH":50,"scaleV":50,"strokes":false}}} ``` +## Scale and Reflect on a turned bounding box + +`object.scale` and `object.reflect` with a named axis act along the selection's bounding box: after a rotation, `sx` +stretches along the box's own width and `sy` along its height, and `"vertical"` and `"horizontal"` are the box's own +axes, until Object › Transform › Reset Bounding Box squares the box to the page. Both take `basis?: "box"|"page"`: +`"box"` is the default, and `"page"` acts along the page's axes. Any other `basis` is an error, and nothing changes. +`origin` is still a page point, and a numeric `axis` is still a line on the page at that angle. Selections whose +objects stand at different angles, and anchors selected with Direct Selection, use the page's axes; with `copy` or +with `objects: false`, the whole objects or their pattern tiles transform, along the box. The journal entry +records the `basis` used, so a recorded action replays in the same frame; a saved step without `basis` (an action or +journal entry recorded before it) plays along the page's axes, as it did when it was recorded. `object.transformAgain` repeats the transform's page matrix, also after Reset Bounding Box. The Scale +and Reflect dialogs, the Transform and Properties panels' flips, the Scale tool and the Reflect tool's default axis +and Shift steps follow the box the same way; a Reflect axis drawn with the tool is the line drawn on the page. + +```json +{"name":"run_command","arguments":{"command":"object.scale","params":{"sx":200,"sy":100}}} +{"name":"run_command","arguments":{"command":"object.reflect","params":{"axis":"vertical","basis":"page"}}} +``` + ## Free Distort on a turned bounding box `object.distort` maps the corners of `from` (TL, TR, BR, BL) onto `corners`, which are page coordinates. With @@ -5834,7 +5946,8 @@ commands send `to: "key"` while the selection has a key, else `"artboard"` for o anchor points, else the Align To choice. The Distribute commands send `to: "key"` while the selection has a key, else the Align To choice, and while there is a key object or a key guide they send the panel's Distribute Spacing value as `spacing`. Edit › Keyboard Shortcuts lists them under Align, with no default shortcut, and -`shortcuts.set {id, shortcut}` gives one a shortcut. +`shortcuts.set {id, shortcut}` gives one a shortcut. The Object › Distribute menu lists the eight Distribute commands, +and each item runs its command. With the Artboard tool chosen, the same buttons and UI commands, and the Control bar's Align and Distribute buttons, run `artboard.align`, `artboard.distribute` and `artboard.distributeSpacing` on the artboards the tool has selected. @@ -6205,8 +6318,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. @@ -6514,7 +6628,8 @@ report warn about it). Commands take and return lengths in points (the distances of `object.path.offsetPath`, `object.path.simplify`, `object.path.splitIntoGrid` and `text.setStyle` `size`/`leading` also take a string with a unit, `"5 mm"`). A length string takes the same arithmetic as the desktop app's fields, where `%` is a share of the value before it: -`"200mm*50%"` is 100 mm and `"50pt+25%"` is 62.5 pt. The units +`"200mm*50%"` is 100 mm and `"50pt+25%"` is 62.5 pt. A length string with more than 128 `+ - * /` signs is not read +as a length. The units only change what the UI shows and how it reads typed numbers. Preferences ▸ Units has four: General (rulers, positions and sizes, the Info panel, dialog distances, canvas measurement labels), Stroke (weights, dashes), Type (font size, leading, baseline shift) and East Asian Type (no field uses it yet). General is the active document's units @@ -7235,6 +7350,14 @@ is mixed with middle gray by its alpha. {"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"distort.glass","params":{"distortion":10,"textureImage":{"path":"/tmp/texture.png"}}}}} ``` +Texturizer (`texture.texturizer`) and Rough Pastels (`artistic.roughPastels`) take `params.textureImage` the same +way, as the surface that Scaling, Relief, Light Direction and Invert act on. With `texture: "loaded"` and no stored +texture they draw Canvas. + +```json +{"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"artistic.roughPastels","params":{"relief":12,"textureImage":{"path":"/tmp/texture.png"}}}}} +``` + ## Linked images A placed image linked to its file (`file.place {path}`, Link on) records the file's absolute path, its size, @@ -7557,6 +7680,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"}}} @@ -7912,10 +8041,11 @@ and is missing from the picture" once for all such images. `document.open` and `file.place` read `.emf` and `.wmf` (placeable or not) into one artboard, the picture's frame, and one layer: paths with their fills and strokes (pens become strokes with caps, joins and dashes), clipping groups, -images and point type in the font the file names. Records VectorCraft doesn't read (EMF+ drawing among them) are -skipped with one warning. `clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard -for `edit.paste`; the app pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's -clipboard service offers it (the Windows desktop service doesn't read metafiles yet). +images and point type in the font the file names. An EMF that draws with EMF+ records is read from them. Hatched and +pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning. +`clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard for `edit.paste`; the app +pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's clipboard service offers it +(the Windows desktop service doesn't read metafiles yet). ```json {"name":"export","arguments":{"path":"/tmp/logo.emf"}} @@ -8198,6 +8328,16 @@ flattened picture every PSD file carries: Bitmap, Grayscale, Duotone, Indexed, R A document with transparency keeps it. `file.place {path}` links the file like any image (`links.update` reads it again when it changes); Multichannel files are refused. +A PSD or PSB file that names a clipping path (the saved path its clipping path resource names, in the +[published PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)) places, and +opens as its merged image (`layers: false`, a file with no layers, or a file whose layers can't be read), inside a clip group whose clipping +path is that path, under the even-odd rule, so the image shows only inside it. The clipping path is an ordinary path +that can be edited or released. `file.place` answers `image`, the id of the image in the clip group. The +[import options help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) +says that a file imported as one flattened image keeps the document's clipping path when it has one. `links.update` +and `links.relink` read the file's pixels again and leave the clip group and its clipping path as they are. Files that name no clipping path, or name a path +they don't have, come in as a plain image. + `document.open` converts a PSD or PSB file's layers to objects. In [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html), the option that converts layers to objects keeps as much of the layer structure as it can, merges the layers of a @@ -9015,7 +9155,8 @@ Options). Warichu characters are set at `warichuScale` percent of their size (10 `warichuLines` lines (a whole number from 1 to 6, default 2) inside their line: one above the other in horizontal type and side by side across the column in vertical type, the first line above or to the right. `warichuGap` is the space between the lines in points (0 to 100, default 0, document points as `baselineShift`). The stack is centered across the -line on the center of the line's ideographic em box, and the line keeps the height of the characters' own size. +line on the center of the line's ideographic em box, and the line keeps the height of the characters' own size, or +more when the stack needs it: the line's ascent and descent take in the characters of the outer lines. A stretch of warichu characters is one block that takes the settings of its first character; a character with other settings, another size or the other kind of leading (Auto or a number) starts a new one, and a tab, a forced line break or a tate-chu-yoko character ends it. In vertical type a character marked `tateChuYoko` as well is set as tate-chu-yoko at its own size, and two or three digits @@ -9062,7 +9203,11 @@ menus, and a value typed past 1000 sets 1000; Reset Panel sets both to 0. Charac in Advanced Character Formats. With Fractional Widths off or System Layout on, each side is set in whole points, and justification keeps that width. Live SVG text places each character the space moves, and type on a path with Insert Aki is written as outlines. An SVG saved without Preserve Editing (`preserveEditing`) reopens without the -Insert Aki values; save it with Preserve Editing to keep them editable. +Insert Aki values; save it with Preserve Editing to keep them editable. An `.ai` file's text document keeps both +values, and opening the file reads them back. The stored values are read in thousandths of an em and a negative +value opens as 0; these are VectorCraft's own rules. When a legacy `.ai` save writes type as text, it writes type with +Insert Aki without the values and warns that they are left out. With `outlineText: true` it writes the type as outlines, +which keep the space Insert Aki adds, and does not warn that the values are left out. ```json {"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"akiRight":500}}} @@ -9090,6 +9235,27 @@ as outlines. {"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"tsume":50}}} ``` +## East Asian glyph forms + +`text.setFormat` and `text.setRangeStyle {glyphForm}` set the East Asian glyph form the characters are drawn in +([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): `"traditional"`, +`"expert"`, `"jis04"`, `"jis90"`, `"jis78"`, `"jis83"`, `"fullWidth"`, `"halfWidth"`, `"thirdWidth"` or +`"quarterWidth"`, which draw them with the font's OpenType feature `trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, +`fwid`, `hwid`, `twid` or `qwid` ([feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)), +or `"default"`, the font's default glyphs. A character holds one form at a time, so setting one replaces another. The +text keeps its characters, and a character the font has no glyph of that form for keeps its own. Runs that differ only +in their form are shaped as one piece of text. The form is saved only when it is not `"default"`, character styles +carry it, PDF draws the glyphs the canvas draws, and live SVG text writes it in `font-feature-settings`. Another value +is refused with `` `glyphForm` must be one of "traditional", … ``. One undo step, and a `text.setFormat` call that +gives the form the characters already have records none. With Show East Asian Options on, the Glyphs panel menu lists +the ten forms and Revert To Default Forms: a form is checked when every selected character has it, choosing it again +does nothing, and it is disabled when none of the faces that draw the selected text, fallback faces included, has a +feature for it. + +```json +{"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"glyphForm":"jis78"}}} +``` + ## Composite Fonts A composite font sets each class of character in a font of its own @@ -9435,6 +9601,24 @@ not kerned). Off by default and saved only when on. One undo step. {"name":"run_command","arguments":{"command":"text.setFormat","params":{"proportionalMetrics":true}}} ``` +## H or V Style and Roman Italics + +With Show East Asian Options on, the OpenType panel menu has H or V Style and Roman Italics +([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)). They are the character +feature tags `hkna` and `ital` of `text.setStyle` and `text.setRangeStyle {features, featureChanges}` +([feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). `hkna` draws kana with the +forms the font makes for horizontal type, and in vertical type the shaper applies `vkna`, the forms for vertical type, +in its place. `ital` draws half-width alphanumerics with the font's italic forms. A font without the feature draws the +characters unchanged. Both are on or off only: `hkna=2` and `ital=0` are refused as unknown features, and `vkna` is +not a tag of its own. A menu item is checked when every character the panel acts on has it; choosing it turns the +feature on for all of them, or off when it is checked, each character keeping its other features, in one undo step. +Reset OpenType Features turns both off. Character styles carry them, and Character Style Options › OpenType Features +has an on, off or unset switch for each. Live SVG text writes them in `font-feature-settings`. + +```json +{"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":6,"featureChanges":["hkna","ital"]}}} +``` + ## Variable fonts `text.setFormat {fontAxes: {"wght": 650}}` (the selected type, or `ids`) and `text.setRangeStyle {id, start, end, 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 e828b4537d..e00e5bd43d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -258,8 +258,8 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on guide and blend spine rows (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | @@ -616,6 +616,7 @@ since 2026-10-01. - **Tab stops in `.ai`/EPS type and right-aligned lines with tabs (#6147):** type from the text document keeps its paragraphs' tab stops (key 30: positions and left, center, right and decimal alignments; leaders aren't read), at most 1,024 a paragraph and 2^20 a story, past which the default stops apply with a warning. In right-aligned area type, the text before a line's last tab sits at its stops, measured from the left edge, and the text after it (none when the tab ends the line, with its hyphen when the line is hyphenated) against the right edge; centred and justified lines, point type and right-to-left paragraphs are aligned as a whole as before. Evidence: `ate::tests::a_paragraph_keeps_its_tab_stops`, `ate::tests::a_story_s_tab_stops_are_bounded`, `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`, `import_fuzz::text_frames_with_hostile_paragraph_attributes_never_panic`. Scores unchanged. - **`.ai`/EPS graphic styles that paint with a named gradient:** a graphic style library's style (or a file's listed style) whose fill, or the fill or stroke of a style of one paint, paints with one of the file's gradients by name loads with that gradient at the style's angle, fitted to the bounds of each object it is applied to (VectorCraft's own placement; the style stores only the gradient's name and angle). A style naming a gradient the file doesn't define, or painting with a pattern, is still left out. Evidence: `fileio::tests_aiimport::graphic_styles_in_a_ai_library_that_paint_with_a_named_gradient_load_with_it`, `style::tests::a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on`. Scores unchanged. - **`.ai`/EPS type laid out closer to the file's page (#6137):** type from the text document keeps auto leading as auto, each line taking the paragraph's Auto Leading share (key 7) of the largest type on it ([Line and character spacing](https://helpx.adobe.com/illustrator/using/line-character-spacing.html)); the paragraph's hyphenation options (keys 10 to 15) are read; area type of one frame whose last lines the file sets, but which don't fit here, may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines and no more than the file has (`vectorcraft_text::fit_source_lines`), with a warning when it does: the frame can stay as it is, or show only some of them; and a line a soft return ends is justified as a wrapped line is, a paragraph's last line keeping its alignment. Evidence: `ate::tests::auto_leading_follows_the_size_of_each_line`, `ate::tests::a_paragraph_keeps_its_auto_leading`, `ate::tests::a_paragraph_keeps_its_hyphenation_options`, `ate::tests::the_last_lines_the_file_sets_in_its_frame_show`, `tests::fit_source_lines_keeps_the_last_lines_the_source_sets`, `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores unchanged. +- **Graphs saved to `.ai` keep their data and settings:** a grouped column, stacked column, line or area graph is written to a `.ai` file, in either form, with the records the `.ai` reader reads (`crates/eps/src/import/ai/read/graph.rs`, #7311): `%_Gs`, its plot, type, settings, axes and table, its series' groups each tagged `Go`, and `%_GS` ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), §17 and appendix A). The file opens again with the same live graph. A graph with settings the reader doesn't keep, graph designs, label formatting, more than 10,000 categories or 256 series, or art the reader doesn't attach a graph to is written as its art, with a warning. `crates/eps/src/legacy_ai/tests.rs` and `crates/eps/src/ai_editing/tests.rs` write and read back each kind of graph; `a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns` checks every graph type the graph tools draw. Scores unchanged. - **Selected Grid Repeat handles (#2691):** `tools/src/repeat_grid.rs` tests place the handles outside the grid at zoom 0.5, 1 and 4, preview rows, columns and spacing, leave no undo step for a drag that ends where it began, and give bounding-box handles priority; a headless canvas regression drags the row handle two tiles down in a zoomed view (3 → 5 rows, the source unchanged, one Undo back) and the column-spacing slider. Scores and hours unchanged. - **Selected Mirror Repeat handles:** a headless canvas regression creates the default mirror repeat and drags its Top bounding-box handle where the axis crosses it; the repeat grows vertically while its width stays fixed. Existing mirror-axis checks cover center movement and end-handle hit priority. The focused UI mirror tests pass. Scores and hours unchanged. - **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). The effects listed after it in that fill's or stroke's list keep their own distances and apply to the transformed art and to each copy, as an object's later effects do after the object's Transform effect: a Drop Shadow after it keeps its offset, an Offset Path after it offsets by its own distance, and an SVG filter after it keeps its scale and the origin of its user space. With Transform Objects off, the effects before it keep their distances too. Before, Scale Strokes & Effects scaled a fill's or stroke's later effects by the mean scale, so existing documents with such effects draw differently. Effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)); how the two options treat the effects after a fill's or stroke's own Transform effect is VectorCraft's own rule, following that order (effects `tests::rasterfollow::a_fills_own_transform_leaves_the_shadow_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_offset_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_svg_filter_after_it`, `tests::transformfx::a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects`; engine `plugins::a_transform_after_a_painted_fill_effect_leaves_the_later_shadow_on_every_paint`). Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged. @@ -743,6 +744,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 +808,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 +819,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 +912,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. @@ -922,9 +926,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). - - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,421 `@msg` rows: a row for each status and error message the untranslated report (`untranslated_report`) finds in the sources, except 38. The report lists those 38 for Japanese: the 36 composite font errors that open #7211 translates, `select a path` (open #7214) and the justification order error (open #7116). The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. + - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`). - The status bar translates the errors a script's `File` and `Folder` objects, `vc.run`, `$.evalFile`, the `$` object's properties and functions, `alert`, `confirm` and `prompt`, `vc.document` and `vc.log` raise, the limits a run can pass, and the errors of Drop Script Engine, and the line for a run that fails (a syntax error, a thrown error, a limit, a stop or an internal error, with the script's name, the line and column, the included file it is in and the files left written), in every language that translates every message. The script's name, paths, numbers, command ids and the text a script throws itself are shown as they are. A failure with no line and column, such as an error in code `eval` compiled, is shown with one colon after the script's name (`an_error_without_a_place_names_the_script_and_kind`). A message template that names a value twice matches only when both places hold the same text, so the line for a failed run is not taken for the message inside it (`a_repeated_placeholder_matches_the_same_text`). The untranslated-strings report also lists the messages the script host's `fail`, `value` and `over` helpers take and the errors the script interpreter throws, and a constant's text comes from the file or crate that declares it, so the Scripts menu's headers are not listed as messages (`script_errors_are_translated`, `script_host_errors_are_translated`, `message_scan_reads_script_interpreter_errors`, `message_scan_reads_constants_of_the_file_and_its_crate`, `message_scan_skips_test_modules_with_any_test_cfg`). + - The Turkish catalog (`crates/ui-egui/src/i18n/tr.tsv`) has an `@msg` row for all but 41 of the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,446 `@msg` rows in all. The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - The Hungarian catalog (`crates/ui-egui/src/i18n/hu.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,444 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 40 Hungarian messages: the composite font, justification order and connect end errors that open #7211, #7116 and #7330 translate, and two messages that no catalog has a row for. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - The Dutch catalog (`crates/ui-egui/src/i18n/nl.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,447 `@msg` rows in all. The report lists 41 Dutch messages: the composite font errors, the justification spacing error and the `connect` end error, which open #7211, #7116 and #7330 translate, and three unknown-parameter and range errors (``unknown parameter `{within}{key}`; {why}``, ``unknown parameter `{within}settings.{format}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`), which open #7353 rewrites so that a catalog row can match them. The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - The Traditional Chinese catalog (`crates/ui-egui/src/i18n/zh-hant.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,438 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 40 Traditional Chinese messages: open #7211, #7116 and #7330 add the rows for 38 of them, and the other 2 have no row in any catalog. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. @@ -949,7 +954,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Align New Objects to Pixel Grid (`document.setup {alignNewObjectsToPixelGrid}`, a checkbox in New Document's Advanced Options and a checked item in the Transform panel menu) gives every path and compound path drawn in the document, the paths of a new grid or flare included, the pixel-aligned property, snapped in the step that draws it; it is on in the Mobile and Web presets and off in the others, saved presets and Recent keep it, and the document saves it. Type, images and groups do not take it, and art already in the document, pasted, duplicated or placed keeps its own property (VectorCraft's own rules) ([Pixel-aligned property](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html); `tests::pixelalign::align_new_objects_makes_new_paths_pixel_aligned`, `align_new_objects_reaches_grids_flares_and_add_on_shapes`, `align_new_objects_is_saved_and_read_back`, `tests::newdoc::align_new_objects_to_pixel_grid_follows_the_preset`, `panels::transform::tests::align_new_objects_menu_item_toggles_the_active_document`, `dialogs::new_document::tests::align_new_objects_checkbox_follows_the_preset_and_reaches_the_document`). - Break Link to Symbol and Object › Expand give a symbol instance's art the instance's own bounding box: after Reset Bounding Box the art stands square to the page, an object turned inside the symbol keeps its angle relative to the instance's box, a group added for the instance's opacity takes the instance's box, and the clip groups of 9-slice art take the angle of their cell. Compound shapes and Pathfinder receive an instance's art with the same angles (VectorCraft's own behavior; `bboxrotate::reset_bounding_box_then_expand_symbol_instance`, `reset_bounding_box_then_expand_keeps_the_angles_inside_the_symbol`, `expanding_a_faded_symbol_instance_gives_its_group_the_instance_box`, `expanding_a_reflected_symbol_instance_keeps_its_box`, `symbol_nine_slice::break_link_turns_the_cells_of_a_sliced_instance_with_its_box`, effects `outline_object_turns_an_instances_art_with_its_box`). - Object › Transform › Reset Bounding Box squares the box of every object inside the selected ones as well: the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. Ungroup and the release commands then bring back boxes square to the page (VectorCraft's own behavior; `bboxrotate::reset_bounding_box_squares_the_objects_inside_a_group`, `reset_bounding_box_squares_the_turned_members_of_a_square_group`, `reset_bounding_box_then_release_clipping_mask` and the other `reset_bounding_box_then_*` tests, `reset_bounding_box_leaves_the_art_of_an_unlinked_opacity_mask`). - - After a rotation the Free Transform tool shows and drags the same turned bounding box as the Selection tool: its handles, their cursors and its rotate zone sit on the selection's own sides, a handle scales along those sides from the opposite handle ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html)), Cmd/Ctrl on a side handle shears along that side, and Perspective Distort and Free Distort start from the turned box's corners (`object.distort` takes `angle` with `from`). The Scale and Reflect tools, their dialogs and commands, and the Transform panel's flips keep the page's axes (VectorCraft's own rule; `bboxrotate::free_transform_handles_turn_with_the_object_and_scale_along_its_axes`, `free_transform_shears_along_the_turned_side`, `free_transform_distort_starts_from_the_turned_box`, `xform::distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle`, tools `xform::free::tests::the_box_and_its_handles_turn_with_the_selection`). + - After a rotation the Free Transform tool shows and drags the same turned bounding box as the Selection tool: its handles, their cursors and its rotate zone sit on the selection's own sides, a handle scales along those sides from the opposite handle ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html)), Cmd/Ctrl on a side handle shears along that side, and Perspective Distort and Free Distort start from the turned box's corners (`object.distort` takes `angle` with `from`) (`bboxrotate::free_transform_handles_turn_with_the_object_and_scale_along_its_axes`, `free_transform_shears_along_the_turned_side`, `free_transform_distort_starts_from_the_turned_box`, `xform::distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle`, tools `xform::free::tests::the_box_and_its_handles_turn_with_the_selection`). + - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - Native macOS menu bar, vector tool cursors, a ⌘K command palette, middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). @@ -985,7 +991,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Symbols panel context menu** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): right-clicking a symbol in thumbnail view or list view displays a context menu with Place Symbol Instance (passes view center or artboard center), Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of this symbol), and Select All Instances. Right-clicking an unselected symbol selects it first (`symbol.setCurrent`). Tests: `panels::symbols::tests::right_click_context_menu_in_symbols_panel_runs_actions`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`. + - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. `ui.panelView` sets the view of the Symbols panel, and of the Swatches and Graphic Styles panels, as their panel menus do. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`, `panels::symbols::tests::panel_view_sets_the_view_of_each_panel`. - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). @@ -1136,6 +1142,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. With Size set to Pressure the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). + The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The outline of a drag with a round Eraser tip is drawn whole each frame. - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). @@ -1380,6 +1387,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Glyphs panel's Alternates for Current Selection (#5514) applies the OpenType feature that draws the glyph to the selected character alone, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Alternates For Current Selection in the Show menu; double-click the glyph to replace the selected character). One deliberate difference from a literal reading: the text keeps the Unicode character and gains a character-style feature with a value (`salt=2`, `ss03`; `text.setRangeStyle {featureChanges}`) instead of taking an unencoded glyph in its place. The grid lists the alternates of the glyph the shaper makes for the character in its word (a medial letter shows its medial variants; the default glyph comes first and the current glyph is highlighted); a variant no supported feature draws there stays enabled as a replacement glyph (`text.setGlyphAlternate`, including positional alternates), and its tooltip says it may not join its neighbors; the default glyph takes the character's alternate features off again. Runs that differ only in their OpenType features are shaped as one piece of text, each run's features over its own characters, so the letters of an Arabic word keep their joining forms. Show › Entire Font also lists the glyphs no character maps, with the font's name for them (or `gid N`) and the feature that gives them. It applies the selected letter's contextual alternates the same way, and applies a glyph no feature reaches whose name does not belong to another letter as a glyph choice; other glyphs are dimmed with the reason. An Arabic presentation form picked there inserts its base letter. These rules are VectorCraft's own. Tests: `tests::glyph_alternates` in the text crate (a fixture font; Kufi Murabba PIIIX when it is installed), `panels::glyphs::tests` (including positional glyph choices, unlisted glyph name ownership, apply and Undo), `tests::textedit::feature_values_are_set_replaced_and_saved`. With a Type tool and exactly one character selected, the canvas shows that character's alternate glyphs in a row beside it, and a click on one replaces the character's glyph, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes ("Replace a character with on-canvas alternate glyphs"). The row shows at most five alternates, and an arrow at its end opens the Glyphs panel on Alternates for Current Selection when the character has more, as the [reference manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479) describes. A click runs the command the panel's double-click runs, as one undo step, so a letter of an Arabic word keeps the word joined. These rules are VectorCraft's own: the row leaves out the glyph the character is drawn with and puts the default glyph first for a character drawn with an alternate; it stands under a character of horizontal type and on the right of a character of vertical type, or on the other side when the canvas ends there or the Contextual Task Bar is there; Preferences › Type › Show Character Alternates (`showCharacterAlternates`, on by default) turns it off. Tests: `canvas::alternates_bar::tests`, `tests::prefs::show_character_alternates_preference_is_on_by_default_and_saved`. The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu shows the first selected character's font's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft design choice. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). + With Show East Asian Options on, the OpenType panel menu has H or V Style and Roman Italics, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes. H or V Style sets the feature tag `hkna`, which draws kana with the forms the font makes for horizontal type, and with `vkna` for vertical type in vertical type; Roman Italics sets `ital`, the font's italic forms of half-width alphanumerics ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). Each is checked when every selected character has it and turns it on or off for all of them in one undo step; character styles carry both in OpenType Features. Tests: `panels::opentype::tests::kana_style_and_roman_italics_turn_on_and_off`, `features::tests::kana_style_and_roman_italics_are_kept_and_shaped`. `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). @@ -1447,9 +1455,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Paragraph panel's Mojikumi Set lists the five predefined sets the help page names (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku and YakumonoZenkaku), then Line-end Punctuation Half Width, and `text.setFormat {mojikumi}` takes each of them. YakumonoHankaku sets every bracket, comma and full stop half width and takes a quarter em off each side of a middle dot; GyomatsuYakumonoHankaku keeps punctuation full width inside a line, sets an opening bracket flush at a line's start and a closing mark half width at its end, and takes the quarter em after a middle dot off at a line's end; GyomatsuYakumonoZenkaku keeps punctuation full width and adds a quarter em between Japanese and Latin text; YakumonoZenkaku sets characters as None does. These widths are VectorCraft's own rules, from the help page's one-line description of each set. Both composers and vertical type measure each line as it is set, the sets save with the document and paragraph styles, and a `.ai` save reports the new sets as left out (`crates/text/src/tests/vertical.rs`, `crates/ui-egui/src/panels/paragraph/tests.rs`). Scores and estimates are unchanged. Interface text in characters the interface's fonts lack, drawn in a bundled Japanese, Georgian or Devanagari face or in an installed font that covers them, sits on the baseline of the Latin text beside it, monospace text included (#5816; `crates/ui-egui/src/ui_fonts.rs`, `crates/ui-egui/src/theme.rs`). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. + The Glyphs panel menu (with the East Asian options) offers Traditional, Expert, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); each draws the selected characters with the font's OpenType feature for that form (`trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, `fwid`, `hwid`, `twid`, `qwid`), one form at a time, and a form none of the faces that draw the selected text has a feature for is disabled. `text.setFormat` and `text.setRangeStyle {glyphForm}` set it; the native file, character styles, the canvas, PDF and SVG (`font-feature-settings`) keep it (`tests::typo::glyph_forms_draw_the_fonts_east_asian_forms`, `typecmd::area_tests::glyph_form_is_one_character_attribute_saved_only_when_set`, `panels::glyphs` tests). Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, on a vertical path it moves toward the path's start and to the path's left, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past the coordinate limit (`MAX_COORD`) either way opens with the nearer end, as the type's own offsets do; an offset within it stays as saved. Character panel › Insert Aki Left and Insert Aki Right (with the East Asian options; `text.setFormat` or `text.setRangeStyle {akiLeft, akiRight}`, thousandths of an em from 0 to 1000, 0 by default) add space before and after each selected character, measured as tracking is, and kept as set through justification ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); before and after follow the reading order in vertical and right-to-left type, character styles carry both values (Character Style Options › Advanced Character Formats edits them), and a file holding a value outside the range opens with the nearer end. + Insert Aki Left and Right open from an `.ai` file's text document (read in thousandths of an em, the unit the [scripting reference](https://web.archive.org/web/20160410092022/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/pdf/illustrator/pdfs/illustrator_scripting_reference_applescript.pdf#page=90) gives `aki left` and `aki right`; VectorCraft's own rule for the stored value) from the run, its character style, the styles that one is based on, `[Normal Character Style]` and the document's defaults in that order. A negative value or one that is not a number opens as 0, and a value past 1000 opens as 1000. An `.ai` save writes each run's nonzero values in the form that reader reads. A legacy `.ai` save writes type with Insert Aki as text without it and reports that it is left out; type it writes as outlines keeps the space. Character panel › Tsume (with the East Asian options; `text.setFormat` or `text.setRangeStyle {tsume}`) narrows the space around each selected character ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); by VectorCraft's own rule the value is a percentage from 0 to 100, 0 by default, of the blank space on each side of the character's ink that horizontal type takes away without changing the glyph's shape, with tracking, kerning and Insert Aki added after it. Character styles carry it (Character Style Options › Advanced Character Formats edits it), and a file holding a value outside the range opens with the nearer end. The Character panel's All Caps, Underline and Strikethrough buttons and its menu's All Caps, Underline, Strikethrough, Proportional Metrics, Tate-chu-yoko and No Break show off while only some of the selected characters have the attribute, and choosing one then turns it on for all of them, as `type.underline` (Cmd+Shift+U) does for underlining; the Character Alignment and Digits submenus check no item while the selected characters differ. `text.setFormat` refuses a value that is not true or false for its on/off attributes, as `text.setRangeStyle` does. - **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `` and PDF soft masks. The constant alpha soft mask that PDF and `.ai` export draw a CMYK page with transparency through is white, so applications that read every soft mask by its luminosity show the page too (#1359, part of #1286). @@ -1491,6 +1501,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, cut-out edges:** in Color and Grayscale, a semi-transparent pixel (alpha 128 to 254) on the edge of a cut-out image, beside a pixel that is less than half opaque, traces as a color of the fully opaque pixels within two pixels of it when its own color is that color or a darker shade of it, and of several such colors, as the one the most of those pixels have (art across a transparent gap does not count), so a darkened edge tone no longer traces as a 1 px sliver of an unrelated palette color, while a thin semi-transparent outline of another color keeps its own; code-drawn cut-out, opaque-edge and thin-outline tests in `crates/trace`. - **Image Trace, cut-out edges choose no color:** in Color and Grayscale, the edge pixels that take the color beside them, and the semi-transparent pixels within two pixels of them whose color is also the opaque art's color blended with the background, do not count when the palette or the grays are chosen, so the edge of a cut-out image no longer adds a second shade of a color to Auto Color's palette, takes away an outline's color or takes a gray of its own; beside those pixels, the anti-aliasing between a color and an outline drawn along the edge is no color of Auto Color's own when it lies at least 0.45 of the way from the color to the outline and at least one in 32 of its pixels has both around it (edge pixels that choose no color count when they lie within 2.5 Oklab × 100 of the nearest of those colors): its pixels trace as the outline, so a thin outline stays a ring of few pieces, except beside an outline along the edge with a region of 8 pixels of its own, where each takes the nearer of the two, so a wider outline is not drawn wider; an outline over the edge in the color of other art traces in that color, while an opaque rim drawn along the edge keeps its color, also where other art reaches it; a thin semi-transparent outline of another color still counts, and opaque images trace as before; code-drawn cut-out outline, rim, opaque line and grayscale edge tests in `crates/trace`. - **Image Trace, blurred edges:** in Color with a Limited palette of at most 16 colors (3 Colors, 6 Colors, 16 Colors) and in Grayscale with at most 16 grays (Shades of Gray), by VectorCraft's own rule (RGB distances, 0 to 255 a channel), a blend pixel with no unblended pixel of its own color within 4 pixels takes the nearer side of the pair of colors within 8 pixels that it is best a blend of, of the 8 colors within 8 pixels nearest to its color, when that pair explains it twice as well as its own color, or when it lies between the two and off the line between them by less than 0.15 of their distance apart; it keeps its color when it is one of the pair. Grayscale compares lightness. The in-between tones of an edge blurred over several pixels no longer trace as rings around it. High Fidelity Photo, Low Fidelity Photo and Black and White trace as before, and so do Automatic, Full Tone and Document Library palettes. Noisy and textured images settle more of their pixels. By `crates/trace/tests/quality` (256 px variants), 16 Colors on blurred flat art went from 9.0 paths to 3.0, 158 anchors to 34 and 0.239 px off to 0.069, and 6 Colors from 6.0 paths to 3.0 and 0.226 px off to 0.071; askew shapes take up to 11 px more area in colors the art does not have, and with 16 Colors the largest distance from a thin line's outline to the trace goes from 23.5 px to 45.3 (see [quality notes](image-trace-quality.md#blurred-edges)). Code-drawn blurred-disc and grayscale ramp tests in `crates/trace`. +- **Image Trace, preset Paths, Corners and Noise:** every built-in preset but Auto Color and Flat Logo traces at Paths 50, and so do their enhanced versions; among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline and 50 in the other eight, and Noise is 1 to 90 px by preset. Palettes and color counts are unchanged. Figures for these presets in the other Image Trace entries were measured at the earlier values. By `crates/trace/tests/quality`, High Fidelity Photo goes from 5,494 anchors to 3,136 and Black and White Logo from 27 to 14, while 16 Colors on flat art goes from 0.100 px off to 0.123 (see [quality notes](image-trace-quality.md#preset-paths-corners-and-noise)). Test `presets_have_their_paths_corners_and_noise` in `crates/trace`. - **Image Trace, simpler contour walk:** `contour::trace_mask` works out each turn from the pixels during the walk, with no precomputed direction table and no assertion; identical loops to the previous walk on every 4 × 4 mask (see [quality notes](image-trace-quality.md#a-simpler-contour-walk)). - **Image Trace, measured:** `crates/trace/tests/quality` traces drawings made from known vector art with every preset and [`image-trace-quality.md`](image-trace-quality.md) records the numbers against the baseline. Black and White, Grayscale and Color place each edge by the blend of the pixels across it (to a fraction of a pixel on anti-aliased and blurred images; hard-edged images are read as staircases) and fit outlines as Flat Logo does. *Measured* on each preset's own inputs, all sizes and variants: Default's outlines went from 0.31 px off on average to 0.09 (largest 1.51 to 1.02), Black and White Logo's from 0.27 to 0.06 with 0.3 kinks per trace where it had 15, and the gaps between abutting paths from 64 px to 22. On clean curved shapes Black and White Logo is 0.02 px off (the open tracer measured beside it: 0.20). The palette is made of the picture's own colours (blends along edges take none of it, colours that noise made of one colour merge, a blend pixel goes to one of the two colours it lies between; #1504): 16 Colors on flat art, all variants, went from 70 paths to 4.2 and from 5.1 px off to 0.13, with no path left in a colour the art doesn't have (5.9 before). Photos are smoothed within their tones before they are quantised and stacked layers go by lightness (#1516): High Fidelity Photo went from 3,653 paths to 121 with its colour error down from 2.30 to 1.75, and a 16 megapixel photo-like image is traced in 3.5 s where 4 megapixels were refused. Since then, by the same harness: outlines are cut at their junctions and each shared piece is fitted once (#1535: gaps and overlaps between abutting paths 22 to 50 px of area down to under 2); layers are traced within the box of their pixels and a few at a time (#1546: a 16 megapixel photo 3.9 GB to 0.9 GB); black and white are read against the image's own black and the paper near each edge (#1563, for thin lines in blurred and scanned art); Ignore Color and the Auto Color and Outline presets (#1574); Snap Curves To Lines levels lines within 2.5 degrees of level or upright (#1593, the angle our choice); Create: Strokes puts centre lines in the middle of their ink and makes them as wide as it (#1595: Outline 0.295 to 0.052 px from the true centre line, 18.4 to 2.7 anchors a stroke); sharp corners whose pixel is mostly outside the shape stay corners (#1609: Default 69% to 76% kept). Three options, each off unless asked for as the legacy presets have them: Shapes (#1609: 57 to 62% of plain circles, ellipses, rectangles and regular polygons come out as live shapes, rounded rectangles rarely), Auto Grouping (#1618: paths grouped with what lies inside them, the same picture) and Gradients (#1627: linear gradients traced as one gradient-filled path; on gradient inputs 6 Colors' colour error 2.12 to 0.62 with 6.4 to 3.4 paths, none found in flat art). Snap Curves To Lines moves no end of a line by more than 1.6 px, so long lines a degree or two off stay as the image has them (#1647: Technical Drawing's largest distance 4.21 px to 1.46). Flat Logo takes the tones a scan's uneven paper makes of one colour for one colour (#1657: on scans 470 paths and 21 px off to 8.5 paths and 0.09 px). Shapes finds rounded rectangles and shapes in aliased, blurred and scanned art (#1845: 57 to 62% of the plain shapes up to 98 to 100%, no false shape but one line 2 px wide). Stroked lines get square caps where their ink is cut square, and a wide end that turned towards a corner goes back on its line (#1846: Outline's largest distance 2.94 px to 0.88, 14 anchors to 10). Each of the 14 documented presets has an enhanced version with Auto Grouping and, in all but High Fidelity Photo, Shapes (#1847), measured beside its preset: equal or better within 0.005 px and 1% of edge ΔE on every preset's own inputs (Default 0.091 to 0.083 px); Auto Grouping keeps traced order in its groups, which removed a light seam along the counters of letters. Gradients grows a gradient over the pixels noise and soft rims took off it (#1848: blurred and noisy linear gradients 3 to 11 paths beside the gradient down to 0.5 with 6 Colors, 24 to 56 down to 0.5 to 1.5 with High Fidelity Photo). Silhouettes is 0.52 px off because its threshold is 200 (0.11 px at 128). Still weak, by the same numbers: rounded rectangles and other line-and-arc outlines take 12 to 16 anchors (the fitter does not split lines from arcs), blurred and scanned polygons lose corners, hairlines under half a pixel are lost to the threshold, aliased art is about 0.25 px off, a scan's uneven paper splits into tones when more colours are asked for than the art has, stroke junctions stay at their skeleton pixels, a three-stop gradient in a small or scanned disc is not found, radial gradients stay bands (a draft, #1849, traces them; the documented option is for linear ones, so it waits for a decision), near-regular polygons a few dozen pixels across are made regular with Shapes (up to 0.5 px off), and aliased stroked lines are 0.8 px off at worst. - **Gradient mesh from an image:** Object › Create Gradient Mesh (`object.mesh.create`) on an embedded image makes a mesh of 1 to 50 rows and columns over the picture's rectangle, placed with the image's transform; each point takes the alpha-weighted average colour and the opacity of the area around it, and Appearance and Highlight apply. A linked image is refused with a message to embed it (#1676). Scores and hours unchanged. @@ -1521,7 +1532,9 @@ 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}`. + Object › Live Paint › Make turns the selected paths into a Live Paint group of faces and edges ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)). As VectorCraft's own rule, each face takes every fill row that draws (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge every stroke row that draws (also with a weight above 0) of its source, in order with their opacity, blending mode, effects and stroke settings, with gradients kept at their fit on the source and with the source's opacity and blending mode. Where a path is cut into several edges, each edge's dashes go on from where it starts along the path with the lengths set (dashes aligned to corners and path ends are not fitted to the cut edges), the arrowheads stay at the path's own ends, and a width profile or brush stays only on an edge that runs the whole path; each edge runs the way its path does, a gradient applied along a stroke starts again on each cut edge, and an inside or outside stroke is drawn centered on an open piece of a closed path. A painted lower row under an unpainted or hidden top row is kept, a hidden top row does not become visible, and a source in front whose fill does not draw does not hide the fill behind it. Rows that do not draw stay with the stored sources, which Release returns unchanged; the source's object effects are not carried. Evidence: `tests::build::{live_paint_make_keeps_lower_drawn_stroke_rows, live_paint_make_fits_dashes_and_arrowheads_to_each_edge, live_paint_make_starts_a_closed_edge_where_its_path_starts, live_paint_make_keeps_the_direction_of_gradient_strokes, live_paint_make_keeps_all_drawn_fill_rows_and_attributes, live_paint_make_uses_frontmost_source_with_drawn_fill}`. 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}`. `livePaint.info` lists every fill and stroke row of each face and edge, bottom first, with its paint, opacity, visibility, weight for a stroke, and whether it draws by the rule above, beside the top fill, stroke and weight it already reported. Evidence: `tests::build::live_paint_info_lists_every_appearance_row`. @@ -1640,7 +1653,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document state; a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document view state saved in native files (#1968); a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export, and type used as a clipping path keeps them when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. + The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export. When the clipping path has a fill or stroke of its own, the geometry effects of those fills and strokes apply after the group's geometry effects instead. Type used as a clipping path keeps its geometry effects when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. + Clicks, Select Behind, the Unlock submenu, marquees and the Enclosing Lasso inside a clip group or a clipping layer follow that area too: the clipped art is found where the effects moved it and not where they took it away. The clipping path itself is still found by its own outline and anchors. A hidden member of a group used as a clipping path does not clip, and a geometry effect on it does not change where clicks land. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. Direct Selection picks and outlines an object of a dynamic symbol's art by the same rules. `doc::hit::tests` and the engine's `tests::clip` cover it. - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports. @@ -1757,7 +1771,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` opened from its editing data opens its Objects on Path groups live, with their path, their objects in order along it, Pivot and Rotate, and their art where the file draws it; a group whose spacing has been dragged, or with options an Objects on Path group doesn't hold, opens as a plain group (`crates/eps/src/import/ai/tests.rs`). `.ai` symbol definitions and placed instances open as live symbols, in the Symbols panel's order; an instance of a symbol that isn't read, or whose appearance differs from its symbol's, comes in as the page draws it (`crates/eps/src/import/ai/tests.rs`). In a `.ai` opened from its editing data, an object in a pattern's art or a brush's art with an art style VectorCraft reads opens as itself with its effects live, as an object on a layer does, and an object in a pattern's art keeps the id of a graphic style in the file's list (`crates/eps/src/import/ai/tests.rs`). - A graph in a `.ai` whose records have the shape and values the published version 7 specification gives ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), printed pp. 109–112 and 146–158) opens as a live grouped column, stacked column, line or area graph with its saved art, table, axes and settings, and Graph Data edits it ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/add-graph-data.html)); other graphs keep their art as plain objects with a note, and saving a graph to `.ai` warns that its data and settings aren't written (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/cmd/graph/tests.rs`). + A graph in a `.ai` whose records have the shape and values the published version 7 specification gives ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), printed pp. 109–112 and 146–158) opens as a live grouped column, stacked column, line or area graph with its saved art, table, axes and settings, and Graph Data edits it ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/add-graph-data.html)); other graphs keep their art as plain objects with a note. Saving to `.ai` writes these records for a graph that reads back as the same graph, and warns that any other graph's data and settings aren't written (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/cmd/graph/tests.rs`). Blends and envelopes in the definitions of a `.ai`'s symbols, patterns and brushes' art count against the same per-file limits on blend layout and envelope checks as the layers' art, so a file with many definitions does not get those limits again for each one (`crates/eps/src/import/ai/read/directives.rs`). A `.ai` or EPS whose editing data has brushes opens with the file's Calligraphic, Scatter, Art and Bristle brushes in the Brushes panel in place of the default ones, in the file's order: the Calligraphic size, roundness and angle with their variation, the Scatter size, spacing, scatter and rotation, the Bristle settings, and the Scatter and Art brushes' art (Art brushes in the older and newer forms of their objects). A brush library `.ai` (brushes and no layers) opens from its PDF part with its brushes, so Other Library lists them. An Art brush in None or Tints keeps that colorization, and one in the newer form also keeps its fixed width, Flip Along and Flip Across, and Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with its guides ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193). Pattern brushes and brushes that can't be read are left out with a note. Paths with a Calligraphic brush, and paths with an Art brush in the newer form that bends art of solid-filled paths with those options, open as the path with the brush on its stroke, except paths whose brush scales its art proportionately. Paths with an Art brush in the older form, and other brushed paths, still come in as their drawn look (part of #372 and #637; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, a path or type object with Offset Path, Outline Object or Outline Stroke on the whole object opens as itself with those effects live, in their order and shown or hidden; on a fill or stroke of type they stay on that fill or stroke. Offset Path keeps its Offset, Joins and Miter Limit, and Outline Stroke takes its width from the stroke. An Offset Path with a setting missing, out of range or not read keeps the drawn art, as does a path with a Path effect on one fill or stroke (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). @@ -1807,17 +1821,20 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), and adjustment layers, layer effects, knockouts and vector masks aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels. There is no PSD import options dialog yet (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` keep the clip group, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`). - PCX files (`.pcx`) open and place, from the ZSoft PCX Technical Reference Manual: 1 bit in the header palette's first two colors (black and white when the version has no palette or both colors are the same), 1 bit in two to four planes and 4 bits with up to 16 colors from the header's palette (the EGA colors for versions 0 and 3), 2 bits in the CGA colors that the header's CGA palette settings pick (background, color burst, palette and intensity), 8 bits with the 256-color palette after the image data (gray levels without one) and 24-bit color in three planes, run-length encoded. The header's HDpi and VDpi size the image. A file of another depth or plane count, one cut short, and one whose pixels as RGBA pass the pixel allowance are refused with a message before its pixels are decoded. Open and Place recognize a PCX file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a PCX file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_pcxread.rs`). - Pixar picture files (`.pxr`) open, place and paste, from "The Format of Stored Pictures" in the Pixar Image Computer manuals: any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded with all four packet kinds and block ends, in tiles of any size (pixels of border tiles past the picture are dropped). R alone is gray, a missing color channel is 0 and a missing A opaque; 12-bit samples are clamped to 0.0 to 1.0; color matted to black becomes straight color; a null tile is transparent when the picture has A and black otherwise. The offsets aren't read, and the image takes the default resolution. Version 2 headers read like version 0. A file cut short, one with a tile whose writing wasn't finished, one with header values or packets the format doesn't define, and one whose pixels as RGBA pass the pixel allowance are refused with a message. Every reader recognizes a Pixar file by its magic number. Tested on synthetic files only (`crates/engine/src/cmd/fileio/tests_pxrread.rs`). - JPEG 2000 JP2 and raw codestream images open and place from `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c` and `.jpc`. Each axis uses the valid display resolution (`resd`), else the valid capture resolution (`resc`), whichever box comes first ([ITU-T T.800](https://www.itu.int/rec/T-REC-T.800/en), I.5.3.7.2); an axis with none uses 72 ppi. Multiple codestreams, JPX composition or layers, and unsupported color spaces are refused with a message. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_jp2read.rs`). - HEIC and HEIF images open and place from `.heic` and `.heif`, as the [supported file formats](https://helpx.adobe.com/illustrator/kb/supported-file-formats-illustrator.html) list High Efficiency Image under both Open and Place (and [Fix HEIF file import errors on Windows](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/fix-heif-file-import-errors-on-windows.html) covers both ways of bringing HEIF files in): HEVC-coded single pictures and grids of tiles, 8 to 10 bits, with an alpha image, decoded by heic-rs in the engine's default `heif` feature. The container's rotation, mirror and crop are applied. Without an `nclx` box, the HEVC stream's video signal type gives the samples' matrix and range. An RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; the EXIF resolution tags size the image, or 72 ppi. Image sequences, other codings and grids of cropped tiles are refused with a message, and so is every HEIF file in a build without the feature. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_heifread.rs`). - HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`, or a name no other format reads when the file starts with plotter instructions) open and place as paths on one layer, the artboard round the art: each line drawn with the pen down is a stroked path in its pen's color and width, line types become dash patterns, circles, arcs, wedges and Bézier curves are curves, filled and edged rectangles, wedges and polygons (polygon mode) are filled or stroked paths, and encoded polylines, scaling points, user units and rotation are read. Labels, symbol mode's symbols, raster images and hatching aren't drawn and are listed in the warnings (`crates/cad/src/hpgl/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - PICT pictures (`.pct`, `.pic`, and `.pict` as VectorCraft's own name) open and place, as [the help page](https://helpx.adobe.com/archive/illustrator/illustrator-cs5-5-troubleshooting.pdf) lists Macintosh PICT under both opening and placing: versions 1 and 2, with or without the file's 512 bytes of application data, read by the opcodes of Apple's [Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html). Lines, rectangles, rounded rectangles, ovals, arcs, polygons and regions become paths in their pen and pattern colors, text becomes point type in the font the picture names, bitmaps, pixel maps and QuickTime JPEG images become images, and the clip region clips what follows it; File › Place places the picture as one group clipped to its frame. Inverted shapes, other transfer modes and other QuickTime formats come back as warnings, and a picture cut short keeps what came before it (`crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs`). + - EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`). - Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - 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. @@ -1859,7 +1876,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. @@ -1871,6 +1888,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. @@ -1962,7 +1980,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Raster-effect resolution in PDF:** when the 64 million pixel cap on an effect image renders an object's raster effects below the document's raster effects resolution, PDF export warns once per object with the requested and the lowest achieved ppi (`crates/engine/src/tests/pdfraster.rs`). - **Rasterize effect:** Effect › Rasterize… (`rasterize`) draws an object as an image of square pixels at its own resolution or the document's raster effects resolution, with Object › Rasterize's color model, background, anti-aliasing, clipping mask and room around the object, while its paths stay editable. Expand Appearance and PDF and SVG export of an object whose only raster effect is Rasterize give the image Object › Rasterize gives (`crates/engine/src/tests/rastersettings.rs`, `crates/render/src/tests/rasterize.rs`). Behavior reference: [How to save artwork in Illustrator](https://helpx.adobe.com/illustrator/using/saving-artwork.html), [Work with effects](https://helpx.adobe.com/illustrator/using/effects.html). - **Rasterize colour models:** Object › Rasterize with the Grayscale colour model makes a grayscale image (a gray PNG, with alpha over a transparent background), and with Bitmap a 1-bit image (a TIFF), or a black-and-white gray PNG with alpha over a transparent background; `image.info` and the Control bar say Grayscale, and a fill color colorizes the image, in RGB and CMYK documents (#6969). Expand Appearance and PDF export of a Rasterize effect make the same images. Regression coverage: `rasterize_to_grayscale_or_bitmap_makes_a_grayscale_image` (`crates/engine/src/tests/rastersettings.rs`) and `gray_and_bilevel_images_store_gray` (`crates/render/src/encode/tests.rs`). Scores and estimates unchanged. -- **SVG filters:** Effect › SVG Filters lists the document's own SVG filters below Apply SVG Filter… and Import SVG Filter…, and choosing one applies it to the selection as a live effect in one undo step (`svgFilter.apply`). Apply SVG Filter applies the selected filter, New and Edit open its code, and Delete and Import… remove filters or add those of an SVG file (`svgFilter.define`, `svgFilter.delete`, `svgFilter.import`). VectorCraft ships no default filters. The canvas, raster export and PDF draw the filter at the Document Raster Effects resolution; SVG export writes it as a `` element when it is the object's last effect and otherwise draws the object as an image; SVG import keeps filters the other live effects can't express as this effect instead of leaving them out; the native format keeps the filters (`crates/engine/src/tests/svgfilter.rs`, `crates/effects/src/svg_filter/tests.rs`). Behavior reference: [Apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html), [CS5 help, Apply SVG effects](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=402), [SVG 1.1 Filter Effects](https://www.w3.org/TR/SVG11/filters.html). +- **SVG filters:** Effect › SVG Filters lists 14 default SVG filters and then the document's own below Apply SVG Filter… and Import SVG Filter…, and choosing one applies it to the selection as a live effect in one undo step (`svgFilter.apply`). Apply SVG Filter applies the selected filter, New and Edit open its code, and Delete and Import… remove filters or add those of an SVG file (`svgFilter.define`, `svgFilter.delete`, `svgFilter.import`). The public page names no default set: the defaults (Soft Blur to Hue Shift, `crates/effects/src/svg_filter/defaults.rs`) are VectorCraft's own, written with SVG 1.1 primitives. A default is copied into the document when it is applied or edited, and Delete does not remove a default. The canvas, raster export and PDF draw the filter at the Document Raster Effects resolution; SVG export writes it as a `` element when it is the object's last effect and otherwise draws the object as an image; SVG import keeps filters the other live effects can't express as this effect instead of leaving them out; the native format keeps the filters (`crates/engine/src/tests/svgfilter.rs`, `crates/effects/src/svg_filter/tests.rs`). Behavior reference: [Apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html), [CS5 help, Apply SVG effects](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=402), [SVG 1.1 Filter Effects](https://www.w3.org/TR/SVG11/filters.html). - **Pattern tiles:** the renderer keeps a tile of each pattern for each scale it rasterizes the pattern at, until the tiles fill the tile cache's budget, and then drops the least recently used tiles first. Objects that show one pattern at different scales, such as a pattern scaled to 25% with Transform Pattern Tiles next to the same pattern at 100%, draw from tiles kept between frames. @@ -1992,6 +2010,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`). @@ -2003,6 +2023,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Moving objects with raster effects (#1257):** during a drag or a dialog's preview, an object whose content only moved draws its cached drop shadows, outer glows and filtered content (Gaussian Blur, Feather and the Photoshop-style filters) from the rasters of an earlier frame at the nearest whole pixel, without running the effects again. The renderer first draws the moved content where the old content lies in its raster and compares the pixels. De-Interlace runs again. The frame after the drag runs the effects again and draws what a fresh renderer draws; on the desktop, the canvas renders that frame on the render worker. `texture_drag_perf` times a drag's frames and the frame after it. - **Glass's Load Texture:** Effect › Distort › Glass… has a Load Texture… button that reads a PNG, JPEG, GIF, WebP, TIFF, BMP, Targa, PSD, PSB, PCX, Pixar, JPEG 2000, HEIC/HEIF or JPEG XL file and adds Loaded Texture to the Texture menu (`textureImage`: `{path}` or `{name?, dataBase64}`, stored in the effect and saved with the document as a grayscale PNG in base64). The texture lies one image pixel per point at Scaling 100%, centered on the object and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray. Scaling and Invert act on it as on the built-in textures. A Glass saved without `textureImage` draws and saves as before. +- **Rough Pastels' Load Texture:** Effect › Artistic › Rough Pastels… has the same Load Texture… button, and its Texture and Light Direction controls are menus. The loaded image's gray levels are the paper surface (Loaded Texture in the Texture menu, `textureImage` stored with the effect), and Scaling, Relief, Light Direction and Invert act on it as on Brick, Burlap, Canvas and Sandstone (`pixel::tests::rough_pastels_draws_a_loaded_texture_as_its_surface`, `rough_pastels_loads_a_texture_saves_it_and_draws_it`). - **Bounded effect length inputs (#4638):** Effect dialog fields with defined length ranges (such as Crystallize Cell Size 3..300 pt) clamp immediately on commit and reject invalid inputs visibly with an accent highlight without reverting to sub-minimum values. - **Color Halftone in raster pixels (#3260):** Max Radius is 4–127 px of the Document Raster Effects resolution, as public documentation gives it, shown in px whatever the document units; documents from before open with their radii in points converted (document version 3), and a file saved for an older app version holds them in points again. @@ -2071,6 +2092,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Later effects on every fill or stroke a painted effect returns (G17):** when a painted effect on a fill or stroke returns several fills or strokes, a later live-effect plug-in in that fill's or stroke's stack, and a later geometry effect on strokes, runs once on each of them in paint order, given its own paint and its own `_context.item` among them. Each run's pieces replace only that fill or stroke. A run that fails, is refused, is deferred or would pass the effects' budget leaves only its own fill or stroke as it was, and the others still run; a deferred stage is listed once, at the source fill's or stroke's place. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/effects/src/tests/painted.rs`. Scores and hours unchanged. - **Painted pieces with brushed strokes are culled and measured by their brush art (G17):** a piece that keeps the object's brushed stroke draws the brush along the piece's own path at the piece's stroke width. Culling leaves VectorCraft's usual room for brush art (16 × the stroke width + 8 pt) past each piece, from the piece's width rather than the object's, and so does culling of a group, layer, symbol instance, blend, envelope or repeat that holds the object. A group or layer also leaves that room for each brushed path among its members, painted or not. Object › Rasterize takes the brush art drawn along each piece and leaves out the object's own brush art, which is not drawn. Pieces without a brush are culled as before. Regressions: `crates/render/src/tests/paintedbrush.rs`. Scores and hours unchanged. +- **Brushed paths just off the page are exported and printed:** PDF and EPS export keep a path or compound path whose brush art reaches the page while the path lies just off it, alone or in a group, by leaving the canvas's room for brush art (16 × the widest stroke + 8 pt, VectorCraft's own value) past its box. Skip Blank Artboards keeps an artboard such brush art reaches, and Print with Ignore Artboards frames the page with that room around brushed paths and around instances whose art holds brushed strokes. A clip group leaves room only for its clipping path. Art without brushed strokes is written as before. Regressions: `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/print.rs`, `crates/eps/src/tests.rs`. Scores and hours unchanged. - **Live-effect plug-ins while a document opens (G17):** the live-effect plug-in runs of a document's first view on screen share a 2,000 ms budget (VectorCraft's own value). A stage left out for time, or one that times out, fails, has no plug-in or meets Safe Mode, draws its input unchanged and is deferred; the status bar says how many, `effect.deferredStatus` lists them with their object, effect and reason, and Effect › Refresh Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget. Each document has its own budget, an edit runs the stages it changes, and exports, Expand Appearance and commands run every stage under the 5 s limit of each run. The web build times the budget and each run's limit with the page's `performance.now()`. Regressions: `crates/plugins/src/deferred.rs`, `crates/plugins/src/effect.rs`, `crates/plugins/src/host.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Refreshing many deferred effects (G17):** Refresh Deferred Effects (`effect.refreshDeferred`) looks up the objects asked for, the stages reached, the objects drawn whole and the inputs that ran in hash sets, so its time no longer grows with the square of the number of deferred stages. The deferred records are indexed by stage and input, so asking whether a stage stays deferred, replacing a stage's records when it runs, and ending a drawing after the first view look at that stage's records only, and the records keep the order they were made in. With 40,000 deferred stages, one refresh in a release build took 38 ms, down from 1,036 ms, and asking about and running each stage once took 16 ms, down from 2,287 ms (wall-clock time on a computer busy with other builds, one run each). Regressions: `crates/plugins/src/deferred.rs`. Scores and hours unchanged. - **Refresh Deferred Effects by object (G17):** `effect.refreshDeferred` takes `ids`, or `id` for one, naming objects in the layers or in the art of a symbol, pattern, brush or opacity mask, the objects `effect.deferredStatus` lists; an object without a deferred stage adds nothing to the counts, and an id of no object in the document is an error. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. diff --git a/docs/type-parity.md b/docs/type-parity.md index 64c6bcf798..fa76290e94 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -34,6 +34,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Preserve font sizes while scaling a group | missing | Separate enhancement; scaling still scales text with the other artwork. | | OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges and Alternates for Current Selection, the selected character's alternate glyphs from the font's `GSUB` table. A double-click applies the OpenType feature that draws a variant to that character alone, or uses a glyph choice when no supported feature draws it; see the Glyphs panel row below for Entire Font and the joining limits. The glyph-cell pop-up of alternates is not there yet | | Glyphs panel: alternates as OpenType feature values, unencoded glyphs | done | #5514, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Show › Alternates For Current Selection; replace the selected character by double-clicking the glyph). A character-style feature takes a value (`"salt=2"`, the font's alternate number; `ss01`–`ss20`, `swsh`, `titl` and `aalt` too) in `features` and `featureChanges`, in SVG `font-feature-settings` (`"salt" 2`) and in native files as the plain string. Show › Entire Font applies an unencoded glyph the same way when it is an alternate of the selected character in its word, applies one no feature reaches (`A.salt` in a font with no `salt`) to the selected character as a glyph choice (it may not join), and dims the others with the reason in the tooltip (e.g. `yehfarsi.fina.alt2 belongs to ی (U+06CC) at the end of a word; your selection is ي (U+064A)`); an Arabic presentation form picked there inserts its letter so the word joins. Runs that differ only in their features shape as one piece of text, each run's features over its own characters, so a variant on one letter of an Arabic word keeps its neighbours' initial, medial and final forms and the letters still touch. The panel lists the alternates of the glyph the shaper makes for the selected character in its word (a medial letter shows medial variants), and a double-click applies the OpenType feature that draws the variant (`salt=N` or `ssNN`) to that character alone, in one undo step (`text.setRangeStyle`); a variant no feature reaches falls back to a replacement glyph (`text.setGlyphAlternate`), which its tooltip says may not join. Show › Entire Font also lists the glyphs no character maps, with their name or `gid N` and the feature that gives them. The text crate reads each face's `GSUB` once (alternate sets, single substitutions, the feature that reaches a glyph). Not done: alternates reached through contextual or ligature lookups, and features of the font that the style has no tag for (`cv01`–`cv99`, `hist`). Evidence: `tests::glyph_alternates` in the text crate (a fixture font with a medial teh at `salt=1` to `3`, the neighbours' forms, no gap; Kufi Murabba PIIIX when it is installed), `features::tests::feature_values_are_parsed_validated_and_shaped`, `tests::textedit::feature_values_are_set_replaced_and_saved`, the `panels::glyphs` tests. | +| OpenType panel menu: H or V Style, Roman Italics | done | With Show East Asian Options, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes: H or V Style is the character feature `hkna` (kana in the font's horizontal forms, shaped as `vkna` in vertical type) and Roman Italics is `ital` (the font's italic half-width alphanumerics), set with `text.setStyle` / `text.setRangeStyle {features, featureChanges}`, on or off only, and in Character Style Options › OpenType Features ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). | | Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice). | | Missing glyphs set in an installed font made for their script (Thai, Lao, Khmer, Myanmar first; then any font that has them) | done | Thai: Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai, TLWG | | Full font-name matching (OpenType name ID 4) | done | #1258: loaded/cataloged faces and Missing Fonts searches; localized names and variable default faces; Windows font-service QA pending | @@ -69,6 +70,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: East Asian Type units (Q, Ha) | done | Preferences › Units › East Asian Type (`unitsAsianType`, Points by default) offers every unit and Q and Ha, a quarter of a millimetre each ([Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/): 0.709 pt per Q; [InDesign's unit notation](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html): `q`, `h`). The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` | | CJK: manual tate-chu-yoko | done | Character panel menu › Tate-chu-yoko (`text.setFormat` / `text.setRangeStyle {tateChuYoko}`), with Show East Asian Options: marked characters stand side by side across one em of a vertical column, squeezed to the em when wider; two or three half-width digits still do so without the mark; horizontal type keeps the mark and does not move them. Tate-chu-yoko Settings… (`ui.tateChuYokoSettings`, `{tcyUpDown, tcyLeftRight}` in points) moves a marked block up or down and right or left as one piece. Evidence: `tests_vertical::manual_tate_chu_yoko_sets_marked_characters_across_one_em`, `tests_vertical::tate_chu_yoko_settings_move_a_marked_block_up_down_left_and_right`, `typecmd::tate_chu_yoko_is_a_character_attribute_saved_only_when_on`, `typecmd::tate_chu_yoko_settings_are_character_attributes_saved_only_when_set`, `dialogs::tate_chu_yoko::tests` | | CJK: Standard Vertical Roman Alignment | done | Character panel menu › Standard Vertical Roman Alignment (`text.setFormat` / `text.setRangeStyle {standardVerticalRoman}`), with Show East Asian Options, off by default: in vertical type the marked half-width characters (Latin letters, digits and other characters that would lie on their side) stand upright one below the other, each in its upright cell; spaces keep their width and tate-chu-yoko blocks stay across the column; horizontal type keeps the mark and does not change. Character Style Options has its own checkbox for it. Evidence: `tests_vertical::standard_vertical_roman_alignment_stands_half_width_characters_upright`, `typecmd::standard_vertical_roman_is_a_character_attribute_saved_only_when_on` | +| CJK: East Asian glyph forms | done | Glyphs panel menu › Traditional Forms, Expert Forms, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms, with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): the selected characters are drawn with the font's OpenType feature for that form (`trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, `fwid`, `hwid`, `twid`, `qwid`; [feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)), one form at a time (`text.setFormat` / `text.setRangeStyle {glyphForm}`); a form none of the faces that draw the selected text (fallback faces included) has a feature for is disabled, and Revert To Default Forms draws the default glyphs. Saved natively only when set, carried by character styles, drawn on the canvas and in PDF, and written to SVG as `font-feature-settings`. Character Style Options has no field for it. Evidence: `tests::typo::glyph_forms_draw_the_fonts_east_asian_forms`, `typecmd::area_tests::glyph_form_is_one_character_attribute_saved_only_when_set`, `panels::glyphs::tests::east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form` | | CJK: warichu | done | Character panel menu › Warichu and Warichu Settings… (`text.setFormat` / `text.setRangeStyle {warichu, warichuLines, warichuGap, warichuScale, warichuAlign}`, `ui.warichuSettings`), with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): marked characters set at a percentage of their size and stacked on 1 to 6 lines inside their line, one above the other in horizontal type and side by side in vertical type, with a line gap and eight alignments; a block stays whole on one line. Saved natively, carried by character styles, drawn on the canvas and in every export (SVG, PDF and `.ai` write such type as outlines). Type on a path sets the characters at their own size. Evidence: `tests::warichu`, `dialogs::warichu::tests`, `typecmd::area_tests::warichu_is_a_character_attribute_set_saved_and_exported` | | CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per class; SVG and legacy `.ai` write it as outlines. Not yet: custom character sets, the Units menu, Show Sample. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | | CJK: ruby | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`) | #633 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5f26e4377e..7496d62ff5 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -207,6 +207,7 @@ tools, never checked side by side) isn't captured row by row. | Ruler guides align to a key object: a click on an object selected with guides makes it the key (one object is enough); Align moves the selected guides to its edge or centre (vertical guides to left, centre or right, horizontal ones to top, centre or bottom) and the key stays put | done | #2143; aligning to the selection or the artboard leaves guides alone | | Align panel menu › Align to Glyph Bounds › Point Text and Area Text (checked while on): Align and Distribute measure point type or area type by the ink of its glyphs instead of its em box or frame | done | #4231; `alignGlyphBoundsPoint`, `alignGlyphBoundsArea` ([Align text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/align-text.html)); `tests::glyphbounds`, `panels::align::tests::align_to_glyph_bounds_toggles_point_and_area_text`; the Character and Properties panels' Align to Glyph Bounds controls are not done | | Align and distribute artboards: with the Artboard tool chosen, the Align panel's Align Objects, Distribute Objects and Distribute Spacing buttons, and the Control bar's, move the selected artboards with the art inside them (Move Artwork with Artboard) | done | `artboard.align`, `artboard.distribute`, `artboard.distributeSpacing` ([Align and distribute artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/align-and-distribute-artboards.html)); VectorCraft's own rules: Align to Artboard keeps the active artboard in place and sends the Distribute Spacing value, Align to Key Object is off, a locked artboard stays where it is; `cmd::artboardalign::tests`, `panels::align::tests::the_align_buttons_align_the_selected_artboards` | +| Object › Distribute, below Object › Align: Horizontal Distribute Left, Center and Right, Vertical Distribute Top, Center and Bottom, Horizontal Distribute Space and Vertical Distribute Space, each running what a click on its Align panel button runs (Align To, the key object, the Distribute Spacing value and, with the Artboard tool chosen, the selected artboards) | done | The `align.distribute*` commands; the public page names Object › Distribute beside Object › Align for the Align and Distribute commands ([Align and distribute objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/align-and-distribute-objects.html)); the items and their order are VectorCraft's own, taken from the Align panel; `menus::tests::object_distribute_runs_the_distribute_buttons` | | A marquee selects the objects whose paths it touches (anchors or segments): drawn inside a filled shape, over a background, it leaves that shape (Preview and Outline) | done | #1103 | | Click a segment independently of its endpoint anchors; only its direction handles show | done | #1278: hollow endpoint squares, selected edge emphasized; headless egui checked | | Drag a curved segment to bend it, a straight one to move its anchors | done | | @@ -268,7 +269,7 @@ tools, never checked side by side) isn't captured row by row. | Bounding-box handles: Shift proportional, Alt from centre, rotate outside the corners | done | | | Rotated objects keep a rotated bounding box and their angle; Reset Bounding Box | done | | | Vector Halftone Preview keeps the selection box and hides selection marks on the temporary dots | done | #6369; Preview off and Cancel restore the original marks. | -| Free Transform, Scale and Reflect along a rotated box | missing | | +| Free Transform, Scale and Reflect along a rotated box | done | The Scale and Reflect tools, dialogs and commands and the Transform and Properties panels' flips act along the turned box until Reset Bounding Box; `basis: "page"` keeps the page's axes | | Free Transform widget: constrain, free distort, perspective distort; the key-held variants | done | | | Transform tools: click sets the reference point (snaps to anchors/centres), Alt-click opens the dialog, Alt-release copies | done | with anchors selected with Direct Selection, the tools, the dialogs and Move transform those anchors alone, about the centre of their box by default (#1408; the default point and whole-object copies are our choices) | | Move, Rotate, Scale, Reflect and Shear dialogs: live Preview; Up/Down step angles and percentages by 1, Shift by 10 | done | #1412; Preview starts off (our choice: the public documentation gives no default), Move's as it was last confirmed; OK is one undo step and Transform Again repeats it |