From 33ab5adbc2102ed46063fa6a23013bf27bcd195e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 18:09:45 -0700 Subject: [PATCH 01/70] PDF/EPS export: flatten see-through and colorized pattern tile images PDF 1.3, PDF/X-1a, PDF/X-3, EPS and PostScript printing flatten transparency with `flatten_document`, which only looked at art in the layers. An image with see-through pixels, a colorize paint, opacity or a blending mode drawn only through a pattern fill stayed in the pattern definition, so the flattener returned early and the writer drew the tile opaque and uncolorized (PDF 1.3 export failed on the transparency left). `flatten_document` now first expands pattern fills whose tile image needs flattening into their tiles, as legacy .ai save does. See-through tile pixels count only where the caller counts see-through images (PDF 1.3); EPS level 3 already masks them out. The EPS and PostScript print transparency warnings now see those tile images too. --- crates/engine/src/cmd/expand.rs | 30 +++++--- crates/engine/src/cmd/fileio/eps.rs | 12 ++-- crates/engine/src/cmd/fileio/pdf.rs | 6 +- crates/engine/src/cmd/flatten.rs | 2 +- crates/engine/src/cmd/flatten/apply.rs | 28 +++++++- crates/engine/src/cmd/print.rs | 10 ++- crates/engine/src/tests/legacy_ai.rs | 97 ++++++++++++++++++++++++++ 7 files changed, 164 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 5ad8054fae..e536d0374a 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -456,18 +456,32 @@ pub(crate) fn expand_transparent_image_patterns(d: &mut Document, root: NodeId, if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { return None; } - let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); - let transparent = |d: &Document, i: &AppearanceItem| { - pattern_fill(d, i).is_some_and(|(f, def, _)| { - let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal; - def.art.iter().any(|a| transparent_image(a, see_through, on)) - }) - }; - expand_patterns_where(d, l, transparent) + expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through)) })?; Ok(n) } +/// Whether a path or compound path of `d` has a pattern fill that +/// [`expand_transparent_image_patterns`] would expand with `see_through`. +pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet) -> bool { + let mut found = false; + d.walk(|n| { + if !found && matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { + found = n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through)); + } + }); + found +} + +/// Whether `i`, an item of leaf `l`, is a pattern fill whose tile art holds a transparent image +/// ([`transparent_image`]), counting the fill's and the shape's opacity and blending mode. +fn transparent_pattern_fill(d: &Document, l: &Node, i: &AppearanceItem, see_through: &BTreeSet) -> bool { + let Some((f, def, _)) = pattern_fill(d, i) else { return false }; + let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); + let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal; + def.art.iter().any(|a| transparent_image(a, see_through, on)) +} + /// Whether `n` has opacity or a blending mode of its own. fn blended(n: &Node) -> bool { n.opacity < 1.0 || n.blend != BlendMode::Normal diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index a05cc08248..a999b31ce3 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -12,7 +12,7 @@ use vectorcraft_doc::Document; use vectorcraft_eps::{EpsOptions, Level, Overprint, Preview, Raster}; use vectorcraft_geom::{Point, Rect}; -use super::super::flatten::{FlattenOptions, flatten_document}; +use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_document}; use super::super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; use super::{ArtboardPick, Encoded, FormatOption}; @@ -299,11 +299,13 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result { return Err(bad(C, "the document has no artboard")); } let regions: Vec = pages.iter().map(|(_, region, _)| *region).collect(); - let transparent = doc.layers.iter().any(|l| l.shows_transparency()); - let flat = flatten_document(doc, &set.flatten)?; - let drawn = flat.as_ref().unwrap_or(doc); + let expanded = expand_transparent_tile_images(doc, &set.flatten)?; + let source = expanded.as_ref().unwrap_or(doc); + let transparent = source.layers.iter().any(|l| l.shows_transparency()); + let flat = flatten_document(source, &set.flatten)?; + let drawn = flat.as_ref().unwrap_or(source); let mut enc = Encoded { warnings, joiner: Some("_"), ..Encoded::default() }; - if transparent && flat.is_some() { + if transparent && (flat.is_some() || expanded.is_some()) { enc.warnings.push("transparency is flattened into opaque art and images (EPS has none): see the flattener preset".into()); } let preview_limit = if saving { SAVE_PREVIEW } else { MAX_PREVIEW }; diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index dfa7d1cfa7..213a442cf6 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -317,9 +317,9 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution"; /// `doc` with its transparency flattened for a PDF 1.3 file (asked for, or PDF/X-1a and PDF/X-3, /// whose files have none), with `flattenerPreset` (default High Resolution) and `p`'s `flattener` -/// options over it; images with see-through pixels and colorized images count as transparency, -/// rasterized areas are clipped to their regions, and discarded overprints are dropped. `None` -/// when nothing changes (or the file keeps transparency). +/// options over it; images with see-through pixels and colorized images, including those in +/// pattern tiles, count as transparency. Rasterized areas are clipped to their regions, and +/// discarded overprints are dropped. `None` when nothing changes (or the file keeps transparency). fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result> { if !set.pdf13() { return Ok(None); diff --git a/crates/engine/src/cmd/flatten.rs b/crates/engine/src/cmd/flatten.rs index 47a190a430..94e05a3572 100644 --- a/crates/engine/src/cmd/flatten.rs +++ b/crates/engine/src/cmd/flatten.rs @@ -49,7 +49,7 @@ mod presets; mod report; pub(crate) use analysis::{outlined_text, see_through_images}; -pub(crate) use apply::flatten_document; +pub(crate) use apply::{expand_transparent_tile_images, flatten_document}; pub use commands::specs; pub use options::FlattenOptions; pub use presets::{FlattenerPreset, PRESET_EXTS, PRESET_FORMAT}; diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 884351dea6..463323029f 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -292,13 +292,35 @@ pub(super) fn opaque(n: &mut Node) { } } +/// Expand pattern fills whose image tiles need transparency flattening. +pub(crate) fn expand_transparent_tile_images(doc: &Document, o: &FlattenOptions) -> Result> { + if doc.patterns.is_empty() { + return Ok(None); + } + let keys = o.no_transparency.clone().unwrap_or_default(); + if !crate::cmd::expand::has_transparent_image_patterns(doc, &keys) { + return Ok(None); + } + let mut d = doc.clone(); + let layers: Vec = d.layers.iter().map(|l| l.id).collect(); + let mut changed = 0; + for id in layers { + changed += crate::cmd::expand::expand_transparent_image_patterns(&mut d, id, &keys)?; + } + Ok((changed > 0).then_some(d)) +} + /// `doc` with everything it draws flattened with `o`, as formats without transparency (EPS) /// write it: every visible object of the visible layers, locked ones too (a clipping layer's -/// clipping path stays). `None` when that changes nothing. +/// clipping path stays). Pattern tile images with opacity, blending or colorize are expanded; +/// see-through tile pixels are expanded when `o.no_transparency` counts them. `None` when nothing +/// changes. pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result> { + let expanded = expand_transparent_tile_images(doc, o)?; + let doc = expanded.as_ref().unwrap_or(doc); let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints; if !outlining && !doc.layers.iter().any(|l| l.shows_transparency() || o.draws_see_through_image(l)) { - return Ok(None); + return Ok(expanded); } let mut roots = vec![]; for l in doc.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) { @@ -307,7 +329,7 @@ pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result Result { // Raster effects print as images at the document's raster effects resolution. let flat = super::rasterfx::flatten_raster_effects(doc); let doc = flat.as_ref().unwrap_or(doc); + let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite; + let expanded = if postscript && !bitmap { + let options = super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?; + options.as_ref().map(|o| expand_transparent_tile_images(doc, o)).transpose()?.flatten() + } else { + None + }; + let doc = expanded.as_ref().unwrap_or(doc); // Print as Bitmap and the flattener preset (Advanced) render and flatten it first. let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?; let path = str_param(p, "path"); @@ -201,7 +210,6 @@ fn print(s: &mut Session, p: &Value) -> Result { None => Level::default(), }; let mut warnings = vec![]; - let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite; if !bitmap && doc.layers.iter().any(|l| l.shows_transparency()) { warnings.push("transparency is flattened into opaque art and images (PostScript has none): see flattenerPreset".to_string()); } diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 7ac5c3c5c9..793fe19d2a 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -704,3 +704,100 @@ fn only_the_transparent_pattern_fill_of_a_leaf_is_expanded() { assert_eq!(patterns.len(), 1, "{patterns:?}"); assert!(images > 0); } + +#[test] +fn pdf13_flattens_see_through_pattern_tile_images() { + let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let page = vectorcraft_pdf::import(&bytes).unwrap(); + let after = [colour_at(&page, 72.0, 72.0), colour_at(&page, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn pdf13_flattens_colorized_pattern_tile_images() { + let mut s = colorized_pattern_over_blue(); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let page = vectorcraft_pdf::import(&bytes).unwrap(); + let after = [colour_at(&page, 72.0, 72.0), colour_at(&page, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn eps_level3_writes_see_through_pattern_tile_images() { + let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); + s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); + let page = &s.doc().unwrap().doc; + let after = [colour_at(page, 72.0, 72.0), colour_at(page, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn eps_flattens_colorized_pattern_tile_images_and_warns() { + let mut s = colorized_pattern_over_blue(); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); + assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r)); + s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); + let after = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn eps_warns_for_colorized_image_nested_in_pattern_tile_group() { + let mut s = colorized_pattern_over_blue(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let id = d.alloc_id(); + let art = std::mem::take(&mut d.patterns[0].art); + d.patterns[0].art.push(std::sync::Arc::new(vectorcraft_doc::Node::group(id, art))); + let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); + assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r)); +} + +#[test] +fn postscript_print_warns_for_colorized_pattern_tile_image() { + let mut s = colorized_pattern_over_blue(); + let r = s.execute("file.print", &json!({"format": "postscript"})).unwrap(); + assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r)); +} + +#[test] +fn eps_pattern_does_not_flatten_a_separate_see_through_image() { + let mut output = vec![]; + for tile in [checker([0, 200, 0, 255], [255, 230, 0, 255]), checker([0, 200, 0, 255], [255, 255, 255, 0])] { + let mut s = pattern_over_blue(&tile, 1.0); + s.execute("shape.rectangle", &json!({"x": 8, "y": 8, "width": 24, "height": 24})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let p = json!({"name": "i.png", "dataBase64": vectorcraft_format::base64_encode(&png(20, 20, [0, 0, 0, 128])), "at": [20, 20]}); + s.execute("file.place", &p).unwrap(); + let r = + s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3, "flattenerPreset": "high"})).unwrap(); + let image_warning = warnings(&r).iter().any(|w| w.contains("partly transparent")); + s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); + output.push((colour_at(&s.doc().unwrap().doc, 20.0, 20.0), image_warning)); + } + assert_eq!(output[0], output[1], "EPS layer image changed when a see-through pattern tile was present: {output:?}"); +} + +#[test] +fn opaque_pattern_tile_images_do_not_change_during_export_flattening() { + let s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 230, 0, 255]), 1.0); + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none()); + let o = crate::cmd::FlattenOptions { no_transparency: Some(crate::cmd::flatten::see_through_images(d)), ..Default::default() }; + assert!(crate::cmd::flatten::flatten_document(d, &o).unwrap().is_none()); +} From 7b4d6282f12f1b95c653d058a92bed1dbf699447 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 21:26:34 -0700 Subject: [PATCH 02/70] Flattening: an option leaves colorized images to writers that draw them Flattening counted every colorized image as transparency, in the art and in pattern tiles. A new flattener option, keeps_colorize, stops counting an image colorized with a solid paint whose pixels are grayscale or 1-bit, for a format whose writer draws such images in their ink. Opacity, blending modes, opacity masks and effects still flatten them, and pattern tiles are still expanded for those. The option is off, so exports flatten as before; the EPS writer that draws colorized images turns it on. The EPS pattern tile tests now check the exported colors, and a tile group with opacity for the warning. --- crates/doc/src/node/ops.rs | 10 ++++-- crates/engine/src/cmd/expand.rs | 38 +++++++++++++++-------- crates/engine/src/cmd/fileio/eps.rs | 2 +- crates/engine/src/cmd/fileio/legacy_ai.rs | 2 +- crates/engine/src/cmd/flatten/apply.rs | 15 ++++----- crates/engine/src/cmd/flatten/options.rs | 22 ++++++++++++- crates/engine/src/tests/legacy_ai.rs | 28 +++++++++++++---- 7 files changed, 86 insertions(+), 31 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index fcf2c9429d..edab5f73c9 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -686,6 +686,12 @@ impl Node { /// stroke opacity below 100%, a blend mode, an opacity mask, effects, transparent gradient /// stops or a colorized image. Hidden objects show none. pub fn shows_transparency(&self) -> bool { + self.shows_transparency_with(&|_| true) + } + + /// [`Self::shows_transparency`], counting a colorized image by itself only when `colorize` + /// accepts it, for files that write some colorized images in their colorize paint (EPS). + pub fn shows_transparency_with(&self, colorize: &dyn Fn(&Node) -> bool) -> bool { use vectorcraft_color::Paint; let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0)); let effects = |fx: &[crate::Effect]| fx.iter().any(|e| e.visible); @@ -693,14 +699,14 @@ impl Node { && (self.opacity < 1.0 || self.blend != BlendMode::Normal || self.extras().mask.as_ref().is_some_and(|m| !m.disabled) - || (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some()) + || (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self)) || effects(&self.appearance.effects) || self .appearance .items .iter() .any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects()))) - || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency()))) + || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize)))) } } diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index e536d0374a..cf61a305b2 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -447,27 +447,32 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { /// Expand the pattern fills under `root` that paint a transparent or colorized image into the tiles they paint /// ([`expand_patterns_where`]), so each tile image becomes an object of its own; the other /// pattern fills stay. A tile image counts when its key is in `see_through` (it has see-through -/// pixels), when it has a colorize paint, or when it, a group +/// pixels), when it has a colorize paint that `colorize` counts, or when it, a group /// in the tile art, the fill, the shape or a group the shape is in has opacity or a blending /// mode. Returns how many shapes changed. -pub(crate) fn expand_transparent_image_patterns(d: &mut Document, root: NodeId, see_through: &BTreeSet) -> Result { +pub(crate) fn expand_transparent_image_patterns( + d: &mut Document, + root: NodeId, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, +) -> Result { let (_, n) = replace_leaves(d, root, |d, l| { // Most leaves have no pattern fill: skip the ancestry walk for them. if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { return None; } - expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through)) + expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through, colorize)) })?; Ok(n) } /// Whether a path or compound path of `d` has a pattern fill that -/// [`expand_transparent_image_patterns`] would expand with `see_through`. -pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet) -> bool { +/// [`expand_transparent_image_patterns`] would expand with `see_through` and `colorize`. +pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool { let mut found = false; d.walk(|n| { if !found && matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { - found = n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through)); + found = n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize)); } }); found @@ -475,11 +480,17 @@ pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSe /// Whether `i`, an item of leaf `l`, is a pattern fill whose tile art holds a transparent image /// ([`transparent_image`]), counting the fill's and the shape's opacity and blending mode. -fn transparent_pattern_fill(d: &Document, l: &Node, i: &AppearanceItem, see_through: &BTreeSet) -> bool { +fn transparent_pattern_fill( + d: &Document, + l: &Node, + i: &AppearanceItem, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, +) -> bool { let Some((f, def, _)) = pattern_fill(d, i) else { return false }; let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal; - def.art.iter().any(|a| transparent_image(a, see_through, on)) + def.art.iter().any(|a| transparent_image(d, a, see_through, colorize, on)) } /// Whether `n` has opacity or a blending mode of its own. @@ -487,13 +498,14 @@ fn blended(n: &Node) -> bool { n.opacity < 1.0 || n.blend != BlendMode::Normal } -/// Whether `n` is or holds an image with see-through pixels (key in `keys`), a colorize paint, -/// opacity or a blending mode of its own or of a group in `n`, or anywhere when `on`. -fn transparent_image(n: &Node, keys: &BTreeSet, on: bool) -> bool { +/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`), a +/// colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in +/// `n`, or anywhere when `on`. +fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool) -> bool { let on = on || blended(n); match &n.kind { - NodeKind::Image(im) => on || keys.contains(&im.key) || n.extras().colorize.is_some(), - _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(c, keys, on))), + NodeKind::Image(im) => on || keys.contains(&im.key) || (n.extras().colorize.is_some() && colorize(d, n)), + _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(d, c, keys, colorize, on))), } } diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index a999b31ce3..2c8ae4a845 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -301,7 +301,7 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result { let regions: Vec = pages.iter().map(|(_, region, _)| *region).collect(); let expanded = expand_transparent_tile_images(doc, &set.flatten)?; let source = expanded.as_ref().unwrap_or(doc); - let transparent = source.layers.iter().any(|l| l.shows_transparency()); + let transparent = source.layers.iter().any(|l| set.flatten.shows_transparency(source, l)); let flat = flatten_document(source, &set.flatten)?; let drawn = flat.as_ref().unwrap_or(source); let mut enc = Encoded { warnings, joiner: Some("_"), ..Encoded::default() }; diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index 0e53a5a18f..7cbbda2fed 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -167,7 +167,7 @@ fn expand_image_patterns(d: &mut Document) -> Result<()> { let keys = super::super::flatten::see_through_images(d); let layers: Vec = d.layers.iter().map(|l| l.id).collect(); for id in layers { - super::super::expand::expand_transparent_image_patterns(d, id, &keys)?; + super::super::expand::expand_transparent_image_patterns(d, id, &keys, &|_, _| true)?; } Ok(()) } diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 463323029f..7fbe44a0d1 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -74,7 +74,7 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: let mut sc = Scratch { brushes: vectorcraft_brush::library(&baked), doc: baked.clone() }; let plain: Vec = art.iter().map(|n| sc.plain(n)).collect(); let reaches: Vec> = plain.iter().map(reach).collect(); - let see_through: Vec = plain.iter().map(|n| n.shows_transparency() || o.draws_see_through_image(n)).collect(); + let see_through: Vec = plain.iter().map(|n| o.shows_transparency(&baked, n) || o.draws_see_through_image(n)).collect(); let cmyk = src.color_mode == ColorMode::Cmyk; let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() }; // Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing). @@ -298,28 +298,29 @@ pub(crate) fn expand_transparent_tile_images(doc: &Document, o: &FlattenOptions) return Ok(None); } let keys = o.no_transparency.clone().unwrap_or_default(); - if !crate::cmd::expand::has_transparent_image_patterns(doc, &keys) { + let colorize = |d: &Document, n: &Node| o.counts_colorize(d, n); + if !crate::cmd::expand::has_transparent_image_patterns(doc, &keys, &colorize) { return Ok(None); } let mut d = doc.clone(); let layers: Vec = d.layers.iter().map(|l| l.id).collect(); let mut changed = 0; for id in layers { - changed += crate::cmd::expand::expand_transparent_image_patterns(&mut d, id, &keys)?; + changed += crate::cmd::expand::expand_transparent_image_patterns(&mut d, id, &keys, &colorize)?; } Ok((changed > 0).then_some(d)) } /// `doc` with everything it draws flattened with `o`, as formats without transparency (EPS) /// write it: every visible object of the visible layers, locked ones too (a clipping layer's -/// clipping path stays). Pattern tile images with opacity, blending or colorize are expanded; -/// see-through tile pixels are expanded when `o.no_transparency` counts them. `None` when nothing -/// changes. +/// clipping path stays). Pattern tile images with opacity, blending or a colorize paint that +/// `o` counts ([`FlattenOptions::counts_colorize`]) are expanded; see-through tile pixels are +/// expanded when `o.no_transparency` counts them. `None` when nothing changes. pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result> { let expanded = expand_transparent_tile_images(doc, o)?; let doc = expanded.as_ref().unwrap_or(doc); let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints; - if !outlining && !doc.layers.iter().any(|l| l.shows_transparency() || o.draws_see_through_image(l)) { + if !outlining && !doc.layers.iter().any(|l| o.shows_transparency(doc, l) || o.draws_see_through_image(l)) { return Ok(expanded); } let mut roots = vec![]; diff --git a/crates/engine/src/cmd/flatten/options.rs b/crates/engine/src/cmd/flatten/options.rs index 57331660ab..d4f18f3857 100644 --- a/crates/engine/src/cmd/flatten/options.rs +++ b/crates/engine/src/cmd/flatten/options.rs @@ -2,7 +2,7 @@ use super::analysis::draws_image; use super::apply::{apply, kept_work, plan}; use super::presets::{FlattenerPreset, saved_preset}; use super::report::target_roots; -use super::{BTreeSet, Deserialize, EngineError, Node, Result, Serialize, Session, Value, bad, json, str_param}; +use super::{BTreeSet, Deserialize, Document, EngineError, Node, NodeKind, Paint, Result, Serialize, Session, Value, bad, json, str_param}; /// Object → Flatten Transparency settings: a preset's, adjusted by the command's params. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -34,6 +34,10 @@ pub struct FlattenOptions { /// amounts). `None` for ordinary flattening. Not a preset option. #[serde(skip)] pub no_transparency: Option>, + /// The file writes a colorized image in its colorize paint (EPS), so a colorize paint by + /// itself doesn't count as transparency. Not a preset option. + #[serde(skip)] + pub keeps_colorize: bool, } impl Default for FlattenOptions { @@ -81,6 +85,7 @@ impl FlattenOptions { preserve_alpha: false, preserve_overprints: true, no_transparency: None, + keeps_colorize: false, } } @@ -138,6 +143,21 @@ impl FlattenOptions { Ok(o) } + /// Whether `n`, art of `d`, shows transparency these options flatten + /// ([`Node::shows_transparency`], colorized images as [`Self::counts_colorize`] says). + pub(crate) fn shows_transparency(&self, d: &Document, n: &Node) -> bool { + n.shows_transparency_with(&|c| self.counts_colorize(d, c)) + } + + /// Whether colorized image `n`, art of `d`, counts as transparency by itself. With + /// [`Self::keeps_colorize`], an image colorized with a solid paint whose pixels are grayscale + /// or 1-bit doesn't: the EPS writer draws it in that paint. + pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool { + let NodeKind::Image(im) = &n.kind else { return true }; + let solid = matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })); + !self.keeps_colorize || !solid || d.image_blob(im).is_some_and(|b| b.gray_source().is_none()) + } + /// `n` shows an image whose see-through pixels count as transparency. pub(super) fn draws_see_through_image(&self, n: &Node) -> bool { self.no_transparency.as_ref().is_some_and(|keys| draws_image(n, keys)) diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 793fe19d2a..0a3f9af6f4 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -546,7 +546,7 @@ fn a_colorized_grayscale_image_pattern_fill_is_expanded() { let keys = crate::cmd::flatten::see_through_images(d); assert!(keys.is_empty()); let layer = d.layers[0].id; - assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys).unwrap(), 1); + assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys, &|_, _| true).unwrap(), 1); let mut patterns = 0; let mut tile_images = 0; d.walk(|n| { @@ -688,7 +688,7 @@ fn only_the_transparent_pattern_fill_of_a_leaf_is_expanded() { let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); let keys = crate::cmd::flatten::see_through_images(d); let layer = d.layers[0].id; - assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys).unwrap(), 1); + assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys, &|_, _| true).unwrap(), 1); let mut patterns = vec![]; let mut images = 0; d.walk(|n| { @@ -745,11 +745,10 @@ fn eps_level3_writes_see_through_pattern_tile_images() { } #[test] -fn eps_flattens_colorized_pattern_tile_images_and_warns() { +fn eps_writes_colorized_pattern_tile_images_in_their_colors() { let mut s = colorized_pattern_over_blue(); let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); - assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r)); s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); let after = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; for (a, b) in before.iter().zip(after) { @@ -758,14 +757,31 @@ fn eps_flattens_colorized_pattern_tile_images_and_warns() { } #[test] -fn eps_warns_for_colorized_image_nested_in_pattern_tile_group() { +fn flattening_that_keeps_colorize_leaves_colorized_pattern_tile_images_alone() { + let s = colorized_pattern_over_blue(); + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_some()); + let o = crate::cmd::FlattenOptions { keeps_colorize: true, ..Default::default() }; + assert!(crate::cmd::flatten::flatten_document(d, &o).unwrap().is_none(), "the pattern isn't expanded for a colorize paint alone"); +} + +#[test] +fn eps_flattens_colorized_image_in_a_see_through_pattern_tile_group_and_warns() { let mut s = colorized_pattern_over_blue(); let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); let id = d.alloc_id(); let art = std::mem::take(&mut d.patterns[0].art); - d.patterns[0].art.push(std::sync::Arc::new(vectorcraft_doc::Node::group(id, art))); + let mut group = vectorcraft_doc::Node::group(id, art); + group.opacity = 0.5; + d.patterns[0].art.push(std::sync::Arc::new(group)); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r)); + s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); + let after = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } } #[test] From 6dfda4db7677b91cb7818a78cae5011795a748b8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 22:44:47 -0700 Subject: [PATCH 03/70] PDF/EPS export: pattern tile images in live art and hidden shapes flatten as drawn Blends, envelopes, repeats and Intertwine groups that hold a see-through or colorized pattern tile image are expanded into the art the writers draw for them before the tiles are expanded, so those tiles are flattened too. Random Transform effects in that art are baked first. Hidden shapes, shapes in hidden groups or layers and template layers are skipped: expanding a hidden shape made its tiles show in the file, and art that is not written no longer makes a flattened copy of the document. --- crates/engine/src/cmd/expand.rs | 94 +++++++++++++++++++++++--- crates/engine/src/cmd/flatten/apply.rs | 3 +- crates/engine/src/tests/legacy_ai.rs | 60 ++++++++++++++++ 3 files changed, 146 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index cf61a305b2..b3bfab9c6e 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -449,33 +449,107 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { /// pattern fills stay. A tile image counts when its key is in `see_through` (it has see-through /// pixels), when it has a colorize paint that `colorize` counts, or when it, a group /// in the tile art, the fill, the shape or a group the shape is in has opacity or a blending -/// mode. Returns how many shapes changed. +/// mode. Blends, envelopes, repeats and Intertwine groups that hold such a fill are expanded +/// first ([`expand_live_with_transparent_image_patterns`]). Hidden shapes and shapes in hidden +/// groups or layers and in template layers stay as they are. Returns how many objects changed. pub(crate) fn expand_transparent_image_patterns( d: &mut Document, root: NodeId, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, ) -> Result { + let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize)?; let (_, n) = replace_leaves(d, root, |d, l| { // Most leaves have no pattern fill: skip the ancestry walk for them. if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { return None; } + // The expanded art would be shown. + if !d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).all(drawn) { + return None; + } expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through, colorize)) })?; - Ok(n) + Ok(live + n) } -/// Whether a path or compound path of `d` has a pattern fill that -/// [`expand_transparent_image_patterns`] would expand with `see_through` and `colorize`. +/// Whether a layer of `d` holds a pattern fill that [`expand_transparent_image_patterns`] would +/// expand with `see_through` and `colorize` ([`holds_transparent_image_patterns`]). pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool { - let mut found = false; - d.walk(|n| { - if !found && matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { - found = n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize)); + d.layers.iter().any(|l| holds_transparent_image_patterns(d, l, see_through, colorize)) +} + +/// Whether `n`, art of `d`, is or holds a shown path or compound path (in groups, blends, +/// envelopes, repeats and Intertwine groups) with a pattern fill that +/// [`transparent_pattern_fill`] counts. Guides, clipping paths and template layers don't count. +fn holds_transparent_image_patterns(d: &Document, n: &Node, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool { + if !drawn(n) { + return false; + } + match &n.kind { + NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => false, + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize)) } - }); - found + _ => n.children().is_some_and(|ch| ch.iter().any(|c| holds_transparent_image_patterns(d, c, see_through, colorize))), + } +} + +/// Whether `n` is shown and isn't a template layer. +fn drawn(n: &Node) -> bool { + n.visible && !matches!(n.kind, NodeKind::Layer { template: true, .. }) +} + +/// Expand the shown blends, envelopes, repeats and Intertwine groups under `root` that hold a +/// pattern fill [`holds_transparent_image_patterns`] counts into the art the exporters write for +/// them ([`expand_live_deep`](vectorcraft_render::effects::expand_live_deep), under one budget for +/// everything nested in each), so the shapes they draw are leaves. Returns how many were expanded. +fn expand_live_with_transparent_image_patterns( + d: &mut Document, + root: NodeId, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, +) -> Result { + fn outermost(d: &Document, n: &Node, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, out: &mut Vec) { + if !drawn(n) { + return; + } + match &n.kind { + NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { + if holds_transparent_image_patterns(d, n, see_through, colorize) { + out.push(n.id); + } + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + children.iter().for_each(|c| outermost(d, c, see_through, colorize, out)); + } + _ => {} + } + } + /// Fresh ids for everything under `n`: copies of the same art share theirs. + fn fresh_ids(d: &mut Document, n: &mut Node) { + for c in n.children_mut().into_iter().flatten() { + let c = Arc::make_mut(c); + c.id = d.alloc_id(); + fresh_ids(d, c); + } + } + let mut live = vec![]; + if let Some(n) = d.node(root) { + outermost(d, n, see_through, colorize, &mut live); + } + let mut count = 0; + for id in &live { + let Some(n) = d.node(*id) else { continue }; + // Random Transform effects take their seed from the ids: bake them first ([`bake_seeded`]), + // and leave the object live when that can't be done. + let Some(mut g) = bake_seeded(&vectorcraft_render::effects::expand_live_deep(Some(d), n)) else { continue }; + g.id = *id; + fresh_ids(d, &mut g); + *d.node_mut(*id).ok_or(EngineError::NoNode(*id))? = g; + count += 1; + } + Ok(count) } /// Whether `i`, an item of leaf `l`, is a pattern fill whose tile art holds a transparent image diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 7fbe44a0d1..0cd1ab159b 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -303,7 +303,8 @@ pub(crate) fn expand_transparent_tile_images(doc: &Document, o: &FlattenOptions) return Ok(None); } let mut d = doc.clone(); - let layers: Vec = d.layers.iter().map(|l| l.id).collect(); + let layers: Vec = + d.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })).map(|l| l.id).collect(); let mut changed = 0; for id in layers { changed += crate::cmd::expand::expand_transparent_image_patterns(&mut d, id, &keys, &colorize)?; diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 0a3f9af6f4..96878b0432 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -817,3 +817,63 @@ fn opaque_pattern_tile_images_do_not_change_during_export_flattening() { let o = crate::cmd::FlattenOptions { no_transparency: Some(crate::cmd::flatten::see_through_images(d)), ..Default::default() }; assert!(crate::cmd::flatten::flatten_document(d, &o).unwrap().is_none()); } + +/// The id of the square [`pattern_over_blue`] fills with its pattern. +fn pattern_square(s: &Session) -> vectorcraft_doc::NodeId { + let mut id = None; + s.doc().unwrap().doc.walk(|n| { + if n.appearance.items.iter().any(|i| matches!(i.paint(), vectorcraft_color::Paint::Pattern { .. })) { + id = Some(n.id); + } + }); + id.unwrap() +} + +/// PDF 1.3 draws `s` as the canvas draws it at two points of the pattern square. +fn assert_pdf13_draws_pattern_square_as_canvas(s: &mut Session) { + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let page = vectorcraft_pdf::import(&bytes).unwrap(); + let after = [colour_at(&page, 72.0, 72.0), colour_at(&page, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn pdf13_flattens_colorized_pattern_tile_images_in_a_repeat() { + let mut s = colorized_pattern_over_blue(); + let square = pattern_square(&s); + s.execute("object.repeat.grid", &json!({"ids": [square.0]})).unwrap(); + assert!(s.doc().unwrap().doc.layers[0].count() > 3); + let d = &s.doc().unwrap().doc; + let mut repeats = 0; + d.walk(|n| repeats += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Repeat(_)))); + assert_eq!(repeats, 1); + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_some()); + assert_pdf13_draws_pattern_square_as_canvas(&mut s); +} + +#[test] +fn pdf13_leaves_a_hidden_shape_with_a_colorized_pattern_tile_image_hidden() { + let mut s = colorized_pattern_over_blue(); + let square = pattern_square(&s); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(square).unwrap().visible = false; + assert_pdf13_draws_pattern_square_as_canvas(&mut s); +} + +#[test] +fn flattening_skips_pattern_tile_images_on_hidden_and_template_layers() { + for template in [false, true] { + let mut s = colorized_pattern_over_blue(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let layer = std::sync::Arc::make_mut(&mut d.layers[0]); + match &mut layer.kind { + vectorcraft_doc::NodeKind::Layer { template: t, .. } if template => *t = true, + _ => layer.visible = false, + } + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none(), "template {template}"); + } +} From c09ea597319ff9b22fff48375cff4099c950b8f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 00:06:51 -0700 Subject: [PATCH 04/70] PDF/EPS export: transparent images in patterns nested in tile art flatten A pattern fill in a pattern's tile art that paints a see-through or colorized image was not counted, so PDF 1.3 export kept it as a pattern and failed on its transparency. Detection now follows pattern fills in tile art down to the three levels the canvas draws, skipping hidden tile art, and the tiles the expansion makes are expanded again for them. Expansion stops once the expanded art holds MAX_GENERATED objects. --- crates/engine/src/cmd/expand.rs | 119 ++++++++++++++++++++------- crates/engine/src/tests/legacy_ai.rs | 48 +++++++++++ 2 files changed, 137 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index b3bfab9c6e..eec854a743 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -451,47 +451,73 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { /// in the tile art, the fill, the shape or a group the shape is in has opacity or a blending /// mode. Blends, envelopes, repeats and Intertwine groups that hold such a fill are expanded /// first ([`expand_live_with_transparent_image_patterns`]). Hidden shapes and shapes in hidden -/// groups or layers and in template layers stay as they are. Returns how many objects changed. +/// groups or layers and in template layers stay as they are. A pattern fill in tile art counts +/// too, down to the [`PATTERN_LEVELS`] the canvas draws, and the tile art the expansion makes is +/// expanded again for it. Pattern fills stay once the expanded art holds +/// [`MAX_GENERATED`](vectorcraft_doc::live::MAX_GENERATED) objects. Returns how many objects +/// changed. pub(crate) fn expand_transparent_image_patterns( d: &mut Document, root: NodeId, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, ) -> Result { - let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize)?; - let (_, n) = replace_leaves(d, root, |d, l| { - // Most leaves have no pattern fill: skip the ancestry walk for them. - if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { - return None; + let mut changed = 0; + let made = std::cell::Cell::new(0usize); + // Each pass brings the patterns in the expanded tiles' art up one level. + for levels in (1..=PATTERN_LEVELS).rev() { + let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize, levels)?; + let (_, n) = replace_leaves(d, root, |d, l| { + // Past the budget, and for most leaves, which have no pattern fill, skip the ancestry walk. + if made.get() >= vectorcraft_doc::live::MAX_GENERATED || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { + return None; + } + // The expanded art would be shown. + if !d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).all(drawn) { + return None; + } + let art = expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through, colorize, levels))?; + made.set(made.get().saturating_add(art.count())); + Some(art) + })?; + if live + n == 0 { + break; } - // The expanded art would be shown. - if !d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).all(drawn) { - return None; - } - expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through, colorize)) - })?; - Ok(live + n) + changed += live + n; + } + Ok(changed) } +/// How many levels of patterns the canvas draws: a pattern fill in the art of a pattern, and so +/// on, as [`vectorcraft_render`] draws them. +const PATTERN_LEVELS: u32 = 3; + /// Whether a layer of `d` holds a pattern fill that [`expand_transparent_image_patterns`] would /// expand with `see_through` and `colorize` ([`holds_transparent_image_patterns`]). pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool { - d.layers.iter().any(|l| holds_transparent_image_patterns(d, l, see_through, colorize)) + d.layers.iter().any(|l| holds_transparent_image_patterns(d, l, see_through, colorize, PATTERN_LEVELS)) } /// Whether `n`, art of `d`, is or holds a shown path or compound path (in groups, blends, /// envelopes, repeats and Intertwine groups) with a pattern fill that -/// [`transparent_pattern_fill`] counts. Guides, clipping paths and template layers don't count. -fn holds_transparent_image_patterns(d: &Document, n: &Node, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool { +/// [`transparent_pattern_fill`] counts with `levels`. Guides, clipping paths and template layers +/// don't count. +fn holds_transparent_image_patterns( + d: &Document, + n: &Node, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, +) -> bool { if !drawn(n) { return false; } match &n.kind { NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => false, NodeKind::Path { .. } | NodeKind::Compound { .. } => { - n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize)) + n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize, levels)) } - _ => n.children().is_some_and(|ch| ch.iter().any(|c| holds_transparent_image_patterns(d, c, see_through, colorize))), + _ => n.children().is_some_and(|ch| ch.iter().any(|c| holds_transparent_image_patterns(d, c, see_through, colorize, levels))), } } @@ -501,7 +527,7 @@ fn drawn(n: &Node) -> bool { } /// Expand the shown blends, envelopes, repeats and Intertwine groups under `root` that hold a -/// pattern fill [`holds_transparent_image_patterns`] counts into the art the exporters write for +/// pattern fill [`holds_transparent_image_patterns`] counts with `levels` into the art the exporters write for /// them ([`expand_live_deep`](vectorcraft_render::effects::expand_live_deep), under one budget for /// everything nested in each), so the shapes they draw are leaves. Returns how many were expanded. fn expand_live_with_transparent_image_patterns( @@ -509,19 +535,27 @@ fn expand_live_with_transparent_image_patterns( root: NodeId, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, ) -> Result { - fn outermost(d: &Document, n: &Node, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, out: &mut Vec) { + fn outermost( + d: &Document, + n: &Node, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, + out: &mut Vec, + ) { if !drawn(n) { return; } match &n.kind { NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { - if holds_transparent_image_patterns(d, n, see_through, colorize) { + if holds_transparent_image_patterns(d, n, see_through, colorize, levels) { out.push(n.id); } } NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { - children.iter().for_each(|c| outermost(d, c, see_through, colorize, out)); + children.iter().for_each(|c| outermost(d, c, see_through, colorize, levels, out)); } _ => {} } @@ -536,7 +570,7 @@ fn expand_live_with_transparent_image_patterns( } let mut live = vec![]; if let Some(n) = d.node(root) { - outermost(d, n, see_through, colorize, &mut live); + outermost(d, n, see_through, colorize, levels, &mut live); } let mut count = 0; for id in &live { @@ -553,18 +587,36 @@ fn expand_live_with_transparent_image_patterns( } /// Whether `i`, an item of leaf `l`, is a pattern fill whose tile art holds a transparent image -/// ([`transparent_image`]), counting the fill's and the shape's opacity and blending mode. +/// ([`transparent_image`], through pattern fills in that art down to `levels` patterns), +/// counting the fill's and the shape's opacity and blending mode. fn transparent_pattern_fill( d: &Document, l: &Node, i: &AppearanceItem, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, ) -> bool { - let Some((f, def, _)) = pattern_fill(d, i) else { return false }; let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); - let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal; - def.art.iter().any(|a| transparent_image(d, a, see_through, colorize, on)) + pattern_fill_holds_transparent_image(d, i, see_through, colorize, shape, levels) +} + +/// Whether `i` is a pattern fill whose tile art holds a transparent image ([`transparent_image`]), +/// down to `levels` patterns, counting the fill's opacity and blending mode, or anything when `on`. +fn pattern_fill_holds_transparent_image( + d: &Document, + i: &AppearanceItem, + keys: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + on: bool, + levels: u32, +) -> bool { + if levels == 0 { + return false; + } + let Some((f, def, _)) = pattern_fill(d, i) else { return false }; + let on = on || f.opacity < 1.0 || f.blend != BlendMode::Normal; + def.art.iter().any(|a| transparent_image(d, a, keys, colorize, on, levels - 1)) } /// Whether `n` has opacity or a blending mode of its own. @@ -574,12 +626,19 @@ fn blended(n: &Node) -> bool { /// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`), a /// colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in -/// `n`, or anywhere when `on`. -fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool) -> bool { +/// `n`, or anywhere when `on`, also in the tile art of the pattern fills of the paths in `n`, down +/// to `levels` patterns. Hidden art doesn't count. +fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool, levels: u32) -> bool { + if !n.visible { + return false; + } let on = on || blended(n); match &n.kind { NodeKind::Image(im) => on || keys.contains(&im.key) || (n.extras().colorize.is_some() && colorize(d, n)), - _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(d, c, keys, colorize, on))), + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + n.appearance.items.iter().any(|i| pattern_fill_holds_transparent_image(d, i, keys, colorize, on, levels)) + } + _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(d, c, keys, colorize, on, levels))), } } diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 96878b0432..ecac48bb7e 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -855,6 +855,54 @@ fn pdf13_flattens_colorized_pattern_tile_images_in_a_repeat() { assert_pdf13_draws_pattern_square_as_canvas(&mut s); } +/// [`colorized_pattern_over_blue`] with the square filled with a pattern named `outer` whose tile +/// art is a 32 pt square filled with the colorized image pattern. +fn nested_colorized_pattern_over_blue() -> Session { + let mut s = colorized_pattern_over_blue(); + let square = pattern_square(&s); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 32, "height": 32})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inner = d.patterns[0].name.clone(); + let rect = d.layers[0].children().unwrap().last().unwrap().id; + let mut tile = d.remove(rect).unwrap(); + let paint = vectorcraft_color::Paint::Pattern { pattern: inner, xf: Default::default() }; + let tile_node = std::sync::Arc::make_mut(&mut tile); + tile_node.appearance.items.retain(|i| matches!(i, vectorcraft_doc::appearance::AppearanceItem::Fill(_))); + for i in &mut tile_node.appearance.items { + if let vectorcraft_doc::appearance::AppearanceItem::Fill(f) = i { + f.paint = paint.clone(); + } + } + let mut outer = d.patterns[0].clone(); + outer.name = "outer".into(); + outer.art = vec![tile]; + d.patterns.push(outer); + for i in &mut d.node_mut(square).unwrap().appearance.items { + if let vectorcraft_doc::appearance::AppearanceItem::Fill(f) = i { + f.paint = vectorcraft_color::Paint::Pattern { pattern: "outer".into(), xf: Default::default() }; + } + } + s +} + +#[test] +fn pdf13_flattens_colorized_image_in_a_pattern_nested_in_tile_art() { + let mut s = nested_colorized_pattern_over_blue(); + assert_eq!(colour_at(&s.doc().unwrap().doc, 72.0, 72.0), [255, 0, 0]); + assert!(crate::cmd::flatten::flatten_document(&s.doc().unwrap().doc, &crate::cmd::FlattenOptions::default()).unwrap().is_some()); + assert_pdf13_draws_pattern_square_as_canvas(&mut s); +} + +#[test] +fn flattening_skips_a_pattern_nested_in_hidden_tile_art() { + let mut s = nested_colorized_pattern_over_blue(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let outer = d.pattern_mut("outer").unwrap(); + std::sync::Arc::make_mut(&mut outer.art[0]).visible = false; + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none()); +} + #[test] fn pdf13_leaves_a_hidden_shape_with_a_colorized_pattern_tile_image_hidden() { let mut s = colorized_pattern_over_blue(); From e2fddc6b127fc4728cecffb13fc9fc9693c1d52a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 04:11:26 -0700 Subject: [PATCH 05/70] PDF/EPS export: pattern fills whose tiles pass the object limit stay pattern fills The expansion counted the objects a pattern fill made only after making them, so one shape could clone up to 250,000 tile positions times the tile art's objects past the limit. Each fill now counts its tiles before they are made, and after outlining strokes and effects for turned or sheared tiles, and keeps room for the copy and group of the fills after it. A fill that does not fit stays a pattern fill. --- crates/engine/src/cmd/expand.rs | 86 ++++++++++++++++++++++------ crates/engine/src/tests/legacy_ai.rs | 55 ++++++++++++++++++ 2 files changed, 125 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index eec854a743..1b09fb6318 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -453,7 +453,7 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { /// first ([`expand_live_with_transparent_image_patterns`]). Hidden shapes and shapes in hidden /// groups or layers and in template layers stay as they are. A pattern fill in tile art counts /// too, down to the [`PATTERN_LEVELS`] the canvas draws, and the tile art the expansion makes is -/// expanded again for it. Pattern fills stay once the expanded art holds +/// expanded again for it. A pattern fill stays when its tiles would take the expanded art past /// [`MAX_GENERATED`](vectorcraft_doc::live::MAX_GENERATED) objects. Returns how many objects /// changed. pub(crate) fn expand_transparent_image_patterns( @@ -461,6 +461,18 @@ pub(crate) fn expand_transparent_image_patterns( root: NodeId, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, +) -> Result { + expand_transparent_image_patterns_within(d, root, see_through, colorize, vectorcraft_doc::live::MAX_GENERATED) +} + +/// [`expand_transparent_image_patterns`] with the art the pattern fills expand to held to `budget` +/// objects. Live art expands under its own budget ([`expand_live_with_transparent_image_patterns`]). +pub(crate) fn expand_transparent_image_patterns_within( + d: &mut Document, + root: NodeId, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + budget: usize, ) -> Result { let mut changed = 0; let made = std::cell::Cell::new(0usize); @@ -469,15 +481,21 @@ pub(crate) fn expand_transparent_image_patterns( let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize, levels)?; let (_, n) = replace_leaves(d, root, |d, l| { // Past the budget, and for most leaves, which have no pattern fill, skip the ancestry walk. - if made.get() >= vectorcraft_doc::live::MAX_GENERATED || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { + if made.get() >= budget || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { return None; } // The expanded art would be shown. if !d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).all(drawn) { return None; } - let art = expand_patterns_where(d, l, |d, i| transparent_pattern_fill(d, l, i, see_through, colorize, levels))?; - made.set(made.get().saturating_add(art.count())); + let which = |d: &Document, i: &AppearanceItem| transparent_pattern_fill(d, l, i, see_through, colorize, levels); + let art = expand_patterns_where(d, l, which, budget - made.get())?; + // The copies of the shape's other items count too. + let count = art.count_with_masks(); + if count > budget - made.get() { + return None; + } + made.set(made.get() + count); Some(art) })?; if live + n == 0 { @@ -650,12 +668,12 @@ fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet, colorize: /// ([`pattern_tiles`]). A pattern fill that lays no tile there stays. `None` when no pattern fill /// lays a tile. fn expand_patterns(d: &mut Document, l: &Node) -> Option { - expand_patterns_where(d, l, |_, _| true) + expand_patterns_where(d, l, |_, _| true, usize::MAX) } /// [`expand_patterns`] for only the pattern fills `which` picks: the others stay like the other -/// items. -fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool) -> Option { +/// items, as does a pattern fill whose tiles would take the tiles of `l` past `budget` objects. +fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool, budget: usize) -> Option { if !matches!(l.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some() && which(d, i)) { @@ -668,19 +686,47 @@ fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, & let mut parts = vec![]; let mut rest = vec![]; let mut expanded = false; + // What `assemble` adds around the tiles when every picked fill expands: a copy of the path for + // each run of other items, a group around the parts and one for the path's transparency, and + // the path's opacity mask. + let (mut copies, mut run, mut picked) = (0usize, false, vec![]); + for i in &l.appearance.items { + if let Some((f, _, _)) = pattern_fill(d, i).filter(|_| which(d, i)) { + run = false; + picked.push(f.opacity < 1.0 || f.blend != BlendMode::Normal); + } else if i.visible() && !i.paint().is_none() && !run { + (copies, run) = (copies + 1, true); + } + } + let group = copies + picked.len() > 1 || !l.appearance.effects.is_empty(); + // A lone tile group with transparency of its own goes in a group for the path's. + let transparency = blended(l) && !group && picked.first().is_some_and(|b| *b); + let around = copies.saturating_mul(l.count()) + usize::from(group) + usize::from(transparency) + l.count_with_masks().saturating_sub(l.count()); + let mut left = budget.saturating_sub(around); + // A fill that expands while others follow leaves room for the copy and group that those take + // if they don't fit, and once one doesn't fit, the ones after it stay too. + let (mut later, mut full) = (picked.len(), false); for item in &l.appearance.items { let fill = pattern_fill(d, item).filter(|_| which(d, item)).map(|(f, def, xf)| (f, def.clone(), xf)); - let tiles = fill.and_then(|(f, def, xf)| { + later -= usize::from(fill.is_some()); + let room = if later > 0 { left.saturating_sub(l.count() + 1) } else { left }; + let tiles = fill.filter(|_| !full).and_then(|(f, def, xf)| { let (fl, _, bounds) = fill_shape(l, item, &path, bounds)?; - let t = pattern_tiles(d, &def, xf, bounds); + let Some(t) = pattern_tiles(d, &def, xf, bounds, room) else { + full = true; + return None; + }; (!t.is_empty()).then_some((f, fl, t)) }); - let Some(art) = tiles.and_then(|(f, fl, t)| tile_art(d, &fl, f, &t)) else { + let art = tiles.and_then(|(f, fl, t)| tile_art(d, &fl, f, &t)); + full |= art.as_ref().is_some_and(|a| a.count_with_masks() > room); + let Some(art) = art.filter(|a| a.count_with_masks() <= room) else { if item.visible() && !item.paint().is_none() { rest.push(item.clone()); } continue; }; + left -= art.count_with_masks(); if !rest.is_empty() { parts.push(styled_copy(d, l, std::mem::take(&mut rest))); } @@ -707,30 +753,38 @@ fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, & /// not, and when it does more than move art that holds a symbol instance, whose strokes the canvas /// draws scaled with the tile and an instance does not scale. Random Transform effects and brushes /// that vary at random in the art are baked first ([`seeds_baked`], [`random_brushes_baked`]). -fn pattern_tiles(d: &mut Document, def: &PatternDef, xf: Affine, bounds: Rect) -> Vec { +/// `None` when the tiles would hold more than `budget` objects. +fn pattern_tiles(d: &mut Document, def: &PatternDef, xf: Affine, bounds: Rect, budget: usize) -> Option> { if !moves_only(xf) && def.art.iter().any(|a| has_instances(a)) { - return vec![]; + return Some(vec![]); } let Some(def) = seeds_baked(def) else { - return vec![]; + return Some(vec![]); }; let brushes = vectorcraft_brush::library(d); let def = random_brushes_baked(d, &brushes, def); let def = &*def; + let per_tile = def.art.iter().map(|a| a.count_with_masks()).sum::(); + if def.offsets_covering(xf.inverse().transform_rect_bbox(bounds)).len().saturating_mul(per_tile) > budget { + return None; + } let scaling = Scaling { strokes: true, effects: Some(vectorcraft_render::effects::scale_effect), patterns: true, ..Scaling::default() }; if scales_evenly(xf) && (moves_only(xf) || !def.art.iter().any(|a| has_geometry_effects(a))) { - return def.instances_in_with(xf, bounds, scaling); + return Some(def.instances_in_with(xf, bounds, scaling)); } if def.art.iter().any(|a| has_unbakeable_effects(a)) { - return vec![]; + return Some(vec![]); } let placed = Scaling { patterns: true, ..Scaling::default() }; let mut tiles = def.instances_in_with(Affine::IDENTITY, xf.inverse().transform_rect_bbox(bounds), placed); + // Outlined strokes and effects can make more objects than the art had. + let mut left = budget; for t in &mut tiles { *t = prepared(d, &brushes, t); + left = left.checked_sub(t.count_with_masks())?; place_art(t, xf, scaling); } - tiles + Some(tiles) } /// Pattern `def` with each path in its art (opacity masks included) that has a random Transform diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index ecac48bb7e..f038ab2514 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -705,6 +705,61 @@ fn only_the_transparent_pattern_fill_of_a_leaf_is_expanded() { assert!(images > 0); } +/// A pattern fill whose expanded art would hold more objects than the budget stays a pattern fill: +/// the 32 pt tiles over the 128 pt square are 25 copies of the tile art's 3 objects, which are not +/// made with a smaller budget, and the clip group around them counts too. +#[test] +fn a_transparent_image_pattern_past_the_budget_stays() { + let expand = |budget: usize| { + let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); + assert_eq!(s.doc().unwrap().doc.patterns[0].art.iter().map(|a| a.count_with_masks()).sum::(), 3); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let keys = crate::cmd::flatten::see_through_images(d); + let layer = d.layers[0].id; + let before = d.layers[0].count_with_masks(); + let n = crate::cmd::expand::expand_transparent_image_patterns_within(d, layer, &keys, &|_, _| true, budget).unwrap(); + // The objects the expansion made, with the square it replaced. + (n, images(d).0, d.layers[0].count_with_masks() + 1 - before) + }; + let (n, tiles, made) = expand(usize::MAX); + assert_eq!((n, tiles), (1, 25)); + assert!(made > 75, "{made}"); + assert_eq!(expand(made), (1, 25, made)); + assert_eq!(expand(made - 1).0, 0); + assert_eq!(expand(74).0, 0); +} + +/// On a shape with two transparent image pattern fills, both expand with a budget their tiles and +/// the group around them fit, and one expands with one object less. +#[test] +fn two_transparent_image_pattern_fills_expand_within_the_budget() { + let expand = |budget: usize| { + let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let mut square = None; + d.walk(|n| { + if n.appearance.items.iter().any( + |i| matches!(i, vectorcraft_doc::appearance::AppearanceItem::Fill(f) if matches!(f.paint, vectorcraft_color::Paint::Pattern { .. })), + ) { + square = Some(n.id); + } + }); + let n = d.node_mut(square.unwrap()).unwrap(); + assert_eq!(n.appearance.items.len(), 1); + let fill = n.appearance.items[0].clone(); + n.appearance.items.push(fill); + let keys = crate::cmd::flatten::see_through_images(d); + let layer = d.layers[0].id; + let before = d.layers[0].count_with_masks(); + let n = crate::cmd::expand::expand_transparent_image_patterns_within(d, layer, &keys, &|_, _| true, budget).unwrap(); + (n, images(d).0, d.layers[0].count_with_masks() + 1 - before) + }; + let (n, tiles, made) = expand(usize::MAX); + assert_eq!((n, tiles), (1, 50)); + assert_eq!(expand(made), (1, 50, made)); + assert_eq!(expand(made - 1).1, 25); +} + #[test] fn pdf13_flattens_see_through_pattern_tile_images() { let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); From a32a7cbb0d685471403764fc97e1e6cd8846fd7c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 04:27:09 -0700 Subject: [PATCH 06/70] PDF/EPS export: EPS export and PostScript printing expand pattern tile images once EPS export expanded the pattern fills whose tile images need flattening and then flattened the result with flatten_document, which expanded them again with a new object limit. PostScript printing did the same, on the layers shown rather than the layers that print. EPS export now flattens the expanded document without expanding it again (flatten_expanded), and PostScript printing leaves the expansion to the flattener, which runs on the layers that print, and only checks for such pattern fills to warn. --- crates/engine/src/cmd/fileio/eps.rs | 4 ++-- crates/engine/src/cmd/flatten.rs | 2 +- crates/engine/src/cmd/flatten/apply.rs | 24 +++++++++++++++++------- crates/engine/src/cmd/print.rs | 16 +++++++--------- crates/engine/src/tests/legacy_ai.rs | 9 +++++++++ 5 files changed, 36 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index 2c8ae4a845..d2424bf0a7 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -12,7 +12,7 @@ use vectorcraft_doc::Document; use vectorcraft_eps::{EpsOptions, Level, Overprint, Preview, Raster}; use vectorcraft_geom::{Point, Rect}; -use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_document}; +use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_expanded}; use super::super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; use super::{ArtboardPick, Encoded, FormatOption}; @@ -302,7 +302,7 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result { let expanded = expand_transparent_tile_images(doc, &set.flatten)?; let source = expanded.as_ref().unwrap_or(doc); let transparent = source.layers.iter().any(|l| set.flatten.shows_transparency(source, l)); - let flat = flatten_document(source, &set.flatten)?; + let flat = flatten_expanded(source, &set.flatten)?; let drawn = flat.as_ref().unwrap_or(source); let mut enc = Encoded { warnings, joiner: Some("_"), ..Encoded::default() }; if transparent && (flat.is_some() || expanded.is_some()) { diff --git a/crates/engine/src/cmd/flatten.rs b/crates/engine/src/cmd/flatten.rs index 94e05a3572..ccbe9c0493 100644 --- a/crates/engine/src/cmd/flatten.rs +++ b/crates/engine/src/cmd/flatten.rs @@ -49,7 +49,7 @@ mod presets; mod report; pub(crate) use analysis::{outlined_text, see_through_images}; -pub(crate) use apply::{expand_transparent_tile_images, flatten_document}; +pub(crate) use apply::{expand_transparent_tile_images, flatten_document, flatten_expanded, has_transparent_tile_images}; pub use commands::specs; pub use options::FlattenOptions; pub use presets::{FlattenerPreset, PRESET_EXTS, PRESET_FORMAT}; diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 0cd1ab159b..d229f1bbb8 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -292,16 +292,21 @@ pub(super) fn opaque(n: &mut Node) { } } +/// Whether `doc` has pattern fills whose image tiles need transparency flattening with `o` +/// ([`expand_transparent_tile_images`]). +pub(crate) fn has_transparent_tile_images(doc: &Document, o: &FlattenOptions) -> bool { + let keys = o.no_transparency.clone().unwrap_or_default(); + let colorize = |d: &Document, n: &Node| o.counts_colorize(d, n); + !doc.patterns.is_empty() && crate::cmd::expand::has_transparent_image_patterns(doc, &keys, &colorize) +} + /// Expand pattern fills whose image tiles need transparency flattening. pub(crate) fn expand_transparent_tile_images(doc: &Document, o: &FlattenOptions) -> Result> { - if doc.patterns.is_empty() { + if !has_transparent_tile_images(doc, o) { return Ok(None); } let keys = o.no_transparency.clone().unwrap_or_default(); let colorize = |d: &Document, n: &Node| o.counts_colorize(d, n); - if !crate::cmd::expand::has_transparent_image_patterns(doc, &keys, &colorize) { - return Ok(None); - } let mut d = doc.clone(); let layers: Vec = d.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })).map(|l| l.id).collect(); @@ -319,10 +324,15 @@ pub(crate) fn expand_transparent_tile_images(doc: &Document, o: &FlattenOptions) /// expanded when `o.no_transparency` counts them. `None` when nothing changes. pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result> { let expanded = expand_transparent_tile_images(doc, o)?; - let doc = expanded.as_ref().unwrap_or(doc); + Ok(flatten_expanded(expanded.as_ref().unwrap_or(doc), o)?.or(expanded)) +} + +/// [`flatten_document`] for `doc` whose pattern tile images were expanded already +/// ([`expand_transparent_tile_images`]). +pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result> { let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints; if !outlining && !doc.layers.iter().any(|l| o.shows_transparency(doc, l) || o.draws_see_through_image(l)) { - return Ok(expanded); + return Ok(None); } let mut roots = vec![]; for l in doc.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) { @@ -331,7 +341,7 @@ pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result Result { let flat = super::rasterfx::flatten_raster_effects(doc); let doc = flat.as_ref().unwrap_or(doc); let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite; - let expanded = if postscript && !bitmap { - let options = super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?; - options.as_ref().map(|o| expand_transparent_tile_images(doc, o)).transpose()?.flatten() - } else { - None - }; - let doc = expanded.as_ref().unwrap_or(doc); + // The flattener expands pattern fills whose tile images need flattening, in the layers that print. + let tile_images = postscript + && !bitmap + && super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)? + .is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o)); // Print as Bitmap and the flattener preset (Advanced) render and flatten it first. let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?; let path = str_param(p, "path"); @@ -210,7 +208,7 @@ fn print(s: &mut Session, p: &Value) -> Result { None => Level::default(), }; let mut warnings = vec![]; - if !bitmap && doc.layers.iter().any(|l| l.shows_transparency()) { + if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) { warnings.push("transparency is flattened into opaque art and images (PostScript has none): see flattenerPreset".to_string()); } if !set.color.profile.trim().is_empty() && set.output.mode == vectorcraft_pdf::OutputMode::Composite { diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index f038ab2514..1b0f7ad3f3 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -820,6 +820,15 @@ fn flattening_that_keeps_colorize_leaves_colorized_pattern_tile_images_alone() { assert!(crate::cmd::flatten::flatten_document(d, &o).unwrap().is_none(), "the pattern isn't expanded for a colorize paint alone"); } +/// EPS export expands pattern tile images once: flattening the expanded +/// document leaves the patterns the expansion kept, past its object limit, as they are. +#[test] +fn flattening_an_expanded_document_does_not_expand_patterns_again() { + let s = colorized_pattern_over_blue(); + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_expanded(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none()); +} + #[test] fn eps_flattens_colorized_image_in_a_see_through_pattern_tile_group_and_warns() { let mut s = colorized_pattern_over_blue(); From 93e27cafd341459b3861feba87470b00ce8fefa1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 04:33:50 -0700 Subject: [PATCH 07/70] PDF/EPS export: live art expanded for pattern tile images counts against the object limit Blends, envelopes, repeats and Intertwine groups that hold a pattern fill with a transparent tile image were each expanded under a limit of their own, so many of them together had no limit. Their art now counts toward the same limit as the pattern tiles, and an object whose art would pass it stays live. --- crates/engine/src/cmd/expand.rs | 26 +++++++++++++++++++------- crates/engine/src/tests/legacy_ai.rs | 16 ++++++++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 1b09fb6318..4745437d40 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -453,9 +453,9 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { /// first ([`expand_live_with_transparent_image_patterns`]). Hidden shapes and shapes in hidden /// groups or layers and in template layers stay as they are. A pattern fill in tile art counts /// too, down to the [`PATTERN_LEVELS`] the canvas draws, and the tile art the expansion makes is -/// expanded again for it. A pattern fill stays when its tiles would take the expanded art past -/// [`MAX_GENERATED`](vectorcraft_doc::live::MAX_GENERATED) objects. Returns how many objects -/// changed. +/// expanded again for it. A pattern fill stays, and a live object stays live, when its art would +/// take the expanded art past [`MAX_GENERATED`](vectorcraft_doc::live::MAX_GENERATED) objects. +/// Returns how many objects changed. pub(crate) fn expand_transparent_image_patterns( d: &mut Document, root: NodeId, @@ -465,8 +465,7 @@ pub(crate) fn expand_transparent_image_patterns( expand_transparent_image_patterns_within(d, root, see_through, colorize, vectorcraft_doc::live::MAX_GENERATED) } -/// [`expand_transparent_image_patterns`] with the art the pattern fills expand to held to `budget` -/// objects. Live art expands under its own budget ([`expand_live_with_transparent_image_patterns`]). +/// [`expand_transparent_image_patterns`] with the expanded art held to `budget` objects. pub(crate) fn expand_transparent_image_patterns_within( d: &mut Document, root: NodeId, @@ -478,7 +477,7 @@ pub(crate) fn expand_transparent_image_patterns_within( let made = std::cell::Cell::new(0usize); // Each pass brings the patterns in the expanded tiles' art up one level. for levels in (1..=PATTERN_LEVELS).rev() { - let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize, levels)?; + let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize, levels, &made, budget)?; let (_, n) = replace_leaves(d, root, |d, l| { // Past the budget, and for most leaves, which have no pattern fill, skip the ancestry walk. if made.get() >= budget || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { @@ -547,13 +546,17 @@ fn drawn(n: &Node) -> bool { /// Expand the shown blends, envelopes, repeats and Intertwine groups under `root` that hold a /// pattern fill [`holds_transparent_image_patterns`] counts with `levels` into the art the exporters write for /// them ([`expand_live_deep`](vectorcraft_render::effects::expand_live_deep), under one budget for -/// everything nested in each), so the shapes they draw are leaves. Returns how many were expanded. +/// everything nested in each), so the shapes they draw are leaves. The objects that art holds count +/// in `made`, and an object whose art would take `made` past `budget` stays live. Returns how many +/// were expanded. fn expand_live_with_transparent_image_patterns( d: &mut Document, root: NodeId, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, levels: u32, + made: &std::cell::Cell, + budget: usize, ) -> Result { fn outermost( d: &Document, @@ -592,10 +595,19 @@ fn expand_live_with_transparent_image_patterns( } let mut count = 0; for id in &live { + if made.get() >= budget { + break; + } let Some(n) = d.node(*id) else { continue }; // Random Transform effects take their seed from the ids: bake them first ([`bake_seeded`]), // and leave the object live when that can't be done. let Some(mut g) = bake_seeded(&vectorcraft_render::effects::expand_live_deep(Some(d), n)) else { continue }; + // An object whose art would take the expanded art past the budget stays live. + let size = g.count_with_masks(); + if size > budget - made.get() { + continue; + } + made.set(made.get() + size); g.id = *id; fresh_ids(d, &mut g); *d.node_mut(*id).ok_or(EngineError::NoNode(*id))? = g; diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 1b0f7ad3f3..90c728a2fc 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -919,6 +919,22 @@ fn pdf13_flattens_colorized_pattern_tile_images_in_a_repeat() { assert_pdf13_draws_pattern_square_as_canvas(&mut s); } +/// A repeat whose art would take the expanded art past the budget stays live. +#[test] +fn a_repeat_past_the_budget_stays_live() { + for (budget, live) in [(1, 1), (usize::MAX, 0)] { + let mut s = colorized_pattern_over_blue(); + let square = pattern_square(&s); + s.execute("object.repeat.grid", &json!({"ids": [square.0]})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let layer = d.layers[0].id; + crate::cmd::expand::expand_transparent_image_patterns_within(d, layer, &Default::default(), &|_, _| true, budget).unwrap(); + let mut repeats = 0; + d.walk(|n| repeats += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Repeat(_)))); + assert_eq!(repeats, live, "budget {budget}"); + } +} + /// [`colorized_pattern_over_blue`] with the square filled with a pattern named `outer` whose tile /// art is a 32 pt square filled with the colorized image pattern. fn nested_colorized_pattern_over_blue() -> Session { From bb6cbfb2b44ceeca70da27c80dcd5760b5e22de0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 18:37:09 -0700 Subject: [PATCH 08/70] Images: SVG and EPS export write colorized grayscale and 1-bit images in their fill color SVG export ignored an image's colorize paint and wrote the image's own black, white and gray pixels. EPS export flattened every colorized image into a process-color raster, so a spot color lost its plate. Both now write the image in the fill color, with the coverage the canvas and PDF export use (darkness times alpha), so white and transparent pixels take no color. - SVG writes a coverage PNG as a mask over a rectangle in the color, shared between repeated images while each keeps its own color. Linked mode writes the coverage PNG as a file, and SVG Tiny 1.2 writes a PNG in the color. A colorized image whose pixels are missing, or whose grayscale pixels can't be decoded, is left out with a warning. - EPS writes fully covered or uncovered pixels as an imagemask in the color's process or Separation ink (Registration on every plate), and a grayscale image as ink samples scaled by coverage. Level 3 masks its uncovered pixels out and Level 2 writes them white; gray midtones are written over white, with the existing warnings. - EPS flattening no longer counts a solid colorize paint on a grayscale or 1-bit image as transparency by itself. Opacity, blending modes, opacity masks, effects and overlapping transparent art still flatten it, and so does a colorize paint the writer can't draw. The svg crate's tests turn on resvg's raster-images feature to render the embedded PNGs. Docs: docs/mcp.md, docs/target-app-parity.md. --- Cargo.lock | 48 +++-- crates/engine/src/cmd/fileio/eps.rs | 2 + crates/engine/src/tests/colorize.rs | 32 ++++ crates/eps/src/scene.rs | 156 +++++++++++++++- crates/eps/src/tests.rs | 181 +++++++++++++++++++ crates/svg/Cargo.toml | 2 +- crates/svg/src/export.rs | 12 ++ crates/svg/src/export/nodes.rs | 13 ++ crates/svg/src/export/paint.rs | 131 +++++++++++++- crates/svg/tests/it/colorized_images.rs | 229 ++++++++++++++++++++++++ crates/svg/tests/it/main.rs | 1 + docs/mcp.md | 2 + docs/target-app-parity.md | 1 + 13 files changed, 795 insertions(+), 15 deletions(-) create mode 100644 crates/svg/tests/it/colorized_images.rs diff --git a/Cargo.lock b/Cargo.lock index a1512c6d0d..aeec6db30e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1940,6 +1940,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "gif" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b" +dependencies = [ + "color_quant", + "weezl 0.1.12", +] + [[package]] name = "gif" version = "0.14.2" @@ -2233,7 +2243,7 @@ dependencies = [ "rustc-hash 2.1.3", "smallvec", "stringprep", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -2609,14 +2619,14 @@ dependencies = [ "bytemuck", "byteorder-lite", "color_quant", - "gif", + "gif 0.14.2", "image-webp", "moxcms", "num-traits", "png 0.18.1", "tiff", - "zune-core", - "zune-jpeg", + "zune-core 0.5.3", + "zune-jpeg 0.5.15", ] [[package]] @@ -2837,7 +2847,7 @@ dependencies = [ "bumpalo", "flate2", "float-cmp", - "gif", + "gif 0.14.2", "image-webp", "imagesize 0.14.0", "indexmap", @@ -2852,7 +2862,7 @@ dependencies = [ "tiny-skia-path 0.12.0", "xmp-writer", "yoke", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -4380,12 +4390,15 @@ version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" dependencies = [ + "gif 0.13.3", + "image-webp", "log", "pico-args", "rgb", "svgtypes 0.15.3", "tiny-skia", "usvg 0.45.1", + "zune-jpeg 0.4.21", ] [[package]] @@ -5490,7 +5503,7 @@ dependencies = [ "half", "quick-error 2.0.1", "weezl 0.1.12", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -6169,7 +6182,7 @@ dependencies = [ "tiff", "vectorcraft-color", "vectorcraft-geom", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -6374,7 +6387,7 @@ name = "vectorcraft-render" version = "0.19.0" dependencies = [ "flate2", - "gif", + "gif 0.14.2", "image", "jpeg-encoder", "log", @@ -7950,19 +7963,34 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "zune-core" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" + [[package]] name = "zune-core" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-jpeg" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" +dependencies = [ + "zune-core 0.4.12", +] + [[package]] name = "zune-jpeg" version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" dependencies = [ - "zune-core", + "zune-core 0.5.3", ] [[package]] diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index d2424bf0a7..49ecfaa345 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -152,6 +152,8 @@ fn parse(p: &Value) -> Result { let overprint = choice("overprints", q.overprints.clone(), Overprint::from_id, d.overprint, "preserve or discard")?; let mut flatten = flattener(&q, &[])?; flatten.preserve_overprints &= overprint == Overprint::Preserve; + // The writer draws colorized images in their ink. + flatten.keeps_colorize = true; let level = q.level.as_ref().map(super::dxf::text); let eps = EpsOptions { level: choice("level", level, Level::from_id, d.level, "2 or 3")?, diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index bb9a9ac0f9..bcd590c2d4 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -379,6 +379,38 @@ fn colorized_gray_image_is_omitted_from_legacy_ai_when_requested() { assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]); } +#[test] +fn eps_export_writes_a_colorized_image_in_its_spot_ink_without_flattening() { + let mut s = session(); + let id = image(&mut s, "gray", gray(false)); + s.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [id.0]})).unwrap(); + let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + assert!(out["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]); + let bytes = vectorcraft_format::base64_decode(out["dataBase64"].as_str().unwrap()).unwrap(); + let ps = String::from_utf8_lossy(&bytes); + assert!(ps.contains("imagemask") && ps.contains("/Separation (Ink) cvn"), "the image prints on the Ink plate"); + assert!(ps.contains("%%DocumentCustomColors: (Ink)")); + + // Opacity still flattens it. + s.execute("transparency.set", &json!({"ids": [id.0], "opacity": 50})).unwrap(); + let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]); +} + +#[test] +fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() { + let mut s = session(); + let rgb = png(image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(2, 1, vec![0, 128, 255, 255, 0, 0]).unwrap())); + let id = image(&mut s, "rgb", rgb); + s.edit("Colorize", |d, _| { + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + Ok(()) + }) + .unwrap(); + let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]); +} + #[test] fn flattened_colorized_image_shows_the_art_under_white_pixels() { let mut s = session(); diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 83d3e7e01f..6e6ba05847 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -119,6 +119,8 @@ pub(crate) struct Scene<'a> { brushes: Option>, /// Image keys → what draws them (`None`: left out). images: HashMap>>, + /// The source key and solid paint together identify a colorized encoding. + colorized_images: HashMap<(String, String), Option>>, /// Symbols and brush art being written inside one another. nest: u32, } @@ -137,6 +139,7 @@ impl<'a> Scene<'a> { warnings: vec![], brushes: None, images: HashMap::new(), + colorized_images: HashMap::new(), nest: 0, } } @@ -297,7 +300,15 @@ impl<'a> Scene<'a> { self.shape(n, &bp, *rule); } NodeKind::Text(t) => self.text(n, t), - NodeKind::Image(im) => self.image(&im.key, self.doc.image_blob(im), im.width, im.height, im.xf), + NodeKind::Image(im) => { + let blob = self.doc.image_blob(im); + match n.extras().colorize.as_deref() { + Some(p @ Paint::Solid { .. }) if blob.is_none_or(|b| b.gray_source().is_some()) => { + self.colorized_image(&im.key, blob, im.width, im.height, im.xf, p); + } + _ => self.image(&im.key, blob, im.width, im.height, im.xf), + } + } NodeKind::SymbolInstance { symbol, xf } => { if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST @@ -886,6 +897,149 @@ impl<'a> Scene<'a> { } } + /// Gray coverage in the selected process or Separation ink. Binary coverage is a stencil; + /// continuous coverage leaves zero pixels untouched at Level 3 and writes them as paper at Level 2. + fn colorized_image(&mut self, key: &str, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, paint: &Paint) { + let place = xf * Affine::scale_non_uniform(f64::from(width.max(1)), f64::from(height.max(1))); + if !invertible(place) { + return; + } + let cache = (key.to_string(), format!("{paint:?}")); + let encoded = match self.colorized_images.get(&cache) { + Some(e) => e.clone(), + None => { + let e = self.encode_colorized(blob, paint).map(Arc::new); + self.colorized_images.insert(cache, e.clone()); + e + } + }; + if let Some(e) = encoded { + self.place_image(&e, place); + } + } + + fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option { + let Some((w, h, coverage)) = blob.and_then(ImageBlob::coverage) else { + self.warn(UNDECODED); + return None; + }; + if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_IMAGE_PIXELS { + self.warn(LARGE_IMAGE); + return None; + } + let Paint::Solid { color, swatch, tint } = paint else { return None }; + let ink = self.solid(color, swatch.as_deref(), *tint); + let binary = coverage.iter().all(|&v| v == 0 || v == 255); + let clear = coverage.contains(&0); + if coverage.iter().any(|&v| v > 0 && v < 255) { + self.warn(IMAGE_PARTLY); + } + let keyed = !binary && clear && self.o.level == Level::Three; + if !binary && clear && !keyed { + self.warn(IMAGE_ALPHA_L2); + } + // Zero tint is uncommon for covered spot pixels; process uses the same rare key as + // ordinary images. Nudge a covered collision so only clear pixels match the mask. + let key = match ink { + Ink::Spot { .. } => [0, 0, 0, 0], + Ink::Process(Space::Gray, ..) => [0, 0, 0, 0], + Ink::Process(..) => [255, 0, 255, 0], + }; + let mut data = Vec::new(); + if binary { + let stride = (w as usize).div_ceil(8); + data.resize(stride.saturating_mul(h as usize), 0); + for (i, &v) in coverage.iter().enumerate() { + if v == 255 + && let Some(byte) = data.get_mut((i / w as usize) * stride + (i % w as usize) / 8) + { + *byte |= 0x80 >> (i % w as usize % 8); + } + } + } else { + for &v in &coverage { + if v == 0 && keyed { + let n = match ink { + Ink::Spot { .. } => 1, + Ink::Process(space, ..) => space.n(), + }; + data.extend(key.iter().take(n)); + continue; + } + let a = f32::from(v) / 255.0; + match ink { + Ink::Spot { tint, .. } => { + let mut sample = (255.0 * tint * a).round() as u8; + if keyed && sample == key[0] { + sample = 1; + } + data.push(sample); + } + Ink::Process(space, components) => { + let paper = if space == Space::Cmyk { 0.0 } else { 1.0 }; + let n = space.n(); + let mut samples = [0; 4]; + for (sample, &component) in samples.iter_mut().zip(components.iter()).take(n) { + *sample = (255.0 * (paper + (component - paper) * a)).round() as u8; + } + if keyed && samples.iter().take(n).eq(key.iter().take(n)) { + samples[if n > 1 { 1 } else { 0 }] = 1; + } + data.extend(samples.iter().take(n)); + } + } + } + } + let (filter, encoded) = match self.o.level { + Level::Three => ("/FlateDecode", ps::deflate(&data)), + Level::Two => { + let mut rl = Vec::new(); + ps::packbits(&data, &mut rl); + rl.push(128); + ("/RunLengthDecode", rl) + } + }; + let mut out = String::new(); + if binary { + // imagemask takes its current ink from the graphics state. + out.push_str(&self.ink_code(ink)); + } else { + match ink { + Ink::Spot { space, .. } => { + let _ = writeln!(out, "VCsp{space} setcolorspace"); + } + Ink::Process(space, ..) => { + let _ = writeln!(out, "{} setcolorspace", space.name()); + } + } + } + let n = match ink { + Ink::Spot { .. } => 1, + Ink::Process(space, ..) => space.n(), + }; + let decode = if binary { "1 0".to_string() } else { "0 1 ".repeat(n).trim_end().to_string() }; + let _ = write!( + out, + "{{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]", + if keyed { 4 } else { 1 }, + if binary { 1 } else { 8 }, + ); + if keyed { + let mask: Vec = key.iter().take(n).map(|v| format!("{v} {v}")).collect(); + let _ = write!(out, " /MaskColor [{}]", mask.join(" ")); + } + let _ = writeln!(out, "\n/DataSource VCsrc {filter} filter >> {}\nVCsrc flushfile }} exec", if binary { "imagemask" } else { "image" }); + out.push_str(&ps::ascii85(&encoded)); + Some(out) + } + + /// Ink-setting operators in the cached stencil body, built with the same path as solid fills. + fn ink_code(&mut self, ink: Ink) -> String { + let body = std::mem::take(&mut self.body); + self.set_ink(ink); + std::mem::replace(&mut self.body, body) + } + /// Image `blob` as RGBA pixels; `None` (with a warning) when it can't be written. fn decode_image(&mut self, blob: Option<&ImageBlob>) -> Option { let Some(img) = blob.and_then(|blob| image::load_from_memory(&blob.bytes).ok()) else { diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 40eade3b59..c8271dda81 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -331,6 +331,187 @@ fn unpack(data: &[u8]) -> Vec { out } +fn colorized_doc(gray: Vec, paint: Option) -> Document { + let mut d = Document::new(200.0, 200.0); + d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), global: true, spot: true }); + let mut png = Vec::new(); + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(gray.len() as u32, 1, gray).unwrap()) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + d.images.insert("gray".into(), ImageBlob::png(png)); + let im = ImageObject { + key: "gray".into(), + width: 3, + height: 1, + xf: Affine::translate((10.0, 10.0)) * Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + n.extras_mut().colorize = paint.map(Box::new); + d.insert(d.default_layer(), 0, n).unwrap(); + d +} + +fn one_bit_blob() -> ImageBlob { + // Uncompressed two-pixel TIFF, BlackIsZero; black then white. + let entries: [(u16, u16, u32); 9] = + [(256, 3, 2), (257, 3, 1), (258, 3, 1), (259, 3, 1), (262, 3, 1), (273, 4, 122), (277, 3, 1), (278, 3, 1), (279, 4, 1)]; + let mut bytes = b"II*\0".to_vec(); + bytes.extend_from_slice(&8u32.to_le_bytes()); + bytes.extend_from_slice(&9u16.to_le_bytes()); + for (tag, kind, value) in entries { + bytes.extend_from_slice(&tag.to_le_bytes()); + bytes.extend_from_slice(&kind.to_le_bytes()); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&value.to_le_bytes()); + } + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.push(0b0100_0000); + ImageBlob::new("image/tiff", bytes) +} + +fn colorized_samples(d: &Document, level: Level) -> (String, Vec, Vec) { + let out = export(d, &EpsOptions { level, ..opts(d) }, None, None).unwrap(); + let ps = text(&out); + checked_page(&ps); + let encoded = image_data(&ps); + let samples = if level == Level::Three { ps::inflate(&encoded, 1 << 20).unwrap() } else { unpack(&encoded) }; + (ps, samples, out.warnings) +} + +#[test] +fn binary_colorized_images_are_ink_stencils_at_both_levels() { + for (paint, setup) in [ + (Paint::solid(Color::rgb8(255, 0, 0)), "1 0 0 rg"), + (Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 0.5 }, "VCsp0 setcolorspace 0.5 setcolor"), + (Paint::registration(), "VCsp0 setcolorspace 1 setcolor"), + ] { + let d = colorized_doc(vec![0, 255, 0], Some(paint.clone())); + for level in [Level::Two, Level::Three] { + let (ps, samples, warnings) = colorized_samples(&d, level); + assert!(ps.contains("imagemask") && ps.contains("/BitsPerComponent 1 /Decode [1 0]"), "{ps}"); + assert!(ps.contains(setup), "{ps}"); + assert_eq!(samples, vec![0b1010_0000]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(ps.contains(if level == Level::Two { "/RunLengthDecode" } else { "/FlateDecode" })); + if matches!(paint, Paint::Solid { swatch: Some(_), .. }) { + assert!(ps.contains("/Separation")); + } + if paint.is_registration() { + assert!(ps.contains("/All /DeviceCMYK")); + assert!(dsc(&ps, "DocumentCustomColors").is_none()); + } else if matches!(paint, Paint::Solid { swatch: Some(_), .. }) { + assert_eq!(dsc(&ps, "DocumentCustomColors").as_deref(), Some("(Ink)")); + } + } + } +} + +#[test] +fn one_bit_source_uses_the_same_stencil_coverage() { + let mut d = colorized_doc(vec![0, 255, 255], Some(Paint::solid(Color::rgb8(0, 0, 255)))); + d.images.insert("gray".into(), one_bit_blob()); + let id = d.layers[0].children().unwrap()[0].id; + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.width = 2; + } + assert!(d.images["gray"].gray_source().unwrap().one_bit); + let (_, samples, warnings) = colorized_samples(&d, Level::Three); + assert_eq!(samples, vec![0b1000_0000]); + assert!(warnings.is_empty()); +} + +#[test] +fn one_source_with_two_spot_tints_writes_two_inks() { + let first = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 }; + let mut d = colorized_doc(vec![0, 255, 0], Some(first)); + let mut n = (*d.layers[0].children().unwrap()[0]).clone(); + n.id = d.alloc_id(); + n.extras_mut().colorize = Some(Box::new(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 })); + d.insert(d.default_layer(), 1, n).unwrap(); + let ps = page_of(&d, &opts(&d)); + assert!(ps.contains("VCsp0 setcolorspace 1 setcolor") && ps.contains("VCsp0 setcolorspace 0.5 setcolor"), "{ps}"); + assert_eq!(ps.matches("imagemask").count(), 2); +} + +#[test] +fn gray_colorized_ramp_scales_process_and_spot_inks_over_paper() { + for level in [Level::Two, Level::Three] { + let process = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::rgb8(255, 0, 0)))); + let (ps, pixels, warnings) = colorized_samples(&process, level); + assert!(ps.contains("/DeviceRGB setcolorspace") && !ps.contains("imagemask")); + if level == Level::Three { + assert!(ps.contains("/ImageType 4") && ps.contains("/MaskColor [255 255 0 0 255 255]")); + assert_eq!(pixels, vec![255, 0, 0, 255, 128, 128, 255, 0, 255]); + assert_eq!(warnings, vec!["partly transparent image pixels are written over white"]); + } else { + assert!(ps.contains("/ImageType 1") && !ps.contains("/MaskColor")); + assert_eq!(pixels, vec![255, 0, 0, 255, 128, 128, 255, 255, 255]); + assert_eq!( + warnings, + vec![ + "partly transparent image pixels are written over white", + "transparent image pixels are written white at PostScript Level 2 (Level 3 masks them out)" + ] + ); + } + + let gray = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::gray(0.5)))); + let (ps, pixels, warnings) = colorized_samples(&gray, level); + assert!(ps.contains("/DeviceGray setcolorspace")); + assert_eq!(pixels, if level == Level::Three { vec![128, 192, 0] } else { vec![128, 192, 255] }); + assert_eq!(ps.contains("/MaskColor [0 0]"), level == Level::Three); + assert_eq!(warnings.len(), if level == Level::Three { 1 } else { 2 }); + + let spot = colorized_doc(vec![0, 128, 255], Some(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 })); + let (ps, pixels, warnings) = colorized_samples(&spot, level); + assert!(ps.contains("/Separation (Ink) cvn") && ps.contains("VCsp0 setcolorspace")); + assert_eq!(dsc(&ps, "DocumentCustomColors").as_deref(), Some("(Ink)")); + assert_eq!(pixels, vec![128, 64, 0]); + assert_eq!(ps.contains("/MaskColor [0 0]"), level == Level::Three); + assert_eq!(warnings.len(), if level == Level::Three { 1 } else { 2 }); + + let mut cmyk = process.clone(); + cmyk.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let (ps, pixels, _) = colorized_samples(&cmyk, level); + assert!(ps.contains("/DeviceCMYK setcolorspace")); + assert_eq!(pixels.len(), 12); + assert_eq!(&pixels[8..], if level == Level::Three { &[255, 0, 255, 0][..] } else { &[0, 0, 0, 0][..] }); + } +} + +#[test] +fn continuous_colorized_coverage_without_clear_pixels_only_warns_for_midtones() { + let d = colorized_doc(vec![0, 128, 254], Some(Paint::solid(Color::rgb8(255, 0, 255)))); + for level in [Level::Two, Level::Three] { + let (ps, pixels, warnings) = colorized_samples(&d, level); + assert!(ps.contains("/ImageType 1") && !ps.contains("/MaskColor")); + assert_eq!(&pixels[..3], &[255, 0, 255]); + assert_eq!(warnings, vec!["partly transparent image pixels are written over white"]); + } + let d = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::rgb8(255, 0, 255)))); + let (ps, pixels, _) = colorized_samples(&d, Level::Three); + assert!(ps.contains("/MaskColor [255 255 0 0 255 255]")); + assert_eq!(&pixels[..3], &[255, 1, 255]); + assert_eq!(&pixels[6..], &[255, 0, 255]); +} + +#[test] +fn uncolorized_image_stays_on_original_eps_path() { + let d = colorized_doc(vec![0, 128, 255], None); + let ps = page_of(&d, &opts(&d)); + assert!(!ps.contains("imagemask") && ps.contains("/ImageType 1")); + let patterned = colorized_doc(vec![0, 128, 255], Some(Paint::Pattern { pattern: "missing".into(), xf: Affine::IDENTITY })); + assert_eq!(page_of(&patterned, &opts(&patterned)), ps); + let mut color = png_doc(); + let original = page_of(&color, &opts(&color)); + let id = color.layers[0].children().unwrap()[0].id; + color.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + assert_eq!(page_of(&color, &opts(&color)), original); +} + #[test] fn run_length_and_ascii85_round_trip() { let cycle: Vec = (0..=255u8).cycle().take(1000).collect(); diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 27be13e207..6ef3b64ddf 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -34,7 +34,7 @@ svgtypes = "0.16" skrifa = { workspace = true } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } -resvg = { version = "0.45", default-features = false } +resvg = { version = "0.45", default-features = false, features = ["raster-images"] } # usvg as a reference viewer that lays text out in a font (text_layout.rs). usvg = { workspace = true, features = ["text"] } vectorcraft-testkit = { workspace = true } diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 1da24959ca..b9cd372eae 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -107,11 +107,17 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: symbol_nest: 0, fonts: Vec::new(), shared_images: HashMap::new(), + colorized_counts: HashMap::new(), + colorized_hrefs: HashMap::new(), + shared_colorized: HashMap::new(), layer_nest: 0, non_latin1_names: false, foreign_ns: BTreeMap::new(), }; w.assign_name_ids(); + for layer in &doc.layers { + w.count_colorized_images(layer); + } // Page Isolated Blending / Page Knockout Group: the page content is one isolated group. let page_group = doc.page_isolate || doc.page_knockout; if page_group { @@ -216,6 +222,8 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: Output { svg: out, linked: w.linked, warnings: w.warnings, encoding } } +type ColorizedKey = (String, u32, u32, Option<[u8; 3]>); + struct Writer<'a> { doc: &'a Document, opts: &'a ExportOptions, @@ -268,6 +276,10 @@ struct Writer<'a> { /// Images written once in the defs and drawn with ``, by key and size: the pieces an /// envelope cuts a distorted image into share its pixels. shared_images: HashMap<(String, u32, u32), String>, + /// Counts and generated PNG hrefs for gray images, keyed by source, size and baked RGB. + colorized_counts: HashMap, + colorized_hrefs: HashMap, + shared_colorized: HashMap, /// Layers being written inside one another (more than one: a sublayer). layer_nest: usize, /// An emitted attribute name requires an encoding wider than Latin-1. diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index 16722d9395..e88ad85098 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -117,6 +117,7 @@ fn pin_to_page(n: &mut Node, m: Affine) { /// What SVG Tiny 1.2 does without masks. const TINY_MASKS: &str = "SVG Tiny 1.2 has no masks: opacity masks are left out and knockout groups written as plain groups"; +pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; /// A region covering any artwork (mask and filter extents). const BIG: &str = "x=\"-100000\" y=\"-100000\" width=\"200000\" height=\"200000\""; @@ -565,6 +566,18 @@ impl Writer<'_> { } NodeKind::Text(t) => self.text_node(n, t), NodeKind::Image(im) => { + if let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() + && let Some(blob) = self.doc.image_blob(im) + && blob.gray_source().is_some() + { + self.colorized_image(n, im, *color, blob); + return; + } + if matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })) && self.doc.image_blob(im).is_none_or(|b| b.bytes.is_empty()) { + // Missing pixels cannot show the original file in place of a colorized image. + self.warn(UNDECODED); + return; + } let id = self.id_attr(n); let m = self.matrix(self.xf * im.xf); let mut props = css::transparency(n); diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index b21d45eb62..462387d70f 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -1,9 +1,9 @@ -use super::nodes::{MASK, doc_path}; +use super::nodes::{MASK, UNDECODED, doc_path}; use super::output::sanitize_id; use super::{ Affine, BezPath, BlendMode, Color, FillLayer, FillRule, GradientKind, GradientPaint, HashMap, ImageBlob, ImageMode, LineCap, LineJoin, - LinkedImage, Node, NodeKind, Paint, PathData, Point, Props, Rect, StrokeAlign, StrokeLayer, Writer, Written, base64_encode, blend_css, fmt_num, - stroke, xml_escape, + LinkedImage, Node, NodeKind, Paint, PathData, Point, Props, Rect, StrokeAlign, StrokeLayer, Writer, Written, base64_encode, blend_css, css, + fmt_num, stroke, xml_escape, }; /// Image `b` as SVG viewers show it: PNG, JPEG, GIF, WebP and SVG as they are, other formats (a @@ -38,6 +38,125 @@ pub(super) enum StrokePlan { } impl Writer<'_> { + pub(super) fn count_colorized_images(&mut self, art: &Node) { + art.walk(&mut |n| { + let NodeKind::Image(im) = &n.kind else { return }; + let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() else { return }; + if self.doc.image_blob(im).is_none_or(|blob| blob.gray_source().is_none()) { + return; + } + let key = self.colorized_key(im, *color); + *self.colorized_counts.entry(key).or_default() += 1; + }); + } + + fn colorized_key(&self, im: &vectorcraft_doc::ImageObject, color: Color) -> super::ColorizedKey { + let rgb = color.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + (im.key.clone(), im.width, im.height, self.tiny().then_some(rgb)) + } + + /// Colorize the decoded gray pixels without changing the source blob. The white pixels of the + /// coverage image contribute their alpha to an alpha mask; Tiny uses the same alpha in RGBA. + pub(super) fn colorized_image(&mut self, n: &Node, im: &vectorcraft_doc::ImageObject, color: Color, blob: &ImageBlob) { + let key = self.colorized_key(im, color); + let rgb = color.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + let href = if let Some(href) = self.colorized_hrefs.get(&key) { + href.clone() + } else { + let Some((width, height, coverage)) = blob.coverage() else { + self.warn(UNDECODED); + return; + }; + if u64::from(width) + .checked_mul(u64::from(height)) + .and_then(|pixels| pixels.checked_mul(4)) + .is_none_or(|bytes| bytes > vectorcraft_doc::MAX_RASTER_ALLOC) + { + self.warn(UNDECODED); + return; + } + let mut rgba = Vec::with_capacity(coverage.len().saturating_mul(4)); + for alpha in coverage { + rgba.extend_from_slice(&if self.tiny() { [rgb[0], rgb[1], rgb[2], alpha] } else { [255, 255, 255, alpha] }); + } + let Some(pixels) = image::RgbaImage::from_raw(width, height, rgba) else { + self.warn(UNDECODED); + return; + }; + let mut png = Vec::new(); + if pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { + self.warn(UNDECODED); + return; + } + let href = self.blob_href(&ImageBlob::png(png)); + self.colorized_hrefs.insert(key.clone(), href.clone()); + href + }; + let shared = if self.opts.images == ImageMode::Embed && self.colorized_counts.get(&key).is_some_and(|count| *count > 1) { + if let Some(id) = self.shared_colorized.get(&key) { + Some(id.clone()) + } else { + let id = self.fresh_id("colorize-image"); + self.def( + 0, + &format!( + "", + im.width, + im.height, + xml_escape(&href) + ), + ); + self.shared_colorized.insert(key, id.clone()); + Some(id) + } + } else { + None + }; + let id = self.id_attr(n); + let transform = self.matrix(self.xf * im.xf); + let outer = self.attrs(&css::transparency(n)); + let sampling = if n.extras().pixelated { " image-rendering=\"pixelated\"" } else { "" }; + if self.tiny() { + if let Some(shared) = shared { + self.line(&format!("")); + } else { + self.line(&format!( + "", + im.width, im.height, xml_escape(&href) + )); + } + return; + } + let mask = self.fresh_id("colorize-mask"); + let size = Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)); + let b = (self.xf * im.xf).transform_rect_bbox(size).inflate(1.0, 1.0); + let (x, y, w, h) = (self.num(b.x0), self.num(b.y0), self.num(b.width()), self.num(b.height())); + self.def(1, &format!("")); + if let Some(shared) = shared { + self.def(2, &format!("")); + } else { + self.def( + 2, + &format!( + "", + im.width, + im.height, + xml_escape(&href) + ), + ); + } + self.def(1, ""); + self.line(&format!("")); + self.depth += 1; + self.line(&format!("")); + self.depth += 1; + self.line(&format!("", im.width, im.height, color.to_hex())); + self.depth -= 1; + self.line(""); + self.depth -= 1; + self.line(""); + } + /// The `href` of image `im`: its file with [`ImageMode::Link`] (or when its pixels are /// missing), else its bytes. `None` when it has neither. pub(super) fn image_href(&mut self, im: &vectorcraft_doc::ImageObject) -> Option { @@ -52,10 +171,16 @@ impl Writer<'_> { /// Images drawn more than once in `art` (the pieces of a distorted image) go into the defs /// once; each piece then draws them with ``. pub(super) fn share_images(&mut self, art: &Node) { + self.count_colorized_images(art); // Each image's count and its first piece, which shows what they all show. let mut seen: HashMap<(String, u32, u32), (usize, vectorcraft_doc::ImageObject)> = HashMap::new(); art.walk(&mut |c| { if let NodeKind::Image(im) = &c.kind { + if matches!(c.extras().colorize.as_deref(), Some(Paint::Solid { .. })) + && self.doc.image_blob(im).is_none_or(|b| b.gray_source().is_some()) + { + return; + } seen.entry((im.key.clone(), im.width, im.height)).or_insert_with(|| (0, (**im).clone())).0 += 1; } }); diff --git a/crates/svg/tests/it/colorized_images.rs b/crates/svg/tests/it/colorized_images.rs new file mode 100644 index 0000000000..d3590977f2 --- /dev/null +++ b/crates/svg/tests/it/colorized_images.rs @@ -0,0 +1,229 @@ +//! Colorized gray and bilevel image export, checked as pixels as well as markup. + +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::{Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind}; +use vectorcraft_geom::Affine; +use vectorcraft_svg::{ExportOptions, ImageMode, Profile, base64_encode, export_full}; + +fn bilevel() -> Vec { + let entries: [(u16, u16, u32); 9] = + [(256, 3, 2), (257, 3, 1), (258, 3, 1), (259, 3, 1), (262, 3, 1), (273, 4, 122), (277, 3, 1), (278, 3, 1), (279, 4, 1)]; + let mut out = b"II*\0".to_vec(); + out.extend_from_slice(&8u32.to_le_bytes()); + out.extend_from_slice(&9u16.to_le_bytes()); + for (tag, kind, value) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&kind.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&0u32.to_le_bytes()); + out.push(0b0100_0000); + out +} + +fn png(img: image::DynamicImage) -> Vec { + let mut out = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +fn document(bytes: Vec, paint: Option) -> Document { + let mut d = Document::new(80.0, 40.0); + d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::rgb8(255, 0, 0)), global: true, spot: true }); + d.images.insert("source".into(), ImageBlob::new("image/tiff", bytes)); + let im = ImageObject { + key: "source".into(), + width: 2, + height: 1, + xf: Affine::translate((10.0, 10.0)) * Affine::scale(20.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + n.extras_mut().pixelated = true; + n.extras_mut().colorize = paint.map(Box::new); + d.insert(d.default_layer(), 0, n).unwrap(); + d +} + +fn rendered(svg: &str) -> ([u8; 4], [u8; 4]) { + let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).unwrap(); + let mut pixmap = resvg::tiny_skia::Pixmap::new(80, 40).unwrap(); + pixmap.fill(resvg::tiny_skia::Color::WHITE); + resvg::render(&tree, resvg::tiny_skia::Transform::identity(), &mut pixmap.as_mut()); + let sample = |x| { + let p = pixmap.pixel(x, 15).unwrap().demultiply(); + [p.red(), p.green(), p.blue(), p.alpha()] + }; + (sample(15), sample(45)) +} + +fn samples(svg: &str, points: &[(u32, u32)]) -> Vec<[u8; 4]> { + let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).unwrap(); + let mut pixmap = resvg::tiny_skia::Pixmap::new(80, 40).unwrap(); + pixmap.fill(resvg::tiny_skia::Color::WHITE); + resvg::render(&tree, resvg::tiny_skia::Transform::identity(), &mut pixmap.as_mut()); + points + .iter() + .map(|&(x, y)| { + let p = pixmap.pixel(x, y).unwrap().demultiply(); + [p.red(), p.green(), p.blue(), p.alpha()] + }) + .collect() +} + +#[test] +fn repeated_colorized_source_shares_coverage_but_keeps_instance_paint() { + let mut d = document(bilevel(), Some(Paint::solid(Color::rgb8(255, 0, 0)))); + let first_id = d.layers[0].children().unwrap()[0].id; + if let NodeKind::Image(im) = &mut d.node_mut(first_id).unwrap().kind { + im.xf = Affine::translate((10.0, 10.0)) * Affine::scale(10.0); + } + for (i, color) in [(1, Color::rgb8(0, 0, 255)), (2, Color::rgb8(255, 0, 0))] { + let mut next = (*d.layers[0].children().unwrap()[0]).clone(); + next.id = d.alloc_id(); + next.extras_mut().colorize = Some(Box::new(Paint::solid(color))); + if let NodeKind::Image(im) = &mut next.kind { + im.xf = Affine::translate((10.0 + f64::from(i) * 25.0, 10.0)) * Affine::scale(10.0); + } + d.insert(d.default_layer(), i as usize, next).unwrap(); + } + for profile in [Profile::Svg11, Profile::Tiny12] { + let svg = export_full(&d, &ExportOptions { profile, artboard: Some(0), ..Default::default() }, None).svg; + let png_count = svg.matches("data:image/png;base64,").count(); + assert_eq!(png_count, if profile == Profile::Svg11 { 1 } else { 2 }, "{svg}"); + assert_eq!(svg.matches(""#.to_vec(); + for (bytes, mime) in [(svg_source, "image/svg+xml"), (vec![1, 2, 3], "image/tiff")] { + let mut d = document(bytes, None); + d.images.get_mut("source").unwrap().mime = mime.into(); + let before = export_full(&d, &ExportOptions { artboard: Some(0), ..Default::default() }, None); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + let after = export_full(&d, &ExportOptions { artboard: Some(0), ..Default::default() }, None); + assert!(after.svg.contains("` with a `` per instance. An instance the def can't stand for is written as its own art: one stained by its fill; one scaled while the symbol has strokes (their weight doesn't scale), or rotated or @@ -4038,6 +4039,7 @@ is accepted); spot colours are Separation colour spaces, and overprinting fills `overprints: "discard"`. RGB documents are written in CMYK unless `cmykPostScript: false`. When the file would hold an image that can't be decoded, the image is left out, and `warnings` carries "an image couldn't be decoded and is missing from the picture" once for all such images. +Colorized grayscale and 1-bit images use their process or spot ink; the flattener leaves them alone unless they have opacity, a blending mode, an opacity mask or effects, or overlap other transparent art. Binary coverage leaves underlying art untouched. For a grayscale image, Level 3 leaves white (zero-coverage) pixels out, Level 2 writes them white, and gray midtones are written over white at both levels. PostScript has no transparency: it is flattened first with `flattenerPreset` (`high`, `medium` (default), `low` or a saved preset, see `flattener.presets.list`) and `flattener: {…}` options over it (those of diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0699ef5bc6..e7e1bbc5f6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -927,6 +927,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged. - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. + - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. SVG writes the fill color through a coverage mask (or a colorized PNG in Tiny 1.2); EPS writes binary coverage as an image mask in the color's ink, and a grayscale image as ink samples scaled by coverage, with white pixels left out at Level 3 and gray midtones written over white. The prompt for deleting several swatches and groups uses the interface language's plural form for the count. Evidence: `deleting_several_swatches_uses_each_count_form` in `crates/ui-egui/src/panels/swatches/tests.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. From d6297dbfb9ed13dbe71f1c924acc91d489a02fb8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 00:35:35 +0700 Subject: [PATCH 09/70] .ai import: type comes from the text document alone when every shown story reads Squashed from #4865 onto main. --- crates/engine/tests/import_fuzz.rs | 117 +++++++ crates/eps/src/import/ate.rs | 38 ++- crates/eps/src/import/native.rs | 49 ++- crates/eps/src/import/native/build.rs | 79 +++-- crates/eps/src/import/native/compare.rs | 135 ++++++-- crates/eps/src/import/native/plan.rs | 316 +++++++++++++------ crates/eps/src/import/native/slots.rs | 41 +-- crates/eps/src/import/tests_native.rs | 402 +++++++++++++++++++++--- docs/file-format-parity.md | 3 +- docs/target-app-parity.md | 5 +- 10 files changed, 962 insertions(+), 223 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 0f096b62ad..12eaf13d64 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2784,9 +2784,126 @@ fn text_eps_of(document: &str, objects: &str) -> Vec { editing_eps(&editing) } +/// A text document of `kinds.len()` stories, story `i` in frame `i` of kind `kinds[i]` (0 point type, +/// 1 area type, 2 type on a path, others a kind the reader doesn't know), with a line break inside +/// its paragraph (`\x03`) at each of `soft` (by character, wrapping, the story's end included) and +/// its paragraph runs `runs` characters long (the whole story when there are none). +fn stories_document_text(kinds: &[u8], soft: &[usize], runs: &[usize]) -> String { + let frames: Vec = kinds + .iter() + .enumerate() + .map(|(i, kind)| { + // Six rows 15 apart on the page (the canvas is y down), then the same rows again a little + // to the right. + let (x, y) = (8150.0 + (i / 6) as f64 * 5.0, 8150.0 + (i % 6) as f64 * 15.0); + match kind { + 0 => format!("<< /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 {x} {y} ] >> >> >>"), + 1 => format!( + "<< /0 << /0 [ 0 0 ] /1 << /0 [ {x} {y} {x} {y} {0} {y} {0} {y} {0} {y} {0} {y} {0} {1} {0} {1} {0} {1} {0} {1} {x} {1} {x} {1} ] >> /2 << /0 1 >> >> >>", + x + 70.0, + y + 12.0 + ), + 2 => format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {x} {y} {x} {y} {0} {y} {0} {y} ] >> /2 << /0 2 /6 [ 0 0.9 ] >> >> >>", x + 70.0), + k => format!("<< /0 << /0 [ 0 0 ] /2 << /0 {k} /2 [ 1 0 0 1 {x} {y} ] >> >> >>"), + } + }) + .collect(); + let stories: Vec = (0..kinds.len()) + .map(|i| { + let mut chars: Vec = format!("Line {i} one two\rand three\r").chars().collect(); + for at in soft { + chars.insert(at % (chars.len() + 1), '\x03'); + } + let n = chars.len(); + let text: String = chars.iter().map(|c| match c { + '\r' => "\\r".to_string(), + '\x03' => "\\003".to_string(), + c => c.to_string(), + }).collect(); + let lengths: Vec = if runs.is_empty() { vec![n] } else { runs.to_vec() }; + let paras: String = lengths + .iter() + .enumerate() + .map(|(j, len)| format!("<< /0 << /0 << /0 () /5 << /0 {} /2 2 /4 {j} >> /6 0 >> >> /1 {len} >> ", j % 3)) + .collect(); + format!( + "<< /0 << /0 ({text}) /5 << /0 [ {paras}] >> /6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /1 8.0 >> >> >> /1 {n} >> ] >> >> /1 << /0 [ << /0 {i} >> ] >> >>" + ) + }) + .collect(); + format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ {} ] >> >>\n/1 << /1 [ {} ] /2 << /1 12.0 >> >>\n", + frames.join(" "), + stories.join(" ") + ) +} + +/// An EPS whose page draws `page` (PostScript), with the text `objects` on a layer that shows and +/// the stories in `document`. +fn shown_text_eps(document: &str, objects: &str, page: &str) -> Vec { + let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let editing = format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\ + %AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(Words) Ln\n{objects}LB\n%AI5_EndLayer--\n\ + %AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n", + lines.join("\n") + ); + let stream = ascii85(&zstd(&editing)); + let private: Vec = stream.as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n0 0 0 1 setcmykcolor /Helvetica findfont 8 scalefont setfont {page}\nshowpage\n%%EOF\n%AI9_PrivateDataBegin\n%AI24_DataStream\n{}\n%AI9_PrivateDataEnd\n", + private.join("\n") + ) + .into_bytes() +} + +/// The page of [`stories_document_text`]'s first story's first line, at its place. +const FIRST_LINE: &str = "8.5 91.5 moveto (Line 0 one two) show"; + +/// The text objects of `pairs` (story, frame among the story's). +fn story_objects(pairs: &[(u32, u32)]) -> String { + pairs.iter().map(|(story, frame)| format!("/AI11Text :\n{frame} /FrameIndex ,\n{story} /StoryIndex ,\n;\n")).collect() +} + +/// The fixture, as it is (point type, area type and type on a path, a line break inside each +/// paragraph), opens with its layers and every story's type from its text document. +#[test] +fn the_shown_stories_fixture_opens_with_its_layers() { + let doc = stories_document_text(&[0, 1, 2], &[4], &[]); + // Each story's first line where the page draws it: the area type's below its frame's top, the + // type on a path on its path. + let page = format!("{FIRST_LINE} 8.5 69.5 moveto (Line 1) show 8.5 61.5 moveto (Line 2) show"); + let l = vectorcraft_engine::cmd::fileio::load("x.eps", &shown_text_eps(&doc, &story_objects(&[(0, 0), (1, 0), (2, 0)]), &page)).unwrap(); + let names: Vec<_> = l.doc.layers.iter().map(|l| l.name.clone()).collect(); + assert_eq!(names, [Some("Words".to_string())], "{:?}", l.warnings); + let mut texts = vec![]; + l.doc.walk(|n| { + if let vectorcraft_doc::NodeKind::Text(t) = &n.kind { + texts.push(t.plain_text()); + } + }); + assert_eq!(texts.len(), 3, "{texts:?} {:?}", l.warnings); + assert!(texts.iter().all(|t| t.contains('\u{2028}') && t.contains('\n')), "{texts:?}"); +} + proptest! { #![proptest_config(config())] + /// An Illustrator EPS with text objects that show, in frames of every kind and some the reader + /// doesn't know, naming stories and frames that may not exist, with line breaks inside their + /// paragraphs and paragraph runs of any length: read as its layers, or as its page. + #[test] + fn eps_shown_stories_never_panic( + kinds in prop::collection::vec(0u8..4, 1..20), + pairs in prop::collection::vec((0u32..24, 0u32..3), 1..24), + soft in prop::collection::vec(0usize..40, 0..5), + runs in prop::collection::vec(0usize..40, 0..5), + ) { + let kinds: Vec = kinds.into_iter().map(|k| if k == 3 { 9 } else { k }).collect(); + let bytes = shown_text_eps(&stories_document_text(&kinds, &soft, &runs), &story_objects(&pairs), FIRST_LINE); + survive("EPS with shown stories", || vectorcraft_engine::cmd::fileio::load("x.eps", &bytes).ok().map(|l| l.doc))?; + } + /// An Illustrator EPS whose text document is damaged or hostile: read as its type, or without it. #[test] fn eps_text_document_never_panics(cut in 0usize..1_500, edits in prop::collection::vec((0usize..1_500, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '<', '>', '\\', 'e', '1'])), 0..12)) { diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 6ad647cad3..60273bb508 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -8,9 +8,9 @@ //! The format isn't documented. What is read here was worked out from the files of the project's //! users, used locally and never committed, by comparing it with the type their pages draw: the //! meaning of each key below was checked against the page's own type in more than a thousand text -//! objects, and it is only used for the keys that matched. A story the reader doesn't recognise (area -//! type, type on a path, anything with a frame that has more than a point and a matrix) is left -//! alone: it has no text, and the importer says so. +//! objects, and it is only used for the keys that matched. Point type, area type and type on a path +//! are read; a story in a frame of any other kind is left alone: it has no text, and the importer +//! says so. //! //! Where type sits: a story lays its lines out round a point `F` (the anchor: the start of a line of //! left-aligned type, the middle of a centred one, the end of a right-aligned one), each line with an @@ -654,11 +654,6 @@ impl Story { self.text.len() } - /// The story's characters, with `\r` ending paragraphs and `\x03` ending lines. - pub(super) fn text(&self) -> &str { - &self.text - } - /// The point frame's matrix (the first frame's, when it is one), else the identity. fn matrix(&self) -> [f64; 6] { match self.frames.first() { @@ -749,10 +744,20 @@ impl Story { (1.0, Affine::IDENTITY, TextKind::OnPath { path: path_of(segments, template, to_doc), start: length_fraction(segments, *start), end }) } }; + // A `\x03` ends a line inside its paragraph: a forced line break (U+2028), which the + // paragraph's style runs over. let text: String = if threaded { String::new() } else { - self.text.trim_end_matches('\r').chars().map(|c| if matches!(c, '\r' | '\x03') { '\n' } else { c }).collect() + self.text + .trim_end_matches('\r') + .chars() + .map(|c| match c { + '\r' => '\n', + '\x03' => '\u{2028}', + c => c, + }) + .collect() }; if text.trim().is_empty() && !threaded { return None; @@ -1253,6 +1258,21 @@ mod tests { assert_eq!(story("one\r", &[0.0], &Para::default()).line_leading(1.0), None); } + /// A `\x03` ends a line inside its paragraph: it comes in as a forced line break, and the + /// paragraph's style runs over it to the paragraph's end. + #[test] + fn a_soft_return_is_a_line_break_in_its_paragraph() { + let para = Para { space_before: 4.0, space_after: 2.0, first_indent: 6.0, ..Para::default() }; + let mut s = story("A\x03B\rC\r", &[0.0, 15.6, 31.2], ¶); + s.paras[1].1 = Para { left_indent: 3.0, ..para.clone() }; + let node = s.node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY).unwrap(); + let NodeKind::Text(t) = &node.kind else { panic!("not text") }; + assert_eq!(t.plain_text(), "A\u{2028}B\nC"); + assert_eq!(t.paras.len(), 2, "{:?}", t.paras); + assert_eq!((t.paras[0].first_line_indent, t.paras[0].left_indent, t.paras[0].space_before), (6.0, 0.0, 4.0)); + assert_eq!((t.paras[1].first_line_indent, t.paras[1].left_indent), (6.0, 3.0)); + } + #[test] fn a_frame_too_short_for_its_first_line_is_made_taller() { // A heading in a frame as tall as its size: a line of the font it shows in here is taller. diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index 42f968faa5..efbb8a3a11 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -12,10 +12,12 @@ //! colours, gradients, transparency and images of the art. //! //! Text objects are slots in that document: their characters, fonts and places are in the file's -//! text document (see `ate`). Type that shows comes from the page, which draws it, into the slot -//! whose text is where the page has it. Type that doesn't show (a hidden layer or object, or off -//! the page) is made from the text document; where that can't be read (area type, type on a path) -//! it's left out, with a warning. +//! text document (see `ate`). When the text document has the type of every text object that shows, +//! all the type is made from it, each text object in its own place, and the page's type is only +//! compared with it. Otherwise the type it has is still made from it, and the page's type that +//! lies elsewhere goes into the text objects it can't make, by where the text document puts their +//! lines or else in painting order. A text object whose type neither has (a frame of a kind it +//! doesn't read, on a hidden layer or object) is left out, with a warning. //! //! What a layer that shows has that `ai` doesn't read makes the file come in as its page, as it did //! before; on a layer that doesn't show it is left out of that layer, with a warning. The page is @@ -46,7 +48,9 @@ mod slots; #[cfg(test)] use build::{Frame, MADE, prune_unseen}; #[cfg(test)] -use compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour}; +use compare::{ + MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour, +}; pub use layers::{ai_alone, layered_ai}; pub(super) use layers::{layered, program_alone}; pub use slots::is_loss; @@ -88,7 +92,7 @@ mod tests { let rect = page.artboards[0].rect; let frame = Frame { page: &page, page_rect: rect, rect, whole: false }; let mut view = PageView::new(&frame); - assert_eq!(prune_unseen(&frame, &mut view, &mut layers), 1, "only the ring the page doesn't draw"); + assert_eq!(prune_unseen(&frame, &mut view, &mut layers, false), 1, "only the ring the page doesn't draw"); let widths: Vec = layers.layers[0].children().unwrap().iter().filter_map(|n| n.appearance.stroke().map(|s| s.width)).collect(); assert_eq!(widths, [12.0, 6.0]); // Taken by lightness alone, the red and the dark red are alike. @@ -99,6 +103,33 @@ mod tests { assert!(!differ(&px(dark), &px(red)) && differ_in_colour(&px(dark), &px(red))); } + /// The share of a rectangle's pixels in the areas, however many areas there are: none for one + /// that only shares their edge, lies off the drawing or isn't a number. + #[test] + fn the_share_of_a_rectangle_in_the_areas_counts_its_pixels() { + let in_areas = |areas: &[Rect], w: usize, h: usize| { + let marks: Vec = (0..w * h) + .map(|k| { + let (x, y) = ((k % w) as f64 + 0.5, (k / w) as f64 + 0.5); + areas.iter().any(|a| a.contains(Point::new(x, y))) + }) + .collect(); + let shares = Shares::of(&marks, w, h); + move |r: &Rect| shares.share(r) + }; + let share = in_areas(&[Rect::new(10.0, 10.0, 20.0, 20.0), Rect::new(30.0, 0.0, 31.0, 1.0)], 40, 40); + assert_eq!((share(&Rect::new(12.0, 12.0, 22.0, 18.0)), share(&Rect::new(10.0, 10.0, 30.0, 20.0))), (0.8, 0.5)); + assert_eq!((share(&Rect::new(15.0, 15.0, 30.0, 30.0)), share(&Rect::new(30.2, 0.2, 30.8, 0.8))), (25.0 / 225.0, 1.0)); + assert_eq!( + [share(&Rect::new(20.0, 20.0, 30.0, 30.0)), share(&Rect::new(0.0, 0.0, 5.0, 5.0)), share(&Rect::new(50.0, 50.0, 60.0, 60.0))], + [0.0; 3] + ); + assert_eq!(share(&Rect::new(f64::NAN, 0.0, 39.0, 39.0)), 0.0); + let many: Vec = (0..5000).map(|i| Rect::new(f64::from(i % 70), 50.0, f64::from(i % 70) + 1.0, 51.0)).collect(); + let share = in_areas(&many, 80, 80); + assert_eq!((share(&Rect::new(60.0, 50.0, 75.0, 51.0)), share(&Rect::new(70.0, 50.0, 75.0, 51.0))), (10.0 / 15.0, 0.0)); + } + fn piece(text: &str, x: f64, y: f64) -> Arc { Arc::new(Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(x, y), text, CharStyle::default()))))) } @@ -163,9 +194,9 @@ mod tests { assert!(compared(&a, &b, &[], &[]).solid > MAX_SOLID_DIFFERENCE, "the old point sampling falsely refused this page"); let frame = Frame { page: &page, page_rect: rect, rect, whole: false }; let mut view = PageView::new(&frame); - assert!(compare(&frame, &mut view, &vector).is_ok()); - assert!(compare(&frame, &mut view, &Document::new(1000.0, 500.0)).is_err(), "missing artwork remains an error"); + assert!(compare(&frame, &mut view, &vector, false).is_ok()); + assert!(compare(&frame, &mut view, &Document::new(1000.0, 500.0), false).is_err(), "missing artwork remains an error"); let shifted = Rect::new(0.0, 0.0, 500.0, 500.0); - assert!(view.difference(&vector, shifted).any > MAX_DIFFERENCE, "wrong framing remains an error"); + assert!(view.difference(&vector, shifted, false).any > MAX_DIFFERENCE, "wrong framing remains an error"); } } diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 8e80703d76..1dd8b7d2b0 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -1,8 +1,8 @@ use super::compare::{MAX_DIFFERENCE, PageView, compare, difference}; -use super::plan::plan; +use super::plan::{made_only, make_slots, plan, readable_all}; use super::slots::{ - ART_LEFT_OUT, Content, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, extent, few, fill_slots, - letters, text_objects, words, + ART_LEFT_OUT, Content, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, extent, few, + fill_slots, letters, text_objects, words, }; use super::{Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, Vec2, ai}; @@ -183,10 +183,6 @@ pub(super) fn build_from( // The page's type that needs no text object of the layers: the layers' own legacy text, or // placed files that show it. let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?; - // The page's type is compared with every text object of the layers: that has its limits. - if infos.len() > MAX_SLOTS || infos.len().saturating_mul(shown.len()) > MAX_PAIRS { - return Err("it has too many text objects".into()); - } let texts = Texts::read(data); // Each story is read once, however many text objects name it. let mut read: std::collections::BTreeMap>> = Default::default(); @@ -202,7 +198,8 @@ pub(super) fn build_from( } let template = template.map(|t| ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0)); let mut notes = warnings; - let content = plan(&infos, &stories, template, to_doc, [&shown, &hidden], &mut notes); + let own = (!outlined).then(|| outside_placed_files(&shown, &doc, &placed_elsewhere)); + let (content, reflow) = slot_content(&infos, &stories, template, to_doc, own.as_deref(), [&shown, &hidden], &mut notes)?; // The glyphs left out with the rest of the page's art, and how many text objects take type of // the page right next to them (not counted past `MAX_PAIRS` comparisons). let compared = lone.len().saturating_mul(shown.iter().chain(&hidden).map(Vec::len).sum()); @@ -211,7 +208,7 @@ pub(super) fn build_from( matches!(n.kind, NodeKind::Text(_)) && n.visual_bounds().is_some_and(|b| missing.iter().any(|r| !b.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).is_zero_area())) }; - let short = content.iter().filter(|c| matches!(c, Content::Page(p) | Content::Made(_, _, _, p) if p.iter().any(next_to_missing))).count(); + let short = content.iter().filter(|c| matches!(c, Content::Page(p) if p.iter().any(next_to_missing))).count(); let mut empty = 0; let mut layers = std::mem::take(&mut doc.layers); let mut made = vec![]; @@ -244,16 +241,16 @@ pub(super) fn build_from( // doesn't draw is weighed again with the images there, since an image that covered a // text object at the first placement may not cover it at the other. let other = elsewhere(&doc, &placed_elsewhere); - let unseen = prune_unseen(&frame, &mut view, &mut doc); + let unseen = prune_unseen(&frame, &mut view, &mut doc, reflow); let unseen_note = |n: usize| (n > 0).then(|| format!("{n} {UNSEEN_TEXT}")); - match compare(&frame, &mut view, &doc) { + match compare(&frame, &mut view, &doc, reflow) { // Placed files at the other point their data gives, where that draws closer to the // page: a small image in the wrong place differs too little to fail. Ok(note) => { let closer = other.and_then(|mut other| { - let unseen = prune_unseen(&frame, &mut view, &mut other); - let closer = view.difference(&other, frame.rect).any < view.difference(&doc, frame.rect).any; - closer.then(|| compare(&frame, &mut view, &other).ok()).flatten().map(|note| (other, unseen, note)) + let unseen = prune_unseen(&frame, &mut view, &mut other, reflow); + let closer = view.difference(&other, frame.rect, reflow).any < view.difference(&doc, frame.rect, reflow).any; + closer.then(|| compare(&frame, &mut view, &other, reflow).ok()).flatten().map(|note| (other, unseen, note)) }); match closer { Some((other, unseen, note)) => { @@ -265,8 +262,8 @@ pub(super) fn build_from( } // Placed files at the other point their data gives, where that draws as the page. Err(why) => match other.map(|mut other| { - let unseen = prune_unseen(&frame, &mut view, &mut other); - (compare(&frame, &mut view, &other), other, unseen) + let unseen = prune_unseen(&frame, &mut view, &mut other, reflow); + (compare(&frame, &mut view, &other, reflow), other, unseen) }) { Some((Ok(note), other, unseen)) => { doc = other; @@ -288,6 +285,34 @@ pub(super) fn build_from( Ok((doc, notes)) } +/// What goes into each of `infos`' slots, and whether the type is all made from the file's text +/// document. When the text document makes the type of every text object that shows (and the type +/// isn't asked for as outlines: `own` has the page's text objects that show outside placed files), +/// each slot takes its own made type and the page's type is only compared with it: type laid out +/// again, in another font where the file's isn't installed, may differ from the page's. Otherwise +/// see [`plan`], with `pages` (the page's text objects that show and that don't). +fn slot_content( + infos: &[SlotInfo], + stories: &[Option>], + template: Option<(f64, f64)>, + to_doc: Affine, + own: Option<&[Vec>]>, + pages: [&[Vec>]; 2], + notes: &mut Vec, +) -> Result<(Vec, bool), String> { + let made = make_slots(infos, stories, template, to_doc, notes); + if let Some(own) = own.filter(|_| readable_all(infos, &made)) { + return Ok((made_only(infos, made, [own, pages[1]], notes), true)); + } + // The page's type is matched with every text object whose type isn't made, and weighed against + // where every made one draws: that has its limits. + let open = made.iter().filter(|m| m.is_none()).count(); + if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS { + return Err("it has too many text objects".into()); + } + Ok((plan(infos, stories, made, template, to_doc, pages, notes), false)) +} + /// `doc` with the placed files `placed` lists at their other placement (see /// [`ai::Structure::placed_elsewhere`]): each image's transform followed by its move. `None` when /// none is listed. @@ -391,6 +416,21 @@ fn in_placed_files(objects: &[Vec>], doc: &Document, placed: &[(NodeId inside(doc) || elsewhere(doc, placed).is_some_and(|other| inside(&other)) } +/// The page's text objects in `objects` that don't lie inside a placed file that shows in `doc`, at +/// either placement (see [`in_placed_files`]): the placed file's preview has the others. +fn outside_placed_files(objects: &[Vec>], doc: &Document, placed: &[(NodeId, Affine)]) -> Vec>> { + let mut files = vec![]; + placed_files(&doc.layers, &mut files); + if let Some(other) = elsewhere(doc, placed) { + placed_files(&other.layers, &mut files); + } + if files.is_empty() { + return objects.to_vec(); + } + let inside = |o: &[Arc]| extent(o).is_some_and(|r| files.iter().any(|f| f.inflate(OUTLINE_REACH, OUTLINE_REACH).contains_rect(r))); + objects.iter().filter(|o| !inside(o)).cloned().collect() +} + /// Where the placed files that show in `nodes` are: the linked images the editing data's reader /// makes of them. fn placed_files(nodes: &[Arc], out: &mut Vec) { @@ -520,15 +560,16 @@ fn take_out(nodes: &mut Vec>, id: NodeId, hide: bool) -> bool { /// The text objects made from the file's text document that show and print on the page's area, /// where the page has no type to match them, and that the layers look no worse without, are not /// drawn by the app that wrote the file (which paints every shown text object; it keeps the type -/// of what was turned to outlines): they are taken out. How many. -pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> usize { +/// of what was turned to outlines): they are taken out. How many. `reflow`: the type is all laid +/// out again from the text document (see [`compare`]). +pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document, reflow: bool) -> usize { let mut found = vec![]; unmark(&mut doc.layers, true, true, &mut found); let rect = frame.rect; if found.is_empty() || found.len() > MAX_WEIGHED { return 0; } - let with = view.difference(doc, rect).any; + let with = view.difference(doc, rect, reflow).weighed(reflow); // Taking a text object out changes only what is drawn in its box. When the art would still // differ from the page by more than `compare` allows with every candidate gone, the layers // aren't used whatever is pruned: don't draw them again for each one (#758). diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index cf86445e59..e8ebed707f 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -75,6 +75,14 @@ pub(super) struct Difference { pub(super) solid: f64, } +impl Difference { + /// The share [`compare`] holds to [`MAX_DIFFERENCE`]: every pixel that differs, or with `reflow` + /// (type laid out again from the file's text) those away from type. + pub(super) fn weighed(&self, reflow: bool) -> f64 { + if reflow { self.art } else { self.any } + } +} + /// The scale the comparisons draw a region at: about 400 pixels along its longer side. fn compare_scale(r: Rect) -> f64 { (400.0 / r.width().max(r.height()).max(1.0)).min(4.0) @@ -129,6 +137,8 @@ pub(super) struct PageView { /// rendering of the style there, the layers VectorCraft's live effects, and the two aren't /// held to look alike. restyled: Vec, + /// Where the page draws anything (its type, or its own outlines of type) or has its type. + page_marks: Shares, layers: vectorcraft_render::Renderer, scale: f64, samples: u32, @@ -144,7 +154,11 @@ impl PageView { let page = comparison_render(&mut vectorcraft_render::Renderer::new(), frame.page, ra, scale, samples); let mut page_type = vec![]; type_areas(&frame.page.layers, ra, scale, &mut page_type); - Self { page, page_type, restyled: vec![], layers: vectorcraft_render::Renderer::new(), scale, samples } + let (w, h) = (page.width as usize, page.height as usize); + let typed = in_areas(&page_type, w, h); + let marks: Vec = page.pixels.as_chunks::<4>().0.iter().zip(&typed).map(|(p, t)| *t || ink(on_white(p)) > WHITE).collect(); + let page_marks = Shares::of(&marks, w, h); + Self { page, page_type, restyled: vec![], page_marks, layers: vectorcraft_render::Renderer::new(), scale, samples } } /// Leave the drawn looks in `looks` (on `region`, the page's area in the layers' document) out @@ -159,13 +173,27 @@ impl PageView { } /// How `b` on `rb` (a rectangle the page's size) draws differently from the page ([`compared`]). - pub(super) fn difference(&mut self, b: &Document, rb: Rect) -> Difference { + /// With `reflow` (`b`'s type laid out again from the file's text), type counts as type only where + /// both have something: `b`'s where the page has type or draws anything in at least [`MARKED`] + /// of it, the page's where at least half of it lies where `b` has a text object, shown or not, + /// or a placed file. Elsewhere it is art the other lacks. + pub(super) fn difference(&mut self, b: &Document, rb: Rect, reflow: bool) -> Difference { // The page doesn't print what isn't printed. let printed = as_printed(b); let b = printed.as_ref().unwrap_or(b); let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples); - let mut areas = self.page_type.clone(); + let mut areas = vec![]; type_areas(&b.layers, rb, self.scale, &mut areas); + if reflow { + areas.retain(|r| self.page_marks.share(r) >= MARKED); + let mut texts = vec![]; + all_type_areas(&b.layers, rb, self.scale, &mut texts); + let (w, h) = (self.page.width as usize, self.page.height as usize); + let on_layers = Shares::of(&in_areas(&texts, w, h), w, h); + areas.extend(self.page_type.iter().filter(|r| on_layers.share(r) >= 0.5)); + } else { + areas.extend(&self.page_type); + } compared(&self.page, &y, &areas, &self.restyled) } @@ -241,6 +269,62 @@ fn type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec } } +/// Where every text object in `nodes` is, shown or not, as [`type_areas`] gives it, and every placed +/// file (whose preview draws the type it has). +fn all_type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec) { + for n in nodes { + let placed = matches!(&n.kind, NodeKind::Image(im) if im.link.is_some()); + if (placed || matches!(n.kind, NodeKind::Text(_))) + && let Some(b) = n.visual_bounds() + { + let b = b.inflate(OUTLINE_REACH, OUTLINE_REACH); + out.push(Rect::new((b.x0 - region.x0) * scale, (b.y0 - region.y0) * scale, (b.x1 - region.x0) * scale, (b.y1 - region.y0) * scale)); + } else if let Some(c) = n.children() { + all_type_areas(c, region, scale, out); + } + } +} + +/// Which of `w` × `h` pixels are marked, counted so that the share of any rectangle's pixels that +/// are is read at once. +pub(super) struct Shares { + /// How many of the marked pixels lie above and left of each pixel corner. + sums: Vec, + w: usize, + h: usize, +} + +impl Shares { + /// The pixels `marks` marks (row by row). + pub(super) fn of(marks: &[bool], w: usize, h: usize) -> Self { + let stride = w + 1; + let mut sums = vec![0u32; stride * (h + 1)]; + for (k, marked) in marks.iter().enumerate().take(w * h) { + let (i, j) = (k % w.max(1), k / w.max(1)); + let left = sums.get((j + 1) * stride + i).copied().unwrap_or(0); + let up = sums.get(j * stride + i + 1).copied().unwrap_or(0); + let corner = sums.get(j * stride + i).copied().unwrap_or(0); + if let Some(s) = sums.get_mut((j + 1) * stride + i + 1) { + *s = (left + up + u32::from(*marked)).saturating_sub(corner); + } + } + Self { sums, w, h } + } + + /// The share (0 to 1) of `r`'s pixels that are marked: 0 for one with none of the pixels. + pub(super) fn share(&self, r: &Rect) -> f64 { + let (w, h, stride) = (self.w, self.h, self.w + 1); + let clamp = |v: f64, max: usize| if v.is_finite() { v.clamp(0.0, max as f64) as usize } else { 0 }; + let (x0, y0, x1, y1) = (clamp(r.x0.floor(), w), clamp(r.y0.floor(), h), clamp(r.x1.ceil(), w), clamp(r.y1.ceil(), h)); + if !r.is_finite() || x1 <= x0 || y1 <= y0 { + return 0.0; + } + let at = |x: usize, y: usize| self.sums.get(y * stride + x).copied().unwrap_or(0); + let inside = (at(x1, y1) + at(x0, y0)).saturating_sub(at(x0, y1) + at(x1, y0)); + f64::from(inside) / ((x1 - x0) as f64 * (y1 - y0) as f64) + } +} + /// Which of `w` × `h` pixels (row by row) lie in one of `areas`. fn in_areas(areas: &[Rect], w: usize, h: usize) -> Vec { // Each area adds one inside it: corners marked, then summed along the rows and down the columns. @@ -272,6 +356,10 @@ fn in_areas(areas: &[Rect], w: usize, h: usize) -> Vec { (0..h).flat_map(|j| (0..w).map(move |i| (i, j))).map(|(i, j)| count.get(j * stride + i).is_some_and(|c| *c > 0)).collect() } +/// The least share of a text object's area (with the margin round it) where the page draws anything +/// or has type, for its type laid out again to count as type. +const MARKED: f64 = 0.05; + /// More of the page than this differing between the layers' art and the page's own, and the /// layers aren't used. pub(super) const MAX_DIFFERENCE: f64 = 0.05; @@ -287,11 +375,13 @@ pub(super) const MAX_SOLID_DIFFERENCE: f64 = 0.001; const PAST_THE_PAGE: f64 = 1.0; /// Do the layers' art and the page's own look alike (where the page holds all the art that prints, -/// also round it)? An error says they don't; `Ok` has the note to give when they differ a little: +/// also round it)? An error says they don't; `Ok` has the notes to give when they differ a little: /// with the share of the pixels that differ away from type when that is notable, otherwise with the -/// share of those that differ in the type's areas. -pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document) -> Result, String> { - let mut diff = view.difference(layered, frame.rect); +/// share of those that differ in the type's areas. With `type_reflow` (all the type laid out again +/// from the file's text, which may show in another font), type that differs doesn't make them +/// differ: only art away from type does, and the type's share is a note of its own. +pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document, type_reflow: bool) -> Result, String> { + let mut diff = view.difference(layered, frame.rect, type_reflow); if frame.whole && let Some(art) = vectorcraft_render::encode::art_bounds(as_printed(layered).as_ref().unwrap_or(layered)) .filter(|a| !frame.rect.inflate(PAST_THE_PAGE, PAST_THE_PAGE).contains_rect(*a)) @@ -302,21 +392,24 @@ pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document let round = difference(frame.page, Rect::new(all.x0 + dx, all.y0 + dy, all.x1 + dx, all.y1 + dy), layered, all); diff = Difference { any: diff.any.max(round.any), art: diff.art.max(round.art), solid: diff.solid.max(round.solid) }; } - if diff.any > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE { - return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.any * 100.0)); + if diff.weighed(type_reflow) > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE { + return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.weighed(type_reflow) * 100.0)); } if diff.any <= NOTABLE_DIFFERENCE { - return Ok(None); + return Ok(vec![]); } - Ok(Some(if diff.art > NOTABLE_DIFFERENCE { - format!( - "the art on the layers differs from the file's own page in about {:.1}% of it (brush strokes, live effects and the like that the layers' data doesn't describe)", - diff.art * 100.0 - ) - } else { - format!( - "the type on the layers differs from the file's own page in about {:.1}% of it (type laid out again from the file's text, or drawn in another font)", - (diff.any - diff.art) * 100.0 - ) - })) + let art = format!( + "the art on the layers differs from the file's own page in about {:.1}% of it (brush strokes, live effects and the like that the layers' data doesn't describe)", + diff.art * 100.0 + ); + let typed = format!( + "the type on the layers differs from the file's own page in about {:.1}% of it (type laid out again from the file's text, or drawn in another font)", + (diff.any - diff.art) * 100.0 + ); + let art_notable = diff.art > NOTABLE_DIFFERENCE; + Ok(match (art_notable, type_reflow && diff.any - diff.art > NOTABLE_DIFFERENCE) { + (true, true) => vec![art, typed], + (true, false) => vec![art], + (false, _) => vec![typed], + }) } diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index 4bb3675cd1..6c6cb82b4d 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -1,11 +1,21 @@ use super::layers::closed_where_ends_meet; -use super::slots::{Content, SlotInfo, assign, covered, extent, join_pieces, letters, same_type, words}; +use super::slots::{ + Content, MAX_PAIRS, OUTLINE_REACH, PAGE_TYPE_LEFT_OUT, PAGE_TYPE_UNCHECKED, SlotInfo, assign, covered, extent, join_pieces, letters, same_type, + words, +}; use super::{Affine, Arc, Node, NodeId, NodeKind, Point, Rect, Story, TextKind}; -/// Match page objects to the nearest slot whose story describes them, including hidden slots. -fn match_page_objects(infos: &[SlotInfo], lines: &[Option>], shown: &[Vec>]) -> Vec> { +/// A slot's type made from the file's text document, and roughly where it lies on the document. +pub(super) type Made = (Box, Option); + +/// Match page objects to the nearest slot that `open` (the slots whose type wasn't made) has and +/// whose story describes them, including hidden slots. +fn match_page_objects(infos: &[SlotInfo], lines: &[Option>], open: &[bool], shown: &[Vec>]) -> Vec> { let mut pairs: Vec<(f64, usize, usize)> = vec![]; for (k, _) in infos.iter().enumerate() { + if !open.get(k).copied().unwrap_or(false) { + continue; + } let Some(l) = lines.get(k).and_then(Option::as_ref) else { continue }; for (j, object) in shown.iter().enumerate() { if let Some(d) = object.iter().filter_map(|n| same_type(n, l)).min_by(f64::total_cmp) { @@ -40,12 +50,139 @@ fn frame_text_from_art(info: &SlotInfo, node: &mut Node, region: &mut Option>], + template: Option<(f64, f64)>, + to_doc: Affine, + warn: &mut Vec, +) -> Vec> { + let mut taller = 0; + let made = infos + .iter() + .enumerate() + .map(|(k, info)| { + let t = template?; + let story = stories.get(k)?.as_ref()?; + let mut node = story.node(NodeId(0), info.frame, t, to_doc)?; + let mut region = story.region(t, to_doc); + // The first line where the file has it, in the text document's frame (that of a + // copied object is its original's, as its lines are). + story.place_first_line(&mut node, t, to_doc); + // Area type and type on a path in the object's own frame: the text document's frame + // of a copied object keeps its original's path. + frame_text_from_art(info, &mut node, &mut region); + if let NodeKind::Text(text) = &mut node.kind + && story.fit_first_line(text) + { + taller += 1; + } + Some((Box::new(node), region)) + }) + .collect(); + if taller > 0 { + warn.push(format!( + "area type in frames too short for a line of the font it shows in got taller frames ({taller}): their type wouldn't show otherwise" + )); + } + made +} + +/// Does the file's text document make the type of every slot that shows (at least one does)? +pub(super) fn readable_all(infos: &[SlotInfo], made: &[Option]) -> bool { + infos.iter().any(|i| i.shown) && infos.iter().zip(made).all(|(i, m)| !i.shown || m.is_some()) +} + +/// Each slot's made type, where its slot is (the page's type that shows isn't put anywhere). Shown +/// made type with none of the page's type where it draws is weighed against the page (see +/// `prune_unseen`); the page's type that no made type takes, shown or not, is left out with a note +/// in `warn`. Slots that don't show and whose type isn't made take the page's type that doesn't +/// show (`pages`: the page's text objects that show and that don't), by painting order. +pub(super) fn made_only(infos: &[SlotInfo], made: Vec>, pages: [&[Vec>]; 2], warn: &mut Vec) -> Vec { + let [shown, hidden] = pages; + let mut content = made_content(infos, made); + match see_page_type(&mut content, shown) { + Some(0) => {} + Some(_) => warn.push(PAGE_TYPE_LEFT_OUT.into()), + None => warn.push(PAGE_TYPE_UNCHECKED.into()), + } + fill_hidden(infos, &mut content, hidden); + content +} + +/// The letters and digits of `s`, in any script, in lower case: what is compared of the page's type +/// and made type (the page may spell a mark another way). +fn spelling(s: &str) -> String { + s.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect() +} + +/// The text of `n`, if it is a text object. +fn plain_text(n: &Node) -> String { + if let NodeKind::Text(t) = &n.kind { t.plain_text() } else { String::new() } +} + +/// The words of the page's text object `o`, each as its [`spelling`], the empty ones left out. +fn object_words(o: &[Arc]) -> Vec { + o.iter().flat_map(|n| plain_text(n).split_whitespace().map(spelling).collect::>()).filter(|w| !w.is_empty()).collect() +} + +/// Each slot's made type as its content, else nothing yet. Made type that shows has where it draws, +/// or where its story lies when it draws nothing. +fn made_content(infos: &[SlotInfo], made: Vec>) -> Vec { + infos + .iter() + .zip(made) + .map(|(info, m)| match m { + Some((node, region)) => { + let drawn = node.visual_bounds().filter(|b| !b.is_zero_area()).or(region); + Content::Made(node, drawn.filter(|_| info.shown), false) + } + None => Content::Empty, + }) + .collect() +} + +/// Mark the made type that has at least half of a piece of the page's type where it draws (or round +/// it, as far as strokes round type reach) as type the page draws. How many of the page's text +/// objects no made type takes, shown or not: none that holds a piece of the object has its words +/// ([`spelling`]). Past `MAX_PAIRS` comparisons nothing is marked or counted (`None`). +fn see_page_type(content: &mut [Content], shown: &[Vec>]) -> Option { + let texts = |o: &[Arc]| o.iter().filter_map(|n| if let NodeKind::Text(_) = &n.kind { Some(n.clone()) } else { None }).collect::>(); + // Each object's pieces of type, and the words of them that no made type holding it has yet. + let mut objects: Vec<(Vec, Vec, bool)> = + shown.iter().map(|o| (texts(o).iter().filter_map(|n| n.visual_bounds()).collect(), object_words(o), false)).collect(); + let pieces: usize = objects.iter().map(|o| o.0.len()).sum(); + if content.len().saturating_mul(pieces) > MAX_PAIRS { + return None; + } + let holds = |drawn: Rect, r: &Rect| drawn.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).area() >= 0.5 * r.area().max(1e-9); + for c in content { + let Content::Made(node, region, seen) = c else { continue }; + // Hidden made type has no region: where it draws, shown, is its own box. + let Some(drawn) = region.or_else(|| node.visual_bounds()) else { continue }; + let spelled = if let NodeKind::Text(t) = &node.kind { spelling(&t.plain_text()) } else { String::new() }; + for (rects, words, held) in &mut objects { + if rects.iter().any(|r| holds(drawn, r)) { + *held = true; + *seen |= region.is_some(); + words.retain(|w| !spelled.contains(w.as_str())); + } + } + } + Some(objects.iter().filter(|(_, words, held)| !held || !words.is_empty()).count()) +} + +/// What goes into each of `infos`' slots when the file's text document can't make the type of every +/// slot that shows: type made from the text document (`made`) where it can, else the page's type that +/// the text document puts where the page has it, else the page's type in painting order. The page's +/// type that lies where made type draws and has its words is that type as the page draws it; the +/// rest goes only into slots without made type. pub(super) fn plan( infos: &[SlotInfo], stories: &[Option>], + made: Vec>, template: Option<(f64, f64)>, to_doc: Affine, pages: [&[Vec>]; 2], @@ -59,49 +196,16 @@ pub(super) fn plan( Some(s.line_starts(t).into_iter().map(|(text, (x, y))| (text, to_doc * Point::new(x, y))).collect()) }) .collect(); - let owner = match_page_objects(infos, &lines, shown); - // Type the text document makes, shown or not: the page's pieces of it aren't needed. - let mut content: Vec = infos.iter().map(|_| Content::Empty).collect(); + // A story's lines are its first frame's: a frame of a story whose type is made in another + // text object can't say that the page's type there is its own. + let made_stories: std::collections::BTreeSet = infos.iter().zip(&made).filter(|(_, m)| m.is_some()).filter_map(|(i, _)| i.story).collect(); + let open: Vec = infos.iter().zip(&made).map(|(i, m)| m.is_none() && i.story.is_none_or(|s| !made_stories.contains(&s))).collect(); + let owner = match_page_objects(infos, &lines, &open, shown); // Where the made type that doesn't show lies, by slot. - let mut hidden_at: Vec<(usize, Rect)> = vec![]; - let mut taller = 0; - if let Some(t) = template { - for (k, info) in infos.iter().enumerate() { - let Some(Some(story)) = stories.get(k) else { continue }; - let Some(mut node) = story.node(NodeId(0), info.frame, t, to_doc) else { continue }; - let mut region = story.region(t, to_doc); - // The first line where the file has it, in the text document's frame (that of a - // copied object is its original's, as its lines are). - story.place_first_line(&mut node, t, to_doc); - // Area type and type on a path in the object's own frame: the text document's frame - // of a copied object keeps its original's path. - frame_text_from_art(info, &mut node, &mut region); - if let (false, Some(r)) = (info.shown, region) { - hidden_at.push((k, r)); - } - if let NodeKind::Text(text) = &mut node.kind - && story.fit_first_line(text) - { - taller += 1; - } - if let Some(c) = content.get_mut(k) { - *c = Content::Made(Box::new(node), region.filter(|_| info.shown), false, vec![]); - } - } - } - if taller > 0 { - warn.push(format!( - "area type in frames too short for a line of the font it shows in got taller frames ({taller}): their type wouldn't show otherwise" - )); - } - // The file's text document is trusted where it agrees with the page about something (its lines - // start where the page's type does, or the page has type where it lays type out), or where the - // page has no type to disagree with. - let in_region = |object: &[Arc]| covered(object, &content, |_| true); - let trusted = owner.iter().any(Option::is_some) || shown.is_empty() || shown.iter().any(|o| in_region(o)); - if !trusted { - content.iter_mut().for_each(|c| *c = Content::Empty); - } + let hidden_at: Vec<(usize, Rect)> = + infos.iter().zip(&made).enumerate().filter_map(|(k, (info, m))| Some((k, m.as_ref().filter(|_| !info.shown)?.1?))).collect(); + // Type the text document makes, shown or not: the page's pieces of it aren't needed. + let mut content = made_content(infos, made); // Is `object` the type of a text object that doesn't show, as the page draws it: in its frame, // with its words? (A copied object's lines are where its original's are, so they don't say.) let hidden_type = |object: &[Arc]| { @@ -116,59 +220,45 @@ pub(super) fn plan( }) }) }; - // The letters of each slot's story, in lower case. - let spelled: Vec = stories.iter().map(|s| s.as_ref().map(|s| letters(s.text()).to_ascii_lowercase()).unwrap_or_default()).collect(); - // For each slot: is its made type where `object` is, with the words of one of `object`'s texts in - // its story? All are false unless such slots have the words of every text between them. - let spelling = |object: &[Arc], content: &[Content]| -> Vec { - let r = extent(object); - let texts: Vec> = object + // The letters and digits of each slot's made type that shows, in any script, in lower case. + let spelled: Vec = content + .iter() + .map(|c| match c { + Content::Made(node, Some(_), _) => match &node.kind { + NodeKind::Text(t) => spelling(&t.plain_text()), + _ => String::new(), + }, + _ => String::new(), + }) + .collect(); + // Has made type that draws where `object` lies every word of it ([`spelling`]), in any order? + let made_words = |object: &[Arc], content: &[Content]| { + let Some(r) = extent(object) else { return true }; + let near: Vec<&String> = content .iter() - .filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(words(&t.plain_text().to_ascii_lowercase())) } else { None }) - .filter(|ws| !ws.is_empty()) + .zip(&spelled) + .filter(|(c, _)| matches!(c, Content::Made(_, Some(region), _) if !region.intersect(r).is_zero_area())) + .map(|(_, s)| s) .collect(); - let has = |k: usize| spelled.get(k).is_some_and(|s| texts.is_empty() || texts.iter().any(|ws| ws.iter().all(|w| s.contains(w.as_str())))); - let near: Vec = content - .iter() - .enumerate() - .map(|(k, c)| match (c, r) { - (Content::Made(_, Some(region), ..), Some(r)) => region.intersect(r).area() > 0.0 && has(k), - _ => false, - }) - .collect(); - let every = texts.iter().flatten().all(|w| near.iter().zip(&spelled).any(|(n, s)| *n && s.contains(w.as_str()))); - if every { near } else { vec![] } + object_words(object).iter().all(|w| near.iter().any(|s| s.contains(w.as_str()))) }; let mut spare: Vec>> = vec![]; for (j, object) in shown.iter().enumerate() { - let spells = spelling(object, &content); - let spells = |k: usize| spells.get(k).copied().unwrap_or(false); - match owner.get(j).copied().flatten().filter(|_| trusted) { - // The type of a text object the layers hide: the layers have it, hidden, so the page's - // isn't another text object's. - Some(k) if infos.get(k).is_some_and(|i| !i.shown) && matches!(content.get(k), Some(Content::Made(..))) => {} + match owner.get(j).copied().flatten() { Some(k) => match content.get_mut(k) { - Some(Content::Made(_, _, seen, _)) => *seen = true, Some(Content::Page(p)) => p.extend(object.iter().cloned()), Some(c) => *c = Content::Page(object.clone()), None => {} }, - // What lies where made type is and has that type's words is that type as the page draws it. - None if covered(object, &content, spells) => { - let r = extent(object).unwrap_or(Rect::ZERO); - for (k, c) in content.iter_mut().enumerate() { - if let Content::Made(_, Some(region), seen, _) = c - && !region.intersect(r).is_zero_area() - && spells(k) - { - *seen = true; - } - } - } - None if trusted && hidden_type(object) => {} + // What lies where made type draws, with its words, is that type as the page draws it (in + // another font, maybe, and in any script). + None if covered(object, &content, |_| true) && made_words(object, &content) => {} + None if hidden_type(object) => {} None => spare.push(object.clone()), } } + // The page's type that no made type takes is the spare type below. + let _ = see_page_type(&mut content, shown); for (k, c) in content.iter_mut().enumerate() { if let (Content::Page(parts), Some(Some(l))) = (c, lines.get(k)) { join_pieces(parts, l); @@ -179,12 +269,11 @@ pub(super) fn plan( infos.iter().enumerate().filter(|(k, i)| i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(); if loose.is_empty() { // Type of the page that no text object says it owns goes with the nearest text object that has - // type of the page; with none, it is left out. + // type of the page (never into made type); with none, it is left out. let mut left_out = false; for object in &spare { let (centre, near) = (extent(object).map(|r| r.center()), |c: &Content| match c { Content::Page(parts) => extent(parts).map(|r| r.center()), - Content::Made(_, region, ..) => region.map(|r| r.center()), _ => None, }); let nearest = content @@ -192,14 +281,14 @@ pub(super) fn plan( .filter_map(|c| near(c).zip(centre).map(|(p, q)| ((p.x - q.x).hypot(p.y - q.y), c))) .min_by(|a, b| a.0.total_cmp(&b.0)); match nearest { - Some((_, Content::Page(parts) | Content::Made(_, _, _, parts))) => parts.extend(object.iter().cloned()), + Some((_, Content::Page(parts))) => parts.extend(object.iter().cloned()), _ => left_out = true, } } if !spare.is_empty() { warn.push( if left_out { - "some of the page's type has no text object in the layers, so it is left out" + PAGE_TYPE_LEFT_OUT } else { "some of the page's type has no text object of its own in the layers, so it is with another's" } @@ -221,13 +310,50 @@ pub(super) fn plan( warn.push("the text is on the layers in the order the page paints it, so a text object may be in another group than it was".into()); } } - // The same for the slots that don't show. + fill_hidden(infos, &mut content, hidden); + content +} + +/// The page's type that doesn't show (`hidden`) goes by painting order into the slots that don't +/// show and have nothing yet, but for what is the type of made type that doesn't show: a page object +/// with words and at least half of it where such type draws, while the type has all its words left +/// (each word an object takes is the type's no longer). Past `MAX_PAIRS` comparisons all of it goes. +fn fill_hidden(infos: &[SlotInfo], content: &mut [Content], hidden: &[Vec>]) { let unread: Vec = infos.iter().enumerate().filter(|(k, i)| !i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(); - for (slot, parts) in unread.iter().zip(assign(hidden, unread.len())) { + if unread.is_empty() { + return; + } + // Where each made type that doesn't show draws, and the letters it has left. + let mut made: Vec<(Rect, String)> = content + .iter() + .filter_map(|c| match c { + Content::Made(node, None, _) => node.visual_bounds().map(|b| (b.inflate(OUTLINE_REACH, OUTLINE_REACH), spelling(&plain_text(node)))), + _ => None, + }) + .collect(); + let pairs = made.len().saturating_mul(hidden.len()); + // Is `o` the type of made type that doesn't show? That type's letters for it are taken. + let mut theirs = |o: &[Arc]| { + let words = object_words(o); + let Some(r) = extent(o).filter(|_| !words.is_empty()) else { return false }; + let found = made.iter_mut().find_map(|(b, s)| { + if b.intersect(r).area() < 0.5 * r.area().max(1e-9) { + return None; + } + let mut left = s.clone(); + for w in &words { + let at = left.find(w.as_str())?; + left.replace_range(at..at + w.len(), ""); + } + Some((s, left)) + }); + found.map(|(s, left)| *s = left).is_some() + }; + let hidden: Vec>> = if pairs > MAX_PAIRS { hidden.to_vec() } else { hidden.iter().filter(|o| !theirs(o)).cloned().collect() }; + for (slot, parts) in unread.iter().zip(assign(&hidden, unread.len())) { if let Some(c) = content.get_mut(*slot) { *c = Content::Page(parts.into_iter().flat_map(|p| p.iter().cloned()).collect()); } } - content } diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index 1548a2e9af..e6dc909ace 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -9,13 +9,23 @@ pub(super) const TYPE_LEFT_OUT: &str = "text objects of kinds VectorCraft doesn' pub(super) const ART_LEFT_OUT: &str = "hidden layers have art this can't read"; +/// The page's type that no text object takes, left out. +pub(super) const PAGE_TYPE_LEFT_OUT: &str = "some of the page's type has no text object in the layers, so it is left out"; + +/// The page's type, too much to check against the text objects (it may have some that none takes). +pub(super) const PAGE_TYPE_UNCHECKED: &str = + "the page's type wasn't checked against the text objects, as there is too much of it: some of it may have no text object"; + pub(super) const LAYERS_UNREAD: &str = "the file's layers weren't read"; /// Does this import note say that the file has something the document doesn't (hidden text, art or -/// layers that could not be read)? Writing the document over the file would lose it for good. +/// layers that could not be read, or the page's type that no text object takes or may not take)? +/// Writing the document over the file would lose it for good. pub fn is_loss(note: &str) -> bool { note.ends_with(TEXT_LEFT_OUT) || note.ends_with(TYPE_LEFT_OUT) + || note == PAGE_TYPE_LEFT_OUT + || note == PAGE_TYPE_UNCHECKED || [ART_LEFT_OUT, LAYERS_UNREAD, crate::import::graphics::TOO_MUCH, crate::import::graphics::FAR_AWAY].iter().any(|n| note.starts_with(n)) } @@ -163,10 +173,9 @@ pub(super) fn assign(objects: &[Vec>], slots: usize) -> Vec>), - /// A text object made from the file's text document, where it lies on the document, whether - /// the page has type where it is, and the page's type of no text object that is nearest it - /// (kept after it). - Made(Box, Option, bool, Vec>), + /// A text object made from the file's text document, where it draws on the document (when it + /// shows), and whether the page has type where it is. + Made(Box, Option, bool), /// Nothing the file lets this read. Empty, /// Its type is on the page with another text object's; there is nothing to put here. @@ -252,7 +261,7 @@ pub(super) fn fill_slots( i += n; continue; } - Some(Content::Made(mut text, _, seen, extra)) => { + Some(Content::Made(mut text, _, seen)) => { text.id = doc.alloc_id(); if let Some(story) = story { made.push((story, frame, text.id)); @@ -265,20 +274,12 @@ pub(super) fn fill_slots( } // Type the page shows is kept; other made type is weighed against the page. text.name = if seen { name.cloned() } else { Some(format!("{MADE}{}", name.map_or("", String::as_str))) }; - let extra: Vec> = extra.iter().map(|p| reid(doc, p)).collect(); - // The type takes the slot's transparency; the page's type kept after it, where it has - // none of its own, goes into a group with it that has the transparency instead. - let parts: Vec> = if transparent && !extra.is_empty() && !extra.iter().any(|p| see_through(p)) { - let mut group = Node::group(doc.alloc_id(), std::iter::once(Arc::new(*text)).chain(extra).collect()); - (group.opacity, group.blend, group.isolate, group.knockout) = state; - vec![Arc::new(group)] - } else { - (text.opacity, text.blend, text.isolate, text.knockout) = state; - std::iter::once(Arc::new(*text)).chain(extra).collect() - }; - let n = parts.len(); - nodes.splice(i..=i, parts); - i += n; + // The type takes the slot's transparency. + (text.opacity, text.blend, text.isolate, text.knockout) = state; + if let Some(slot) = nodes.get_mut(i) { + *slot = Arc::new(*text); + } + i += 1; continue; } Some(Content::Merged) => { diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index ee4beca057..29e73bbc92 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -342,6 +342,24 @@ fn type_of_the_page_inside_a_placed_file_needs_no_text_object() { assert!(!read, "{warnings:?}"); assert!(warnings.iter().any(|w| w.contains("its layers have no text objects")), "{warnings:?}"); } + // With a text object the text document makes beside it, the placed file's type is still its + // own, not type left out. + // The template box's centre (100, 50) is the canvas centre: the anchor is at (5, 10) in the art. + let doc = text_document(&[("Note\r", 0, (8096.5, 8231.5), (0.0, 0.0), 0.0)]); + let both = native_with_text(&layer("Pages", true, &format!("{place}{}", text_object(0))), &doc) + .replace("%AI3_TemplateBox: 50 50 50 50", "%AI3_TemplateBox: 100 50 100 50"); + let mut page = pdf(38.0); + let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() }; + let note = Node::new( + page.alloc_id(), + NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(5.0, 90.0), "Note", style))), + ); + let layer_id = page.layers[0].id; + page.insert(Some(layer_id), 2, note).unwrap(); + let (d, warnings, read) = crate::layered_ai(&private(&both), page, vec![], false, false, 1.0); + assert!(read, "{warnings:?}"); + assert_eq!(text_of(&d.layers[0]).iter().map(|t| t.plain_text()).collect::>(), ["Note"], "{warnings:?}"); + assert!(!warnings.iter().any(|w| w.contains("left out")), "{warnings:?}"); } /// A palette of `[None]` and White, and a color group `Inks` holding a spot color, Red ink. @@ -979,38 +997,83 @@ fn a_line_the_page_draws_in_pieces_goes_to_its_text_object_whole() { assert!(t.cached_bounds.is_none() && t.cached_baselines.is_empty()); } -#[test] -fn type_of_the_page_that_no_story_places_stays_with_the_nearest_text_object() { - let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); - let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); - let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 30 moveto (Extra) show"; - let r = import(&eps(page, &art)).unwrap(); - let mut all = vec![]; - r.document.walk(|n| { - if let NodeKind::Text(t) = &n.kind { - all.push(t.plain_text()); - } - }); - assert!(all.contains(&"Extra".to_string()), "{all:?} {:?}", r.warnings); +/// `doc` (from [`text_document`], whose stories all name the first frame) with its last story in +/// its own frame, the last, of a kind this doesn't read. +fn last_frame_unread(doc: &str) -> String { + let frames = doc.matches("/2 << /2 [").count(); + let mut doc = doc.to_string(); + let at = doc.rfind("/1 << /0 [ << /0 0 >> ]").unwrap(); + doc.replace_range(at..at + 23, &format!("/1 << /0 [ << /0 {} >> ]", frames - 1)); + let at = doc.rfind("/2 << /2 [").unwrap() + "/2 << ".len(); + doc.insert_str(at, "/0 9 "); + doc } -/// Page type of no text object that lies where made type is, but has other letters, is not that type: -/// it stays, with the nearest text object. -#[test] -fn type_of_the_page_near_made_type_with_other_letters_stays() { - // "Extra" is 11.5 below the line of "Hi there", well inside the box round that line. - let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); - let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); - let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 50 moveto (Extra) show"; - let r = import(&eps(page, &art)).unwrap(); +/// The plain text of every text object in `d`, in order. +fn all_texts(d: &Document) -> Vec { let mut all = vec![]; - r.document.walk(|n| { + d.walk(|n| { if let NodeKind::Text(t) = &n.kind { all.push(t.plain_text()); } }); - assert_eq!(all, ["Hi there", "Extra"], "{:?}", r.warnings); - assert!(r.warnings.iter().any(|w| w.contains("with another's")), "{:?}", r.warnings); + all +} + +/// Type of the page that no story places goes to the text object whose type the text document +/// can't make, not into made type; with no such text object and none of the page's type in a text +/// object, it is art the layers don't draw, which the comparison weighs. +#[test] +fn type_of_the_page_that_no_story_places_goes_to_a_text_object_that_cant_be_made() { + let doc = + last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8200.0, 8120.0), (0.0, 0.0), 0.0)])); + let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 30 moveto (Extra) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hi there", "Extra"], "{:?}", r.warnings); + // Every text object's type made: the page's "Extra" is in none of them, so the file comes in as its page. + let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let r = import(&eps(page, &native_with_text(&layer("Art", true, &text_object(0)), &doc))).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings); +} + +/// A story whose first frame's type is made and whose second frame's can't be: the page's type of +/// the first frame stays the made type's, and isn't the second frame's too. +#[test] +fn page_type_of_a_made_frame_isnt_given_to_the_storys_other_frame() { + let mut doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Spare\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0)]); + // Story 0 in frames 0 and 1, both point type: point type isn't threaded, so its second frame has none. + let at = doc.find("/1 << /0 [ << /0 0 >> ]").unwrap(); + doc.replace_range(at..at + 23, "/1 << /0 [ << /0 0 >> << /0 1 >> ]"); + let art = native_with_text(&layer("Art", true, &(frame_object(0, 0) + &frame_object(0, 1))), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings); +} + +/// Page type of no text object that lies where made type draws, with its words in any case, is that +/// type as the page draws it, and doesn't go to a text object whose type can't be made. Page type +/// with other words there, or beside made type, does. +#[test] +fn type_of_the_page_where_made_type_draws_with_its_words_is_that_type() { + let doc = + last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8200.0, 8120.0), (0.0, 0.0), 0.0)])); + let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc); + let with = |drawn: &str, y: f64| { + format!("0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 {y} moveto ({drawn}) show") + }; + // "THERE" over the line of "Hi there", a point below it. + let r = import(&eps(&with("THERE", 60.5), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.starts_with("1 text objects")), "{:?}", r.warnings); + // "Extra" there, or 11.5 below that line: the text object that can't be made takes it. + for y in [60.5, 50.0] { + let r = import(&eps(&with("Extra", y), &art)).unwrap(); + assert_eq!(all_texts(&r.document), ["Hi there", "Extra"], "{y}: {:?}", r.warnings); + } } /// Page type of no text object that lies where made type is and has its letters, in any case, is that @@ -1075,22 +1138,23 @@ fn type_of_the_page_with_the_letters_of_two_made_types_where_it_lies_is_their_ty } /// The file's text document is trusted where the page has type where it lays type out, whatever -/// letters that type has: its type is weighed against the page. +/// letters that type has: the type is the text document's, and the difference is noted as type. +/// The page's type with other words is left out, with a note that is a loss. #[test] fn page_type_where_made_type_is_trusts_the_text_document_whatever_its_letters() { let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 50 moveto (Extra) show"; let r = import(&eps(page, &art)).unwrap(); - let mut all = vec![]; - r.document.walk(|n| { - if let NodeKind::Text(t) = &n.kind { - all.push(t.plain_text()); - } - }); - assert_eq!(all, ["Extra"], "{:?}", r.warnings); - // "Hi there" was made from the text document and left out because the page doesn't draw it. - assert!(r.warnings.iter().any(|w| w.contains("doesn't draw")), "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.starts_with("the type on the layers differs")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("doesn't draw")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.ends_with("so it is left out") && crate::is_loss(w)), "{:?}", r.warnings); + // The page's type with the text document's words, in capitals: nothing is left out. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 50 moveto (HI THERE) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings); } #[test] @@ -1161,15 +1225,6 @@ fn type_keeps_the_opacity_and_blend_mode_of_its_text_object() { let art = native_with_text(&layer("Art", true, &(drawing.clone() + &format!("{own}1 (Style) XW\n").repeat(50))), &doc); let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); assert_eq!(depth(&d.layers[0]), 4, "{notes:?}"); - // Made type with the page's type of no text object kept after it: a group of the two has it. - let art = native_with_text(&layer("Art", true, &format!("1 0.2 0 0 0 Xy\n{}", text_object(0))), &doc); - let r = import(&eps(&format!("{page} 58.5 30 moveto (Extra) show"), &art)).unwrap(); - assert_eq!(kinds(&r.document.layers[0]), ["group[2]"], "{:?}", r.warnings); - let group = &r.document.layers[0].children().unwrap()[0]; - assert_eq!((group.opacity, group.blend), (0.2, BlendMode::Multiply)); - let texts: Vec = text_of(group).iter().map(|t| t.plain_text()).collect(); - assert_eq!(texts, ["Hi there", "Extra"]); - assert!(group.children().unwrap().iter().all(|p| (p.opacity, p.blend) == (1.0, BlendMode::Normal))); // A story in a frame of a kind this doesn't know: the type that shows is the page's. An EPS page has // no transparency, so its type takes its text object's. let doc = doc.replace("/2 << /2 [ 1 0 0 1 0 0 ] >>", "/2 << /0 9 /2 [ 1 0 0 1 0 0 ] >>"); @@ -1296,8 +1351,9 @@ fn a_run_longer_than_any_text_doesnt_overflow() { #[test] fn more_text_objects_than_are_matched_leave_the_page() { + // Text objects whose type the text document can't make are matched with the page's type. let many = text_object(0).repeat(5001); - let doc = text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let doc = last_frame_unread(&text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)])); let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &many)), &doc); let r = import(&eps(&page_square(10, 10), &art)).unwrap(); assert_eq!(names(&r.document), ["Back", "Spare", "Layer 1"], "{:?}", r.warnings); @@ -1440,8 +1496,10 @@ fn art_the_page_doesnt_draw_is_noted_with_its_own_share_and_not_the_types() { let r = import(&page_in_pieces_and_layers(bar)).unwrap(); assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); let notes: Vec<&String> = r.warnings.iter().filter(|w| w.contains("differs from the file's own page")).collect(); - assert_eq!(notes.len(), 1, "{:?}", r.warnings); + // The type, all laid out again from the text document, has a note of its own. + assert_eq!(notes.len(), 2, "{:?}", r.warnings); assert!(notes[0].starts_with("the art on the layers differs from the file's own page in about 0.4% of it (brush strokes"), "{notes:?}"); + assert!(notes[1].starts_with("the type on the layers differs from the file's own page"), "{notes:?}"); } /// An EPS whose page is its art's box `[x0 y0 x1 y1]` (not its artboard, 0 0 100 100), drawing @@ -1587,6 +1645,258 @@ fn area_type_and_type_on_a_path_come_from_the_text_document() { assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings); } +/// A point type frame at the point (`x`, `y`) of the art. +fn point_frame(x: f64, y: f64) -> String { + let (cx, cy) = canvas(x, y); + format!("<< /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 {cx} {cy} ] >> >> >>") +} + +/// An area type frame of the rectangle `x0 y0 x1 y1` of the art. +fn area_frame(x0: f64, y0: f64, x1: f64, y1: f64) -> String { + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(x0, y0, x1, y1)) +} + +/// The text of `n` when it is a text object, or a group of one object whose text that is. +fn lone_text(n: &Node) -> Option { + match &n.kind { + NodeKind::Text(t) => Some(t.plain_text()), + NodeKind::Group { .. } => match n.children()?.as_slice() { + [only] => lone_text(only), + _ => None, + }, + _ => None, + } +} + +/// What each object of layer `l` holds as one text object ([`lone_text`]). +fn lone_texts(l: &Node) -> Vec> { + l.children().into_iter().flatten().map(|n| lone_text(n)).collect() +} + +/// `text` as a string of the text document: UTF-16 after its byte order mark, each byte in octal. +fn utf16(text: &str) -> String { + let mut out = String::from("\\376\\377"); + for unit in text.encode_utf16() { + for b in unit.to_be_bytes() { + out.push_str(&format!("\\{b:03o}")); + } + } + out +} + +/// Type the text document makes for every text object that shows stays in each one's own group, +/// on its own layer, however the page draws it: in pieces, in another order, with a quote hung +/// outside its frame. +#[test] +fn type_from_the_text_document_stays_in_its_groups() { + let frames = [ + point_frame(10.0, 90.0), + point_frame(10.0, 78.0), + point_frame(55.0, 90.0), + area_frame(10.0, 40.0, 45.0, 55.0), + area_frame(55.0, 40.0, 90.0, 55.0), + ]; + let style = "/1 8.0"; + let doc = document_of( + &frames, + &[ + story("Alpha\\r", &[0], "/0 0", style), + story("Bravo\\r", &[1], "/0 0", style), + story("Charlie\\r", &[2], "/0 0", style), + story("\"Delta\"\\r", &[3], "/0 0", style), + story("\"Echo\"\\r", &[4], "/0 0", style), + ], + ); + let nested = |s: u32| format!("u\nu\n{}U\nU\n", frame_object(s, 0)); + let single = |s: u32| format!("u\n{}U\n", frame_object(s, 0)); + let words = layer("Words", true, &(nested(0) + &nested(1) + &single(3))); + let more = layer("More", true, &(single(2) + &nested(4))); + let art = native_with_text(&(words + &more), &doc); + // The page paints the third story before the first, each in two pieces, and hangs the area + // type's opening quotes outside their frames, painted last. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 8 scalefont setfont \ + 55 90 moveto (Char) show 72.3 90 moveto (lie) show 10 90 moveto (Al) show 17.1 90 moveto (pha) show \ + 10 78 moveto (Bravo) show 10 48.5 moveto (Delta\") show 55 48.5 moveto (Echo\") show \ + 7.2 48.5 moveto (\") show 52.2 48.5 moveto (\") show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Words", "More"], "{:?}", r.warnings); + let some = |v: &[&str]| v.iter().map(|s| Some(s.to_string())).collect::>(); + assert_eq!(lone_texts(&r.document.layers[0]), some(&["Alpha", "Bravo", "\"Delta\""]), "{:?}", r.warnings); + assert_eq!(lone_texts(&r.document.layers[1]), some(&["Charlie", "\"Echo\""]), "{:?}", r.warnings); + assert_eq!(all_texts(&r.document).len(), 5, "{:?}", r.warnings); +} + +/// The page's type isn't matched with the text objects when the text document makes the type of +/// every one: a file of more of them than are matched still comes in with its layers. +#[test] +fn six_thousand_point_stories_open_with_layers() { + let stories: Vec<(String, (f64, f64))> = + (0..6000).map(|i| (format!("S{i}\r"), (8150.0 + f64::from(i % 60), 8150.0 + f64::from(i / 60) * 0.8))).collect(); + let list: Vec> = stories.iter().map(|(t, at)| (t.as_str(), 0, *at, (0.0, 0.0), 0.0)).collect(); + let doc = text_document(&list); + let objects: String = (0..6000).map(text_object).collect(); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Words", true, &objects)), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + assert_eq!(names(&d), ["Back", "Words"], "{notes:?}"); + assert_eq!(text_of(&d.layers[1]).len(), 6000, "{notes:?}"); +} + +/// A story in a frame of a kind this doesn't read takes the page's type for its own text object +/// only: the others keep the type made from the text document, in their groups, and the page's +/// type beside made type, with its letters, goes to the text object that can't be made. +#[test] +fn a_story_with_an_unknown_frame_kind_falls_back_for_that_slot_only() { + let doc = last_frame_unread(&text_document(&[ + ("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), + ("Low\r", 0, (8160.0, 8221.5), (0.0, 0.0), 0.0), + ("Hi\r", 0, (8200.0, 8191.5), (0.0, 0.0), 0.0), + ])); + let grouped = |s: u32| format!("u\n{}U\n", text_object(s)); + let art = native_with_text(&layer("Art", true, &(grouped(0) + &grouped(1) + &grouped(2))), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 18.5 20 moveto (Low) show \ + 58.5 50 moveto (Hi) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let some = |v: &[&str]| v.iter().map(|s| Some(s.to_string())).collect::>(); + assert_eq!(lone_texts(&r.document.layers[0]), some(&["Hi there", "Low", "Hi"]), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings); +} + +/// Type laid out from the text document that the page draws differently (in another font, where +/// the file's isn't installed) keeps the layers, with a note; art that differs still doesn't. +#[test] +fn type_drawn_in_another_font_keeps_the_layers() { + let lines = [("Hello\r", 8221.5), ("World\r", 8201.5), ("Again\r", 8181.5), ("Today\r", 8161.5)]; + let list: Vec> = lines.iter().map(|(t, y)| (*t, 0, (8146.5, *y), (0.0, 0.0), 0.0)).collect(); + let doc = text_document(&list).replace("/1 14.0", "/1 20.0"); + let objects: String = (0..4).map(text_object).collect(); + // The page draws each line in capitals: a font that isn't this one. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 20 scalefont setfont \ + 5 85 moveto (HELLO) show 5 65 moveto (WORLD) show 5 45 moveto (AGAIN) show 5 25 moveto (TODAY) show"; + let r = import(&eps(page, &native_with_text(&layer("Art", true, &objects), &doc))).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hello", "World", "Again", "Today"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.starts_with("the type on the layers differs from the file's own page")), "{:?}", r.warnings); + // A square the page doesn't draw, away from the type: the file comes in as its page. + let block = "0 0 0 1 k\n80 5 m\n90 5 L\n90 15 L\n80 15 L\nf\n"; + let r = import(&eps(page, &native_with_text(&layer("Art", true, &format!("{block}{objects}")), &doc))).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings); +} + +/// Type laid out from the text document where the page draws nothing is art the page lacks, even +/// with more such text objects than are weighed one by one against the page. +#[test] +fn type_the_page_doesnt_draw_on_bare_page_still_differs() { + let mut list: Vec> = vec![("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]; + for i in 0..14 { + list.push(("Gm\r", 0, (8146.5 + f64::from(i % 4) * 22.0, 8216.5 + f64::from(i / 4) * 18.0), (0.0, 0.0), 0.0)); + } + let doc = text_document(&list); + let objects: String = (0..15).map(text_object).collect(); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show"; + let r = import(&eps(page, &native_with_text(&layer("Art", true, &objects), &doc))).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings); +} + +/// A hidden text object whose type the text document can't make takes the page's hidden type, as +/// it does when some shown text object's type can't be made either, but not the page's hidden type +/// of one whose type is made. +#[test] +fn a_hidden_text_object_that_cant_be_made_takes_the_pages_hidden_type() { + let doc = last_frame_unread(&text_document(&[ + ("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), + ("Known\rMore\r", 0, (8200.0, 8200.0), (0.0, 0.0), 0.0), + ("Secret\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0), + ])); + let spare = layer("Spare", false, &(text_object(1) + &text_object(2))); + let art = native_with_text(&(layer("Art", true, &format!("{}\n{}", square(10, 10), text_object(0))) + &spare), &doc); + let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() }; + let text = |d: &mut Document, s: &str, y: f64| { + Node::new(d.alloc_id(), NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(58.5, y), s, style.clone())))) + }; + // The last text object's type over "Known", in words or in marks only. + for secret in ["Secret", "?!"] { + let mut page = pdf_part(10.0, 86.0); + let shown = text(&mut page, "Hi there", 38.5); + let first = page.layers[0].id; + page.insert(Some(first), 1, shown).unwrap(); + let spare = page.add_layer(Some("Spare")); + // The two lines of "Known More" where its story puts them, and the other over them, painted + // first. + for (i, (s, y)) in [(secret, 60.0), ("Known", 58.5), ("More", 73.0)].into_iter().enumerate() { + let n = text(&mut page, s, y); + page.insert(Some(spare), i, n).unwrap(); + } + if let Some(l) = page.node_mut(spare) { + l.visible = false; + } + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{secret}: {w:?}"); + assert_eq!(names(&d), ["Art", "Spare"], "{w:?}"); + let texts = |l: usize| text_of(&d.layers[l]).iter().map(|t| t.plain_text()).collect::>(); + assert_eq!((texts(0), texts(1)), (vec!["Hi there".to_string()], vec!["Known\nMore".to_string(), secret.to_string()]), "{w:?}"); + } +} + +/// A small label the page draws where no text object of the layers has type differs too little to +/// send the file to its page: the import says it is left out. Type the page draws of a hidden +/// text object isn't counted. +#[test] +fn a_small_label_of_the_page_in_no_text_object_is_noted() { + let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Extra\r", 0, (8200.0, 8211.5), (0.0, 0.0), 0.0)]); + let art = native_with_text(&(layer("Art", true, &text_object(0)) + &layer("Spare", false, &text_object(1))), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 30 moveto (Extra) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art", "Spare"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("so it is left out")), "{:?}", r.warnings); + let label = format!("{page} /Helvetica findfont 3 scalefont setfont 10 90 moveto (no.) show"); + let r = import(&eps(&label, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art", "Spare"], "{:?}", r.warnings); + let note = r.warnings.iter().find(|w| *w == "some of the page's type has no text object in the layers, so it is left out"); + assert!(note.is_some_and(|w| crate::is_loss(w)), "{:?}", r.warnings); +} + +/// A line break inside a paragraph (`\x03` in the text document) stays a line break in it. +#[test] +fn a_soft_return_is_a_line_break_in_its_paragraph() { + let doc = text_document(&[("One\\003Two\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Words", true, &text_object(0))), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + let texts = text_of(&d.layers[1]); + assert_eq!(texts.len(), 1, "{notes:?}"); + assert_eq!(texts[0].plain_text(), "One\u{2028}Two"); + assert!(texts[0].paras.is_empty(), "one paragraph: {:?}", texts[0].paras); +} + +/// A Thai story is one text object however the page splits its type: by word, and its marks +/// above apart from their letters, above the top of its frame. +#[test] +fn a_thai_story_stays_one_text_object() { + let thai = "\u{0E2A}\u{0E38}\u{0E02}\u{0E2A}\u{0E31}\u{0E19}\u{0E15}\u{0E4C} \u{0E27}\u{0E31}\u{0E19}\u{0E40}\u{0E01}\u{0E34}\u{0E14}"; + let doc = document_of(&[area_frame(10.0, 30.0, 90.0, 60.0)], &[story(&utf16(&format!("{thai}\r")), &[0], "/0 0", "/1 14.0")]); + let art = native_with_text(&layer("Art", true, &format!("{}\nu\n{}U\n", square(10, 10), frame_object(0, 0))), &doc); + let mut page = pdf_part(10.0, 86.0); + let layer_id = page.layers[0].id; + let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() }; + // Doc y 40 is the frame's top: the words on its first line, the marks a little above it. + let pieces = [ + ("\u{0E2A}\u{0E38}\u{0E02}\u{0E2A}\u{0E19}\u{0E15}", 10.0, 53.0), + ("\u{0E27}\u{0E19}\u{0E40}\u{0E01}\u{0E14}", 50.0, 53.0), + ("\u{0E31}\u{0E4C}", 24.0, 41.0), + ("\u{0E31}\u{0E34}", 58.0, 41.0), + ]; + for (i, (text, x, y)) in pieces.iter().enumerate() { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(*x, *y), text, style.clone()); + let n = Node::new(page.alloc_id(), NodeKind::Text(Box::new(t))); + page.insert(Some(layer_id), 1 + i, n).unwrap(); + } + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{w:?}"); + assert_eq!(names(&d), ["Art"], "{w:?}"); + assert_eq!(all_texts(&d), [thai], "{w:?}"); + assert_eq!(lone_texts(&d.layers[0]).last(), Some(&Some(thai.to_string())), "{w:?}"); +} + /// A story of `text` on frame 0 whose layout sets glyphs `advance` wide round the outside of a /// circle of radius `radius`, the circle's length between their centres `fraction` of an advance. fn round_story(text: &str, advance: f64, radius: f64, fraction: f64) -> String { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index ce464cc58c..c01f0005e5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -84,8 +84,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. Where the text document can't say (a frame of another kind, or a document that doesn't agree with the page), type that shows comes from the page into its text object's place (no group around it), and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5%, where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. Where the text document can't say (a frame of another kind, or a document that doesn't agree with the page), type that shows comes from the page into its text object's place (no group around it), and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5%, where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e7e1bbc5f6..97e9abf9f0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1033,11 +1033,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.svgz` file copied in a file manager pastes as its art, as a copied `.svg` file does. SVG export (Save As, Export As, Export for Screens, Asset Export and the clipboard share the writer) writes simple shapes as SVG basic shapes, as the reference app does (an ellipse is an `ellipse` tag until an anchor is added, [forum](https://community.adobe.com/t5/illustrator-discussions/trouble-exporting-shape-with-points-to-svg/td-p/10720325); rectangles come out as `` and ``, [forum](https://community.adobe.com/t5/illustrator-discussions/force-svg-export-using-all-lt-rect-gt/td-p/11282378)): an axis-aligned rectangle as ``, a circle or ellipse drawn with four standard arcs as ``/``, a straight line as ``, and other straight-segment paths as ``/``, at the written precision (#4652). A rectangle or ellipse with a dashed stroke, whose dashes would start elsewhere, a turned ellipse, curves and compound paths stay ``. `crates/svg/tests/it/basic_shapes.rs` checks each element, that the picture renders as the canvas does and that the geometry reimports. SVG import keeps attributes in other applications' XML namespaces (`plotter:pen="2"`) on the objects and layers they belong to, as it keeps their `data-*` attributes: copies, duplicates and `.vectorcraft` files keep them, and SVG export writes them back with each namespace declared once on the root (the rest of #522; `crates/svg/tests/it/foreign_attributes.rs`, `tests/attributes.rs`). - In a `.ai` or EPS opened from its editing data, type has its text object's opacity and blend mode, whether it is made from the file's text document or taken from the page. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, that type is left out only when, for each piece of it, one of those text objects has the piece's Latin letters and digits in its text, in capitals or not; other such type is kept as the page's other type of no text object is. + In a `.ai` or EPS opened from its editing data, type has its text object's opacity and blend mode, whether it is made from the file's text document or taken from the page. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. + A `.ai` or EPS opened from its editing data whose text document makes the type of every text object that shows takes all its type from the text document: each text object stays in its own group, frame and layer, the page's type isn't matched with them, a file of more than 5,000 text objects still opens with its layers, and type the page draws differently (in another font) keeps the layers, with a warning. A line break inside a paragraph stays a line break in it (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ate.rs`). In SVG export without Fewer `` Elements, each character of live type that justification or Mojikumi moves (the letter gaps of a Justify All line without word spaces, the gaps between the characters of a justified Japanese line, closed-up punctuation, the space between Japanese and Latin letters) starts its own positioned ``, and type scaled horizontally on a justified line is stretched to its own width (`crates/svg/tests/it/text_layout.rs`). SVG export (live text), legacy `.ai` saves (text objects), DXF export (`TEXT` entities) and the CSS Properties panel write area type that Shrink Text to Fit scales down at the size it draws at, and scale its tracking, kerning, leading and baseline shifts the same way where the format holds them. A PDF saved with Illustrator's editing data opens through it as a PDF-compatible `.ai` does, with its layers and groups and with art reaching past its page unclipped; such a PDF holds the data in `AIPDFPrivateData` streams (part of #868). A shape a PDF or `.ai` paints with a gradient (a clip path round a shading) opens as one path filled with the gradient, not a clip group round a rectangle, so Shape Builder, Live Paint and Pathfinder work on its outline (#1304). - In a `.ai` opened from its editing data, a text object on a layer that shows and doesn't print stays on that layer, made from the file's text document, even where the page doesn't draw it (`crates/eps/src/import/tests_native.rs`). Such a `.ai` opens without the PDF part's warnings that text was kept as outlines when no outlined glyphs come in, and a warning counts the text objects that hold the page's type next to glyphs the page has only as outlines, which don't come in (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Where the art of a `.ai` or EPS opened from its editing data differs a little from the file's page, the warning gives the share of the page that differs away from type. When that share is 0.2% or less, the warning names the type and gives the share of the page that differs where the type is (`crates/eps/src/import/tests_native.rs`). + In a `.ai` opened from its editing data, a text object on a layer that shows and doesn't print stays on that layer, made from the file's text document, even where the page doesn't draw it (`crates/eps/src/import/tests_native.rs`). Such a `.ai` opens without the PDF part's warnings that text was kept as outlines when no outlined glyphs come in, and a warning counts the text objects that hold the page's type next to glyphs the page has only as outlines, which don't come in (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Where the art of a `.ai` or EPS opened from its editing data differs a little from the file's page, the warning gives the share of the page that differs away from type. When that share is 0.2% or less, the warning names the type and gives the share of the page that differs where the type is; when all the type is made from the text document, the type's share has a warning of its own beside the art's (`crates/eps/src/import/tests_native.rs`). PDF text opens with every glyph where the file draws it (#722): the font's kerning or none, whichever the file followed, word and character spacing, `TJ` adjustments and horizontal scaling kept per character as tracking, text rise as baseline shift within its line, vertical glyphs narrower than an em centred on their column (`/W2`, `/W`, `/DW`), justified text boxes with word spacing back as justified area type (`tests_text_placement`, fixtures written from ISO 32000-1 §9). A `.ai` or PDF whose editing data holds a variable library opens with a warning that its variables and data sets weren't read, with how many of each it has, whether its layers are read or it comes in as its PDF part (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). A PDF page whose `UserUnit` (PDF 1.6) is above 1 opens at its size in points, its numbers times the `UserUnit` (one above 75,000 counts as 75,000), and `document.pdfInfo` gives its size and boxes in points too. A `.ai` whose editing data has its artboards in the units of such a page opens from that data at the page's size, with its layers, and when the layers can't be read its pages still take the artboard layout of the data, scaled the same way (part of #1482). From ec8c1cb8d1f59563691017da8db96a52ddd22405 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 00:36:29 +0700 Subject: [PATCH 10/70] Intertwine: a right-click where three or more objects overlap arranges the nearest one Squashed from #4862 onto main. --- crates/doc/src/hit.rs | 21 ++- crates/doc/src/intertwine.rs | 79 +++++++++--- crates/doc/src/mem.rs | 3 + crates/doc/src/node/extras.rs | 6 + crates/doc/src/node/ops.rs | 9 +- crates/doc/src/node/tests.rs | 17 +++ crates/doc/src/node/wire.rs | 37 +++++- crates/engine/src/cmd/intertwine.rs | 164 ++++++++++++++++-------- crates/engine/src/tests/intertwine.rs | 127 ++++++++++++++++++ crates/tools/src/intertwine.rs | 124 +++++++++++++++--- crates/ui-egui/src/canvas/context.rs | 13 +- crates/ui-egui/src/menus/context.rs | 23 +++- crates/ui-egui/src/state.rs | 8 ++ crates/ui-egui/src/tests/contextmenu.rs | 55 ++++++++ docs/gaps.md | 8 +- docs/mcp.md | 13 ++ 16 files changed, 592 insertions(+), 115 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 8379858745..eb436e9711 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -538,20 +538,15 @@ fn hit_children( } /// The order a click at `p` tries the children of `parent` in, front first: their stacking order -/// from the top, except that in an Intertwine group the members drawn over the others at `p` -/// come first (from the top among them too). +/// from the top, except that in an Intertwine group the members are tried in the order they are +/// drawn at `p`, from the top ([`crate::intertwine::tier_at`]). fn hit_order<'a>(parent: &Node, children: &'a [std::sync::Arc], p: Point) -> impl Iterator + 'a { - let over: Vec = if matches!(parent.kind, NodeKind::Intertwine { .. }) { - let contains = |a: &vectorcraft_geom::PathData| fill_contains(&a.to_bezpath(), vectorcraft_geom::FillRule::NonZero, p); - (0..children.len()).rev().filter(|i| children.get(*i).and_then(|c| crate::intertwine::over_area(c)).is_some_and(contains)).collect() - } else { - vec![] - }; - let rest = (0..children.len()).rev().filter({ - let over = over.clone(); - move |i| !over.contains(i) - }); - over.into_iter().chain(rest) + let mut order: Vec = (0..children.len()).rev().collect(); + if matches!(parent.kind, NodeKind::Intertwine { .. }) { + let tier = |i: usize| children.get(i).map_or(0, |c| crate::intertwine::tier_at(c, p)); + order.sort_by_cached_key(|i| std::cmp::Reverse((tier(*i), *i))); + } + order.into_iter() } /// A click on the strokes of a path or compound path `n` along `bp`: what any visible stroke diff --git a/crates/doc/src/intertwine.rs b/crates/doc/src/intertwine.rs index e22ccbbaf3..8a6ab6786f 100644 --- a/crates/doc/src/intertwine.rs +++ b/crates/doc/src/intertwine.rs @@ -1,36 +1,51 @@ //! Object › Intertwine: objects that pass over and under each other. //! //! An Intertwine group ([`NodeKind::Intertwine`]) keeps its members as they are, in their own -//! stacking order. A member can be drawn over the other members in part of the group: that area -//! is the member's [`crate::node::NodeExtras::intertwine`], in document coordinates. The group -//! draws (and exports, and is hit) as its live expansion ([`expand`]): the members, then, for -//! each member with an area, a copy of it clipped to that area. Where several members are drawn -//! over the others in one place, the upper one in the stacking order ends on top. +//! stacking order. A member can be drawn over other members in part of the group, at a tier: the +//! area of tier 1 is the member's [`crate::node::NodeExtras::intertwine`], and the areas of tiers 2 +//! and up are its [`crate::node::NodeExtras::intertwine_tiers`], in document coordinates. In each +//! place the members are drawn by their tier there (0 outside their areas), and members of one +//! tier in their stacking order, so any order of the members can be set for each overlap area. +//! The group draws (and exports, and is hit) as its live expansion ([`expand`]): the members, +//! then, tier by tier, a copy of each member with an area of that tier clipped to it. //! //! The members stay editable, and Release gives them back as they were (the areas let go). //! Behaviour: . use std::sync::Arc; -use vectorcraft_geom::{FillRule, PathData}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{FillRule, PathData, Point}; use crate::{Node, NodeId, NodeKind}; -/// The area where `n` is drawn over the other members of its Intertwine group (empty: nowhere). -pub fn over_area(n: &Node) -> Option<&PathData> { - n.extras().intertwine.as_deref().filter(|a| !a.is_empty()) +/// The areas where `n` is drawn over other members of its Intertwine group, each with its tier +/// (1 and up); empty ones are left out. +pub fn tier_areas(n: &Node) -> impl Iterator { + let e = n.extras(); + e.intertwine + .as_deref() + .map(|a| (1, a)) + .into_iter() + .chain(e.intertwine_tiers.iter().enumerate().map(|(k, a)| (k + 2, a))) + .filter(|(_, a)| !a.is_empty()) } -/// The members of an Intertwine group evaluated as plain art: the members (ids kept), then each -/// member with an area drawn over the others, as a clip group of that area around a copy of it -/// (ids 0: generated art). +/// The tier `n` is drawn at at `p`: the highest tier whose area holds `p` (0: none does). +pub fn tier_at(n: &Node, p: Point) -> usize { + tier_areas(n).filter(|(_, a)| fill_contains(&a.to_bezpath(), FillRule::NonZero, p)).map(|(t, _)| t).max().unwrap_or(0) +} + +/// The members of an Intertwine group evaluated as plain art: the members (ids kept), then, for +/// each tier from 1 up, each member with an area of that tier, as a clip group of that area +/// around a copy of it (ids 0: generated art). pub fn expand(children: &[Arc]) -> Vec { let mut out: Vec = children.iter().map(|c| plain(c)).collect(); - for c in children { - let Some(area) = over_area(c) else { continue }; - if !c.visible { - continue; - } + let mut over: Vec<(usize, usize, &PathData)> = + children.iter().enumerate().filter(|(_, c)| c.visible).flat_map(|(i, c)| tier_areas(c).map(move |(t, a)| (t, i, a))).collect(); + over.sort_by_key(|(t, i, _)| (*t, *i)); + for (_, i, area) in over { + let Some(c) = children.get(i) else { continue }; let mut clip = Node::new(NodeId(0), NodeKind::Path { path: area.clone(), rule: FillRule::NonZero, live: None, clipping: true, guide: false }); clip.appearance = crate::Appearance::default().into(); let mut copy = plain(c); @@ -40,11 +55,13 @@ pub fn expand(children: &[Arc]) -> Vec { out } -/// `n` without its Intertwine area (the expansion is plain art). +/// `n` without its Intertwine areas (the expansion is plain art). fn plain(n: &Node) -> Node { let mut n = n.clone(); - if n.extras().intertwine.is_some() { - n.extras_mut().intertwine = None; + if n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty() { + let mut e = n.extras_mut(); + e.intertwine = None; + e.intertwine_tiers = Vec::new(); } n } @@ -88,6 +105,28 @@ mod tests { assert_eq!((out[2].id, children[1].id), (NodeId(0), NodeId(0)), "generated art has no ids of its own"); } + #[test] + fn copies_are_drawn_tier_by_tier() { + let over = || shapes::rectangle(Rect::new(5.0, 0.0, 10.0, 10.0)); + // The lower member at tier 2, the upper one at tier 1: the lower one ends on top. + let mut a = (*square(1, 0.0)).clone(); + a.extras_mut().intertwine_tiers = vec![over()]; + let mut b = (*square(2, 5.0)).clone(); + b.extras_mut().intertwine = Some(Box::new(over())); + let kids = vec![Arc::new(a), Arc::new(b)]; + assert_eq!((tier_at(&kids[0], Point::new(7.0, 5.0)), tier_at(&kids[1], Point::new(7.0, 5.0))), (2, 1)); + assert_eq!(tier_at(&kids[0], Point::new(2.0, 5.0)), 0); + let out = expand(&kids); + assert_eq!(out.len(), 4, "both members, then the copy of tier 1, then the one of tier 2"); + assert!(out.iter().all(|n| n.extras().intertwine.is_none() && n.extras().intertwine_tiers.is_empty()), "the expansion is plain art"); + let copied = |n: &Node| match &n.kind { + NodeKind::Group { children, clip: true } => children[1].path_data().cloned(), + k => panic!("a clip group: {k:?}"), + }; + assert_eq!(copied(&out[2]).as_ref(), kids[1].path_data()); + assert_eq!(copied(&out[3]).as_ref(), kids[0].path_data()); + } + #[test] fn a_hidden_member_is_not_drawn_over_the_others() { let mut a = (*square(1, 0.0)).clone(); diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index a971a383b5..bf9259943b 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -253,6 +253,9 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize { b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize); b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::() + json_bytes(t)); b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::() + path_bytes(a)); + if e.intertwine_tiers.capacity() > 0 { + b += ALLOC + e.intertwine_tiers.capacity() * size_of::() + e.intertwine_tiers.iter().map(path_bytes).sum::(); + } b += e.objects_on_path.as_deref().map_or(0, |o| { ALLOC + size_of::() + o.members.capacity() * size_of::() }); diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 633f9b6967..93145985be 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -44,6 +44,11 @@ pub struct NodeExtras { /// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates, /// filled non-zero) where this object is drawn over the group's other members. pub intertwine: Option>, + /// Object › Intertwine: as a member of an Intertwine group, the areas (document coordinates, + /// filled non-zero) where this object is drawn over members that are themselves drawn over + /// others there. Item `k` is the area of tier `k + 2`; [`NodeExtras::intertwine`] is tier 1 + /// (see [`crate::intertwine`]). + pub intertwine_tiers: Vec, /// Live Paint group: its Gap Options (Object › Live Paint › Gap Options; `None`: the defaults). pub live_paint_gaps: Option>, /// Object › Objects on Path: the group's path and the objects attached to it (see @@ -76,6 +81,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { perspective: None, dimension: None, intertwine: None, + intertwine_tiers: Vec::new(), live_paint_gaps: None, objects_on_path: None, colorize: None, diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index edab5f73c9..e5c98886a2 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -496,8 +496,13 @@ impl Node { Arc::make_mut(&mut m.art).transform_scaled(a, sc); } // The area where an Intertwine member is drawn over the others moves with it. - if let Some(area) = self.extras_if_any().and_then(|e| e.intertwine.as_mut()) { - area.transform(a); + if let Some(e) = self.extras_if_any() { + if let Some(area) = e.intertwine.as_mut() { + area.transform(a); + } + for area in &mut e.intertwine_tiers { + area.transform(a); + } } } diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index b4cc7b0722..df675580e2 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -484,6 +484,23 @@ fn objects_are_read_within_the_node_budget() { assert!(with_node_budget(3, read).is_ok()); } +/// An Intertwine member's areas of tier 2 and up are written and read back, and each one counts +/// against [`with_node_budget`] as an object does, so a file of many empty areas is refused. +#[test] +fn intertwine_tiers_are_read_within_the_node_budget() { + let mut n = Node::group(NodeId(1), vec![]); + let area = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + n.extras_mut().intertwine_tiers = vec![PathData::default(), area]; + let json = serde_json::to_string(&n).unwrap(); + assert!(json.contains("\"intertwine_tiers\""), "{json}"); + let read = || serde_json::from_str::(&json); + assert_eq!(with_node_budget(3, read).unwrap(), n, "the object and its two areas fit a budget of three"); + let why = with_node_budget(2, read).unwrap_err().to_string(); + assert!(why.contains("more than 2 objects"), "{why}"); + let plain = serde_json::to_string(&Node::group(NodeId(1), vec![])).unwrap(); + assert!(!plain.contains("intertwine_tiers"), "an object without tiers writes none: {plain}"); +} + /// #3587: fields read before an object's `type` are buffered value by value within /// [`with_buffered_value_budget`], each counted once: a group read back from the buffer buffers /// its own fields again without counting them twice. VectorCraft writes `type` first, which diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 76d4c3c14a..3456b359e2 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -46,6 +46,7 @@ impl Serialize for Node { e.perspective.is_none(), e.dimension.is_none(), e.intertwine.is_none(), + e.intertwine_tiers.is_empty(), e.live_paint_gaps.is_none(), e.objects_on_path.is_none(), e.colorize.is_none(), @@ -85,6 +86,7 @@ impl Serialize for Node { field!("perspective", &e.perspective); field!("dimension", &e.dimension); field!("intertwine", &e.intertwine); + field!("intertwine_tiers", &e.intertwine_tiers); field!("live_paint_gaps", &e.live_paint_gaps); field!("objects_on_path", &e.objects_on_path); field!("colorize", &e.colorize); @@ -123,11 +125,39 @@ pub fn with_node_budget(max: usize, f: impl FnOnce() -> T) -> T { /// each counts once, and the id usually comes first, before the node's children are read. fn counted_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { let id = NodeId::deserialize(d)?; + count_one()?; + Ok(id) +} + +/// Count one object against [`with_node_budget`]. +fn count_one() -> Result<(), E> { if let Some((left, max)) = NODES_LEFT.get() { - let left = left.checked_sub(1).ok_or_else(|| serde::de::Error::custom(format!("the document has more than {max} objects")))?; + let left = left.checked_sub(1).ok_or_else(|| E::custom(format!("the document has more than {max} objects")))?; NODES_LEFT.set(Some((left, max))); } - Ok(id) + Ok(()) +} + +/// A member's Intertwine areas of tier 2 and up, each counting against [`with_node_budget`] as +/// an object does: a compressed file of repeated empty areas stays small while they take memory +/// once read. +fn counted_tiers<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + struct Tiers; + impl<'de> serde::de::Visitor<'de> for Tiers { + type Value = Vec; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a list of areas") + } + fn visit_seq>(self, mut seq: A) -> Result, A::Error> { + let mut out = Vec::new(); + while let Some(area) = seq.next_element::()? { + count_one()?; + out.push(area); + } + Ok(out) + } + } + d.deserialize_seq(Tiers) } /// How a [`Node`] is read: the flat field list of the file format. Fields move into the node @@ -186,6 +216,8 @@ pub(super) struct NodeWire { dimension: Option>, #[serde(default)] intertwine: Option>, + #[serde(default, deserialize_with = "counted_tiers")] + intertwine_tiers: Vec, #[serde(default)] live_paint_gaps: Option>, #[serde(default)] @@ -215,6 +247,7 @@ impl From for Node { perspective: w.perspective, dimension: w.dimension, intertwine: w.intertwine, + intertwine_tiers: w.intertwine_tiers, live_paint_gaps: w.live_paint_gaps, objects_on_path: w.objects_on_path, colorize: w.colorize, diff --git a/crates/engine/src/cmd/intertwine.rs b/crates/engine/src/cmd/intertwine.rs index 27f1080e1f..23f1be1906 100644 --- a/crates/engine/src/cmd/intertwine.rs +++ b/crates/engine/src/cmd/intertwine.rs @@ -3,18 +3,19 @@ //! `object.intertwine.make` puts the selected objects in an Intertwine group //! (`NodeKind::Intertwine`), `object.intertwine.release` gives them back as they were. In between, //! `object.intertwine.arrange` picks overlap areas, by a click (`at`) or by an enclosed path drawn -//! around them (`area`), and changes which member is drawn on top there: each member keeps the -//! area where it is drawn over the others (`NodeExtras::intertwine`, see -//! `vectorcraft_doc::intertwine`). Object › Expand turns the group into a plain group of what it -//! draws ([`expand_intertwines`]), which Ungroup takes apart. +//! around them (`area`), and changes the order the members are drawn in there: each member keeps +//! the areas where it is drawn over others, by tier (`NodeExtras::intertwine` and +//! `NodeExtras::intertwine_tiers`, see `vectorcraft_doc::intertwine`). Object › Expand turns the +//! group into a plain group of what it draws ([`expand_intertwines`]), which Ungroup takes apart. //! //! An overlap area is a face of the planar arrangement of what the members paint (their fills and //! strokes, type outlined; other objects by their bounds): the part where two or more of them //! overlap, split wherever a member's edge crosses it. //! //! Behaviour: (Make, -//! Release, clicking or drawing around an overlap, Bring to Front and Send to Back where three or -//! more objects overlap). +//! Release, clicking or drawing around an overlap, Bring to Front, Bring Forward, Send Backward +//! and Send to Back where three or more objects overlap: +//! ). use std::sync::Arc; @@ -62,7 +63,7 @@ pub fn specs() -> Vec { "Arrange Intertwine Area", [], None, - "{id?: Intertwine group (default: the selected one), at?: [x,y] (the overlap area under this point, as a click picks it) | area?: [[x,y]…] (a closed polygon drawn around overlap areas: every area whose inside it encloses), order?: toggle|front|back (toggle: the object drawn right below the top comes to the front, so two objects swap), member?: id (front and back: the object to move; default: front brings the object right below the top, back sends the top one)} → {count: areas changed, top: [id of the object now on top in each area]}", + "{id?: Intertwine group (default: the selected one), at?: [x,y] (the overlap area under this point, as a click picks it) | area?: [[x,y]…] (a closed polygon drawn around overlap areas: every area whose inside it encloses), order?: toggle|front|forward|backward|back (toggle: the object drawn right below the top comes to the front, so two objects swap; forward and backward move an object one place up or down among the objects in that area; the others keep their order there), member?: id (front, forward, backward and back: the object to move; default: front and forward move the object right below the top, back and backward the top one)} → {count: areas changed (an area already in that order is not changed, and with none changed there is no undo step), top: [id of the object now on top in each changed area]}", has_doc, arrange ), @@ -173,7 +174,10 @@ fn release(s: &mut Session, _: &Value) -> Result { .flatten() .map(|c| { let mut c = (**c).clone(); - c.extras_mut().intertwine = None; + let mut e = c.extras_mut(); + e.intertwine = None; + e.intertwine_tiers = Vec::new(); + drop(e); c }) .collect(); @@ -228,6 +232,8 @@ pub(crate) fn expand_intertwines(d: &mut Document, roots: &[NodeId]) -> Result Option { Some(PathData::single(SubPath::polyline(&pts, true))) } -/// `n`'s area with `face` added (`add`) or taken out. -fn with_area(n: &mut Node, face: &PathData, add: bool) { - let old = n.extras().intertwine.as_deref().cloned(); - let new = match (old, add) { +/// Area `old` with `face` added (`add`) or taken out. +fn with_face(old: Option, face: &PathData, add: bool) -> Option { + match (old, add) { (None, true) => nonempty(face.clone()), (None, false) => None, (Some(a), true) => nonempty(po::boolean(&a, FillRule::NonZero, face, FillRule::NonZero, po::BoolOp::Union)), (Some(a), false) => nonempty(po::boolean(&a, FillRule::NonZero, face, FillRule::NonZero, po::BoolOp::Difference)), - }; - if new.as_ref() != n.extras().intertwine.as_deref() { - n.extras_mut().intertwine = new.map(Box::new); } } -/// Bring member `x` to the front of `face` (`front`) or send it to the back there; returns the -/// member now on top there. -fn arrange_face(children: &mut [Arc], face: &Face, x: usize, front: bool) -> Option { - let lowest = face.members.iter().min().copied()?; - let highest = face.members.iter().max().copied()?; - for &i in &face.members { - let Some(c) = children.get_mut(i) else { continue }; - let c = Arc::make_mut(c); - if front { - // Only `x` is drawn over the others here, unless it is on top in its own order. - with_area(c, &face.path, i == x && x != highest); - } else if i == x { - with_area(c, &face.path, false); - } else if x != lowest { - // Every other member is drawn over `x`, keeping their own order among them. - with_area(c, &face.path, true); +/// Draw `n` at `tier` in `face` (0: in its own order): `face` joins its area of that tier and +/// leaves its areas of the other tiers. +fn set_tier(n: &mut Node, face: &PathData, tier: usize) { + let e = n.extras(); + let mut areas: Vec> = + std::iter::once(e.intertwine.as_deref().cloned()).chain(e.intertwine_tiers.iter().map(|a| (!a.is_empty()).then(|| a.clone()))).collect(); + if areas.len() < tier { + areas.resize(tier, None); + } + for (k, a) in areas.iter_mut().enumerate() { + *a = with_face(a.take(), face, k + 1 == tier); + } + while areas.len() > 1 && areas.last().is_some_and(Option::is_none) { + areas.pop(); + } + let mut areas = areas.into_iter(); + let first = areas.next().flatten(); + let rest: Vec = areas.map(Option::unwrap_or_default).collect(); + if first.as_ref() != n.extras().intertwine.as_deref() || rest != n.extras().intertwine_tiers { + let mut e = n.extras_mut(); + e.intertwine = first.map(Box::new); + e.intertwine_tiers = rest; + } +} + +/// The tiers that draw members in `order` (bottom first): each member one tier above the member +/// below it when it comes before that member in the group's order, else at the same tier. +fn tiers(order: &[usize]) -> Vec<(usize, usize)> { + let mut tier = 0; + let mut below: Option = None; + order + .iter() + .map(|&i| { + if below.is_some_and(|b| i < b) { + tier += 1; + } + below = Some(i); + (i, tier) + }) + .collect() +} + +/// Draw the members of `face` in `order` there (bottom first), leaving the other areas as they +/// are. +fn arrange_face(children: &mut [Arc], face: &Face, order: &[usize]) { + for (i, tier) in tiers(order) { + if let Some(c) = children.get_mut(i) { + set_tier(Arc::make_mut(c), &face.path, tier); } } - drawn_order(children, face).last().copied() +} + +/// `drawn` (the members of an area, bottom first) with member `x` moved as `order` says. +fn moved(drawn: &[usize], x: usize, order: Order) -> Vec { + let mut out = drawn.to_vec(); + let Some(at) = out.iter().position(|i| *i == x) else { return out }; + match order { + Order::Toggle | Order::Front => { + out.remove(at); + out.push(x); + } + Order::Back => { + out.remove(at); + out.insert(0, x); + } + Order::Forward if at + 1 < out.len() => out.swap(at, at + 1), + Order::Backward if at > 0 => out.swap(at - 1, at), + Order::Forward | Order::Backward => {} + } + out } fn arrange(s: &mut Session, p: &Value) -> Result { @@ -309,15 +362,17 @@ fn arrange(s: &mut Session, p: &Value) -> Result { let order = match str_param(p, "order").unwrap_or("toggle") { "toggle" => Order::Toggle, "front" => Order::Front, + "forward" => Order::Forward, + "backward" => Order::Backward, "back" => Order::Back, - o => return Err(bad(C, format!("unknown order `{o}`: toggle, front or back"))), + o => return Err(bad(C, format!("unknown order `{o}`: toggle, front, forward, backward or back"))), }; let member = match p.get("member") { Some(v) => Some(checked_id(s, v, C)?), None => None, }; if member.is_some() && order == Order::Toggle { - return Err(bad(C, "member is for order front or back")); + return Err(bad(C, "member is for order front, forward, backward or back")); } let children: Vec> = s.doc()?.doc.node(group).and_then(Node::children).cloned().unwrap_or_default(); let member = match member { @@ -345,25 +400,32 @@ fn arrange(s: &mut Session, p: &Value) -> Result { { return Err(bad(C, "that object is not in the overlap")); } - let tops = s.edit("Intertwine", |d, _| { + // The new order of each area that changes; areas already in that order are left out. + let mut plans: Vec<(&Face, Vec)> = vec![]; + for face in found.iter().filter(|f| member.is_none_or(|m| f.members.contains(&m))) { + let drawn = drawn_order(&children, face); + let x = match (order, member) { + (_, Some(m)) => Some(m), + (Order::Toggle | Order::Front | Order::Forward, None) => drawn.iter().rev().nth(1).copied(), + (Order::Back | Order::Backward, None) => drawn.last().copied(), + }; + let Some(x) = x else { continue }; + let new = moved(&drawn, x, order); + if new != drawn { + plans.push((face, new)); + } + } + let tops: Vec = plans.iter().filter_map(|(_, new)| children.get(*new.last()?)).map(|c| c.id.0).collect(); + if plans.is_empty() { + return Ok(json!({ "count": 0, "top": tops })); + } + s.edit("Intertwine", |d, _| { let n = d.node_mut(group).ok_or(EngineError::NoNode(group))?; let NodeKind::Intertwine { children } = &mut n.kind else { return Err(EngineError::NoNode(group)) }; - let mut tops = vec![]; - for face in found.iter().filter(|f| member.is_none_or(|m| f.members.contains(&m))) { - let drawn = drawn_order(children, face); - let (x, front) = match (order, member) { - (Order::Toggle, _) => (drawn.iter().rev().nth(1).copied(), true), - (Order::Front, m) => (m.or(drawn.iter().rev().nth(1).copied()), true), - (Order::Back, m) => (m.or(drawn.last().copied()), false), - }; - let Some(x) = x else { continue }; - if let Some(top) = arrange_face(children, face, x, front) - && let Some(c) = children.get(top) - { - tops.push(c.id.0); - } + for (face, new) in &plans { + arrange_face(children, face, new); } - Ok(tops) + Ok(()) })?; - Ok(json!({ "count": tops.len(), "top": tops })) + Ok(json!({ "count": plans.len(), "top": tops })) } diff --git a/crates/engine/src/tests/intertwine.rs b/crates/engine/src/tests/intertwine.rs index bdd3455f7f..6895d74a07 100644 --- a/crates/engine/src/tests/intertwine.rs +++ b/crates/engine/src/tests/intertwine.rs @@ -135,6 +135,133 @@ fn front_and_back_choose_the_member_where_three_objects_overlap() { assert!(e.to_string().contains("999"), "{e}"); } +/// The rings with a green bar across their top crossing, in front of both, made into an +/// Intertwine group: (group, a, b, c). A, B and C overlap at (50, 30); only A and B at (50, 70). +fn rings_and_bar(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { + let (a, b) = rings(s); + let c = id_of(&s.execute("shape.rectangle", &json!({"x": 46, "y": 20, "width": 8, "height": 20})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#00ff00"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [c.0], "none": true})).unwrap(); + select(s, &[a, b, c]); + let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap()); + (g, a, b, c) +} + +/// The members of the overlap area of Intertwine group `g` at (x, y), in the order they are drawn +/// there, bottom first. +fn order_at(d: &Document, g: NodeId, x: f64, y: f64) -> Vec { + use vectorcraft_tools::intertwine::{drawn_order, face_at, faces}; + let children = d.node(g).unwrap().children().unwrap(); + let face = face_at(&faces(children), vectorcraft_geom::Point::new(x, y)).unwrap(); + drawn_order(children, &face).into_iter().map(|i| children[i].id).collect() +} + +/// Bring Forward and Send Backward move an object one place among the objects of one overlap +/// area, keeping the others' order, so every order of three objects can be set there (C, B, A +/// included); the other areas stay as they are. +#[test] +fn forward_and_backward_move_an_object_one_place_in_an_area() { + let mut s = session(); + let (g, a, b, c) = rings_and_bar(&mut s); + let order = |s: &Session| order_at(&s.doc().unwrap().doc, g, 50.0, 30.0); + let v = arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": a.0})); + assert_eq!((&v["count"], &v["top"]), (&json!(1), &json!([c.0]))); + assert_eq!(order(&s), [b, a, c]); + arrange(&mut s, json!({"at": [50, 30], "order": "backward", "member": c.0})); + assert_eq!(order(&s), [b, c, a]); + assert!(red(&render(&s), 50, 30), "A is on top"); + let v = arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": b.0})); + assert_eq!(v["top"], json!([a.0])); + assert_eq!(order(&s), [c, b, a], "the reverse of the group's order"); + assert_eq!(hit(&s, 50.0, 30.0), Some(a), "a click picks the object drawn on top"); + // Without a member: forward moves the object right below the top, backward the top one. + arrange(&mut s, json!({"at": [50, 30], "order": "backward"})); + assert_eq!(order(&s), [c, a, b]); + assert!(blue(&render(&s), 50, 30)); + assert_eq!(hit(&s, 50.0, 30.0), Some(b)); + arrange(&mut s, json!({"at": [50, 30], "order": "forward"})); + assert_eq!(order(&s), [c, b, a]); + // Bring to Front and Send to Back keep the order of the others. + arrange(&mut s, json!({"at": [50, 30], "order": "front", "member": c.0})); + assert_eq!(order(&s), [b, a, c]); + arrange(&mut s, json!({"at": [50, 30], "order": "back", "member": a.0})); + assert_eq!(order(&s), [a, b, c]); + // The crossing where only the rings overlap is as it was. + assert_eq!(order_at(&s.doc().unwrap().doc, g, 50.0, 70.0), [a, b]); + assert!(blue(&render(&s), 50, 70)); + // There only the rings count: forward moves A over B, and C is not in that area. + let v = arrange(&mut s, json!({"at": [50, 70], "order": "forward"})); + assert_eq!(v["top"], json!([a.0])); + assert!(red(&render(&s), 50, 70)); + let e = s.execute("object.intertwine.arrange", &json!({"at": [50, 70], "order": "backward", "member": c.0})).unwrap_err(); + assert!(e.to_string().contains("not in the overlap"), "{e}"); + assert_eq!(order(&s), [a, b, c]); +} + +/// An object already at the end it is moved to is not moved: no area changes and no undo step is +/// recorded. One move is one undo step, and undo, redo and a saved file keep the order. +#[test] +fn a_move_that_changes_nothing_records_nothing_and_orders_survive_undo_and_save() { + let mut s = session(); + let (g, a, b, c) = rings_and_bar(&mut s); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = undo(&s); + for (order, member) in [("forward", c), ("front", c), ("backward", a), ("back", a)] { + let v = arrange(&mut s, json!({"at": [50, 30], "order": order, "member": member.0})); + assert_eq!((&v["count"], &v["top"]), (&json!(0), &json!([])), "{order}"); + } + assert_eq!(undo(&s), before, "nothing to undo"); + arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": b.0})); + arrange(&mut s, json!({"at": [50, 30], "order": "backward", "member": c.0})); + arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": a.0})); + assert_eq!(undo(&s), before + 3, "one undo step a move"); + let order = |s: &Session| order_at(&s.doc().unwrap().doc, g, 50.0, 30.0); + assert_eq!(order(&s), [c, b, a]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(order(&s), [c, a, b]); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(order(&s), [c, b, a]); + let data = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone(); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "rings.vectorcraft", "dataBase64": data})).unwrap(); + assert_eq!(order_at(&o.doc().unwrap().doc, g, 50.0, 30.0), [c, b, a]); + assert!(red(&render(&o), 50, 30) && blue(&render(&o), 50, 70)); + // Expand draws the same. + s.execute("object.expand", &json!({"fill": false, "stroke": false})).unwrap(); + assert!(red(&render(&s), 50, 30) && blue(&render(&s), 50, 70)); +} + +/// Where three or more objects overlap, hovering highlights the outline of the object nearest to +/// the pointer. +#[test] +fn hovering_where_three_overlap_highlights_the_nearest_object() { + use kurbo::Shape; + let mut s = session(); + let view = ViewInfo::default(); + // Squares from x = 0, 20 and 40, 60 wide: all three overlap from x = 40 to 60. + let ids: Vec = + [0, 20, 40].iter().map(|x| id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 60, "height": 60})).unwrap())).collect(); + select(&mut s, &ids); + s.execute("object.intertwine.make", &json!({})).unwrap(); + let highlighted = |s: &mut Session, x: f64| { + s.pointer(&vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Move, x, 30.0), view).unwrap(); + let o = s.overlays(view); + let [vectorcraft_tools::Overlay::Path { path, .. }] = o.as_slice() else { panic!("one highlight: {o:?}") }; + let r = path.bounding_box(); + (r.x0, r.x1) + }; + // Within the half point a 1 pt stroke reaches past each edge. + let near = |(x0, x1): (f64, f64), (e0, e1): (f64, f64)| (x0 - e0).abs() <= 0.6 && (x1 - e1).abs() <= 0.6; + // By the left edge of the third square, then by the right edge of the first one. + let h = highlighted(&mut s, 41.0); + assert!(near(h, (40.0, 100.0)), "{h:?}"); + let h = highlighted(&mut s, 59.0); + assert!(near(h, (0.0, 60.0)), "{h:?}"); + // Where two overlap, the area is highlighted. + let h = highlighted(&mut s, 30.0); + assert!(near(h, (20.0, 40.0)), "{h:?}"); +} + #[test] fn release_gives_the_objects_back_as_they_were() { let mut s = session(); diff --git a/crates/tools/src/intertwine.rs b/crates/tools/src/intertwine.rs index 984b272e6e..fb292ea37c 100644 --- a/crates/tools/src/intertwine.rs +++ b/crates/tools/src/intertwine.rs @@ -7,7 +7,9 @@ //! which member is drawn on top there. //! //! The Intertwine tool is what `object.intertwine.make` and `object.intertwine.edit` leave the -//! canvas in: hovering highlights the overlap area under the pointer, a click arranges it, a drag +//! canvas in: hovering highlights the overlap area under the pointer (where three or more members +//! overlap, the outline of the member nearest to the pointer, which the right-click menu +//! arranges: [`menu_target`]), a click arranges it, a drag //! draws a path around overlap areas (Shift: a rectangle) and arranges every one inside it. //! Esc or Enter goes back to the tool chosen before. Behaviour: //! . @@ -16,7 +18,7 @@ use std::sync::Arc; use kurbo::BezPath; use serde_json::{Value, json}; -use vectorcraft_doc::intertwine::over_area; +use vectorcraft_doc::intertwine::tier_at; use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind}; use vectorcraft_effects as effects; use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath, shapes}; @@ -101,8 +103,18 @@ pub struct Face { /// Every overlap area of `children`. pub fn faces(children: &[Arc]) -> Vec { + faces_of(&painted_areas(children)) +} + +/// What each of `children` paints ([`painted_area`]), by child index. +pub fn painted_areas(children: &[Arc]) -> Vec> { + children.iter().map(|c| painted_area(c)).collect() +} + +/// Every overlap area of the members that paint `areas` ([`painted_areas`]). +pub fn faces_of(areas: &[Option]) -> Vec { let shapes: Vec = - children.iter().enumerate().filter_map(|(i, c)| Some(po::Shape::new(painted_area(c)?, FillRule::NonZero, i as u64))).collect(); + areas.iter().enumerate().filter_map(|(i, a)| Some(po::Shape::new(a.clone()?, FillRule::NonZero, i as u64))).collect(); let key = |k: usize| shapes.get(k).map(|s| s.key as usize); po::regions(&shapes) .into_iter() @@ -124,15 +136,37 @@ pub fn faces_in(faces: &[Face], lasso: &PathData) -> Vec { faces.iter().filter(|f| contains(lasso, f.inside)).cloned().collect() } -/// The members of `face` in the order they are drawn there, bottom first: those drawn in their -/// own order, then those drawn over the others there, each run in the group's order. +/// The members of `face` in the order they are drawn there, bottom first: by their tier there +/// ([`tier_at`]), and members of one tier in the group's order. pub fn drawn_order(children: &[Arc], face: &Face) -> Vec { - let over = |i: &usize| children.get(*i).and_then(|c| over_area(c)).is_some_and(|a| contains(a, face.inside)); + let tier = |i: usize| children.get(i).map_or(0, |c| tier_at(c, face.inside)); let mut order = face.members.clone(); - order.sort_by_key(|i| (over(i), *i)); + order.sort_by_cached_key(|i| (tier(*i), *i)); order } +/// The fewest members an overlap area needs for the right-click menu that arranges one of them. +pub const MENU_MEMBERS: usize = 3; + +/// The member of `face` whose outline (what it paints, `areas` from [`painted_areas`]) is nearest +/// to `p`. +pub fn nearest_member(areas: &[Option], face: &Face, p: Point) -> Option { + let dist = |i: usize| areas.get(i).and_then(Option::as_ref).map(|a| vectorcraft_geom::hit::distance_to_outline(&a.to_bezpath(), p)); + face.members.iter().filter_map(|i| Some((*i, dist(*i)?))).filter(|(_, d)| d.is_finite()).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i) +} + +/// What a right-click at `p` arranges with the Intertwine tool: the Intertwine group of the +/// selection, and the member nearest to `p` (by id) in the overlap area under `p`, when +/// [`MENU_MEMBERS`] or more members overlap there. +pub fn menu_target(doc: &Document, selected: &[NodeId], p: Point) -> Option<(NodeId, NodeId)> { + let g = selected_group(doc, selected)?; + let children = doc.node(g)?.children()?; + let areas = painted_areas(children); + let face = face_at(&faces_of(&areas), p).filter(|f| f.members.len() >= MENU_MEMBERS)?; + let m = nearest_member(&areas, &face, p)?; + Some((g, children.get(m)?.id)) +} + /// The Intertwine group the selection is in, or is (the innermost one around the first selected /// object that is in one). pub fn selected_group(doc: &Document, selected: &[NodeId]) -> Option { @@ -149,6 +183,8 @@ pub fn is_intertwine(n: &Node) -> bool { struct Found { revision: (u64, u64), group: NodeId, + /// What each member paints, by child index. + areas: Arc>>, faces: Arc>, } @@ -159,7 +195,8 @@ pub struct IntertwineTool { prev: Option, /// The overlap areas of the group, for the document revision they were found in. cache: Option, - /// The overlap area under the pointer. + /// What the pointer highlights: the overlap area under it, or where [`MENU_MEMBERS`] or more + /// members overlap, the outline of the member nearest to it. hover: Option, /// A drag's points (document space); the first is where it started. points: Vec, @@ -170,17 +207,31 @@ pub struct IntertwineTool { impl IntertwineTool { fn faces(&mut self, cx: &ToolContext) -> Option<(NodeId, Arc>)> { + self.found(cx).map(|c| (c.group, c.faces.clone())) + } + + /// The overlap areas of the selection's group, found again when the document changed. + fn found(&mut self, cx: &ToolContext) -> Option<&Found> { let g = selected_group(cx.doc, &cx.selection.objects)?; - if let Some(c) = &self.cache - && c.revision == cx.revision - && c.group == g - { - return Some((g, c.faces.clone())); + if !self.cache.as_ref().is_some_and(|c| c.revision == cx.revision && c.group == g) { + let children = cx.doc.node(g)?.children()?; + let areas = painted_areas(children); + let faces = Arc::new(faces_of(&areas)); + self.cache = Some(Found { revision: cx.revision, group: g, areas: Arc::new(areas), faces }); } - let children = cx.doc.node(g)?.children()?; - let f = Arc::new(faces(children)); - self.cache = Some(Found { revision: cx.revision, group: g, faces: f.clone() }); - Some((g, f)) + self.cache.as_ref() + } + + /// What hovering `p` highlights ([`IntertwineTool::hover`]). + fn highlight(&mut self, cx: &ToolContext, p: Point) -> Option { + let found = self.found(cx)?; + let face = face_at(&found.faces, p)?; + if face.members.len() >= MENU_MEMBERS + && let Some(a) = nearest_member(&found.areas, &face, p).and_then(|m| found.areas.get(m)).and_then(Option::as_ref) + { + return Some(a.to_bezpath()); + } + Some(face.path.to_bezpath()) } /// The closed path the drag drew. @@ -209,7 +260,7 @@ impl Tool for IntertwineTool { let p = ev.pos; match ev.kind { PointerKind::Move => { - self.hover = self.faces(cx).and_then(|(_, f)| face_at(&f, p)).map(|f| f.path.to_bezpath()); + self.hover = self.highlight(cx, p); vec![] } PointerKind::Down => { @@ -332,6 +383,43 @@ mod tests { assert_eq!(drawn_order(&kids, &f[0]), [1, 0]); } + #[test] + fn members_drawn_at_higher_tiers_are_drawn_later() { + // Three squares over one another; the bottom one at tier 2, the middle one at tier 1. + let over = || shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let mut a = (*square(1, 0.0)).clone(); + a.extras_mut().intertwine_tiers = vec![over()]; + let mut b = (*square(2, 0.0)).clone(); + b.extras_mut().intertwine = Some(Box::new(over())); + let kids = vec![Arc::new(a), Arc::new(b), square(3, 0.0)]; + let f = faces(&kids); + assert_eq!(f.len(), 1); + assert_eq!(drawn_order(&kids, &f[0]), [2, 1, 0]); + } + + #[test] + fn the_member_nearest_to_the_pointer_is_picked_where_three_overlap() { + // Squares 20 wide from x = 0, 4 and 8: all three overlap from x = 8 to 20. + let wide = + |id: u64, x: f64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 20.0)), Appearance::default_art())); + let kids = vec![wide(1, 0.0), wide(2, 4.0), wide(3, 8.0)]; + let areas = painted_areas(&kids); + let all = faces_of(&areas); + let face = face_at(&all, Point::new(14.0, 10.0)).unwrap(); + assert_eq!(face.members, [0, 1, 2]); + // By the left edge of the third square, then by the right edge of the first one. + assert_eq!(nearest_member(&areas, &face, Point::new(8.5, 10.0)), Some(2)); + assert_eq!(nearest_member(&areas, &face, Point::new(19.5, 10.0)), Some(0)); + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let g = d.alloc_id(); + d.insert(Some(l), 0, Node::new(g, NodeKind::Intertwine { children: kids })).unwrap(); + assert_eq!(menu_target(&d, &[g], Point::new(8.5, 10.0)), Some((g, NodeId(3)))); + assert_eq!(menu_target(&d, &[g], Point::new(19.5, 10.0)), Some((g, NodeId(1)))); + assert_eq!(menu_target(&d, &[g], Point::new(6.0, 10.0)), None, "only two overlap there"); + assert_eq!(menu_target(&d, &[], Point::new(8.5, 10.0)), None, "no Intertwine group selected"); + } + #[test] fn a_lasso_takes_the_areas_whose_inside_it_encloses() { let kids = vec![square(1, 0.0), square(2, 5.0)]; diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index 8db01d4223..38311b773d 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -4,7 +4,9 @@ use super::{Ui, VectorcraftApp, Xf, json, widgets}; /// Right-click: the object under the pointer is selected first unless it already is, then the /// context menu lists what applies to the selection ([`crate::menus::context_items`]). The locked /// objects under the pointer ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in -/// `ui.context_locked` while the menu is open, for its Unlock submenu. +/// `ui.context_locked` while the menu is open, for its Unlock submenu. With the Intertwine tool, a +/// right-click where three or more objects of the group overlap keeps the selection and puts what +/// it arranges in `ui.context_intertwine` ([`vectorcraft_tools::intertwine::menu_target`]). pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: &Xf) { if resp.secondary_clicked() && let Some(p) = resp.interact_pointer_pos() @@ -12,7 +14,13 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: let p = xf.to_doc(p); let locked = hit_with(app, p, xf.zoom, |doc, p, opt| Some(vectorcraft_doc::hit::locked_objects_at(doc, p, opt))); app.ui.context_locked = app.session.active().map(|st| st.uid).zip(locked); - if let Some(st) = app.session.active() + app.ui.context_intertwine = app + .session + .active() + .filter(|_| app.session.tool_id() == "intertwine") + .and_then(|st| vectorcraft_tools::intertwine::menu_target(&st.doc, &st.selection.objects, p).map(|(g, m)| (st.uid, g, p, m))); + if app.ui.context_intertwine.is_none() + && let Some(st) = app.session.active() && let Some(top) = selection_hit_at(app, p, xf.zoom).map(|h| h.top_object(st.isolation)) && !st.selection.contains(top) { @@ -23,6 +31,7 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: let mut clicked = None; if resp.context_menu(|ui| crate::menus::context_menu_body(app, ui, &mut clicked)).is_none() { app.ui.context_locked = None; + app.ui.context_intertwine = None; } if let Some((id, p)) = clicked { crate::menus::invoke(app, &id, p); diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 9a4284bb17..3af95c6074 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -15,6 +15,21 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { if st.isolation.is_some() { v.extend([c("Exit Isolation Mode", "object.exitIsolation"), Sep]); } + // With the Intertwine tool, where three or more objects overlap: the object nearest to the + // right-click moves in that overlap area only (`object.intertwine.arrange`), in place of the + // Arrange submenu, which moves objects in the whole group. + let intertwine = app.ui.context_intertwine.filter(|(uid, ..)| *uid == st.uid && app.session.tool_id() == "intertwine"); + if let Some((_, group, at, member)) = intertwine { + let item = + |label, order| cp(label, "object.intertwine.arrange", json!({"id": group.0, "at": [at.x, at.y], "order": order, "member": member.0})); + v.extend([ + item("Bring to Front", "front"), + item("Bring Forward", "forward"), + item("Send Backward", "backward"), + item("Send to Back", "back"), + Sep, + ]); + } // Managing artboards from the canvas: with the Artboard tool, the menu locks and unlocks them // (`artboard.setProps` with `locked` for each artboard named; an entry with none to change is left out). if app.session.tool_id() == "artboard" { @@ -107,11 +122,11 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { if crate::panels::character::text_style(app).is_some() { v.push(sub("Bullets and Numbering", vec![c("Apply Bullets", "type.applyBullets"), c("Apply Numbers", "type.applyNumbers")])); } + v.extend([c("Make Guides", "view.guides.make"), Sep, sub("Transform", transform_items())]); + if intertwine.is_none() { + v.push(sub("Arrange", arrange_items())); + } v.extend([ - c("Make Guides", "view.guides.make"), - Sep, - sub("Transform", transform_items()), - sub("Arrange", arrange_items()), sub( "Select", vec![c("Next Object Above", "select.nextAbove"), c("Next Object Below", "select.nextBelow"), Sep, c("Deselect", "select.none")], diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index c85f6e6686..2b5c9c379c 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -357,6 +357,13 @@ pub struct UiState { /// saved. #[serde(skip)] pub context_locked: Option<(u64, Vec)>, + /// What the last right-click on the canvas with the Intertwine tool arranges, with the + /// document's `uid`: the Intertwine group, the point and the object nearest to it where three + /// or more objects overlap ([`vectorcraft_tools::intertwine::menu_target`]). The context menu + /// lists Bring to Front, Bring Forward, Send Backward and Send to Back for that object while it + /// is open. Not saved. + #[serde(skip)] + pub context_intertwine: Option<(u64, vectorcraft_doc::NodeId, vectorcraft_geom::Point, vectorcraft_doc::NodeId)>, /// Last tool shown in each toolbar slot (keyed by the slot's first tool id). #[serde(default)] pub slot_tool: std::collections::BTreeMap, @@ -833,6 +840,7 @@ impl Default for UiState { task_bar: true, task_bar_place: TaskBarPlace::default(), context_locked: None, + context_intertwine: None, slot_tool: Default::default(), floating_flyouts: vec![], toolbar_edits: ToolbarEdits::default(), diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 74e5c27854..e4445ca343 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -288,6 +288,61 @@ fn selected_type_has_apply_numbers() { assert_eq!(text.para_at(0).list.and_then(|l| l.number), Some(vectorcraft_doc::text::NumberStyle::Arabic)); } +/// The members of the overlap area of Intertwine group `g` at (x, y), in the order they are drawn +/// there, bottom first. +fn intertwine_order(app: &VectorcraftApp, g: NodeId, x: f64, y: f64) -> Vec { + use vectorcraft_tools::intertwine::{drawn_order, face_at, faces}; + let st = app.session.active().unwrap(); + let children = st.doc.node(g).unwrap().children().unwrap(); + let face = face_at(&faces(children), Point::new(x, y)).unwrap(); + drawn_order(children, &face).into_iter().map(|i| children[i].id).collect() +} + +/// With the Intertwine tool, a right-click where three or more objects of the group overlap lists +/// Bring to Front, Bring Forward, Send Backward and Send to Back for the object nearest to the +/// pointer in place of the Arrange submenu, and they move it in that overlap area only. Elsewhere +/// the menu is the usual one. +#[test] +fn right_click_where_three_intertwined_objects_overlap_arranges_the_nearest_one() { + let mut app = app(); + // Rectangles from x = 50, 90 and 130, 120 wide: all three overlap from x = 130 to 170. + let wide = |app: &mut VectorcraftApp, x: f64| { + NodeId(app.run("shape.rectangle", json!({"x": x, "y": 50, "width": 120, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + let (a, b, c) = (wide(&mut app, 50.0), wide(&mut app, 90.0), wide(&mut app, 130.0)); + app.run("select.set", json!({"ids": [a.0, b.0, c.0]})).unwrap(); + let g = NodeId(app.run("object.intertwine.make", json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(app.session.tool_id(), "intertwine"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let items = ["Bring to Front", "Bring Forward", "Send Backward", "Send to Back"]; + // By the right edge of A (the first rectangle), where all three overlap. + let p = screen(&app, 169.0, 100.0); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert_eq!(app.session.active().unwrap().selection.objects, [g], "the selection stays the group"); + for label in items { + assert!(has(&texts, label), "{label} in {texts:?}"); + } + assert!(!has(&texts, "Arrange"), "no Arrange submenu: {texts:?}"); + let rows: Vec = items.iter().map(|l| at(&texts, l).y).collect(); + assert!(rows.windows(2).all(|w| w[0] < w[1]), "in that order: {rows:?}"); + let Some(Item::Cmd(_, id, params)) = menus::context_items(&app).into_iter().find(|i| matches!(i, Item::Cmd("Bring Forward", ..))) else { + panic!("no Bring Forward item") + }; + assert_eq!(id, "object.intertwine.arrange"); + assert_eq!((¶ms["id"], ¶ms["order"], ¶ms["member"]), (&json!(g.0), &json!("forward"), &json!(a.0))); + // Bring Forward moves A one place up in that area only. + assert_eq!(intertwine_order(&app, g, 150.0, 100.0), [a, b, c]); + let texts = click(&mut app, &ctx, at(&texts, "Bring Forward"), PointerButton::Primary); + assert!(!has(&texts, "Bring Forward"), "the menu closes"); + assert_eq!(intertwine_order(&app, g, 150.0, 100.0), [b, a, c]); + assert_eq!(intertwine_order(&app, g, 110.0, 100.0), [a, b], "where only A and B overlap"); + // Where only two overlap, the menu is the usual one. + let p = screen(&app, 110.0, 100.0); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert!(has(&texts, "Arrange") && !has(&texts, "Bring Forward"), "{texts:?}"); +} + /// Every label the context menu can show is a menu string, so complete catalogs must translate it. #[test] fn every_context_label_is_a_menu_string() { diff --git a/docs/gaps.md b/docs/gaps.md index eb8d42b54e..b7ffe7f758 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -439,9 +439,11 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** Object › Intertwine (#1763): Make, Edit and Release; the Intertwine tool highlights the overlap area under the pointer, a click swaps which object is on top there, and a path (Shift: a rectangle) drawn around overlaps - arranges each one inside it; `object.intertwine.arrange` also brings an object to the front or sends it to the back - where three or more overlap. The group renders, saves and exports through its live expansion. Still missing: the - right-click Bring Forward / Send Backward menu where three or more objects overlap; adding objects to the group by + arranges each one inside it. Where three or more objects overlap, hovering highlights the object nearest to the + pointer, and a right-click offers Bring to Front, Bring Forward, Send Backward and Send to Back for it in that area + (`object.intertwine.arrange` with `order` front, forward, backward or back; + ). + The group renders, saves and exports through its live expansion. Still missing: adding objects to the group by dragging them in the Layers panel is untested. - **Done (from users' reports):** Object › Create Gradient Mesh on an embedded image turns it into a mesh over its rectangle, with the image's transform kept; each point takes the average colour and opacity of the picture around it diff --git a/docs/mcp.md b/docs/mcp.md index 89afecd0dd..d4898b5170 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1433,6 +1433,19 @@ Group. Construction mode ends when the group was in it. outside the bounds the group's original shapes had before the move, in the move's undo step. A shape whose bounds still overlap them only moves. The Selection tool sends it at the end of a move in Construction mode. +## Intertwine + +`object.intertwine.arrange {id?, at?|area?, order?, member?}` changes the order the objects of an Intertwine group are +drawn in, in the overlap areas under `at` or enclosed by the polygon `area`. `order` is `toggle` (the default: the +object right below the top comes to the front), `front`, `forward`, `backward` or `back`. `forward` and `backward` move +`member` one place up or down among the objects that overlap in that area, and `front` and `back` move it to the top or +the bottom there; the other objects keep their order. Without `member`, `front` and `forward` move the object right +below the top, and `back` and `backward` move the top one. The command returns `{count, top}`: the number of areas +whose order changed and the id of the object now on top in each. A move that changes no area returns +`{count: 0, top: []}` and records no undo step. With the Intertwine tool, a right-click where three or more objects +overlap offers Bring to Front, Bring Forward, Send Backward and Send to Back, which run this command for the object +nearest to the pointer. + ## Global Edit Select › Start Global Edit is `select.globalEdit {appearance?, size?, artboards?, includeCanvas?}`. With one path, From 9bb6d0f51d8bda8a12902ad406966a681eecf94f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 00:58:52 -0700 Subject: [PATCH 11/70] Eyedropper: Shift-click samples the color of a pattern or gradient mesh Shift-click with the Eyedropper sampled solid colors, gradients and images only; on a pattern fill or a gradient mesh it sampled nothing. - A pattern gives the color of the front-most tile art at the point, placed by the pattern's transform, at any tile size. Tile art that is itself a gradient, image, mesh, symbol or pattern is sampled the same way, and a pattern inside tile art moves with its tile. A gap between the tile art gives the color of what lies below. - A gradient mesh gives the patch color interpolated at the point. - A symbol instance gives the color of its symbol's art at the point. The Live Paint Bucket's Eyedropper sampling and Brush Options' Key Color eyedropper use the same sampling. --- crates/tools/src/xform/eyedropper.rs | 323 ++++++++++++++++++++++++--- 1 file changed, 298 insertions(+), 25 deletions(-) diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 5586b987df..1e612a6cb5 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -4,9 +4,10 @@ //! selection and the paint defaults (`appearance.copyFrom`); Alt-click: the selection's attributes //! onto the clicked object (`reverse`); Shift+Alt-click: add the clicked object's appearance to the //! selection's (`append`). Shift-click: sample only the colour under the cursor into the active -//! fill/stroke (`paint.sampleColor`; in a CMYK document an RGB color is stored as CMYK). Clicking -//! an image samples its pixels (averaged over the options' raster sample size; a CMYK image gives -//! its ink amounts). +//! fill/stroke (`paint.sampleColor`; in a CMYK document an RGB color is stored as CMYK): a +//! gradient's color at that point, a pattern's tile art there (after the pattern's transform), or +//! a gradient mesh's interpolated patch color. Clicking an image samples its pixels (averaged over +//! the options' raster sample size; a CMYK image gives its ink amounts). //! //! The Gradient panel's eyedropper sets the `stop` option (the tool to return to): the next click //! samples the colour under the cursor into the selected gradient stop (`paint.sampleColor @@ -17,9 +18,10 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::hit::{HitKind, hit_test, hit_test_visible}; -use vectorcraft_doc::{Node, NodeKind}; -use vectorcraft_geom::Point; +use vectorcraft_doc::hit::{HitKind, HitOptions, hit_test, hit_test_visible}; +use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{Affine, Point, Rect}; use super::paint_owner; use crate::params::color_json; @@ -49,18 +51,83 @@ pub fn paint_color_at(paint: &Paint, bounds: Option, p: } } +/// How many patterns and symbols deep a sample follows art inside art (tile art painted with a +/// pattern, a symbol whose art holds an instance of another): as deep as a document draws. +const MAX_NESTING: usize = vectorcraft_doc::depth::MAX_DRAWN_DEPTH; + +/// Most tiles of one pattern a sample looks at, front to back, for art that paints the point. +const MAX_TILES: usize = 1_000; + +/// The Eyedropper's hit options: a click inside a fill or among characters samples it too, +/// whatever Object and Type Object Selection by Path Only say. +fn sample_options(cx: &ToolContext) -> HitOptions { + HitOptions { path_only: false, type_path_only: false, ..cx.hit_options() } +} + /// The visible object under `p`, using the Eyedropper's source selection rules. pub(crate) fn sample_source(cx: &ToolContext, p: Point) -> Option<(vectorcraft_doc::NodeId, HitKind)> { - let opts = vectorcraft_doc::hit::HitOptions { path_only: false, type_path_only: false, ..cx.hit_options() }; - let h = hit_test_visible(cx.doc, p, opts)?; + let h = hit_test_visible(cx.doc, p, sample_options(cx))?; Some((paint_owner(cx.doc, h.leaf), h.kind)) } -/// The visible color under `p`, including image pixels and intermediate gradient colors. +/// The visible color under `p`, including image pixels, pattern tiles, mesh colors and +/// intermediate gradient colors. pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option { - let (id, kind) = sample_source(cx, p)?; - let n = cx.doc.node(id)?; - if matches!(n.kind, NodeKind::Image(_)) { image_color_at(cx, n, p) } else { paint_sample(n, kind == HitKind::Stroke, p) } + color_under(cx, cx.doc, p, sample_options(cx), 0) +} + +/// The color the front-most object of `doc` hit at `p` with `opts` shows there. Where a stroke +/// gives no color at `p` (a gap between its pattern's tiles), the object's own fill there does; +/// an object that gives none at all is passed over for the ones below it. +fn color_under(cx: &ToolContext, doc: &Document, p: Point, opts: HitOptions, depth: usize) -> Option { + let mut rest: Option = None; + loop { + let d = rest.as_ref().unwrap_or(doc); + let h = hit_test_visible(d, p, opts)?; + let id = paint_owner(d, h.leaf); + let n = d.node(id)?; + let on_stroke = h.kind == HitKind::Stroke; + let fill = || if on_stroke && fill_covers(n, p) { node_color_at(cx, d, n, false, p, depth) } else { None }; + if let Some(c) = node_color_at(cx, d, n, on_stroke, p, depth).or_else(fill) { + return Some(c); + } + rest.get_or_insert_with(|| doc.clone()).remove(id).ok()?; + } +} + +/// Whether the fill of path or compound path `n` covers `p`. +fn fill_covers(n: &Node, p: Point) -> bool { + match &n.kind { + NodeKind::Path { path, rule, .. } => fill_contains(&path.to_bezpath(), *rule, p), + NodeKind::Compound { rule, .. } => n.stroke_path().is_some_and(|bp| fill_contains(&bp, *rule, p)), + _ => false, + } +} + +/// The color `n` (in `doc`) shows at `p`: an image's pixels, a mesh's interpolated patch color, a +/// symbol instance's art, or the color of its fill (or its stroke, when the stroke was hit or there +/// is no fill) there. `depth` counts the patterns and symbols the sample is already inside. +fn node_color_at(cx: &ToolContext, doc: &Document, n: &Node, on_stroke: bool, p: Point, depth: usize) -> Option { + match &n.kind { + NodeKind::Image(_) => image_color_at(cx, doc, n, p), + NodeKind::Mesh(m) => { + let (r, c, u, v) = m.locate(p)?; + Some(m.color_at(r, c, u, v).0) + } + NodeKind::SymbolInstance { symbol, xf } => { + symbol_color_at(cx, doc, symbol, *xf, p, depth).or_else(|| paint_sample(cx, doc, n, on_stroke, p, depth)) + } + _ => paint_sample(cx, doc, n, on_stroke, p, depth), + } +} + +/// The color the art of symbol `name` of `doc`, placed in the document by `xf`, shows at `p`. +fn symbol_color_at(cx: &ToolContext, doc: &Document, name: &str, xf: Affine, p: Point, depth: usize) -> Option { + if xf.determinant().abs() < 1e-12 { + return None; + } + let sym = doc.symbols.iter().find(|s| s.name == name)?; + art_color_at(cx, doc, [(*sym.art).clone()], xf.inverse() * p, depth) } /// Whether the source has fill or stroke paint for an attribute sample. @@ -69,24 +136,82 @@ pub(crate) fn has_sampleable_paint(cx: &ToolContext, id: vectorcraft_doc::NodeId } /// The colour of `n`'s fill (or its stroke, when the stroke was hit or there is no fill) at `p`, -/// sampled in the paint's own space (text space for type runs) and box. -fn paint_sample(n: &Node, on_stroke: bool, p: Point) -> Option { +/// sampled in the paint's own space (text space for type runs) and box. A pattern gives the color +/// of its tile art at `p` ([`pattern_color_at`]). +fn paint_sample(cx: &ToolContext, doc: &Document, n: &Node, on_stroke: bool, p: Point, depth: usize) -> Option { let fill_none = n.proxy_paint(false, None).is_none_or(|(p, ..)| p.is_none()); let (paint, to_doc, bounds) = n.proxy_paint(on_stroke || fill_none, None)?; + if let Paint::Pattern { pattern, xf } = paint { + return pattern_color_at(cx, doc, pattern, to_doc * *xf, p, depth); + } let p = if to_doc.determinant().abs() > 1e-12 { to_doc.inverse() * p } else { p }; paint_color_at(paint, Some(bounds), p) } -/// The color of image `n`'s pixels at `p`, averaged over the raster sample size: a CMYK image's -/// ink amounts as they are, other images' sRGB pixels in the working RGB space (the color that -/// shows as that pixel). -fn image_color_at(cx: &ToolContext, n: &Node, p: Point) -> Option { +/// The color pattern `name` of `doc`, placed in the document by `xf`, shows at `p`: the color of +/// the front-most tile art there. A point the tiles leave empty has no color. +fn pattern_color_at(cx: &ToolContext, doc: &Document, name: &str, xf: Affine, p: Point, depth: usize) -> Option { + if xf.determinant().abs() < 1e-12 { + return None; + } + let def = doc.patterns.iter().find(|d| d.name == name)?; + // Sampled in pattern space, one tile at a time from the front, among the tiles whose art reaches + // the point (or meets it at an edge). The art moves by whole tiles, and the patterns it is + // painted with move with it. + let q = xf.inverse() * p; + let near = Rect::from_points(q, q).inflate(1e-6, 1e-6); + let bounds: Vec> = def.art.iter().map(|a| a.visual_bounds()).collect(); + let reaches = |m: Affine| bounds.iter().any(|b| b.is_none_or(|b| m.transform_rect_bbox(b).inflate(1e-6, 1e-6).contains(q))); + let scaling = vectorcraft_doc::Scaling { patterns: true, ..Default::default() }; + def.offsets_covering(near).into_iter().rev().map(|o| def.instance_xf(o)).filter(|m| reaches(*m)).take(MAX_TILES).find_map(|m| { + let art = def.art.iter().map(|a| { + let mut n = (**a).clone(); + vectorcraft_doc::pattern::place_art(&mut n, m, scaling); + n + }); + art_color_at(cx, doc, art, q, depth) + }) +} + +/// The color the front-most of `art` (in paint order, in the space of `p`) shows at `p`, sampled +/// as [`node_color_at`] samples an object. The art is hit in a scratch document with the images, +/// symbols and patterns of `doc`, with no tolerance around outlines and strokes: only what it +/// paints at `p` counts. +fn art_color_at(cx: &ToolContext, doc: &Document, art: impl IntoIterator, p: Point, depth: usize) -> Option { + if depth >= MAX_NESTING { + return None; + } + let mut scratch = Document::new(1.0, 1.0); + scratch.images = doc.images.clone(); + scratch.symbols = doc.symbols.clone(); + scratch.patterns = doc.patterns.clone(); + let layer = scratch.layers.first()?.id; + for mut n in art { + renumber(&mut scratch, &mut n); + scratch.insert(Some(layer), usize::MAX, n).ok()?; + } + let opts = HitOptions { scope: None, tol: 0.0, outline: false, ..sample_options(cx) }; + color_under(cx, &scratch, p, opts, depth + 1) +} + +/// Gives `n` and everything in it new ids from `doc` (pattern instances all have id 0). +fn renumber(doc: &mut Document, n: &mut Node) { + n.id = doc.alloc_id(); + for c in n.children_mut().into_iter().flatten() { + renumber(doc, std::sync::Arc::make_mut(c)); + } +} + +/// The color of image `n`'s pixels (in `doc`) at `p`, averaged over the raster sample size: a CMYK +/// image's ink amounts as they are, other images' sRGB pixels in the working RGB space (the color +/// that shows as that pixel). +fn image_color_at(cx: &ToolContext, doc: &Document, n: &Node, p: Point) -> Option { let NodeKind::Image(im) = &n.kind else { return None }; if im.xf.determinant().abs() < 1e-12 { return None; } let px = im.xf.inverse() * p; - let blob = cx.doc.images.get(&im.key)?; + let blob = doc.images.get(&im.key)?; let object = (im.width, im.height); if let Some(inks) = blob.sample_cmyk_object(px.x, px.y, object, cx.raster_sample) { let [c, m, y, k] = inks.map(|v| f32::from(v) / 255.0); @@ -106,9 +231,7 @@ impl Tool for EyedropperTool { if ev.kind != PointerKind::Down { return vec![]; } - // A click inside a fill or among characters samples it too, whatever Object and Type - // Object Selection by Path Only say. - let opts = vectorcraft_doc::hit::HitOptions { path_only: false, type_path_only: false, ..cx.hit_options() }; + let opts = sample_options(cx); if self.brush_key_color { let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; let back = self.stop.clone().unwrap_or_else(|| "selection".to_string()); @@ -124,7 +247,7 @@ impl Tool for EyedropperTool { } else { sample_source(cx, ev.pos) }; - let Some((src, kind)) = source else { return vec![] }; + let Some((src, _)) = source else { return vec![] }; let Some(n) = cx.doc.node(src) else { return vec![] }; if ev.mods.alt && stop.is_none() { let how = if ev.mods.shift { "append" } else { "reverse" }; @@ -134,8 +257,7 @@ impl Tool for EyedropperTool { if !(ev.mods.shift || stop.is_some() || image) { return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0 }))]; } - let sampled = if image { image_color_at(cx, n, ev.pos) } else { paint_sample(n, kind == HitKind::Stroke, ev.pos) }; - let Some(c) = sampled else { return vec![] }; + let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; let color = color_json(&c); let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] }; let out = vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back.clone())]; @@ -389,6 +511,157 @@ mod tests { ); } + /// An unstroked rectangle filled with `fill`, with id 0 (as pattern and symbol art is). + fn filled_rect(r: vectorcraft_geom::Rect, fill: Paint) -> std::sync::Arc { + let mut a = vectorcraft_doc::Appearance::default(); + a.set_fill(fill); + std::sync::Arc::new(Node::path(vectorcraft_doc::NodeId(0), vectorcraft_geom::shapes::rectangle(r), a)) + } + + /// [`doc_with_rect`] plus the pattern "Halves": a 20 × 10 tile, red on its left half and blue + /// on its right half. + fn doc_with_halves() -> (vectorcraft_doc::Document, vectorcraft_doc::NodeId) { + use vectorcraft_geom::Rect; + let (mut d, id) = doc_with_rect(); + 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 def = vectorcraft_doc::PatternDef::new( + "Halves", + vec![filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), red), filled_rect(Rect::new(10.0, 0.0, 20.0, 10.0), blue)], + ); + def.tile = Rect::new(0.0, 0.0, 20.0, 10.0); + d.patterns.push(def); + (d, id) + } + + /// Shift-click on a pattern fill samples the color of the tile art under the cursor, where the + /// pattern's own transform puts it, however small the tiles are. + #[test] + fn shift_click_samples_the_pattern_tile_under_the_cursor() { + use vectorcraft_geom::Affine; + let (mut d, id) = doc_with_halves(); + d.node_mut(id).unwrap().appearance.set_fill(Paint::Pattern { pattern: "Halves".into(), xf: Affine::translate((5.0, 0.0)) }); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |d: &vectorcraft_doc::Document, x: f64| { + EyedropperTool::default().pointer(&cx(d, &s, &p), &PointerEvent::new(PointerKind::Down, x, 155.0).with_mods(shift)) + }; + // Pattern space x 128 (8 into a tile), then x 137 (17 into a tile). + assert_eq!(sampled_hex(&at(&d, 133.0)), "#ff0000"); + assert_eq!(sampled_hex(&at(&d, 142.0)), "#0000ff"); + assert_eq!(crate::xform::eyedropper::sample_color_at(&cx(&d, &s, &p), Point::new(142.0, 155.0)).map(|c| c.to_hex()), Some("#0000ff".into())); + // Art 300 pt wide on a 1 pt tile: about 90,000 tiles reach every point. + let mut wide = vectorcraft_doc::PatternDef::new( + "Wide", + vec![filled_rect(vectorcraft_geom::Rect::new(0.0, 0.0, 300.0, 300.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0)))], + ); + wide.tile = vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0); + let mut wide_doc = d.clone(); + wide_doc.patterns.push(wide); + wide_doc.node_mut(id).unwrap().appearance.set_fill(vectorcraft_doc::pattern::pattern_paint("Wide")); + assert_eq!(sampled_hex(&at(&wide_doc, 142.0)), "#00ff00"); + // Pattern space x 140, on the edge between two tiles. + let edge = sampled_hex(&at(&d, 145.0)); + assert!(edge == "#ff0000" || edge == "#0000ff", "{edge}"); + // Tiles 0.2 × 0.1 pt, 0.05 pt down: pattern space y 15495, x 15005 (5 into a tile), then + // x 15015 (15 into a tile). + let tiny = Affine::translate((0.0, 0.05)) * Affine::scale(0.01); + d.node_mut(id).unwrap().appearance.set_fill(Paint::Pattern { pattern: "Halves".into(), xf: tiny }); + assert_eq!(sampled_hex(&at(&d, 150.05)), "#ff0000"); + assert_eq!(sampled_hex(&at(&d, 150.15)), "#0000ff"); + } + + /// Tile art painted with another pattern is sampled where that tile draws it: the inner + /// pattern moves with each tile. A symbol instance is sampled from its symbol's art. + #[test] + fn shift_click_samples_patterns_and_symbols_inside_art() { + use vectorcraft_geom::{Affine, Rect}; + let (mut d, id) = doc_with_halves(); + // A 30 pt tile filled with "Halves": every other tile starts halfway through a "Halves" tile. + let mut outer = vectorcraft_doc::PatternDef::new( + "Outer", + vec![filled_rect(Rect::new(0.0, 0.0, 30.0, 10.0), vectorcraft_doc::pattern::pattern_paint("Halves"))], + ); + outer.tile = Rect::new(0.0, 0.0, 30.0, 10.0); + d.patterns.push(outer); + d.node_mut(id).unwrap().appearance.set_fill(vectorcraft_doc::pattern::pattern_paint("Outer")); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + // The tile at x 150 draws "Halves" from x 150: x 165 is 15 into it. + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 165.0, 155.0).with_mods(shift)); + assert_eq!(sampled_hex(&a), "#0000ff"); + // A symbol of a green square, placed at (300, 300) and doubled. + d.symbols.push(vectorcraft_doc::Symbol { + name: "Green".into(), + art: filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0))), + }); + let l = d.layers[0].id; + let inst = d.alloc_id(); + let kind = NodeKind::SymbolInstance { symbol: "Green".into(), xf: Affine::translate((300.0, 300.0)) * Affine::scale(2.0) }; + d.insert(Some(l), usize::MAX, Node::new(inst, kind)).unwrap(); + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 310.0, 310.0).with_mods(shift)); + assert_eq!(sampled_hex(&a), "#00ff00"); + } + + /// A gap between a pattern's tile art shows what lies below it, in the document and in the tile + /// art of another pattern. + #[test] + fn a_gap_in_a_pattern_samples_what_lies_below() { + use vectorcraft_doc::pattern::pattern_paint; + use vectorcraft_geom::Rect; + // The white rectangle (100, 100)–(200, 200), under one filled with red 10 pt squares 20 pt apart. + let (mut d, _) = doc_with_rect(); + let mut gappy = + vectorcraft_doc::PatternDef::new("Gappy", vec![filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)))]); + gappy.tile = Rect::new(0.0, 0.0, 20.0, 10.0); + d.patterns.push(gappy); + let (l, top) = (d.layers[0].id, d.alloc_id()); + let mut over = (*filled_rect(Rect::new(100.0, 100.0, 200.0, 200.0), pattern_paint("Gappy"))).clone(); + over.id = top; + d.insert(Some(l), usize::MAX, over).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |d: &vectorcraft_doc::Document, x: f64| { + sampled_hex(&EyedropperTool::default().pointer(&cx(d, &s, &p), &PointerEvent::new(PointerKind::Down, x, 155.0).with_mods(shift))) + }; + // x 125 is 5 into a tile, on a red square; x 133 is 13 into one, between them. + assert_eq!((at(&d, 125.0), at(&d, 133.0)), ("#ff0000".to_string(), "#ffffff".to_string())); + // Tile art: a green rectangle behind one filled with "Gappy". + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let mut lined = vectorcraft_doc::PatternDef::new( + "Lined", + vec![filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), green), filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), pattern_paint("Gappy"))], + ); + lined.tile = Rect::new(0.0, 0.0, 20.0, 10.0); + d.patterns.push(lined); + d.node_mut(top).unwrap().appearance.set_fill(pattern_paint("Lined")); + assert_eq!((at(&d, 125.0), at(&d, 133.0)), ("#ff0000".to_string(), "#00ff00".to_string())); + // A blue fill under a 20 pt stroke of "Gappy", 5 pt left: x 107 is 12 into a tile, in a gap + // of the stroke over the fill. + let shape = &mut d.node_mut(top).unwrap().appearance; + shape.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + shape.set_stroke(Paint::Pattern { pattern: "Gappy".into(), xf: vectorcraft_geom::Affine::translate((-5.0, 0.0)) }); + shape.stroke_mut().unwrap().width = 20.0; + assert_eq!((at(&d, 103.0), at(&d, 107.0)), ("#ff0000".to_string(), "#0000ff".to_string())); + } + + /// Shift-click on a gradient mesh samples the patch color interpolated at the cursor. + #[test] + fn shift_click_samples_the_mesh_color_under_the_cursor() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + // Black on the left edge, white on the right edge. + let mesh = GradientMesh::from_surface(1, 1, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|u, _| { + if u < 0.5 { Color::rgb(0.0, 0.0, 0.0) } else { Color::rgb(1.0, 1.0, 1.0) } + }); + d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(mesh))).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 125.0, 150.0).with_mods(shift)); + assert_eq!(sampled_hex(&a), "#404040"); + } + #[test] fn gradient_sampled_along_vector() { let g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()); From 034a327f5b87197a5b94c2207c90be190c778de6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 07:47:48 -0700 Subject: [PATCH 12/70] Eyedropper: bound the work of one color sample A sample now shares one work limit, counted in objects looked at, across hit tests, pattern tiles and the tile or symbol art it places for hit testing, and gives no color when the limit runs out. Objects that give no color are skipped by id instead of cloning the document for each retry, each nesting level reuses one scratch document that holds only the symbols, and patterns and images are looked up in the sampled document. The sample runs on a deep stack and follows art inside art at most 16 levels deep. A symbol instance is now sampled as it draws: its art is stained by the instance's fill and placed by the instance's transform without moving the patterns in it or scaling its strokes. Between the shapes of its art the sample shows what lies below instead of the stain, and a pattern tile holding an instance is sampled wherever the symbol's art reaches. --- Cargo.lock | 1 + crates/doc/src/hit.rs | 6 + crates/tools/Cargo.toml | 1 + crates/tools/src/xform/eyedropper.rs | 313 ++++++++++++++++++++++----- 4 files changed, 264 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aeec6db30e..9362671b07 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6499,6 +6499,7 @@ dependencies = [ "kurbo 0.13.1", "serde", "serde_json", + "vectorcraft-brush", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index eb436e9711..b754e0d565 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -110,6 +110,12 @@ pub fn hit_test_visible(doc: &Document, p: Point, opt: HitOptions) -> Option bool) -> Option { + hit_test_skipping(doc, p, opt, skip, false) +} + /// The object of `selected` (topmost first) whose own art lies under `p` where a clipping mask /// hides it: a clip group (or a layer with a clipping mask) holding it doesn't clip to `p`. A /// click there hits nothing ([`hit_test`]), so the selection tools grab the selection by that diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml index 1a0f8e6335..042a6f5174 100644 --- a/crates/tools/Cargo.toml +++ b/crates/tools/Cargo.toml @@ -12,6 +12,7 @@ workspace = true vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } +vectorcraft-brush = { workspace = true } vectorcraft-pathops = { workspace = true } vectorcraft-effects = { workspace = true } vectorcraft-text = { workspace = true } diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 1e612a6cb5..5620be4d54 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -16,10 +16,12 @@ //! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into //! the open dialog (`brushKeyColor` UI request) and switches back. +use std::collections::HashSet; + use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::hit::{HitKind, HitOptions, hit_test, hit_test_visible}; -use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_doc::hit::{HitKind, HitOptions, hit_test, hit_test_visible, hit_test_visible_skipping}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::hit::fill_contains; use vectorcraft_geom::{Affine, Point, Rect}; @@ -52,12 +54,47 @@ pub fn paint_color_at(paint: &Paint, bounds: Option, p: } /// How many patterns and symbols deep a sample follows art inside art (tile art painted with a -/// pattern, a symbol whose art holds an instance of another): as deep as a document draws. -const MAX_NESTING: usize = vectorcraft_doc::depth::MAX_DRAWN_DEPTH; +/// pattern, a symbol whose art holds an instance of another). +const MAX_NESTING: usize = 16; /// Most tiles of one pattern a sample looks at, front to back, for art that paints the point. const MAX_TILES: usize = 1_000; +/// Most work one sample does, in objects looked at: each hit test after the first in a document +/// counts the objects of the document and of its symbols, each pattern tile or symbol instance +/// sampled counts the objects of its art, and every hundred tile positions checked count one. +/// Art inside art multiplies them; a sample that would need more gives no color. +const MAX_WORK: usize = 1_000_000; + +/// One color sample: the document, the hit options, the raster sample size and the work left. +struct Sampler<'a> { + doc: &'a Document, + opts: HitOptions, + raster_sample: u32, + /// The objects in the art of the document's symbols, which a hit test may measure. + symbol_nodes: usize, + work: usize, + /// The work ran out: the sample gives no color. + exhausted: bool, +} + +impl Sampler<'_> { + /// Count `n` units of work, or `None` when that is more than is left. + fn spend(&mut self, n: usize) -> Option<()> { + match self.work.checked_sub(n) { + Some(left) => { + self.work = left; + Some(()) + } + None => { + self.work = 0; + self.exhausted = true; + None + } + } + } +} + /// The Eyedropper's hit options: a click inside a fill or among characters samples it too, /// whatever Object and Type Object Selection by Path Only say. fn sample_options(cx: &ToolContext) -> HitOptions { @@ -73,25 +110,45 @@ pub(crate) fn sample_source(cx: &ToolContext, p: Point) -> Option<(vectorcraft_d /// The visible color under `p`, including image pixels, pattern tiles, mesh colors and /// intermediate gradient colors. pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option { - color_under(cx, cx.doc, p, sample_options(cx), 0) + let (doc, opts, raster_sample) = (cx.doc, sample_options(cx), cx.raster_sample); + vectorcraft_doc::depth::with_deep_stack(|| { + let symbol_nodes = doc.symbols.iter().map(|s| s.art.count()).sum(); + let mut s = Sampler { doc, opts, raster_sample, symbol_nodes, work: MAX_WORK, exhausted: false }; + let mut levels: Vec> = (0..MAX_NESTING).map(|_| None).collect(); + let c = color_under(&mut s, doc, &mut levels, p, opts); + c.filter(|_| !s.exhausted) + }) } /// The color the front-most object of `doc` hit at `p` with `opts` shows there. Where a stroke /// gives no color at `p` (a gap between its pattern's tiles), the object's own fill there does; -/// an object that gives none at all is passed over for the ones below it. -fn color_under(cx: &ToolContext, doc: &Document, p: Point, opts: HitOptions, depth: usize) -> Option { - let mut rest: Option = None; +/// an object that gives none at all is passed over for the ones below it. `levels` holds the +/// scratch documents for art inside art, one for each level deeper. +fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], p: Point, opts: HitOptions) -> Option { + let mut passed: HashSet = HashSet::new(); + let mut size = None; loop { - let d = rest.as_ref().unwrap_or(doc); - let h = hit_test_visible(d, p, opts)?; - let id = paint_owner(d, h.leaf); - let n = d.node(id)?; + // The first hit test is the one a click makes anyway; each one after it may visit every + // object again. + let cost = + if passed.is_empty() { 1 } else { *size.get_or_insert_with(|| s.symbol_nodes + doc.layers.iter().map(|l| l.count()).sum::()) }; + s.spend(cost)?; + let h = hit_test_visible_skipping(doc, p, opts, &|id| passed.contains(&id))?; + let id = paint_owner(doc, h.leaf); + let n = doc.node(id)?; let on_stroke = h.kind == HitKind::Stroke; - let fill = || if on_stroke && fill_covers(n, p) { node_color_at(cx, d, n, false, p, depth) } else { None }; - if let Some(c) = node_color_at(cx, d, n, on_stroke, p, depth).or_else(fill) { + if let Some(c) = node_color_at(s, levels, n, on_stroke, p) { return Some(c); } - rest.get_or_insert_with(|| doc.clone()).remove(id).ok()?; + if on_stroke + && fill_covers(n, p) + && let Some(c) = node_color_at(s, levels, n, false, p) + { + return Some(c); + } + if !passed.insert(id) { + return None; + } } } @@ -104,30 +161,34 @@ fn fill_covers(n: &Node, p: Point) -> bool { } } -/// The color `n` (in `doc`) shows at `p`: an image's pixels, a mesh's interpolated patch color, a -/// symbol instance's art, or the color of its fill (or its stroke, when the stroke was hit or there -/// is no fill) there. `depth` counts the patterns and symbols the sample is already inside. -fn node_color_at(cx: &ToolContext, doc: &Document, n: &Node, on_stroke: bool, p: Point, depth: usize) -> Option { +/// The color `n` shows at `p`: an image's pixels, a mesh's interpolated patch color, a symbol +/// instance's art, or the color of its fill (or its stroke, when the stroke was hit or there is no +/// fill) there. Images, symbols and patterns are looked up in the sampled document. +fn node_color_at(s: &mut Sampler, levels: &mut [Option], n: &Node, on_stroke: bool, p: Point) -> Option { match &n.kind { - NodeKind::Image(_) => image_color_at(cx, doc, n, p), + NodeKind::Image(_) => image_color_at(s, n, p), NodeKind::Mesh(m) => { let (r, c, u, v) = m.locate(p)?; Some(m.color_at(r, c, u, v).0) } - NodeKind::SymbolInstance { symbol, xf } => { - symbol_color_at(cx, doc, symbol, *xf, p, depth).or_else(|| paint_sample(cx, doc, n, on_stroke, p, depth)) - } - _ => paint_sample(cx, doc, n, on_stroke, p, depth), + // The instance's fill only stains its art: where the art paints nothing, nothing shows. + NodeKind::SymbolInstance { symbol, xf } => symbol_color_at(s, levels, n, symbol, *xf, p), + _ => paint_sample(s, levels, n, on_stroke, p), } } -/// The color the art of symbol `name` of `doc`, placed in the document by `xf`, shows at `p`. -fn symbol_color_at(cx: &ToolContext, doc: &Document, name: &str, xf: Affine, p: Point, depth: usize) -> Option { +/// The color the art of symbol `name` shows at `p` as instance `inst` draws it: stained by the +/// instance's fill and placed in the document by `xf`, its strokes and patterns unscaled. +fn symbol_color_at(s: &mut Sampler, levels: &mut [Option], inst: &Node, name: &str, xf: Affine, p: Point) -> Option { if xf.determinant().abs() < 1e-12 { return None; } + let doc = s.doc; let sym = doc.symbols.iter().find(|s| s.name == name)?; - art_color_at(cx, doc, [(*sym.art).clone()], xf.inverse() * p, depth) + s.spend(sym.art.count())?; + let mut art = vectorcraft_brush::instance_art(&sym.art, inst); + art.transform(xf, false); + art_color_at(s, levels, [art], p) } /// Whether the source has fill or stroke paint for an attribute sample. @@ -138,60 +199,83 @@ pub(crate) fn has_sampleable_paint(cx: &ToolContext, id: vectorcraft_doc::NodeId /// The colour of `n`'s fill (or its stroke, when the stroke was hit or there is no fill) at `p`, /// sampled in the paint's own space (text space for type runs) and box. A pattern gives the color /// of its tile art at `p` ([`pattern_color_at`]). -fn paint_sample(cx: &ToolContext, doc: &Document, n: &Node, on_stroke: bool, p: Point, depth: usize) -> Option { +fn paint_sample(s: &mut Sampler, levels: &mut [Option], n: &Node, on_stroke: bool, p: Point) -> Option { let fill_none = n.proxy_paint(false, None).is_none_or(|(p, ..)| p.is_none()); let (paint, to_doc, bounds) = n.proxy_paint(on_stroke || fill_none, None)?; if let Paint::Pattern { pattern, xf } = paint { - return pattern_color_at(cx, doc, pattern, to_doc * *xf, p, depth); + return pattern_color_at(s, levels, pattern, to_doc * *xf, p); } let p = if to_doc.determinant().abs() > 1e-12 { to_doc.inverse() * p } else { p }; paint_color_at(paint, Some(bounds), p) } -/// The color pattern `name` of `doc`, placed in the document by `xf`, shows at `p`: the color of -/// the front-most tile art there. A point the tiles leave empty has no color. -fn pattern_color_at(cx: &ToolContext, doc: &Document, name: &str, xf: Affine, p: Point, depth: usize) -> Option { +/// The color pattern `name`, placed in the document by `xf`, shows at `p`: the color of the +/// front-most tile art there. A point the tiles leave empty has no color. +fn pattern_color_at(s: &mut Sampler, levels: &mut [Option], name: &str, xf: Affine, p: Point) -> Option { if xf.determinant().abs() < 1e-12 { return None; } + let doc = s.doc; let def = doc.patterns.iter().find(|d| d.name == name)?; // Sampled in pattern space, one tile at a time from the front, among the tiles whose art reaches // the point (or meets it at an edge). The art moves by whole tiles, and the patterns it is // painted with move with it. let q = xf.inverse() * p; let near = Rect::from_points(q, q).inflate(1e-6, 1e-6); - let bounds: Vec> = def.art.iter().map(|a| a.visual_bounds()).collect(); + let (mut art_nodes, mut instances) = (0, false); + for a in &def.art { + a.walk(&mut |n| { + art_nodes += 1; + instances |= matches!(n.kind, NodeKind::SymbolInstance { .. }); + }); + } + // Symbol instances in the art are measured by their symbols' art. + s.spend(1 + art_nodes + if instances { s.symbol_nodes } else { 0 })?; + let symbols = doc.symbol_boxes(); + let bounds: Vec> = def.art.iter().map(|a| a.visual_bounds_with(&symbols)).collect(); let reaches = |m: Affine| bounds.iter().any(|b| b.is_none_or(|b| m.transform_rect_bbox(b).inflate(1e-6, 1e-6).contains(q))); let scaling = vectorcraft_doc::Scaling { patterns: true, ..Default::default() }; - def.offsets_covering(near).into_iter().rev().map(|o| def.instance_xf(o)).filter(|m| reaches(*m)).take(MAX_TILES).find_map(|m| { + let offsets = def.offsets_covering(near); + // Each tile position is checked against each piece of art: a hundred checks count as one unit. + s.spend(offsets.len().saturating_mul(bounds.len().max(1)) / 100)?; + for m in offsets.into_iter().rev().map(|o| def.instance_xf(o)).filter(|m| reaches(*m)).take(MAX_TILES) { + s.spend(1 + art_nodes)?; let art = def.art.iter().map(|a| { let mut n = (**a).clone(); vectorcraft_doc::pattern::place_art(&mut n, m, scaling); n }); - art_color_at(cx, doc, art, q, depth) - }) + if let Some(c) = art_color_at(s, levels, art, q) { + return Some(c); + } + } + None } /// The color the front-most of `art` (in paint order, in the space of `p`) shows at `p`, sampled -/// as [`node_color_at`] samples an object. The art is hit in a scratch document with the images, -/// symbols and patterns of `doc`, with no tolerance around outlines and strokes: only what it -/// paints at `p` counts. -fn art_color_at(cx: &ToolContext, doc: &Document, art: impl IntoIterator, p: Point, depth: usize) -> Option { - if depth >= MAX_NESTING { - return None; +/// as [`node_color_at`] samples an object, with no tolerance around outlines and strokes: only +/// what it paints at `p` counts. The art is hit in the first of `levels`, a scratch document with +/// the sampled document's symbols, made on first use and emptied for each new piece of art; art +/// inside it uses the levels after it. With no level left, the art gives no color. +fn art_color_at(s: &mut Sampler, levels: &mut [Option], art: impl IntoIterator, p: Point) -> Option { + let (slot, deeper) = levels.split_first_mut()?; + let doc = s.doc; + let scratch = slot.get_or_insert_with(|| { + let mut d = Document::new(1.0, 1.0); + d.symbols = doc.symbols.clone(); + d + }); + let layer = scratch.layers.first()?; + let (layer, placed) = (layer.id, layer.children().map(|c| c.iter().map(|n| n.id).collect::>()).unwrap_or_default()); + for id in placed { + scratch.remove(id).ok()?; } - let mut scratch = Document::new(1.0, 1.0); - scratch.images = doc.images.clone(); - scratch.symbols = doc.symbols.clone(); - scratch.patterns = doc.patterns.clone(); - let layer = scratch.layers.first()?.id; for mut n in art { - renumber(&mut scratch, &mut n); + renumber(scratch, &mut n); scratch.insert(Some(layer), usize::MAX, n).ok()?; } - let opts = HitOptions { scope: None, tol: 0.0, outline: false, ..sample_options(cx) }; - color_under(cx, &scratch, p, opts, depth + 1) + let opts = HitOptions { scope: None, tol: 0.0, outline: false, ..s.opts }; + color_under(s, scratch, deeper, p, opts) } /// Gives `n` and everything in it new ids from `doc` (pattern instances all have id 0). @@ -202,22 +286,22 @@ fn renumber(doc: &mut Document, n: &mut Node) { } } -/// The color of image `n`'s pixels (in `doc`) at `p`, averaged over the raster sample size: a CMYK -/// image's ink amounts as they are, other images' sRGB pixels in the working RGB space (the color -/// that shows as that pixel). -fn image_color_at(cx: &ToolContext, doc: &Document, n: &Node, p: Point) -> Option { +/// The color of image `n`'s pixels at `p`, averaged over the raster sample size: a CMYK image's ink +/// amounts as they are, other images' sRGB pixels in the working RGB space (the color that shows +/// as that pixel). +fn image_color_at(s: &Sampler, n: &Node, p: Point) -> Option { let NodeKind::Image(im) = &n.kind else { return None }; if im.xf.determinant().abs() < 1e-12 { return None; } let px = im.xf.inverse() * p; - let blob = doc.images.get(&im.key)?; + let blob = s.doc.images.get(&im.key)?; let object = (im.width, im.height); - if let Some(inks) = blob.sample_cmyk_object(px.x, px.y, object, cx.raster_sample) { + if let Some(inks) = blob.sample_cmyk_object(px.x, px.y, object, s.raster_sample) { let [c, m, y, k] = inks.map(|v| f32::from(v) / 255.0); return Some(Color::cmyk(c, m, y, k)); } - let [r, g, b, _] = blob.sample_object(px.x, px.y, object, cx.raster_sample)?; + let [r, g, b, _] = blob.sample_object(px.x, px.y, object, s.raster_sample)?; let [r, g, b] = vectorcraft_color::cms::active().srgb_to_rgb([r, g, b].map(|v| f32::from(v) / 255.0)); Some(Color::rgb(r, g, b)) } @@ -602,6 +686,121 @@ mod tests { assert_eq!(sampled_hex(&a), "#00ff00"); } + /// A symbol instance is sampled as it draws: its art stained by the instance's fill, and a + /// pattern in its art left where the document puts it when the instance moves. + #[test] + fn symbol_samples_follow_the_instances_stain_and_placement() { + use vectorcraft_geom::{Affine, Rect}; + let (mut d, _) = doc_with_halves(); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + d.symbols.push(vectorcraft_doc::Symbol { name: "Red".into(), art: filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), red) }); + d.symbols.push(vectorcraft_doc::Symbol { + name: "Tiled".into(), + art: filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), vectorcraft_doc::pattern::pattern_paint("Halves")), + }); + let l = d.layers[0].id; + let place = |d: &mut vectorcraft_doc::Document, name: &str, at: (f64, f64), stain: Option| { + let id = d.alloc_id(); + let mut n = Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::translate(at) }); + if let Some(c) = stain { + n.appearance.set_fill(Paint::solid(c)); + } + d.insert(Some(l), usize::MAX, n).unwrap(); + }; + place(&mut d, "Red", (300.0, 300.0), Some(Color::rgb(0.0, 0.0, 1.0))); + place(&mut d, "Tiled", (310.0, 400.0), None); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |x: f64, y: f64| { + sampled_hex(&EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift))) + }; + assert_eq!(at(305.0, 305.0), "#0000ff", "stained"); + // Document x 312 is 12 into a "Halves" tile, though only 2 into the instance's art. + assert_eq!(at(312.0, 405.0), "#0000ff", "pattern in place"); + } + + /// Between the shapes of a stained instance's art, the eyedropper samples what lies below, not + /// the stain; and a pattern tile is sampled wherever its symbol art reaches. + #[test] + fn symbol_art_decides_where_an_instance_paints() { + use std::sync::Arc; + use vectorcraft_doc::NodeId; + use vectorcraft_geom::{Affine, Rect}; + let (mut d, id) = doc_with_rect(); + let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let pair = + Node::group(NodeId(0), vec![filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), red()), filled_rect(Rect::new(20.0, 0.0, 30.0, 10.0), red())]); + d.symbols.push(vectorcraft_doc::Symbol { name: "Pair".into(), art: Arc::new(pair) }); + let (l, inst) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Pair".into(), xf: Affine::translate((100.0, 140.0)) }); + n.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + d.insert(Some(l), usize::MAX, n).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |d: &vectorcraft_doc::Document, x: f64, y: f64| { + sampled_hex(&EyedropperTool::default().pointer(&cx(d, &s, &p), &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift))) + }; + assert_eq!((at(&d, 105.0, 145.0), at(&d, 115.0, 145.0)), ("#0000ff".to_string(), "#ffffff".to_string())); + // A 200 pt tile holding an instance of a 180 pt green bar, which reaches far past the + // square an instance is measured by without its symbol. + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + d.symbols.push(vectorcraft_doc::Symbol { name: "Bar".into(), art: filled_rect(Rect::new(0.0, 0.0, 180.0, 10.0), green) }); + let bar = Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY })); + let mut bars = vectorcraft_doc::PatternDef::new("Bars", vec![bar]); + bars.tile = Rect::new(0.0, 0.0, 200.0, 10.0); + d.patterns.push(bars); + d.node_mut(id).unwrap().appearance.set_fill(vectorcraft_doc::pattern::pattern_paint("Bars")); + assert_eq!(at(&d, 150.0, 155.0), "#00ff00"); + } + + /// Patterns whose tile art is painted with the next one, on tiles far smaller than their art, + /// symbols whose art holds four instances of the next, and symbols nested far deeper than a + /// sample follows: each sample stops within its work limit and gives no color, instead of + /// trying every tile or instance at every level or running out of stack. + #[test] + fn nested_patterns_and_symbols_sample_within_the_work_limit() { + use std::sync::Arc; + use vectorcraft_doc::pattern::pattern_paint; + use vectorcraft_doc::{NodeId, Symbol}; + use vectorcraft_geom::{Affine, Rect}; + let (mut d, id) = doc_with_rect(); + // "Nest0" to "Nest7": 300 pt art on 1 pt tiles, each painted with the next. "Nest8" doesn't + // exist, so no tile gives a color and every one is tried. + for i in 0..8 { + let mut def = vectorcraft_doc::PatternDef::new( + &format!("Nest{i}"), + vec![filled_rect(Rect::new(0.0, 0.0, 300.0, 300.0), pattern_paint(&format!("Nest{}", i + 1)))], + ); + def.tile = Rect::new(0.0, 0.0, 1.0, 1.0); + d.patterns.push(def); + } + d.node_mut(id).unwrap().appearance.set_fill(pattern_paint("Nest0")); + // "Fan0" to "Fan11": four instances of the next symbol; "Fan12" a square filled with "Nest8". + let instance = |name: String| Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name, xf: Affine::IDENTITY })); + for i in 0..12 { + let art = Node::group(NodeId(0), (0..4).map(|_| instance(format!("Fan{}", i + 1))).collect()); + d.symbols.push(Symbol { name: format!("Fan{i}"), art: Arc::new(art) }); + } + d.symbols.push(Symbol { name: "Fan12".into(), art: filled_rect(Rect::new(300.0, 300.0, 400.0, 400.0), pattern_paint("Nest8")) }); + // "Deep0" to "Deep99": one instance of the next; "Deep100" a green square. + for i in 0..100 { + d.symbols.push(Symbol { name: format!("Deep{i}"), art: instance(format!("Deep{}", i + 1)) }); + } + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + d.symbols.push(Symbol { name: "Deep100".into(), art: filled_rect(Rect::new(300.0, 0.0, 400.0, 100.0), green) }); + let l = d.layers[0].id; + for name in ["Fan0", "Deep0"] { + let inst = d.alloc_id(); + d.insert(Some(l), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap(); + } + let (s, p) = (Selection::default(), paint()); + let start = std::time::Instant::now(); + for at in [Point::new(150.0, 150.0), Point::new(350.0, 350.0), Point::new(350.0, 50.0)] { + assert_eq!(sample_color_at(&cx(&d, &s, &p), at), None, "{at:?}"); + } + assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); + } + /// A gap between a pattern's tile art shows what lies below it, in the document and in the tile /// art of another pattern. #[test] From a8b3786f8c291d0264a8fcf8b1f9cf626c306720 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 01:07:45 -0700 Subject: [PATCH 13/70] Symbols: Delete Symbol asks first, and Alt-click deletes an unused symbol without asking The Symbols panel's Delete Symbol button and menu item now ask before deleting. A symbol no instance uses gets "Delete the selected symbol?" with Yes and No. A symbol with placed instances gets Expand Instances, which turns the instances into ordinary art, Delete Instances, which removes them, and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol at once and still asks about one with instances. The question is bound to the document it was asked in: once another document is active, or the symbol is gone, Yes deletes nothing, and a symbol that gained instances while the question was open gets the in-use question instead. symbol.delete itself does not ask. The shared dialog frame takes a Cancel label (DialogSpec::cancel) for the No button. The new strings have rows in every catalog. --- crates/ui-egui/src/dialogs.rs | 9 +- crates/ui-egui/src/dialogs/symbol_delete.rs | 100 ++++++++++ crates/ui-egui/src/i18n/bg.tsv | 6 + crates/ui-egui/src/i18n/bs.tsv | 6 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + crates/ui-egui/src/panels/symbols.rs | 208 +++++++++++++++++++- docs/target-app-parity.md | 1 + 30 files changed, 471 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/symbol_delete.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 83e7850f4e..488cd1d956 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -106,6 +106,7 @@ pub mod spot_colors; pub(crate) mod svg_options; pub mod swatch_conflict; pub mod swatch_options; +pub mod symbol_delete; pub mod symbol_options; pub mod symbolism_options; mod text_export; @@ -175,6 +176,8 @@ pub(crate) struct DialogSpec { pub confirm: fn(&mut VectorcraftApp, &Dialog) -> DialogResult, /// The OK button's label. None: no OK button, Enter does nothing and Cancel reads "Close". pub ok: Option<&'static str>, + /// The Cancel button's label when it is not "Cancel" ("No"). Only with an `ok`. + pub cancel: Option<&'static str>, /// An extra button left of Cancel that sets `discard: true` and confirms ("Don't Save"). pub discard: Option<&'static str>, /// A button left of Cancel, as (label, field), that sets `field: true` and confirms, as OK @@ -217,6 +220,7 @@ impl DialogSpec { Ok(Value::Null) }, ok: Some("OK"), + cancel: None, discard: None, alternate: None, reset: None, @@ -371,6 +375,8 @@ registry! { ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, + DeleteSymbol: [symbol_delete::KIND] => symbol_delete::SPEC, + DeleteUsedSymbol: [symbol_delete::USED] => symbol_delete::USED_SPEC, SymbolismOptions: [symbolism_options::KIND] => symbolism_options::SPEC, PerspectiveGridPresets: [perspective_presets::KIND] => perspective_presets::SPEC, PerspectiveGridOptions: [perspective_options::KIND] => perspective_options::SPEC, @@ -397,6 +403,7 @@ pub fn button_labels() -> Vec<&'static str> { let mut v = vec!["Cancel", "Close"]; for spec in std::iter::once(&DialogSpec::FORM).chain(DialogKind::ALL.iter().map(|k| k.spec())) { v.extend(spec.ok); + v.extend(spec.cancel); v.extend(spec.discard); v.extend(spec.alternate.map(|(label, _)| label)); v.extend(spec.reset.map(|_| "Reset")); @@ -638,7 +645,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let label = if resets { "Reset" } else if spec.ok.is_some() { - "Cancel" + spec.cancel.unwrap_or("Cancel") } else { "Close" }; diff --git a/crates/ui-egui/src/dialogs/symbol_delete.rs b/crates/ui-egui/src/dialogs/symbol_delete.rs new file mode 100644 index 0000000000..730c00cb4d --- /dev/null +++ b/crates/ui-egui/src/dialogs/symbol_delete.rs @@ -0,0 +1,100 @@ +//! The Symbols panel's Delete Symbol question ([`ask`]). A symbol no instance uses gets "Delete the +//! selected symbol?" with Yes and No ([`KIND`]); a symbol with placed instances gets Expand +//! Instances, Delete Instances and Cancel ([`USED`]). +//! +//! Fields: `name` (the symbol) and `doc` (the [`vectorcraft_engine::DocState::uid`] of the document +//! it was asked in). Yes or either Instances button deletes the symbol only while that document is +//! the active one and still has the symbol; an unused symbol that has gained instances since asks +//! the in-use question instead. + +use serde_json::{Value, json}; + +use super::{DialogResult, DialogSpec}; +use crate::VectorcraftApp; +use crate::state::Dialog; + +/// The dialog kind of the question for a symbol no instance uses. +pub const KIND: &str = "deleteSymbol"; + +/// The dialog kind of the question for a symbol with placed instances. +pub const USED: &str = "deleteUsedSymbol"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Delete the selected symbol?").into(), + body: |_, _, _| false, + confirm: confirm_unused, + ok: Some("Yes"), + cancel: Some("No"), + max_width: Some(420.0), + ..DialogSpec::FORM +}; + +pub(super) const USED_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted.").into(), + body: |_, _, _| false, + confirm: confirm_used, + ok: Some("Expand Instances"), + discard: Some("Delete Instances"), + max_width: Some(420.0), + ..DialogSpec::FORM +}; + +/// Delete Symbol for symbol `name` of the active document. A symbol with instances always asks +/// what becomes of them; an unused one is deleted at once with `now` (Alt-click on the panel's +/// button) and asked about otherwise. +pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) { + let Some(uid) = app.session.active().map(|st| st.uid) else { return }; + match instances(app, uid, name) { + None => {} + Some(0) if now => { + if let Err(e) = app.run("symbol.delete", json!({ "name": name })) { + app.status(e); + } + } + Some(n) => open(app, if n == 0 { KIND } else { USED }, name, uid), + } +} + +fn open(app: &mut VectorcraftApp, kind: &str, name: &str, uid: u64) { + app.ui.dialog = Some(Dialog::new(kind, json!({ "name": name, "doc": uid }))); +} + +/// How many instances symbol `name` has, while the document `uid` is the active one and has the +/// symbol; `None` otherwise. +fn instances(app: &mut VectorcraftApp, uid: u64, name: &str) -> Option { + if app.session.active().map(|st| st.uid) != Some(uid) { + return None; + } + let list = app.run("symbol.list", json!({})).ok()?; + list["symbols"].as_array()?.iter().find(|s| s["name"].as_str() == Some(name)).map(|s| s["instances"].as_u64().unwrap_or(0)) +} + +/// The document and symbol `d` asks about. +fn target(d: &Dialog) -> (u64, String) { + (d.fields.get("doc").and_then(Value::as_u64).unwrap_or(0), d.str("name")) +} + +/// Yes: deletes the symbol, or asks the in-use question when it has gained instances. +fn confirm_unused(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + app.ui.dialog = None; + let (uid, name) = target(d); + match instances(app, uid, &name) { + None => Ok(Value::Null), + Some(0) => app.run("symbol.delete", json!({ "name": name })), + Some(_) => { + open(app, USED, &name, uid); + Ok(Value::Null) + } + } +} + +/// Expand Instances (OK) turns the instances into ordinary art; Delete Instances (`discard`) +/// removes them. Either one deletes the symbol in one undo step. +fn confirm_used(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + app.ui.dialog = None; + let (uid, name) = target(d); + if instances(app, uid, &name).is_none() { + return Ok(Value::Null); + } + app.run("symbol.delete", json!({ "name": name, "expandInstances": !d.bool("discard") })) +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 5b65923a19..2048bbcc9c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -735,6 +735,12 @@ font-technology Variable Променливи Delete Stop Изтриване на репер Delete Swatch Изтриване на образец Delete Symbol Изтриване на символ + Delete the selected symbol? Да се изтрие ли избраният символ? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Един или повече от символите се използват и не могат да бъдат изтрити, докато екземплярите им не бъдат разширени или изтрити. + Expand Instances Разширяване на екземплярите + Delete Instances Изтриване на екземплярите + Yes Да + No Не Delete Tab Изтриване на табулация Delete the graphic style “{name}”? Изтриване на графичния стил „{name}“? Delete Theme Изтриване на тема diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5798a7a798..2ac957c9ac 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3046,6 +3046,12 @@ theme Appearance Izgled Current Symbol Trenutni simbol Delete Brush Izbriši četkicu Delete Symbol Izbriši simbol + Delete the selected symbol? Izbrisati odabrani simbol? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Jedan ili više simbola se koriste i ne mogu se izbrisati dok se njihove instance ne prošire ili izbrišu. + Expand Instances Proširi instance + Delete Instances Izbriši instance + Yes Da + No Ne Duplicate Brush Dupliciraj četkicu Duplicate Symbol Dupliciraj simbol Edit Symbol Uredi simbol diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index d93092418f..ea8d621822 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1052,6 +1052,12 @@ Delete Styles Suprimeix els estils Delete Swatch Suprimeix la mostra Delete Symbol Suprimeix el símbol + Delete the selected symbol? Voleu suprimir el símbol seleccionat? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Un o més dels símbols estan en ús i no es poden suprimir fins que se n’expandeixin o se’n suprimeixin les instàncies. + Expand Instances Expandeix les instàncies + Delete Instances Suprimeix les instàncies + Yes Sí + No No Delete Tab Suprimeix la tabulació Delete the graphic style “{name}”? Voleu suprimir l’estil gràfic “{name}”? Delete the library “{name}”? Voleu suprimir la biblioteca “{name}”? diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 50a8f953e1..93142cadb6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3078,6 +3078,12 @@ theme Appearance Motiv Current Symbol Aktuální symbol Delete Brush Odstranit štětec Delete Symbol Odstranit symbol + Delete the selected symbol? Odstranit vybraný symbol? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Jeden nebo více symbolů se používá a nelze je odstranit, dokud jejich instance nerozložíte nebo neodstraníte. + Expand Instances Rozložit instance + Delete Instances Odstranit instance + Yes Ano + No Ne Duplicate Brush Duplikovat štětec Duplicate Symbol Duplikovat symbol Edit Symbol Upravit symbol diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 87249badf8..160abd6bf7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2837,6 +2837,12 @@ theme Appearance Udseende Current Symbol Aktuelt symbol Delete Brush Slet pensel Delete Symbol Slet symbol + Delete the selected symbol? Vil du slette det markerede symbol? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Et eller flere af symbolerne er i brug og kan ikke slettes, før deres forekomster er udvidet eller slettet. + Expand Instances Udvid forekomster + Delete Instances Slet forekomster + Yes Ja + No Nej Duplicate Brush Duplikér pensel Duplicate Symbol Duplikér symbol Edit Symbol Redigér symbol diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 513ff8e4f4..08869d7652 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -729,6 +729,12 @@ font-technology Variable Variabel Delete Stop Farbstopp löschen Delete Swatch Farbfeld löschen Delete Symbol Symbol löschen + Delete the selected symbol? Ausgewähltes Symbol löschen? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Mindestens eines der Symbole wird verwendet und kann erst gelöscht werden, wenn seine Instanzen umgewandelt oder gelöscht wurden. + Expand Instances Instanzen umwandeln + Delete Instances Instanzen löschen + Yes Ja + No Nein Delete Tab Tabulator löschen Delete the graphic style “{name}”? Grafikstil „{name}“ löschen? Delete Theme Thema löschen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ce282989f0..3d074c7167 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -709,6 +709,12 @@ font-technology Variable Μεταβλητές Delete Stop Διαγραφή στάσης ντεγκραντέ Delete Swatch Διαγραφή δείγματος χρώματος Delete Symbol Διαγραφή συμβόλου + Delete the selected symbol? Να διαγραφεί το επιλεγμένο σύμβολο; + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Ένα ή περισσότερα από τα σύμβολα χρησιμοποιούνται και δεν μπορούν να διαγραφούν μέχρι να επεκταθούν ή να διαγραφούν τα στιγμιότυπά τους. + Expand Instances Επέκταση στιγμιοτύπων + Delete Instances Διαγραφή στιγμιοτύπων + Yes Ναι + No Όχι Delete Tab Διαγραφή στηλοθέτη Delete the graphic style “{name}”? Να διαγραφεί το στυλ γραφικών «{name}»; Delete Theme Διαγραφή θέματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index fe945423e6..c3b905d18c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -750,6 +750,12 @@ font-technology Variable Variables Delete Stop Eliminar parada Delete Swatch Eliminar muestra Delete Symbol Eliminar símbolo + Delete the selected symbol? ¿Eliminar el símbolo seleccionado? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Uno o más de los símbolos están en uso y no se pueden eliminar hasta que se expandan o eliminen sus instancias. + Expand Instances Expandir instancias + Delete Instances Eliminar instancias + Yes Sí + No No Delete Tab Eliminar tabulación Delete the graphic style “{name}”? ¿Eliminar el estilo gráfico “{name}”? Delete Theme Eliminar tema diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7ebd23d6bc..dd157932cf 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3018,6 +3018,12 @@ theme Appearance Ulkoasu Current Symbol Nykyinen symboli Delete Brush Poista sivellin Delete Symbol Poista symboli + Delete the selected symbol? Poistetaanko valittu symboli? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Yksi tai useampi symboleista on käytössä, eikä niitä voi poistaa ennen kuin niiden ilmentymät on laajennettu tai poistettu. + Expand Instances Laajenna ilmentymät + Delete Instances Poista ilmentymät + Yes Kyllä + No Ei Duplicate Brush Monista sivellin Duplicate Symbol Monista symboli Edit Symbol Muokkaa symbolia diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 859b2bfcd3..1ff18594a7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -752,6 +752,12 @@ font-technology Variable Variables Delete Stop Supprimer l’étape de dégradé Delete Swatch Supprimer la nuance Delete Symbol Supprimer le symbole + Delete the selected symbol? Supprimer le symbole sélectionné ? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Un ou plusieurs symboles sont utilisés et ne peuvent pas être supprimés tant que leurs instances ne sont pas décomposées ou supprimées. + Expand Instances Décomposer les instances + Delete Instances Supprimer les instances + Yes Oui + No Non Delete Tab Supprimer la tabulation Delete the graphic style “{name}”? Supprimer le style graphique « {name} » ? Delete Theme Supprimer le thème diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 02e7303ed4..254eb37fcd 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -974,6 +974,12 @@ font-technology Variable Változó Delete Stop Színátmenet-pont törlése Delete Swatch Színminta törlése Delete Symbol Szimbólum törlése + Delete the selected symbol? Törli a kijelölt szimbólumot? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Egy vagy több szimbólum használatban van, és nem törölhető, amíg a példányait ki nem bontja vagy nem törli. + Expand Instances Példányok kibontása + Delete Instances Példányok törlése + Yes Igen + No Nem Delete Tab Tabulátor törlése Delete the graphic style “{name}”? Törlöd ezt a grafikai stílust: „{name}”? Delete the library “{name}”? Törlöd ezt a könyvtárat: „{name}”? diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c2d3695755..8e49c172b2 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2837,6 +2837,12 @@ theme Appearance Tampilan Current Symbol Simbol saat ini Delete Brush Hapus kuas Delete Symbol Hapus simbol + Delete the selected symbol? Hapus simbol yang dipilih? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Satu atau beberapa simbol sedang digunakan dan tidak dapat dihapus sampai instansinya diperluas atau dihapus. + Expand Instances Perluas instansi + Delete Instances Hapus instansi + Yes Ya + No Tidak Duplicate Brush Duplikatkan kuas Duplicate Symbol Duplikatkan simbol Edit Symbol Edit simbol diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8021409d21..39addf3619 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -750,6 +750,12 @@ font-technology Variable Variabili Delete Stop Elimina cursore colore Delete Swatch Elimina campione Delete Symbol Elimina simbolo + Delete the selected symbol? Eliminare il simbolo selezionato? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Uno o più simboli sono in uso e non possono essere eliminati finché le loro istanze non vengono espanse o eliminate. + Expand Instances Espandi istanze + Delete Instances Elimina istanze + Yes Sì + No No Delete Tab Elimina tabulazione Delete the graphic style “{name}”? Eliminare lo stile grafico “{name}”? Delete Theme Elimina tema diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 269651408f..d9106487d1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1297,6 +1297,12 @@ font-technology Variable バリアブル Delete Stop 分岐点を削除 Delete Swatch スウォッチを削除 Delete Symbol シンボルを削除 + Delete the selected symbol? 選択したシンボルを削除しますか? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. 1 つ以上のシンボルが使用中のため、インスタンスを拡張または削除するまで削除できません。 + Expand Instances インスタンスを拡張 + Delete Instances インスタンスを削除 + Yes はい + No いいえ Delete Tab タブを削除 Delete Theme テーマを削除 Delete Transparency Flattener Preset 透明の分割・統合プリセットを削除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index fd0eaae44a..9c4d6ff2fe 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2650,6 +2650,12 @@ theme Appearance იერსახე Current Symbol მიმდინარე სიმბოლო Delete Brush ფუნჯის წაშლა Delete Symbol სიმბოლოს წაშლა + Delete the selected symbol? წაიშალოს მონიშნული სიმბოლო? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. ერთი ან მეტი სიმბოლო გამოიყენება და მისი წაშლა შეუძლებელია, სანამ მისი ეგზემპლარები არ გაიშლება ან არ წაიშლება. + Expand Instances ეგზემპლარების გაშლა + Delete Instances ეგზემპლარების წაშლა + Yes დიახ + No არა Duplicate Brush ფუნჯის დუბლირება Duplicate Symbol სიმბოლოს დუბლირება Edit Symbol სიმბოლოს რედაქტირება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 00666a8401..f04039cdc7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1288,6 +1288,12 @@ font-technology Variable 가변 Delete Stop 정지점 삭제 Delete Swatch 견본 삭제 Delete Symbol 심볼 삭제 + Delete the selected symbol? 선택한 심볼을 삭제하시겠습니까? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. 하나 이상의 심볼이 사용 중이므로 인스턴스를 확장하거나 삭제하기 전에는 삭제할 수 없습니다. + Expand Instances 인스턴스 확장 + Delete Instances 인스턴스 삭제 + Yes 예 + No 아니요 Delete Tab 탭 삭제 Delete Theme 테마 삭제 Delete Transparency Flattener Preset 투명도 병합 프리셋 삭제 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f04ea4da45..01d80c460f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2851,6 +2851,13 @@ theme Appearance Vormgeving Current Symbol Huidig symbool Delete Brush Penseel verwijderen Delete Symbol Symbool verwijderen + Delete the selected symbol? Het geselecteerde symbool verwijderen? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Een of meer van de symbolen zijn in gebruik en kunnen pas worden verwijderd als hun exemplaren zijn uitgebreid of verwijderd. + Expand Instances Exemplaren uitbreiden + Delete Instances Exemplaren verwijderen + Yes Ja + No Nee + Duplicate Brush Kwast dupliceren Duplicate Brush Penseel dupliceren Duplicate Symbol Symbool dupliceren Edit Symbol Symbool bewerken diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 17810fe501..84ac64f406 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2958,6 +2958,12 @@ theme Appearance Wygląd Current Symbol Bieżący symbol Delete Brush Usuń pędzel Delete Symbol Usuń symbol + Delete the selected symbol? Usunąć zaznaczony symbol? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Co najmniej jeden z symboli jest używany i nie można go usunąć, dopóki jego wystąpienia nie zostaną rozszerzone lub usunięte. + Expand Instances Rozszerz wystąpienia + Delete Instances Usuń wystąpienia + Yes Tak + No Nie Duplicate Brush Powiel pędzel Duplicate Symbol Powiel symbol Edit Symbol Edytuj symbol diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e1fc3b3e6d..e48ef54bd6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -663,6 +663,12 @@ Delete Stop Excluir Parada Delete Swatch Excluir Amostra Delete Symbol Excluir Símbolo + Delete the selected symbol? Excluir o símbolo selecionado? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Um ou mais símbolos estão em uso e não podem ser excluídos até que suas instâncias sejam expandidas ou excluídas. + Expand Instances Expandir Instâncias + Delete Instances Excluir Instâncias + Yes Sim + No Não Delete Tab Excluir Parada de Tabulação Delete Theme Excluir Tema Delete Transparency Flattener Preset Excluir Predefinido de Achatamento de Transparência diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 412d4d129b..c1567d10ca 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -748,6 +748,12 @@ font-technology Variable Вариативные Delete Stop Удалить точку перехода Delete Swatch Удалить образец Delete Symbol Удалить символ + Delete the selected symbol? Удалить выбранный символ? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Один или несколько символов используются, и их нельзя удалить, пока их экземпляры не будут разобраны или удалены. + Expand Instances Разобрать экземпляры + Delete Instances Удалить экземпляры + Yes Да + No Нет Delete Tab Удалить табуляцию Delete the graphic style “{name}”? Удалить графический стиль «{name}»? Delete Theme Удалить тему diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 08b0b8105c..c75c0f6ce8 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -737,6 +737,12 @@ font-technology Variable Variabla Delete Stop Radera stopp Delete Swatch Radera färgruta Delete Symbol Radera symbol + Delete the selected symbol? Vill du radera den markerade symbolen? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. En eller flera av symbolerna används och kan inte raderas förrän deras instanser har expanderats eller raderats. + Expand Instances Expandera instanser + Delete Instances Radera instanser + Yes Ja + No Nej Delete Tab Radera tabb Delete the graphic style “{name}”? Radera grafikstilen ”{name}”? Delete Theme Radera tema diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index fff0356575..21c15371a9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -729,6 +729,12 @@ font-technology Variable Değişken Delete Stop Durdurmayı Sil Delete Swatch Renk Örneğini Sil Delete Symbol Sembolü Sil + Delete the selected symbol? Seçili sembol silinsin mi? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Sembollerden biri veya birkaçı kullanımda ve örnekleri genişletilene ya da silinene kadar silinemez. + Expand Instances Örnekleri Genişlet + Delete Instances Örnekleri Sil + Yes Evet + No Hayır Delete Tab Sekmeyi Sil Delete the graphic style “{name}”? “{name}” grafik stili silinsin mi? Delete Theme Temayı Sil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 1c6f93e5d0..3117511dc8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -744,6 +744,12 @@ font-technology Variable Варіативні Delete Stop Видалити точку переходу Delete Swatch Видалити зразок Delete Symbol Видалити символ + Delete the selected symbol? Видалити вибраний символ? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Один або кілька символів використовуються, і їх не можна видалити, доки їхні екземпляри не буде розібрано або видалено. + Expand Instances Розібрати екземпляри + Delete Instances Видалити екземпляри + Yes Так + No Ні Delete Tab Видалити табуляцію Delete the graphic style “{name}”? Видалити графічний стиль «{name}»? Delete Theme Видалити тему diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 99d8437f89..b6d5604b37 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -870,6 +870,12 @@ font-technology Variable Biến thiên Delete Stop Xóa điểm dừng Delete Swatch Xóa mẫu màu Delete Symbol Xóa ký hiệu + Delete the selected symbol? Xóa ký hiệu đã chọn? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Một hoặc nhiều ký hiệu đang được sử dụng và không thể xóa cho đến khi các thực thể của chúng được mở rộng hoặc xóa. + Expand Instances Mở rộng thực thể + Delete Instances Xóa thực thể + Yes Có + No Không Delete Tab Xóa tab Delete the graphic style “{name}”? Xóa kiểu đồ họa “{name}”? Delete the library “{name}”? Xóa thư viện “{name}”? diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 6ecaf09308..7c50ba5773 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -693,6 +693,12 @@ Delete Stop 删除色标 Delete Swatch 删除色板 Delete Symbol 删除符号 + Delete the selected symbol? 要删除所选符号吗? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. 一个或多个符号正在使用中,在扩展或删除其实例之前无法删除。 + Expand Instances 扩展实例 + Delete Instances 删除实例 + Yes 是 + No 否 Delete Tab 删除制表位 Delete the graphic style “{name}”? 要删除图形样式“{name}”吗? Delete Theme 删除主题 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 75ee3a4134..2d61281dd2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -712,6 +712,12 @@ font-technology Variable 可變 Delete Stop 刪除色標 Delete Swatch 刪除色票 Delete Symbol 刪除符號 + Delete the selected symbol? 要刪除選取的符號嗎? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. 一個或多個符號正在使用中,在展開或刪除其範例之前無法刪除。 + Expand Instances 展開範例 + Delete Instances 刪除範例 + Yes 是 + No 否 Delete Tab 刪除定位點 Delete the graphic style “{name}”? 要刪除繪圖樣式「{name}」嗎? Delete Theme 刪除主題 diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index e99a24bf66..bc77f8e4c1 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -273,10 +273,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let cmd = if ui.input(|i| i.modifiers.alt) { "symbol.new" } else { "ui.symbolOptions" }; app.run(cmd, json!({})).ok(); } + // Alt deletes an unused symbol without asking; a symbol with instances still asks. if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Symbol"), false, sel.is_some(), 24.0).clicked() && let Some(n) = &sel { - app.run("symbol.delete", json!({"name": n})).ok(); + crate::dialogs::symbol_delete::ask(app, n, super::alt_held(ui)); } }); } @@ -286,11 +287,23 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let has_sel = app.session.active().is_some_and(|d| !d.selection.is_empty()); let inst = has_instances_selected(app); let name = json!({"name": sel}); - let items: [(&str, bool, &str, Value); 10] = [ + let items: [(&str, bool, &str, Value); 3] = [ (tl!("New Symbol…"), has_sel, "ui.symbolOptions", json!({})), (tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", name.clone()), (tl!("Duplicate Symbol"), sel.is_some(), "symbol.duplicate", name.clone()), - (tl!("Delete Symbol"), sel.is_some(), "symbol.delete", name.clone()), + ]; + for (label, enabled, cmd, params) in items { + if menu_item(ui, label, enabled, false) { + app.run(cmd, params).ok(); + } + } + // Asks first, as the panel's button does; the menu item has no Alt shortcut. + if menu_item(ui, tl!("Delete Symbol"), sel.is_some(), false) + && let Some(n) = &sel + { + crate::dialogs::symbol_delete::ask(app, n, false); + } + let items: [(&str, bool, &str, Value); 6] = [ (tl!("Symbol Options…"), sel.is_some(), "ui.symbolOptions", json!({"edit": true, "name": sel})), (tl!("Edit Symbol"), inst, "symbol.edit", json!({})), (tl!("Place Symbol Instance"), sel.is_some(), "symbol.place", name.clone()), @@ -738,6 +751,195 @@ mod tests { assert!(orange(3, 3) && orange(36, 36), "{:?} {:?}", thumb.pixels[3 * 40 + 3], thumb.pixels[36 * 40 + 36]); } + /// A document with symbol "Leaf", whose instance stands where its rectangle was, and symbol + /// "Dot", which no instance uses; "Dot" is current. + fn leaf_and_dot() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + for (name, x) in [("Leaf", 10), ("Dot", 150)] { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 30})).unwrap(); + app.run("symbol.new", json!({"name": name})).unwrap(); + } + // Dot's instance goes: no art uses Dot. + app.run("edit.clear", json!({})).unwrap(); + app.run("symbol.setCurrent", json!({"name": "Dot"})).unwrap(); + app + } + + /// The instances of symbol `name` in the active document, and the ordinary paths in it. + fn art(app: &VectorcraftApp, name: &str) -> (usize, usize) { + let (mut instances, mut paths) = (0, 0); + for l in &app.session.active().unwrap().doc.layers { + l.walk(&mut |n| match &n.kind { + NodeKind::SymbolInstance { symbol, .. } if symbol == name => instances += 1, + NodeKind::Path { .. } => paths += 1, + _ => {} + }); + } + (instances, paths) + } + + fn dialog_kind(app: &VectorcraftApp) -> Option<&str> { + app.ui.dialog.as_ref().map(|d| d.kind.as_str()) + } + + /// One frame of the panel with `modifiers` held, its output kept. + fn frame_held(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec, modifiers: egui::Modifiers) -> egui::FullOutput { + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(236.0, 400.0))); + let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out + } + + /// The labels of the clickable accessibility nodes of `out`, with their centers. + fn clickable(out: &egui::FullOutput) -> Vec<(String, Pos2)> { + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + nodes + .iter() + .filter(|(_, n)| n.supports_action(egui::accesskit::Action::Click)) + .filter_map(|(_, n)| { + let b = n.bounds()?; + Some((n.label()?.trim().to_string(), pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32))) + }) + .collect() + } + + /// Clicks the panel's Delete Symbol button with `modifiers` held. + fn click_delete(app: &mut VectorcraftApp, modifiers: egui::Modifiers) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, app, vec![], modifiers); + let at = clickable(&out).into_iter().find(|(l, _)| l == "Delete Symbol").expect("a Delete Symbol button").1; + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + frame_held(&ctx, app, vec![egui::Event::PointerMoved(at), press(true), press(false)], modifiers); + } + + /// Clicks the panel menu's Delete Symbol item. + fn menu_delete(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let labels = menu_frame(&ctx, app, vec![]); + let item = labels.iter().find(|(t, _)| t.trim() == "Delete Symbol").map(|(_, r)| r.center()).expect("Delete Symbol in the menu"); + menu_frame(&ctx, app, vec![egui::Event::PointerMoved(item), button(item, true)]); + menu_frame(&ctx, app, vec![button(item, false)]); + } + + /// Delete Symbol, from the panel's button or its menu, asks "Delete the selected symbol?" for a + /// symbol no instance uses, and the in-use question for one with instances, before changing + /// the document; No leaves it as it was and Yes deletes the symbol. Alt-click on the button + /// deletes an unused symbol without asking, and still asks for one with instances. + #[test] + fn delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once() { + let mut app = leaf_and_dot(); + let before = app.session.active().unwrap().doc.clone(); + let unchanged = |app: &VectorcraftApp| Arc::ptr_eq(&before, &app.session.active().unwrap().doc); + click_delete(&mut app, egui::Modifiers::NONE); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND)); + assert!(unchanged(&app), "nothing changes while it asks"); + crate::dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert!(unchanged(&app), "No changes nothing"); + menu_delete(&mut app); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND), "the menu item asks too"); + assert!(unchanged(&app)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(symbols(&mut app), ["Leaf"], "Yes deletes it"); + // Alt-click on the button: an unused symbol goes without a question. + app.run("edit.undo", json!({})).unwrap(); + app.run("symbol.setCurrent", json!({"name": "Dot"})).unwrap(); + click_delete(&mut app, egui::Modifiers::ALT); + assert!(app.ui.dialog.is_none()); + assert_eq!(symbols(&mut app), ["Leaf"]); + // A symbol with an instance asks, with Alt held too, from the button and from the menu. + app.run("symbol.setCurrent", json!({"name": "Leaf"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + for alt in [egui::Modifiers::NONE, egui::Modifiers::ALT] { + click_delete(&mut app, alt); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::USED), "{alt:?}"); + crate::dialogs::cancel(&mut app); + } + menu_delete(&mut app); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::USED)); + crate::dialogs::cancel(&mut app); + assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc), "Cancel changes nothing"); + assert_eq!(art(&app, "Leaf"), (1, 0)); + } + + /// The in-use question: Expand Instances deletes the symbol and turns its instance into + /// ordinary art, Delete Instances deletes the symbol and its instance, each in one undo step. + #[test] + fn the_in_use_question_expands_or_deletes_the_instances() { + for (discard, left) in [(false, (0, 1)), (true, (0, 0))] { + let mut app = leaf_and_dot(); + crate::dialogs::symbol_delete::ask(&mut app, "Leaf", false); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::USED)); + if discard { + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(symbols(&mut app), ["Dot"], "discard {discard}"); + assert_eq!(art(&app, "Leaf"), left, "discard {discard}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!((symbols(&mut app), art(&app, "Leaf")), (vec!["Leaf".to_string(), "Dot".to_string()], (1, 0)), "one undo step"); + } + } + + /// A question asked in one document deletes nothing once another is active, and Yes for a + /// symbol that has gained an instance since asks the in-use question instead. + #[test] + fn a_stale_delete_symbol_question_deletes_nothing() { + let mut app = leaf_and_dot(); + crate::dialogs::symbol_delete::ask(&mut app, "Dot", false); + let asked = app.ui.dialog.clone(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + app.run("symbol.new", json!({"name": "Dot"})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + app.ui.dialog = asked; + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(symbols(&mut app), ["Dot"], "the other document keeps its symbol"); + // Back in the first document: Dot gains an instance while the question is open. + app.run("document.activate", json!({"index": 0})).unwrap(); + crate::dialogs::symbol_delete::ask(&mut app, "Dot", false); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND)); + app.run("symbol.place", json!({"name": "Dot"})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::USED)); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); + assert_eq!(art(&app, "Dot"), (1, 0)); + } + + /// The questions' buttons: Yes and No for an unused symbol; Expand Instances, Delete Instances + /// and Cancel for one with instances. + #[test] + fn the_delete_symbol_questions_show_their_buttons() { + let mut app = leaf_and_dot(); + for (name, want) in [("Dot", &["Yes", "No"][..]), ("Leaf", &["Expand Instances", "Delete Instances", "Cancel"][..])] { + crate::dialogs::symbol_delete::ask(&mut app, name, false); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + // The window measures itself in its first frame and draws its buttons in the next. + let mut out = None; + for _ in 0..2 { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut o = ctx.run_ui(raw, |ui| crate::dialogs::show(&mut app, ui.ctx())); + o.textures_delta.clear(); + out = Some(o); + } + let out = out.expect("a frame"); + let labels: Vec = clickable(&out).into_iter().map(|(l, _)| l).collect(); + for w in want { + assert!(labels.iter().any(|l| l == w), "{name}: {w} in {labels:?}"); + } + assert!(!labels.iter().any(|l| l == "OK"), "{name}: {labels:?}"); + crate::dialogs::cancel(&mut app); + } + } + /// #4121: with symbol instances selected, the Control bar's Replace menu lists the document's /// symbols and shows the instance's own; picking another replaces it. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 97e9abf9f0..6d97e0097d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -597,6 +597,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493). - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in library, Basic Shapes, is original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. + - **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`. - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol. A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection), or the view commands on empty canvas. - A right-click over locked objects adds an Unlock submenu to the canvas context menu. The submenu lists up to 20 locked objects under the pointer, topmost first, by the name the Layers panel shows, and choosing one unlocks it (`layer.setProps`). A locked group is listed as one item. Objects on hidden, locked or template layers are not listed. From f4161a3ab75f08bb154005345665565337e0c36b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 01:25:05 -0700 Subject: [PATCH 14/70] Symbols: the French delete question keeps the no-break space before ? --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1ff18594a7..5747e2663d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -752,7 +752,7 @@ font-technology Variable Variables Delete Stop Supprimer l’étape de dégradé Delete Swatch Supprimer la nuance Delete Symbol Supprimer le symbole - Delete the selected symbol? Supprimer le symbole sélectionné ? + Delete the selected symbol? Supprimer le symbole sélectionné ? One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Un ou plusieurs symboles sont utilisés et ne peuvent pas être supprimés tant que leurs instances ne sont pas décomposées ou supprimées. Expand Instances Décomposer les instances Delete Instances Supprimer les instances From 62555c224626535d6deb402744f266fa045e11f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 00:56:17 -0700 Subject: [PATCH 15/70] Contextual Task Bar: a basic shape shows its properties in place of Lock A live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool shows a Shape Properties button where Lock was. It opens a popup with the shape's rows from the Transform panel, which stays open while the fields are edited. Every other selection, and the Direct and Group Selection tools, keep Lock; Object > Lock and Cmd+2 still lock a shape. The Transform panel, the Properties panel and the popup draw the rows through one live_shape_rows function. --- crates/ui-egui/src/canvas/task_bar.rs | 34 +++++- crates/ui-egui/src/canvas/tests.rs | 15 ++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/panels/properties.rs | 12 +- crates/ui-egui/src/panels/transform.rs | 47 +++++--- crates/ui-egui/src/tests/taskbar.rs | 146 +++++++++++++++++++++++- docs/target-app-parity.md | 1 + 32 files changed, 243 insertions(+), 38 deletions(-) diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 61c9719878..cf40955ee6 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -33,6 +33,7 @@ fn picked_artboards_bounds(app: &VectorcraftApp) -> Option { /// The Contextual Task Bar: a floating pill under the selection with the most likely next actions. /// With the Artboard tool it sits under the selected artboards and offers Resize (Artboard /// Options), Duplicate, Rearrange All (with two or more artboards) and Export (Export for Screens). +/// A basic shape selected with the Selection tool shows a Shape Properties button in place of Lock. /// Its handle drags it anywhere on the canvas; unpinned it keeps that offset as it follows the /// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { @@ -67,6 +68,17 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { && first.as_ref().is_some_and(|f| { f.name.as_deref() == Some("Image Trace") && f.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) }); + // A basic shape (a live rectangle, rounded rectangle, ellipse or polygon) selected whole with the + // Selection tool: its properties take the place of Lock, as in the reference app + // (). + use vectorcraft_doc::LiveShape; + let shape = first.clone().filter(|f| { + n == 1 + && st.selection.anchors.is_empty() + && app.session.tool_id() == "selection" + && matches!(&f.kind, NodeKind::Path { live: Some(l), .. } + if matches!(**l, LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. })) + }); let mut items: Vec<(&str, &str, &str, serde_json::Value)> = vec![]; // (label, icon, command, params) let none = || json!({}); if on_artboards { @@ -228,7 +240,8 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { run = Some((*cmd, params.clone())); } } - // The selected objects' Fill, Stroke, Recolor Artwork and Lock, left out with the Artboard tool. + // The selected objects' Fill, Stroke, Recolor Artwork and Lock (a basic shape's + // properties instead), left out with the Artboard tool. if !on_artboards { let (r, resp) = ui.allocate_exact_size(vec2(26.0, 30.0), Sense::click()); let chip = egui::Rect::from_center_size(r.center(), vec2(16.0, 16.0)); @@ -251,10 +264,21 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { if colored && widgets::icon_button(ui, "palette", tl!("Recolor Artwork"), false, 30.0).clicked() { run = Some(("ui.recolorDialog", json!({}))); } - // The Lock button is off in isolation mode, as Object › Lock › Selection is. - let lockable = crate::menus::enabled(app, "object.lock"); - if widgets::icon_button_enabled(ui, "lock", tl!("Lock (⌘2)"), false, lockable, 30.0).clicked() { - run = Some(("object.lock", json!({}))); + if let Some(shape) = &shape + && let NodeKind::Path { live: Some(live), .. } = &shape.kind + { + // The shape's properties in a popup that stays open while its fields are edited. + let props = widgets::icon_button(ui, "shapes", tl!("Shape Properties"), false, 30.0); + egui::Popup::menu(&props).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.set_min_width(250.0); + crate::panels::transform::live_shape_rows(app, ui, shape, live, "task-bar-shape", true); + }); + } else { + // The Lock button is off in isolation mode, as Object › Lock › Selection is. + let lockable = crate::menus::enabled(app, "object.lock"); + if widgets::icon_button_enabled(ui, "lock", tl!("Lock (⌘2)"), false, lockable, 30.0).clicked() { + run = Some(("object.lock", json!({}))); + } } } let more = widgets::icon_button(ui, "ellipsis", tl!("More Options"), false, 30.0); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index ed67da7129..17b05d72ee 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6839,7 +6839,8 @@ fn the_task_bar_shows_a_stroke_chip_beside_fill() { let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui)); out.textures_delta.clear(); let bar = task_bar_rect(&ctx).expect("the task bar shows"); - // Right to left: the frame's margin, More Options, Lock, Recolor, then Stroke and Fill. + // Right to left: the frame's margin, More Options, Shape Properties (Lock's place), Recolor, + // then Stroke and Fill. let stroke_x = bar.right() - 8.0 - 3.0 * (30.0 + 6.0) - 13.0; let fill_x = stroke_x - 26.0 - 6.0; let blue = Color32::from_rgb(0x22, 0x44, 0xcc); @@ -6896,7 +6897,8 @@ fn the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere() { out.textures_delta.clear(); out.shapes }; - // Right to left: the frame's margin, More Options, Lock, Recolor, then Stroke and Fill. + // Right to left: the frame's margin, More Options, Shape Properties (Lock's place), Recolor, + // then Stroke and Fill. let stroke_x = |bar: egui::Rect| bar.right() - 8.0 - 3.0 * (30.0 + 6.0) - 13.0; let chip_with = |shapes: &[egui::epaint::ClippedShape], bar: egui::Rect, x: f32, color: Color32| { shapes.iter().any(|c| match &c.shape { @@ -6948,7 +6950,7 @@ fn the_task_bar_recolors_coloured_art() { frame(app, &ctx, vec![]); frame(app, &ctx, vec![]); let bar = task_bar_rect(&ctx).expect("the task bar shows"); - // Right to left: the frame's margin, More Options, Lock, then Recolor. + // Right to left: the frame's margin, More Options, Shape Properties (Lock's place), then Recolor. let at = pos2(bar.right() - 8.0 - 30.0 - 6.0 - 30.0 - 6.0 - 15.0, bar.center().y); let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; frame(app, &ctx, vec![egui::Event::PointerMoved(at)]); @@ -6975,8 +6977,11 @@ fn the_task_bar_recolors_coloured_art() { fn the_task_bar_lock_button_is_off_in_isolation_mode() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); - let a = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); - let b = app.session.execute("shape.rectangle", &json!({"x": 210, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); + // Plain paths: a basic shape shows its properties in Lock's place. + let square = + |x: f64| json!({"anchors": [{"x": x, "y": 130}, {"x": x + 40.0, "y": 130}, {"x": x + 40.0, "y": 170}, {"x": x, "y": 170}], "closed": true}); + let a = app.session.execute("path.create", &square(150.0)).unwrap()["id"].clone(); + let b = app.session.execute("path.create", &square(210.0)).unwrap()["id"].clone(); app.session.execute("select.set", &json!({"ids": [a.clone(), b]})).unwrap(); let g = app.session.execute("object.group", &json!({})).unwrap()["id"].clone(); app.select_tool("selection"); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2048bbcc9c..dabb1c8e9a 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2922,6 +2922,7 @@ font-technology Variable Променливи Shape Mode Режим на фигура Shape Modes: Режими на фигури: Shape Properties: Свойства на фигурата: + Shape Properties Свойства на фигурата Shaper Tool Инструмент „Shaper“ Shapes Фигури Shear Срязване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 2ac957c9ac..da8c5d134e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2014,6 +2014,7 @@ lighting Light Svjetlo Polygon Properties: Svojstva mnogougla: Rectangle Properties: Svojstva pravougaonika: Shape Properties: Svojstva oblika: + Shape Properties Svojstva oblika Sides: Stranice: Transform options Opcije transformacije Transform Both Transformiši oboje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index ea8d621822..59984a5192 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3753,6 +3753,7 @@ Shape Mode Mode de forma Shape Modes: Modes de forma: Shape Properties: Propietats de la forma: + Shape Properties Propietats de la forma Shape: Forma: Shaper Shaper Shaper Tool Eina Shaper diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 93142cadb6..11d38443b6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2041,6 +2041,7 @@ lighting Light Světlo Polygon Properties: Vlastnosti mnohoúhelníku: Rectangle Properties: Vlastnosti obdélníku: Shape Properties: Vlastnosti tvaru: + Shape Properties Vlastnosti tvaru Sides: Strany: Transform options Možnosti transformace Transform Both Transformovat obojí diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 160abd6bf7..1203b3d366 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1852,6 +1852,7 @@ lighting Light Lys Polygon Properties: Polygonegenskaber: Rectangle Properties: Rektangelegenskaber: Shape Properties: Figuregenskaber: + Shape Properties Figuregenskaber Sides: Sider: Transform options Transformeringsindstillinger Transform Both Transformer begge diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 08869d7652..e832311b06 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2957,6 +2957,7 @@ mark-style Japanese Japanisch Shape Mode Formmodus Shape Modes: Formmodi: Shape Properties: Formeigenschaften: + Shape Properties Formeigenschaften Shaper Tool Shaper-Werkzeug Shapes Formen Shear Verbiegen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 3d074c7167..90709397af 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3428,6 +3428,7 @@ theme Appearance Εμφάνιση Shape Mode Λειτουργία σχήματος Shape Modes: Λειτουργίες σχημάτων: Shape Properties: Ιδιότητες σχήματος: + Shape Properties Ιδιότητες σχήματος Shaper Tool Διαμορφωτής σχημάτων (Shaper Tool) Shear Tool Διάτμηση (Shear Tool) Shift to Color… Μετατόπιση προς χρώμα… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c3b905d18c..f90a4b0471 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2992,6 +2992,7 @@ font-technology Variable Variables Shape Mode Modo de forma Shape Modes: Modos de forma: Shape Properties: Propiedades de forma: + Shape Properties Propiedades de forma Shaper Tool Herramienta Shaper Shapes Formas Shear Inclinar diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index dd157932cf..8c4bc1fc10 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2003,6 +2003,7 @@ lighting Light Valo Polygon Properties: Monikulmion ominaisuudet: Rectangle Properties: Suorakulmion ominaisuudet: Shape Properties: Muodon ominaisuudet: + Shape Properties Muodon ominaisuudet Sides: Sivut: Transform options Muunnosasetukset Transform Both Muunna molemmat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 5747e2663d..7db8ee535a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2989,6 +2989,7 @@ font-technology Variable Variables Shape Effects Effets de forme Shape Mode Mode de forme Shape Modes: Modes de forme : + Shape Properties Propriétés de la forme Shape Properties: Propriétés de la forme : Shaper Tool Outil Shaper Shapes Formes diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 254eb37fcd..0aceab5ab4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3602,6 +3602,7 @@ mark-style Japanese Japán Shape Mode Alakzatmód Shape Modes: Alakzatmódok: Shape Properties: Alakzat tulajdonságai: + Shape Properties Alakzat tulajdonságai Shape: Alak: Shaper Alakformáló Shaper Tool Alakformáló diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 8e49c172b2..95a3036337 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1852,6 +1852,7 @@ lighting Light Cahaya Polygon Properties: Properti poligon: Rectangle Properties: Properti persegi panjang: Shape Properties: Properti bentuk: + Shape Properties Properti bentuk Sides: Sisi: Transform options Opsi transformasi Transform Both Transformasikan keduanya diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 39addf3619..a9c16d3ba9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3026,6 +3026,7 @@ mark-style Japanese Giapponese Shape Mode Metodo forma Shape Modes: Metodi forma: Shape Properties: Proprietà forma: + Shape Properties Proprietà forma Shaper Tool Strumento Sagomatore Shapes Forme Shear Inclina diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d9106487d1..01c25917b9 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2868,6 +2868,7 @@ mark-style Japanese 日本式 Shape Mode シェイプモード Shape Modes: シェイプモード: Shape Properties: シェイプのプロパティ: + Shape Properties シェイプのプロパティ Shaper Tool Shaper ツール Shapes シェイプ Shear シアー diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9c4d6ff2fe..e0e1a10953 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1754,6 +1754,7 @@ lighting Light სინათლე Polygon Properties: მრავალკუთხედის თვისებები: Rectangle Properties: მართკუთხედის თვისებები: Shape Properties: ფიგურის თვისებები: + Shape Properties ფიგურის თვისებები Sides: გვერდები: Transform options გარდაქმნის პარამეტრები Transform Both ორივეს გარდაქმნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f04039cdc7..45ce73252c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2858,6 +2858,7 @@ mark-style Japanese 일본식 Shape Mode 모양 모드 Shape Modes: 모양 모드: Shape Properties: 모양 속성: + Shape Properties 모양 속성 Shaper Tool 셰이퍼 도구 Shapes 모양 Shear 기울이기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 7fb221d3ed..e4cca253f8 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1866,6 +1866,7 @@ lighting Light Licht Polygon Properties: Veelhoekeigenschappen: Rectangle Properties: Rechthoekeigenschappen: Shape Properties: Vormeigenschappen: + Shape Properties Vormeigenschappen Sides: Zijden: Transform options Transformatieopties Transform Both Beide transformeren diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 84ac64f406..027f7198e2 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1962,6 +1962,7 @@ lighting Light Światło Polygon Properties: Właściwości wielokąta: Rectangle Properties: Właściwości prostokąta: Shape Properties: Właściwości kształtu: + Shape Properties Właściwości kształtu Sides: Boki: Transform options Opcje przekształcania Transform Both Przekształć oba diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e48ef54bd6..e9ee07994f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2483,6 +2483,7 @@ Shape Mode Modo de Forma Shape Modes: Modos de Forma: Shape Properties: Propriedades da Forma: + Shape Properties Propriedades da Forma Shaper Tool Ferramenta Formador Shapes Formas Shear Cisalhar diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index c1567d10ca..dea1bee849 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3022,6 +3022,7 @@ mark-style Japanese Японский Shape Mode Режим фигуры Shape Modes: Режимы фигур: Shape Properties: Свойства фигуры: + Shape Properties Свойства фигуры Shaper Tool Инструмент «Формообразование» Shapes Фигуры Shear Наклонить diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c75c0f6ce8..fcd0427a77 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2922,6 +2922,7 @@ font-technology Variable Variabla Shape Mode Formläge Shape Modes: Formlägen: Shape Properties: Formegenskaper: + Shape Properties Formegenskaper Shaper Tool Formningsverktyg Shapes Former Shear Skjuva diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 21c15371a9..7a1ea36471 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2833,6 +2833,7 @@ shape Open Açık Shape Mode Şekil Modu Shape Modes: Şekil Modları: Shape Properties: Şekil Özellikleri: + Shape Properties Şekil Özellikleri Shaper Tool Şekillendirici Aracı Shapes Şekiller Shear Kesme diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 3117511dc8..58693ddfd1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3018,6 +3018,7 @@ mark-style Japanese Японський Shape Mode Режим фігури Shape Modes: Режими фігур: Shape Properties: Властивості фігури: + Shape Properties Властивості фігури Shaper Tool Інструмент «Формоутворення» Shapes Фігури Shear Нахилити diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index b6d5604b37..aaa74d0e7c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3346,6 +3346,7 @@ mark-style Japanese Kiểu Nhật Shape Mode Chế độ hình dạng Shape Modes: Chế độ hình dạng: Shape Properties: Thuộc tính hình dạng: + Shape Properties Thuộc tính hình dạng Shape: Hình dạng: Shaper Tạo hình Shaper Tool Công cụ Tạo hình diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 7c50ba5773..71b1fead14 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2859,6 +2859,7 @@ font-script Japanese 汉字 Shape Mode 形状模式 Shape Modes: 形状模式: Shape Properties: 形状属性: + Shape Properties 形状属性 Shaper Tool Shaper 工具 Shapes 形状 Shear 倾斜 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 2d61281dd2..a89fd28cce 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3833,6 +3833,7 @@ font-script Japanese 漢字 Shape Mode 形狀模式 Shape Modes: 形狀模式: Shape Properties: 形狀內容: + Shape Properties 形狀內容 Shaper Tool Shaper 工具 Shapes 形狀 Shear 傾斜 diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index a10f5c1334..c0ab7f5e9a 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -6,7 +6,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{LiveCorners, LiveShape, NodeKind, Unit, WidthProfile}; use vectorcraft_engine::cmd::newdoc; -use super::{corner_radius_row, first_selected, pstate, set_pstate}; +use super::{first_selected, pstate, set_pstate}; use crate::theme::Tokens; use crate::widgets::{self, dim_label, divider, section_header}; use crate::{VectorcraftApp, icons}; @@ -798,15 +798,7 @@ pub fn transform_section(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(n) = first_selected(app) && let NodeKind::Path { live: Some(live), .. } = &n.kind { - match &**live { - vectorcraft_doc::LiveShape::Rectangle { .. } => corner_radius_row(app, ui, &n, "radius"), - vectorcraft_doc::LiveShape::Polygon { .. } => super::transform::polygon_rows(app, ui, &n, live, "props-polygon"), - vectorcraft_doc::LiveShape::Ellipse { pie, .. } => { - widgets::subheader(ui, tl!("Ellipse Properties:")); - super::transform::pie_rows(app, ui, *pie, "props-pie"); - } - _ => {} - } + super::transform::live_shape_rows(app, ui, &n, live, "props", false); } } diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 95f1488408..df8683a012 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -345,23 +345,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { && !matches!(**live, vectorcraft_doc::LiveShape::Path { .. }) { widgets::divider(ui); - match &**live { - vectorcraft_doc::LiveShape::Rectangle { .. } => { - widgets::subheader(ui, tl!("Rectangle Properties:")); - corner_radius_row(app, ui, &n, "xfp-radius"); - } - vectorcraft_doc::LiveShape::Polygon { .. } => { - widgets::subheader(ui, tl!("Polygon Properties:")); - polygon_rows(app, ui, &n, live, "xfp-polygon"); - } - vectorcraft_doc::LiveShape::Ellipse { pie, .. } => { - widgets::subheader(ui, tl!("Ellipse Properties:")); - pie_rows(app, ui, *pie, "xfp-pie"); - } - _ => { - widgets::subheader(ui, tl!("Shape Properties:")); - widgets::dim_label(ui, tl!(n.kind_label())); - } + if !live_shape_rows(app, ui, &n, live, "xfp", true) { + widgets::subheader(ui, tl!("Shape Properties:")); + widgets::dim_label(ui, tl!(n.kind_label())); } } if pstate::(ui.ctx(), "xf-hide-options") { @@ -377,6 +363,33 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// A live rectangle's, polygon's or ellipse's properties (Transform and Properties panels, and the +/// Contextual Task Bar), their widget ids under `id`. `headed` adds the Rectangle and Polygon +/// Properties headings; an ellipse's heading always shows. Returns false, drawing nothing, for +/// other live shapes. +pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, id: &str, headed: bool) -> bool { + match live { + LiveShape::Rectangle { .. } => { + if headed { + widgets::subheader(ui, tl!("Rectangle Properties:")); + } + corner_radius_row(app, ui, n, &format!("{id}-radius")); + } + LiveShape::Polygon { .. } => { + if headed { + widgets::subheader(ui, tl!("Polygon Properties:")); + } + polygon_rows(app, ui, n, live, &format!("{id}-polygon")); + } + LiveShape::Ellipse { pie, .. } => { + widgets::subheader(ui, tl!("Ellipse Properties:")); + pie_rows(app, ui, *pie, &format!("{id}-pie")); + } + _ => return false, + } + true +} + /// An ellipse's Pie Start and End Angle (degrees, counterclockwise from 3 o'clock; 0 to 360 is the /// whole ellipse) and Invert Pie, which shows the other part of it (Transform and Properties panels). pub(crate) fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64), id: &str) { diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 27c49ac5e3..2cc79e6daa 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1,6 +1,7 @@ //! The Contextual Task Bar's actions for each kind of selection: open paths offer Join and Edit //! Path, compound paths and clipping masks their Release, images selected with vector art Make -//! Clipping Mask, and type converts between point and area type. +//! Clipping Mask, type converts between point and area type, and a basic shape shows its +//! properties in place of Lock. use egui::{Event, PointerButton, Pos2, Rect, vec2}; use serde_json::json; @@ -219,6 +220,149 @@ fn direct_selected_anchors_still_offer_remove_and_cut() { assert!(!has(&texts, "Edit Path"), "{texts:?}"); } +/// Click the task bar's button left of More Options (Lock, or a basic shape's Shape Properties), +/// and return the context and what the frame after the click draws. +fn click_lock_slot(app: &mut VectorcraftApp) -> (egui::Context, Vec<(String, Rect)>) { + let (ctx, _) = bar(app); + let r = canvas::task_bar_rect(&ctx).expect("the task bar shows"); + // Right to left: the frame's margin, More Options, then the button. + let p = Pos2::new(r.right() - 8.0 - 30.0 - 6.0 - 15.0, r.center().y); + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![Event::PointerMoved(p)]); + frame(app, &ctx, vec![press(true)]); + frame(app, &ctx, vec![press(false)]); + let texts = frame(app, &ctx, vec![]); + (ctx, texts) +} + +/// Type `value` into the field showing `field` and press Enter. +fn type_into(app: &mut VectorcraftApp, ctx: &egui::Context, texts: &[(String, Rect)], field: &str, value: &str) { + let p = at(texts, field); + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(p), press(true), press(false)]); + // Focus selected the whole field: typing replaces it. + frame(app, ctx, vec![]); + frame(app, ctx, vec![Event::Text(value.into())]); + let enter = Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(app, ctx, vec![enter]); + frame(app, ctx, vec![]); +} + +fn live(app: &VectorcraftApp, id: u64) -> vectorcraft_doc::LiveShape { + match kind(app, id) { + NodeKind::Path { live: Some(l), .. } => *l, + k => panic!("not a live shape: {k:?}"), + } +} + +fn locked(app: &VectorcraftApp, id: u64) -> bool { + app.session.active().unwrap().doc.node(NodeId(id)).unwrap().locked +} + +/// A basic shape selected with the Selection tool shows Shape Properties in place of Lock: a +/// rectangle, rounded rectangle, ellipse or polygon, each under its own heading. +#[test] +fn a_basic_shape_shows_its_properties_in_place_of_lock() { + let mut app = app(); + let shapes = [ + (id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()), "Rectangle Properties:"), + (id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60, "radius": 10})).unwrap()), "Rectangle Properties:"), + (id(app.run("shape.ellipse", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()), "Ellipse Properties:"), + (id(app.run("shape.polygon", json!({"cx": 100, "cy": 100, "radius": 40, "sides": 6})).unwrap()), "Polygon Properties:"), + ]; + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + for (shape, heading) in shapes { + select(&mut app, &[shape]); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, heading), "the popup starts closed: {texts:?}"); + let (_, texts) = click_lock_slot(&mut app); + assert!(has(&texts, heading), "{heading}: {texts:?}"); + assert!(!locked(&app, shape), "the button doesn't lock the shape"); + } +} + +/// The popup's fields edit the shape through `object.setLiveShape`, and Undo restores it. +#[test] +fn the_shape_properties_popup_edits_the_shape() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let corners = |app: &VectorcraftApp, id: u64| match live(app, id) { + vectorcraft_doc::LiveShape::Rectangle { radii, .. } => radii, + l => panic!("{l:?}"), + }; + let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60, "radius": 10})).unwrap()); + select(&mut app, &[rect]); + let (ctx, texts) = click_lock_slot(&mut app); + type_into(&mut app, &ctx, &texts, "10 pt", "20"); + assert_eq!(corners(&app, rect), [20.0; 4]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(corners(&app, rect), [10.0; 4]); + + let ellipse = id(app.run("shape.ellipse", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()); + select(&mut app, &[ellipse]); + let pie = |app: &VectorcraftApp| match live(app, ellipse) { + vectorcraft_doc::LiveShape::Ellipse { pie, .. } => pie, + l => panic!("{l:?}"), + }; + let (ctx, texts) = click_lock_slot(&mut app); + type_into(&mut app, &ctx, &texts, "360°", "180"); + assert_eq!(pie(&app), (0.0, 180.0)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(pie(&app), (0.0, 360.0)); + + let polygon = id(app.run("shape.polygon", json!({"cx": 100, "cy": 100, "radius": 40, "sides": 6})).unwrap()); + select(&mut app, &[polygon]); + let sides = |app: &VectorcraftApp| match live(app, polygon) { + vectorcraft_doc::LiveShape::Polygon { sides, .. } => sides, + l => panic!("{l:?}"), + }; + let (ctx, texts) = click_lock_slot(&mut app); + type_into(&mut app, &ctx, &texts, "6", "5"); + assert_eq!(sides(&app), 5); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(sides(&app), 6); +} + +/// Every other selection keeps Lock: a plain closed path, a star (a plain path), a path with live +/// corners, a group and several objects. The Direct Selection tool keeps it for a basic shape. +#[test] +fn other_selections_keep_lock() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let closed = json!({"anchors": [{"x": 50, "y": 200}, {"x": 150, "y": 80}, {"x": 250, "y": 200}], "closed": true}); + let path = id(app.run("path.create", closed).unwrap()); + let star = id(app.run("shape.star", json!({"cx": 200, "cy": 150, "radius1": 40})).unwrap()); + let rounded = id(app.run("shape.star", json!({"cx": 300, "cy": 150, "radius1": 40})).unwrap()); + select(&mut app, &[rounded]); + app.run("object.setLiveShape", json!({"radius": 4})).unwrap(); + assert!(matches!(live(&app, rounded), vectorcraft_doc::LiveShape::Path { .. })); + let a = id(app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 30, "height": 30})).unwrap()); + let b = id(app.run("shape.ellipse", json!({"x": 60, "y": 20, "width": 30, "height": 30})).unwrap()); + select(&mut app, &[a, b]); + let several = [a, b]; + let c = id(app.run("shape.rectangle", json!({"x": 20, "y": 250, "width": 30, "height": 30})).unwrap()); + let d = id(app.run("shape.rectangle", json!({"x": 60, "y": 250, "width": 30, "height": 30})).unwrap()); + select(&mut app, &[c, d]); + let group = id(app.run("object.group", json!({})).unwrap()); + let headings = ["Rectangle Properties:", "Ellipse Properties:", "Polygon Properties:"]; + for ids in [vec![path], vec![star], vec![rounded], vec![group], several.to_vec()] { + select(&mut app, &ids); + let (_, texts) = click_lock_slot(&mut app); + assert!(!headings.iter().any(|h| has(&texts, h)), "{ids:?}: {texts:?}"); + assert!(ids.iter().all(|i| locked(&app, *i)), "{ids:?} locks"); + app.run("object.unlockAll", json!({})).unwrap(); + } + let shape = id(app.run("shape.rectangle", json!({"x": 300, "y": 40, "width": 30, "height": 30})).unwrap()); + for tool in ["directSelection", "groupSelection"] { + app.run("tool.select", json!({ "tool": tool })).unwrap(); + select(&mut app, &[shape]); + let (_, texts) = click_lock_slot(&mut app); + assert!(!has(&texts, "Rectangle Properties:"), "{tool}: {texts:?}"); + assert!(locked(&app, shape), "{tool} keeps Lock"); + app.run("object.unlockAll", json!({})).unwrap(); + } +} + /// A compound path under the Direct Selection tool isn't offered Edit Path, which would only switch /// to the tool already in use; the Selection tool still offers it. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6d97e0097d..cc2b987b3f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -572,6 +572,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With one image selected, the contextual task bar offers Image Trace, which traces the image at once with the Default preset (the Image Trace panel is left as it was), and Crop Image; with an Image Trace object it offers Expand, which keeps only the traced paths. This follows Illustrator's bar: for a selected image it includes Image Trace, Retype and Crop Image, and traced artwork can be expanded from it ([Contextual Task Bar announcement](https://community.adobe.com/announcements-651/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580)). Offset Path and Simplify, which don't apply to an image, aren't offered for one. Not done: Retype, which the app doesn't have. - With the Artboard tool, the contextual task bar sits under the selected artboards and offers Resize (Artboard Options for the active artboard), Duplicate (each selected artboard, in one undo step, the copies then selected), Rearrange All (with two or more artboards) and Export (Export for Screens with the selected artboards checked). This follows Illustrator's bar: while the Artboard tool is in use, it has options for resizing, duplicating and exporting artboards (the [Contextual Task Bar announcement](https://community.adobe.com/questions-652/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580); Rearrange and Export on the bar: [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/)). - The contextual task bar offers more next steps by selection (): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, and point or area type Convert To Area Type or Convert To Point Type beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`. + - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview says: "For a basic shape created with tools such as the Rectangle tool and the Star tool, you get the option to adjust its properties instead of Lock Object" ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. - The contextual task bar has a Stroke chip beside the Fill chip, drawn with the paint the Stroke proxy shows (a "?" when the selected objects' strokes differ, as on the Fill chip); a click brings the Stroke proxy forward and shows the Swatches panel wherever it is docked, floating or closed, as a click on the Fill chip does for the Fill proxy. The reference app's bar has Fill and Stroke controls for changing an object's colors ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Evidence: `the_task_bar_shows_a_stroke_chip_beside_fill` and `the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere` in `crates/ui-egui/src/canvas/tests.rs`. - With anchor points selected with Direct Selection, the contextual task bar offers Remove Anchor Points, Connect (`path.join`), Cut Path, Corner and Smooth (`path.convertAnchors` with `to` set to `corner` or `smooth`), the commands of the Control bar's anchor buttons. As in Illustrator, whose bar has items that delete the selected anchors, join selected end points, split the path at the selected anchors, and make the selected anchors corner or smooth points ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Not done: Simplify, which the bar offers only while no anchors are selected, and the bar's Smooth item that adjusts a path's curvature, a command the app doesn't have (Object › Path › Smooth). - Tool flyouts tear off: dragging or clicking the tear-off bar on a flyout's right side (or releasing the long press over it) floats its group as a strip of tool buttons, moved by the same bar and put back in the toolbar by the × at its top (`window.floatTools`). While a group floats, the presses that would open its flyout raise the strip instead. Floating strips are kept with the preferences and in user workspaces. Not done: turning a strip vertical, docking it. From 5a00238a0c55bd78eea027d6fb6c2042f9650bc4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 03:26:59 -0700 Subject: [PATCH 16/70] Docs: describe the Shape Properties overview line in our own words The evidence line for the Shape Properties button quoted the reference app's overview. It now paraphrases it and keeps the citation. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cc2b987b3f..e950d73e70 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -572,7 +572,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With one image selected, the contextual task bar offers Image Trace, which traces the image at once with the Default preset (the Image Trace panel is left as it was), and Crop Image; with an Image Trace object it offers Expand, which keeps only the traced paths. This follows Illustrator's bar: for a selected image it includes Image Trace, Retype and Crop Image, and traced artwork can be expanded from it ([Contextual Task Bar announcement](https://community.adobe.com/announcements-651/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580)). Offset Path and Simplify, which don't apply to an image, aren't offered for one. Not done: Retype, which the app doesn't have. - With the Artboard tool, the contextual task bar sits under the selected artboards and offers Resize (Artboard Options for the active artboard), Duplicate (each selected artboard, in one undo step, the copies then selected), Rearrange All (with two or more artboards) and Export (Export for Screens with the selected artboards checked). This follows Illustrator's bar: while the Artboard tool is in use, it has options for resizing, duplicating and exporting artboards (the [Contextual Task Bar announcement](https://community.adobe.com/questions-652/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580); Rearrange and Export on the bar: [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/)). - The contextual task bar offers more next steps by selection (): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, and point or area type Convert To Area Type or Convert To Point Type beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`. - - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview says: "For a basic shape created with tools such as the Rectangle tool and the Star tool, you get the option to adjust its properties instead of Lock Object" ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. + - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview describes this: when a shape drawn with a shape tool (Rectangle, Star) is selected, the bar offers to change its properties where Lock Object would be ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. - The contextual task bar has a Stroke chip beside the Fill chip, drawn with the paint the Stroke proxy shows (a "?" when the selected objects' strokes differ, as on the Fill chip); a click brings the Stroke proxy forward and shows the Swatches panel wherever it is docked, floating or closed, as a click on the Fill chip does for the Fill proxy. The reference app's bar has Fill and Stroke controls for changing an object's colors ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Evidence: `the_task_bar_shows_a_stroke_chip_beside_fill` and `the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere` in `crates/ui-egui/src/canvas/tests.rs`. - With anchor points selected with Direct Selection, the contextual task bar offers Remove Anchor Points, Connect (`path.join`), Cut Path, Corner and Smooth (`path.convertAnchors` with `to` set to `corner` or `smooth`), the commands of the Control bar's anchor buttons. As in Illustrator, whose bar has items that delete the selected anchors, join selected end points, split the path at the selected anchors, and make the selected anchors corner or smooth points ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Not done: Simplify, which the bar offers only while no anchors are selected, and the bar's Smooth item that adjusts a path's curvature, a command the app doesn't have (Object › Path › Smooth). - Tool flyouts tear off: dragging or clicking the tear-off bar on a flyout's right side (or releasing the long press over it) floats its group as a strip of tool buttons, moved by the same bar and put back in the toolbar by the × at its top (`window.floatTools`). While a group floats, the presses that would open its flyout raise the strip instead. Floating strips are kept with the preferences and in user workspaces. Not done: turning a strip vertical, docking it. From b46cdc4e4ddfca13f00b45a398b1548d3e87165c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 00:37:24 +0700 Subject: [PATCH 17/70] Isolation mode: Lock, Unlock All, Hide and Show All work on the isolated art Squashed from #4849 onto main. --- crates/engine/src/cmd.rs | 28 +- crates/engine/src/cmd/edit.rs | 22 +- crates/engine/src/cmd/menucmds.rs | 71 ++- crates/engine/src/cmd/object/arrange.rs | 40 +- crates/engine/src/cmd/object/commands.rs | 18 +- crates/engine/src/tests/menucmds.rs | 482 +++++++++++++----- crates/ui-egui/src/canvas/tests.rs | 12 +- crates/ui-egui/src/menus/tests.rs | 10 +- crates/ui-egui/src/panels/properties/tests.rs | 17 +- crates/ui-egui/src/shortcuts/tests.rs | 8 +- docs/mcp.md | 23 +- docs/target-app-parity.md | 6 +- 12 files changed, 511 insertions(+), 226 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index dc047d9d65..2d9fea923f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -182,20 +182,22 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.selection.len() < 2 { Err("select at least two objects".into()) } else { Ok(()) } } -/// A document is open and it is not in isolation mode: Object › Lock's and Object › Hide's items, -/// Unlock All and Show All are off in isolation mode. Pattern editing mode and opacity mask -/// editing isolate their art too, and do not count as isolation mode here while their own layer -/// is the isolated one. An object isolated inside them counts. -pub fn outside_isolation(s: &Session) -> std::result::Result<(), String> { - let st = s.active().ok_or("no document open")?; - let editing_layer = |l| st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == l) || st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == l); - if st.isolation.is_some_and(|l| !editing_layer(l)) { Err("exit isolation mode first".into()) } else { Ok(()) } +/// The isolated group, layer or object in isolation mode. Pattern editing mode and opacity mask +/// editing isolate their own layer, which does not count here; an object isolated inside them +/// counts. +pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option { + st.isolation.filter(|l| !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l)) } -/// Objects are selected ([`has_selection`]) and the document is not in isolation mode -/// ([`outside_isolation`]). -pub fn has_selection_outside_isolation(s: &Session) -> std::result::Result<(), String> { - outside_isolation(s)?; - has_selection(s) +/// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at +/// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items. +pub fn has_selected_member(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + let Some(root) = ordinary_isolation(st) else { return has_selection(s) }; + if st.selection.objects.iter().any(|id| inside_isolation(&st.doc, root, *id)) { Ok(()) } else { Err("nothing selected".into()) } +} +/// Whether `id` lies inside the isolated object `root` (the root itself does not). +pub(crate) fn inside_isolation(d: &vectorcraft_doc::Document, root: vectorcraft_doc::NodeId, id: vectorcraft_doc::NodeId) -> bool { + id != root && d.ancestry(id).is_some_and(|a| a.contains(&root)) } pub fn can_undo(s: &Session) -> std::result::Result<(), String> { s.active().filter(|d| !d.history.undo.is_empty()).map(|_| ()).ok_or_else(|| "nothing to undo".into()) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a2cab84a89..3534d40ac5 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -566,17 +566,29 @@ pub(crate) fn selected_roots(s: &Session) -> Result> { /// rest still go to the compound path, which holds the paint. pub(crate) fn selected_roots_to_transform(s: &Session) -> Result> { let st = s.doc()?; - Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), true)) + Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_| true)) +} + +/// [`selected_roots`] for the selected objects inside the isolated object `root` +/// ([`super::inside_isolation`]): `root` itself and objects outside it are left out before the +/// objects held by another selected object are dropped. A selected path of a compound path stands +/// for its compound unless the compound is `root` or `members` is set (as in +/// [`selected_roots_to_transform`]). +pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result> { + let st = s.doc()?; + let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(); + Ok(roots_within(&st.doc, ids, |compound| members || compound == root)) } /// The top-level objects among `ids` (in paint order): compound-path members stand for their /// compound, and ids whose ancestor is also listed, and layers, are dropped. pub(crate) fn roots_of(doc: &Document, ids: Vec) -> Vec { - roots_within(doc, ids, false) + roots_within(doc, ids, |_| false) } -/// [`roots_of`]; with `members`, a compound path's member listed stays itself. -fn roots_within(doc: &Document, ids: Vec, members: bool) -> Vec { +/// [`roots_of`]; a compound path's member listed stays itself when `members` holds for the +/// compound's id. +fn roots_within(doc: &Document, ids: Vec, members: impl Fn(NodeId) -> bool) -> Vec { // Every id's place in the tree, found in one walk (a lookup per id is a walk per id). let paths = doc.index_paths(ids.iter().copied()); // A compound-path member acts as its compound (compounds are one object). @@ -586,7 +598,7 @@ fn roots_within(doc: &Document, ids: Vec, members: bool) -> Vec let path = paths.get(&id); let parent = path.and_then(|p| p.split_last()).map(|(_, up)| up).filter(|up| !up.is_empty()); match parent.and_then(|up| doc.node_at(up).map(|n| (up, n))) { - Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members => (n.id, Some(up.to_vec())), + Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members(n.id) => (n.id, Some(up.to_vec())), _ => (id, path.cloned()), } }) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 7a93ac6176..73cf96c9ba 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat}; use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform}; use super::{ - CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selection, - has_selection_outside_isolation, switch_or, + CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member, + has_selection, switch_or, }; /// Session-level (not saved) state owned by the menu commands. @@ -43,8 +43,8 @@ pub fn specs() -> Vec { "All Artwork Above", ["Object", "Lock"], None, - "{} lock objects in the same layer that are above and overlap the selection, deselecting every selected object left locked or hidden (the key object too) → {count}", - has_selection_outside_isolation, + "{} lock objects in the same layer that are above and overlap the selection, deselecting every selected object left locked or hidden (the key object too); in isolation mode, lock the selected objects and the objects above them inside the isolated object → {count}", + has_selected_member, |s, _| above(s, true) ), cmd!( @@ -52,8 +52,8 @@ pub fn specs() -> Vec { "Other Layers", ["Object", "Lock"], None, - "{} lock every layer that holds no selected object → {count}", - has_selection_outside_isolation, + "{} lock every layer that holds no selected object; in isolation mode, change nothing and return a count of 0 → {count}", + has_selected_member, |s, _| other_layers(s, true) ), cmd!( @@ -61,8 +61,8 @@ pub fn specs() -> Vec { "Unselected Artwork", ["Object", "Lock"], Some("Cmd+Alt+Shift+2"), - "{} lock unselected artwork in one undo step, including unselected members of partly selected groups, clipping groups and compound paths, and guides while Lock Guides is on; hidden art and art on locked layers stay unlocked; a selected layer's art counts as selected; in isolation, only art inside the isolated object is affected; object.unlockAll unlocks locked art document-wide → {count}", - has_selection, + "{} lock unselected artwork in one undo step, including unselected members of partly selected groups, clipping groups and compound paths, and guides while Lock Guides is on; hidden art and art on locked layers stay unlocked; a selected layer's art counts as selected; in isolation, only art inside the isolated object is affected; object.unlockAll unlocks locked art document-wide, or inside the isolated object in isolation mode → {count}", + has_selected_member, |s, _| unselected_art(s, true) ), cmd!( @@ -70,8 +70,8 @@ pub fn specs() -> Vec { "All Artwork Above", ["Object", "Hide"], None, - "{} hide objects in the same layer that are above and overlap the selection, deselecting every selected object left hidden or locked (the key object too) → {count}", - has_selection_outside_isolation, + "{} hide objects in the same layer that are above and overlap the selection, deselecting every selected object left hidden or locked (the key object too); in isolation mode, hide the selected objects and the objects above them inside the isolated object → {count}", + has_selected_member, |s, _| above(s, false) ), cmd!( @@ -79,8 +79,8 @@ pub fn specs() -> Vec { "Other Layers", ["Object", "Hide"], None, - "{} hide every layer that holds no selected object → {count}", - has_selection_outside_isolation, + "{} hide every layer that holds no selected object; in isolation mode, change nothing and return a count of 0 → {count}", + has_selected_member, |s, _| other_layers(s, false) ), cmd!( @@ -88,8 +88,8 @@ pub fn specs() -> Vec { "Unselected Artwork", ["Object", "Hide"], Some("Cmd+Alt+Shift+3"), - "{} hide, in one undo step, every object select.all takes that is not selected and holds no selected object; in a group that holds one it hides the other members one by one, and a clip group, compound path or other object that holds one stays as it is; the objects of a selected layer count as selected; while Lock Guides is on, guide paths count as selected and stay as they are; object.showAll shows them again; disabled in isolation mode → {count}", - has_selection_outside_isolation, + "{} hide, in one undo step, every object select.all takes that is not selected and holds no selected object; in a group that holds one it hides the other members one by one, and a clip group, compound path or other object that holds one stays as it is; the objects of a selected layer count as selected; while Lock Guides is on, guide paths count as selected and stay as they are; in isolation mode, only art inside the isolated object is affected; object.showAll shows them again → {count}", + has_selected_member, |s, _| unselected_art(s, false) ), cmd!( @@ -243,14 +243,21 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result { // ---------- Lock / Hide ---------- fn above(s: &mut Session, lock: bool) -> Result { - let roots = selected_roots(s)?; - let d = &s.doc()?.doc; + let st = s.doc()?; + let d = &st.doc; + let isolation = super::ordinary_isolation(st); + // In isolation mode a path of the isolated compound path is an object of its own. + let roots = match isolation { + Some(root) => super::edit::selected_roots_inside(s, root, false)?, + None => selected_roots(s)?, + }; let symbols = d.symbol_boxes(); - // `selected` holds each selected object's visual bounds, by layer, with the index there of its - // ancestor directly inside the layer. Symbol instances are measured by their art. + // `selected` holds each selected object's visual bounds, by layer (the isolated object in + // isolation mode), with the index there of its ancestor directly inside it. Symbol instances + // are measured by their art. let mut selected: BTreeMap> = BTreeMap::new(); for id in &roots { - let Some(layer) = d.layer_of(*id) else { continue }; + let Some(layer) = isolation.or_else(|| d.layer_of(*id)) else { continue }; // The selected object's ancestor directly inside the layer. let anc = d.ancestry(*id).unwrap_or_default(); let Some(pos) = anc.iter().position(|a| *a == layer) else { continue }; @@ -259,10 +266,14 @@ fn above(s: &mut Session, lock: bool) -> Result { let Some((_, idx, _)) = d.position(top) else { continue }; selected.entry(layer).or_default().push((idx, b)); } - // The loop walks up each layer once. Each object that is not selected and overlaps a selected - // object below it is locked (Lock) or hidden (Hide). + // The loop walks up each layer once, or the isolated object in isolation mode. Each object that + // is not selected and overlaps a selected object below it is locked (Lock) or hidden (Hide). In + // isolation mode the selected objects are locked or hidden too. let roots: HashSet = roots.into_iter().collect(); let mut hits: BTreeSet = BTreeSet::new(); + if isolation.is_some() { + hits.extend(roots.iter().copied()); + } for (layer, mut below) in selected { below.sort_by_key(|(idx, _)| *idx); let mut below = below.into_iter().peekable(); @@ -307,6 +318,11 @@ fn above(s: &mut Session, lock: bool) -> Result { fn other_layers(s: &mut Session, lock: bool) -> Result { let st = s.doc()?; + // In isolation mode the other layers lie outside the isolated group, layer or sublayer, so the + // document and its undo history stay as they are. + if super::ordinary_isolation(st).is_some() { + return Ok(json!({ "count": 0 })); + } let keep: Vec = st.selection.objects.iter().filter_map(|id| st.doc.ancestry(*id)).flatten().collect(); let others: Vec = st.doc.layers.iter().map(|l| l.id).filter(|l| !keep.contains(l)).collect(); let n = others.len(); @@ -370,10 +386,19 @@ fn unselected( } fn unselected_art(s: &mut Session, lock: bool) -> Result { - let roots = selected_roots_to_transform(s)?; + // In isolation mode the isolated object itself does not count as a selected object. + let iso = super::ordinary_isolation(s.doc()?); + let roots = match iso { + Some(root) => super::edit::selected_roots_inside(s, root, true)?, + None => selected_roots_to_transform(s)?, + }; let guides_locked = s.menu.guides_locked; let st = s.doc()?; - let ids = unselected(&st.doc, st.isolation, &st.selection.objects, &roots, guides_locked, lock); + let selection: Vec = match iso { + Some(root) => st.selection.objects.iter().copied().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(), + None => st.selection.objects.to_vec(), + }; + let ids = unselected(&st.doc, st.isolation, &selection, &roots, guides_locked, lock); // With nothing to lock (Lock) or hide (Hide), the document and its undo history stay as they are. if !ids.is_empty() { s.edit(if lock { "Lock" } else { "Hide" }, |d, _| { diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 325024bcb1..741475d87f 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -143,7 +143,7 @@ pub(super) fn ungroup(s: &mut Session, _: &Value) -> Result { } pub(super) fn lock(s: &mut Session, _: &Value) -> Result { - let ids = selected_roots(s)?; + let ids = selected_lock_hide_roots(s)?; // With every selected object already locked, the document and its undo history stay as they // are, and the objects are deselected. let d = &s.doc()?.doc; @@ -163,6 +163,16 @@ pub(super) fn lock(s: &mut Session, _: &Value) -> Result { ok() } +/// The selected objects ([`selected_roots`]) that Lock › Selection and Hide › Selection change: in +/// isolation mode, only those inside the isolated object, where a path of the isolated compound +/// path is an object of its own. +fn selected_lock_hide_roots(s: &Session) -> Result> { + match crate::cmd::ordinary_isolation(s.doc()?) { + Some(root) => crate::cmd::edit::selected_roots_inside(s, root, false), + None => selected_roots(s), + } +} + fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec { let mut v = vec![]; d.walk(|n| { @@ -174,14 +184,28 @@ fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec { } /// The objects that `f` picks for `object.unlockAll` and `object.showAll` (`cmd`): in the whole -/// document, or with `scope: "group"` inside the groups that hold the selected objects. A selected -/// group is the group that holds its own members, and the objects of a group inside another such -/// group are taken once. With `scope: "group"` and no selected object in a group, it returns an -/// error. +/// document, inside the isolated object in isolation mode, or with `scope: "group"` inside the +/// groups that hold the selected objects (in isolation mode, only the objects of those groups +/// that are inside the isolated object). A selected group is the group that holds its own +/// members, and the objects of a group inside another such group are taken once. With +/// `scope: "group"` and no selected object in a group, it returns an error. fn collect_flag_in_scope(s: &Session, cmd: &str, p: &Value, f: impl Fn(&Node) -> bool) -> Result> { let st = s.doc()?; let d = &st.doc; if choice(p, cmd, "scope", &["document", "group"])? != Some("group") { + if let Some(root) = crate::cmd::ordinary_isolation(st) { + let mut ids = vec![]; + if let Some(node) = d.node(root) { + for child in node.children().into_iter().flatten() { + child.walk(&mut |n| { + if !n.is_layer() && f(n) { + ids.push(n.id); + } + }); + } + } + return Ok(ids); + } return Ok(collect_flag(d, f)); } let is_group = |id: &NodeId| d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. })); @@ -204,6 +228,10 @@ fn collect_flag_in_scope(s: &Session, cmd: &str, p: &Value, f: impl Fn(&Node) -> }); } } + // In isolation mode only the objects inside the isolated object are taken. + if let Some(root) = crate::cmd::ordinary_isolation(st) { + v.retain(|id| crate::cmd::inside_isolation(d, root, *id)); + } Ok(v) } @@ -226,7 +254,7 @@ pub(super) fn unlock_all(s: &mut Session, p: &Value) -> Result { } pub(super) fn hide(s: &mut Session, _: &Value) -> Result { - let ids = selected_roots(s)?; + let ids = selected_lock_hide_roots(s)?; // With every selected object already hidden, the document and its undo history stay as they // are, and the objects are deselected. let d = &s.doc()?.doc; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index d5885ad3cf..69f464edb1 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -6,7 +6,7 @@ use super::props::set_props; use super::shape::{expand_shape, set_live_shape}; use super::transform::{move_cmd, nudge, reflect, rotate, scale, shear, transform, transform_again}; use super::{CommandSpec, cmd, has_doc, has_multi, has_selection, has_selection_or_guides}; -use crate::cmd::{has_selection_outside_isolation, outside_isolation}; +use crate::cmd::has_selected_member; pub fn specs() -> Vec { vec![ @@ -150,8 +150,8 @@ pub fn specs() -> Vec { "Selection", ["Object", "Lock"], Some("Cmd+2"), - "{ids?: [id…] (selected first; default: the selection)}", - has_selection_outside_isolation, + "{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}", + has_selected_member, lock ), cmd!( @@ -159,8 +159,8 @@ pub fn specs() -> Vec { "Unlock All", ["Object"], Some("Cmd+Alt+2"), - "{scope?: \"document\"|\"group\" (default document; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}", - outside_isolation, + "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}", + has_doc, unlock_all ), cmd!( @@ -168,8 +168,8 @@ pub fn specs() -> Vec { "Selection", ["Object", "Hide"], Some("Cmd+3"), - "{ids?: [id…] (selected first; default: the selection)}", - has_selection_outside_isolation, + "{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}", + has_selected_member, hide ), cmd!( @@ -177,8 +177,8 @@ pub fn specs() -> Vec { "Show All", ["Object"], Some("Cmd+Alt+3"), - "{scope?: \"document\"|\"group\" (default document; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}", - outside_isolation, + "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}", + has_doc, show_all ), cmd!( diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index ff11009b16..91194b2730 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -316,137 +316,347 @@ fn shown_and_locked(s: &Session, id: NodeId) -> (bool, bool) { (n.visible, n.locked) } -/// Each of `commands` is off in isolation mode: the command list reports it disabled, its error -/// names isolation mode, and so does the error of a call that gives the selection as `ids` (for a -/// command that takes them). -fn off_in_isolation(s: &mut Session, commands: &[&str]) { - let ids: Vec = selected(s).iter().map(|i| i.0).collect(); - for c in commands { - let spec = find_command(c).unwrap(); - assert_eq!(spec.info(s).disabled_reason.as_deref(), Some("exit isolation mode first"), "{c}"); - let given = cmd::params::takes_key(spec.params, "ids").then(|| json!({"ids": ids})); - for p in std::iter::once(json!({})).chain(given) { - let e = s.execute(c, &p).unwrap_err().to_string(); - assert!(e.contains("exit isolation mode first"), "{c} {p}: {e}"); - } - } -} - -/// In isolation mode, Lock › Selection and Hide › Selection are off and change nothing, in an -/// isolated group and in an isolated compound path with one of its paths selected. After Exit -/// Isolation Mode they lock and hide again. -#[test] -fn lock_and_hide_selection_are_off_in_isolation_mode() { - let mut s = session(); - let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); - let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); - sel(&mut s, &[a, b]); - let g = id_of(&s.execute("object.group", &json!({})).unwrap()); - let outer = rect(&mut s, 100.0, 100.0, 100.0, 100.0); - let hole = rect(&mut s, 120.0, 120.0, 20.0, 20.0); - sel(&mut s, &[outer, hole]); - let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); - let ids = [a, b, g, outer, hole, compound]; - let commands = ["object.lock", "object.hide"]; - for (isolated, member) in [(g, a), (compound, hole)] { - s.execute("object.isolate", &json!({"id": isolated.0})).unwrap(); - sel(&mut s, &[member]); - off_in_isolation(&mut s, &commands); - for id in ids { - assert_eq!(shown_and_locked(&s, id), (true, false), "{id:?} in isolation of {isolated:?}"); - } - assert_eq!(selected(&s), [member]); - s.execute("object.exitIsolation", &json!({})).unwrap(); - } - sel(&mut s, &[a]); - s.execute("object.lock", &json!({})).unwrap(); - sel(&mut s, &[outer]); - s.execute("object.hide", &json!({})).unwrap(); - assert_eq!(shown_and_locked(&s, a), (true, true)); - assert_eq!(shown_and_locked(&s, compound), (false, false)); -} - -/// In isolation mode, Unlock All and Show All are off: the locked and the hidden objects outside -/// and inside the isolated group stay as they are. Pattern editing mode and opacity mask editing -/// are not isolation mode for them. -#[test] -fn unlock_all_and_show_all_are_off_in_isolation_mode() { - let mut s = session(); - let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); - let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); - let c = rect(&mut s, 40.0, 0.0, 10.0, 10.0); - sel(&mut s, &[a, b, c]); - let g = id_of(&s.execute("object.group", &json!({})).unwrap()); - let locked = rect(&mut s, 100.0, 0.0, 10.0, 10.0); - let hidden = rect(&mut s, 120.0, 0.0, 10.0, 10.0); - s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap(); - s.execute("layer.setProps", &json!({"id": hidden.0, "visible": false})).unwrap(); - s.execute("layer.setProps", &json!({"id": b.0, "locked": true})).unwrap(); - s.execute("layer.setProps", &json!({"id": c.0, "visible": false})).unwrap(); - s.execute("object.isolate", &json!({"id": g.0})).unwrap(); - sel(&mut s, &[a]); - off_in_isolation(&mut s, &["object.unlockAll", "object.showAll"]); - for (id, want) in [(locked, (true, true)), (hidden, (false, false)), (b, (true, true)), (c, (false, false))] { - assert_eq!(shown_and_locked(&s, id), want, "{id:?}"); - } - s.execute("object.exitIsolation", &json!({})).unwrap(); - s.execute("object.unlockAll", &json!({})).unwrap(); - s.execute("object.showAll", &json!({})).unwrap(); - for id in [locked, hidden, b, c] { - assert_eq!(shown_and_locked(&s, id), (true, false), "{id:?}"); - } - - // Pattern editing mode: the tile's art hides and shows again. - let r = rect(&mut s, 300.0, 300.0, 10.0, 10.0); - sel(&mut s, &[r]); - s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); - let tile = selected(&s); - s.execute("object.hide", &json!({})).unwrap(); - assert!(!node(&s, tile[0]).visible, "hidden in pattern editing mode"); - s.execute("object.showAll", &json!({})).unwrap(); - assert!(node(&s, tile[0]).visible, "shown in pattern editing mode"); - // An object isolated inside pattern editing mode is isolation mode again. - s.execute("object.isolate", &json!({"id": tile[0].0})).unwrap(); - sel(&mut s, &[tile[0]]); - off_in_isolation(&mut s, &["object.unlockAll", "object.showAll"]); - s.execute("object.pattern.cancel", &json!({})).unwrap(); - - // Opacity mask editing: the mask's art locks and unlocks again. - let obj = rect(&mut s, 0.0, 300.0, 200.0, 200.0); - let m = rect(&mut s, 0.0, 300.0, 100.0, 200.0); - sel(&mut s, &[obj, m]); - s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); - s.execute("transparency.editOpacityMask", &json!({})).unwrap(); - let mask = selected(&s); - s.execute("object.lock", &json!({})).unwrap(); - assert!(node(&s, mask[0]).locked, "locked in opacity mask editing"); - s.execute("object.unlockAll", &json!({})).unwrap(); - assert!(!node(&s, mask[0]).locked, "unlocked in opacity mask editing"); -} - -/// In isolation mode, Lock › All Artwork Above, Lock › Other Layers, Hide › All Artwork Above and -/// Hide › Other Layers are off: the art above and the other layer stay as they are. -#[test] -fn lock_and_hide_above_and_other_layers_are_off_in_isolation_mode() { +/// Check command enablement, targets, selection and history inside an isolated group. +fn check_group_isolation_command(command: &str, lock: bool, a_changed: bool, b_changed: bool) { let mut s = session(); let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); - let b = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 20.0, 20.0, 100.0, 100.0); sel(&mut s, &[a, b]); let g = id_of(&s.execute("object.group", &json!({})).unwrap()); - let over = rect(&mut s, 50.0, 50.0, 100.0, 100.0); + let out = rect(&mut s, 30.0, 30.0, 100.0, 100.0); let l2 = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[out]); + assert!(!find_command(command).unwrap().info(&s).enabled, "{command}: outside selection"); + sel(&mut s, &[a]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + let before = history(&s).0; + s.execute(command, &json!({})).unwrap(); + let changed = |s: &Session, id| if lock { node(s, id).locked } else { !node(s, id).visible }; + assert_eq!(changed(&s, a), a_changed, "{command}: A"); + assert_eq!(changed(&s, b), b_changed, "{command}: B"); + assert!(!changed(&s, out) && !changed(&s, p) && !changed(&s, l2), "{command}: outside"); + assert_eq!(selected(&s), if a_changed { vec![] } else { vec![a] }, "{command}: selection"); + let steps = usize::from(a_changed || b_changed); + assert_eq!(history(&s).0, before + steps, "{command}: history"); + if steps != 0 { + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!changed(&s, a) && !changed(&s, b), "{command}: undo"); + assert_eq!(selected(&s), [a], "{command}: undo selection"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((changed(&s, a), changed(&s, b)), (a_changed, b_changed), "{command}: redo"); + assert_eq!(selected(&s), if a_changed { vec![] } else { vec![a] }, "{command}: redo selection"); + } + if !a_changed && b_changed { + let restore = if lock { "object.unlockAll" } else { "object.showAll" }; + let params = if lock { json!({"id": out.0, "locked": true}) } else { json!({"id": out.0, "visible": false}) }; + s.execute("layer.setProps", ¶ms).unwrap(); + assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 1})); + assert!(!changed(&s, b) && changed(&s, out), "{command}: scoped restore"); + } +} + +/// Generate the focused group isolation checks for each Lock and Hide command. +macro_rules! group_isolation_command_test { + ($name:ident, $command:literal, $lock:literal, $a:literal, $b:literal) => { + #[doc = concat!("Checks ", $command, " targets and history in group isolation.")] + #[test] + fn $name() { + check_group_isolation_command($command, $lock, $a, $b); + } + }; +} + +group_isolation_command_test!(lock_selection_in_group_isolation, "object.lock", true, true, false); +group_isolation_command_test!(lock_above_in_group_isolation, "object.lock.above", true, true, true); +group_isolation_command_test!(lock_other_layers_in_group_isolation, "object.lock.otherLayers", true, false, false); +group_isolation_command_test!(lock_unselected_in_group_isolation, "object.lock.unselected", true, false, true); +group_isolation_command_test!(hide_selection_in_group_isolation, "object.hide", false, true, false); +group_isolation_command_test!(hide_above_in_group_isolation, "object.hide.above", false, true, true); +group_isolation_command_test!(hide_other_layers_in_group_isolation, "object.hide.otherLayers", false, false, false); +group_isolation_command_test!(hide_unselected_in_group_isolation, "object.hide.unselected", false, false, true); + +/// Lock › Selection, Hide › Selection and All Artwork Above change only the selected path inside +/// an isolated compound path, with the other path below it. +#[test] +fn lock_and_hide_selection_in_isolated_compound_path() { + for command in ["object.lock", "object.hide", "object.lock.above", "object.hide.above"] { + let mut s = session(); + let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let hole = rect(&mut s, 20.0, 20.0, 20.0, 20.0); + sel(&mut s, &[outer, hole]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let outside = rect(&mut s, 150.0, 0.0, 20.0, 20.0); + s.execute("object.isolate", &json!({"id": compound.0})).unwrap(); + sel(&mut s, &[hole]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + let before = history(&s).0; + let want = if command.ends_with(".above") { json!({"count": 1}) } else { serde_json::Value::Null }; + assert_eq!(s.execute(command, &json!({})).unwrap(), want, "{command}"); + assert_eq!(history(&s).0, before + 1, "{command}"); + assert_eq!(selected(&s), [], "{command}"); + let expected = if command.starts_with("object.lock") { (true, true) } else { (false, false) }; + assert_eq!(shown_and_locked(&s, hole), expected, "{command}"); + for id in [outer, compound, outside] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + } +} + +/// Lock › Selection, Hide › Selection and All Artwork Above change the whole compound path when +/// one of its paths is selected inside an isolated group that holds it. +#[test] +fn lock_and_hide_a_compound_path_member_in_an_isolated_group() { + for command in ["object.lock", "object.hide", "object.lock.above", "object.hide.above"] { + let mut s = session(); + let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let hole = rect(&mut s, 20.0, 20.0, 20.0, 20.0); + sel(&mut s, &[outer, hole]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let b = rect(&mut s, 150.0, 0.0, 20.0, 20.0); + sel(&mut s, &[compound, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[hole]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + let before = history(&s).0; + s.execute(command, &json!({})).unwrap(); + assert_eq!(history(&s).0, before + 1, "{command}"); + assert_eq!(selected(&s), [], "{command}"); + let expected = if command.starts_with("object.lock") { (true, true) } else { (false, false) }; + assert_eq!(shown_and_locked(&s, compound), expected, "{command}"); + for id in [outer, hole, b, g] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + } +} + +/// Check that restore commands affect only isolated art and preserve undo and selection. +fn check_restore_in_group_isolation(change: &str, restore: &str, lock: bool) { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 20.0, 20.0, 100.0, 100.0); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + let out = rect(&mut s, 30.0, 30.0, 100.0, 100.0); + let l2 = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + for id in [out, p] { + let params = if lock { json!({"id": id.0, "locked": true}) } else { json!({"id": id.0, "visible": false}) }; + s.execute("layer.setProps", ¶ms).unwrap(); + } s.execute("object.isolate", &json!({"id": g.0})).unwrap(); sel(&mut s, &[a]); - off_in_isolation(&mut s, &["object.lock.above", "object.lock.otherLayers", "object.hide.above", "object.hide.otherLayers"]); - for id in [a, b, g, over, l2] { - assert_eq!(shown_and_locked(&s, id), (true, false), "{id:?}"); + s.execute(change, &json!({})).unwrap(); + assert!(selected(&s).is_empty()); + assert!(find_command(restore).unwrap().info(&s).enabled); + let before = history(&s).0; + assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 1})); + assert_eq!(history(&s).0, before + 1); + assert_eq!(selected(&s), [a]); + let changed = |s: &Session, id| if lock { node(s, id).locked } else { !node(s, id).visible }; + assert!(!changed(&s, a) && !changed(&s, b)); + assert!(changed(&s, out) && changed(&s, p)); + let no_op = history(&s).0; + assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 0})); + assert_eq!(history(&s).0, no_op); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(changed(&s, a)); + assert!(selected(&s).is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(!changed(&s, a) && changed(&s, out) && changed(&s, p) && !changed(&s, l2)); + assert_eq!(selected(&s), [a]); +} + +/// Unlock All restores locked art inside the group after Lock Selection clears selection. +#[test] +fn unlock_all_in_group_isolation_without_selection() { + check_restore_in_group_isolation("object.lock", "object.unlockAll", true); +} + +/// Show All restores hidden art inside the group after Hide Selection clears selection. +#[test] +fn show_all_in_group_isolation_without_selection() { + check_restore_in_group_isolation("object.hide", "object.showAll", false); +} + +/// With `scope: "group"`, Unlock All and Show All in an isolated compound path inside a group +/// change only the compound path's paths, not the group's other objects or a group outside it +/// that holds a selected object. +#[test] +fn group_scope_restore_stays_inside_isolated_compound_path() { + for (restore, lock) in [("object.unlockAll", true), ("object.showAll", false)] { + let mut s = session(); + let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let hole = rect(&mut s, 20.0, 20.0, 20.0, 20.0); + sel(&mut s, &[outer, hole]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let sibling = rect(&mut s, 150.0, 0.0, 20.0, 20.0); + sel(&mut s, &[compound, sibling]); + s.execute("object.group", &json!({})).unwrap(); + let away = rect(&mut s, 300.0, 0.0, 20.0, 20.0); + let away_mate = rect(&mut s, 350.0, 0.0, 20.0, 20.0); + sel(&mut s, &[away, away_mate]); + s.execute("object.group", &json!({})).unwrap(); + for id in [hole, sibling, away_mate] { + let params = if lock { json!({"id": id.0, "locked": true}) } else { json!({"id": id.0, "visible": false}) }; + s.execute("layer.setProps", ¶ms).unwrap(); + } + s.execute("object.isolate", &json!({"id": compound.0})).unwrap(); + let changed = |s: &Session, id| if lock { node(s, id).locked } else { !node(s, id).visible }; + sel(&mut s, &[away]); + assert_eq!(s.execute(restore, &json!({"scope": "group"})).unwrap(), json!({"count": 0}), "{restore}: outside selection"); + assert!(changed(&s, away_mate) && changed(&s, hole) && changed(&s, sibling), "{restore}: outside selection"); + sel(&mut s, &[outer]); + assert_eq!(s.execute(restore, &json!({"scope": "group"})).unwrap(), json!({"count": 1}), "{restore}"); + assert!(!changed(&s, hole), "{restore}: hole"); + assert!(changed(&s, sibling) && changed(&s, away_mate), "{restore}: outside"); + assert_eq!(selected(&s), [hole], "{restore}: selection"); + } +} + +/// Lock › Selection, Hide › Selection and All Artwork Above, with the isolated group and one of +/// its members both selected, change the member. +#[test] +fn lock_and_hide_with_the_isolated_group_selected_change_its_member() { + for command in ["object.lock", "object.hide", "object.lock.above", "object.hide.above"] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[g, a]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + let before = history(&s).0; + let want = if command.ends_with(".above") { json!({"count": 1}) } else { serde_json::Value::Null }; + assert_eq!(s.execute(command, &json!({})).unwrap(), want, "{command}"); + assert_eq!(history(&s).0, before + 1, "{command}"); + let expected = if command.starts_with("object.lock") { (true, true) } else { (false, false) }; + assert_eq!(shown_and_locked(&s, a), expected, "{command}: A"); + for id in [b, g] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + } +} + +/// Lock and Hide Unselected with the isolated group and one of its members selected change only its other members. +#[test] +fn lock_and_hide_unselected_with_the_isolated_group_selected_keep_its_member() { + for command in ["object.lock.unselected", "object.hide.unselected"] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[g, a]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 1}), "{command}"); + let changed = if command == "object.lock.unselected" { (true, true) } else { (false, false) }; + assert_eq!(shown_and_locked(&s, b), changed, "{command}: B"); + for id in [a, g] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + } +} + +/// Lock and Hide Unselected with the isolated layer and one of its objects selected change the layer's other objects, +/// and a selected sublayer inside the isolated layer keeps its art. +#[test] +fn lock_and_hide_unselected_with_the_isolated_layer_selected_keep_its_object() { + for command in ["object.lock.unselected", "object.hide.unselected"] { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id; + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + let sub = id_of(&s.execute("layer.newSublayer", &json!({"parent": layer.0})).unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let c = rect(&mut s, 400.0, 0.0, 100.0, 100.0); + s.execute("object.isolate", &json!({"id": layer.0})).unwrap(); + let changed = if command == "object.lock.unselected" { (true, true) } else { (false, false) }; + sel(&mut s, &[layer, a]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 2}), "{command}"); + for id in [b, c] { + assert_eq!(shown_and_locked(&s, id), changed, "{command}: {id:?}"); + } + for id in [a, sub, layer] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + sel(&mut s, &[layer, sub]); + assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 2}), "{command}: sublayer"); + for id in [a, b] { + assert_eq!(shown_and_locked(&s, id), changed, "{command}: sublayer, {id:?}"); + } + for id in [c, sub, layer] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: sublayer, {id:?}"); + } + } +} + +/// Pattern editing keeps Lock Selection and Unlock All available for its tile art. +#[test] +fn pattern_editing_keeps_lock_and_unlock_available() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[a]); + s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); + let tile = selected(&s)[0]; + assert!(find_command("object.lock").unwrap().info(&s).enabled); + s.execute("object.lock", &json!({})).unwrap(); + assert!(node(&s, tile).locked); + assert!(find_command("object.unlockAll").unwrap().info(&s).enabled); + s.execute("object.unlockAll", &json!({})).unwrap(); + assert!(!node(&s, tile).locked); + assert_eq!(selected(&s), [tile]); +} + +/// Opacity mask editing lets Lock and Hide Selection change mask art and restores it with Unlock All and Show All. +#[test] +fn opacity_mask_editing_keeps_lock_hide_and_restore_available() { + let mut s = session(); + let artwork = rect(&mut s, 0.0, 0.0, 200.0, 200.0); + let mask_source = rect(&mut s, 0.0, 0.0, 100.0, 200.0); + sel(&mut s, &[artwork, mask_source]); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("transparency.editOpacityMask", &json!({})).unwrap(); + let mask = selected(&s)[0]; + for (change, restore) in [("object.lock", "object.unlockAll"), ("object.hide", "object.showAll")] { + assert!(find_command(change).unwrap().info(&s).enabled, "{change}"); + s.execute(change, &json!({})).unwrap(); + assert!(selected(&s).is_empty(), "{change}"); + assert_eq!(shown_and_locked(&s, mask), if change == "object.lock" { (true, true) } else { (false, false) }); + assert!(find_command(restore).unwrap().info(&s).enabled, "{restore}"); + assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 1}), "{restore}"); + assert_eq!(shown_and_locked(&s, mask), (true, false), "{restore}"); + assert_eq!(selected(&s), [mask], "{restore}"); + } +} + +/// Other Layers changes nothing in an isolated layer or sublayer. +#[test] +fn other_layers_has_no_target_in_isolated_layers_or_sublayers() { + for sublayer in [false, true] { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id; + let root = if sublayer { id_of(&s.execute("layer.newSublayer", &json!({"parent": layer.0})).unwrap()) } else { layer }; + s.execute("layer.setCurrent", &json!({"id": root.0})).unwrap(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let other = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap()); + s.execute("object.isolate", &json!({"id": root.0})).unwrap(); + sel(&mut s, &[a]); + for command in ["object.lock.otherLayers", "object.hide.otherLayers"] { + assert!(find_command(command).unwrap().info(&s).enabled); + let before = history(&s).0; + assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 0})); + assert_eq!(history(&s).0, before); + assert_eq!(selected(&s), [a]); + assert_eq!(shown_and_locked(&s, other), (true, false)); + } } - s.execute("object.exitIsolation", &json!({})).unwrap(); - sel(&mut s, &[g]); - assert_eq!(s.execute("object.lock.above", &json!({})).unwrap(), json!({"count": 1})); - s.execute("object.hide.otherLayers", &json!({})).unwrap(); - assert_eq!(shown_and_locked(&s, over), (true, true)); - assert_eq!(shown_and_locked(&s, l2), (false, false)); } /// How many steps there are to undo and to redo, and whether the document has unsaved changes. @@ -580,12 +790,10 @@ fn hide_unselected_artwork_leaves_the_art_on_a_locked_artboard() { assert_eq!([a, b, on_locked].map(|id| node(&s, id).visible), [true, false, true]); } -/// In isolation mode Hide › Unselected Artwork is disabled: the menu item is off, and the command returns an error that -/// names isolation mode and changes nothing. While Lock Guides is on it leaves the guides as they are. With nothing -/// left to hide it records no undo step and returns a count of 0. A compound path that holds a selected path stays as -/// it is. +/// Hide Unselected affects only isolated art, keeps locked guides, records no step for a no-op, and +/// preserves a compound path that holds the selected path. #[test] -fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode() { +fn hide_unselected_artwork_keeps_locked_guides_and_scopes_isolation() { let mut s = session(); let guide = rect(&mut s, 0.0, 0.0, 10.0, 10.0); sel(&mut s, &[guide]); @@ -600,17 +808,15 @@ fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode let shown = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).visible).collect::>(); s.execute("object.isolate", &json!({"id": g.0})).unwrap(); select_with_a_step_to_redo(&mut s, &[m]); - let before = history(&s); - let info = find_command("object.hide.unselected").unwrap().info(&s); - assert!(!info.enabled && info.disabled_reason.as_deref() == Some("exit isolation mode first"), "{info:?}"); - let e = s.execute("object.hide.unselected", &json!({})).unwrap_err(); - assert!(matches!(e, EngineError::Disabled(..)) && e.to_string().contains("isolation mode"), "{e}"); - assert_eq!(shown(&s, &[m, n, out, guide]), [true; 4]); - assert_eq!((history(&s), selected(&s)), (before, vec![m])); + let before = history(&s).0; + assert!(find_command("object.hide.unselected").unwrap().info(&s).enabled); + assert_eq!(hide(&mut s), json!({"count": 1})); + assert_eq!(history(&s).0, before + 1); + assert_eq!(shown(&s, &[m, n, out, guide]), [true, false, true, true]); + assert_eq!(selected(&s), [m]); s.execute("object.exitIsolation", &json!({})).unwrap(); sel(&mut s, &[m]); - assert!(find_command("object.hide.unselected").unwrap().info(&s).enabled); - assert_eq!(hide(&mut s), json!({"count": 2})); + assert_eq!(hide(&mut s), json!({"count": 1})); assert_eq!(shown(&s, &[n, out, guide]), [false, false, true]); select_with_a_step_to_redo(&mut s, &[m]); let before = history(&s); @@ -621,7 +827,7 @@ fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode sel(&mut s, &[m]); assert_eq!(hide(&mut s), json!({"count": 1})); assert_eq!(shown(&s, &[guide]), [false]); - // A compound path that holds the selected path stays as it is with its paths. + // The compound path and its paths stay visible when one path is selected. let outer = rect(&mut s, 0.0, 200.0, 100.0, 100.0); let hole = rect(&mut s, 40.0, 240.0, 20.0, 20.0); sel(&mut s, &[outer, hole]); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 17b05d72ee..b323306af7 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6971,10 +6971,10 @@ fn the_task_bar_recolors_coloured_art() { assert!(app.ui.dialog.is_none(), "no Recolor button without colours"); } -/// The Contextual Task Bar's Lock button is off in isolation mode, as Object › Lock › Selection -/// is: a click locks nothing and shows no error. Outside isolation mode it locks the selection. +/// The Contextual Task Bar's Lock button locks the selected member in isolation mode and the +/// selected group outside isolation mode. #[test] -fn the_task_bar_lock_button_is_off_in_isolation_mode() { +fn the_task_bar_lock_button_locks_selected_art_in_isolation_mode() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); // Plain paths: a basic shape shows its properties in Lock's place. @@ -6983,6 +6983,9 @@ fn the_task_bar_lock_button_is_off_in_isolation_mode() { let a = app.session.execute("path.create", &square(150.0)).unwrap()["id"].clone(); let b = app.session.execute("path.create", &square(210.0)).unwrap()["id"].clone(); app.session.execute("select.set", &json!({"ids": [a.clone(), b]})).unwrap(); + let a = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); + let b = app.session.execute("shape.rectangle", &json!({"x": 210, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [a.clone(), b.clone()]})).unwrap(); let g = app.session.execute("object.group", &json!({})).unwrap()["id"].clone(); app.select_tool("selection"); let ctx = egui::Context::default(); @@ -7003,7 +7006,8 @@ fn the_task_bar_lock_button_is_off_in_isolation_mode() { app.session.execute("object.isolate", &json!({"id": g.clone()})).unwrap(); app.session.execute("select.set", &json!({"ids": [a.clone()]})).unwrap(); click_lock(&mut app); - assert!(!locked(&app, &a), "nothing is locked in isolation mode"); + assert!(locked(&app, &a), "the selected member is locked in isolation mode"); + assert!(!locked(&app, &b), "the other member stays unlocked"); assert_eq!(app.ui.status, "", "no error"); app.session.execute("object.exitIsolation", &json!({})).unwrap(); app.session.execute("select.set", &json!({"ids": [g.clone()]})).unwrap(); diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index b0ee269ad3..17a8864c10 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -669,10 +669,9 @@ fn expand_appearance_is_an_object_menu_item_only() { assert_eq!(paths, [vec!["Object".to_string()]]); } -/// In isolation mode, every item of Object › Lock and Object › Hide, Unlock All and Show All are -/// greyed out, while Group stays on. After Exit Isolation Mode they are on again. +/// Isolation keeps the Lock and Hide actions available for selected members. #[test] -fn lock_and_hide_menus_are_greyed_out_in_isolation_mode() { +fn lock_and_hide_menus_are_enabled_in_isolation_mode() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({})).unwrap(); let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].clone(); @@ -715,8 +714,11 @@ fn lock_and_hide_menus_are_greyed_out_in_isolation_mode() { }; app.run("object.isolate", json!({"id": g.clone()})).unwrap(); app.run("select.set", json!({"ids": [b]})).unwrap(); - assert_eq!(shown(&app), [false, false, false, false, false, false, false, false, false, true], "in isolation mode"); + assert_eq!(shown(&app), [true; 10], "in isolation mode"); assert!(lock_unselected(&app), "shortcut command remains enabled in isolation"); + assert!(crate::menus::enabled(&app, "object.hide.unselected"), "Hide Unselected remains enabled in isolation"); + let chord = crate::shortcut_editor::default_of("object.hide.unselected").expect("default Hide Unselected shortcut"); + assert_eq!(crate::shortcut_editor::normalize(chord), crate::shortcut_editor::normalize("Cmd+Alt+Shift+3")); app.run("object.exitIsolation", json!({})).unwrap(); app.run("select.set", json!({"ids": [g]})).unwrap(); assert_eq!(shown(&app), [true; 10], "after Exit Isolation Mode"); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 0bd879a318..49acb3e8af 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1286,25 +1286,28 @@ fn blend_options_is_a_quick_action_for_one_blend() { assert!(!shows(&tall(&mut app, &ctx, vec![]), "Blend Options"), "a rectangle"); } -/// Quick Actions have no Lock in isolation mode, where Object › Lock › Selection is off. Outside -/// isolation mode Lock is there and locks the selection. +/// Quick Actions offer Lock for a selected member in isolation and for a selected group outside it. #[test] -fn lock_is_a_quick_action_outside_isolation_mode_only() { +fn lock_is_a_quick_action_in_and_outside_isolation_mode() { let mut app = new_app(); let (a, b) = (rect(&mut app, 20.0, 20.0, 40.0, 40.0), rect(&mut app, 200.0, 20.0, 40.0, 40.0)); app.run("select.set", json!({"ids": [a.clone(), b]})).unwrap(); let g = app.run("object.group", json!({})).unwrap()["id"].clone(); app.run("object.isolate", json!({"id": g.clone()})).unwrap(); - app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("select.set", json!({"ids": [a.clone()]})).unwrap(); let ctx = egui::Context::default(); let texts = tall(&mut app, &ctx, vec![]); - assert!(shows(&texts, "Offset Path") && !shows(&texts, "Lock"), "no Lock in isolation mode: {texts:?}"); + assert!(shows(&texts, "Offset Path") && shows(&texts, "Lock"), "Lock in isolation mode: {texts:?}"); + press(&mut app, &ctx, text_at(&texts, "Lock").center()); + let locked = |app: &VectorcraftApp, id: &serde_json::Value| { + app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().locked + }; + assert!(locked(&app, &a)); app.run("object.exitIsolation", json!({})).unwrap(); app.run("select.set", json!({"ids": [g.clone()]})).unwrap(); let texts = tall(&mut app, &ctx, vec![]); press(&mut app, &ctx, text_at(&texts, "Lock").center()); - let locked = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(g.as_u64().unwrap())).unwrap().locked; - assert!(locked, "Lock locks the group"); + assert!(locked(&app, &g), "Lock locks the group"); } /// A Live Paint group selected with a path has Merge Live Paint in Quick Actions, which adds diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 38365f5ed1..ad71fb3977 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -264,7 +264,7 @@ fn cmd_shift_o_creates_outlines() { /// Cmd+Alt+Shift+3 is Object › Hide › Unselected Artwork: it hides the object that is not /// selected. Cmd+Alt+3 still shows all, and Cmd+3 still hides the selection. In isolation mode -/// the item is disabled. +/// the shortcut hides unselected members of the isolated group. #[test] fn cmd_alt_shift_3_hides_unselected_artwork() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -285,15 +285,15 @@ fn cmd_alt_shift_3_hides_unselected_artwork() { app.session.execute("select.set", &json!({"ids": [a.0]})).unwrap(); frame(&mut app, vec![three(Modifiers::COMMAND)]); assert_eq!(shown(&app), [false, true], "Cmd+3 hides the selection"); - // In isolation mode the menu item is off, and the shortcut hides nothing. + // In isolation mode the shortcut hides only the group's unselected member. app.session.execute("object.showAll", &json!({})).unwrap(); app.session.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); let g = app.session.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); app.session.execute("object.isolate", &json!({"id": g})).unwrap(); app.session.execute("select.set", &json!({"ids": [a.0]})).unwrap(); - assert!(!crate::menus::enabled(&app, "object.hide.unselected")); + assert!(crate::menus::enabled(&app, "object.hide.unselected")); frame(&mut app, vec![three(Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT)]); - assert_eq!(shown(&app), [true, true], "nothing is hidden in isolation mode"); + assert_eq!(shown(&app), [true, false], "the unselected member is hidden in isolation mode"); } /// Cmd+Alt+Shift+J opens Average & Join's dialog, Points: Corner the first time. Cancel changes diff --git a/docs/mcp.md b/docs/mcp.md index d4898b5170..6f342c98cd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1380,7 +1380,8 @@ them again with the key object. When the call changes nothing, it records no und Other `object.setProps` calls leave the selection unchanged. `object.unlockAll` and `object.showAll` unlock or show every locked or hidden object in the document and select -them → `{count}`. With `scope: "group"` they take only the objects inside the groups that hold the selected objects: +them → `{count}`. In isolation mode they take only the objects inside the isolated object. With `scope: "group"` they +take only the objects inside the groups that hold the selected objects: for each selected object, the group nearest above it, or the object itself when it is a group. The objects of a group inside another such group are counted once. With no selected object in a group, the call returns the error "nothing selected is in a group" and changes nothing. `scope: "document"` is the default, and any other value is @@ -1397,16 +1398,15 @@ object that `select.all` takes and that is neither selected nor holds a selected group that holds a selected object it hides the group's other members one by one; a clip group, a compound path or another object that holds a selected object stays as it is with its members. The objects of a selected layer count as selected. While Lock Guides is on, the guide paths count as selected and stay as they are. The selection stays as it is, and `object.showAll` shows the objects again. With nothing to -hide it records no undo step. In isolation mode the menu item is disabled, and the command returns the error "exit -isolation mode first" and changes nothing. +hide it records no undo step. In isolation mode it hides only unselected objects inside the isolated object. `object.lock.unselected` (Cmd+Alt+Shift+2; shortcut and command, with no Object › Lock menu item) locks unselected artwork in one undo step and returns `{count}`. In a partly selected group, clipping group, or compound path, it locks the unselected members and leaves the container and selected members unlocked. It includes unselected guides even while Lock Guides is on. Hidden art and art on locked layers stay individually unlocked; a selected layer's artwork counts as selected. In ordinary isolation mode it locks only unselected art inside the isolated object. The selection -stays as it is. `object.unlockAll` unlocks and selects all locked artwork in the document, including art locked before -this command. With nothing to lock it records no undo step. +stays as it is. `object.unlockAll` unlocks and selects all locked artwork in the document, or inside the isolated +object in isolation mode, including art locked before this command. With nothing to lock it records no undo step. These Select menu commands select only the objects that `select.all` selects and the objects inside them: every `select.same.*` and `select.object.*` command except `select.object.slices`, `select.nextAbove`, `select.nextBelow` @@ -2334,11 +2334,14 @@ and `layerRows`, the rows highlighted in the panel. opens no rows for it and scrolls as with the option off. A change made with the panel's own rows, buttons or menu is not located, and a change made during a drag is located when the drag ends. A document opens with only its top-level layers open; the open rows are saved in the native file and reopen that way. -- **Lock and Hide in isolation mode**: in isolation mode, Object › Lock's and Object › Hide's items (`object.lock`, - `object.lock.above`, `object.lock.otherLayers`, `object.hide`, `object.hide.above`, `object.hide.otherLayers`), - `object.unlockAll` and `object.showAll` are off, and a call returns the error "command `object.hide` is not - available right now: exit isolation mode first", with the command's own id. Pattern editing mode and opacity mask - editing do not count as isolation mode for these commands. +- **Lock and Hide in isolation mode**: Object › Lock's and Object › Hide's items (`object.lock`, `object.lock.above`, + `object.lock.otherLayers`, `object.lock.unselected`, `object.hide`, `object.hide.above`, `object.hide.otherLayers`, + `object.hide.unselected`) are on while an object inside the isolated object is selected, and they change only objects + inside it. All Artwork Above locks or hides the selected objects as well as the objects above them that overlap them. + Other Layers changes nothing in an isolated group, layer or sublayer, returns a count of 0 and records no undo step. + `object.unlockAll` and `object.showAll` are on with nothing selected, and they unlock or show and select only the + objects inside the isolated object. Pattern editing mode and opacity mask editing do not count as isolation mode for + these commands. - **Search and filter** (control channel and the app's MCP): the Search All field keeps the rows whose names hold the text typed, and `ui.layersFilter {objects?, layers?}` sets the choices of the Filter button beside it. `objects` (By Object) takes `paths` (paths and compound paths), `shapes` (live rectangles, ellipses, polygons and lines), `text`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e950d73e70..05985f9f18 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -986,9 +986,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Colour, type and file workflows:** Recolor Artwork (dialog with harmonies), Edit Colors, Find & Replace, Change Case, Smart Punctuation, Guides, Lock/Hide Above, Transform Each, Rasterize. The Libraries panel holds gradients and patterns: its + button adds the selection's fill or stroke gradient or pattern, a gradient or pattern swatch dragged from the Swatches panel is added, and a click paints the selection through the active Fill/Stroke proxy, a pattern bringing its definition and swatch into the document. Object › Lock › All Artwork Above and Object › Hide › All Artwork Above deselect the selected objects they lock or hide, the key object included. - Object › Hide › Unselected Artwork (Cmd/Ctrl+Alt+Shift+3, `object.hide.unselected`) hides, in one undo step, every object Select All takes that is not selected and holds no selected object; the members of a group that holds a selected object are hidden one by one, and Object › Show All shows them again. It is disabled in isolation mode. Public references: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Hide unselected artwork"; [How to lock, hide, and delete objects in Illustrator](https://web.archive.org/web/20220303070637/https://helpx.adobe.com/illustrator/using/locking-hiding-deleting-objects.html), which says the Show All and Hide menus are unavailable in isolation mode. - Cmd/Ctrl+Alt+Shift+2 (`object.lock.unselected`) locks unselected artwork in one undo step and has no Object › Lock menu item. It locks unselected members of partly selected groups, clipping groups and compound paths, and unselected guides while Lock Guides is on. In ordinary isolation mode it locks only unselected art inside the isolated object. Object › Unlock All unlocks all locked art in the document. The [public shortcut page](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) calls the action "Lock all deselected artwork". - In isolation mode, the visible items of Object › Lock and Object › Hide, Unlock All and Show All are greyed out ([lock, hide, and delete objects](https://web.archive.org/web/20220303070637/https://helpx.adobe.com/illustrator/using/locking-hiding-deleting-objects.html)); the shortcut-only `object.lock.unselected` command remains enabled with a selection. The Contextual Task Bar's Lock button is greyed out too, the Properties panel's Quick Actions have no Lock, and the other Lock and Hide commands return an error. Pattern editing mode and opacity mask editing do not count as isolation mode for them. + Object › Hide › Unselected Artwork (Cmd/Ctrl+Alt+Shift+3, `object.hide.unselected`) hides, in one undo step, every object Select All takes that is not selected and holds no selected object; the members of a group that holds a selected object are hidden one by one, and Object › Show All shows them again. In isolation mode it hides only unselected objects inside the isolated object. Public reference: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Hide unselected artwork". + Cmd/Ctrl+Alt+Shift+2 (`object.lock.unselected`) locks unselected artwork in one undo step and has no Object › Lock menu item. It locks unselected members of partly selected groups, clipping groups and compound paths, and unselected guides while Lock Guides is on. In ordinary isolation mode it locks only unselected art inside the isolated object. Object › Unlock All unlocks all locked art in the document, or inside the isolated object in isolation mode. The [public shortcut page](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) calls the action "Lock all deselected artwork". + In isolation mode, the items of Object › Lock and Object › Hide are on while an object inside the isolated object is selected, and they change only objects inside it: All Artwork Above locks or hides the selected objects and the objects above them that overlap them, and Other Layers changes nothing in an isolated group, layer or sublayer. Unlock All and Show All are on with nothing selected and unlock or show and select only the objects inside the isolated object. The Contextual Task Bar's Lock button and the Properties panel's Quick Actions Lock lock the selected object. Pattern editing mode and opacity mask editing do not count as isolation mode for them. Liquify (its brush Width, Height and Angle, Intensity, Detail, Simplify, Twirl Rate, Complexity, Horizontal and Vertical), Puppet Warp (its Expand and each pin's angle), Transform in Perspective (its depth), Nudge in Perspective (its direction) and Move Plane (its location or distance) refuse a value other than a number or null, such as "40", Draw in Perspective refuses a click point that is not two numbers, and Width Profile refuses a point that is not three numbers; each leaves the document and its undo history as they were. Object › Lock › All Artwork Above and Object › Hide › All Artwork Above go through each top-level layer once, checking each object that is not selected against the selected objects below it: with 100 tiles selected under 25,000 rectangles, Lock took 6.4 s and now takes under 0.1 s, and with all of 5,001 objects selected it took 8.8 s and now takes under 0.1 s. Object › Unlock All and Object › Show All clicked in the in-window menu bar with Shift+Alt (Shift+Option) held unlock or show only the objects inside the groups that hold the selected objects ([lock, hide, and delete objects](https://web.archive.org/web/20230623025912/https://helpx.adobe.com/illustrator/using/locking-hiding-deleting-objects.html)); `object.unlockAll` and `object.showAll` take `scope: "group"` for it. From 9badc6bae7bc1dd483c7971b48d4305108eb09af Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sun, 1 Nov 2026 01:21:53 +0700 Subject: [PATCH 18/70] i18n: one row per catalog entry after #4860 --- crates/ui-egui/src/i18n/nl.tsv | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 01d80c460f..7fb221d3ed 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2858,7 +2858,6 @@ theme Appearance Vormgeving Yes Ja No Nee Duplicate Brush Kwast dupliceren - Duplicate Brush Penseel dupliceren Duplicate Symbol Symbool dupliceren Edit Symbol Symbool bewerken Expand Brush Strokes Penseelstreken omzetten From f1a6a9ff67f7b34bab378b351a6d504380efa4d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 03:34:44 -0700 Subject: [PATCH 19/70] Contextual Task Bar: the Shape Properties popup stays open for its Corner dropdown Opening a polygon's Corner dropdown closed the Shape Properties popup, so no corner type could be picked from it. The popup now uses widgets::popover, which keeps it open while its dropdowns are open. --- crates/ui-egui/src/canvas/task_bar.rs | 5 +++-- crates/ui-egui/src/tests/taskbar.rs | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index cf40955ee6..73a6334866 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -267,9 +267,10 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { if let Some(shape) = &shape && let NodeKind::Path { live: Some(live), .. } = &shape.kind { - // The shape's properties in a popup that stays open while its fields are edited. + // The shape's properties in a popover that stays open while its fields and + // its Corner dropdown are used. let props = widgets::icon_button(ui, "shapes", tl!("Shape Properties"), false, 30.0); - egui::Popup::menu(&props).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + widgets::popover(&props, props.clicked(), |ui| { ui.set_min_width(250.0); crate::panels::transform::live_shape_rows(app, ui, shape, live, "task-bar-shape", true); }); diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 2cc79e6daa..7a6bd26168 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -323,6 +323,27 @@ fn the_shape_properties_popup_edits_the_shape() { assert_eq!(sides(&app), 6); } +/// The popup stays open while a polygon's Corner dropdown is open, so a corner type can be picked +/// from it. +#[test] +fn the_shape_properties_popup_keeps_its_corner_dropdown() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let polygon = id(app.run("shape.polygon", json!({"cx": 100, "cy": 100, "radius": 40, "sides": 6})).unwrap()); + select(&mut app, &[polygon]); + let (ctx, texts) = click_lock_slot(&mut app); + let click = |app: &mut VectorcraftApp, p: Pos2| { + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![Event::PointerMoved(p), press(true), press(false)]); + frame(app, &ctx, vec![]) + }; + let texts = click(&mut app, at(&texts, "Round")); + assert!(has(&texts, "Polygon Properties:") && has(&texts, "Chamfer"), "the popup and its dropdown: {texts:?}"); + click(&mut app, at(&texts, "Chamfer")); + let vectorcraft_doc::LiveShape::Polygon { kinds, .. } = live(&app, polygon) else { panic!("not a polygon") }; + assert!(!kinds.is_empty() && kinds.iter().all(|k| *k == vectorcraft_geom::shapes::CornerKind::Chamfer), "{kinds:?}"); +} + /// Every other selection keeps Lock: a plain closed path, a star (a plain path), a path with live /// corners, a group and several objects. The Direct Selection tool keeps it for a basic shape. #[test] From 19b4fc8d437fa273f6e203be46f0841bd764527a Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sun, 1 Nov 2026 00:53:01 +0700 Subject: [PATCH 20/70] Canvas tests: the isolation-mode Lock test uses plain paths, as the task bar shows Lock for them --- crates/ui-egui/src/canvas/tests.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index b323306af7..f7361da0ca 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6982,9 +6982,6 @@ fn the_task_bar_lock_button_locks_selected_art_in_isolation_mode() { |x: f64| json!({"anchors": [{"x": x, "y": 130}, {"x": x + 40.0, "y": 130}, {"x": x + 40.0, "y": 170}, {"x": x, "y": 170}], "closed": true}); let a = app.session.execute("path.create", &square(150.0)).unwrap()["id"].clone(); let b = app.session.execute("path.create", &square(210.0)).unwrap()["id"].clone(); - app.session.execute("select.set", &json!({"ids": [a.clone(), b]})).unwrap(); - let a = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); - let b = app.session.execute("shape.rectangle", &json!({"x": 210, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); app.session.execute("select.set", &json!({"ids": [a.clone(), b.clone()]})).unwrap(); let g = app.session.execute("object.group", &json!({})).unwrap()["id"].clone(); app.select_tool("selection"); From 49290fa8e6bd32b1f841718a28e73a7f2b6ebdd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 06:32:34 -0700 Subject: [PATCH 21/70] Brushes: Delete Brush asks first, and Alt-click deletes without asking The Brushes panel's Delete Brush button and its panel menu item now ask before deleting the selected brushes, as Swatches and Graphic Styles do. OK deletes them in one undo step and strokes that used them become plain strokes; Cancel leaves the document unchanged. Alt-click (Option-click on macOS) on the button deletes without asking. The brush.delete command still deletes at once. --- crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/panels/brushes.rs | 21 +++++- crates/ui-egui/src/panels/brushes/tests.rs | 83 ++++++++++++++++++++-- docs/target-app-parity.md | 1 + 28 files changed, 171 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index dabb1c8e9a..702fb78d2b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -742,6 +742,9 @@ font-technology Variable Променливи Yes Да No Не Delete Tab Изтриване на табулация + Delete the brush “{name}”? Да се изтрие четката „{name}“? + Delete these {count} brushes? Да се изтрият тези {count} четки? + Strokes using deleted brushes become plain strokes. Щрихите, които използват изтритите четки, стават обикновени щрихи. Delete the graphic style “{name}”? Изтриване на графичния стил „{name}“? Delete Theme Изтриване на тема Delete theme Изтриване на тема diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 59984a5192..4269d2b7e7 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1059,6 +1059,9 @@ Yes Sí No No Delete Tab Suprimeix la tabulació + Delete the brush “{name}”? Voleu suprimir el pinzell “{name}”? + Delete these {count} brushes? Voleu suprimir aquests {count} pinzells? + Strokes using deleted brushes become plain strokes. Els traços que utilitzen pinzells suprimits esdevenen traços normals. Delete the graphic style “{name}”? Voleu suprimir l’estil gràfic “{name}”? Delete the library “{name}”? Voleu suprimir la biblioteca “{name}”? Delete Theme Suprimeix el tema diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 11d38443b6..39c5e2be1a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1558,6 +1558,9 @@ lighting Light Světlo Reverse Gradient Obrátit přechod Save to Swatches Uložit do vzorníku Delete Graphic Style (Alt-click: without asking) Odstranit grafický styl (Alt+kliknutí: bez dotazu) + Delete the brush “{name}”? Odstranit štětec „{name}“? + Delete these {count} brushes? Odstranit těchto {count} štětců? + Strokes using deleted brushes become plain strokes. Tahy používající odstraněné štětce se změní na běžné tahy. Delete the graphic style “{name}”? Odstranit grafický styl „{name}“? Delete these {n} graphic styles? Odstranit tyto grafické styly ({n})? Delete this {n} graphic style? Odstranit tento grafický styl ({n})? diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 1203b3d366..f7021936c3 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1472,6 +1472,9 @@ lighting Light Lys Reverse Gradient Omvend gradient Save to Swatches Gem i farveprøver Delete Graphic Style (Alt-click: without asking) Slet grafisk typografi (Alt-klik: uden at spørge) + Delete the brush “{name}”? Slet penslen »{name}«? + Delete these {count} brushes? Slet disse {count} pensler? + Strokes using deleted brushes become plain strokes. Streger, der bruger slettede pensler, bliver almindelige streger. Delete the graphic style “{name}”? Slet den grafiske typografi »{name}«? Delete these {n} graphic styles? Slet disse {n} grafiske typografier? Delete this {n} graphic style? Slet denne {n} grafiske typografi? diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index e832311b06..dc9c67f8bb 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -736,6 +736,9 @@ font-technology Variable Variabel Yes Ja No Nein Delete Tab Tabulator löschen + Delete the brush “{name}”? Pinsel „{name}“ löschen? + Delete these {count} brushes? Diese {count} Pinsel löschen? + Strokes using deleted brushes become plain strokes. Konturen mit gelöschten Pinseln werden zu einfachen Konturen. Delete the graphic style “{name}”? Grafikstil „{name}“ löschen? Delete Theme Thema löschen Delete theme Thema löschen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 90709397af..150002aa42 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -716,6 +716,9 @@ font-technology Variable Μεταβλητές Yes Ναι No Όχι Delete Tab Διαγραφή στηλοθέτη + Delete the brush “{name}”? Να διαγραφεί το πινέλο «{name}»; + Delete these {count} brushes? Να διαγραφούν αυτά τα {count} πινέλα; + Strokes using deleted brushes become plain strokes. Οι πινελιές που χρησιμοποιούν διαγραμμένα πινέλα γίνονται απλές πινελιές. Delete the graphic style “{name}”? Να διαγραφεί το στυλ γραφικών «{name}»; Delete Theme Διαγραφή θέματος Delete theme Διαγραφή θέματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f90a4b0471..2bbb317024 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -757,6 +757,9 @@ font-technology Variable Variables Yes Sí No No Delete Tab Eliminar tabulación + Delete the brush “{name}”? ¿Eliminar el pincel “{name}”? + Delete these {count} brushes? ¿Eliminar estos {count} pinceles? + Strokes using deleted brushes become plain strokes. Los trazos que usan pinceles eliminados se convierten en trazos simples. Delete the graphic style “{name}”? ¿Eliminar el estilo gráfico “{name}”? Delete Theme Eliminar tema Delete theme Eliminar tema diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 8c4bc1fc10..1a276e0e71 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1532,6 +1532,9 @@ lighting Light Valo Reverse Gradient Käännä liukuväri Save to Swatches Tallenna värimalleihin Delete Graphic Style (Alt-click: without asking) Poista grafiikkatyyli (Alt-napsautus: kysymättä) + Delete the brush “{name}”? Poistetaanko sivellin ”{name}”? + Delete these {count} brushes? Poistetaanko nämä {count} sivellintä? + Strokes using deleted brushes become plain strokes. Poistettuja siveltimiä käyttävät viivat muuttuvat tavallisiksi viivoiksi. Delete the graphic style “{name}”? Poistetaanko grafiikkatyyli ”{name}”? Delete these {n} graphic styles? Poistetaanko nämä {n} grafiikkatyyliä? Delete this {n} graphic style? Poistetaanko tämä {n} grafiikkatyyli? diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 7db8ee535a..68a78da7dd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -759,6 +759,9 @@ font-technology Variable Variables Yes Oui No Non Delete Tab Supprimer la tabulation + Delete the brush “{name}”? Supprimer la forme « {name} » ? + Delete these {count} brushes? Supprimer ces {count} formes ? + Strokes using deleted brushes become plain strokes. Les contours utilisant des formes supprimées deviennent des contours simples. Delete the graphic style “{name}”? Supprimer le style graphique « {name} » ? Delete Theme Supprimer le thème Delete theme Supprimer le thème diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0aceab5ab4..322770fb87 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -981,6 +981,9 @@ font-technology Variable Változó Yes Igen No Nem Delete Tab Tabulátor törlése + Delete the brush “{name}”? Törlöd ezt az ecsetet: „{name}”? + Delete these {count} brushes? Törlöd ezt a {count} ecsetet? + Strokes using deleted brushes become plain strokes. A törölt ecseteket használó körvonalak egyszerű körvonalakká válnak. Delete the graphic style “{name}”? Törlöd ezt a grafikai stílust: „{name}”? Delete the library “{name}”? Törlöd ezt a könyvtárat: „{name}”? Delete Theme Téma törlése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 95a3036337..25ee0213a1 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1472,6 +1472,9 @@ lighting Light Cahaya Reverse Gradient Balikkan gradien Save to Swatches Simpan ke swatch Delete Graphic Style (Alt-click: without asking) Hapus gaya grafis (Alt+klik: tanpa konfirmasi) + Delete the brush “{name}”? Hapus kuas “{name}”? + Delete these {count} brushes? Hapus {count} kuas ini? + Strokes using deleted brushes become plain strokes. Goresan yang menggunakan kuas terhapus menjadi goresan biasa. Delete the graphic style “{name}”? Hapus gaya grafis “{name}”? Delete these {n} graphic styles? Hapus {n} gaya grafis ini? Delete this {n} graphic style? Hapus {n} gaya grafis ini? diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a9c16d3ba9..7685ad98a5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -757,6 +757,9 @@ font-technology Variable Variabili Yes Sì No No Delete Tab Elimina tabulazione + Delete the brush “{name}”? Eliminare il pennello “{name}”? + Delete these {count} brushes? Eliminare questi {count} pennelli? + Strokes using deleted brushes become plain strokes. I tracciati che usano pennelli eliminati diventano tracciati semplici. Delete the graphic style “{name}”? Eliminare lo stile grafico “{name}”? Delete Theme Elimina tema Delete theme Elimina tema diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 01c25917b9..99376a0f11 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1308,6 +1308,9 @@ font-technology Variable バリアブル Delete Transparency Flattener Preset 透明の分割・統合プリセットを削除 Delete Width Point 幅ポイントを削除 Delete Workspace ワークスペースを削除 + Delete the brush “{name}”? ブラシ「{name}」を削除しますか? + Delete these {count} brushes? これら {count} 個のブラシを削除しますか? + Strokes using deleted brushes become plain strokes. 削除したブラシを使用する線は通常の線になります。 Delete the graphic style “{name}”? グラフィックスタイル「{name}」を削除しますか? Delete theme テーマを削除 Delete this saved preset この保存済みプリセットを削除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e0e1a10953..b55b3f2c95 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1389,6 +1389,9 @@ lighting Light სინათლე Reverse Gradient გრადიენტის შებრუნება Save to Swatches ფერის ნიმუშებში შენახვა Delete Graphic Style (Alt-click: without asking) გრაფიკული სტილის წაშლა (Alt-დაწკაპუნებით: დაუკითხავად) + Delete the brush “{name}”? წაიშალოს ფუნჯი „{name}“? + Delete these {count} brushes? წაიშალოს ეს {count} ფუნჯი? + Strokes using deleted brushes become plain strokes. წაშლილი ფუნჯებით დახატული შტრიხები ჩვეულებრივ შტრიხებად იქცევა. Delete the graphic style “{name}”? წაიშალოს გრაფიკული სტილი „{name}“? Delete these {n} graphic styles? წაიშალოს ეს გრაფიკული სტილები ({n})? Delete this {n} graphic style? წაიშალოს ეს გრაფიკული სტილი ({n})? diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 45ce73252c..e5dee07ee1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1299,6 +1299,9 @@ font-technology Variable 가변 Delete Transparency Flattener Preset 투명도 병합 프리셋 삭제 Delete Width Point 너비 포인트 삭제 Delete Workspace 작업 영역 삭제 + Delete the brush “{name}”? 브러시 “{name}”을(를) 삭제하시겠습니까? + Delete these {count} brushes? 이 브러시 {count}개를 삭제하시겠습니까? + Strokes using deleted brushes become plain strokes. 삭제된 브러시를 사용한 선은 일반 선이 됩니다. Delete the graphic style “{name}”? 그래픽 스타일 “{name}”을(를) 삭제하시겠습니까? Delete theme 테마 삭제 Delete this saved preset 저장된 이 프리셋 삭제 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index e4cca253f8..bbee0d063b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1486,6 +1486,9 @@ lighting Light Licht Reverse Gradient Verloop omkeren Save to Swatches Opslaan in stalen Delete Graphic Style (Alt-click: without asking) Grafische stijl verwijderen (Alt-klik: zonder vragen) + Delete the brush “{name}”? Kwast „{name}” verwijderen? + Delete these {count} brushes? Deze {count} kwasten verwijderen? + Strokes using deleted brushes become plain strokes. Lijnen die verwijderde kwasten gebruiken, worden gewone lijnen. Delete the graphic style “{name}”? De grafische stijl „{name}” verwijderen? Delete these {n} graphic styles? Deze {n} grafische stijlen verwijderen? Delete this {n} graphic style? Deze {n} grafische stijl verwijderen? diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 027f7198e2..95d62b9a05 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1472,6 +1472,9 @@ lighting Light Światło Reverse Gradient Odwróć gradient Save to Swatches Zapisz w próbkach Delete Graphic Style (Alt-click: without asking) Usuń styl graficzny (kliknięcie z Alt: bez pytania) + Delete the brush “{name}”? Usunąć pędzel „{name}”? + Delete these {count} brushes? Usunąć te {count} pędzle? + Strokes using deleted brushes become plain strokes. Obrysy używające usuniętych pędzli stają się zwykłymi obrysami. Delete the graphic style “{name}”? Usunąć styl graficzny „{name}”? Delete these {n} graphic styles? Usunąć te style graficzne ({n})? Delete this {n} graphic style? Usunąć ten styl graficzny ({n})? diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e9ee07994f..7f4d8287a3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -674,6 +674,9 @@ Delete Transparency Flattener Preset Excluir Predefinido de Achatamento de Transparência Delete Width Point Excluir Ponto de Largura Delete Workspace Excluir Espaço de Trabalho + Delete the brush “{name}”? Excluir o pincel “{name}”? + Delete these {count} brushes? Excluir estes {count} pincéis? + Strokes using deleted brushes become plain strokes. Traços que usam pincéis excluídos tornam-se traços simples. Delete the graphic style “{name}”? Excluir o estilo gráfico “{name}”? Delete theme Excluir tema Delete this saved preset Excluir este predefinido salvo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index dea1bee849..583a3f09a7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -755,6 +755,9 @@ font-technology Variable Вариативные Yes Да No Нет Delete Tab Удалить табуляцию + Delete the brush “{name}”? Удалить кисть «{name}»? + Delete these {count} brushes? Удалить эти кисти ({count})? + Strokes using deleted brushes become plain strokes. Обводки, использующие удалённые кисти, становятся обычными обводками. Delete the graphic style “{name}”? Удалить графический стиль «{name}»? Delete Theme Удалить тему Delete theme Удалить тему diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index fcd0427a77..1b68826627 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -744,6 +744,9 @@ font-technology Variable Variabla Yes Ja No Nej Delete Tab Radera tabb + Delete the brush “{name}”? Radera penseln ”{name}”? + Delete these {count} brushes? Radera dessa {count} penslar? + Strokes using deleted brushes become plain strokes. Linjer som använder borttagna penslar blir vanliga linjer. Delete the graphic style “{name}”? Radera grafikstilen ”{name}”? Delete Theme Radera tema Delete theme Radera tema diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7a1ea36471..d318f8a75d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -736,6 +736,9 @@ font-technology Variable Değişken Yes Evet No Hayır Delete Tab Sekmeyi Sil + Delete the brush “{name}”? “{name}” fırçası silinsin mi? + Delete these {count} brushes? Bu {count} fırça silinsin mi? + Strokes using deleted brushes become plain strokes. Silinen fırçaları kullanan konturlar düz konturlara dönüşür. Delete the graphic style “{name}”? “{name}” grafik stili silinsin mi? Delete Theme Temayı Sil Delete theme Temayı sil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 58693ddfd1..5dd9b8979c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -751,6 +751,9 @@ font-technology Variable Варіативні Yes Так No Ні Delete Tab Видалити табуляцію + Delete the brush “{name}”? Видалити пензель «{name}»? + Delete these {count} brushes? Видалити ці пензлі ({count})? + Strokes using deleted brushes become plain strokes. Обведення, що використовують видалені пензлі, стають звичайними обведеннями. Delete the graphic style “{name}”? Видалити графічний стиль «{name}»? Delete Theme Видалити тему Delete theme Видалити тему diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index aaa74d0e7c..6136b2ddd6 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -877,6 +877,9 @@ font-technology Variable Biến thiên Yes Có No Không Delete Tab Xóa tab + Delete the brush “{name}”? Xóa cọ “{name}”? + Delete these {count} brushes? Xóa {count} cọ này? + Strokes using deleted brushes become plain strokes. Các nét dùng cọ đã xóa trở thành nét thông thường. Delete the graphic style “{name}”? Xóa kiểu đồ họa “{name}”? Delete the library “{name}”? Xóa thư viện “{name}”? Delete Theme Xóa bộ màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 71b1fead14..7fbdf119b0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -700,6 +700,9 @@ Yes 是 No 否 Delete Tab 删除制表位 + Delete the brush “{name}”? 要删除画笔“{name}”吗? + Delete these {count} brushes? 要删除这 {count} 个画笔吗? + Strokes using deleted brushes become plain strokes. 使用已删除画笔的描边会变成普通描边。 Delete the graphic style “{name}”? 要删除图形样式“{name}”吗? Delete Theme 删除主题 Delete theme 删除主题 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a89fd28cce..3cb07c146a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -719,6 +719,9 @@ font-technology Variable 可變 Yes 是 No 否 Delete Tab 刪除定位點 + Delete the brush “{name}”? 要刪除筆刷「{name}」嗎? + Delete these {count} brushes? 要刪除這 {count} 個筆刷嗎? + Strokes using deleted brushes become plain strokes. 使用已刪除筆刷的筆畫會變成一般筆畫。 Delete the graphic style “{name}”? 要刪除繪圖樣式「{name}」嗎? Delete Theme 刪除主題 Delete theme 刪除主題 diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index cf95c5a9f1..29acddf378 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -204,6 +204,23 @@ fn run_on(app: &mut VectorcraftApp, id: &str, names: &[String]) { app.run(id, p).ok(); } +/// Delete `names` after asking, or immediately when the bottom button was Alt-clicked. +fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { + let params = match names { + [name] => json!({ "name": name }), + _ => json!({ "names": names }), + }; + if now { + app.run("brush.delete", params).ok(); + return; + } + let message = match names { + [name] => crate::i18n::fmt(tl!("Delete the brush “{name}”?"), &[("name", name)]), + _ => crate::i18n::fmt(tl!("Delete these {count} brushes?"), &[("count", &names.len().to_string())]), + }; + crate::dialogs::confirm::ask(app, &message, tl!("Strokes using deleted brushes become plain strokes."), "brush.delete", params); +} + /// The names in `list` in the order the panel shows them: by type in [`KINDS`] order, without the /// hidden types. fn shown<'a>(list: &'a [(String, String)], hidden: &[String]) -> Vec<&'a str> { @@ -417,7 +434,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { app.status(e); } if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Brush"), false, !targets.is_empty(), 24.0).clicked() { - run_on(app, "brush.delete", &targets); + delete(app, &targets, ui.input(|i| i.modifiers.alt)); } }); } @@ -452,7 +469,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { run_on(app, "brush.duplicate", &targets); } if menu_item(ui, tl!("Delete Brush"), !targets.is_empty(), false) { - run_on(app, "brush.delete", &targets); + delete(app, &targets, false); } if menu_item(ui, tl!("Remove Brush Stroke"), sel.is_some(), false) { app.run("brush.remove", json!({})).ok(); diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index 47fc962c64..711a601999 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -146,6 +146,23 @@ fn names(app: &mut VectorcraftApp) -> Vec { brushes(app).0.into_iter().map(|b| b.0).collect() } +fn undo_count(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +fn delete_button(ctx: &egui::Context, app: &mut VectorcraftApp, modifiers: egui::Modifiers, time: f64) { + let out = frame_with(ctx, app, vec![], egui::Modifiers::NONE, time, show); + let at = clickable(&out).into_iter().find(|(label, _)| label.as_deref() == Some("Delete Brush")).expect("Delete Brush button").1.center(); + click(ctx, app, at, modifiers, time + 0.5, show); +} + +fn assert_delete_dialog(app: &VectorcraftApp, message: &str) { + let d = app.ui.dialog.as_ref().expect("Delete Brush asks first"); + assert_eq!(d.kind, crate::dialogs::confirm::KIND); + assert_eq!(d.str("message"), message); + assert_eq!(d.str("detail"), "Strokes using deleted brushes become plain strokes."); +} + /// Click the panel menu's item `label` (frames at `time`, `time + 0.5`). fn menu_click(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, time: f64) { let out = frame_with(ctx, app, vec![], egui::Modifiers::NONE, time, menu); @@ -186,21 +203,23 @@ fn shift_and_command_clicks_select_brushes_for_delete_and_duplicate() { click(&ctx, &mut app, tiles[1].center(), egui::Modifiers::COMMAND, 3.0, show); let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 3.5, show); assert_eq!(lit_tiles(&out), [0, 2]); - let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); - let before = (names(&mut app), undo(&app)); + let before = (names(&mut app), undo_count(&app)); menu_click(&ctx, &mut app, "Duplicate Brush", 4.0); let copies = [format!("{} copy", three[0]), format!("{} copy", three[2])]; assert_eq!(names(&mut app)[before.0.len()..], copies); - assert_eq!(undo(&app), before.1 + 1); + assert_eq!(undo_count(&app), before.1 + 1); // The bottom bar's last button, Delete Brush. - let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 5.0, show); - let trash = clickable(&out).last().unwrap().1.center(); - click(&ctx, &mut app, trash, egui::Modifiers::NONE, 6.0, show); + delete_button(&ctx, &mut app, egui::Modifiers::NONE, 5.0); + assert_delete_dialog(&app, "Delete these 2 brushes?"); + assert_eq!(names(&mut app), [before.0.clone(), copies.to_vec()].concat()); + assert_eq!(brush_of(&app, rect).as_deref(), Some(three[0].as_str())); + assert_eq!(undo_count(&app), before.1 + 1); + crate::dialogs::confirm(&mut app).unwrap(); let left = names(&mut app); assert!(!left.contains(&three[0]) && !left.contains(&three[2]) && left.contains(&three[1]), "{left:?}"); assert!(copies.iter().all(|c| left.contains(c)), "{left:?}"); assert_eq!(brush_of(&app, rect), None); - assert_eq!(undo(&app), before.1 + 2); + assert_eq!(undo_count(&app), before.1 + 2); } /// Selecting other art ends the multi-selection: selecting the first art again does not bring @@ -231,6 +250,9 @@ fn selecting_other_art_ends_the_brush_multi_selection() { let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 4.0, show); assert_eq!(lit_tiles(&out), [1]); menu_click(&ctx, &mut app, "Delete Brush", 5.0); + assert_delete_dialog(&app, &format!("Delete the brush “{}”?", three[1])); + assert!(names(&mut app).contains(&three[1])); + crate::dialogs::confirm(&mut app).unwrap(); let left = names(&mut app); assert!(left.contains(&three[0]) && !left.contains(&three[1]) && left.contains(&three[2]), "{left:?}"); assert_eq!((brush_of(&app, a).as_deref(), brush_of(&app, c)), (Some(three[0].as_str()), None)); @@ -297,10 +319,57 @@ fn select_all_unused_selects_the_brushes_no_stroke_paints_with() { let on: Vec = (0..tiles.len()).filter(|i| lit(&ctx, &out).contains(&tiles[*i])).collect(); assert_eq!(on, (0..tiles.len()).filter(|i| *i != 1).collect::>()); menu_click(&ctx, &mut app, "Delete Brush", 3.0); + assert_delete_dialog(&app, &format!("Delete these {} brushes?", list.len() - 1)); + assert_eq!(names(&mut app).len(), list.len()); + crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(names(&mut app), [list[1].0.clone()]); assert_eq!(brush_of(&app, a), Some(list[1].0.clone())); } +#[test] +fn delete_button_cancel_keeps_selected_brushes_strokes_and_history() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let rect = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap()); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let (three, _) = select_three(&ctx, &mut app, rect); + let before = (names(&mut app), brush_of(&app, rect), undo_count(&app)); + delete_button(&ctx, &mut app, egui::Modifiers::NONE, 3.0); + assert_delete_dialog(&app, "Delete these 3 brushes?"); + assert_eq!((names(&mut app), brush_of(&app, rect), undo_count(&app)), before); + crate::dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!((names(&mut app), brush_of(&app, rect), undo_count(&app)), before); + assert_eq!(before.1.as_deref(), Some(three[0].as_str())); + app.run("brush.delete", json!({"name": three[0]})).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(undo_count(&app), before.2 + 1); + app.run("brush.delete", json!({"names": [three[1], three[2]]})).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(undo_count(&app), before.2 + 2); +} + +#[test] +fn alt_delete_button_removes_selected_brushes_without_dialog() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let rect = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap()); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let (three, _) = select_three(&ctx, &mut app, rect); + let before = undo_count(&app); + delete_button(&ctx, &mut app, egui::Modifiers::NONE, 3.0); + assert_delete_dialog(&app, "Delete these 3 brushes?"); + crate::dialogs::cancel(&mut app); + delete_button(&ctx, &mut app, egui::Modifiers::ALT, 4.0); + assert!(app.ui.dialog.is_none()); + let left = names(&mut app); + assert!(three.iter().all(|name| !left.contains(name))); + assert_eq!(brush_of(&app, rect), None); + assert_eq!(undo_count(&app), before + 1); +} + #[test] fn art_dropped_on_the_panel_becomes_an_art_brush_and_a_brush_drags_out() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 05985f9f18..ab9b96f4b3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -962,6 +962,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). In the Brushes panel, Shift-click selects a range of brushes and Ctrl/Cmd-click adds or removes one. Delete Brush and Duplicate Brush then act on all of them (`brush.delete {names}`, `brush.duplicate {names}`). + The bottom Delete Brush button and the panel menu ask before deleting; Alt-click (Option-click on macOS) on the button deletes without asking. Document Info has a Brushes category after Graphic Styles. It lists the Brushes panel's brushes, or with Selection Only it lists the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`). Document Info has a Repeat Objects category after Embedded Images. It lists each radial, grid and mirror Repeat object by name with its kind and the number of instances it makes. For a grid it gives the rows and columns instead, followed by the number of instances it draws when that is fewer. With Selection Only it lists the Repeat objects in the selection. The Document Info report and Package's report list them too (`document.info {category: "repeats"}`, `repeatObjects`). The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). From 90f9907de970c3dc8d6c66ddce35941e2e992751 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 06:49:52 -0700 Subject: [PATCH 22/70] Brushes: Alt-click Delete Brush runs through the shared command helper --- crates/ui-egui/src/panels/brushes.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 29acddf378..22b7d9401e 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -206,14 +206,14 @@ fn run_on(app: &mut VectorcraftApp, id: &str, names: &[String]) { /// Delete `names` after asking, or immediately when the bottom button was Alt-clicked. fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { + if now { + run_on(app, "brush.delete", names); + return; + } let params = match names { [name] => json!({ "name": name }), _ => json!({ "names": names }), }; - if now { - app.run("brush.delete", params).ok(); - return; - } let message = match names { [name] => crate::i18n::fmt(tl!("Delete the brush “{name}”?"), &[("name", name)]), _ => crate::i18n::fmt(tl!("Delete these {count} brushes?"), &[("count", &names.len().to_string())]), From 79188b359387ff99743a0ec1ac37a1cc5bebdc90 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 07:21:27 -0700 Subject: [PATCH 23/70] Brushes: the Delete Brush prompt for several brushes uses each language's plural forms The confirmation for several brushes now goes through i18n::tn, as the Graphic Styles prompt does, and each catalog gives the count-dependent forms in an @plural row. --- crates/ui-egui/src/i18n/bg.tsv | 2 +- crates/ui-egui/src/i18n/ca.tsv | 2 +- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/da.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/id.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- crates/ui-egui/src/panels/brushes.rs | 2 +- crates/ui-egui/src/panels/brushes/tests.rs | 13 +++++++++++++ 27 files changed, 39 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 702fb78d2b..5a5efddad2 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -743,7 +743,6 @@ font-technology Variable Променливи No Не Delete Tab Изтриване на табулация Delete the brush “{name}”? Да се изтрие четката „{name}“? - Delete these {count} brushes? Да се изтрият тези {count} четки? Strokes using deleted brushes become plain strokes. Щрихите, които използват изтритите четки, стават обикновени щрихи. Delete the graphic style “{name}”? Изтриване на графичния стил „{name}“? Delete Theme Изтриване на тема @@ -3634,6 +3633,7 @@ imageTrace Outline Контур @plural {n} item|{n} items {n} обект|{n} обекта @plural Color Table ({n} color)|Color Table ({n} colors) Цветна таблица ({n} цвят)|Цветна таблица ({n} цвята) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Изтриване на този графичен стил ({n})?|Изтриване на тези графични стилове ({n})? +@plural Delete this {n} brush?|Delete these {n} brushes? Изтриване на тази четка ({n})?|Изтриване на тези четки ({n})? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Изтриване на този {n} образец или група?|Изтриване на тези {n} образца и групи? @plural {n} Layer|{n} Layers {n} слой|{n} слоя @plural {n} Object|{n} Objects {n} обект|{n} обекта diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 4269d2b7e7..cd1046755c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1060,7 +1060,6 @@ No No Delete Tab Suprimeix la tabulació Delete the brush “{name}”? Voleu suprimir el pinzell “{name}”? - Delete these {count} brushes? Voleu suprimir aquests {count} pinzells? Strokes using deleted brushes become plain strokes. Els traços que utilitzen pinzells suprimits esdevenen traços normals. Delete the graphic style “{name}”? Voleu suprimir l’estil gràfic “{name}”? Delete the library “{name}”? Voleu suprimir la biblioteca “{name}”? @@ -4694,6 +4693,7 @@ @plural agrees with {n} default shortcut|agrees with {n} default shortcuts coincideix amb {n} drecera per defecte|coincideix amb {n} dreceres per defecte @plural Color Table ({n} color)|Color Table ({n} colors) Taula de colors ({n} color)|Taula de colors ({n} colors) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Voleu suprimir aquest {n} estil gràfic?|Voleu suprimir aquests {n} estils gràfics? +@plural Delete this {n} brush?|Delete these {n} brushes? Voleu suprimir aquest {n} pinzell?|Voleu suprimir aquests {n} pinzells? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Voleu suprimir aquesta {n} mostra o grup?|Voleu suprimir aquestes {n} mostres i grups? @plural {n} area highlighted|{n} areas highlighted {n} àrea ressaltada|{n} àrees ressaltades @plural {n} color|{n} colors {n} color|{n} colors diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 39c5e2be1a..4ffe67aea9 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1559,7 +1559,6 @@ lighting Light Světlo Save to Swatches Uložit do vzorníku Delete Graphic Style (Alt-click: without asking) Odstranit grafický styl (Alt+kliknutí: bez dotazu) Delete the brush “{name}”? Odstranit štětec „{name}“? - Delete these {count} brushes? Odstranit těchto {count} štětců? Strokes using deleted brushes become plain strokes. Tahy používající odstraněné štětce se změní na běžné tahy. Delete the graphic style “{name}”? Odstranit grafický styl „{name}“? Delete these {n} graphic styles? Odstranit tyto grafické styly ({n})? @@ -4138,6 +4137,7 @@ imageTrace Outline Obrys @plural {n} item|{n} items {n} položka|{n} položky|{n} položek @plural Color Table ({n} color)|Color Table ({n} colors) Tabulka barev ({n} barva)|Tabulka barev ({n} barvy)|Tabulka barev ({n} barev) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Odstranit {n} grafický styl?|Odstranit {n} grafické styly?|Odstranit {n} grafických stylů? +@plural Delete this {n} brush?|Delete these {n} brushes? Odstranit {n} štětec?|Odstranit {n} štětce?|Odstranit {n} štětců? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Odstranit {n} položku vzorníku nebo skupinu?|Odstranit {n} položky vzorníku a skupiny?|Odstranit {n} položek vzorníku a skupin? @plural {n} Layer|{n} Layers {n} vrstva|{n} vrstvy|{n} vrstev @plural {n} Object|{n} Objects {n} objekt|{n} objekty|{n} objektů diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f7021936c3..bce83c7bd6 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1473,7 +1473,6 @@ lighting Light Lys Save to Swatches Gem i farveprøver Delete Graphic Style (Alt-click: without asking) Slet grafisk typografi (Alt-klik: uden at spørge) Delete the brush “{name}”? Slet penslen »{name}«? - Delete these {count} brushes? Slet disse {count} pensler? Strokes using deleted brushes become plain strokes. Streger, der bruger slettede pensler, bliver almindelige streger. Delete the graphic style “{name}”? Slet den grafiske typografi »{name}«? Delete these {n} graphic styles? Slet disse {n} grafiske typografier? @@ -3870,6 +3869,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} element|{n} elementer @plural Color Table ({n} color)|Color Table ({n} colors) Farvetabel ({n} farve)|Farvetabel ({n} farver) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Vil du slette denne {n} grafikstil?|Vil du slette disse {n} grafikstile? +@plural Delete this {n} brush?|Delete these {n} brushes? Vil du slette denne {n} pensel?|Vil du slette disse {n} pensler? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Slet denne {n} farveprøve eller gruppe?|Slet disse {n} farveprøver og grupper? @plural {n} Layer|{n} Layers {n} lag|{n} lag @plural {n} Object|{n} Objects {n} objekt|{n} objekter diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index dc9c67f8bb..9e837d8eb6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -737,7 +737,6 @@ font-technology Variable Variabel No Nein Delete Tab Tabulator löschen Delete the brush “{name}”? Pinsel „{name}“ löschen? - Delete these {count} brushes? Diese {count} Pinsel löschen? Strokes using deleted brushes become plain strokes. Konturen mit gelöschten Pinseln werden zu einfachen Konturen. Delete the graphic style “{name}”? Grafikstil „{name}“ löschen? Delete Theme Thema löschen @@ -3621,6 +3620,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} Element|{n} Elemente @plural Color Table ({n} color)|Color Table ({n} colors) Farbtabelle ({n} Farbe)|Farbtabelle ({n} Farben) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Diesen {n} Grafikstil löschen?|Diese {n} Grafikstile löschen? +@plural Delete this {n} brush?|Delete these {n} brushes? Diesen {n} Pinsel löschen?|Diese {n} Pinsel löschen? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? {n} Farbfeld oder Gruppe löschen?|Diese {n} Farbfelder und Gruppen löschen? @plural {n} Layer|{n} Layers {n} Ebene|{n} Ebenen @plural {n} Object|{n} Objects {n} Objekt|{n} Objekte diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 150002aa42..e5ac837751 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -717,7 +717,6 @@ font-technology Variable Μεταβλητές No Όχι Delete Tab Διαγραφή στηλοθέτη Delete the brush “{name}”? Να διαγραφεί το πινέλο «{name}»; - Delete these {count} brushes? Να διαγραφούν αυτά τα {count} πινέλα; Strokes using deleted brushes become plain strokes. Οι πινελιές που χρησιμοποιούν διαγραμμένα πινέλα γίνονται απλές πινελιές. Delete the graphic style “{name}”? Να διαγραφεί το στυλ γραφικών «{name}»; Delete Theme Διαγραφή θέματος @@ -2032,6 +2031,7 @@ imageTrace Outline Περίγραμμα @plural {n} item|{n} items {n} στοιχείο|{n} στοιχεία @plural Color Table ({n} color)|Color Table ({n} colors) Πίνακας χρωμάτων ({n} χρώμα)|Πίνακας χρωμάτων ({n} χρώματα) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Να διαγραφεί αυτό το {n} στυλ γραφικών;|Να διαγραφούν αυτά τα {n} στυλ γραφικών; +@plural Delete this {n} brush?|Delete these {n} brushes? Να διαγραφεί αυτό το {n} πινέλο;|Να διαγραφούν αυτά τα {n} πινέλα; @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Να διαγραφεί αυτό το {n} δείγμα χρώματος ή ομάδα;|Να διαγραφούν αυτά τα {n} δείγματα χρωμάτων και οι ομάδες; @plural {n} Layer|{n} Layers {n} επίπεδο|{n} επίπεδα @plural {n} Object|{n} Objects {n} αντικείμενο|{n} αντικείμενα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2bbb317024..367692be2f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -758,7 +758,6 @@ font-technology Variable Variables No No Delete Tab Eliminar tabulación Delete the brush “{name}”? ¿Eliminar el pincel “{name}”? - Delete these {count} brushes? ¿Eliminar estos {count} pinceles? Strokes using deleted brushes become plain strokes. Los trazos que usan pinceles eliminados se convierten en trazos simples. Delete the graphic style “{name}”? ¿Eliminar el estilo gráfico “{name}”? Delete Theme Eliminar tema @@ -3706,6 +3705,7 @@ imageTrace Outline Contorno @plural {n} item|{n} items {n} elemento|{n} elementos @plural Color Table ({n} color)|Color Table ({n} colors) Tabla de colores ({n} color)|Tabla de colores ({n} colores) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? ¿Eliminar {n} estilo gráfico?|¿Eliminar estos {n} estilos gráficos? +@plural Delete this {n} brush?|Delete these {n} brushes? ¿Eliminar {n} pincel?|¿Eliminar estos {n} pinceles? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? ¿Eliminar {n} muestra o grupo?|¿Eliminar estas {n} muestras y grupos? @plural {n} Layer|{n} Layers {n} capa|{n} capas @plural {n} Object|{n} Objects {n} objeto|{n} objetos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1a276e0e71..d0b30760ac 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1533,7 +1533,6 @@ lighting Light Valo Save to Swatches Tallenna värimalleihin Delete Graphic Style (Alt-click: without asking) Poista grafiikkatyyli (Alt-napsautus: kysymättä) Delete the brush “{name}”? Poistetaanko sivellin ”{name}”? - Delete these {count} brushes? Poistetaanko nämä {count} sivellintä? Strokes using deleted brushes become plain strokes. Poistettuja siveltimiä käyttävät viivat muuttuvat tavallisiksi viivoiksi. Delete the graphic style “{name}”? Poistetaanko grafiikkatyyli ”{name}”? Delete these {n} graphic styles? Poistetaanko nämä {n} grafiikkatyyliä? @@ -4056,6 +4055,7 @@ imageTrace Outline Ääriviiva @plural {n} item|{n} items {n} kohde|{n} kohdetta @plural Color Table ({n} color)|Color Table ({n} colors) Väritaulukko ({n} väri)|Väritaulukko ({n} väriä) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Poistetaanko tämä {n} grafiikkatyyli?|Poistetaanko nämä {n} grafiikkatyyliä? +@plural Delete this {n} brush?|Delete these {n} brushes? Poistetaanko tämä {n} sivellin?|Poistetaanko nämä {n} sivellintä? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Poistetaanko tämä {n} värimalli tai ryhmä?|Poistetaanko nämä {n} värimallia ja ryhmää? @plural {n} Layer|{n} Layers {n} taso|{n} tasoa @plural {n} Object|{n} Objects {n} objekti|{n} objektia diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 68a78da7dd..ab5fc9acd1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -760,7 +760,6 @@ font-technology Variable Variables No Non Delete Tab Supprimer la tabulation Delete the brush “{name}”? Supprimer la forme « {name} » ? - Delete these {count} brushes? Supprimer ces {count} formes ? Strokes using deleted brushes become plain strokes. Les contours utilisant des formes supprimées deviennent des contours simples. Delete the graphic style “{name}”? Supprimer le style graphique « {name} » ? Delete Theme Supprimer le thème @@ -3704,6 +3703,7 @@ imageTrace Outline Contour @plural {n} item|{n} items {n} élément|{n} éléments @plural Color Table ({n} color)|Color Table ({n} colors) Table des couleurs ({n} couleur)|Table des couleurs ({n} couleurs) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Supprimer {n} style graphique ?|Supprimer ces {n} styles graphiques ? +@plural Delete this {n} brush?|Delete these {n} brushes? Supprimer {n} forme ?|Supprimer ces {n} formes ? @plural {n} Layer|{n} Layers {n} calque|{n} calques @plural {n} Object|{n} Objects {n} objet|{n} objets @plural {n} area highlighted|{n} areas highlighted {n} zone mise en évidence|{n} zones mises en évidence diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 322770fb87..e91e7dfe56 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -982,7 +982,6 @@ font-technology Variable Változó No Nem Delete Tab Tabulátor törlése Delete the brush “{name}”? Törlöd ezt az ecsetet: „{name}”? - Delete these {count} brushes? Törlöd ezt a {count} ecsetet? Strokes using deleted brushes become plain strokes. A törölt ecseteket használó körvonalak egyszerű körvonalakká válnak. Delete the graphic style “{name}”? Törlöd ezt a grafikai stílust: „{name}”? Delete the library “{name}”? Törlöd ezt a könyvtárat: „{name}”? @@ -4459,6 +4458,7 @@ theme Appearance Kinézet imageTrace Outline Körvonal @plural Color Table ({n} color)|Color Table ({n} colors) Színtábla ({n} szín) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? {n} grafikai stílus törlése? +@plural Delete this {n} brush?|Delete these {n} brushes? {n} ecset törlése? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? {n} színminta és csoport törlése? @plural {n} area highlighted|{n} areas highlighted Kiemelt terület: {n} @plural {n} color|{n} colors {n} szín diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 25ee0213a1..265da6fbee 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1473,7 +1473,6 @@ lighting Light Cahaya Save to Swatches Simpan ke swatch Delete Graphic Style (Alt-click: without asking) Hapus gaya grafis (Alt+klik: tanpa konfirmasi) Delete the brush “{name}”? Hapus kuas “{name}”? - Delete these {count} brushes? Hapus {count} kuas ini? Strokes using deleted brushes become plain strokes. Goresan yang menggunakan kuas terhapus menjadi goresan biasa. Delete the graphic style “{name}”? Hapus gaya grafis “{name}”? Delete these {n} graphic styles? Hapus {n} gaya grafis ini? @@ -3870,6 +3869,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} item @plural Color Table ({n} color)|Color Table ({n} colors) Tabel warna ({n} warna) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Hapus {n} gaya grafis ini? +@plural Delete this {n} brush?|Delete these {n} brushes? Hapus {n} kuas ini? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Hapus {n} swatch dan grup ini? @plural {n} Layer|{n} Layers {n} lapisan @plural {n} Object|{n} Objects {n} objek diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7685ad98a5..af6874bbe8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -758,7 +758,6 @@ font-technology Variable Variabili No No Delete Tab Elimina tabulazione Delete the brush “{name}”? Eliminare il pennello “{name}”? - Delete these {count} brushes? Eliminare questi {count} pennelli? Strokes using deleted brushes become plain strokes. I tracciati che usano pennelli eliminati diventano tracciati semplici. Delete the graphic style “{name}”? Eliminare lo stile grafico “{name}”? Delete Theme Elimina tema @@ -3742,6 +3741,7 @@ imageTrace Outline Contorno @plural {n} item|{n} items {n} elemento|{n} elementi @plural Color Table ({n} color)|Color Table ({n} colors) Tabella colori ({n} colore)|Tabella colori ({n} colori) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Eliminare {n} stile grafico?|Eliminare questi {n} stili grafici? +@plural Delete this {n} brush?|Delete these {n} brushes? Eliminare {n} pennello?|Eliminare questi {n} pennelli? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Eliminare {n} campione o gruppo?|Eliminare questi {n} campioni e gruppi? @plural {n} Layer|{n} Layers {n} livello|{n} livelli @plural {n} Object|{n} Objects {n} oggetto|{n} oggetti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 99376a0f11..f9ad60b875 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1309,7 +1309,6 @@ font-technology Variable バリアブル Delete Width Point 幅ポイントを削除 Delete Workspace ワークスペースを削除 Delete the brush “{name}”? ブラシ「{name}」を削除しますか? - Delete these {count} brushes? これら {count} 個のブラシを削除しますか? Strokes using deleted brushes become plain strokes. 削除したブラシを使用する線は通常の線になります。 Delete the graphic style “{name}”? グラフィックスタイル「{name}」を削除しますか? Delete theme テーマを削除 @@ -3725,6 +3724,7 @@ file-filter Templates テンプレート imageTrace Outline アウトライン @plural Color Table ({n} color)|Color Table ({n} colors) カラーテーブル ({n} 色) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? {n} 個のグラフィックスタイルを削除しますか? +@plural Delete this {n} brush?|Delete these {n} brushes? {n} 個のブラシを削除しますか? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? これら {n} 個のスウォッチとグループを削除しますか? @plural {n} Layer|{n} Layers {n} レイヤー @plural {n} Object|{n} Objects {n} オブジェクト diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b55b3f2c95..7f6eb84ba3 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1390,7 +1390,6 @@ lighting Light სინათლე Save to Swatches ფერის ნიმუშებში შენახვა Delete Graphic Style (Alt-click: without asking) გრაფიკული სტილის წაშლა (Alt-დაწკაპუნებით: დაუკითხავად) Delete the brush “{name}”? წაიშალოს ფუნჯი „{name}“? - Delete these {count} brushes? წაიშალოს ეს {count} ფუნჯი? Strokes using deleted brushes become plain strokes. წაშლილი ფუნჯებით დახატული შტრიხები ჩვეულებრივ შტრიხებად იქცევა. Delete the graphic style “{name}”? წაიშალოს გრაფიკული სტილი „{name}“? Delete these {n} graphic styles? წაიშალოს ეს გრაფიკული სტილები ({n})? @@ -3636,6 +3635,7 @@ font-technology Variable ცვლადი @plural {n} item|{n} items ელემენტი: {n} @plural Color Table ({n} color)|Color Table ({n} colors) ფერების ცხრილი (ფერი: {n}) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? წაიშალოს გრაფიკული სტილები ({n})? +@plural Delete this {n} brush?|Delete these {n} brushes? წაიშალოს ეს ფუნჯი ({n})? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? წაიშალოს ეს ფერის ნიმუშები და ჯგუფები ({n})? @plural {n} Layer|{n} Layers შრე: {n} @plural {n} Object|{n} Objects ობიექტი: {n} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e5dee07ee1..a64392ef3b 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1300,7 +1300,6 @@ font-technology Variable 가변 Delete Width Point 너비 포인트 삭제 Delete Workspace 작업 영역 삭제 Delete the brush “{name}”? 브러시 “{name}”을(를) 삭제하시겠습니까? - Delete these {count} brushes? 이 브러시 {count}개를 삭제하시겠습니까? Strokes using deleted brushes become plain strokes. 삭제된 브러시를 사용한 선은 일반 선이 됩니다. Delete the graphic style “{name}”? 그래픽 스타일 “{name}”을(를) 삭제하시겠습니까? Delete theme 테마 삭제 @@ -3714,6 +3713,7 @@ file-filter Templates 템플릿 imageTrace Outline 윤곽선 @plural Color Table ({n} color)|Color Table ({n} colors) 색상 표 ({n}색)|색상 표 ({n}색) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? 그래픽 스타일 {n}개를 삭제하시겠습니까?|그래픽 스타일 {n}개를 삭제하시겠습니까? +@plural Delete this {n} brush?|Delete these {n} brushes? 브러시 {n}개를 삭제하시겠습니까?|브러시 {n}개를 삭제하시겠습니까? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? 견본과 그룹 {n}개를 삭제하시겠습니까? @plural {n} Layer|{n} Layers 레이어 {n}개|레이어 {n}개 @plural {n} Object|{n} Objects 개체 {n}개|개체 {n}개 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index bbee0d063b..ed254e2a19 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1487,7 +1487,6 @@ lighting Light Licht Save to Swatches Opslaan in stalen Delete Graphic Style (Alt-click: without asking) Grafische stijl verwijderen (Alt-klik: zonder vragen) Delete the brush “{name}”? Kwast „{name}” verwijderen? - Delete these {count} brushes? Deze {count} kwasten verwijderen? Strokes using deleted brushes become plain strokes. Lijnen die verwijderde kwasten gebruiken, worden gewone lijnen. Delete the graphic style “{name}”? De grafische stijl „{name}” verwijderen? Delete these {n} graphic styles? Deze {n} grafische stijlen verwijderen? @@ -3884,6 +3883,7 @@ imageTrace Outline Contour @plural {n} item|{n} items {n} item|{n} items @plural Color Table ({n} color)|Color Table ({n} colors) Kleurentabel ({n} kleur)|Kleurentabel ({n} kleuren) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Deze {n} grafische stijl verwijderen?|Deze {n} grafische stijlen verwijderen? +@plural Delete this {n} brush?|Delete these {n} brushes? Deze {n} kwast verwijderen?|Deze {n} kwasten verwijderen? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Deze {n} staal of groep verwijderen?|Deze {n} stalen en groepen verwijderen? @plural {n} Layer|{n} Layers {n} laag|{n} lagen @plural {n} Object|{n} Objects {n} object|{n} objecten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 95d62b9a05..f2e5c5964b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1473,7 +1473,6 @@ lighting Light Światło Save to Swatches Zapisz w próbkach Delete Graphic Style (Alt-click: without asking) Usuń styl graficzny (kliknięcie z Alt: bez pytania) Delete the brush “{name}”? Usunąć pędzel „{name}”? - Delete these {count} brushes? Usunąć te {count} pędzle? Strokes using deleted brushes become plain strokes. Obrysy używające usuniętych pędzli stają się zwykłymi obrysami. Delete the graphic style “{name}”? Usunąć styl graficzny „{name}”? Delete these {n} graphic styles? Usunąć te style graficzne ({n})? @@ -3964,6 +3963,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} element|{n} elementy|{n} elementów @plural Color Table ({n} color)|Color Table ({n} colors) Tablica kolorów ({n} kolor)|Tablica kolorów ({n} kolory)|Tablica kolorów ({n} kolorów) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Usunąć {n} styl graficzny?|Usunąć {n} style graficzne?|Usunąć {n} stylów graficznych? +@plural Delete this {n} brush?|Delete these {n} brushes? Usunąć {n} pędzel?|Usunąć {n} pędzle?|Usunąć {n} pędzli? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Usunąć {n} próbkę lub grupę?|Usunąć {n} próbki i grupy?|Usunąć {n} próbek i grup? @plural {n} Layer|{n} Layers {n} warstwa|{n} warstwy|{n} warstw @plural {n} Object|{n} Objects {n} obiekt|{n} obiekty|{n} obiektów diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 7f4d8287a3..4d39287c57 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -675,7 +675,6 @@ Delete Width Point Excluir Ponto de Largura Delete Workspace Excluir Espaço de Trabalho Delete the brush “{name}”? Excluir o pincel “{name}”? - Delete these {count} brushes? Excluir estes {count} pincéis? Strokes using deleted brushes become plain strokes. Traços que usam pincéis excluídos tornam-se traços simples. Delete the graphic style “{name}”? Excluir o estilo gráfico “{name}”? Delete theme Excluir tema @@ -3044,6 +3043,7 @@ imageTrace Outline Contorno @plural {n} item|{n} items {n} item|{n} itens @plural Color Table ({n} color)|Color Table ({n} colors) Tabela de Cores ({n} cor)|Tabela de Cores ({n} cores) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Excluir este {n} estilo gráfico?|Excluir estes {n} estilos gráficos? +@plural Delete this {n} brush?|Delete these {n} brushes? Excluir este {n} pincel?|Excluir estes {n} pincéis? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Excluir esta {n} amostra ou grupo?|Excluir estas {n} amostras e grupos? @plural {n} Layer|{n} Layers {n} Camada|{n} Camadas @plural {n} Object|{n} Objects {n} Objeto|{n} Objetos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 583a3f09a7..952171bbf1 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -756,7 +756,6 @@ font-technology Variable Вариативные No Нет Delete Tab Удалить табуляцию Delete the brush “{name}”? Удалить кисть «{name}»? - Delete these {count} brushes? Удалить эти кисти ({count})? Strokes using deleted brushes become plain strokes. Обводки, использующие удалённые кисти, становятся обычными обводками. Delete the graphic style “{name}”? Удалить графический стиль «{name}»? Delete Theme Удалить тему @@ -3738,6 +3737,7 @@ imageTrace Outline Контур @plural {n} item|{n} items {n} элемент|{n} элемента|{n} элементов @plural Color Table ({n} color)|Color Table ({n} colors) Цветовая таблица ({n} цвет)|Цветовая таблица ({n} цвета)|Цветовая таблица ({n} цветов) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Удалить этот графический стиль ({n})?|Удалить эти графические стили ({n})?|Удалить эти графические стили ({n})? +@plural Delete this {n} brush?|Delete these {n} brushes? Удалить эту кисть ({n})?|Удалить эти кисти ({n})?|Удалить {n} кистей? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Удалить образцы и группы ({n})?|Удалить {n} образца и группы?|Удалить {n} образцов и групп? @plural {n} Layer|{n} Layers {n} слой|{n} слоя|{n} слоёв @plural {n} Object|{n} Objects {n} объект|{n} объекта|{n} объектов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1b68826627..9f24f8e02c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -745,7 +745,6 @@ font-technology Variable Variabla No Nej Delete Tab Radera tabb Delete the brush “{name}”? Radera penseln ”{name}”? - Delete these {count} brushes? Radera dessa {count} penslar? Strokes using deleted brushes become plain strokes. Linjer som använder borttagna penslar blir vanliga linjer. Delete the graphic style “{name}”? Radera grafikstilen ”{name}”? Delete Theme Radera tema @@ -3634,6 +3633,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} objekt|{n} objekt @plural Color Table ({n} color)|Color Table ({n} colors) Färgtabell ({n} färg)|Färgtabell ({n} färger) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Radera {n} grafisk stil?|Radera de här {n} grafiska stilarna? +@plural Delete this {n} brush?|Delete these {n} brushes? Radera {n} pensel?|Radera dessa {n} penslar? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Radera {n} färgruta eller grupp?|Radera dessa {n} färgrutor och grupper? @plural {n} Layer|{n} Layers {n} lager|{n} lager @plural {n} Object|{n} Objects {n} objekt|{n} objekt diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d318f8a75d..91fd8143d1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -737,7 +737,6 @@ font-technology Variable Değişken No Hayır Delete Tab Sekmeyi Sil Delete the brush “{name}”? “{name}” fırçası silinsin mi? - Delete these {count} brushes? Bu {count} fırça silinsin mi? Strokes using deleted brushes become plain strokes. Silinen fırçaları kullanan konturlar düz konturlara dönüşür. Delete the graphic style “{name}”? “{name}” grafik stili silinsin mi? Delete Theme Temayı Sil @@ -3528,6 +3527,7 @@ imageTrace Outline Kontur @plural {n} item|{n} items {n} öğe @plural Color Table ({n} color)|Color Table ({n} colors) Renk Tablosu ({n} renk) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Bu {n} grafik stili silinsin mi? +@plural Delete this {n} brush?|Delete these {n} brushes? Bu {n} fırça silinsin mi? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Bu {n} renk örneği ve grup silinsin mi? @plural {n} Layer|{n} Layers {n} Katman @plural {n} Object|{n} Objects {n} Nesne diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 5dd9b8979c..750796afe1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -752,7 +752,6 @@ font-technology Variable Варіативні No Ні Delete Tab Видалити табуляцію Delete the brush “{name}”? Видалити пензель «{name}»? - Delete these {count} brushes? Видалити ці пензлі ({count})? Strokes using deleted brushes become plain strokes. Обведення, що використовують видалені пензлі, стають звичайними обведеннями. Delete the graphic style “{name}”? Видалити графічний стиль «{name}»? Delete Theme Видалити тему @@ -3735,6 +3734,7 @@ imageTrace Outline Контур @plural {n} item|{n} items {n} елемент|{n} елементи|{n} елементів @plural Color Table ({n} color)|Color Table ({n} colors) Таблиця кольорів ({n} колір)|Таблиця кольорів ({n} кольори)|Таблиця кольорів ({n} кольорів) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Видалити цей графічний стиль ({n})?|Видалити ці графічні стилі ({n})?|Видалити ці графічні стилі ({n})? +@plural Delete this {n} brush?|Delete these {n} brushes? Видалити цей пензель ({n})?|Видалити ці пензлі ({n})?|Видалити {n} пензлів? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Видалити зразки та групи ({n})?|Видалити {n} зразки та групи?|Видалити {n} зразків і груп? @plural {n} Layer|{n} Layers {n} шар|{n} шари|{n} шарів @plural {n} Object|{n} Objects {n} об’єкт|{n} об’єкти|{n} об’єктів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 6136b2ddd6..494b40265c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -878,7 +878,6 @@ font-technology Variable Biến thiên No Không Delete Tab Xóa tab Delete the brush “{name}”? Xóa cọ “{name}”? - Delete these {count} brushes? Xóa {count} cọ này? Strokes using deleted brushes become plain strokes. Các nét dùng cọ đã xóa trở thành nét thông thường. Delete the graphic style “{name}”? Xóa kiểu đồ họa “{name}”? Delete the library “{name}”? Xóa thư viện “{name}”? @@ -4100,6 +4099,7 @@ gradient-kind Radial Hướng tâm imageTrace Outline Đường viền @plural Color Table ({n} color)|Color Table ({n} colors) Bảng màu ({n} màu) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Xóa {n} kiểu đồ họa này? +@plural Delete this {n} brush?|Delete these {n} brushes? Xóa {n} cọ này? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Xóa {n} mẫu màu và nhóm này? @plural {n} area highlighted|{n} areas highlighted {n} vùng được tô sáng @plural {n} color|{n} colors {n} màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 7fbdf119b0..105fefd26d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -701,7 +701,6 @@ No 否 Delete Tab 删除制表位 Delete the brush “{name}”? 要删除画笔“{name}”吗? - Delete these {count} brushes? 要删除这 {count} 个画笔吗? Strokes using deleted brushes become plain strokes. 使用已删除画笔的描边会变成普通描边。 Delete the graphic style “{name}”? 要删除图形样式“{name}”吗? Delete Theme 删除主题 @@ -3581,6 +3580,7 @@ imageTrace Outline 轮廓 @plural {n} item|{n} items {n} 个项目 @plural Color Table ({n} color)|Color Table ({n} colors) 颜色表 ({n} 色) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? 要删除这 {n} 个图形样式吗? +@plural Delete this {n} brush?|Delete these {n} brushes? 要删除这 {n} 个画笔吗? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? 要删除这 {n} 个色板和编组吗? @plural {n} Layer|{n} Layers {n} 个图层 @plural {n} Object|{n} Objects {n} 个对象 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3cb07c146a..7ffb1831a4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -720,7 +720,6 @@ font-technology Variable 可變 No 否 Delete Tab 刪除定位點 Delete the brush “{name}”? 要刪除筆刷「{name}」嗎? - Delete these {count} brushes? 要刪除這 {count} 個筆刷嗎? Strokes using deleted brushes become plain strokes. 使用已刪除筆刷的筆畫會變成一般筆畫。 Delete the graphic style “{name}”? 要刪除繪圖樣式「{name}」嗎? Delete Theme 刪除主題 @@ -4560,6 +4559,7 @@ imageTrace Outline 輪廓 @plural {n} item|{n} items {n} 個項目 @plural Color Table ({n} color)|Color Table ({n} colors) 色彩表 ({n} 色) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? 要刪除這 {n} 個繪圖樣式嗎? +@plural Delete this {n} brush?|Delete these {n} brushes? 要刪除這 {n} 個筆刷嗎? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? 要刪除這 {n} 個色票和群組嗎? @plural {n} Layer|{n} Layers {n} 個圖層 @plural {n} Object|{n} Objects {n} 個物件 diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 22b7d9401e..b734047305 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -216,7 +216,7 @@ fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { }; let message = match names { [name] => crate::i18n::fmt(tl!("Delete the brush “{name}”?"), &[("name", name)]), - _ => crate::i18n::fmt(tl!("Delete these {count} brushes?"), &[("count", &names.len().to_string())]), + _ => crate::i18n::tn(names.len() as u64, "Delete this {n} brush?", "Delete these {n} brushes?"), }; crate::dialogs::confirm::ask(app, &message, tl!("Strokes using deleted brushes become plain strokes."), "brush.delete", params); } diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index 711a601999..421c0162a4 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -163,6 +163,19 @@ fn assert_delete_dialog(app: &VectorcraftApp, message: &str) { assert_eq!(d.str("detail"), "Strokes using deleted brushes become plain strokes."); } +#[test] +fn deleting_five_brushes_uses_polish_many_form() { + let previous = crate::i18n::current(); + let polish = crate::i18n::Lang::from_code("pl").unwrap(); + crate::i18n::set_current(polish); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let names: Vec = (1..=5).map(|n| format!("Brush {n}")).collect(); + delete(&mut app, &names, false); + let message = app.ui.dialog.as_ref().map(|d| d.str("message")); + crate::i18n::set_current(previous); + assert_eq!(message, Some("Usunąć 5 pędzli?".to_string())); +} + /// Click the panel menu's item `label` (frames at `time`, `time + 0.5`). fn menu_click(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, time: f64) { let out = frame_with(ctx, app, vec![], egui::Modifiers::NONE, time, menu); From b1aa5767648715225b5ebc294bdf7698e3e39a1b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 21:56:48 -0700 Subject: [PATCH 24/70] Brushes: Delete Brush asks Yes or No for unused brushes, and Remove Strokes or Cancel for brushes in use The question for brushes no stroke uses reads "Delete the brush selection?" with Yes and No, from the bottom button and the panel menu, and Alt-click (Option-click on macOS) on the button still deletes them without asking. When a stroke uses one of the brushes, the button, Alt-click and the menu item ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. brush.unused also counts the tile that pattern editing's Cancel puts back, which brush.delete already clears, so the panel asks the in-use question for a brush only that tile uses. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/brushes.rs | 7 +- crates/engine/src/tests/brushsym.rs | 25 +++++++ crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/brush_delete.rs | 61 +++++++++++++++ .../ui-egui/src/dialogs/brush_delete/tests.rs | 71 ++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 7 +- crates/ui-egui/src/i18n/bs.tsv | 5 ++ crates/ui-egui/src/i18n/ca.tsv | 7 +- crates/ui-egui/src/i18n/cs.tsv | 7 +- crates/ui-egui/src/i18n/da.tsv | 7 +- crates/ui-egui/src/i18n/de.tsv | 7 +- crates/ui-egui/src/i18n/el.tsv | 7 +- crates/ui-egui/src/i18n/es.tsv | 7 +- crates/ui-egui/src/i18n/fi.tsv | 7 +- crates/ui-egui/src/i18n/fr.tsv | 8 +- crates/ui-egui/src/i18n/hu.tsv | 7 +- crates/ui-egui/src/i18n/id.tsv | 7 +- crates/ui-egui/src/i18n/it.tsv | 7 +- crates/ui-egui/src/i18n/ja.tsv | 7 +- crates/ui-egui/src/i18n/ka.tsv | 7 +- crates/ui-egui/src/i18n/ko.tsv | 7 +- crates/ui-egui/src/i18n/nl.tsv | 7 +- crates/ui-egui/src/i18n/pl.tsv | 7 +- crates/ui-egui/src/i18n/pt-br.tsv | 7 +- crates/ui-egui/src/i18n/ru.tsv | 7 +- crates/ui-egui/src/i18n/sv.tsv | 7 +- crates/ui-egui/src/i18n/tr.tsv | 7 +- crates/ui-egui/src/i18n/uk.tsv | 7 +- crates/ui-egui/src/i18n/vi.tsv | 7 +- crates/ui-egui/src/i18n/zh-hans.tsv | 7 +- crates/ui-egui/src/i18n/zh-hant.tsv | 7 +- crates/ui-egui/src/panels/brushes.rs | 16 ++-- crates/ui-egui/src/panels/brushes/tests.rs | 75 +++++++++++++++---- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 36 files changed, 367 insertions(+), 81 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/brush_delete.rs create mode 100644 crates/ui-egui/src/dialogs/brush_delete/tests.rs diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 8ef171d326..7b37fea769 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -125,7 +125,7 @@ pub fn specs() -> Vec { "Select All Unused", [], None, - "{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes panel selects them): strokes in the art (opacity masks included), symbols, graph designs, pattern tiles and graphic styles count, and so do strokes in the art of a brush that is used", + "{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes 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 strokes in the art of a brush that is used", has_doc, brush_unused ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 66dd546e90..f5e5c73fce 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -362,14 +362,15 @@ fn art_brushes(n: &Node, out: &mut Vec) { } /// The brushes no stroke paints with. Strokes in the art (opacity masks included), symbols, graph -/// designs, pattern tiles and graphic styles count, and so do the strokes in the art of every brush -/// that a counted stroke paints with. +/// designs, pattern tiles and the tiles that pattern editing's Cancel puts back, and graphic styles +/// count, and so do the strokes in the art of every brush that a counted stroke paints with. pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result { let d = &s.doc()?.doc; let lib = brush::library(d); let mut todo = vec![]; let trees = d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.graph_designs.iter().map(|g| &g.art)); - trees.chain(d.patterns.iter().flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo)); + let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); + trees.chain(patterns.flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo)); d.graphic_styles.iter().for_each(|g| stroke_brushes(&g.appearance.items, &mut todo)); let mut used = BTreeSet::new(); while let Some(name) = todo.pop() { diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index c6a33ffc66..bba39230bc 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -457,6 +457,31 @@ fn brush_unused_lists_the_brushes_no_stroke_paints_with() { assert_eq!(unused(&mut s), ["3 pt. Round", "6 pt. Flat", "Charcoal"]); } +/// A stroke in the tile that pattern editing's Cancel puts back counts as a use, as `brush.delete` +/// clears it there. +#[test] +fn brush_unused_counts_pattern_edit_originals() { + let mut s = session(); + let id = rect(&mut s, 10.0, 10.0, 40.0, 20.0); + s.execute("brush.apply", &json!({"name": "6 pt. Flat", "ids": [id.0]})).unwrap(); + let name = s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap()["name"].clone(); + s.execute("brush.remove", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.pattern.edit", &json!({ "name": name })).unwrap(); + // The tile's copies in the editing layer are selected; only the tile kept for Cancel paints with the brush. + s.execute("brush.remove", &json!({})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let original = d.pattern_edit.as_ref().and_then(|pe| pe.original.as_ref()).expect("pattern edit original"); + assert_eq!(original.art.first().and_then(|n| n.appearance.stroke()).and_then(|k| k.brush.as_deref()), Some("6 pt. Flat")); + for pattern in &mut d.patterns { + for art in &mut pattern.art { + if let Some(stroke) = std::sync::Arc::make_mut(art).appearance.stroke_mut() { + stroke.brush = None; + } + } + } + assert!(!unused(&mut s).contains(&"6 pt. Flat".to_string())); +} + /// A brush counts as used when a stroke paints with it in an opacity mask, a symbol, a graph /// design, a pattern tile, a graphic style, or the art of a brush that is used. The art of a brush /// that is not used, its own strokes included, does not count. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 488cd1d956..b2a42af49b 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -12,6 +12,7 @@ pub mod action_set_options; pub mod artboard_options; pub mod blend_options; mod brush_art_options; +pub mod brush_delete; pub mod brush_options; pub mod color_balance; pub mod color_guide_options; @@ -293,6 +294,7 @@ registry! { FindFont: ["findFont"] => DialogSpec::window(crate::find_font::show, |app, _| crate::find_font::confirm(app)), SwatchOptions: [swatch_options::KIND] => swatch_options::SPEC, Confirm: [confirm::KIND] => confirm::SPEC, + BrushDelete: [brush_delete::KIND] => brush_delete::SPEC, Message: [confirm::MESSAGE] => confirm::MESSAGE_SPEC, Replace: [confirm::REPLACE] => confirm::REPLACE_SPEC, NewSwatch: [new_swatch::KIND] => new_swatch::SPEC, diff --git a/crates/ui-egui/src/dialogs/brush_delete.rs b/crates/ui-egui/src/dialogs/brush_delete.rs new file mode 100644 index 0000000000..9488d14bec --- /dev/null +++ b/crates/ui-egui/src/dialogs/brush_delete.rs @@ -0,0 +1,61 @@ +//! The Brushes panel's Delete Brush question ([`ask`]): Yes or No when none of the brushes is in +//! use, else Remove Strokes or Cancel. Yes and Remove Strokes run `brush.delete`, which leaves the +//! strokes that used the brushes as plain strokes. +//! +//! Fields: `message` (the question, shown as the heading), `used` (whether a brush is in use) and +//! `params` (the `brush.delete` params). + +use serde_json::{Value, json}; + +use super::{DialogAction, DialogSpec}; +use crate::VectorcraftApp; +use crate::state::Dialog; +use crate::widgets; + +/// The dialog kind of the Delete Brush question. +pub const KIND: &str = "brushDelete"; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |d| d.str("message"), body_with_actions: Some(body), confirm, ok: None, max_width: Some(540.0), ..DialogSpec::FORM }; + +/// Ask whether to delete the brushes `params` names (`used`: one of them is in use). +pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) { + let message = if used { + tl!("One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed.") + } else { + tl!("Delete the brush selection?") + }; + app.ui.dialog = Some(Dialog::new(KIND, json!({"params": params, "used": used, "message": message}))); +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let mut action = DialogAction::None; + ui.horizontal(|ui| { + if d.bool("used") { + if widgets::primary_button_enabled(ui, tl!("Remove Strokes"), true).clicked() { + action = DialogAction::Confirm; + } + if widgets::secondary_button(ui, tl!("Cancel")).clicked() { + action = DialogAction::Cancel; + } + } else { + if widgets::primary_button_enabled(ui, tl!("Yes"), true).clicked() { + action = DialogAction::Confirm; + } + if widgets::secondary_button(ui, tl!("No")).clicked() { + action = DialogAction::Cancel; + } + } + }); + action +} + +/// Closes before running, so a dialog the command opens stays open. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let params = d.fields.get("params").cloned().unwrap_or_else(|| json!({})); + app.ui.dialog = None; + app.run("brush.delete", params) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs new file mode 100644 index 0000000000..407351c794 --- /dev/null +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -0,0 +1,71 @@ +use egui::{Pos2, Rect, pos2, vec2}; +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +use super::*; + +fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec, time: f64) -> egui::FullOutput { + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let input = egui::RawInput { screen_rect, time: Some(time), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + out +} + +fn press(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, time: f64) { + frame(ctx, app, vec![], time); + let out = frame(ctx, app, vec![], time + 0.1); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("dialog accessibility tree").nodes; + let button = nodes.iter().find(|(_, node)| node.label().map(str::trim) == Some(label)); + let bounds = button.and_then(|(_, node)| node.bounds()).expect("visible button"); + let at = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true), button(false)], time + 0.2); +} + +fn context() -> egui::Context { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + ctx +} + +#[test] +fn visible_yes_and_no_buttons_control_unused_deletion() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let name = app.run("brush.list", json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string(); + let ctx = context(); + let before = app.session.active().unwrap().history.undo.len(); + ask(&mut app, json!({"name": name}), false); + press(&ctx, &mut app, "No", 0.0); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); + assert!(app.run("brush.get", json!({"name": name})).is_ok()); + ask(&mut app, json!({"name": name}), false); + press(&ctx, &mut app, "Yes", 1.0); + assert!(app.run("brush.get", json!({"name": name})).is_err()); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); +} + +#[test] +fn visible_remove_strokes_and_cancel_buttons_control_used_deletion() { + for choice in ["Cancel", "Remove Strokes"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let path = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap()); + let name = "10 pt. Oval"; + app.run("brush.apply", json!({"name": name})).unwrap(); + let before = app.session.active().unwrap().history.undo.len(); + let ctx = context(); + ask(&mut app, json!({"name": name}), true); + press(&ctx, &mut app, choice, 0.0); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + usize::from(choice != "Cancel")); + let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); + assert_eq!(stroke.brush.as_deref(), (choice == "Cancel").then_some(name)); + assert!(stroke.width > 0.0); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 5a5efddad2..e423aab1a6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -742,8 +742,6 @@ font-technology Variable Променливи Yes Да No Не Delete Tab Изтриване на табулация - Delete the brush “{name}”? Да се изтрие четката „{name}“? - Strokes using deleted brushes become plain strokes. Щрихите, които използват изтритите четки, стават обикновени щрихи. Delete the graphic style “{name}”? Изтриване на графичния стил „{name}“? Delete Theme Изтриване на тема Delete theme Изтриване на тема @@ -5901,6 +5899,11 @@ breakText Glyphs Глифи Gap 4 Разстояние 4 Dash 5 Тире 5 Gap 5 Разстояние 5 + Delete the brush selection? Да се изтрият избраните четки? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Една или повече от четките се използват и не могат да бъдат изтрити, докато щрихите им не бъдат разширени или премахнати. + Remove Strokes Премахване на щрихи + Yes Да + No Не # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Инструменти за подреждане Arrange in Grid… Подреждане в мрежа… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index da8c5d134e..6b48514683 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5931,6 +5931,11 @@ shape Open Otvoren @msg `follow` must be "average", "a" or "b" `follow` mora biti "average", "a" ili "b" @msg the paths have nothing to merge there putanje tu nemaju šta spojiti @msg the path is locked or hidden putanja je zaključana ili skrivena + Delete the brush selection? Izbrisati odabrane četkice? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Jedna ili više četkica se koristi i ne mogu se izbrisati dok se njihovi potezi ne prošire ili uklone. + Remove Strokes Ukloni poteze + Yes Da + No Ne # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Alati za raspoređivanje Arrange in Grid… Rasporedi u mrežu… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index cd1046755c..970625ac0e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1059,8 +1059,6 @@ Yes Sí No No Delete Tab Suprimeix la tabulació - Delete the brush “{name}”? Voleu suprimir el pinzell “{name}”? - Strokes using deleted brushes become plain strokes. Els traços que utilitzen pinzells suprimits esdevenen traços normals. Delete the graphic style “{name}”? Voleu suprimir l’estil gràfic “{name}”? Delete the library “{name}”? Voleu suprimir la biblioteca “{name}”? Delete Theme Suprimeix el tema @@ -6001,6 +5999,11 @@ breakText Glyphs Glifs Gap 4 Separació 4 Dash 5 Guió 5 Gap 5 Separació 5 + Delete the brush selection? Voleu suprimir la selecció de pinzells? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Un o més pinzells estan en ús i no es poden suprimir fins que els traços s’expandeixin o s’eliminin. + Remove Strokes Elimina els traços + Yes Sí + No No # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Eines d’organització Arrange in Grid… Organitza en quadrícula… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4ffe67aea9..bc8c6b09bd 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1558,8 +1558,6 @@ lighting Light Světlo Reverse Gradient Obrátit přechod Save to Swatches Uložit do vzorníku Delete Graphic Style (Alt-click: without asking) Odstranit grafický styl (Alt+kliknutí: bez dotazu) - Delete the brush “{name}”? Odstranit štětec „{name}“? - Strokes using deleted brushes become plain strokes. Tahy používající odstraněné štětce se změní na běžné tahy. Delete the graphic style “{name}”? Odstranit grafický styl „{name}“? Delete these {n} graphic styles? Odstranit tyto grafické styly ({n})? Delete this {n} graphic style? Odstranit tento grafický styl ({n})? @@ -6010,6 +6008,11 @@ breakText Glyphs Glyfy Gap 4 Mezera 4 Dash 5 Čárka 5 Gap 5 Mezera 5 + Delete the brush selection? Odstranit vybrané štětce? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Jeden nebo více štětců se používá a nelze je odstranit, dokud jejich tahy nebudou rozloženy nebo odebrány. + Remove Strokes Odebrat tahy + Yes Ano + No Ne # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Nástroje uspořádání Arrange in Grid… Uspořádat do mřížky… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index bce83c7bd6..fc45ef6e51 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1472,8 +1472,6 @@ lighting Light Lys Reverse Gradient Omvend gradient Save to Swatches Gem i farveprøver Delete Graphic Style (Alt-click: without asking) Slet grafisk typografi (Alt-klik: uden at spørge) - Delete the brush “{name}”? Slet penslen »{name}«? - Strokes using deleted brushes become plain strokes. Streger, der bruger slettede pensler, bliver almindelige streger. Delete the graphic style “{name}”? Slet den grafiske typografi »{name}«? Delete these {n} graphic styles? Slet disse {n} grafiske typografier? Delete this {n} graphic style? Slet denne {n} grafiske typografi? @@ -5915,6 +5913,11 @@ breakText Glyphs Glyffer Gap 4 Mellemrum 4 Dash 5 Streg 5 Gap 5 Mellemrum 5 + Delete the brush selection? Slet de valgte pensler? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. En eller flere pensler er i brug og kan ikke slettes, før deres streger er udvidet eller fjernet. + Remove Strokes Fjern streger + Yes Ja + No Nej # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Arrangeringsværktøjer Arrange in Grid… Arrangér i gitter… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9e837d8eb6..a36a57825e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -736,8 +736,6 @@ font-technology Variable Variabel Yes Ja No Nein Delete Tab Tabulator löschen - Delete the brush “{name}”? Pinsel „{name}“ löschen? - Strokes using deleted brushes become plain strokes. Konturen mit gelöschten Pinseln werden zu einfachen Konturen. Delete the graphic style “{name}”? Grafikstil „{name}“ löschen? Delete Theme Thema löschen Delete theme Thema löschen @@ -5596,6 +5594,11 @@ breakText Glyphs Glyphen Gap 4 Lücke 4 Dash 5 Strich 5 Gap 5 Lücke 5 + Delete the brush selection? Ausgewählte Pinsel löschen? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Ein oder mehrere Pinsel werden verwendet und können erst gelöscht werden, wenn ihre Konturen umgewandelt oder entfernt wurden. + Remove Strokes Konturen entfernen + Yes Ja + No Nein # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Anordnungswerkzeuge Arrange in Grid… In Raster anordnen… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e5ac837751..7c9b2fa5c8 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -716,8 +716,6 @@ font-technology Variable Μεταβλητές Yes Ναι No Όχι Delete Tab Διαγραφή στηλοθέτη - Delete the brush “{name}”? Να διαγραφεί το πινέλο «{name}»; - Strokes using deleted brushes become plain strokes. Οι πινελιές που χρησιμοποιούν διαγραμμένα πινέλα γίνονται απλές πινελιές. Delete the graphic style “{name}”? Να διαγραφεί το στυλ γραφικών «{name}»; Delete Theme Διαγραφή θέματος Delete theme Διαγραφή θέματος @@ -5963,6 +5961,11 @@ breakText Glyphs Γλύφοι Gap 4 Διάκενο 4 Dash 5 Παύλα 5 Gap 5 Διάκενο 5 + Delete the brush selection? Να διαγραφούν τα επιλεγμένα πινέλα; + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Ένα ή περισσότερα πινέλα χρησιμοποιούνται και δεν μπορούν να διαγραφούν μέχρι να επεκταθούν ή να αφαιρεθούν τα περιγράμματά τους. + Remove Strokes Αφαίρεση περιγραμμάτων + Yes Ναι + No Όχι # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Εργαλεία διάταξης Arrange in Grid… Διάταξη σε πλέγμα… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 367692be2f..70e009d067 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -757,8 +757,6 @@ font-technology Variable Variables Yes Sí No No Delete Tab Eliminar tabulación - Delete the brush “{name}”? ¿Eliminar el pincel “{name}”? - Strokes using deleted brushes become plain strokes. Los trazos que usan pinceles eliminados se convierten en trazos simples. Delete the graphic style “{name}”? ¿Eliminar el estilo gráfico “{name}”? Delete Theme Eliminar tema Delete theme Eliminar tema @@ -5953,6 +5951,11 @@ breakText Glyphs Glifos Gap 4 Hueco 4 Dash 5 Guion 5 Gap 5 Hueco 5 + Delete the brush selection? ¿Eliminar los pinceles seleccionados? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Uno o más pinceles están en uso y no se pueden eliminar hasta expandir o quitar sus trazos. + Remove Strokes Quitar trazos + Yes Sí + No No # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Herramientas de organización Arrange in Grid… Organizar en cuadrícula… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d0b30760ac..51e68665ba 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1532,8 +1532,6 @@ lighting Light Valo Reverse Gradient Käännä liukuväri Save to Swatches Tallenna värimalleihin Delete Graphic Style (Alt-click: without asking) Poista grafiikkatyyli (Alt-napsautus: kysymättä) - Delete the brush “{name}”? Poistetaanko sivellin ”{name}”? - Strokes using deleted brushes become plain strokes. Poistettuja siveltimiä käyttävät viivat muuttuvat tavallisiksi viivoiksi. Delete the graphic style “{name}”? Poistetaanko grafiikkatyyli ”{name}”? Delete these {n} graphic styles? Poistetaanko nämä {n} grafiikkatyyliä? Delete this {n} graphic style? Poistetaanko tämä {n} grafiikkatyyli? @@ -6041,6 +6039,11 @@ breakText Glyphs Merkit Gap 4 Väli 4 Dash 5 Viiva 5 Gap 5 Väli 5 + Delete the brush selection? Poistetaanko valitut siveltimet? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Yksi tai useampi sivellin on käytössä eikä niitä voi poistaa ennen kuin niiden viivat on laajennettu tai poistettu. + Remove Strokes Poista viivat + Yes Kyllä + No Ei # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Järjestelytyökalut Arrange in Grid… Järjestä ruudukkoon… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ab5fc9acd1..0c355f4785 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -759,8 +759,6 @@ font-technology Variable Variables Yes Oui No Non Delete Tab Supprimer la tabulation - Delete the brush “{name}”? Supprimer la forme « {name} » ? - Strokes using deleted brushes become plain strokes. Les contours utilisant des formes supprimées deviennent des contours simples. Delete the graphic style “{name}”? Supprimer le style graphique « {name} » ? Delete Theme Supprimer le thème Delete theme Supprimer le thème @@ -3703,7 +3701,6 @@ imageTrace Outline Contour @plural {n} item|{n} items {n} élément|{n} éléments @plural Color Table ({n} color)|Color Table ({n} colors) Table des couleurs ({n} couleur)|Table des couleurs ({n} couleurs) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Supprimer {n} style graphique ?|Supprimer ces {n} styles graphiques ? -@plural Delete this {n} brush?|Delete these {n} brushes? Supprimer {n} forme ?|Supprimer ces {n} formes ? @plural {n} Layer|{n} Layers {n} calque|{n} calques @plural {n} Object|{n} Objects {n} objet|{n} objets @plural {n} area highlighted|{n} areas highlighted {n} zone mise en évidence|{n} zones mises en évidence @@ -6009,6 +6006,11 @@ breakText Glyphs Glyphes Gap 4 Écart 4 Dash 5 Tiret 5 Gap 5 Écart 5 + Delete the brush selection? Supprimer les formes sélectionnées ? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Une ou plusieurs formes sont utilisées et ne peuvent pas être supprimées tant que leurs contours ne sont pas décomposés ou supprimés. + Remove Strokes Supprimer les contours + Yes Oui + No Non # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Outils de disposition Arrange in Grid… Disposer en grille… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e91e7dfe56..965e4ddb27 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -981,8 +981,6 @@ font-technology Variable Változó Yes Igen No Nem Delete Tab Tabulátor törlése - Delete the brush “{name}”? Törlöd ezt az ecsetet: „{name}”? - Strokes using deleted brushes become plain strokes. A törölt ecseteket használó körvonalak egyszerű körvonalakká válnak. Delete the graphic style “{name}”? Törlöd ezt a grafikai stílust: „{name}”? Delete the library “{name}”? Törlöd ezt a könyvtárat: „{name}”? Delete Theme Téma törlése @@ -5997,6 +5995,11 @@ breakText Glyphs Glifák Gap 4 Hézag 4 Dash 5 Vonal 5 Gap 5 Hézag 5 + Delete the brush selection? Törlöd a kijelölt ecseteket? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Egy vagy több ecset használatban van, és nem törölhető, amíg a körvonalait ki nem bontod vagy el nem távolítod. + Remove Strokes Körvonalak eltávolítása + Yes Igen + No Nem # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Elrendezőeszközök Arrange in Grid… Elrendezés rácsba… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 265da6fbee..ebfdabf544 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1472,8 +1472,6 @@ lighting Light Cahaya Reverse Gradient Balikkan gradien Save to Swatches Simpan ke swatch Delete Graphic Style (Alt-click: without asking) Hapus gaya grafis (Alt+klik: tanpa konfirmasi) - Delete the brush “{name}”? Hapus kuas “{name}”? - Strokes using deleted brushes become plain strokes. Goresan yang menggunakan kuas terhapus menjadi goresan biasa. Delete the graphic style “{name}”? Hapus gaya grafis “{name}”? Delete these {n} graphic styles? Hapus {n} gaya grafis ini? Delete this {n} graphic style? Hapus {n} gaya grafis ini? @@ -5915,6 +5913,11 @@ breakText Glyphs Glif Gap 4 Jarak 4 Dash 5 Garis 5 Gap 5 Jarak 5 + Delete the brush selection? Hapus kuas yang dipilih? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Satu atau beberapa kuas sedang digunakan dan tidak dapat dihapus sampai stroke-nya diperluas atau dihapus. + Remove Strokes Hapus Stroke + Yes Ya + No Tidak # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Alat penyusunan Arrange in Grid… Susun dalam grid… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index af6874bbe8..ffc95c4da3 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -757,8 +757,6 @@ font-technology Variable Variabili Yes Sì No No Delete Tab Elimina tabulazione - Delete the brush “{name}”? Eliminare il pennello “{name}”? - Strokes using deleted brushes become plain strokes. I tracciati che usano pennelli eliminati diventano tracciati semplici. Delete the graphic style “{name}”? Eliminare lo stile grafico “{name}”? Delete Theme Elimina tema Delete theme Elimina tema @@ -5630,6 +5628,11 @@ breakText Glyphs Glifi Gap 4 Spazio 4 Dash 5 Tratto 5 Gap 5 Spazio 5 + Delete the brush selection? Eliminare i pennelli selezionati? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Uno o più pennelli sono in uso e non possono essere eliminati finché le tracce non vengono espanse o rimosse. + Remove Strokes Rimuovi tracce + Yes Sì + No No # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Strumenti di disposizione Arrange in Grid… Disponi in griglia… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f9ad60b875..754362ef57 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1308,8 +1308,6 @@ font-technology Variable バリアブル Delete Transparency Flattener Preset 透明の分割・統合プリセットを削除 Delete Width Point 幅ポイントを削除 Delete Workspace ワークスペースを削除 - Delete the brush “{name}”? ブラシ「{name}」を削除しますか? - Strokes using deleted brushes become plain strokes. 削除したブラシを使用する線は通常の線になります。 Delete the graphic style “{name}”? グラフィックスタイル「{name}」を削除しますか? Delete theme テーマを削除 Delete this saved preset この保存済みプリセットを削除 @@ -5696,6 +5694,11 @@ breakText Glyphs 字形 Gap 4 間隔 4 Dash 5 線分 5 Gap 5 間隔 5 + Delete the brush selection? 選択したブラシを削除しますか? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 使用中のブラシが含まれています。線を拡張または削除するまでブラシを削除できません。 + Remove Strokes 線を削除 + Yes はい + No いいえ # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 配置ツール Arrange in Grid… グリッドに配置… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 7f6eb84ba3..b07dfd7fca 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1389,8 +1389,6 @@ lighting Light სინათლე Reverse Gradient გრადიენტის შებრუნება Save to Swatches ფერის ნიმუშებში შენახვა Delete Graphic Style (Alt-click: without asking) გრაფიკული სტილის წაშლა (Alt-დაწკაპუნებით: დაუკითხავად) - Delete the brush “{name}”? წაიშალოს ფუნჯი „{name}“? - Strokes using deleted brushes become plain strokes. წაშლილი ფუნჯებით დახატული შტრიხები ჩვეულებრივ შტრიხებად იქცევა. Delete the graphic style “{name}”? წაიშალოს გრაფიკული სტილი „{name}“? Delete these {n} graphic styles? წაიშალოს ეს გრაფიკული სტილები ({n})? Delete this {n} graphic style? წაიშალოს ეს გრაფიკული სტილი ({n})? @@ -6000,6 +5998,11 @@ breakText Glyphs გლიფები Gap 4 შუალედი 4 Dash 5 ტირე 5 Gap 5 შუალედი 5 + Delete the brush selection? წაიშალოს არჩეული ფუნჯები? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. ერთი ან მეტი ფუნჯი გამოიყენება და მათი წაშლა შეუძლებელია, სანამ კონტურები არ გაიშლება ან არ მოიხსნება. + Remove Strokes კონტურების მოხსნა + Yes დიახ + No არა # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools განლაგების ხელსაწყოები Arrange in Grid… ბადეში განლაგება… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a64392ef3b..e487667b56 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1299,8 +1299,6 @@ font-technology Variable 가변 Delete Transparency Flattener Preset 투명도 병합 프리셋 삭제 Delete Width Point 너비 포인트 삭제 Delete Workspace 작업 영역 삭제 - Delete the brush “{name}”? 브러시 “{name}”을(를) 삭제하시겠습니까? - Strokes using deleted brushes become plain strokes. 삭제된 브러시를 사용한 선은 일반 선이 됩니다. Delete the graphic style “{name}”? 그래픽 스타일 “{name}”을(를) 삭제하시겠습니까? Delete theme 테마 삭제 Delete this saved preset 저장된 이 프리셋 삭제 @@ -5593,6 +5591,11 @@ breakText Glyphs 글리프 Gap 4 간격 4 Dash 5 대시 5 Gap 5 간격 5 + Delete the brush selection? 선택한 브러시를 삭제하시겠습니까? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 하나 이상의 브러시가 사용 중이며 선을 확장하거나 제거할 때까지 삭제할 수 없습니다. + Remove Strokes 선 제거 + Yes 예 + No 아니요 # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 배치 도구 Arrange in Grid… 격자로 배치… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ed254e2a19..71d7a6d732 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1486,8 +1486,6 @@ lighting Light Licht Reverse Gradient Verloop omkeren Save to Swatches Opslaan in stalen Delete Graphic Style (Alt-click: without asking) Grafische stijl verwijderen (Alt-klik: zonder vragen) - Delete the brush “{name}”? Kwast „{name}” verwijderen? - Strokes using deleted brushes become plain strokes. Lijnen die verwijderde kwasten gebruiken, worden gewone lijnen. Delete the graphic style “{name}”? De grafische stijl „{name}” verwijderen? Delete these {n} graphic styles? Deze {n} grafische stijlen verwijderen? Delete this {n} graphic style? Deze {n} grafische stijl verwijderen? @@ -5959,6 +5957,11 @@ breakText Glyphs Glyphs Gap 4 Tussenruimte 4 Dash 5 Streepje 5 Gap 5 Tussenruimte 5 + Delete the brush selection? Geselecteerde kwasten verwijderen? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Een of meer kwasten zijn in gebruik en kunnen pas worden verwijderd als hun contouren zijn uitgebreid of verwijderd. + Remove Strokes Contouren verwijderen + Yes Ja + No Nee # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Schikgereedschappen Arrange in Grid… In raster schikken… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f2e5c5964b..7a606131ff 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1472,8 +1472,6 @@ lighting Light Światło Reverse Gradient Odwróć gradient Save to Swatches Zapisz w próbkach Delete Graphic Style (Alt-click: without asking) Usuń styl graficzny (kliknięcie z Alt: bez pytania) - Delete the brush “{name}”? Usunąć pędzel „{name}”? - Strokes using deleted brushes become plain strokes. Obrysy używające usuniętych pędzli stają się zwykłymi obrysami. Delete the graphic style “{name}”? Usunąć styl graficzny „{name}”? Delete these {n} graphic styles? Usunąć te style graficzne ({n})? Delete this {n} graphic style? Usunąć ten styl graficzny ({n})? @@ -5866,6 +5864,11 @@ breakText Glyphs Glify Gap 4 Odstęp 4 Dash 5 Kreska 5 Gap 5 Odstęp 5 + Delete the brush selection? Usunąć zaznaczone pędzle? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Co najmniej jeden pędzel jest używany i nie można go usunąć, dopóki jego obrysy nie zostaną rozszerzone lub usunięte. + Remove Strokes Usuń obrysy + Yes Tak + No Nie # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Narzędzia układania Arrange in Grid… Ułóż w siatce… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4d39287c57..e1044cbbd7 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -674,8 +674,6 @@ Delete Transparency Flattener Preset Excluir Predefinido de Achatamento de Transparência Delete Width Point Excluir Ponto de Largura Delete Workspace Excluir Espaço de Trabalho - Delete the brush “{name}”? Excluir o pincel “{name}”? - Strokes using deleted brushes become plain strokes. Traços que usam pincéis excluídos tornam-se traços simples. Delete the graphic style “{name}”? Excluir o estilo gráfico “{name}”? Delete theme Excluir tema Delete this saved preset Excluir este predefinido salvo @@ -5930,6 +5928,11 @@ breakText Glyphs Glifos Gap 4 Lacuna 4 Dash 5 Traço 5 Gap 5 Lacuna 5 + Delete the brush selection? Excluir os pincéis selecionados? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Um ou mais pincéis estão em uso e não podem ser excluídos até que seus traçados sejam expandidos ou removidos. + Remove Strokes Remover Traçados + Yes Sim + No Não # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Ferramentas de Organização Arrange in Grid… Organizar em Grade… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 952171bbf1..d9cede6983 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -755,8 +755,6 @@ font-technology Variable Вариативные Yes Да No Нет Delete Tab Удалить табуляцию - Delete the brush “{name}”? Удалить кисть «{name}»? - Strokes using deleted brushes become plain strokes. Обводки, использующие удалённые кисти, становятся обычными обводками. Delete the graphic style “{name}”? Удалить графический стиль «{name}»? Delete Theme Удалить тему Delete theme Удалить тему @@ -5988,6 +5986,11 @@ breakText Glyphs Глифы Gap 4 Зазор 4 Dash 5 Штрих 5 Gap 5 Зазор 5 + Delete the brush selection? Удалить выбранные кисти? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Одна или несколько кистей используются и не могут быть удалены, пока их обводки не будут разобраны или убраны. + Remove Strokes Убрать обводки + Yes Да + No Нет # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Инструменты размещения Arrange in Grid… Разместить по сетке… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9f24f8e02c..68239d409b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -744,8 +744,6 @@ font-technology Variable Variabla Yes Ja No Nej Delete Tab Radera tabb - Delete the brush “{name}”? Radera penseln ”{name}”? - Strokes using deleted brushes become plain strokes. Linjer som använder borttagna penslar blir vanliga linjer. Delete the graphic style “{name}”? Radera grafikstilen ”{name}”? Delete Theme Radera tema Delete theme Radera tema @@ -6063,6 +6061,11 @@ breakText Glyphs Glyfer Gap 4 Mellanrum 4 Dash 5 Streck 5 Gap 5 Mellanrum 5 + Delete the brush selection? Radera de valda penslarna? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. En eller flera penslar används och kan inte raderas förrän deras konturer har expanderats eller tagits bort. + Remove Strokes Ta bort konturer + Yes Ja + No Nej # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Ordningsverktyg Arrange in Grid… Ordna i rutnät… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 91fd8143d1..44cc14ba51 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -736,8 +736,6 @@ font-technology Variable Değişken Yes Evet No Hayır Delete Tab Sekmeyi Sil - Delete the brush “{name}”? “{name}” fırçası silinsin mi? - Strokes using deleted brushes become plain strokes. Silinen fırçaları kullanan konturlar düz konturlara dönüşür. Delete the graphic style “{name}”? “{name}” grafik stili silinsin mi? Delete Theme Temayı Sil Delete theme Temayı sil @@ -5968,6 +5966,11 @@ breakText Glyphs Glifler Gap 4 Boşluk 4 Dash 5 Çizgi 5 Gap 5 Boşluk 5 + Delete the brush selection? Seçili fırçalar silinsin mi? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Bir veya daha fazla fırça kullanılıyor ve konturları genişletilmeden veya kaldırılmadan silinemez. + Remove Strokes Konturları Kaldır + Yes Evet + No Hayır # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Düzenleme Araçları Arrange in Grid… Izgarada Düzenle… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 750796afe1..271b96793e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -751,8 +751,6 @@ font-technology Variable Варіативні Yes Так No Ні Delete Tab Видалити табуляцію - Delete the brush “{name}”? Видалити пензель «{name}»? - Strokes using deleted brushes become plain strokes. Обведення, що використовують видалені пензлі, стають звичайними обведеннями. Delete the graphic style “{name}”? Видалити графічний стиль «{name}»? Delete Theme Видалити тему Delete theme Видалити тему @@ -5610,6 +5608,11 @@ breakText Glyphs Гліфи Gap 4 Проміжок 4 Dash 5 Штрих 5 Gap 5 Проміжок 5 + Delete the brush selection? Видалити вибрані пензлі? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Один або кілька пензлів використовуються і не можуть бути видалені, доки їхні обведення не буде розібрано або забрано. + Remove Strokes Забрати обведення + Yes Так + No Ні # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Інструменти розміщення Arrange in Grid… Розмістити сіткою… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 494b40265c..66978c3703 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -877,8 +877,6 @@ font-technology Variable Biến thiên Yes Có No Không Delete Tab Xóa tab - Delete the brush “{name}”? Xóa cọ “{name}”? - Strokes using deleted brushes become plain strokes. Các nét dùng cọ đã xóa trở thành nét thông thường. Delete the graphic style “{name}”? Xóa kiểu đồ họa “{name}”? Delete the library “{name}”? Xóa thư viện “{name}”? Delete Theme Xóa bộ màu @@ -5612,6 +5610,11 @@ breakText Glyphs Glyph Gap 4 Khoảng hở 4 Dash 5 Nét 5 Gap 5 Khoảng hở 5 + Delete the brush selection? Xóa các cọ đã chọn? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Một hoặc nhiều cọ đang được sử dụng và không thể xóa cho đến khi nét được mở rộng hoặc gỡ bỏ. + Remove Strokes Gỡ nét + Yes Có + No Không # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Công cụ sắp xếp Arrange in Grid… Sắp xếp theo lưới… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 105fefd26d..85e1ffd3d9 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -700,8 +700,6 @@ Yes 是 No 否 Delete Tab 删除制表位 - Delete the brush “{name}”? 要删除画笔“{name}”吗? - Strokes using deleted brushes become plain strokes. 使用已删除画笔的描边会变成普通描边。 Delete the graphic style “{name}”? 要删除图形样式“{name}”吗? Delete Theme 删除主题 Delete theme 删除主题 @@ -5852,6 +5850,11 @@ breakText Glyphs 字形 Gap 4 间隔 4 Dash 5 虚线 5 Gap 5 间隔 5 + Delete the brush selection? 删除选中的画笔吗? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 一个或多个画笔正在使用中,必须先扩展或移除其描边才能删除。 + Remove Strokes 移除描边 + Yes 是 + No 否 # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 排列工具 Arrange in Grid… 按网格排列… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7ffb1831a4..44e077e904 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -719,8 +719,6 @@ font-technology Variable 可變 Yes 是 No 否 Delete Tab 刪除定位點 - Delete the brush “{name}”? 要刪除筆刷「{name}」嗎? - Strokes using deleted brushes become plain strokes. 使用已刪除筆刷的筆畫會變成一般筆畫。 Delete the graphic style “{name}”? 要刪除繪圖樣式「{name}」嗎? Delete Theme 刪除主題 Delete theme 刪除主題 @@ -5649,6 +5647,11 @@ breakText Glyphs 字符 Gap 4 間隙 4 Dash 5 虛線 5 Gap 5 間隙 5 + Delete the brush selection? 要刪除選取的筆刷嗎? + One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 一個或多個筆刷正在使用中,必須先擴展或移除其筆畫才能刪除。 + Remove Strokes 移除筆畫 + Yes 是 + No 否 # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 排列工具 Arrange in Grid… 依格狀排列… diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index b734047305..279677527f 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -204,9 +204,15 @@ fn run_on(app: &mut VectorcraftApp, id: &str, names: &[String]) { app.run(id, p).ok(); } -/// Delete `names` after asking, or immediately when the bottom button was Alt-clicked. +/// Delete `names` after asking: Yes or No when none of them is in use, else Remove Strokes or +/// Cancel. With `now` (Alt-click on the bottom button), brushes that are not in use go at once. fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { - if now { + let Ok(unused) = app.run("brush.unused", json!({})) else { + return; + }; + let unused = unused.get("names").and_then(Value::as_array).cloned().unwrap_or_default(); + let used = names.iter().any(|name| !unused.iter().any(|n| n.as_str() == Some(name))); + if now && !used { run_on(app, "brush.delete", names); return; } @@ -214,11 +220,7 @@ fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { [name] => json!({ "name": name }), _ => json!({ "names": names }), }; - let message = match names { - [name] => crate::i18n::fmt(tl!("Delete the brush “{name}”?"), &[("name", name)]), - _ => crate::i18n::tn(names.len() as u64, "Delete this {n} brush?", "Delete these {n} brushes?"), - }; - crate::dialogs::confirm::ask(app, &message, tl!("Strokes using deleted brushes become plain strokes."), "brush.delete", params); + crate::dialogs::brush_delete::ask(app, params, used); } /// The names in `list` in the order the panel shows them: by type in [`KINDS`] order, without the diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index 421c0162a4..c4b794677a 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -158,22 +158,25 @@ fn delete_button(ctx: &egui::Context, app: &mut VectorcraftApp, modifiers: egui: fn assert_delete_dialog(app: &VectorcraftApp, message: &str) { let d = app.ui.dialog.as_ref().expect("Delete Brush asks first"); - assert_eq!(d.kind, crate::dialogs::confirm::KIND); + assert_eq!(d.kind, crate::dialogs::brush_delete::KIND); assert_eq!(d.str("message"), message); - assert_eq!(d.str("detail"), "Strokes using deleted brushes become plain strokes."); + assert_eq!(d.bool("used"), message.starts_with("One or more")); } +/// Deleting several unused brushes asks one question about the selection, with no count in it. #[test] -fn deleting_five_brushes_uses_polish_many_form() { +fn deleting_five_brushes_uses_one_selection_question() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let five: Vec = names(&mut app).into_iter().take(5).collect(); + assert_eq!(five.len(), 5); let previous = crate::i18n::current(); let polish = crate::i18n::Lang::from_code("pl").unwrap(); crate::i18n::set_current(polish); - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let names: Vec = (1..=5).map(|n| format!("Brush {n}")).collect(); - delete(&mut app, &names, false); + delete(&mut app, &five, false); let message = app.ui.dialog.as_ref().map(|d| d.str("message")); crate::i18n::set_current(previous); - assert_eq!(message, Some("Usunąć 5 pędzli?".to_string())); + assert_eq!(message, Some("Usunąć zaznaczone pędzle?".to_string())); } /// Click the panel menu's item `label` (frames at `time`, `time + 0.5`). @@ -223,7 +226,7 @@ fn shift_and_command_clicks_select_brushes_for_delete_and_duplicate() { assert_eq!(undo_count(&app), before.1 + 1); // The bottom bar's last button, Delete Brush. delete_button(&ctx, &mut app, egui::Modifiers::NONE, 5.0); - assert_delete_dialog(&app, "Delete these 2 brushes?"); + assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); assert_eq!(names(&mut app), [before.0.clone(), copies.to_vec()].concat()); assert_eq!(brush_of(&app, rect).as_deref(), Some(three[0].as_str())); assert_eq!(undo_count(&app), before.1 + 1); @@ -263,7 +266,7 @@ fn selecting_other_art_ends_the_brush_multi_selection() { let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 4.0, show); assert_eq!(lit_tiles(&out), [1]); menu_click(&ctx, &mut app, "Delete Brush", 5.0); - assert_delete_dialog(&app, &format!("Delete the brush “{}”?", three[1])); + assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); assert!(names(&mut app).contains(&three[1])); crate::dialogs::confirm(&mut app).unwrap(); let left = names(&mut app); @@ -332,7 +335,7 @@ fn select_all_unused_selects_the_brushes_no_stroke_paints_with() { let on: Vec = (0..tiles.len()).filter(|i| lit(&ctx, &out).contains(&tiles[*i])).collect(); assert_eq!(on, (0..tiles.len()).filter(|i| *i != 1).collect::>()); menu_click(&ctx, &mut app, "Delete Brush", 3.0); - assert_delete_dialog(&app, &format!("Delete these {} brushes?", list.len() - 1)); + assert_delete_dialog(&app, "Delete the brush selection?"); assert_eq!(names(&mut app).len(), list.len()); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(names(&mut app), [list[1].0.clone()]); @@ -349,7 +352,7 @@ fn delete_button_cancel_keeps_selected_brushes_strokes_and_history() { let (three, _) = select_three(&ctx, &mut app, rect); let before = (names(&mut app), brush_of(&app, rect), undo_count(&app)); delete_button(&ctx, &mut app, egui::Modifiers::NONE, 3.0); - assert_delete_dialog(&app, "Delete these 3 brushes?"); + assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); assert_eq!((names(&mut app), brush_of(&app, rect), undo_count(&app)), before); crate::dialogs::cancel(&mut app); assert!(app.ui.dialog.is_none()); @@ -364,7 +367,7 @@ fn delete_button_cancel_keeps_selected_brushes_strokes_and_history() { } #[test] -fn alt_delete_button_removes_selected_brushes_without_dialog() { +fn alt_delete_button_asks_when_a_selected_brush_is_used() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); let rect = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap()); @@ -373,16 +376,56 @@ fn alt_delete_button_removes_selected_brushes_without_dialog() { let (three, _) = select_three(&ctx, &mut app, rect); let before = undo_count(&app); delete_button(&ctx, &mut app, egui::Modifiers::NONE, 3.0); - assert_delete_dialog(&app, "Delete these 3 brushes?"); + assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); crate::dialogs::cancel(&mut app); delete_button(&ctx, &mut app, egui::Modifiers::ALT, 4.0); - assert!(app.ui.dialog.is_none()); + assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + crate::dialogs::cancel(&mut app); let left = names(&mut app); - assert!(three.iter().all(|name| !left.contains(name))); - assert_eq!(brush_of(&app, rect), None); + assert!(three.iter().all(|name| left.contains(name))); + assert_eq!(brush_of(&app, rect).as_deref(), Some(three[0].as_str())); + assert_eq!(undo_count(&app), before); +} + +#[test] +fn alt_delete_button_deletes_unused_brush_without_a_question() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let first = names(&mut app)[0].clone(); + let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 0.0, show); + let tile = clickable(&out).into_iter().find(|(label, _)| label.as_deref() == Some(first.as_str())).expect("brush tile").1.center(); + click(&ctx, &mut app, tile, egui::Modifiers::NONE, 1.0, show); + let before = undo_count(&app); + delete_button(&ctx, &mut app, egui::Modifiers::ALT, 2.0); + assert!(app.ui.dialog.is_none()); + assert!(!names(&mut app).contains(&first)); assert_eq!(undo_count(&app), before + 1); } +#[test] +fn menu_delete_used_brush_requires_remove_strokes_or_cancel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let rect = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap()); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let (three, _) = select_three(&ctx, &mut app, rect); + let before = undo_count(&app); + menu_click(&ctx, &mut app, "Delete Brush", 3.0); + assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + crate::dialogs::cancel(&mut app); + assert_eq!(undo_count(&app), before); + assert_eq!(brush_of(&app, rect).as_deref(), Some(three[0].as_str())); + menu_click(&ctx, &mut app, "Delete Brush", 4.0); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(undo_count(&app), before + 1); + assert_eq!(brush_of(&app, rect), None); + assert!(app.session.active().unwrap().doc.node(rect).unwrap().appearance.stroke().is_some()); + assert!(three.iter().all(|name| !names(&mut app).contains(name))); +} + #[test] fn art_dropped_on_the_panel_becomes_an_art_brush_and_a_brush_drags_out() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/docs/mcp.md b/docs/mcp.md index 6f342c98cd..1f843271e9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1557,8 +1557,10 @@ already walks Image Trace. Short agent entry points: name they are given, as `symbol.options` trims `newName`; a blank one gives "New Symbol" or " copy". - 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 and graphic styles count, and so do the strokes in the art of a brush that is used. The art of a brush - that is not used does not count, so a brush whose own art is the only art that paints with it is listed. + pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do the + strokes in the art of a brush that is used. The art of a brush that is not used does not count, so a brush whose own + art is the only art that paints with it is listed. The panel's Delete Brush asks Yes/No when every brush it deletes + is unused, and offers Remove Strokes or Cancel when one of them is in use. - Brushes: `brush.list`, `brush.get {name}`, `brush.apply {name, ids?}`, `brush.new {type, name?, params?, ids?}`, `brush.setCurrent {name}`, `brush.options {name, params?, newName?}`, `brush.delete {name} | {names}`, `brush.duplicate {name, newName?} | {names}`, `brush.freehand`, `object.expandBrush {ids?}`. `brush.new`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ab9b96f4b3..a035815286 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -962,7 +962,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). In the Brushes panel, Shift-click selects a range of brushes and Ctrl/Cmd-click adds or removes one. Delete Brush and Duplicate Brush then act on all of them (`brush.delete {names}`, `brush.duplicate {names}`). - The bottom Delete Brush button and the panel menu ask before deleting; Alt-click (Option-click on macOS) on the button deletes without asking. + The Brushes panel's Delete Brush button and panel menu item ask "Delete the brush selection?" with Yes and No when none of the brushes is in use. Alt-click (Option-click on macOS) on the button deletes them without asking, as the [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists ("Delete without confirmation (except for Layers panel)"). When a stroke uses one of the brushes, the button, Alt-click and the menu item all ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. Tests: `panels::brushes::tests`, `dialogs::brush_delete::tests`. Document Info has a Brushes category after Graphic Styles. It lists the Brushes panel's brushes, or with Selection Only it lists the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`). Document Info has a Repeat Objects category after Embedded Images. It lists each radial, grid and mirror Repeat object by name with its kind and the number of instances it makes. For a grid it gives the rows and columns instead, followed by the number of instances it draws when that is fewer. With Selection Only it lists the Repeat objects in the selection. The Document Info report and Package's report list them too (`document.info {category: "repeats"}`, `repeatObjects`). The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). From 3937473e54b40ecde00826fae336f7fb9d71ec7f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 22:11:51 -0700 Subject: [PATCH 25/70] Brushes: the Delete Brush question for brushes in use no longer mentions expanding strokes The dialog offers Remove Strokes and Cancel, so the question asks only about taking the brushes off the strokes. Both questions are reworded in every catalog. --- crates/ui-egui/src/dialogs/brush_delete.rs | 4 ++-- crates/ui-egui/src/i18n/bg.tsv | 4 ++-- crates/ui-egui/src/i18n/bs.tsv | 4 ++-- crates/ui-egui/src/i18n/ca.tsv | 4 ++-- crates/ui-egui/src/i18n/cs.tsv | 4 ++-- crates/ui-egui/src/i18n/da.tsv | 4 ++-- crates/ui-egui/src/i18n/de.tsv | 4 ++-- crates/ui-egui/src/i18n/el.tsv | 4 ++-- crates/ui-egui/src/i18n/es.tsv | 4 ++-- crates/ui-egui/src/i18n/fi.tsv | 4 ++-- crates/ui-egui/src/i18n/fr.tsv | 4 ++-- crates/ui-egui/src/i18n/hu.tsv | 4 ++-- crates/ui-egui/src/i18n/id.tsv | 4 ++-- crates/ui-egui/src/i18n/it.tsv | 4 ++-- crates/ui-egui/src/i18n/ja.tsv | 4 ++-- crates/ui-egui/src/i18n/ka.tsv | 4 ++-- crates/ui-egui/src/i18n/ko.tsv | 4 ++-- crates/ui-egui/src/i18n/nl.tsv | 4 ++-- crates/ui-egui/src/i18n/pl.tsv | 4 ++-- crates/ui-egui/src/i18n/pt-br.tsv | 4 ++-- crates/ui-egui/src/i18n/ru.tsv | 4 ++-- crates/ui-egui/src/i18n/sv.tsv | 4 ++-- crates/ui-egui/src/i18n/tr.tsv | 4 ++-- crates/ui-egui/src/i18n/uk.tsv | 4 ++-- crates/ui-egui/src/i18n/vi.tsv | 4 ++-- crates/ui-egui/src/i18n/zh-hans.tsv | 4 ++-- crates/ui-egui/src/i18n/zh-hant.tsv | 4 ++-- crates/ui-egui/src/panels/brushes/tests.rs | 19 +++++++++++-------- docs/target-app-parity.md | 2 +- 29 files changed, 66 insertions(+), 63 deletions(-) diff --git a/crates/ui-egui/src/dialogs/brush_delete.rs b/crates/ui-egui/src/dialogs/brush_delete.rs index 9488d14bec..ee4d6c964e 100644 --- a/crates/ui-egui/src/dialogs/brush_delete.rs +++ b/crates/ui-egui/src/dialogs/brush_delete.rs @@ -21,9 +21,9 @@ pub(super) const SPEC: DialogSpec = /// Ask whether to delete the brushes `params` names (`used`: one of them is in use). pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) { let message = if used { - tl!("One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed.") + tl!("Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes?") } else { - tl!("Delete the brush selection?") + tl!("Delete the selected brushes?") }; app.ui.dialog = Some(Dialog::new(KIND, json!({"params": params, "used": used, "message": message}))); } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index e423aab1a6..43cef9353d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5899,8 +5899,8 @@ breakText Glyphs Глифи Gap 4 Разстояние 4 Dash 5 Тире 5 Gap 5 Разстояние 5 - Delete the brush selection? Да се изтрият избраните четки? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Една или повече от четките се използват и не могат да бъдат изтрити, докато щрихите им не бъдат разширени или премахнати. + Delete the selected brushes? Да се изтрият избраните четки? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Щрихи използват една или повече от тези четки. Да се премахнат ли четките от тези щрихи и да се изтрият четките? Remove Strokes Премахване на щрихи Yes Да No Не diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 6b48514683..0deb3e7c36 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5931,8 +5931,8 @@ shape Open Otvoren @msg `follow` must be "average", "a" or "b" `follow` mora biti "average", "a" ili "b" @msg the paths have nothing to merge there putanje tu nemaju šta spojiti @msg the path is locked or hidden putanja je zaključana ili skrivena - Delete the brush selection? Izbrisati odabrane četkice? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Jedna ili više četkica se koristi i ne mogu se izbrisati dok se njihovi potezi ne prošire ili uklone. + Delete the selected brushes? Izbrisati odabrane četkice? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Potezi koriste jednu ili više ovih četkica. Ukloniti četkice s tih poteza i izbrisati četkice? Remove Strokes Ukloni poteze Yes Da No Ne diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 970625ac0e..a83e611a34 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5999,8 +5999,8 @@ breakText Glyphs Glifs Gap 4 Separació 4 Dash 5 Guió 5 Gap 5 Separació 5 - Delete the brush selection? Voleu suprimir la selecció de pinzells? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Un o més pinzells estan en ús i no es poden suprimir fins que els traços s’expandeixin o s’eliminin. + Delete the selected brushes? Voleu suprimir els pinzells seleccionats? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Hi ha traços que fan servir un o més d’aquests pinzells. Voleu treure els pinzells d’aquests traços i suprimir els pinzells? Remove Strokes Elimina els traços Yes Sí No No diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index bc8c6b09bd..6fac8c5586 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6008,8 +6008,8 @@ breakText Glyphs Glyfy Gap 4 Mezera 4 Dash 5 Čárka 5 Gap 5 Mezera 5 - Delete the brush selection? Odstranit vybrané štětce? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Jeden nebo více štětců se používá a nelze je odstranit, dokud jejich tahy nebudou rozloženy nebo odebrány. + Delete the selected brushes? Odstranit vybrané štětce? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Tahy používají jeden nebo více z těchto štětců. Odebrat štětce z těchto tahů a odstranit štětce? Remove Strokes Odebrat tahy Yes Ano No Ne diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index fc45ef6e51..ef3b48df54 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5913,8 +5913,8 @@ breakText Glyphs Glyffer Gap 4 Mellemrum 4 Dash 5 Streg 5 Gap 5 Mellemrum 5 - Delete the brush selection? Slet de valgte pensler? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. En eller flere pensler er i brug og kan ikke slettes, før deres streger er udvidet eller fjernet. + Delete the selected brushes? Slet de valgte pensler? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Streger bruger en eller flere af disse pensler. Fjern penslerne fra stregerne, og slet penslerne? Remove Strokes Fjern streger Yes Ja No Nej diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index a36a57825e..9028735e09 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5594,8 +5594,8 @@ breakText Glyphs Glyphen Gap 4 Lücke 4 Dash 5 Strich 5 Gap 5 Lücke 5 - Delete the brush selection? Ausgewählte Pinsel löschen? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Ein oder mehrere Pinsel werden verwendet und können erst gelöscht werden, wenn ihre Konturen umgewandelt oder entfernt wurden. + Delete the selected brushes? Ausgewählte Pinsel löschen? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturen verwenden einen oder mehrere dieser Pinsel. Pinsel von diesen Konturen entfernen und die Pinsel löschen? Remove Strokes Konturen entfernen Yes Ja No Nein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7c9b2fa5c8..b8bd5f396b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5961,8 +5961,8 @@ breakText Glyphs Γλύφοι Gap 4 Διάκενο 4 Dash 5 Παύλα 5 Gap 5 Διάκενο 5 - Delete the brush selection? Να διαγραφούν τα επιλεγμένα πινέλα; - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Ένα ή περισσότερα πινέλα χρησιμοποιούνται και δεν μπορούν να διαγραφούν μέχρι να επεκταθούν ή να αφαιρεθούν τα περιγράμματά τους. + Delete the selected brushes? Να διαγραφούν τα επιλεγμένα πινέλα; + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Περιγράμματα χρησιμοποιούν ένα ή περισσότερα από αυτά τα πινέλα. Να αφαιρεθούν τα πινέλα από αυτά τα περιγράμματα και να διαγραφούν τα πινέλα; Remove Strokes Αφαίρεση περιγραμμάτων Yes Ναι No Όχι diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 70e009d067..ac1e149df1 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5951,8 +5951,8 @@ breakText Glyphs Glifos Gap 4 Hueco 4 Dash 5 Guion 5 Gap 5 Hueco 5 - Delete the brush selection? ¿Eliminar los pinceles seleccionados? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Uno o más pinceles están en uso y no se pueden eliminar hasta expandir o quitar sus trazos. + Delete the selected brushes? ¿Eliminar los pinceles seleccionados? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Algunos trazos usan uno o más de estos pinceles. ¿Quitar los pinceles de esos trazos y eliminar los pinceles? Remove Strokes Quitar trazos Yes Sí No No diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 51e68665ba..13107e11ec 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6039,8 +6039,8 @@ breakText Glyphs Merkit Gap 4 Väli 4 Dash 5 Viiva 5 Gap 5 Väli 5 - Delete the brush selection? Poistetaanko valitut siveltimet? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Yksi tai useampi sivellin on käytössä eikä niitä voi poistaa ennen kuin niiden viivat on laajennettu tai poistettu. + Delete the selected brushes? Poistetaanko valitut siveltimet? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Viivat käyttävät yhtä tai useampaa näistä siveltimistä. Irrotetaanko siveltimet näistä viivoista ja poistetaanko siveltimet? Remove Strokes Poista viivat Yes Kyllä No Ei diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 0c355f4785..f80a70246a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6006,8 +6006,8 @@ breakText Glyphs Glyphes Gap 4 Écart 4 Dash 5 Tiret 5 Gap 5 Écart 5 - Delete the brush selection? Supprimer les formes sélectionnées ? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Une ou plusieurs formes sont utilisées et ne peuvent pas être supprimées tant que leurs contours ne sont pas décomposés ou supprimés. + Delete the selected brushes? Supprimer les formes sélectionnées ? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Des contours utilisent une ou plusieurs de ces formes. Retirer les formes de ces contours et supprimer les formes ? Remove Strokes Supprimer les contours Yes Oui No Non diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 965e4ddb27..3e72e0c398 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5995,8 +5995,8 @@ breakText Glyphs Glifák Gap 4 Hézag 4 Dash 5 Vonal 5 Gap 5 Hézag 5 - Delete the brush selection? Törlöd a kijelölt ecseteket? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Egy vagy több ecset használatban van, és nem törölhető, amíg a körvonalait ki nem bontod vagy el nem távolítod. + Delete the selected brushes? Törlöd a kijelölt ecseteket? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Körvonalak használnak egyet vagy többet ezek közül az ecsetek közül. Leveszed az ecseteket ezekről a körvonalakról, és törlöd az ecseteket? Remove Strokes Körvonalak eltávolítása Yes Igen No Nem diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ebfdabf544..00bbfac314 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5913,8 +5913,8 @@ breakText Glyphs Glif Gap 4 Jarak 4 Dash 5 Garis 5 Gap 5 Jarak 5 - Delete the brush selection? Hapus kuas yang dipilih? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Satu atau beberapa kuas sedang digunakan dan tidak dapat dihapus sampai stroke-nya diperluas atau dihapus. + Delete the selected brushes? Hapus kuas yang dipilih? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Stroke menggunakan satu atau beberapa kuas ini. Lepaskan kuas dari stroke tersebut dan hapus kuasnya? Remove Strokes Hapus Stroke Yes Ya No Tidak diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ffc95c4da3..81b4ec79fa 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5628,8 +5628,8 @@ breakText Glyphs Glifi Gap 4 Spazio 4 Dash 5 Tratto 5 Gap 5 Spazio 5 - Delete the brush selection? Eliminare i pennelli selezionati? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Uno o più pennelli sono in uso e non possono essere eliminati finché le tracce non vengono espanse o rimosse. + Delete the selected brushes? Eliminare i pennelli selezionati? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Alcune tracce usano uno o più di questi pennelli. Rimuovere i pennelli da queste tracce ed eliminare i pennelli? Remove Strokes Rimuovi tracce Yes Sì No No diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 754362ef57..3064294fd4 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5694,8 +5694,8 @@ breakText Glyphs 字形 Gap 4 間隔 4 Dash 5 線分 5 Gap 5 間隔 5 - Delete the brush selection? 選択したブラシを削除しますか? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 使用中のブラシが含まれています。線を拡張または削除するまでブラシを削除できません。 + Delete the selected brushes? 選択したブラシを削除しますか? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? これらのブラシの 1 つ以上が線で使われています。それらの線からブラシを外して、ブラシを削除しますか? Remove Strokes 線を削除 Yes はい No いいえ diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b07dfd7fca..2d65308cba 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5998,8 +5998,8 @@ breakText Glyphs გლიფები Gap 4 შუალედი 4 Dash 5 ტირე 5 Gap 5 შუალედი 5 - Delete the brush selection? წაიშალოს არჩეული ფუნჯები? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. ერთი ან მეტი ფუნჯი გამოიყენება და მათი წაშლა შეუძლებელია, სანამ კონტურები არ გაიშლება ან არ მოიხსნება. + Delete the selected brushes? წაიშალოს არჩეული ფუნჯები? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? კონტურები იყენებს ამ ფუნჯებიდან ერთს ან მეტს. მოიხსნას ფუნჯები ამ კონტურებიდან და წაიშალოს ფუნჯები? Remove Strokes კონტურების მოხსნა Yes დიახ No არა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e487667b56..e9fa809c25 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5591,8 +5591,8 @@ breakText Glyphs 글리프 Gap 4 간격 4 Dash 5 대시 5 Gap 5 간격 5 - Delete the brush selection? 선택한 브러시를 삭제하시겠습니까? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 하나 이상의 브러시가 사용 중이며 선을 확장하거나 제거할 때까지 삭제할 수 없습니다. + Delete the selected brushes? 선택한 브러시를 삭제하시겠습니까? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 선에서 이 브러시 중 하나 이상을 사용합니다. 해당 선에서 브러시를 제거하고 브러시를 삭제하시겠습니까? Remove Strokes 선 제거 Yes 예 No 아니요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 71d7a6d732..2fdb5d58b8 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5957,8 +5957,8 @@ breakText Glyphs Glyphs Gap 4 Tussenruimte 4 Dash 5 Streepje 5 Gap 5 Tussenruimte 5 - Delete the brush selection? Geselecteerde kwasten verwijderen? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Een of meer kwasten zijn in gebruik en kunnen pas worden verwijderd als hun contouren zijn uitgebreid of verwijderd. + Delete the selected brushes? Geselecteerde kwasten verwijderen? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Contouren gebruiken een of meer van deze kwasten. De kwasten van deze contouren halen en de kwasten verwijderen? Remove Strokes Contouren verwijderen Yes Ja No Nee diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 7a606131ff..73117d2fcf 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5864,8 +5864,8 @@ breakText Glyphs Glify Gap 4 Odstęp 4 Dash 5 Kreska 5 Gap 5 Odstęp 5 - Delete the brush selection? Usunąć zaznaczone pędzle? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Co najmniej jeden pędzel jest używany i nie można go usunąć, dopóki jego obrysy nie zostaną rozszerzone lub usunięte. + Delete the selected brushes? Usunąć zaznaczone pędzle? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Obrysy używają co najmniej jednego z tych pędzli. Zdjąć pędzle z tych obrysów i usunąć pędzle? Remove Strokes Usuń obrysy Yes Tak No Nie diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e1044cbbd7..b2282cb815 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5928,8 +5928,8 @@ breakText Glyphs Glifos Gap 4 Lacuna 4 Dash 5 Traço 5 Gap 5 Lacuna 5 - Delete the brush selection? Excluir os pincéis selecionados? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Um ou mais pincéis estão em uso e não podem ser excluídos até que seus traçados sejam expandidos ou removidos. + Delete the selected brushes? Excluir os pincéis selecionados? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Traçados usam um ou mais destes pincéis. Remover os pincéis desses traçados e excluir os pincéis? Remove Strokes Remover Traçados Yes Sim No Não diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d9cede6983..a25e32e226 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5986,8 +5986,8 @@ breakText Glyphs Глифы Gap 4 Зазор 4 Dash 5 Штрих 5 Gap 5 Зазор 5 - Delete the brush selection? Удалить выбранные кисти? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Одна или несколько кистей используются и не могут быть удалены, пока их обводки не будут разобраны или убраны. + Delete the selected brushes? Удалить выбранные кисти? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обводки используют одну или несколько из этих кистей. Убрать кисти с этих обводок и удалить кисти? Remove Strokes Убрать обводки Yes Да No Нет diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 68239d409b..7075d1cd00 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6061,8 +6061,8 @@ breakText Glyphs Glyfer Gap 4 Mellanrum 4 Dash 5 Streck 5 Gap 5 Mellanrum 5 - Delete the brush selection? Radera de valda penslarna? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. En eller flera penslar används och kan inte raderas förrän deras konturer har expanderats eller tagits bort. + Delete the selected brushes? Radera de valda penslarna? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturer använder en eller flera av de här penslarna. Ta bort penslarna från konturerna och radera penslarna? Remove Strokes Ta bort konturer Yes Ja No Nej diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 44cc14ba51..65679691a9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5966,8 +5966,8 @@ breakText Glyphs Glifler Gap 4 Boşluk 4 Dash 5 Çizgi 5 Gap 5 Boşluk 5 - Delete the brush selection? Seçili fırçalar silinsin mi? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Bir veya daha fazla fırça kullanılıyor ve konturları genişletilmeden veya kaldırılmadan silinemez. + Delete the selected brushes? Seçili fırçalar silinsin mi? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturlar bu fırçalardan birini veya daha fazlasını kullanıyor. Fırçalar bu konturlardan kaldırılsın ve fırçalar silinsin mi? Remove Strokes Konturları Kaldır Yes Evet No Hayır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 271b96793e..7229a24aff 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5608,8 +5608,8 @@ breakText Glyphs Гліфи Gap 4 Проміжок 4 Dash 5 Штрих 5 Gap 5 Проміжок 5 - Delete the brush selection? Видалити вибрані пензлі? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Один або кілька пензлів використовуються і не можуть бути видалені, доки їхні обведення не буде розібрано або забрано. + Delete the selected brushes? Видалити вибрані пензлі? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обведення використовують один або кілька з цих пензлів. Забрати пензлі з цих обведень і видалити пензлі? Remove Strokes Забрати обведення Yes Так No Ні diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 66978c3703..7e5393289f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5610,8 +5610,8 @@ breakText Glyphs Glyph Gap 4 Khoảng hở 4 Dash 5 Nét 5 Gap 5 Khoảng hở 5 - Delete the brush selection? Xóa các cọ đã chọn? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. Một hoặc nhiều cọ đang được sử dụng và không thể xóa cho đến khi nét được mở rộng hoặc gỡ bỏ. + Delete the selected brushes? Xóa các cọ đã chọn? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Có nét đang dùng một hoặc nhiều cọ này. Gỡ cọ khỏi các nét đó và xóa cọ? Remove Strokes Gỡ nét Yes Có No Không diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 85e1ffd3d9..5f0b5adcea 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5850,8 +5850,8 @@ breakText Glyphs 字形 Gap 4 间隔 4 Dash 5 虚线 5 Gap 5 间隔 5 - Delete the brush selection? 删除选中的画笔吗? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 一个或多个画笔正在使用中,必须先扩展或移除其描边才能删除。 + Delete the selected brushes? 删除选中的画笔吗? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有描边使用了其中一个或多个画笔。要从这些描边移除画笔并删除画笔吗? Remove Strokes 移除描边 Yes 是 No 否 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 44e077e904..65e66a36e7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5647,8 +5647,8 @@ breakText Glyphs 字符 Gap 4 間隙 4 Dash 5 虛線 5 Gap 5 間隙 5 - Delete the brush selection? 要刪除選取的筆刷嗎? - One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed. 一個或多個筆刷正在使用中,必須先擴展或移除其筆畫才能刪除。 + Delete the selected brushes? 要刪除選取的筆刷嗎? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有筆畫使用了其中一個或多個筆刷。要從這些筆畫移除筆刷並刪除筆刷嗎? Remove Strokes 移除筆畫 Yes 是 No 否 diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index c4b794677a..0aef4fb634 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -160,9 +160,12 @@ fn assert_delete_dialog(app: &VectorcraftApp, message: &str) { let d = app.ui.dialog.as_ref().expect("Delete Brush asks first"); assert_eq!(d.kind, crate::dialogs::brush_delete::KIND); assert_eq!(d.str("message"), message); - assert_eq!(d.bool("used"), message.starts_with("One or more")); + assert_eq!(d.bool("used"), message == IN_USE); } +/// The Delete Brush question when a stroke uses one of the brushes. +const IN_USE: &str = "Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes?"; + /// Deleting several unused brushes asks one question about the selection, with no count in it. #[test] fn deleting_five_brushes_uses_one_selection_question() { @@ -226,7 +229,7 @@ fn shift_and_command_clicks_select_brushes_for_delete_and_duplicate() { assert_eq!(undo_count(&app), before.1 + 1); // The bottom bar's last button, Delete Brush. delete_button(&ctx, &mut app, egui::Modifiers::NONE, 5.0); - assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + assert_delete_dialog(&app, IN_USE); assert_eq!(names(&mut app), [before.0.clone(), copies.to_vec()].concat()); assert_eq!(brush_of(&app, rect).as_deref(), Some(three[0].as_str())); assert_eq!(undo_count(&app), before.1 + 1); @@ -266,7 +269,7 @@ fn selecting_other_art_ends_the_brush_multi_selection() { let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 4.0, show); assert_eq!(lit_tiles(&out), [1]); menu_click(&ctx, &mut app, "Delete Brush", 5.0); - assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + assert_delete_dialog(&app, IN_USE); assert!(names(&mut app).contains(&three[1])); crate::dialogs::confirm(&mut app).unwrap(); let left = names(&mut app); @@ -335,7 +338,7 @@ fn select_all_unused_selects_the_brushes_no_stroke_paints_with() { let on: Vec = (0..tiles.len()).filter(|i| lit(&ctx, &out).contains(&tiles[*i])).collect(); assert_eq!(on, (0..tiles.len()).filter(|i| *i != 1).collect::>()); menu_click(&ctx, &mut app, "Delete Brush", 3.0); - assert_delete_dialog(&app, "Delete the brush selection?"); + assert_delete_dialog(&app, "Delete the selected brushes?"); assert_eq!(names(&mut app).len(), list.len()); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(names(&mut app), [list[1].0.clone()]); @@ -352,7 +355,7 @@ fn delete_button_cancel_keeps_selected_brushes_strokes_and_history() { let (three, _) = select_three(&ctx, &mut app, rect); let before = (names(&mut app), brush_of(&app, rect), undo_count(&app)); delete_button(&ctx, &mut app, egui::Modifiers::NONE, 3.0); - assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + assert_delete_dialog(&app, IN_USE); assert_eq!((names(&mut app), brush_of(&app, rect), undo_count(&app)), before); crate::dialogs::cancel(&mut app); assert!(app.ui.dialog.is_none()); @@ -376,10 +379,10 @@ fn alt_delete_button_asks_when_a_selected_brush_is_used() { let (three, _) = select_three(&ctx, &mut app, rect); let before = undo_count(&app); delete_button(&ctx, &mut app, egui::Modifiers::NONE, 3.0); - assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + assert_delete_dialog(&app, IN_USE); crate::dialogs::cancel(&mut app); delete_button(&ctx, &mut app, egui::Modifiers::ALT, 4.0); - assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + assert_delete_dialog(&app, IN_USE); crate::dialogs::cancel(&mut app); let left = names(&mut app); assert!(three.iter().all(|name| left.contains(name))); @@ -414,7 +417,7 @@ fn menu_delete_used_brush_requires_remove_strokes_or_cancel() { let (three, _) = select_three(&ctx, &mut app, rect); let before = undo_count(&app); menu_click(&ctx, &mut app, "Delete Brush", 3.0); - assert_delete_dialog(&app, "One or more of the brushes are in use and cannot be deleted until their strokes are expanded or removed."); + assert_delete_dialog(&app, IN_USE); crate::dialogs::cancel(&mut app); assert_eq!(undo_count(&app), before); assert_eq!(brush_of(&app, rect).as_deref(), Some(three[0].as_str())); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a035815286..c53382a210 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -962,7 +962,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). In the Brushes panel, Shift-click selects a range of brushes and Ctrl/Cmd-click adds or removes one. Delete Brush and Duplicate Brush then act on all of them (`brush.delete {names}`, `brush.duplicate {names}`). - The Brushes panel's Delete Brush button and panel menu item ask "Delete the brush selection?" with Yes and No when none of the brushes is in use. Alt-click (Option-click on macOS) on the button deletes them without asking, as the [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists ("Delete without confirmation (except for Layers panel)"). When a stroke uses one of the brushes, the button, Alt-click and the menu item all ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. Tests: `panels::brushes::tests`, `dialogs::brush_delete::tests`. + The Brushes panel's Delete Brush button and panel menu item ask "Delete the selected brushes?" with Yes and No when none of the brushes is in use. Alt-click (Option-click on macOS) on the button deletes them without asking, as the [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page (archived copy) lists ("Delete without confirmation (except for Layers panel)"). When a stroke uses one of the brushes, the button, Alt-click and the menu item all ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. Tests: `panels::brushes::tests`, `dialogs::brush_delete::tests`. Document Info has a Brushes category after Graphic Styles. It lists the Brushes panel's brushes, or with Selection Only it lists the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`). Document Info has a Repeat Objects category after Embedded Images. It lists each radial, grid and mirror Repeat object by name with its kind and the number of instances it makes. For a grid it gives the rows and columns instead, followed by the number of instances it draws when that is fewer. With Selection Only it lists the Repeat objects in the selection. The Document Info report and Package's report list them too (`document.info {category: "repeats"}`, `repeatObjects`). The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). From 3a6770e7842558d8599dc50027be163835e3ba3d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 22:25:32 -0700 Subject: [PATCH 26/70] Brushes: Yes in Delete Brush asks again when a stroke started using a brush meanwhile The question for unused brushes checks again when Yes is chosen. If a stroke uses one of the brushes by then, the dialog asks with Remove Strokes and Cancel instead of deleting. --- crates/ui-egui/src/dialogs/brush_delete.rs | 22 ++++++++++++++++++- .../ui-egui/src/dialogs/brush_delete/tests.rs | 19 ++++++++++++++++ crates/ui-egui/src/panels/brushes.rs | 4 +--- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/brush_delete.rs b/crates/ui-egui/src/dialogs/brush_delete.rs index ee4d6c964e..84f2786d4f 100644 --- a/crates/ui-egui/src/dialogs/brush_delete.rs +++ b/crates/ui-egui/src/dialogs/brush_delete.rs @@ -28,6 +28,21 @@ pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) { app.ui.dialog = Some(Dialog::new(KIND, json!({"params": params, "used": used, "message": message}))); } +/// Whether a stroke uses one of `names` (`brush.unused`), or `None` when the query fails. +pub fn used(app: &mut VectorcraftApp, names: &[String]) -> Option { + let unused = app.run("brush.unused", json!({})).ok()?; + let unused = unused.get("names").and_then(Value::as_array).cloned().unwrap_or_default(); + Some(names.iter().any(|name| !unused.iter().any(|n| n.as_str() == Some(name)))) +} + +/// The brush names in `brush.delete` params (`name` or `names`). +fn names(params: &Value) -> Vec { + match params.get("name").and_then(Value::as_str) { + Some(name) => vec![name.to_string()], + None => params.get("names").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(), + } +} + fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { let mut action = DialogAction::None; ui.horizontal(|ui| { @@ -50,9 +65,14 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogActi action } -/// Closes before running, so a dialog the command opens stays open. +/// Closes before running, so a dialog the command opens stays open. Yes on brushes that a stroke +/// has started to use since the question opened asks again with Remove Strokes and Cancel. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let params = d.fields.get("params").cloned().unwrap_or_else(|| json!({})); + if !d.bool("used") && used(app, &names(¶ms)) == Some(true) { + ask(app, params, true); + return Ok(json!({})); + } app.ui.dialog = None; app.run("brush.delete", params) } diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs index 407351c794..6f753505cb 100644 --- a/crates/ui-egui/src/dialogs/brush_delete/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -50,6 +50,25 @@ fn visible_yes_and_no_buttons_control_unused_deletion() { assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); } +#[test] +fn yes_asks_again_when_a_stroke_started_using_the_brush() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let name = "10 pt. Oval"; + let ctx = context(); + ask(&mut app, json!({"names": [name]}), false); + let path = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap()); + app.run("brush.apply", json!({"name": name})).unwrap(); + let before = app.session.active().unwrap().history.undo.len(); + press(&ctx, &mut app, "Yes", 0.0); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND && d.bool("used")), "asks again with Remove Strokes"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); + let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); + assert_eq!(stroke.brush.as_deref(), Some(name)); + press(&ctx, &mut app, "Remove Strokes", 1.0); + assert!(app.run("brush.get", json!({"name": name})).is_err()); +} + #[test] fn visible_remove_strokes_and_cancel_buttons_control_used_deletion() { for choice in ["Cancel", "Remove Strokes"] { diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 279677527f..6f99c8a36d 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -207,11 +207,9 @@ fn run_on(app: &mut VectorcraftApp, id: &str, names: &[String]) { /// Delete `names` after asking: Yes or No when none of them is in use, else Remove Strokes or /// Cancel. With `now` (Alt-click on the bottom button), brushes that are not in use go at once. fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { - let Ok(unused) = app.run("brush.unused", json!({})) else { + let Some(used) = crate::dialogs::brush_delete::used(app, names) else { return; }; - let unused = unused.get("names").and_then(Value::as_array).cloned().unwrap_or_default(); - let used = names.iter().any(|name| !unused.iter().any(|n| n.as_str() == Some(name))); if now && !used { run_on(app, "brush.delete", names); return; From bb563452904aedbfdcf96b59297953db090fb137 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 22:41:30 -0700 Subject: [PATCH 27/70] Brushes: the Delete Brush question deletes nothing once another document is active The question records the document it was opened for. If another document has become the active one by the time it is confirmed, it closes as Cancel does. --- crates/ui-egui/src/dialogs/brush_delete.rs | 17 +++++++++++++---- .../ui-egui/src/dialogs/brush_delete/tests.rs | 16 ++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/brush_delete.rs b/crates/ui-egui/src/dialogs/brush_delete.rs index 84f2786d4f..52a86dc167 100644 --- a/crates/ui-egui/src/dialogs/brush_delete.rs +++ b/crates/ui-egui/src/dialogs/brush_delete.rs @@ -2,8 +2,8 @@ //! use, else Remove Strokes or Cancel. Yes and Remove Strokes run `brush.delete`, which leaves the //! strokes that used the brushes as plain strokes. //! -//! Fields: `message` (the question, shown as the heading), `used` (whether a brush is in use) and -//! `params` (the `brush.delete` params). +//! Fields: `message` (the question, shown as the heading), `used` (whether a brush is in use), +//! `params` (the `brush.delete` params) and `__doc` (the uid of the document it asks about). use serde_json::{Value, json}; @@ -25,9 +25,13 @@ pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) { } else { tl!("Delete the selected brushes?") }; - app.ui.dialog = Some(Dialog::new(KIND, json!({"params": params, "used": used, "message": message}))); + let doc = app.session.active().map(|d| d.uid); + app.ui.dialog = Some(Dialog::new(KIND, json!({"params": params, "used": used, "message": message, DOC: doc}))); } +/// The field that holds the uid of the document the question is about. +const DOC: &str = "__doc"; + /// Whether a stroke uses one of `names` (`brush.unused`), or `None` when the query fails. pub fn used(app: &mut VectorcraftApp, names: &[String]) -> Option { let unused = app.run("brush.unused", json!({})).ok()?; @@ -66,9 +70,14 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogActi } /// Closes before running, so a dialog the command opens stays open. Yes on brushes that a stroke -/// has started to use since the question opened asks again with Remove Strokes and Cancel. +/// has started to use since the question opened asks again with Remove Strokes and Cancel. When +/// another document has become the active one, it closes as Cancel does and deletes nothing. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let params = d.fields.get("params").cloned().unwrap_or_else(|| json!({})); + if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } if !d.bool("used") && used(app, &names(¶ms)) == Some(true) { ask(app, params, true); return Ok(json!({})); diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs index 6f753505cb..4092d63387 100644 --- a/crates/ui-egui/src/dialogs/brush_delete/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -69,6 +69,22 @@ fn yes_asks_again_when_a_stroke_started_using_the_brush() { assert!(app.run("brush.get", json!({"name": name})).is_err()); } +#[test] +fn yes_deletes_nothing_after_another_document_became_active() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let name = app.run("brush.list", json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string(); + let ctx = context(); + ask(&mut app, json!({"name": name}), false); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + press(&ctx, &mut app, "Yes", 0.0); + assert!(app.ui.dialog.is_none()); + assert!(app.run("brush.get", json!({"name": name})).is_ok(), "the second document keeps the brush"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(app.run("brush.get", json!({"name": name})).is_ok(), "the first document keeps the brush"); +} + #[test] fn visible_remove_strokes_and_cancel_buttons_control_used_deletion() { for choice in ["Cancel", "Remove Strokes"] { From beac4504fcaa0021c8e74f6de5d823acda904e15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 01:29:21 -0700 Subject: [PATCH 28/70] Brushes: the French delete questions keep the no-break space before ? --- crates/ui-egui/src/i18n/fr.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index f80a70246a..b8bfd769a0 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6006,8 +6006,8 @@ breakText Glyphs Glyphes Gap 4 Écart 4 Dash 5 Tiret 5 Gap 5 Écart 5 - Delete the selected brushes? Supprimer les formes sélectionnées ? - Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Des contours utilisent une ou plusieurs de ces formes. Retirer les formes de ces contours et supprimer les formes ? + Delete the selected brushes? Supprimer les formes sélectionnées ? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Des contours utilisent une ou plusieurs de ces formes. Retirer les formes de ces contours et supprimer les formes ? Remove Strokes Supprimer les contours Yes Oui No Non From 34d58c1bfbd95bdccc280849f3af991f06a50bdc Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sun, 1 Nov 2026 01:22:03 +0700 Subject: [PATCH 29/70] i18n: one row per catalog entry after #4829 --- crates/ui-egui/src/i18n/bg.tsv | 2 -- crates/ui-egui/src/i18n/bs.tsv | 2 -- crates/ui-egui/src/i18n/ca.tsv | 2 -- crates/ui-egui/src/i18n/cs.tsv | 2 -- crates/ui-egui/src/i18n/da.tsv | 2 -- crates/ui-egui/src/i18n/de.tsv | 2 -- crates/ui-egui/src/i18n/el.tsv | 2 -- crates/ui-egui/src/i18n/es.tsv | 2 -- crates/ui-egui/src/i18n/fi.tsv | 2 -- crates/ui-egui/src/i18n/fr.tsv | 2 -- crates/ui-egui/src/i18n/hu.tsv | 2 -- crates/ui-egui/src/i18n/id.tsv | 2 -- crates/ui-egui/src/i18n/it.tsv | 2 -- crates/ui-egui/src/i18n/ja.tsv | 2 -- crates/ui-egui/src/i18n/ka.tsv | 2 -- crates/ui-egui/src/i18n/ko.tsv | 2 -- crates/ui-egui/src/i18n/nl.tsv | 2 -- crates/ui-egui/src/i18n/pl.tsv | 2 -- crates/ui-egui/src/i18n/pt-br.tsv | 2 -- crates/ui-egui/src/i18n/ru.tsv | 2 -- crates/ui-egui/src/i18n/sv.tsv | 2 -- crates/ui-egui/src/i18n/tr.tsv | 2 -- crates/ui-egui/src/i18n/uk.tsv | 2 -- crates/ui-egui/src/i18n/vi.tsv | 2 -- crates/ui-egui/src/i18n/zh-hans.tsv | 2 -- crates/ui-egui/src/i18n/zh-hant.tsv | 2 -- 26 files changed, 52 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 43cef9353d..0888ac645d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5902,8 +5902,6 @@ breakText Glyphs Глифи Delete the selected brushes? Да се изтрият избраните четки? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Щрихи използват една или повече от тези четки. Да се премахнат ли четките от тези щрихи и да се изтрият четките? Remove Strokes Премахване на щрихи - Yes Да - No Не # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Инструменти за подреждане Arrange in Grid… Подреждане в мрежа… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 0deb3e7c36..d89af156f8 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5934,8 +5934,6 @@ shape Open Otvoren Delete the selected brushes? Izbrisati odabrane četkice? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Potezi koriste jednu ili više ovih četkica. Ukloniti četkice s tih poteza i izbrisati četkice? Remove Strokes Ukloni poteze - Yes Da - No Ne # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Alati za raspoređivanje Arrange in Grid… Rasporedi u mrežu… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a83e611a34..15bd85222d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6002,8 +6002,6 @@ breakText Glyphs Glifs Delete the selected brushes? Voleu suprimir els pinzells seleccionats? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Hi ha traços que fan servir un o més d’aquests pinzells. Voleu treure els pinzells d’aquests traços i suprimir els pinzells? Remove Strokes Elimina els traços - Yes Sí - No No # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Eines d’organització Arrange in Grid… Organitza en quadrícula… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6fac8c5586..fe80401bc1 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6011,8 +6011,6 @@ breakText Glyphs Glyfy Delete the selected brushes? Odstranit vybrané štětce? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Tahy používají jeden nebo více z těchto štětců. Odebrat štětce z těchto tahů a odstranit štětce? Remove Strokes Odebrat tahy - Yes Ano - No Ne # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Nástroje uspořádání Arrange in Grid… Uspořádat do mřížky… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index ef3b48df54..74107e22cb 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5916,8 +5916,6 @@ breakText Glyphs Glyffer Delete the selected brushes? Slet de valgte pensler? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Streger bruger en eller flere af disse pensler. Fjern penslerne fra stregerne, og slet penslerne? Remove Strokes Fjern streger - Yes Ja - No Nej # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Arrangeringsværktøjer Arrange in Grid… Arrangér i gitter… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9028735e09..447c98350d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5597,8 +5597,6 @@ breakText Glyphs Glyphen Delete the selected brushes? Ausgewählte Pinsel löschen? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturen verwenden einen oder mehrere dieser Pinsel. Pinsel von diesen Konturen entfernen und die Pinsel löschen? Remove Strokes Konturen entfernen - Yes Ja - No Nein # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Anordnungswerkzeuge Arrange in Grid… In Raster anordnen… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b8bd5f396b..8dea59f7f0 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5964,8 +5964,6 @@ breakText Glyphs Γλύφοι Delete the selected brushes? Να διαγραφούν τα επιλεγμένα πινέλα; Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Περιγράμματα χρησιμοποιούν ένα ή περισσότερα από αυτά τα πινέλα. Να αφαιρεθούν τα πινέλα από αυτά τα περιγράμματα και να διαγραφούν τα πινέλα; Remove Strokes Αφαίρεση περιγραμμάτων - Yes Ναι - No Όχι # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Εργαλεία διάταξης Arrange in Grid… Διάταξη σε πλέγμα… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ac1e149df1..e6c7dd7690 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5954,8 +5954,6 @@ breakText Glyphs Glifos Delete the selected brushes? ¿Eliminar los pinceles seleccionados? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Algunos trazos usan uno o más de estos pinceles. ¿Quitar los pinceles de esos trazos y eliminar los pinceles? Remove Strokes Quitar trazos - Yes Sí - No No # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Herramientas de organización Arrange in Grid… Organizar en cuadrícula… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 13107e11ec..08122ed024 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6042,8 +6042,6 @@ breakText Glyphs Merkit Delete the selected brushes? Poistetaanko valitut siveltimet? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Viivat käyttävät yhtä tai useampaa näistä siveltimistä. Irrotetaanko siveltimet näistä viivoista ja poistetaanko siveltimet? Remove Strokes Poista viivat - Yes Kyllä - No Ei # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Järjestelytyökalut Arrange in Grid… Järjestä ruudukkoon… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b8bfd769a0..b35297550a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6009,8 +6009,6 @@ breakText Glyphs Glyphes Delete the selected brushes? Supprimer les formes sélectionnées ? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Des contours utilisent une ou plusieurs de ces formes. Retirer les formes de ces contours et supprimer les formes ? Remove Strokes Supprimer les contours - Yes Oui - No Non # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Outils de disposition Arrange in Grid… Disposer en grille… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3e72e0c398..cac7189ed7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5998,8 +5998,6 @@ breakText Glyphs Glifák Delete the selected brushes? Törlöd a kijelölt ecseteket? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Körvonalak használnak egyet vagy többet ezek közül az ecsetek közül. Leveszed az ecseteket ezekről a körvonalakról, és törlöd az ecseteket? Remove Strokes Körvonalak eltávolítása - Yes Igen - No Nem # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Elrendezőeszközök Arrange in Grid… Elrendezés rácsba… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 00bbfac314..29e87826ab 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5916,8 +5916,6 @@ breakText Glyphs Glif Delete the selected brushes? Hapus kuas yang dipilih? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Stroke menggunakan satu atau beberapa kuas ini. Lepaskan kuas dari stroke tersebut dan hapus kuasnya? Remove Strokes Hapus Stroke - Yes Ya - No Tidak # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Alat penyusunan Arrange in Grid… Susun dalam grid… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 81b4ec79fa..51870220aa 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5631,8 +5631,6 @@ breakText Glyphs Glifi Delete the selected brushes? Eliminare i pennelli selezionati? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Alcune tracce usano uno o più di questi pennelli. Rimuovere i pennelli da queste tracce ed eliminare i pennelli? Remove Strokes Rimuovi tracce - Yes Sì - No No # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Strumenti di disposizione Arrange in Grid… Disponi in griglia… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 3064294fd4..c6c4227b6b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5697,8 +5697,6 @@ breakText Glyphs 字形 Delete the selected brushes? 選択したブラシを削除しますか? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? これらのブラシの 1 つ以上が線で使われています。それらの線からブラシを外して、ブラシを削除しますか? Remove Strokes 線を削除 - Yes はい - No いいえ # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 配置ツール Arrange in Grid… グリッドに配置… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2d65308cba..c02d40eb17 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6001,8 +6001,6 @@ breakText Glyphs გლიფები Delete the selected brushes? წაიშალოს არჩეული ფუნჯები? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? კონტურები იყენებს ამ ფუნჯებიდან ერთს ან მეტს. მოიხსნას ფუნჯები ამ კონტურებიდან და წაიშალოს ფუნჯები? Remove Strokes კონტურების მოხსნა - Yes დიახ - No არა # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools განლაგების ხელსაწყოები Arrange in Grid… ბადეში განლაგება… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e9fa809c25..5c24bd9ca2 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5594,8 +5594,6 @@ breakText Glyphs 글리프 Delete the selected brushes? 선택한 브러시를 삭제하시겠습니까? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 선에서 이 브러시 중 하나 이상을 사용합니다. 해당 선에서 브러시를 제거하고 브러시를 삭제하시겠습니까? Remove Strokes 선 제거 - Yes 예 - No 아니요 # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 배치 도구 Arrange in Grid… 격자로 배치… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 2fdb5d58b8..282b0a4aad 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5960,8 +5960,6 @@ breakText Glyphs Glyphs Delete the selected brushes? Geselecteerde kwasten verwijderen? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Contouren gebruiken een of meer van deze kwasten. De kwasten van deze contouren halen en de kwasten verwijderen? Remove Strokes Contouren verwijderen - Yes Ja - No Nee # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Schikgereedschappen Arrange in Grid… In raster schikken… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 73117d2fcf..3999714470 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5867,8 +5867,6 @@ breakText Glyphs Glify Delete the selected brushes? Usunąć zaznaczone pędzle? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Obrysy używają co najmniej jednego z tych pędzli. Zdjąć pędzle z tych obrysów i usunąć pędzle? Remove Strokes Usuń obrysy - Yes Tak - No Nie # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Narzędzia układania Arrange in Grid… Ułóż w siatce… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b2282cb815..4f75dd659d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5931,8 +5931,6 @@ breakText Glyphs Glifos Delete the selected brushes? Excluir os pincéis selecionados? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Traçados usam um ou mais destes pincéis. Remover os pincéis desses traçados e excluir os pincéis? Remove Strokes Remover Traçados - Yes Sim - No Não # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Ferramentas de Organização Arrange in Grid… Organizar em Grade… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a25e32e226..d412fa13bc 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5989,8 +5989,6 @@ breakText Glyphs Глифы Delete the selected brushes? Удалить выбранные кисти? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обводки используют одну или несколько из этих кистей. Убрать кисти с этих обводок и удалить кисти? Remove Strokes Убрать обводки - Yes Да - No Нет # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Инструменты размещения Arrange in Grid… Разместить по сетке… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 7075d1cd00..2a1ba37453 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6064,8 +6064,6 @@ breakText Glyphs Glyfer Delete the selected brushes? Radera de valda penslarna? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturer använder en eller flera av de här penslarna. Ta bort penslarna från konturerna och radera penslarna? Remove Strokes Ta bort konturer - Yes Ja - No Nej # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Ordningsverktyg Arrange in Grid… Ordna i rutnät… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 65679691a9..215b7f8e6d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5969,8 +5969,6 @@ breakText Glyphs Glifler Delete the selected brushes? Seçili fırçalar silinsin mi? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturlar bu fırçalardan birini veya daha fazlasını kullanıyor. Fırçalar bu konturlardan kaldırılsın ve fırçalar silinsin mi? Remove Strokes Konturları Kaldır - Yes Evet - No Hayır # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Düzenleme Araçları Arrange in Grid… Izgarada Düzenle… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 7229a24aff..13fab3c518 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5611,8 +5611,6 @@ breakText Glyphs Гліфи Delete the selected brushes? Видалити вибрані пензлі? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обведення використовують один або кілька з цих пензлів. Забрати пензлі з цих обведень і видалити пензлі? Remove Strokes Забрати обведення - Yes Так - No Ні # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Інструменти розміщення Arrange in Grid… Розмістити сіткою… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7e5393289f..f45d5d04ae 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5613,8 +5613,6 @@ breakText Glyphs Glyph Delete the selected brushes? Xóa các cọ đã chọn? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Có nét đang dùng một hoặc nhiều cọ này. Gỡ cọ khỏi các nét đó và xóa cọ? Remove Strokes Gỡ nét - Yes Có - No Không # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Công cụ sắp xếp Arrange in Grid… Sắp xếp theo lưới… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f0b5adcea..4e105573f1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5853,8 +5853,6 @@ breakText Glyphs 字形 Delete the selected brushes? 删除选中的画笔吗? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有描边使用了其中一个或多个画笔。要从这些描边移除画笔并删除画笔吗? Remove Strokes 移除描边 - Yes 是 - No 否 # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 排列工具 Arrange in Grid… 按网格排列… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 65e66a36e7..acb8291996 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5650,8 +5650,6 @@ breakText Glyphs 字符 Delete the selected brushes? 要刪除選取的筆刷嗎? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有筆畫使用了其中一個或多個筆刷。要從這些筆畫移除筆刷並刪除筆刷嗎? Remove Strokes 移除筆畫 - Yes 是 - No 否 # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 排列工具 Arrange in Grid… 依格狀排列… From 012af4fd49914f68f40f9a3288e6d8ce03371f14 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 19:45:16 -0700 Subject: [PATCH 30/70] Brushes: each Pattern Brush Options tile can be set to a pattern swatch or None A menu under each of the five tiles in Pattern Brush Options lists None, Original and the document's pattern swatches; the corner menus keep the four automatic corners. A swatch choice copies the swatch's whole art and its tile frame into the brush, so the brush keeps drawing after the swatch is deleted, and the menu then shows that art as Original. Side cannot be None: OK shows "You must choose a side pattern." and keeps the dialog open. brush.options takes side_tile, outer_corner_tile, inner_corner_tile, start_tile and end_tile (a pattern name, none, original, the corner auto ids, or {"pattern": name} for a swatch named like one of those words), and rejects side_tile "none" and unknown names before editing. --- crates/brush/src/lib.rs | 43 ++++ crates/brush/src/tests.rs | 37 ++++ crates/brush/src/warp.rs | 22 +- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/brushes.rs | 70 ++++++ crates/engine/src/tests/brushsym.rs | 188 ++++++++++++++++ .../ui-egui/src/dialogs/brush_art_options.rs | 184 +++++++++++++--- crates/ui-egui/src/dialogs/brush_options.rs | 38 +++- .../src/dialogs/brush_options/tests.rs | 203 +++++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/widgets.rs | 2 +- docs/gaps.md | 8 +- docs/mcp.md | 7 +- docs/target-app-parity.md | 3 +- 39 files changed, 837 insertions(+), 48 deletions(-) diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index e76e67ba5b..fbec570112 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -386,10 +386,22 @@ impl CornerSource { #[serde(default)] pub struct PatternBrush { pub side: Node, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub side_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub side_swatch: Option, #[serde(skip_serializing_if = "Option::is_none")] pub outer_corner: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outer_corner_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outer_corner_swatch: Option, #[serde(skip_serializing_if = "Option::is_none")] pub inner_corner: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub inner_corner_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub inner_corner_swatch: Option, /// What the outer corners take when there is no `outer_corner` art. Without art or a source, /// they take the `inner_corner` art. #[serde(skip_serializing_if = "Option::is_none")] @@ -400,8 +412,16 @@ pub struct PatternBrush { pub inner_source: Option, #[serde(skip_serializing_if = "Option::is_none")] pub start: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start_swatch: Option, #[serde(skip_serializing_if = "Option::is_none")] pub end: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_swatch: Option, /// Scale in percent. pub scale: f64, /// Space between tiles in percent of the tile width. @@ -422,12 +442,22 @@ impl Default for PatternBrush { fn default() -> Self { Self { side: defaults::stitch_tile(), + side_frame: None, + side_swatch: None, outer_corner: None, + outer_corner_frame: None, + outer_corner_swatch: None, inner_corner: None, + inner_corner_frame: None, + inner_corner_swatch: None, outer_source: None, inner_source: None, start: None, + start_frame: None, + start_swatch: None, end: None, + end_frame: None, + end_swatch: None, scale: 100.0, spacing: 0.0, fit: PatternFit::Stretch, @@ -500,6 +530,14 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6 (within(a, range, fallback), within(b, range, fallback)) } +fn valid_tile_frame(frame: Rect) -> bool { + [frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite) + && frame.width().is_finite() + && frame.height().is_finite() + && frame.width() > 1e-9 + && frame.height() > 1e-9 +} + impl Colorization { /// A Hue Shift key colour that isn't a colour (components out of reach) becomes black. fn sanitize(&mut self) { @@ -600,6 +638,11 @@ impl Brush { BrushKind::Pattern(p) => { p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0); p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0); + for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] { + if frame.is_some_and(|f| !valid_tile_frame(f)) { + *frame = None; + } + } p.colorization.sanitize(); } BrushKind::Bristle(b) => { diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 28bbcda752..6362c8da8d 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -561,6 +561,43 @@ fn pattern_corner_source_none_leaves_that_kind_of_corner_empty() { assert!((outer == plain && inner == saved) || (inner == plain && outer == saved), "only the corners set to None are empty"); } +#[test] +fn pattern_without_start_tile_runs_side_to_path_start() { + let path = line(0.0, 0.0, 100.0, 0.0); + let doc = Document::new(1.0, 1.0); + let mut b = pattern_brush(PatternFit::Stretch, false); + if let BrushKind::Pattern(p) = &mut b.kind { + p.start = Some(rect_art(20.0, 4.0)); + } + let with_start = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(with_start[0].geometric_bounds().unwrap().width(), 20.0); + if let BrushKind::Pattern(p) = &mut b.kind { + p.start = None; + } + let without_start = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(without_start.len(), 10); + assert!(near(without_start[0].geometric_bounds().unwrap().x0, 0.0, 1e-6)); + assert!(near(without_start[0].geometric_bounds().unwrap().width(), 10.0, 1e-6)); +} + +#[test] +fn pattern_without_end_tile_runs_side_to_path_end() { + let path = line(0.0, 0.0, 100.0, 0.0); + let doc = Document::new(1.0, 1.0); + let mut b = pattern_brush(PatternFit::Stretch, false); + if let BrushKind::Pattern(p) = &mut b.kind { + p.end = Some(rect_art(20.0, 4.0)); + } + let with_end = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert!(with_end.iter().any(|n| near(n.geometric_bounds().unwrap().width(), 20.0, 1e-6))); + if let BrushKind::Pattern(p) = &mut b.kind { + p.end = None; + } + let without_end = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(without_end.len(), 10); + assert!(near(without_end.last().unwrap().geometric_bounds().unwrap().x1, 100.0, 1e-6)); +} + #[test] fn pattern_corner_sources_round_trip_and_stay_out_of_brushes_without_them() { let saved = serde_json::to_value(pattern_brush(PatternFit::Stretch, true)).unwrap(); diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index d66d5679fb..78c2f547f3 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -247,6 +247,16 @@ fn oriented(art: &Node, dir: Direction, flip_along: bool, flip_across: bool) -> (b.width() > 1e-9).then_some((a, b)) } +/// Orient a tile's repeat frame with its art. The frame can be smaller than the art. +fn oriented_tile(art: &Node, frame: Option, flip_along: bool, flip_across: bool) -> Option<(Node, Rect)> { + let (node, bounds) = oriented(art, Direction::LeftToRight, flip_along, flip_across)?; + let Some(frame) = frame else { return Some((node, bounds)) }; + let x = if flip_along { (-frame.x1, -frame.x0) } else { (frame.x0, frame.x1) }; + let y = if flip_across { (-frame.y1, -frame.y0) } else { (frame.y0, frame.y1) }; + let frame = Rect::new(x.0, y.0, x.1, y.1); + (frame.width() > 1e-9 && frame.height() > 1e-9).then_some((node, frame)) +} + /// Piecewise-linear map from art x (offset from the art's left edge) to arc length. #[derive(Clone, Copy, Debug)] pub(crate) struct AlongMap { @@ -800,13 +810,13 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option { } pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec { - let orient = |n: &Node| oriented(n, Direction::LeftToRight, pb.flip_along, pb.flip_across); - let Some(side) = orient(&pb.side) else { return vec![] }; + let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across); + let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] }; let k = weight * pb.scale.max(1.0) / 100.0; - let outer = pb.outer_corner.as_ref().and_then(orient); - let inner = pb.inner_corner.as_ref().and_then(orient); - let start = pb.start.as_ref().and_then(orient); - let end = pb.end.as_ref().and_then(orient); + let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame)); + let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame)); + let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame)); + let end = pb.end.as_ref().and_then(|n| orient(n, pb.end_frame)); let tw = side.1.width() * k; let gap = tw * pb.spacing.max(0.0) / 100.0; // Each kind of corner takes its own art, else its source, else the other kind's art. diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 7b37fea769..3b9a476d42 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -134,7 +134,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art). scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index f5e5c73fce..9cc52c82c8 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -390,7 +390,77 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result { let i = lib.iter().position(|b| b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?; let mut v = serde_json::to_value(&lib[i]).unwrap_or_default(); if let Some(params) = p.get("params") { + let original = v.clone(); merge(&mut v, params); + if lib[i].kind.type_id() == "pattern" { + let tiles = [ + ("side_tile", "side"), + ("outer_corner_tile", "outer_corner"), + ("inner_corner_tile", "inner_corner"), + ("start_tile", "start"), + ("end_tile", "end"), + ]; + // Resolve all Original choices against the brush before any tile can clear the art + // another corner borrows. Keep the matching frame with each copied tile. + let originals: Vec<_> = tiles + .iter() + .map(|(_, art)| { + let from = if art.ends_with("corner") + && original.get(art).is_none_or(Value::is_null) + && original.get(if *art == "outer_corner" { "outer_source" } else { "inner_source" }).is_none_or(Value::is_null) + { + if *art == "outer_corner" { "inner_corner" } else { "outer_corner" } + } else { + *art + }; + (original.get(from).cloned().unwrap_or(Value::Null), original.get(format!("{from}_frame")).cloned().unwrap_or(Value::Null)) + }) + .collect(); + for ((tile, art), (original_art, original_frame)) in tiles.into_iter().zip(originals) { + let frame = format!("{art}_frame"); + let swatch = format!("{art}_swatch"); + let Some(choice) = params.get(tile) else { + if params.get(art).is_some() { + if params.get(frame.as_str()).is_none() { + v[frame.as_str()] = Value::Null; + } + if params.get(swatch.as_str()).is_none() { + v[swatch.as_str()] = Value::Null; + } + } + continue; + }; + let (choice, swatch_only) = if let Some(name) = choice.as_object() { + (name.get("pattern").and_then(Value::as_str).ok_or_else(|| bad(C, "invalid pattern tile choice"))?, true) + } else { + (choice.as_str().ok_or_else(|| bad(C, "invalid pattern tile choice"))?, false) + }; + if art == "side" && choice == "none" && !swatch_only { + return Err(bad(C, "You must choose a side pattern.")); + } + if choice == "original" && !swatch_only { + v[art] = original_art; + v[frame.as_str()] = original_frame; + v[swatch.as_str()] = Value::Null; + } else if !swatch_only && (choice == "none" || (art.ends_with("corner") && brush::CornerSource::parse(choice).is_some())) { + v[art] = Value::Null; + v[frame.as_str()] = Value::Null; + v[swatch.as_str()] = Value::Null; + if art.ends_with("corner") { + v[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = json!(choice); + } + } else { + let pattern = s.doc()?.doc.pattern(choice).ok_or_else(|| bad(C, format!("no pattern named `{choice}`")))?; + let copy = Node::new(NodeId(0), NodeKind::Group { children: pattern.art.clone(), clip: false }); + v[art] = serde_json::to_value(copy).unwrap_or_default(); + v[frame.as_str()] = serde_json::to_value(pattern.tile).unwrap_or_default(); + v[swatch.as_str()] = json!(choice); + if art.ends_with("corner") { + v[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = Value::Null; + } + } + } + } } let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty() && *n != name).map(str::to_string); if let Some(nn) = &new_name { diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index bba39230bc..ef448da9de 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -832,6 +832,194 @@ fn art_brush_options_keep_the_scale_fields_an_edit_leaves_out() { assert_eq!(s.execute("brush.get", &json!({"name": "Bar"})).unwrap()["scale"], json!({"mode": "stretch"})); } +#[test] +fn pattern_tile_choices_copy_whole_swatch_art_and_reject_invalid_side() { + use std::sync::Arc; + use vectorcraft_doc::{PatternDef, StrokeLayer}; + use vectorcraft_geom::BezPath; + + let mut s = session(); + s.edit("Pattern", |d, _| { + let art = + Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), vectorcraft_doc::Appearance::default_art()); + d.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Wide", vec![Arc::new(art)]) }); + Ok(()) + }) + .unwrap(); + let side = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap()["side"].clone(); + s.execute("brush.new", &json!({"type":"pattern", "name":"Plain Tiles", "params":{"side":side}})).unwrap(); + let original = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + for choice in ["none", "Missing"] { + let error = s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"side_tile":choice}})).unwrap_err().to_string(); + assert!(error.contains(if choice == "none" { "You must choose a side pattern." } else { "no pattern named" }), "{error}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(), original); + } + s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"side_tile":"Wide", "fit":"addSpace"}})).unwrap(); + let saved = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(); + assert_eq!(saved["side_frame"], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); + assert_eq!(saved["side_swatch"], "Wide"); + let brush: vectorcraft_brush::Brush = serde_json::from_value(saved).unwrap(); + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((100.0, 0.0)); + let pieces = vectorcraft_brush::stroke_pieces( + &s.doc().unwrap().doc, + &brush, + &path, + &StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0), + ); + assert_eq!(pieces.len(), 10, "10 pt tile frame repeats ten times along 100 pt"); + assert!(pieces[0].geometric_bounds().unwrap().width() >= 29.9, "whole 30 pt art is copied"); + s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"inner_corner_tile":"Wide", "outer_corner_tile":"none"}})).unwrap(); + let corners: vectorcraft_brush::Brush = serde_json::from_value(s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()).unwrap(); + let mut fallback = corners.clone(); + if let (vectorcraft_brush::BrushKind::Pattern(actual), vectorcraft_brush::BrushKind::Pattern(legacy)) = (&corners.kind, &mut fallback.kind) { + assert_eq!(actual.outer_source, Some(vectorcraft_brush::CornerSource::None)); + assert!(actual.inner_corner.is_some()); + legacy.outer_source = None; + } + let square = |clockwise: bool| { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + if clockwise { + for point in [(100.0, 0.0), (100.0, 100.0), (0.0, 100.0)] { + p.line_to(point); + } + } else { + for point in [(0.0, 100.0), (100.0, 100.0), (100.0, 0.0)] { + p.line_to(point); + } + } + p.close_path(); + p + }; + let stroke = StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0); + assert!( + [false, true].into_iter().any(|clockwise| { + let path = square(clockwise); + vectorcraft_brush::stroke_pieces(&s.doc().unwrap().doc, &corners, &path, &stroke) + != vectorcraft_brush::stroke_pieces(&s.doc().unwrap().doc, &fallback, &path, &stroke) + }), + "explicit outer None omits the inner corner art on outer turns" + ); + let borrowed_art = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()["inner_corner"].clone(); + s.execute("brush.new", &json!({"type":"pattern", "name":"Borrowed Corner", "params":{"side":original["side"], "inner_corner":borrowed_art}})) + .unwrap(); + s.execute("brush.options", &json!({"name":"Borrowed Corner", "params":{"outer_corner_tile":"original", "inner_corner_tile":"none"}})).unwrap(); + let borrowed = s.execute("brush.get", &json!({"name":"Borrowed Corner"})).unwrap(); + assert!(borrowed["outer_corner"].is_object()); + assert_eq!(borrowed["inner_source"], "none"); + s.edit("Delete pattern", |d, _| { + d.patterns.clear(); + Ok(()) + }) + .unwrap(); + let after: vectorcraft_brush::Brush = serde_json::from_value(s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()).unwrap(); + assert_eq!( + vectorcraft_brush::stroke_pieces( + &s.doc().unwrap().doc, + &after, + &path, + &StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0) + ) + .len(), + 10 + ); + let copied = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()["side"].clone(); + s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"side_tile":"original"}})).unwrap(); + let original_choice = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(); + assert_eq!(original_choice["side"], copied); + assert!(original_choice.get("side_swatch").is_none()); +} + +#[test] +fn pattern_original_corner_keeps_borrowed_art_and_frame_when_source_is_cleared() { + let mut s = session(); + let chain = s.execute("brush.get", &json!({"name": "Chain"})).unwrap(); + let art = chain["outer_corner"].clone(); + let frame = json!(Rect::new(1.0, 2.0, 15.0, 18.0)); + for (name, source, borrowed) in [("Borrow Outer", "inner", "outer"), ("Borrow Inner", "outer", "inner")] { + let source_art = format!("{source}_corner"); + let source_frame = format!("{source_art}_frame"); + let borrowed_art = format!("{borrowed}_corner"); + let borrowed_frame = format!("{borrowed_art}_frame"); + let source_tile = format!("{source_art}_tile"); + let borrowed_tile = format!("{borrowed_art}_tile"); + s.execute("brush.new", &json!({"type":"pattern", "name":name, "params":{"side":chain["side"], source_art:art, source_frame:frame}})).unwrap(); + s.execute("brush.options", &json!({"name":name, "params":{source_tile:"none", borrowed_tile:"original"}})).unwrap(); + let saved = s.execute("brush.get", &json!({"name":name})).unwrap(); + assert_eq!(saved[&borrowed_art], chain["outer_corner"], "{borrowed} art"); + assert_eq!(saved[&borrowed_frame], frame, "{borrowed} frame"); + assert_eq!(saved[format!("{source}_source")], "none"); + } +} + +#[test] +fn pattern_tile_object_selects_reserved_swatch_names() { + use std::sync::Arc; + use vectorcraft_doc::PatternDef; + + let mut s = session(); + let names = ["none", "original", "autoCentered", "autoBetween", "autoSliced", "autoOverlap"]; + s.edit("Patterns", |doc, _| { + for name in names { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new(name, vec![Arc::new(art)]) }); + } + Ok(()) + }) + .unwrap(); + let before = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap(); + for invalid in [json!({}), json!({"pattern": null}), json!({"pattern": 1})] { + let error = s.execute("brush.options", &json!({"name":"Diamonds", "params":{"side_tile":invalid}})).unwrap_err().to_string(); + assert!(error.contains("invalid pattern tile choice"), "{error}"); + assert_eq!(s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap(), before); + } + let slots = ["side_tile", "outer_corner_tile", "inner_corner_tile", "start_tile", "end_tile"]; + for (slot, name) in slots.into_iter().zip(names) { + s.execute("brush.options", &json!({"name":"Diamonds", "params":{(slot):{"pattern":name}}})).unwrap(); + } + let saved = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap(); + for (art, name) in ["side", "outer_corner", "inner_corner", "start", "end"].into_iter().zip(names) { + assert_eq!(saved[format!("{art}_swatch")], name); + assert_eq!(saved[format!("{art}_frame")], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); + } + s.execute("brush.options", &json!({"name":"Diamonds", "params":{"outer_corner_tile":{"pattern":"autoOverlap"}}})).unwrap(); + assert_eq!(s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap()["outer_corner_swatch"], "autoOverlap"); +} + +#[test] +fn pattern_end_tile_none_choices_leave_side_art_at_both_path_ends() { + use vectorcraft_doc::StrokeLayer; + use vectorcraft_geom::BezPath; + + let mut s = session(); + let side = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap()["side"].clone(); + let cap = s.execute("brush.get", &json!({"name":"Chain"})).unwrap()["outer_corner"].clone(); + s.execute("brush.new", &json!({"type":"pattern", "name":"Capped", "params":{"side":side, "start":cap, "end":cap}})).unwrap(); + s.execute("brush.options", &json!({"name":"Capped", "params":{"start_tile":"none", "end_tile":"none"}})).unwrap(); + let def = s.execute("brush.get", &json!({"name":"Capped"})).unwrap(); + assert!(def.get("start").is_none() && def.get("end").is_none()); + let brush: vectorcraft_brush::Brush = serde_json::from_value(def).unwrap(); + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((100.0, 0.0)); + let pieces = vectorcraft_brush::stroke_pieces( + &s.doc().unwrap().doc, + &brush, + &path, + &StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0), + ); + let bounds = pieces.iter().fold(None, |bounds, node| vectorcraft_geom::union_opt(bounds, node.geometric_bounds())).unwrap(); + assert!((bounds.x0 - 0.0).abs() < 1e-6 && (bounds.x1 - 100.0).abs() < 1e-6, "{bounds:?}"); +} + // ---------- symbols ---------- fn make_symbol(s: &mut Session) -> (NodeId, String, Rect) { diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index f9b5bf5584..c9071fd376 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -26,7 +26,7 @@ use egui::{Color32, Sense, Stroke, pos2, vec2}; use serde_json::{Map, Value, json}; use vectorcraft_brush::{ArtBrush, ArtScale, Brush, BrushKind, Colorization, CornerSource, Direction, PatternBrush, PatternFit, Scatter, Variation}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, PatternDef}; use super::brush_options::{clamped, mode_key, stroke_preview}; use crate::VectorcraftApp; @@ -44,6 +44,55 @@ const DIRECTIONS: [Direction; 4] = [Direction::LeftToRight, Direction::RightToLe const TILES: [(&str, &str); 5] = [("outer_corner", "outerCorner"), ("side", "side"), ("inner_corner", "innerCorner"), ("start", "start"), ("end", "end")]; +fn tile_key(field: &str) -> String { + match field { + "outer_corner" => "outerCornerTile".into(), + "inner_corner" => "innerCornerTile".into(), + _ => format!("{field}Tile"), + } +} + +pub(super) fn pattern_names(d: &Dialog) -> Vec { + d.fields + .get("__patterns") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|v| v.get("name").and_then(Value::as_str).map(str::to_string)) + .collect() +} + +fn pattern_choice(d: &Dialog, choice: &str) -> Option { + let name = choice.strip_prefix("pattern:").unwrap_or(choice); + let reserved = choice == "none" || choice == "original" || CornerSource::parse(choice).is_some(); + (!reserved && pattern_names(d).iter().any(|candidate| candidate == name)).then(|| name.to_string()) +} + +pub(super) fn original_available(d: &Dialog, field: &str) -> bool { + let choice = d.str(&tile_key(field)); + let drawn = if field.ends_with("corner") { corner_art_field(d.fields.get("__def"), field) } else { Some(field) }; + drawn.is_some() && pattern_choice(d, &choice).is_none() +} + +pub(super) fn reconcile_pattern_choices(f: &mut Map) { + let names: Vec = f + .get("__patterns") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|v| v.get("name").and_then(Value::as_str).map(str::to_string)) + .collect(); + let def = f.get("__def").cloned().unwrap_or_default(); + for (art, _) in TILES { + let swatch = def.get(format!("{art}_swatch")).and_then(Value::as_str); + if let Some(name) = swatch.filter(|name| names.iter().any(|n| n == name)) { + f.insert(tile_key(art), json!(format!("pattern:{name}"))); + } else if !art.ends_with("corner") { + f.insert(tile_key(art), json!(if def.get(art).is_some_and(|v| !v.is_null()) { "original" } else { "none" })); + } + } +} + /// Pattern brush corner tiles: (dialog field, art field of the definition, source field, art field /// of the other kind of corner). const CORNER_TILES: [(&str, &str, &str, &str); 2] = @@ -63,20 +112,20 @@ fn corner_art_field<'a>(def: Option<&Value>, field: &'a str) -> Option<&'a str> } } -/// The dialog field that records that corner tile `key`'s menu was set. +/// The dialog field that records that tile `key`'s menu was set. fn corner_set_key(key: &str) -> String { format!("__{key}Set") } -/// Sets corner tile `key` to `choice` from its menu. +/// Sets tile `key` to `choice` from its menu. pub(super) fn choose_corner(d: &mut Dialog, key: &str, choice: &str) { d.fields.insert(key.into(), json!(choice)); note_set(d, key); } -/// Records that field `field` was set, from its menu or `ui.dialog.set`, when it is a corner tile. +/// Records that a tile field was set from its menu or `ui.dialog.set`. pub(super) fn note_set(d: &mut Dialog, field: &str) { - if CORNER_TILES.iter().any(|(key, ..)| *key == field) { + if CORNER_TILES.iter().any(|(key, ..)| *key == field) || TILES.iter().any(|(art, _)| tile_key(art) == field) { d.fields.insert(corner_set_key(field), json!(true)); } } @@ -259,18 +308,34 @@ pub(super) fn params(d: &Dialog) -> Value { let def = d.fields.get("__def"); for (key, art, source, other) in CORNER_TILES { let choice = d.str(key); + if let Some(name) = pattern_choice(d, &choice) { + if d.bool(&corner_set_key(key)) { + p[format!("{art}_tile")] = json!({"pattern": name}); + } + continue; + } let unset = |f: &str| def.and_then(|d| d.get(f)).is_none_or(Value::is_null); if choice == CornerSource::None.id() && !d.bool(&corner_set_key(key)) && unset(source) && corner_art_field(def, art).is_none() { continue; } if let Some(s) = CornerSource::parse(&choice) { - p[art] = Value::Null; - p[source] = json!(s.id()); + p[format!("{art}_tile")] = json!(s.id()); } else if choice == "original" && let Some(from) = corner_art_field(def, art).filter(|f| *f != art) && CORNER_TILES.iter().find(|(_, a, _, _)| *a == other).is_some_and(|(k, ..)| d.str(k) != "original") { p[art] = def.and_then(|d| d.get(from)).cloned().unwrap_or_default(); + p[format!("{art}_frame")] = def.and_then(|d| d.get(format!("{from}_frame"))).cloned().unwrap_or(Value::Null); + } + if choice == "original" && d.bool(&corner_set_key(key)) { + p[format!("{art}_tile")] = json!("original"); + } + } + for art in ["side", "start", "end"] { + let key = tile_key(art); + if d.bool(&corner_set_key(&key)) { + let choice = d.str(&key); + p[format!("{art}_tile")] = pattern_choice(d, &choice).map_or_else(|| json!(choice), |name| json!({"pattern": name})); } } p @@ -302,6 +367,35 @@ pub(super) fn edited_def(d: &Dialog) -> Value { if let (Some(o), Value::Object(p)) = (def.as_object_mut(), params(d)) { o.extend(p); } + if d.str("__type") == "pattern" { + for (art, _) in TILES { + let key = tile_key(art); + if !d.bool(&corner_set_key(&key)) { + continue; + } + let choice = d.str(&key); + if choice == "none" || (art.ends_with("corner") && CornerSource::parse(&choice).is_some()) { + def[art] = Value::Null; + def[format!("{art}_frame")] = Value::Null; + def[format!("{art}_swatch")] = Value::Null; + if art.ends_with("corner") { + def[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = json!(choice); + } + } else if choice == "original" { + def[format!("{art}_swatch")] = Value::Null; + } else if let Some(name) = pattern_choice(d, &choice) + && let Some(pattern) = d.fields.get("__patterns").and_then(Value::as_array).and_then(|a| a.iter().find(|p| p["name"] == name)) + && let Ok(pattern) = serde_json::from_value::(pattern.clone()) + { + def[art] = serde_json::to_value(Node::new(NodeId(0), NodeKind::Group { children: pattern.art, clip: false })).unwrap_or_default(); + def[format!("{art}_frame")] = json!(pattern.tile); + def[format!("{art}_swatch")] = json!(name); + if art.ends_with("corner") { + def[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = Value::Null; + } + } + } + } def } @@ -447,12 +541,12 @@ fn pattern_body(ui: &mut egui::Ui, d: &mut Dialog) { radios(ui, d, "fit", &fits); } -/// What a corner tile can be: (choice, label). Original (the corner art the brush draws there) is -/// offered only when the brush draws corner art there. +/// Built-in corner choices. Original is disabled when the slot has no retained art or a listed +/// swatch was selected. fn corner_choices() -> [(&'static str, &'static str); 6] { [ - ("original", tl!("Original")), (CornerSource::None.id(), tl!("None")), + ("original", tl!("Original")), (CornerSource::AutoCentered.id(), tl!("Auto-Centered")), (CornerSource::AutoBetween.id(), tl!("Auto-Between")), (CornerSource::AutoSliced.id(), tl!("Auto-Sliced")), @@ -460,31 +554,47 @@ fn corner_choices() -> [(&'static str, &'static str); 6] { ] } -/// The pattern's five tiles, each with its art (or None when the brush has no such tile). Below -/// each corner tile, a menu sets it to the brush's art, None or a tile made from the side tile. +pub(super) fn tile_choices(d: &Dialog, corner: bool) -> Vec<(String, String)> { + let mut choices: Vec<(String, String)> = if corner { + corner_choices().into_iter().map(|(id, label)| (id.into(), label.into())).collect() + } else { + vec![("none".into(), tl!("None").into()), ("original".into(), tl!("Original").into())] + }; + choices.extend(pattern_names(d).into_iter().map(|name| (format!("pattern:{name}"), name))); + choices +} + +/// The pattern's five tiles, each with its art (or None when the brush has no such tile). A menu +/// below each preview selects retained art, no art, or a document pattern; corners also offer +/// generated choices. fn tiles(ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); let names = [tl!("Outer Corner Tile"), tl!("Side Tile"), tl!("Inner Corner Tile"), tl!("Start Tile"), tl!("End Tile")]; - let keys = d.fields.get("__tiles").cloned(); + let preview_def = edited_def(d); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 6.0; - for ((field, slot), name) in TILES.into_iter().zip(names) { + for ((field, _slot), name) in TILES.into_iter().zip(names) { let corner = CORNER_TILES.iter().find(|(_, art, _, _)| *art == field).map(|(key, ..)| *key); // The art the tile draws with: its own, or a corner's that falls back on the other's. - let drawn = if corner.is_some() { corner_art_field(d.fields.get("__def"), field) } else { Some(field) }; - let drawn_slot = drawn.and_then(|f| TILES.iter().find(|(tf, _)| *tf == f)).map_or(slot, |(_, s)| *s); - let choices: Vec<(&str, &str)> = corner_choices().into_iter().filter(|(c, _)| drawn.is_some() || *c != "original").collect(); - let choice = corner.map(|key| d.str(key)); + let drawn = if corner.is_some() { corner_art_field(Some(&preview_def), field) } else { Some(field) }; + let choice = d.str(&tile_key(field)); + let original_enabled = original_available(d, field); + let choices = tile_choices(d, corner.is_some()); // The label of the corner's choice when it shows no art. - let shown = choice.as_deref().filter(|c| *c != "original"); - let label = shown.and_then(|c| choices.iter().find(|(id, _)| *id == c)).map_or(tl!("None"), |(_, l)| *l); + let shown = (choice != "original" && pattern_choice(d, &choice).is_none()).then_some(choice.as_str()); + let label = shown.and_then(|c| choices.iter().find(|(id, _)| id == c)).map_or(tl!("None"), |(_, l)| l.as_str()); ui.vertical(|ui| { let (r, resp) = ui.allocate_exact_size(vec2(76.0, 44.0), Sense::hover()); ui.painter().rect_filled(r, 0.0, Color32::WHITE); - let key = keys.as_ref().filter(|_| shown.is_none()).and_then(|k| k.get(drawn_slot)).and_then(Value::as_str); - let tex = key.and_then(|key| { + let art_value = drawn.and_then(|f| preview_def.get(f)).filter(|_| shown.is_none()); + let key = art_value.map(|art| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + art.to_string().hash(&mut h); + format!("brush-tile:{:x}", h.finish()) + }); + let tex = key.as_deref().and_then(|key| { widgets::doc_preview(ui, key, r.size(), |w, h| { - let art: Node = serde_json::from_value(d.fields.get("__def")?.get(drawn?)?.clone()).ok()?; + let art: Node = serde_json::from_value(art_value?.clone()).ok()?; tile_doc(&art, w, h) }) }); @@ -499,14 +609,26 @@ fn tiles(ui: &mut egui::Ui, d: &mut Dialog) { ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); resp.on_hover_text(name); ui.add_sized(vec2(76.0, 14.0), egui::Label::new(egui::RichText::new(name).size(10.5).color(t.text_dim)).truncate()); - if let (Some(key), Some(cur)) = (corner, &choice) { - let current = choices.iter().find(|(id, _)| id == cur).map_or(tl!("None"), |(_, l)| *l); - let labels: Vec<&str> = choices.iter().map(|(_, l)| *l).collect(); - if let Some((id, _)) = - widgets::dropdown_named(ui, ("brush-pattern-corner", key), Some(name), current, &labels, 76.0).and_then(|i| choices.get(i)) - { - choose_corner(d, key, id); - } + let current = choices.iter().find(|(id, _)| id == &choice).map_or(tl!("None"), |(_, l)| l.as_str()); + if let Some(id) = widgets::combo_named(ui, ("brush-pattern-tile", field), Some(name), current, 76.0, |ui| { + choices.iter().enumerate().find_map(|(i, (id, label))| { + ui.add_enabled(id != "original" || original_enabled, egui::Button::selectable(id == &choice, label.as_str())) + .clicked() + .then_some(i) + }) + }) + .and_then(|i| choices.get(i).map(|(id, _)| id.clone())) + { + let key = corner.unwrap_or_else(|| { + if field == "side" { + "sideTile" + } else if field == "start" { + "startTile" + } else { + "endTile" + } + }); + choose_corner(d, key, &id); } }); } diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index f03518b161..19a8e9c6e6 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -97,6 +97,10 @@ pub fn open(app: &mut VectorcraftApp, name: Option<&str>) -> Result Option { /// opens. pub(super) fn open_new(app: &mut VectorcraftApp, ty: &str, ids: Option) -> Result { let st = app.session.active().ok_or("no document open")?; + let patterns = serde_json::to_value(&st.doc.patterns).unwrap_or_default(); let title: String = ty.chars().take(1).flat_map(char::to_uppercase).chain(ty.chars().skip(1)).collect(); let name = vectorcraft_brush::unique_name(&vectorcraft_brush::library(&st.doc), &format!("New {title} Brush")); let mut def = json!({ "name": name, "type": ty }); @@ -169,6 +174,8 @@ pub(super) fn open_new(app: &mut VectorcraftApp, ty: &str, ids: Option) - b.sanitize(); let def = serde_json::to_value(&b).map_err(|e| e.to_string())?; let mut f = fields(&b, def)?; + f.insert("__patterns".into(), patterns); + brush_art_options::reconcile_pattern_choices(&mut f); f.insert(CREATE.into(), json!(true)); if let Some(ids) = ids { f.insert(IDS.into(), ids); @@ -183,9 +190,38 @@ pub(super) fn open_new(app: &mut VectorcraftApp, ty: &str, ids: Option) - /// dialog closes once the brush is made. fn create(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut brush_params = params(d); + if d.str("__type") == "pattern" { + if d.str("sideTile") == "none" { + return Err("You must choose a side pattern.".into()); + } + let preview = brush_art_options::edited_def(d); + for key in [ + "side", + "side_frame", + "side_swatch", + "outer_corner", + "outer_corner_frame", + "outer_corner_swatch", + "outer_source", + "inner_corner", + "inner_corner_frame", + "inner_corner_swatch", + "inner_source", + "start", + "start_frame", + "start_swatch", + "end", + "end_frame", + "end_swatch", + ] { + if let Some(value) = preview.get(key) { + brush_params[key] = value.clone(); + } + } + } if let Some(def) = d.fields.get("__def") { for key in ["art", "side"] { - if let Some(art) = def.get(key).filter(|v| !v.is_null()) { + if let Some(art) = def.get(key).filter(|v| !v.is_null() && brush_params.get(key).is_none_or(Value::is_null)) { brush_params[key] = art.clone(); } } diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 9adeffed1b..83fe73e3c1 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -458,7 +458,7 @@ fn pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile() assert!(roles.contains(&egui::accesskit::Role::ComboBox), "a menu named {name}: {roles:?}"); } for name in ["Side Tile", "Start Tile", "End Tile"] { - assert!(!shown_tree.iter().any(|n| n.label() == Some(name) && n.role() == egui::accesskit::Role::ComboBox), "no menu for {name}"); + assert!(shown_tree.iter().any(|n| n.label() == Some(name) && n.role() == egui::accesskit::Role::ComboBox), "a menu for {name}"); } set(&mut app, json!({"outerCornerTile": "autoBetween", "innerCornerTile": "autoOverlap"})); let text = shown(&mut app); @@ -492,6 +492,98 @@ fn pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile() assert_eq!(app.ui.dialog.as_ref().unwrap().str("outerCornerTile"), "autoSliced"); } +#[test] +fn pattern_tile_menus_use_document_patterns_and_side_none_keeps_dialog_open() { + use std::sync::Arc; + use vectorcraft_doc::{Node, PatternDef}; + use vectorcraft_geom::Rect; + + let mut app = app(); + app.session + .edit("Pattern", |doc, _| { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Wide", vec![Arc::new(art)]) }); + Ok(()) + }) + .unwrap(); + let before = app.run("brush.get", json!({"name":"Diamonds"})).unwrap(); + app.run("ui.brushOptions", json!({"name":"Diamonds"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(crate::dialogs::brush_art_options::pattern_names(d), vec!["Wide".to_string()]); + for key in ["sideTile", "outerCornerTile", "innerCornerTile", "startTile", "endTile"] { + assert!(d.fields.contains_key(key), "{key}"); + } + for corner in [false, true] { + let ids: Vec<_> = crate::dialogs::brush_art_options::tile_choices(d, corner).into_iter().map(|(id, _)| id).collect(); + assert!(ids.contains(&"pattern:Wide".to_string())); + if corner { + for auto in ["autoCentered", "autoBetween", "autoSliced", "autoOverlap"] { + assert!(ids.contains(&auto.to_string())); + } + } else { + assert_eq!(ids.first().map(String::as_str), Some("none")); + assert_eq!(ids.get(1).map(String::as_str), Some("original")); + } + } + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, "sideTile", "Wide"); + assert!(!crate::dialogs::brush_art_options::original_available(d, "side")); + let preview = crate::dialogs::brush_art_options::edited_def(d); + assert_eq!(preview["side_frame"], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); + assert_ne!(preview["side"], before["side"]); + super::super::confirm(&mut app).unwrap(); + app.session + .edit("Delete pattern", |doc, _| { + doc.patterns.clear(); + Ok(()) + }) + .unwrap(); + app.run("ui.brushOptions", json!({"name":"Diamonds"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("sideTile"), "original"); + let saved = app.run("brush.get", json!({"name":"Diamonds"})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, "sideTile", "none"); + let error = super::super::confirm(&mut app).unwrap_err(); + assert!(error.contains("You must choose a side pattern."), "{error}"); + assert!(app.ui.dialog.is_some()); + assert_eq!(app.run("brush.get", json!({"name":"Diamonds"})).unwrap(), saved); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); +} + +#[test] +fn new_pattern_brush_keeps_a_tile_swatch_choice() { + use std::sync::Arc; + use vectorcraft_doc::{Node, PatternDef}; + use vectorcraft_geom::Rect; + + let mut app = app(); + app.run("shape.rectangle", json!({"x":0,"y":0,"width":20,"height":4})).unwrap(); + app.session + .edit("Pattern", |doc, _| { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Wide", vec![Arc::new(art)]) }); + Ok(()) + }) + .unwrap(); + super::open_new(&mut app, "pattern", None).unwrap(); + let name = app.ui.dialog.as_ref().unwrap().str("name"); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, "sideTile", "Wide"); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name":name})).unwrap(); + assert_eq!(def["side_swatch"], "Wide"); + assert_eq!(def["side_frame"], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); +} + /// A pattern brush with art for one kind of corner draws it at both kinds. Its other corner tile /// shows that art as Original, and OK keeps it there when the first corner tile changes. #[test] @@ -509,6 +601,115 @@ fn pattern_options_keep_the_corner_art_a_corner_borrows() { assert_eq!(def["outer_source"], json!("none")); } +#[test] +fn pattern_options_preview_and_save_borrowed_corner_before_clearing_source() { + use vectorcraft_geom::Rect; + + let mut app = app(); + let chain = app.run("brush.get", json!({"name": "Chain"})).unwrap(); + let art = chain["outer_corner"].clone(); + let frame = json!(Rect::new(1.0, 2.0, 15.0, 18.0)); + for (name, source, borrowed) in [("Borrow Outer", "inner", "outer"), ("Borrow Inner", "outer", "inner")] { + let source_art = format!("{source}_corner"); + let source_frame = format!("{source_art}_frame"); + let borrowed_art = format!("{borrowed}_corner"); + let borrowed_frame = format!("{borrowed_art}_frame"); + let source_tile = format!("{source}CornerTile"); + let borrowed_tile = format!("{borrowed}CornerTile"); + app.run("brush.new", json!({"type":"pattern", "name":name, "params":{"side":chain["side"], source_art:art, source_frame:frame}})).unwrap(); + app.run("ui.brushOptions", json!({"name":name})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, &source_tile, "none"); + crate::dialogs::brush_art_options::choose_corner(d, &borrowed_tile, "original"); + let preview = crate::dialogs::brush_art_options::edited_def(d); + assert_eq!(preview[&borrowed_art], chain["outer_corner"], "{borrowed} preview art"); + assert_eq!(preview[&borrowed_frame], frame, "{borrowed} preview frame"); + super::super::confirm(&mut app).unwrap(); + let saved = app.run("brush.get", json!({"name":name})).unwrap(); + assert_eq!(saved[&borrowed_art], chain["outer_corner"], "{borrowed} saved art"); + assert_eq!(saved[&borrowed_frame], frame, "{borrowed} saved frame"); + } +} + +#[test] +fn pattern_options_borrowed_swatch_corner_keeps_its_frame() { + use std::sync::Arc; + use vectorcraft_doc::{Node, PatternDef}; + use vectorcraft_geom::Rect; + + let mut app = app(); + app.session + .edit("Pattern", |doc, _| { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Corner", vec![Arc::new(art)]) }); + Ok(()) + }) + .unwrap(); + let side = app.run("brush.get", json!({"name":"Diamonds"})).unwrap()["side"].clone(); + app.run("brush.new", json!({"type":"pattern", "name":"Borrow", "params":{"side":side}})).unwrap(); + app.run("brush.options", json!({"name":"Borrow", "params":{"outer_corner_tile":{"pattern":"Corner"}}})).unwrap(); + let before = app.run("brush.get", json!({"name":"Borrow"})).unwrap(); + app.run("ui.brushOptions", json!({"name":"Borrow"})).unwrap(); + set(&mut app, json!({"outerCornerTile":"none"})); + super::super::confirm(&mut app).unwrap(); + let after = app.run("brush.get", json!({"name":"Borrow"})).unwrap(); + assert_eq!(after["inner_corner"], before["outer_corner"]); + assert_eq!(after["inner_corner_frame"], before["outer_corner_frame"]); + assert_eq!(after["outer_source"], json!("none")); +} + +#[test] +fn pattern_options_selects_swatches_with_reserved_names() { + use std::sync::Arc; + use vectorcraft_doc::{Node, PatternDef}; + use vectorcraft_geom::Rect; + + let mut app = app(); + let names = ["none", "original", "autoCentered", "autoBetween", "autoSliced", "autoOverlap"]; + app.session + .edit("Patterns", |doc, _| { + for name in names { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new(name, vec![Arc::new(art)]) }); + } + Ok(()) + }) + .unwrap(); + app.run("ui.brushOptions", json!({"name":"Diamonds"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + for name in names { + let choice = (format!("pattern:{name}"), name.to_string()); + assert!(crate::dialogs::brush_art_options::tile_choices(d, true).contains(&choice)); + } + for (field, name) in [ + ("sideTile", "none"), + ("outerCornerTile", "original"), + ("innerCornerTile", "autoCentered"), + ("startTile", "autoBetween"), + ("endTile", "autoSliced"), + ] { + crate::dialogs::brush_art_options::choose_corner(app.ui.dialog.as_mut().unwrap(), field, &format!("pattern:{name}")); + } + let preview = crate::dialogs::brush_art_options::edited_def(app.ui.dialog.as_ref().unwrap()); + assert_eq!(preview["side_swatch"], "none"); + super::super::confirm(&mut app).unwrap(); + let saved = app.run("brush.get", json!({"name":"Diamonds"})).unwrap(); + for (art, name) in + [("side", "none"), ("outer_corner", "original"), ("inner_corner", "autoCentered"), ("start", "autoBetween"), ("end", "autoSliced")] + { + assert_eq!(saved[format!("{art}_swatch")], name); + assert_eq!(saved[format!("{art}_frame")], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); + } +} + /// OK leaves the corner fields of a corner tile the menus were not set to as they were: a corner /// without art keeps borrowing the other kind's art when it gets some, and a corner that borrows /// art still borrows it. A None picked from the menu is saved, after another choice too. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 0888ac645d..2104ac7af6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5899,6 +5899,9 @@ breakText Glyphs Глифи Gap 4 Разстояние 4 Dash 5 Тире 5 Gap 5 Разстояние 5 +@msg You must choose a side pattern. Трябва да изберете страничен шаблон. +@msg invalid pattern tile choice невалиден избор на плочка за шаблон +@msg no pattern named `{choice}` няма шаблон с име `{choice}` Delete the selected brushes? Да се изтрият избраните четки? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Щрихи използват една или повече от тези четки. Да се премахнат ли четките от тези щрихи и да се изтрият четките? Remove Strokes Премахване на щрихи diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d89af156f8..2d42bf75d5 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5931,6 +5931,9 @@ shape Open Otvoren @msg `follow` must be "average", "a" or "b" `follow` mora biti "average", "a" ili "b" @msg the paths have nothing to merge there putanje tu nemaju šta spojiti @msg the path is locked or hidden putanja je zaključana ili skrivena +@msg You must choose a side pattern. Morate odabrati bočni uzorak. +@msg invalid pattern tile choice nevažeći izbor pločice uzorka +@msg no pattern named `{choice}` nema uzorka pod nazivom `{choice}` Delete the selected brushes? Izbrisati odabrane četkice? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Potezi koriste jednu ili više ovih četkica. Ukloniti četkice s tih poteza i izbrisati četkice? Remove Strokes Ukloni poteze diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 15bd85222d..b7a1506662 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5999,6 +5999,9 @@ breakText Glyphs Glifs Gap 4 Separació 4 Dash 5 Guió 5 Gap 5 Separació 5 +@msg You must choose a side pattern. Heu de triar un patró lateral. +@msg invalid pattern tile choice opció de mosaic de patró no vàlida +@msg no pattern named `{choice}` no hi ha cap patró anomenat `{choice}` Delete the selected brushes? Voleu suprimir els pinzells seleccionats? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Hi ha traços que fan servir un o més d’aquests pinzells. Voleu treure els pinzells d’aquests traços i suprimir els pinzells? Remove Strokes Elimina els traços diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index fe80401bc1..75765ab754 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6008,6 +6008,9 @@ breakText Glyphs Glyfy Gap 4 Mezera 4 Dash 5 Čárka 5 Gap 5 Mezera 5 +@msg You must choose a side pattern. Musíte zvolit boční vzorek. +@msg invalid pattern tile choice neplatná volba dlaždice vzorku +@msg no pattern named `{choice}` vzorek s názvem `{choice}` neexistuje Delete the selected brushes? Odstranit vybrané štětce? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Tahy používají jeden nebo více z těchto štětců. Odebrat štětce z těchto tahů a odstranit štětce? Remove Strokes Odebrat tahy diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 74107e22cb..8140d38e19 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5913,6 +5913,9 @@ breakText Glyphs Glyffer Gap 4 Mellemrum 4 Dash 5 Streg 5 Gap 5 Mellemrum 5 +@msg You must choose a side pattern. Du skal vælge et sidemønster. +@msg invalid pattern tile choice ugyldigt valg af mønsterflise +@msg no pattern named `{choice}` intet mønster med navnet `{choice}` Delete the selected brushes? Slet de valgte pensler? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Streger bruger en eller flere af disse pensler. Fjern penslerne fra stregerne, og slet penslerne? Remove Strokes Fjern streger diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 447c98350d..fa638758f3 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5594,6 +5594,9 @@ breakText Glyphs Glyphen Gap 4 Lücke 4 Dash 5 Strich 5 Gap 5 Lücke 5 +@msg You must choose a side pattern. Sie müssen ein Seitenmuster auswählen. +@msg invalid pattern tile choice ungültige Auswahl einer Musterkachel +@msg no pattern named `{choice}` kein Muster mit dem Namen `{choice}` Delete the selected brushes? Ausgewählte Pinsel löschen? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturen verwenden einen oder mehrere dieser Pinsel. Pinsel von diesen Konturen entfernen und die Pinsel löschen? Remove Strokes Konturen entfernen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 8dea59f7f0..baf6f52ec9 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5961,6 +5961,9 @@ breakText Glyphs Γλύφοι Gap 4 Διάκενο 4 Dash 5 Παύλα 5 Gap 5 Διάκενο 5 +@msg You must choose a side pattern. Πρέπει να επιλέξετε πλευρικό μοτίβο. +@msg invalid pattern tile choice μη έγκυρη επιλογή πλακιδίου μοτίβου +@msg no pattern named `{choice}` δεν υπάρχει μοτίβο με όνομα `{choice}` Delete the selected brushes? Να διαγραφούν τα επιλεγμένα πινέλα; Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Περιγράμματα χρησιμοποιούν ένα ή περισσότερα από αυτά τα πινέλα. Να αφαιρεθούν τα πινέλα από αυτά τα περιγράμματα και να διαγραφούν τα πινέλα; Remove Strokes Αφαίρεση περιγραμμάτων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e6c7dd7690..7b5b6aae3e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5951,6 +5951,9 @@ breakText Glyphs Glifos Gap 4 Hueco 4 Dash 5 Guion 5 Gap 5 Hueco 5 +@msg You must choose a side pattern. Debe elegir un motivo lateral. +@msg invalid pattern tile choice selección de mosaico de motivo no válida +@msg no pattern named `{choice}` no hay ningún motivo llamado `{choice}` Delete the selected brushes? ¿Eliminar los pinceles seleccionados? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Algunos trazos usan uno o más de estos pinceles. ¿Quitar los pinceles de esos trazos y eliminar los pinceles? Remove Strokes Quitar trazos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 08122ed024..606118dba8 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6039,6 +6039,9 @@ breakText Glyphs Merkit Gap 4 Väli 4 Dash 5 Viiva 5 Gap 5 Väli 5 +@msg You must choose a side pattern. Valitse sivukuvio. +@msg invalid pattern tile choice virheellinen kuviolaatan valinta +@msg no pattern named `{choice}` kuviota nimeltä `{choice}` ei löydy Delete the selected brushes? Poistetaanko valitut siveltimet? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Viivat käyttävät yhtä tai useampaa näistä siveltimistä. Irrotetaanko siveltimet näistä viivoista ja poistetaanko siveltimet? Remove Strokes Poista viivat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b35297550a..5e8203d511 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6006,6 +6006,9 @@ breakText Glyphs Glyphes Gap 4 Écart 4 Dash 5 Tiret 5 Gap 5 Écart 5 +@msg You must choose a side pattern. Vous devez choisir un motif latéral. +@msg invalid pattern tile choice choix de tuile de motif non valide +@msg no pattern named `{choice}` aucun motif nommé `{choice}` Delete the selected brushes? Supprimer les formes sélectionnées ? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Des contours utilisent une ou plusieurs de ces formes. Retirer les formes de ces contours et supprimer les formes ? Remove Strokes Supprimer les contours diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index cac7189ed7..aec44044da 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5995,6 +5995,9 @@ breakText Glyphs Glifák Gap 4 Hézag 4 Dash 5 Vonal 5 Gap 5 Hézag 5 +@msg You must choose a side pattern. Válasszon oldalsó mintát. +@msg invalid pattern tile choice érvénytelen mintacsempe-választás +@msg no pattern named `{choice}` nincs `{choice}` nevű minta Delete the selected brushes? Törlöd a kijelölt ecseteket? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Körvonalak használnak egyet vagy többet ezek közül az ecsetek közül. Leveszed az ecseteket ezekről a körvonalakról, és törlöd az ecseteket? Remove Strokes Körvonalak eltávolítása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 29e87826ab..5329eea88d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5913,6 +5913,9 @@ breakText Glyphs Glif Gap 4 Jarak 4 Dash 5 Garis 5 Gap 5 Jarak 5 +@msg You must choose a side pattern. Anda harus memilih pola sisi. +@msg invalid pattern tile choice pilihan ubin pola tidak valid +@msg no pattern named `{choice}` tidak ada pola bernama `{choice}` Delete the selected brushes? Hapus kuas yang dipilih? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Stroke menggunakan satu atau beberapa kuas ini. Lepaskan kuas dari stroke tersebut dan hapus kuasnya? Remove Strokes Hapus Stroke diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 51870220aa..34c18549d2 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5628,6 +5628,9 @@ breakText Glyphs Glifi Gap 4 Spazio 4 Dash 5 Tratto 5 Gap 5 Spazio 5 +@msg You must choose a side pattern. Devi scegliere un motivo laterale. +@msg invalid pattern tile choice scelta della tessera motivo non valida +@msg no pattern named `{choice}` nessun motivo chiamato `{choice}` Delete the selected brushes? Eliminare i pennelli selezionati? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Alcune tracce usano uno o più di questi pennelli. Rimuovere i pennelli da queste tracce ed eliminare i pennelli? Remove Strokes Rimuovi tracce diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c6c4227b6b..5d8e120742 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5694,6 +5694,9 @@ breakText Glyphs 字形 Gap 4 間隔 4 Dash 5 線分 5 Gap 5 間隔 5 +@msg You must choose a side pattern. 側面パターンを選択してください。 +@msg invalid pattern tile choice パターンタイルの選択が無効です +@msg no pattern named `{choice}` `{choice}` というパターンはありません Delete the selected brushes? 選択したブラシを削除しますか? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? これらのブラシの 1 つ以上が線で使われています。それらの線からブラシを外して、ブラシを削除しますか? Remove Strokes 線を削除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index c02d40eb17..ab0f0704d5 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5998,6 +5998,9 @@ breakText Glyphs გლიფები Gap 4 შუალედი 4 Dash 5 ტირე 5 Gap 5 შუალედი 5 +@msg You must choose a side pattern. აირჩიეთ გვერდითი ნიმუში. +@msg invalid pattern tile choice ნიმუშის ფილა არასწორად არის არჩეული +@msg no pattern named `{choice}` ნიმუში სახელით `{choice}` არ არსებობს Delete the selected brushes? წაიშალოს არჩეული ფუნჯები? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? კონტურები იყენებს ამ ფუნჯებიდან ერთს ან მეტს. მოიხსნას ფუნჯები ამ კონტურებიდან და წაიშალოს ფუნჯები? Remove Strokes კონტურების მოხსნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5c24bd9ca2..5da60d2476 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5591,6 +5591,9 @@ breakText Glyphs 글리프 Gap 4 간격 4 Dash 5 대시 5 Gap 5 간격 5 +@msg You must choose a side pattern. 측면 패턴을 선택해야 합니다. +@msg invalid pattern tile choice 잘못된 패턴 타일 선택 +@msg no pattern named `{choice}` `{choice}` 이름의 패턴이 없습니다 Delete the selected brushes? 선택한 브러시를 삭제하시겠습니까? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 선에서 이 브러시 중 하나 이상을 사용합니다. 해당 선에서 브러시를 제거하고 브러시를 삭제하시겠습니까? Remove Strokes 선 제거 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 282b0a4aad..ee4e09b61f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5957,6 +5957,9 @@ breakText Glyphs Glyphs Gap 4 Tussenruimte 4 Dash 5 Streepje 5 Gap 5 Tussenruimte 5 +@msg You must choose a side pattern. Kies een zijpatroon. +@msg invalid pattern tile choice ongeldige keuze voor patroontegel +@msg no pattern named `{choice}` geen patroon met de naam `{choice}` Delete the selected brushes? Geselecteerde kwasten verwijderen? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Contouren gebruiken een of meer van deze kwasten. De kwasten van deze contouren halen en de kwasten verwijderen? Remove Strokes Contouren verwijderen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 3999714470..5c90b4d977 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5864,6 +5864,9 @@ breakText Glyphs Glify Gap 4 Odstęp 4 Dash 5 Kreska 5 Gap 5 Odstęp 5 +@msg You must choose a side pattern. Musisz wybrać wzór boczny. +@msg invalid pattern tile choice nieprawidłowy wybór kafelka wzoru +@msg no pattern named `{choice}` nie ma wzoru o nazwie `{choice}` Delete the selected brushes? Usunąć zaznaczone pędzle? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Obrysy używają co najmniej jednego z tych pędzli. Zdjąć pędzle z tych obrysów i usunąć pędzle? Remove Strokes Usuń obrysy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4f75dd659d..0694d8f183 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5928,6 +5928,9 @@ breakText Glyphs Glifos Gap 4 Lacuna 4 Dash 5 Traço 5 Gap 5 Lacuna 5 +@msg You must choose a side pattern. Você deve escolher um padrão lateral. +@msg invalid pattern tile choice escolha inválida de ladrilho de padrão +@msg no pattern named `{choice}` não há padrão chamado `{choice}` Delete the selected brushes? Excluir os pincéis selecionados? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Traçados usam um ou mais destes pincéis. Remover os pincéis desses traçados e excluir os pincéis? Remove Strokes Remover Traçados diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d412fa13bc..105ba72d17 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5986,6 +5986,9 @@ breakText Glyphs Глифы Gap 4 Зазор 4 Dash 5 Штрих 5 Gap 5 Зазор 5 +@msg You must choose a side pattern. Выберите боковой узор. +@msg invalid pattern tile choice недопустимый выбор плитки узора +@msg no pattern named `{choice}` узор с именем `{choice}` не найден Delete the selected brushes? Удалить выбранные кисти? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обводки используют одну или несколько из этих кистей. Убрать кисти с этих обводок и удалить кисти? Remove Strokes Убрать обводки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 2a1ba37453..4831119887 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6061,6 +6061,9 @@ breakText Glyphs Glyfer Gap 4 Mellanrum 4 Dash 5 Streck 5 Gap 5 Mellanrum 5 +@msg You must choose a side pattern. Du måste välja ett sidomönster. +@msg invalid pattern tile choice ogiltigt val av mönsterplatta +@msg no pattern named `{choice}` inget mönster med namnet `{choice}` Delete the selected brushes? Radera de valda penslarna? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturer använder en eller flera av de här penslarna. Ta bort penslarna från konturerna och radera penslarna? Remove Strokes Ta bort konturer diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 215b7f8e6d..23bdb68391 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5966,6 +5966,9 @@ breakText Glyphs Glifler Gap 4 Boşluk 4 Dash 5 Çizgi 5 Gap 5 Boşluk 5 +@msg You must choose a side pattern. Bir yan desen seçmelisiniz. +@msg invalid pattern tile choice geçersiz desen döşemesi seçimi +@msg no pattern named `{choice}` `{choice}` adlı desen yok Delete the selected brushes? Seçili fırçalar silinsin mi? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturlar bu fırçalardan birini veya daha fazlasını kullanıyor. Fırçalar bu konturlardan kaldırılsın ve fırçalar silinsin mi? Remove Strokes Konturları Kaldır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 13fab3c518..dde23c7422 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5608,6 +5608,9 @@ breakText Glyphs Гліфи Gap 4 Проміжок 4 Dash 5 Штрих 5 Gap 5 Проміжок 5 +@msg You must choose a side pattern. Виберіть бічний візерунок. +@msg invalid pattern tile choice недійсний вибір плитки візерунка +@msg no pattern named `{choice}` візерунка з назвою `{choice}` немає Delete the selected brushes? Видалити вибрані пензлі? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обведення використовують один або кілька з цих пензлів. Забрати пензлі з цих обведень і видалити пензлі? Remove Strokes Забрати обведення diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f45d5d04ae..e060c09993 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5610,6 +5610,9 @@ breakText Glyphs Glyph Gap 4 Khoảng hở 4 Dash 5 Nét 5 Gap 5 Khoảng hở 5 +@msg You must choose a side pattern. Bạn phải chọn mẫu bên. +@msg invalid pattern tile choice lựa chọn ô mẫu không hợp lệ +@msg no pattern named `{choice}` không có mẫu tên `{choice}` Delete the selected brushes? Xóa các cọ đã chọn? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Có nét đang dùng một hoặc nhiều cọ này. Gỡ cọ khỏi các nét đó và xóa cọ? Remove Strokes Gỡ nét diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 4e105573f1..65842950a7 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5850,6 +5850,9 @@ breakText Glyphs 字形 Gap 4 间隔 4 Dash 5 虚线 5 Gap 5 间隔 5 +@msg You must choose a side pattern. 必须选择侧边图案。 +@msg invalid pattern tile choice 图案拼块选项无效 +@msg no pattern named `{choice}` 没有名为 `{choice}` 的图案 Delete the selected brushes? 删除选中的画笔吗? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有描边使用了其中一个或多个画笔。要从这些描边移除画笔并删除画笔吗? Remove Strokes 移除描边 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index acb8291996..fb06daa662 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5647,6 +5647,9 @@ breakText Glyphs 字符 Gap 4 間隙 4 Dash 5 虛線 5 Gap 5 間隙 5 +@msg You must choose a side pattern. 必須選擇側邊圖樣。 +@msg invalid pattern tile choice 圖樣拼塊選項無效 +@msg no pattern named `{choice}` 沒有名為 `{choice}` 的圖樣 Delete the selected brushes? 要刪除選取的筆刷嗎? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有筆畫使用了其中一個或多個筆刷。要從這些筆畫移除筆刷並刪除筆刷嗎? Remove Strokes 移除筆畫 diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 107350b749..c6b855ffdc 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -40,7 +40,7 @@ pub use color::{ pub use drag::{PanelDrag, SwatchRows, art_drop, doc_preview, drag_source}; #[cfg(test)] use dropdowns::combo_button_id; -pub(crate) use dropdowns::{combo, combo_menu}; +pub(crate) use dropdowns::{combo, combo_menu, combo_named}; pub use dropdowns::{ dropdown, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, diff --git a/docs/gaps.md b/docs/gaps.md index b7ffe7f758..072ee477a3 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -536,13 +536,11 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall dragging one onto the Brushes panel adds it; Save Brushes / Save Brush Library writes the document's brushes as a `.vectorcraft` library into the user library folder (listed under User Defined) or a file (`brush.libraries`, `brush.addFromLibrary`, `brush.saveLibrary`, `brush.loadLibrary`). -- **Missing:** the Art brush's Overlap, auto-generated Pattern brush corners, new tile art in Pattern Brush - Options; more built-in brush, symbol and graphic-style libraries (original, generated in code, never - Adobe's); dynamic symbols; Global Edit of similar groups (edits to an object inside a group reaching the - matching objects of similar groups, [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)), +- **Missing:** the Art brush's Overlap; more built-in brush, symbol and graphic-style libraries (original, + generated in code, never Adobe's); dynamic symbols; Global Edit of similar groups (edits to an object inside a + group reaching the matching objects of similar groups, [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)), rotated copies as matches, Shift-click to leave a match out and highlighting matches before the start; drawing the 9-slice guides on the canvas in symbol edit mode and scaling by them. - Options; more built-in brush and symbol libraries (original, never Adobe's); dynamic symbols; Start Global Edit; drawing the 9-slice guides on the canvas in symbol edit mode and scaling by them. - **Estimate:** 15–26 h. ## G3 3D and Materials diff --git a/docs/mcp.md b/docs/mcp.md index 1f843271e9..0595340df1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1578,7 +1578,12 @@ already walks Image Trace. Short agent entry points: what that kind of corner draws when the brush has no `outer_corner` or `inner_corner` art for it: `none` draws no corner tile, and `autoCentered`, `autoBetween`, `autoSliced` and `autoOverlap` make one from the side tile. Without a source, the corner draws the other kind of corner's art. `brush.options {params: {outer_corner: null}}` removes - the art. + the art. Pattern Brush Options also accepts `side_tile`, `outer_corner_tile`, `inner_corner_tile`, + `start_tile` and `end_tile` in `params`. Each takes `none`, `original` or the name of a pattern + swatch in the active document, and `{"pattern": ""}` names a swatch even when its name is one of those + words. Corner tiles also take `autoCentered`, `autoBetween`, `autoSliced` and `autoOverlap`. A swatch choice copies its whole art and tile frame into the brush. `original` + keeps the current art and clears its swatch label. `side_tile: "none"` fails with "You must choose a + side pattern." An unknown swatch name also fails; neither error edits the brush or adds an Undo step. - Variables: `variable.list`, `variable.define {name, kind: text|visibility|image|graph}`, `variable.bind {variable, ids?}`, `variable.makeTextDynamic`, `variable.makeVisibilityDynamic`, `variable.makeImageDynamic`, `variable.makeGraphDynamic`, `variable.unbind`, `variable.rename`, `variable.delete`, `variable.highlight` (image values are file paths, graph diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c53382a210..3d706ba6bb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -954,7 +954,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. Points in different models mix in display RGB, and a CMYK document stores the result as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty more arrowheads, and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random or Pressure with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values or Pressure from the first at the lightest pressure to the second at the heaviest; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Still to come: the Art brush's Overlap, auto-generated Pattern brush corners, new tile art picked in Pattern Brush Options, Stylus Wheel, Tilt, Bearing and Rotation, and pen pressure on macOS. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random or Pressure with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values or Pressure from the first at the lightest pressure to the second at the heaviest; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Still to come: the Art brush's Overlap, Stylus Wheel, Tilt, Bearing and Rotation, and pen pressure on macOS. Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. Stylus Wheel, Tilt, Bearing and Rotation are not built. @@ -968,6 +968,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). A rename in Brush Options and Delete Brush change every stroke that paints with the brush: in the layers and opacity masks, symbols, graph designs, pattern tiles, graphic styles and the art of other brushes. A rename gives those strokes the new name, and Delete Brush makes them plain strokes, in one undo step. In Pattern Brush Options, a menu below the Outer Corner Tile and the Inner Corner Tile sets each to the brush's own corner art (Original), None, or a tile made from the side tile: Auto-Centered stretches one side tile around the corner, Auto-Between bends a side tile on each side into the corner's diagonal, Auto-Sliced cuts a side tile on each side along the diagonal, and Auto-Overlap runs a side tile on each side past the corner. Auto-Sliced masks the tiles at the diagonal, so their outlines stay as drawn. Brushes saved without these choices draw their corners as before (`brush.options` `outer_source`, `inner_source`). Evidence: `tests::pattern_auto_corners_fill_each_corner_of_a_square`, `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), `dialogs::brush_options::tests::pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile` (vectorcraft-ui-egui). + - The [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) page describes up to five Pattern brush tiles: sides, inner corner, outer corner, beginning and end. The archived [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says to add pattern tiles to the Swatches panel and select a swatch from the scroll list for each tile. Pattern Brush Options offers document pattern swatches in all five tile menus, including swatches named like built-in choices. The brush copies each swatch's whole art and tile frame. Side requires art; explicit None on a corner prevents fallback to the other corner's art. After a swatch is deleted, the brush keeps drawing its copied art and shows it as Original. The cited pages do not describe copying the whole art, requiring Side, suppressing corner fallback after explicit None, or showing deleted swatch art as Original. `brush.options` accepts swatch names and an object form for names that match built-in choices, and rejects unknown patterns before editing. Evidence: `tests::brushsym::pattern_tile_choices_copy_whole_swatch_art_and_reject_invalid_side` and `tests::brushsym::pattern_tile_object_selects_reserved_swatch_names` (vectorcraft-engine), `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), and `dialogs::brush_options::tests::pattern_tile_menus_use_document_patterns_and_side_none_keeps_dialog_open`, `dialogs::brush_options::tests::pattern_options_borrowed_swatch_corner_keeps_its_frame`, and `dialogs::brush_options::tests::pattern_options_selects_swatches_with_reserved_names` (vectorcraft-ui-egui). - **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups, whose blend-mode list and opacity slider stay open inside them (#430; the Control bar's Stroke popover too); Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export. Groups, layers and type have their own fills, strokes and effects (Contents and Characters rows); the Layers panel's target circles target layers, groups and objects; Expand Appearance turns fills, strokes, effects and brushes into objects. Fill and stroke paint (Fill, Stroke, None, Apply Last Color and Apply Last Gradient, also on characters selected with the Type tool), the Stroke panel's options, gradient and freeform point edits, Swap Fill and Stroke, Default Fill and Stroke, the Eyedropper, and the Appearance panel's item edits, Clear Appearance, Reduce to Basic Appearance, Remove Item, item reordering and Move Appearance record no undo step when they change nothing. An image's own fills and strokes draw the shape that a Convert to Shape or Outline Object effect on them gives them (the image's box or its frame, reshaped by the effects after it), under or over the image as its Contents row says, on the canvas, in exports and through Expand Appearance; new fills and strokes on an image go under it. Without one of those effects they draw nothing, and Use Preview Bounds measures an image by its frame. From 9896f633dabeb52e04cbf3ddafcf6798d784eb95 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 00:39:08 +0700 Subject: [PATCH 31/70] Type: Kerning has an Optical option that spaces characters by their shapes Squashed from #4825 onto main. --- crates/doc/src/tests.rs | 12 + crates/doc/src/text/char_style.rs | 6 +- crates/doc/src/text/tabs_lists.rs | 1 + crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/panelcmds.rs | 19 +- crates/engine/src/cmd/textedit.rs | 97 ++++++- crates/engine/src/cmd/textstyles.rs | 1 + crates/engine/src/cmd/textstyles/tests.rs | 14 + crates/engine/src/tests/textedit.rs | 164 ++++++++++- crates/text/src/shape.rs | 282 ++++++++++++++++++- crates/text/src/test_fonts.rs | 75 +++++ crates/text/src/tests/typo.rs | 261 +++++++++++++++++ crates/text/src/tests/vertical.rs | 24 ++ crates/ui-egui/src/i18n/bg.tsv | 4 +- crates/ui-egui/src/i18n/bs.tsv | 4 +- crates/ui-egui/src/i18n/ca.tsv | 4 +- crates/ui-egui/src/i18n/cs.tsv | 4 +- crates/ui-egui/src/i18n/da.tsv | 4 +- crates/ui-egui/src/i18n/de.tsv | 4 +- crates/ui-egui/src/i18n/el.tsv | 4 +- crates/ui-egui/src/i18n/es.tsv | 4 +- crates/ui-egui/src/i18n/fi.tsv | 4 +- crates/ui-egui/src/i18n/fr.tsv | 4 +- crates/ui-egui/src/i18n/hu.tsv | 4 +- crates/ui-egui/src/i18n/id.tsv | 4 +- crates/ui-egui/src/i18n/it.tsv | 4 +- crates/ui-egui/src/i18n/ja.tsv | 4 +- crates/ui-egui/src/i18n/ka.tsv | 4 +- crates/ui-egui/src/i18n/ko.tsv | 4 +- crates/ui-egui/src/i18n/nl.tsv | 4 +- crates/ui-egui/src/i18n/pl.tsv | 4 +- crates/ui-egui/src/i18n/pt-br.tsv | 4 +- crates/ui-egui/src/i18n/ru.tsv | 4 +- crates/ui-egui/src/i18n/sv.tsv | 4 +- crates/ui-egui/src/i18n/tests.rs | 2 +- crates/ui-egui/src/i18n/tr.tsv | 4 +- crates/ui-egui/src/i18n/uk.tsv | 4 +- crates/ui-egui/src/i18n/vi.tsv | 4 +- crates/ui-egui/src/i18n/zh-hans.tsv | 4 +- crates/ui-egui/src/i18n/zh-hant.tsv | 4 +- crates/ui-egui/src/panels/character.rs | 60 +++- crates/ui-egui/src/panels/character/tests.rs | 32 +++ crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/numeric.rs | 59 +++- docs/mcp.md | 13 +- docs/target-app-parity.md | 3 +- docs/typography-lettering.md | 2 +- 47 files changed, 1165 insertions(+), 69 deletions(-) diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a13fb21680..0b205a5b16 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -388,6 +388,18 @@ fn char_position_round_trips() { assert!((scale - 0.583).abs() < 1e-9 && (shift + 3.33).abs() < 1e-9); } +#[test] +fn optical_kerning_round_trips_and_old_style_defaults_to_auto() { + let st = CharStyle { optical_kerning: true, kerning: Some(120.0), ..CharStyle::default() }; + let value = serde_json::to_value(&st).unwrap(); + assert_eq!(value["opticalKerning"], true); + assert_eq!(serde_json::from_value::(value.clone()).unwrap(), st); + let mut old = value; + old.as_object_mut().unwrap().remove("opticalKerning"); + assert!(!serde_json::from_value::(old).unwrap().optical_kerning); + assert!(serde_json::to_value(CharStyle::default()).unwrap().get("opticalKerning").is_none()); +} + #[test] fn units() { assert_eq!(Unit::Inches.parse("1"), Some(72.0)); diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 0e3aea70e9..5189e7aa28 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -25,9 +25,12 @@ pub struct CharStyle { /// Tracking in 1/1000 em. #[serde(default)] pub tracking: f64, - /// Kerning: None = Auto (metrics), Some(v) = manual in 1/1000 em. + /// Manual pair spacing in 1/1000 em; None uses the automatic mode. #[serde(default, skip_serializing_if = "Option::is_none")] pub kerning: Option, + /// Use glyph shapes for automatic pair spacing; false uses font metrics. + #[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")] + pub optical_kerning: bool, #[serde(default)] pub baseline_shift: f64, #[serde(default = "hundred")] @@ -266,6 +269,7 @@ impl Default for CharStyle { leading: None, tracking: 0.0, kerning: None, + optical_kerning: false, baseline_shift: 0.0, h_scale: 100.0, v_scale: 100.0, diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index 47106d7882..b66795e890 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -223,6 +223,7 @@ impl ParaList { position: CharPosition::Normal, tracking: 0.0, kerning: None, + optical_kerning: first.optical_kerning, tate_chu_yoko: false, underline: false, strikethrough: false, diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 2d9fea923f..8758262628 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -87,6 +87,7 @@ pub mod swatchlib; pub mod symbollib; pub(crate) mod tabs; mod textedit; +pub use textedit::effective_kerning; pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 969daf4f6b..4c52da717e 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), 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\" (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), 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\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), 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), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), 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\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), 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), 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)", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), 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\" (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), 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\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), 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), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), 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\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), 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), 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)", has_doc, set_format ), @@ -323,7 +323,13 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let kerning = match p.get("kerning") { None | Some(Value::Null) => None, Some(Value::String(a)) if a.eq_ignore_ascii_case("auto") => Some(None), - Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(C, "kerning must be a number or \"auto\""))?.clamp(-1000.0, 10000.0))), + Some(Value::String(a)) if a.eq_ignore_ascii_case("optical") => None, + Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(C, "kerning must be a number, \"auto\", or \"optical\""))?.clamp(-1000.0, 10000.0))), + }; + let optical_kerning = match p.get("kerning") { + Some(Value::String(a)) if a.eq_ignore_ascii_case("auto") => Some(false), + Some(Value::String(a)) if a.eq_ignore_ascii_case("optical") => Some(true), + _ => None, }; let keys = [ "kerning", @@ -479,6 +485,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(k) = kerning { st.kerning = k; } + if let Some(v) = optical_kerning { + st.optical_kerning = v; + } if let Some(v) = baseline_shift { st.baseline_shift = v; } @@ -649,7 +658,11 @@ fn set_format(s: &mut Session, p: &Value) -> Result { } Ok(()) })?; - Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) + let mut result = json!({ "ids": ids.iter().map(|i| i.0).collect::>() }); + if let Some(kerning) = p.get("kerning") { + result["kerning"] = kerning.clone(); + } + Ok(result) } /// The part of a story paragraph in one frame, as [`convert_list_to_text`] reads it: the frame, diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index cb4a51354a..8d393a58e9 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", 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\", …], 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), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), 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\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), 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)} 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), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", 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\", …], 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), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), 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\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), 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)} 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 ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Reset Tracking and Kerning", [], Some("Cmd+Alt+Q"), - "{ids?: [id…]} set tracking to 0 and kerning to Auto (the font's own kerning, which the Character panel shows as 0) in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning of the character before it), else in every selected type object, as one undo step → {ids}", + "{ids?: [id…]} set tracking to 0 and clear manual kerning without changing the automatic method in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning of the character before it), else in every selected type object, as one undo step → {ids}", has_selection, reset_tracking ), @@ -300,6 +300,7 @@ pub(crate) struct CharChange { leading: Option>, tracking: Option, kerning: Option>, + optical_kerning: Option, baseline_shift: Option, h_scale: Option, v_scale: Option, @@ -476,7 +477,17 @@ impl CharChange { size: num("size"), leading: auto_or_num(p, "leading", cmd)?, tracking: num("tracking"), - kerning: auto_or_num(p, "kerning", cmd)?, + kerning: match p.get("kerning") { + None | Some(Value::Null) => None, + Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") => None, + Some(Value::String(v)) if v.eq_ignore_ascii_case("auto") => Some(None), + Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(cmd, "kerning must be a number, \"auto\", or \"optical\""))?)), + }, + optical_kerning: match p.get("kerning") { + Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") => Some(true), + Some(Value::String(v)) if v.eq_ignore_ascii_case("auto") => Some(false), + _ => None, + }, baseline_shift: num("baselineShift"), h_scale: num("hScale"), v_scale: num("vScale"), @@ -521,6 +532,7 @@ impl CharChange { && self.leading.is_none() && self.tracking.is_none() && self.kerning.is_none() + && self.optical_kerning.is_none() && self.baseline_shift.is_none() && self.h_scale.is_none() && self.v_scale.is_none() @@ -583,6 +595,9 @@ impl CharChange { if let Some(v) = self.kerning { st.kerning = v.map(|k| k.clamp(-1000.0, 10000.0)); } + if let Some(v) = self.optical_kerning { + st.optical_kerning = v; + } if let Some(v) = self.baseline_shift { st.baseline_shift = v; } @@ -734,18 +749,53 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { if let Some(w) = super::fonts::set_font_warning(set) { out["warning"] = json!(w); } + if let Some(kerning) = p.get("kerning") { + out["kerning"] = kerning.clone(); + } Ok(out) } /// The em a laid-out glyph's kerning and tracking are measured in, in text space: the size it /// was shaped at (superscript, small caps and Shrink Text to Fit included). -fn glyph_em(t: &TextObject, g: &vectorcraft_text::PositionedGlyph) -> Option { - let face = vectorcraft_text::FontDb::global().face_by_id(g.font_id)?; +fn glyph_em(db: &vectorcraft_text::FontDb, t: &TextObject, g: &vectorcraft_text::PositionedGlyph) -> Option { + let face = db.face_by_id(g.font_id)?; let h_scale = edit::slice_runs(&t.runs, g.byte, g.byte + g.len).first()?.style.h_scale / 100.0; let [a, b, ..] = g.xf.as_coeffs(); Some(a.hypot(b) * face.units_per_em() / h_scale).filter(|em| em.is_finite() && *em > 0.0) } +/// The current pair correction in thousandths of an em, including an automatic correction. +pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &vectorcraft_text::TextLayout, x: usize, y: usize) -> f64 { + if let Some(value) = edit::slice_runs(&t.runs, x, y).first().and_then(|r| r.style.kerning) { + return value; + } + // Measure both layouts without wrapping so the same pair stays on one line. + let mut trial = t.clone(); + trial.kind = TextKind::Point; + let unwrapped = (!matches!(t.kind, TextKind::Point)).then(|| vectorcraft_text::layout(db, &trial)); + let original = unwrapped.as_ref().unwrap_or(lay); + edit::style_range(&mut trial.runs, x, y, |st| st.kerning = Some(0.0)); + let base = vectorcraft_text::layout(db, &trial); + let owner = original.glyphs.iter().find(|g| g.byte == x); + let rtl = owner.is_some_and(|g| g.rtl); + let drawn_gap = |layout: &vectorcraft_text::TextLayout| { + let first = layout.glyphs.iter().find(|g| g.byte == if rtl { y } else { x })?; + let following = layout.glyphs.iter().find(|g| g.byte == if rtl { x } else { y })?; + if first.line != following.line { + return None; + } + let axis = vectorcraft_geom::Vec2::new(first.angle.cos(), first.angle.sin()); + let along = if rtl { -axis } else { axis }; + let drawn = |g: &vectorcraft_text::PositionedGlyph| { + let [_, _, _, _, tx, ty] = g.xf.as_coeffs(); + Point::new(tx, ty) + }; + Some((drawn(following) - drawn(first)).dot(along)) + }; + let em = owner.and_then(|g| glyph_em(db, t, g)).unwrap_or(0.0); + if em > 0.0 { drawn_gap(original).zip(drawn_gap(&base)).map_or(0.0, |(a, b)| (a - b) * 1000.0 / em) } else { 0.0 } +} + fn touch_type(s: &mut Session, p: &Value) -> Result { const C: &str = "text.touchType"; let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; @@ -780,18 +830,21 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { // A list marker's glyphs (length 0) stand for no character. let prev = lay.glyphs.iter().find(|h| h.line == g.line && h.len > 0 && h.byte + h.len == a); let pr = prev.map(|h| (h.byte, h.byte + h.len)); - let em = glyph_em(&t, g).ok_or_else(|| bad(C, "the character's size can't be measured"))?; + let db = vectorcraft_text::FontDb::global(); + let em = glyph_em(db, &t, g).ok_or_else(|| bad(C, "the character's size can't be measured"))?; let em_prev = match prev { - Some(h) => Some(glyph_em(&t, h).ok_or_else(|| bad(C, "the character's size can't be measured"))?), + Some(h) => Some(glyph_em(db, &t, h).ok_or_else(|| bad(C, "the character's size can't be measured"))?), None if dx != 0.0 => return Err(bad(C, "the first character of a line has no character before it to kern: it moves only up and down (dy)")), None => None, }; - let kerning_in = |(x, y): (usize, usize)| edit::slice_runs(&t.runs, x, y).first().and_then(|r| r.style.kerning).unwrap_or(0.0); + let kerning_in = |(x, y): (usize, usize)| effective_kerning(db, &t, &lay, x, y); + let original_before = pr.map(kerning_in); + let original_own = kerning_in((a, b)); // The move along the line, in text space, limited to what kerning from -1000 to 10000 (1/1000 // em) on the character before it and on the character itself can give. let mut moved = dx / doc_len(along); - if let (Some(range), Some(ep)) = (pr, em_prev) { - let (kp, kc) = (kerning_in(range), kerning_in((a, b))); + if let (Some(_range), Some(ep)) = (pr, em_prev) { + let (kp, kc) = (original_before.unwrap_or(0.0), original_own); let hi = ((10000.0 - kp) * ep).min((kc + 1000.0) * em) / 1000.0; let lo = ((-1000.0 - kp) * ep).max((kc - 10000.0) * em) / 1000.0; if lo <= hi { @@ -803,7 +856,8 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { let touch = |t: &mut TextObject, before: Option, own: Option, raise: f64| { for (range, by) in [(pr, before), (Some((a, b)), own)] { if let (Some((x, y)), Some(by)) = (range, by) { - edit::style_range(&mut t.runs, x, y, |st| st.kerning = Some((st.kerning.unwrap_or(0.0) + by).clamp(-1000.0, 10000.0))); + let original = if (x, y) == (a, b) { original_own } else { original_before.unwrap_or(0.0) }; + edit::style_range(&mut t.runs, x, y, |st| st.kerning = Some((original + by).clamp(-1000.0, 10000.0))); } } edit::style_range(&mut t.runs, a, b, |st| { @@ -1086,9 +1140,20 @@ fn type_step(s: &mut Session, p: &Value) -> Result { } _ => None, })?; + let mut caret_kerning = Vec::with_capacity(ranges.len()); + for &(id, a, b, caret) in &ranges { + let value = if matches!(step, Step::Kerning) && caret { + let t = text_ref(s, id)?; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + Some(effective_kerning(vectorcraft_text::FontDb::global(), &t, &lay, a, b)) + } else { + None + }; + caret_kerning.push(value); + } if !ranges.is_empty() { s.edit("Character", |d, _| { - for &(id, a, b, _) in &ranges { + for (range_index, &(id, a, b, _)) in ranges.iter().enumerate() { let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?; let points = if matches!(step, Step::Size | Step::Leading | Step::BaselineShift) { t.style_scale().ok_or_else(|| bad(C, "text transform is collapsed or unrepresentable"))?.points @@ -1127,7 +1192,10 @@ fn type_step(s: &mut Session, p: &Value) -> Result { st.leading = Some(super::typecmd::local_type_value(t, leading * points + inc, (0.1, 5000.0), false, C)?); } Step::Tracking => st.tracking = (st.tracking + inc).clamp(-1000.0, 10000.0), - Step::Kerning => st.kerning = Some((st.kerning.unwrap_or(0.0) + inc).clamp(-1000.0, 10000.0)), + Step::Kerning => { + let current = caret_kerning.get(range_index).copied().flatten().unwrap_or_else(|| st.kerning.unwrap_or(0.0)); + st.kerning = Some((current + inc).clamp(-1000.0, 10000.0)); + } Step::BaselineShift => { st.baseline_shift = super::typecmd::local_type_value(t, st.baseline_shift * points + inc, (-1296.0, 1296.0), false, C)?; } @@ -1142,9 +1210,10 @@ fn type_step(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ranges.iter().map(|(id, ..)| id.0).collect::>() })) } -/// Cmd/Ctrl+Alt+Q: tracking 0 and kerning Auto (0 in the Character panel) in the type objects in +/// Cmd/Ctrl+Alt+Q: tracking 0 and manual kerning cleared in the type objects in /// `ids`, else in the Type tool's selected text, else in every selected type object. At a caret, /// only the kerning of the character before it changes, as Alt+←/→ in horizontal type or Alt+↓/↑ in vertical type kerns there. +/// The automatic method remains selected. fn reset_tracking(s: &mut Session, p: &Value) -> Result { let ranges = type_ranges(s, p, "type.resetTracking", |text, a| Some((edit::prev_char(text, a), a)))?; if !ranges.is_empty() { diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 2a8d48fab5..c1312fa9ba 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -152,6 +152,7 @@ pub fn char_attrs(v: &CharStyle) -> Map { ("fontAxes", json!(v.font_axes)), ("leading", json!(v.leading)), ("kerning", json!(v.kerning)), + ("opticalKerning", json!(v.optical_kerning)), ("features", json!(v.features)), ("overprint_fill", json!(v.overprint_fill)), ("overprint_stroke", json!(v.overprint_stroke)), diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 2cdcaf77af..670e3bbb7a 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -460,6 +460,20 @@ fn auto_leading_new_distinguishes_unset_attributes() { assert_eq!(s.doc().unwrap().doc.char_styles[2].attrs.get("leading"), Some(&Value::Null)); } +#[test] +fn optical_character_style_captures_and_redefines_automatic_mode() { + let (mut s, id) = session_with_text("III"); + s.execute("text.setRangeStyle", &json!({"id": id, "kerning": "optical"})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Profile", "id": id})).unwrap(); + assert_eq!(s.doc().unwrap().doc.char_styles[0].attrs.get("opticalKerning"), Some(&json!(true))); + s.execute("text.setRangeStyle", &json!({"id": id, "kerning": "auto"})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Profile", "id": id})).unwrap(); + assert!(runs(&s, id)[0].style.optical_kerning); + s.execute("text.setRangeStyle", &json!({"id": id, "kerning": "auto"})).unwrap(); + s.execute("charStyle.redefine", &json!({"name": "Profile", "id": id})).unwrap(); + assert_eq!(s.doc().unwrap().doc.char_styles[0].attrs.get("opticalKerning"), Some(&json!(false))); +} + #[test] fn paragraph_styles_and_survive_save() { let (mut s, id) = session_with_text("Body"); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index be98613162..025cf6d30a 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -2,7 +2,7 @@ //! on-path type from paths, Fit Headline, Convert To Area/Point Type. use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind, TextKind, TextObject}; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextKind, TextObject}; use vectorcraft_geom::Point; use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; @@ -87,6 +87,168 @@ fn set_range_style_splits_runs() { assert!(s.execute("text.setRangeStyle", &json!({"id": id.0, "size": -1})).is_err()); } +#[test] +fn optical_command_manual_pair_undo_redo_and_native_reopen() { + let mut s = session(); + let id = text(&mut s, "III"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": 70})).unwrap(); + let result = s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap(); + assert_eq!(result["kerning"], "optical"); + assert!(obj(&s, id).runs[0].style.optical_kerning); + assert_eq!(obj(&s, id).runs[0].style.kerning, Some(70.0)); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "kerning": 0})).unwrap(); + let styled = obj(&s, id); + assert_eq!(styled.runs.iter().map(|r| r.style.kerning).collect::>(), vec![Some(70.0), Some(0.0), Some(70.0)]); + assert!(styled.runs.iter().all(|r| r.style.optical_kerning)); + let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc); + let opened = vectorcraft_format::load(&bytes).unwrap(); + let NodeKind::Text(reopened) = &opened.node(id).unwrap().kind else { panic!("text missing") }; + assert_eq!( + reopened.runs.iter().map(|r| (r.style.optical_kerning, r.style.kerning)).collect::>(), + styled.runs.iter().map(|r| (r.style.optical_kerning, r.style.kerning)).collect::>() + ); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(obj(&s, id).runs[0].style.kerning, Some(70.0)); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(obj(&s, id).runs[1].style.kerning, Some(0.0)); + assert!(obj(&s, id).runs.iter().all(|r| r.style.optical_kerning)); +} + +#[test] +fn optical_set_format_keeps_existing_pair_override() { + let mut s = session(); + let id = text(&mut s, "III"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerning": 40})).unwrap(); + let result = s.execute("text.setFormat", &json!({"ids": [id.0], "kerning": "optical"})).unwrap(); + assert_eq!(result["kerning"], "optical"); + let t = obj(&s, id); + assert!(t.runs.iter().all(|r| r.style.optical_kerning)); + assert_eq!(t.runs[0].style.kerning, Some(40.0)); +} + +#[test] +fn optical_kerning_step_starts_from_the_automatic_pair() { + let mut s = session(); + let id = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "AVA", "size": 100, "font": "JetBrains Mono"})).unwrap()["id"].as_u64().unwrap(), + ); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap(); + let t = obj(&s, id); + let optical = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let mut manual = t.clone(); + vectorcraft_text::edit::style_range(&mut manual.runs, 0, 1, |st| st.kerning = Some(0.0)); + let unkerned = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &manual); + let auto = (optical.glyphs[0].advance - unkerned.glyphs[0].advance) * 1000.0 / 100.0; + assert!(auto.abs() > 1.0, "the font needs a measurable shape correction"); + s.execute("type.step", &json!({"id": id.0, "start": 1, "end": 1, "attribute": "kerning", "by": 1})).unwrap(); + let after = obj(&s, id); + assert!((after.runs[0].style.kerning.unwrap() - auto - s.prefs.tracking_increment).abs() < 0.01); + assert!(after.runs.iter().all(|r| r.style.optical_kerning)); +} + +#[test] +fn metrics_pair_step_preserves_the_drawn_auto_position() { + use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + + let db = vectorcraft_text::FontDb::global(); + db.add_font(pair_kerning_font().unwrap()); + let mut s = session(); + let id = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "AV", "size": 100, "font": PAIR_KERNING_FAMILY})).unwrap()["id"].as_u64().unwrap(), + ); + let before = obj(&s, id); + let auto = vectorcraft_text::layout(db, &before); + let drawn_v = |layout: &vectorcraft_text::TextLayout| layout.glyphs.iter().find(|g| g.byte == 1).unwrap().xf.as_coeffs()[4]; + assert!((crate::cmd::effective_kerning(db, &before, &auto, 0, 1) + 160.0).abs() < 0.01); + let mut same = before.clone(); + vectorcraft_text::edit::style_range(&mut same.runs, 0, 1, |st| st.kerning = Some(-160.0)); + assert!((drawn_v(&vectorcraft_text::layout(db, &same)) - drawn_v(&auto)).abs() < 0.01); + + s.execute("type.step", &json!({"id": id.0, "start": 1, "end": 1, "attribute": "kerning", "by": 1})).unwrap(); + let after = obj(&s, id); + assert!((after.runs[0].style.kerning.unwrap() + 160.0 - s.prefs.tracking_increment).abs() < 0.01); + let moved = drawn_v(&vectorcraft_text::layout(db, &after)) - drawn_v(&auto); + assert!((moved - s.prefs.tracking_increment * 0.1).abs() < 0.01, "V moves by one kerning increment: {moved}"); +} + +#[test] +fn effective_auto_kerning_at_area_line_end_survives_unkerned_wrap() { + use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + + let db = vectorcraft_text::FontDb::global(); + db.add_font(pair_kerning_font().unwrap()); + let style = CharStyle { font_family: PAIR_KERNING_FAMILY.into(), size: 100.0, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AV", style); + let mut wrapping_pair = None; + for width in 80..160 { + text.kind = TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(width), 300.0)) }; + let auto = vectorcraft_text::layout(db, &text); + let mut trial = text.clone(); + vectorcraft_text::edit::style_range(&mut trial.runs, 0, 1, |st| st.kerning = Some(0.0)); + let unkerned = vectorcraft_text::layout(db, &trial); + if auto.glyphs.len() >= 2 + && unkerned.glyphs.len() >= 2 + && auto.glyphs[0].line == auto.glyphs[1].line + && unkerned.glyphs[0].line != unkerned.glyphs[1].line + { + wrapping_pair = Some((text.clone(), auto, unkerned)); + break; + } + } + let (text, auto, unkerned) = wrapping_pair.expect("the kerned pair fits on a line that wraps the unkerned pair"); + assert_ne!(unkerned.glyphs[0].line, unkerned.glyphs[1].line); + assert!((crate::cmd::effective_kerning(db, &text, &auto, 0, 1) + 160.0).abs() < 0.01); +} + +#[test] +fn effective_optical_kerning_reads_the_right_to_left_pair() { + use vectorcraft_text::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font}; + + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(right_to_left_optical_font().unwrap()), 1); + let style = CharStyle { font_family: RIGHT_TO_LEFT_OPTICAL_FAMILY.into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let text = TextObject::point(Point::ZERO, "אב", style); + let optical = vectorcraft_text::layout(&db, &text); + let mut manual = text.clone(); + manual.runs[0].style.kerning = Some(0.0); + let unkerned = vectorcraft_text::layout(&db, &manual); + let drawn_gap = |lay: &vectorcraft_text::TextLayout| { + let drawn = |byte| lay.glyphs.iter().find(|g| g.byte == byte).unwrap().xf.as_coeffs()[4]; + drawn(2) - drawn(0) + }; + let expected = (drawn_gap(&optical) - drawn_gap(&unkerned)) * 10.0; + assert!(expected.abs() > 1.0, "the outlined pair has a measurable Optical correction"); + let actual = crate::cmd::effective_kerning(&db, &text, &optical, 0, 2); + assert!((actual - expected).abs() < 0.01, "the caret reads the adjacent right-to-left pair"); +} + +#[test] +fn reset_tracking_clears_manual_pairs_without_changing_optical_mode() { + let mut s = session(); + let id = text(&mut s, "III"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerning": 80})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + let t = obj(&s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let (a, b) = vectorcraft_text::caret_position(&lay, 1); + let p = t.xf * a.midpoint(b); + click(&mut s, p.x, p.y); + assert!(s.tool_wants_text()); + s.set_tool_option("select", &json!({"start": 1, "end": 1})); + s.execute("type.resetTracking", &json!({})).unwrap(); + let caret = obj(&s, id); + assert_eq!(caret.runs[0].style.kerning, None); + assert!(caret.runs.iter().all(|r| r.style.optical_kerning)); + + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": 60, "tracking": 30})).unwrap(); + s.set_tool_option("select", &json!({"start": 0, "end": 3})); + s.execute("type.resetTracking", &json!({})).unwrap(); + let range = obj(&s, id); + assert!(range.runs.iter().all(|r| r.style.kerning.is_none() && r.style.tracking == 0.0)); + assert!(range.runs.iter().all(|r| r.style.optical_kerning)); +} + /// A character style applied from byte 2^32 to 2^32 + 5 styles no character, as a range past the /// end does. A 32-bit build read the range as bytes 0 to 5 and styled "Hello". #[test] diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 2c79099b4b..5c69a6a935 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -1,5 +1,6 @@ //! Shaping: text runs -> positioned glyphs in points (before line breaking). +use std::collections::HashMap; use std::ops::Range; use std::sync::Arc; @@ -8,6 +9,7 @@ use unicode_script::{Script, UnicodeScript}; use unicode_segmentation::UnicodeSegmentation; use harfrust::{Direction, Feature, ShapeOptions, Tag, UnicodeBuffer}; +use kurbo::Shape; use skrifa::MetadataProvider; use skrifa::charmap::Charmap; use skrifa::instance::Size; @@ -446,6 +448,216 @@ pub(crate) fn shape_range( { o.sort_by_key(|g| g.byte); } + if !feats.vertical { + optical_pairs(db, text, out.get_mut(output_start..).unwrap_or_default(), runs); + } +} + +/// Line segments of a glyph outline in font units, cached for the current shaping pass. +type Profile = Vec<(f64, f64, f64, f64)>; +type CachedProfile = (Profile, (f64, f64)); + +fn outline_profile(db: &FontDb, g: &SGlyph, cache: &mut HashMap<(u32, u32), Option>>) -> Option> { + let key = (g.face.id(), g.gid); + cache + .entry(key) + .or_insert_with(|| { + let path = db.outline(&g.face, g.gid); + let bounds = path.bounding_box(); + if path.elements().is_empty() + || path.elements().len() > 512 + || ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite() && v.abs() <= 100_000.0) + { + return None; + } + let mut lines = Vec::new(); + let mut previous = None; + let mut contour_start = None; + kurbo::flatten(path.iter(), 2.0, |el| match el { + kurbo::PathEl::MoveTo(p) => { + previous = Some(p); + contour_start = Some(p); + } + kurbo::PathEl::LineTo(p) => { + if let Some(a) = previous + && lines.len() < 8192 + { + lines.push((a.x, a.y, p.x, p.y)); + } + previous = Some(p); + } + kurbo::PathEl::ClosePath => { + if let Some((a, b)) = previous.zip(contour_start) + && lines.len() < 8192 + { + lines.push((a.x, a.y, b.x, b.y)); + } + previous = None; + contour_start = None; + } + _ => {} + }); + (!lines.is_empty() && lines.len() < 8192).then(|| Arc::new((lines, (bounds.y0, bounds.y1)))) + }) + .clone() +} + +/// The left and right ink edges where a horizontal slice crosses an outline. +fn profile_edges(lines: &[(f64, f64, f64, f64)], y: f64, sx: f64, sy: f64, dx: f64, dy: f64) -> Option<(f64, f64)> { + let mut left = f64::INFINITY; + let mut right = f64::NEG_INFINITY; + for &(x0, y0, x1, y1) in lines { + let (a, b) = (y0 * sy + dy, y1 * sy + dy); + if (a <= y && y < b) || (b <= y && y < a) { + let x = (x0 + (x1 - x0) * (y - a) / (b - a)) * sx + dx; + left = left.min(x); + right = right.max(x); + } + } + (left.is_finite() && right.is_finite()).then_some((left, right)) +} + +#[allow(clippy::too_many_arguments)] +fn profile_correction( + a: &[(f64, f64, f64, f64)], + b: &[(f64, f64, f64, f64)], + left: (f64, f64, f64, f64), + right: (f64, f64, f64, f64), + advance: f64, + em: f64, + upem: f64, + low: f64, + high: f64, +) -> Option { + if !low.is_finite() || !high.is_finite() || high <= low || !em.is_finite() || em <= 0.0 || !upem.is_finite() || upem <= 0.0 { + return None; + } + let mut gaps = Vec::new(); + for j in 0..24 { + let y = low + (high - low) * (f64::from(j) + 0.5) / 24.0; + if let (Some((_, ar)), Some((bl, _))) = + (profile_edges(a, y, left.0, left.1, left.2, left.3), profile_edges(b, y, right.0, right.1, right.2, right.3)) + { + gaps.push(advance + bl - ar); + } + } + if gaps.is_empty() { + return None; + } + gaps.sort_by(f64::total_cmp); + let gap = gaps.get(gaps.len() / 2).copied().unwrap_or(0.0); + let unit = em / upem; + let correction = ((0.08 * em - gap).clamp(-0.25 * em, 0.25 * em) / unit).round() * unit; + let correction = correction.clamp(-0.25 * em, 0.25 * em); + correction.is_finite().then_some(correction) +} + +/// Move each Optical pair toward an ink gap of 0.08 em, at 24 overlapping vertical slices. +/// The median avoids a single narrow tip deciding the entire pair. Corrections are rounded to +/// one font unit and limited to 1/4 em in either direction. Missing ink gives zero correction. +fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range, &CharStyle)]) { + let mut cache = HashMap::new(); + let mut corrections: HashMap<[u64; 15], Option> = HashMap::new(); + let shaped_advances: Vec = glyphs.iter().map(|g| g.adv).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 { + continue; + } + let Some(owner) = runs.get(a.run).map(|(_, s)| *s) else { continue }; + let invisible = |ch: char| matches!(ch, SOFT_HYPHEN | '\u{2028}') || ch.is_control(); + if !owner.optical_kerning + || a.byte == b.byte + || invisible(a.ch) + || invisible(b.ch) + || text.get(a.byte..b.byte).is_some_and(|between| between.chars().skip(1).any(invisible)) + || a.rotation != 0.0 + || b.rotation != 0.0 + { + continue; + } + if owner.kerning.is_some() { + continue; + } + let mut start = i; + while start > 0 && glyphs[start - 1].byte == a.byte { + start -= 1; + } + let mut end = i + 1; + while end + 1 < glyphs.len() && glyphs[end + 1].byte == b.byte { + end += 1; + } + // A mark may precede its base inside either direction's shaped cluster. + let first_base = glyphs[start..=i] + .iter() + .enumerate() + .max_by(|(a, _), (b, _)| shaped_advances[start + *a].total_cmp(&shaped_advances[start + *b])) + .map_or(start, |(offset, _)| start + offset); + let second_base = glyphs[i + 1..=end] + .iter() + .enumerate() + .max_by(|(a, _), (b, _)| shaped_advances[i + 1 + *a].total_cmp(&shaped_advances[i + 1 + *b])) + .map_or(i + 1, |(offset, _)| i + 1 + offset); + let (left_index, right_index, target, cluster_start, cluster_end) = + if a.level.is_rtl() { (second_base, first_base, end, i + 1, end) } else { (first_base, second_base, i, start, i) }; + let (left, right) = (&glyphs[left_index], &glyphs[right_index]); + if left.byte == right.byte + || left.is_space() + || right.is_space() + || is_mark(right.ch) + || left.inline.is_some() + || right.inline.is_some() + || left.ch == '\n' + || right.ch == '\n' + { + continue; + } + 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 }; + let em = left.sx * left.face.upem / (left_style.h_scale / 100.0); + let tracking = left_style.tracking / 1000.0 * em; + let manual = left_style.kerning.unwrap_or(0.0) / 1000.0 * em; + let advance = glyphs[cluster_start..=cluster_end].iter().map(|g| g.adv).sum::() - tracking - manual; + let key = [ + u64::from(left.face.id()), + u64::from(left.gid), + u64::from(right.face.id()), + u64::from(right.gid), + left.sx.to_bits(), + left.sy.to_bits(), + left.dx.to_bits(), + left_y.to_bits(), + right.sx.to_bits(), + right.sy.to_bits(), + right.dx.to_bits(), + right_y.to_bits(), + advance.to_bits(), + em.to_bits(), + left.face.upem.to_bits(), + ]; + let correction = *corrections.entry(key).or_insert_with(|| { + let (Some(a), Some(b)) = (outline_profile(db, left, &mut cache), outline_profile(db, right, &mut cache)) else { return None }; + let low = (a.1.0 * left.sy + left_y).max(b.1.0 * right.sy + right_y); + let high = (a.1.1 * left.sy + left_y).min(b.1.1 * right.sy + right_y); + profile_correction( + &a.0, + &b.0, + (left.sx, left.sy, left.dx, left_y), + (right.sx, right.sy, right.dx, right_y), + advance, + em, + left.face.upem, + low, + high, + ) + }); + if let (Some(correction), Some(glyph)) = (correction, glyphs.get_mut(target)) + && !invisible(glyph.ch) + { + glyph.adv += correction; + } + } } /// Index in the original run list containing `byte`, limited to one coalesced shaping span. @@ -474,6 +686,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { leading: _, tracking, kerning: _, + optical_kerning: _, baseline_shift: _, h_scale, v_scale, @@ -696,6 +909,15 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe }; let manual = |byte: usize| run_at(byte).1.kerning.is_some(); let mixed_kerning = boundaries().any(|b| manual(b) != manual(range.start)); + let optical = |byte: usize| run_at(byte).1.optical_kerning; + let mode_boundaries: Vec = boundaries().filter(|&b| !feats.vertical && optical(b - 1) && !optical(b)).collect(); + if !mode_boundaries.is_empty() { + return shape_apart(mode_boundaries, out); + } + let manual_ends: Vec = boundaries().filter(|&b| manual(b - 1) && !manual(b)).collect(); + if !manual_ends.is_empty() { + return shape_apart(manual_ends, out); + } // Shape the segment as if all of it were in `st`, with the features `more` on top. let shape_in = |st: &CharStyle, more: &[Feature]| { @@ -793,17 +1015,43 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe } shaped }; - let Shaped { raw, proportional, vpal } = if mixed_kerning { + let first_optical = if optical(range.start) { Some(range.start) } else { boundaries().find(|&b| optical(b)) }; + let Shaped { raw, proportional, vpal } = if let Some(first) = first_optical.filter(|_| !feats.vertical) { + // The pair entering Optical keeps the left character's font kerning. Subsequent + // Optical pairs use outline spacing, so font pair features stop at its second character. + let optical_off = if first == range.start { + first + } else { + text.get(first..range.end).and_then(|s| s.chars().next()).map_or(range.end, |c| first + c.len_utf8()) + }; + let first_manual = if manual(range.start) { Some(range.start) } else { boundaries().find(|&b| manual(b)) }; + if let Some(start) = first_manual.filter(|&b| b > range.start) + && upper + && first_char(start).to_uppercase().nth(1).is_some() + { + return shape_apart(vec![start], out); + } + let manual_off = first_manual.map_or(range.end, |start| { + if start == range.start { + start + } else { + text.get(start..range.end).and_then(|s| s.chars().next()).map_or(range.end, |c| start + c.len_utf8()) + } + }); + let off = optical_off.min(manual_off); + let more: Vec = [b"kern", b"apkn", b"vkrn", b"vapk"] + .into_iter() + .filter(|_| off < range.end) + .map(|t| Feature::new(Tag::new(t), 0, off..range.end)) + .collect(); + shape_in(&CharStyle { kerning: None, ..run_at(range.start).1.clone() }, &more) + } else if mixed_kerning { // A font's kerning pair applies after a character with automatic kerning and not after one // with manual kerning. The segment is shaped apart where manual kerning ends, so each piece // is text with automatic kerning followed by text with manual kerning. A piece is shaped // with the font's kerning on, and off (`kern`, and the `apkn`, `vkrn` and `vapk` that // `OtFeatures` turns off with it) from the second character with manual kerning on: a // pair is applied only when both of its glyphs have the feature on. - let ends: Vec = boundaries().filter(|&b| manual(b - 1) && !manual(b)).collect(); - if !ends.is_empty() { - return shape_apart(ends, out); - } let first = boundaries().find(|&b| manual(b)).unwrap_or(range.end); // A first character with manual kerning that All Caps or Small Caps sets as several letters // (ß as SS) gives them one cluster, which a feature range cannot split, so the font's @@ -879,3 +1127,27 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe }); } } + +#[cfg(test)] +mod optical_tests { + use super::*; + + fn box_profile(left: f64, right: f64) -> Profile { + vec![(left, 0.0, left, 100.0), (right, 0.0, right, 100.0)] + } + + #[test] + fn optical_side_profiles_tighten_loosen_and_stay_bounded() { + let a = box_profile(0.0, 80.0); + let b = box_profile(0.0, 20.0); + let place = (1.0, 1.0, 0.0, 0.0); + let tight = profile_correction(&a, &b, place, place, 120.0, 100.0, 1000.0, 0.0, 100.0).unwrap(); + let loose = profile_correction(&a, &b, place, place, 60.0, 100.0, 1000.0, 0.0, 100.0).unwrap(); + assert_eq!(tight, -25.0); + assert_eq!(loose, 25.0); + assert_eq!(profile_correction(&a, &b, place, place, 88.0, 100.0, 1000.0, 0.0, 100.0), Some(0.0)); + assert_eq!(profile_correction(&a, &b, place, place, 120.0, 100.0, 1000.0, 0.0, 100.0), Some(tight)); + assert_eq!(profile_correction(&a, &b, place, place, 120.0, 100.0, 1000.0, 100.0, 100.0), None); + assert_eq!(profile_correction(&[], &b, place, place, 120.0, 100.0, 1000.0, 0.0, 100.0), None); + } +} diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index f3619679ff..817f1689f4 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -412,6 +412,81 @@ pub fn lam_alef_font(feature: &[u8; 4]) -> Option> { /// The family of [`pair_kerning_font`]. pub const PAIR_KERNING_FAMILY: &str = "Pairtest Sans"; +/// The family of [`no_pair_kerning_font`]. +pub const NO_PAIR_KERNING_FAMILY: &str = "No Pairtest Sans"; + +/// A font with the bundled Source Sans 3 outlines and no `GPOS` or `kern` table. +pub fn no_pair_kerning_font() -> Option> { + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let family = NO_PAIR_KERNING_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "No Pairtest Sans Regular"), (6, "NoPairtestSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !matches!(tag, t if t == Tag::new(b"name") || t == Tag::new(b"GPOS") || t == Tag::new(b"kern")) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + +/// The family of [`right_to_left_optical_font`]. +pub const RIGHT_TO_LEFT_OPTICAL_FAMILY: &str = "Right-to-left Profile Sans"; + +/// Two Hebrew characters mapped to the bundled Source Sans 3 A and V outlines. +pub fn right_to_left_optical_font() -> Option> { + use write_fonts::tables::cmap::Cmap; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let mapping = [('א', 'A'), ('ב', 'V')]; + let mappings = mapping.into_iter().map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); + let cmap = Cmap::from_mappings(mappings.collect::>>()?).ok()?; + let family = RIGHT_TO_LEFT_OPTICAL_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Right-to-left Profile Sans Regular"), (6, "RtlProfileSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"GPOS") && tag != Tag::new(b"kern") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + +/// The family of [`soft_hyphen_outline_font`]. +pub const SOFT_HYPHEN_OUTLINE_FAMILY: &str = "Soft Hyphen Profile Sans"; + +/// A face that maps the invisible soft hyphen to the bundled hyphen outline. +pub fn soft_hyphen_outline_font() -> Option> { + use write_fonts::tables::cmap::Cmap; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let mappings = [('A', 'A'), ('V', 'V'), ('-', '-'), ('\u{00AD}', '-')] + .into_iter() + .map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); + let cmap = Cmap::from_mappings(mappings.collect::>>()?).ok()?; + let family = SOFT_HYPHEN_OUTLINE_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Soft Hyphen Profile Sans Regular"), (6, "SoftHyphenProfileSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"GPOS") && tag != Tag::new(b"kern") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The bundled Source Sans 3 Regular as family [`PAIR_KERNING_FAMILY`], its `GPOS` replaced by two /// `kern` pairs, A followed by V and S followed by S: each takes 60 units off the first glyph's /// advance (the pair's first value record) and moves the second 100 units left (its second). diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 345340b52e..105c1b424e 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -18,6 +18,267 @@ fn run(text: &str, size: f64) -> TextRun { TextRun { text: text.into(), style: style(size), inline: None } } +#[test] +fn optical_pairs_cross_paint_runs_and_manual_and_tracking_are_independent() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let mut t = TextObject::point(Point::ZERO, "III", st); + let advance = |t: &TextObject| layout(db(), t).glyphs.iter().map(|g| g.advance).collect::>(); + let optical = advance(&t); + let mut plain = t.clone(); + plain.runs[0].style.kerning = Some(0.0); + let unkerned = advance(&plain); + assert!((optical[0] - unkerned[0]).abs() > 0.1, "Optical changes the monospaced pair"); + edit::style_range(&mut t.runs, 1, 2, |s| s.fill = vectorcraft_doc::color::Paint::solid(vectorcraft_doc::color::Color::rgb(1.0, 0.0, 0.0))); + let painted = advance(&t); + assert!((painted[0] - optical[0]).abs() < 0.01, "paint does not interrupt Optical"); + edit::style_range(&mut t.runs, 0, 1, |s| s.kerning = Some(0.0)); + let manual = advance(&t); + assert!((manual[0] - unkerned[0]).abs() < 0.01); + assert!((manual[1] - optical[1]).abs() < 0.01, "the next pair remains Optical"); + edit::style_range(&mut t.runs, 0, 3, |s| s.tracking = 100.0); + let tracked = advance(&t); + assert!((tracked[0] - manual[0] - 10.0).abs() < 0.01); + assert!((tracked[1] - manual[1] - 10.0).abs() < 0.01); + + for text in ["I I", "I\u{301}"] { + let sample = TextObject::point(Point::ZERO, text, CharStyle { kerning: None, ..t.runs[0].style.clone() }); + let mut zero = sample.clone(); + zero.runs[0].style.kerning = Some(0.0); + assert_eq!(advance(&sample), advance(&zero), "spaces and marks inside a cluster have no Optical correction"); + } + let mut vertical = TextObject::point(Point::ZERO, "II", CharStyle { kerning: None, ..t.runs[0].style.clone() }); + vertical.vertical = true; + let mut vertical_zero = vertical.clone(); + vertical_zero.runs[0].style.kerning = Some(0.0); + assert_eq!(advance(&vertical), advance(&vertical_zero), "vertical type keeps a neutral correction"); + let rtl = TextObject::point(Point::ZERO, "אב", CharStyle { kerning: None, ..t.runs[0].style.clone() }); + let rtl_advances = advance(&rtl); + assert!(rtl_advances.len() >= 2 && rtl_advances.iter().all(|v| v.is_finite())); + let mut rtl_zero = rtl.clone(); + rtl_zero.runs[0].style.kerning = Some(0.0); + assert!((rtl_advances[1] - advance(&rtl_zero)[1]).abs() <= 25.0, "right-to-left Optical corrections remain bounded"); + let mut rtl_manual = rtl.clone(); + edit::style_range(&mut rtl_manual.runs, 0, 2, |s| s.kerning = Some(200.0)); + let mut rtl_pair_zero = rtl.clone(); + edit::style_range(&mut rtl_pair_zero.runs, 0, 2, |s| s.kerning = Some(0.0)); + let pair_advance = |t: &TextObject| layout(db(), t).glyphs.iter().find(|g| g.byte == 0).map(|g| g.advance).unwrap(); + assert!((pair_advance(&rtl_pair_zero) - pair_advance(&rtl_zero)).abs() < 0.01, "manual zero replaces the right-to-left Optical correction"); + assert!((pair_advance(&rtl_manual) - pair_advance(&rtl_pair_zero) - 20.0).abs() < 0.01, "manual spacing changes the adjacent right-to-left pair"); +} + +#[test] +fn optical_pair_skips_an_invisible_soft_hyphen_with_an_outline() { + use crate::test_fonts::{SOFT_HYPHEN_OUTLINE_FAMILY, soft_hyphen_outline_font}; + + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(soft_hyphen_outline_font().unwrap()), 1); + let style = CharStyle { font_family: SOFT_HYPHEN_OUTLINE_FAMILY.into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let face = db.style_face(&style).unwrap(); + assert_ne!(face.glyph_for('\u{00AD}'), 0); + assert_eq!(face.glyph_for('\u{00AD}'), face.glyph_for('-')); + let paired = layout(&db, &TextObject::point(Point::ZERO, "AV", style.clone())); + let separated = layout(&db, &TextObject::point(Point::ZERO, "A\u{00AD}V", style.clone())); + let mut manual = style; + manual.kerning = Some(0.0); + let plain = layout(&db, &TextObject::point(Point::ZERO, "A\u{00AD}V", manual)); + + assert!((paired.glyphs[0].advance - plain.glyphs[0].advance).abs() > 0.1, "A-V has an Optical correction"); + // A keeps its uncorrected advance because neither pair across the invisible glyph is measured. + assert!((separated.glyphs[0].advance - plain.glyphs[0].advance).abs() < 0.01); + assert!(separated.glyphs.iter().filter(|g| g.byte == 1).all(|g| g.advance == 0.0), "the soft hyphen remains zero width if emitted"); + let v = |lay: &TextLayout| lay.glyphs.iter().find(|g| g.byte == 3).unwrap().origin.x; + assert!((v(&separated) - v(&plain)).abs() < 0.01, "the soft hyphen adds no spacing"); +} + +#[test] +fn optical_pair_after_separate_combining_mark_uses_base_outline() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let advances = |text: &str, manual: bool| { + let mut style = st.clone(); + if manual { + style.kerning = Some(0.0); + } + layout(db(), &TextObject::point(Point::ZERO, text, style)).glyphs.iter().map(|g| (g.byte, g.advance)).collect::>() + }; + let plain = advances("II", false); + let plain_zero = advances("II", true); + let accented = advances("I\u{30d}I", false); + let accented_zero = advances("I\u{30d}I", true); + assert_eq!(accented.len(), 3, "the accent has its own glyph"); + assert_eq!(accented[0].0, accented[1].0, "the base and mark share a cluster"); + assert!((accented[0].1 - accented_zero[0].1).abs() < 0.01, "the base keeps its advance"); + let correction = accented[1].1 - accented_zero[1].1; + assert!((correction - (plain[0].1 - plain_zero[0].1)).abs() < 0.01, "the marked cluster uses the base outline"); + assert!(correction.abs() > 0.1, "Optical adjusts the pair after the accent"); +} + +#[test] +fn optical_pair_after_rtl_separate_mark_uses_base_outline() { + let st = CharStyle { font_family: "Noto Sans Arabic".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let shaped = |text: &str, manual: bool| { + let mut style = st.clone(); + if manual { + style.kerning = Some(0.0); + } + layout(db(), &TextObject::point(Point::ZERO, text, style)).glyphs.iter().map(|g| (g.byte, g.advance)).collect::>() + }; + let plain = shaped("بب", false); + let plain_zero = shaped("بب", true); + let marked = shaped("بَب", false); + let marked_zero = shaped("بَب", true); + let marked_cluster = marked.iter().filter(|g| g.0 == 0).collect::>(); + assert_eq!(marked_cluster.len(), plain.iter().filter(|g| g.0 == 0).count() + 1, "the mark has its own glyph in the base cluster"); + assert_eq!(marked_cluster.first().unwrap().1, 0.0, "the cluster starts with a nonspacing glyph"); + assert!(marked_cluster.last().unwrap().1 > 0.0, "the base follows the mark"); + let correction = marked.iter().filter(|g| g.0 == 4).map(|g| g.1).sum::() - marked_zero.iter().filter(|g| g.0 == 4).map(|g| g.1).sum::(); + let plain_correction = + plain.iter().filter(|g| g.0 == 2).map(|g| g.1).sum::() - plain_zero.iter().filter(|g| g.0 == 2).map(|g| g.1).sum::(); + assert!(plain_correction.abs() > 0.1, "Optical adjusts the unmarked pair"); + assert!((correction - plain_correction).abs() < 0.01, "the marked cluster uses the base outline"); +} + +#[test] +fn recurring_optical_pairs_have_equal_corrections() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let text = "II".repeat(50); + let optical = layout(db(), &TextObject::point(Point::ZERO, &text, st.clone())).glyphs.iter().map(|g| g.advance).collect::>(); + let zero = layout(db(), &TextObject::point(Point::ZERO, &text, CharStyle { kerning: Some(0.0), ..st })) + .glyphs + .iter() + .map(|g| g.advance) + .collect::>(); + assert_eq!(optical.len(), zero.len()); + let correction = optical[0] - zero[0]; + assert!(correction.abs() > 0.1); + for i in 1..optical.len() - 1 { + assert_eq!(optical[i] - zero[i], correction, "pair {i} has the same correction"); + } +} + +#[test] +fn metrics_pair_survives_transition_to_optical() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AVV", st); + let advances = |text: &TextObject| layout(db(), text).glyphs.iter().map(|g| g.advance).collect::>(); + let metrics = advances(&text); + let mut unkerned = text.clone(); + unkerned.runs[0].style.kerning = Some(0.0); + assert!((metrics[0] - advances(&unkerned)[0]).abs() > 0.1, "the font supplies an AV pair"); + edit::style_range(&mut text.runs, 1, 3, |s| s.optical_kerning = true); + let mixed = advances(&text); + assert!((mixed[0] - metrics[0]).abs() < 0.01, "the metrics AV pair crosses the mode change"); + let mut optical = TextObject::point(Point::ZERO, "VV", text.runs[1].style.clone()); + let optical_pair = advances(&optical)[0]; + optical.runs[0].style.kerning = Some(0.0); + assert!((mixed[1] - optical_pair).abs() < 0.01, "the first Optical V keeps its next pair"); + assert!((mixed[1] - advances(&optical)[0]).abs() > 0.1, "Optical corrects the next pair"); +} + +#[test] +fn manual_pair_before_optical_does_not_gain_font_kerning() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AVA", st); + edit::style_range(&mut text.runs, 1, 2, |s| s.kerning = Some(0.0)); + edit::style_range(&mut text.runs, 2, 3, |s| s.optical_kerning = true); + let mixed = layout(db(), &text).glyphs[1].advance; + let mut unkerned = TextObject::point(Point::ZERO, "VA", text.runs[1].style.clone()); + unkerned.runs[0].style.kerning = Some(0.0); + let manual = layout(db(), &unkerned).glyphs[0].advance; + assert!((mixed - manual).abs() < 0.01, "manual V keeps its unkerned pair with Optical A"); +} + +#[test] +fn optical_pair_uses_drawn_baseline() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "II", st); + let first = |text: &TextObject| layout(db(), text).glyphs[0].advance; + let normal = first(&text); + edit::style_range(&mut text.runs, 1, 2, |s| s.baseline_shift = 80.0); + let shifted = first(&text); + assert!((shifted - normal).abs() > 0.1, "a displaced outline changes the Optical correction"); +} + +#[test] +fn optical_pair_skips_rotated_glyphs() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "II", st); + let first = |text: &TextObject| layout(db(), text).glyphs[0].advance; + let unrotated = first(&text); + let mut plain = text.clone(); + plain.runs[0].style.kerning = Some(0.0); + assert!((unrotated - first(&plain)).abs() > 0.1, "the unrotated pair has an Optical correction"); + edit::style_range(&mut text.runs, 1, 2, |s| s.rotation = 20.0); + let rotated = first(&text); + let mut manual_zero = text.clone(); + edit::style_range(&mut manual_zero.runs, 0, 1, |s| s.kerning = Some(0.0)); + assert!((rotated - first(&manual_zero)).abs() < 0.01, "rotated pairs keep their uncorrected advance"); +} + +#[test] +fn optical_shaping_keeps_manual_value_on_first_run() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, optical_kerning: true, kerning: Some(0.0), ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AVA", st); + let zero = layout(db(), &text).glyphs.iter().map(|g| g.advance).collect::>(); + edit::style_range(&mut text.runs, 0, 1, |s| s.kerning = Some(120.0)); + let manual = layout(db(), &text).glyphs.iter().map(|g| g.advance).collect::>(); + assert!((manual[0] - zero[0] - 12.0).abs() < 0.01, "the first run adds its manual value"); + assert!((manual[1] - zero[1]).abs() < 0.01, "the following run keeps its advance"); +} + +#[test] +fn ordinary_and_vertical_segments_keep_their_spacing() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, kerning: Some(100.0), ..CharStyle::default() }; + let plain = TextObject::point(Point::ZERO, "AVA", st); + let advances = |text: &TextObject| layout(db(), text).glyphs.iter().map(|g| g.advance).collect::>(); + let expected = advances(&plain); + let mut split = plain.clone(); + edit::style_range(&mut split.runs, 1, 2, |s| s.fill = vectorcraft_doc::color::Paint::solid(vectorcraft_doc::color::Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(advances(&split), expected, "a non-Optical segment keeps the same spacing across runs"); + + let mut vertical = plain; + vertical.vertical = true; + let expected = advances(&vertical); + edit::style_range(&mut vertical.runs, 0, 1, |s| s.kerning = Some(120.0)); + let manual = advances(&vertical); + assert!((manual[0] - expected[0] - 2.0).abs() < 0.01, "vertical manual spacing changes only its own advance"); + edit::style_range(&mut vertical.runs, 0, 3, |s| s.optical_kerning = true); + assert_eq!(advances(&vertical), manual, "vertical type keeps its spacing with Optical selected"); +} + +#[test] +fn optical_spacing_works_without_font_pair_tables() { + use crate::test_fonts::{NO_PAIR_KERNING_FAMILY, no_pair_kerning_font}; + + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(no_pair_kerning_font().unwrap()), 1); + let st = CharStyle { font_family: NO_PAIR_KERNING_FAMILY.into(), size: 100.0, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AV", st); + let metrics = layout(&db, &text).glyphs[0].advance; + text.runs[0].style.kerning = Some(0.0); + let manual_zero = layout(&db, &text).glyphs[0].advance; + assert!((metrics - manual_zero).abs() < 0.01, "the font has no automatic pair correction"); + text.runs[0].style.kerning = None; + text.runs[0].style.optical_kerning = true; + let optical = layout(&db, &text).glyphs[0].advance; + assert!((optical - manual_zero).abs() > 0.1, "Optical uses outlines without a pair table"); +} + +#[test] +fn manual_pair_positions_match_under_auto_and_optical_in_both_directions() { + use crate::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font}; + + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(right_to_left_optical_font().unwrap()), 1); + for (letters, family) in [("AV", "Source Sans 3"), ("אב", RIGHT_TO_LEFT_OPTICAL_FAMILY)] { + let mut text = TextObject::point(Point::ZERO, letters, CharStyle { font_family: family.into(), size: 100.0, ..CharStyle::default() }); + edit::style_range(&mut text.runs, 0, letters.chars().next().unwrap().len_utf8(), |s| s.kerning = Some(200.0)); + let positions = |text: &TextObject| layout(&db, text).glyphs.iter().map(|g| (g.byte, g.origin, g.advance)).collect::>(); + let auto = positions(&text); + edit::style_range(&mut text.runs, 0, letters.len(), |s| s.optical_kerning = true); + assert_eq!(positions(&text), auto, "{letters}: manual pair has the same positions in both modes"); + } +} + fn area_path(text: &str, st: CharStyle, frame: &BezPath, justify: Justify) -> TextObject { let mut t = TextObject::point(Point::ZERO, text, st); t.kind = TextKind::Area { frame: PathData::from_bezpath(frame) }; diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index d69b5df292..a2206df5eb 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -719,5 +719,29 @@ fn proportional_metrics_kern_the_glyphs_they_respace() { }; let (auto, manual) = (lay(true, None), lay(true, Some(0.0))); assert!(auto.iter().zip(&manual).any(|(a, b)| (a - b).abs() > 0.01), "kerned: {auto:?} {manual:?}"); + let optical = { + let s = CharStyle { font_family: "Noto Sans CJK SC".into(), optical_kerning: true, ..st(true, None) }; + layout(&db, &vertical_styled("「カタカナ」とトップ、ヤッホー。", s)).glyphs.iter().map(|g| g.advance).collect::>() + }; + assert!(auto.iter().zip(&optical).all(|(a, b)| (a - b).abs() < 0.01), "vertical Optical uses font metrics: {auto:?} {optical:?}"); assert!(lay(false, None).iter().all(|a| (a - 20.0).abs() < 0.01), "off: an em each, as before"); } + +#[test] +fn vertical_optical_to_auto_keeps_the_fonts_pair() { + use crate::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(pair_kerning_font().unwrap()); + let style = CharStyle { font_family: PAIR_KERNING_FAMILY.into(), size: 100.0, ..CharStyle::default() }; + let positions = + |t: &TextObject| layout(&db, t).glyphs.iter().map(|g| (g.advance, g.origin, g.xf.as_coeffs()[4], g.xf.as_coeffs()[5])).collect::>(); + let auto = vertical_styled("AV", style.clone()); + let mut mixed = auto.clone(); + edit::style_range(&mut mixed.runs, 0, 1, |s| s.optical_kerning = true); + let mut unkerned = auto.clone(); + edit::style_range(&mut unkerned.runs, 0, 1, |s| s.kerning = Some(0.0)); + let expected = positions(&auto); + assert_eq!(expected.len(), 2); + assert_ne!(expected, positions(&unkerned), "the font's A-V pair changes vertical positions"); + assert_eq!(positions(&mixed), expected, "vertical Optical keeps the A-V font pair across the style boundary"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2104ac7af6..fbb0019ec4 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1587,7 +1587,7 @@ font-technology Variable Променливи Keep the pasted color as a new swatch with a numbered name. Запазване на поставения цвят като нов образец с номерирано име. Keep this row's colors (exclude) Запазване на цветовете на този ред (изключване) Keep: Запазване: - Kerning (0 = Auto) Кернинг (0 = Автоматично) + Kerning Кернинг Keyboard Increment Стъпка с клавиатурата Keyboard Shortcut Conflicts Конфликти на клавишни комбинации Keyboard Shortcut Set Набор клавишни комбинации @@ -2159,6 +2159,7 @@ font-technology Variable Променливи Open the URL in the web browser Отваряне на URL адреса в уеб браузъра Opened with {} note(s): {} Отворено с {} бележка(и): {} Open… Отваряне… + Optical Оптично Optical Margin Alignment Подравняване по оптично поле Optimize for fast web view Оптимизиране за бърз уеб преглед Optimized Оптимизирано @@ -3761,6 +3762,7 @@ axis Both И двете Float Tool Group Плаваща група инструменти @msg no library `{id}` няма библиотека `{id}` @msg select some type first първо изберете текст +@msg kerning must be a number, "auto", or "optical" Кернингът трябва да е число, „auto“ или „optical“ @msg {_1} has no {_2} style {_1} няма стил {_2} @msg a layer couldn't be read слой не можа да бъде прочетен @msg it has more than one artboard има повече от една работна област diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 2d42bf75d5..311580ce5e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1411,7 +1411,8 @@ lighting Light Svjetlo Fractional Widths Djelimične širine Hide Options Sakrij opcije Horizontal Scale % Vodoravna skala % - Kerning (0 = Auto) Podrezivanje (0 = automatski) + Kerning Podrezivanje + Optical Optičko Leading Prored No Break Bez preloma Proportional Metrics Proporcionalna metrika @@ -4114,6 +4115,7 @@ imageTrace Outline Obris @plural {n} stroke|{n} strokes {n} potez|{n} poteza|{n} poteza @msg no library `{id}` nema biblioteke `{id}` @msg select some type first prvo odaberite tekst +@msg kerning must be a number, "auto", or "optical" Podrezivanje mora biti broj, „auto” ili „optical” @msg the selection has no gradient fill odabir nema ispunu gradijentom @msg the selection has no gradient stroke odabir nema potez gradijentom @msg the selection has no pattern fill odabir nema ispunu uzorkom diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index b7a1506662..442e051c03 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2046,8 +2046,8 @@ Keep visible surfaces only when expanding Conserva només les superfícies visibles en expandir Keep: Conserva: Keeps the document editable: VectorCraft reopens the PDF with nothing lost. For files you'll edit again. Manté el document editable: VectorCraft reobre el PDF sense perdre res. Per a fitxers que editaràs de nou. - Kerning (0 = Auto) Kerning (0 = automàtic) Key Color: Color clau: + Kerning Kerning Keyboard Increment Increment de teclat Keyboard Shortcut Conflicts Conflictes de dreceres de teclat Keyboard Shortcut Set Conjunt de dreceres de teclat @@ -2740,6 +2740,7 @@ Opens files in other apps Obre fitxers en altres aplicacions Opens network connections Obre connexions de xarxa Open… Obre… + Optical Òptic Optical Margin Alignment Alineació òptica de marges Optimize for fast web view Optimitza per a la visualització web ràpida Optimized Optimitzat @@ -5354,6 +5355,7 @@ @msg select paths or anchor points selecciona traçats o punts d’ancoratge @msg select paths to join selecciona traçats per unir @msg select some type first selecciona text primer +@msg kerning must be a number, "auto", or "optical" El kerning ha de ser un nombre, «auto» o «optical» @msg Select text or click into text with the Type tool to insert glyphs Selecciona text o fes clic dins del text amb l’eina de text per inserir glifs @msg select the art to export first selecciona primer la il·lustració que vols exportar @msg select the art to repeat selecciona la il·lustració que vols repetir diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 75765ab754..aa88620f4d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1436,7 +1436,6 @@ lighting Light Světlo Fractional Widths Zlomkové šířky Hide Options Skrýt možnosti Horizontal Scale % Vodorovná změna velikosti % - Kerning (0 = Auto) Vyrovnání párů (0 = automaticky) Leading Proklad No Break Nezalamovat Proportional Metrics Proporcionální metrika @@ -3514,6 +3513,7 @@ theme Appearance Motiv Identify Objects By Identifikovat objekty podle Include SVG Code Zahrnout kód SVG Italian Italština + Kerning Vyrovnání párů Keyboard Increment Krok klávesnice Language Options Možnosti jazyka Large Velké @@ -3556,6 +3556,7 @@ theme Appearance Motiv On Paste Při vložení On Screen Na obrazovce Open Documents As Tabs Otevírat dokumenty jako karty + Optical Optické Options Možnosti Output All Blacks Accurately Ve výstupu všechny černé přesně Output All Blacks as Rich Black Ve výstupu všechny černé jako sytou černou @@ -4151,6 +4152,7 @@ imageTrace Outline Obrys # Status and error messages @msg no library `{id}` knihovna `{id}` neexistuje @msg select some type first nejprve vyberte text +@msg kerning must be a number, "auto", or "optical" Vyrovnání párů musí být číslo, „auto“ nebo „optical“ @msg the selection has no gradient fill výběr nemá přechodovou výplň @msg the selection has no gradient stroke výběr nemá přechodový tah @msg the selection has no pattern fill výběr nemá vzorkovou výplň diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 8140d38e19..b7c6e23fda 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1351,7 +1351,6 @@ lighting Light Lys Fractional Widths Fraktionerede bredder Hide Options Skjul indstillinger Horizontal Scale % Vandret skalering % - Kerning (0 = Auto) Kerning (0 = automatisk) Leading Linjeafstand No Break Ingen ombrydning Proportional Metrics Proportionale metrikker @@ -3271,6 +3270,7 @@ theme Appearance Udseende Identify Objects By Identificér objekter ud fra Include SVG Code Medtag SVG-kode Italian Italiensk + Kerning Kerning Keyboard Increment Tastaturtrin Language Options Sprogindstillinger Large Stor @@ -3299,6 +3299,7 @@ theme Appearance Udseende On Paste Ved indsættelse On Screen På skærmen Open Documents As Tabs Åbn dokumenter som faner + Optical Optisk Options Indstillinger Output All Blacks Accurately Udskriv alle sorte nøjagtigt Output All Blacks as Rich Black Udskriv alle sorte som rich black @@ -3881,6 +3882,7 @@ imageTrace Outline Kontur @plural {n} stroke|{n} strokes {n} kontur|{n} konturer @msg no library `{id}` intet bibliotek `{id}` @msg select some type first markér først noget tekst +@msg kerning must be a number, "auto", or "optical" Kerning skal være et tal, „auto“ eller „optical“ @msg {_1} has no {_2} style {_1} har ingen {_2}-stil @msg a layer couldn't be read et lag kunne ikke læses @msg it has more than one artboard den har mere end én tegneflade diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index fa638758f3..2d1e728453 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1625,7 +1625,7 @@ file-filter Templates Vorlagen Keep the pasted color as a new swatch with a numbered name. Die eingefügte Farbe als neues Farbfeld mit nummeriertem Namen behalten. Keep this row's colors (exclude) Farben dieser Zeile beibehalten (ausschließen) Keep: Beibehalten: - Kerning (0 = Auto) Kerning (0 = Auto) + Kerning Kerning Keyboard Increment Schritte per Tastatur Keyboard Shortcut Conflicts Konflikte bei Tastaturbefehlen Keyboard Shortcut Set Tastaturbefehlssatz @@ -2172,6 +2172,7 @@ file-filter Templates Vorlagen Open the URL in the web browser Die URL im Webbrowser öffnen Opened with {} note(s): {} Mit {} Hinweis(en) geöffnet: {} Open… Öffnen… + Optical Optisch Optical Margin Alignment Optischer Randausgleich Optimize for fast web view Für schnelle Webanzeige optimieren Optimized Optimiert @@ -3763,6 +3764,7 @@ theme Appearance Erscheinungsbild # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. @msg no library `{id}` keine Bibliothek `{id}` @msg select some type first wählen Sie zuerst Text aus +@msg kerning must be a number, "auto", or "optical" Kerning muss eine Zahl, „auto“ oder „optical“ sein @msg the selection has no gradient fill die Auswahl hat keinen Flächenverlauf @msg the selection has no gradient stroke die Auswahl hat keinen Konturverlauf @msg the selection has no pattern fill die Auswahl hat kein Flächenmuster diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index baf6f52ec9..16fe9435e1 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1543,7 +1543,7 @@ font-technology Variable Μεταβλητές Keep Plain Text Διατήρηση απλού κειμένου Keep this row's colors (exclude) Διατήρηση των χρωμάτων αυτής της γραμμής (εξαίρεση) Keep: Διατήρηση: - Kerning (0 = Auto) Διαγραμμάτωση (0 = Αυτόματο) + Kerning Διαγραμμάτωση Keyboard Increment Βήμα πληκτρολογίου Keyboard Shortcut Conflicts Διενέξεις συντομεύσεων πληκτρολογίου Keyboard Shortcut Set Σύνολο συντομεύσεων πληκτρολογίου @@ -2080,6 +2080,7 @@ axis Both Και τα δύο Dock Panel Αγκύρωση πάνελ @msg no library `{id}` Δεν υπάρχει βιβλιοθήκη με αναγνωριστικό `{id}` @msg select some type first Επιλέξτε πρώτα κάποιο κείμενο +@msg kerning must be a number, "auto", or "optical" Η διαγραμμάτωση πρέπει να είναι αριθμός, «auto» ή «optical» @msg the selection has no gradient fill η επιλογή δεν έχει ντεγκραντέ γεμίσματος @msg the selection has no gradient stroke η επιλογή δεν έχει ντεγκραντέ περιγράμματος @msg the selection has no pattern fill η επιλογή δεν έχει μοτίβο γεμίσματος @@ -2886,6 +2887,7 @@ theme Appearance Εμφάνιση Open Swatch Library Άνοιγμα βιβλιοθήκης δειγμάτων χρωμάτων Open the URL in the web browser Άνοιγμα της διεύθυνσης στο πρόγραμμα περιήγησης Opened with {} note(s): {} Άνοιξε με {} σημειώσεις: {} + Optical Οπτική Optical Margin Alignment Οπτική στοίχιση περιθωρίου Optimize for fast web view Βελτιστοποίηση για γρήγορη προβολή στον ιστό Options for Selection… Επιλογές για την επιλογή… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 7b5b6aae3e..d4d2d20eb3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1625,7 +1625,7 @@ font-technology Variable Variables Keep the pasted color as a new swatch with a numbered name. Conservar el color pegado como una muestra nueva con nombre numerado. Keep this row's colors (exclude) Conservar los colores de esta fila (excluir) Keep: Conservar: - Kerning (0 = Auto) Interletraje (0 = auto) + Kerning Interletraje Keyboard Increment Incremento de teclado Keyboard Shortcut Conflicts Conflictos de métodos abreviados de teclado Keyboard Shortcut Set Conjunto de métodos abreviados de teclado @@ -2214,6 +2214,7 @@ font-technology Variable Variables Open the URL in the web browser Abrir la URL en el navegador web Opened with {} note(s): {} Abierto con {} nota(s): {} Open… Abrir… + Optical Óptico Optical Margin Alignment Alineación óptica de márgenes Optimize for fast web view Optimizar para vista web rápida Optimized Optimizado @@ -3843,6 +3844,7 @@ axis Both Ambos # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. @msg no library `{id}` no hay ninguna biblioteca `{id}` @msg select some type first selecciona primero algún texto +@msg kerning must be a number, "auto", or "optical" El interletraje debe ser un número, «auto» u «optical» @msg the selection has no gradient fill la selección no tiene un degradado de relleno @msg the selection has no gradient stroke la selección no tiene un degradado de trazo @msg the selection has no pattern fill la selección no tiene un motivo de relleno diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 606118dba8..e080c8f98d 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1411,7 +1411,6 @@ lighting Light Valo Fractional Widths Murtolukuleveydet Hide Options Piilota asetukset Horizontal Scale % Vaakaskaalaus % - Kerning (0 = Auto) Parivälistys (0 = automaattinen) Leading Riviväli No Break Ei katkoa Proportional Metrics Suhteelliset metriikat @@ -3453,6 +3452,7 @@ theme Appearance Ulkoasu Identify Objects By Tunnista objektit Include SVG Code Sisällytä SVG-koodi Italian Italia + Kerning Parivälistys Keyboard Increment Näppäimistön lisäys Language Options Kieliasetukset Large Suuri @@ -3481,6 +3481,7 @@ theme Appearance Ulkoasu On Paste Liitettäessä On Screen Näytöllä Open Documents As Tabs Avaa asiakirjat välilehtinä + Optical Optinen Options Asetukset Output All Blacks Accurately Tulosta kaikki mustat tarkasti Output All Blacks as Rich Black Tulosta kaikki mustat syvämustina @@ -4067,6 +4068,7 @@ imageTrace Outline Ääriviiva @plural {n} stroke|{n} strokes {n} viiva|{n} viivaa @msg no library `{id}` ei kirjastoa `{id}` @msg select some type first valitse ensin tekstiä +@msg kerning must be a number, "auto", or "optical" Parivälistyksen on oltava luku, ”auto” tai ”optical” @msg the selection has no gradient fill valinnalla ei ole liukuväritäyttöä @msg the selection has no gradient stroke valinnalla ei ole liukuväriviivaa @msg the selection has no pattern fill valinnalla ei ole kuviotäyttöä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 5e8203d511..dd9cc259a2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1625,7 +1625,7 @@ font-technology Variable Variables Keep the pasted color as a new swatch with a numbered name. Conserver la couleur collée comme nouvelle nuance avec un nom numéroté. Keep this row's colors (exclude) Conserver les couleurs de cette ligne (exclure) Keep: Conserver : - Kerning (0 = Auto) Crénage (0 = auto) + Kerning Crénage Keyboard Increment Incrément clavier Keyboard Shortcut Conflicts Conflits de raccourcis clavier Keyboard Shortcut Set Jeu de raccourcis clavier @@ -2212,6 +2212,7 @@ font-technology Variable Variables Open the URL in the web browser Ouvrir l’URL dans le navigateur web Opened with {} note(s): {} Ouvert avec {} remarque(s) : {} Open… Ouvrir… + Optical Optique Optical Margin Alignment Alignement optique des marges Optimize for fast web view Optimiser pour un affichage web rapide Optimized Optimisé @@ -3839,6 +3840,7 @@ axis Both Les deux # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. @msg no library `{id}` aucune bibliothèque `{id}` @msg select some type first sélectionnez d’abord du texte +@msg kerning must be a number, "auto", or "optical" Le crénage doit être un nombre, « auto » ou « optical » @msg the selection has no gradient fill la sélection n’a pas de dégradé de fond @msg the selection has no gradient stroke la sélection n’a pas de dégradé de contour @msg the selection has no pattern fill la sélection n’a pas de motif de fond diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index aec44044da..671a569caa 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2044,8 +2044,8 @@ file-filter Templates Sablonok Keep visible surfaces only when expanding Kibontáskor csak a látható felületek megtartása Keep: Megtartás: Keeps the document editable: VectorCraft reopens the PDF with nothing lost. For files you'll edit again. Szerkeszthető marad a dokumentum: a VectorCraft veszteség nélkül nyitja meg újra a PDF-et. Azokhoz a fájlokhoz, amelyeket még szerkesztesz. - Kerning (0 = Auto) Alávágás (0 = automatikus) Key Color: Kulcsszín: + Kerning Alávágás Keyboard Increment Billentyűzetes lépésköz Keyboard Shortcut Conflicts Billentyűparancs-ütközések Keyboard Shortcut Set Billentyűparancs-készlet @@ -2688,6 +2688,7 @@ file-filter Templates Sablonok “{name}” already exists. Replace it? „{name}” már létezik. Felülírod? The name in the save panel was “{typed}”; VectorCraft added the file type's extension. Replacing the file overwrites its contents. A mentési panelen megadott név ez volt: „{typed}”, a VectorCraft pedig hozzáadta a fájltípus kiterjesztését. A fájl felülírásakor a tartalma elvész. Open… Megnyitás… + Optical Optikai Optical Margin Alignment Optikai margóigazítás Optimize for fast web view Optimalizálás gyors webes megtekintéshez Optimized Optimalizált @@ -5044,6 +5045,7 @@ imageTrace Outline Körvonal @msg select paths or anchor points jelölj ki útvonalakat vagy horgonypontokat @msg select paths to join jelöld ki az összekapcsolandó útvonalakat @msg select some type first előbb jelölj ki szöveget +@msg kerning must be a number, "auto", or "optical" Az alávágás szám, „auto” vagy „optical” lehet @msg the selection has no gradient fill a kijelölésnek nincs színátmenetes kitöltése @msg the selection has no gradient stroke a kijelölésnek nincs színátmenetes körvonala @msg the selection has no pattern fill a kijelölésnek nincs mintázatos kitöltése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 5329eea88d..664551a1fa 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1351,7 +1351,6 @@ lighting Light Cahaya Fractional Widths Lebar fraksional Hide Options Sembunyikan opsi Horizontal Scale % Skala horizontal % - Kerning (0 = Auto) Kerning (0 = Otomatis) Leading Leading No Break Tanpa pemenggalan Proportional Metrics Metrik proporsional @@ -3271,6 +3270,7 @@ theme Appearance Tampilan Identify Objects By Identifikasi objek berdasarkan Include SVG Code Sertakan kode SVG Italian Italia + Kerning Kerning Keyboard Increment Inkremen papan ketik Language Options Opsi bahasa Large Besar @@ -3299,6 +3299,7 @@ theme Appearance Tampilan On Paste Saat menempel On Screen Di layar Open Documents As Tabs Buka dokumen sebagai tab + Optical Optis Options Opsi Output All Blacks Accurately Keluarkan semua warna hitam secara akurat Output All Blacks as Rich Black Keluarkan semua warna hitam sebagai rich black @@ -3881,6 +3882,7 @@ imageTrace Outline Kontur @plural {n} stroke|{n} strokes {n} goresan @msg no library `{id}` tidak ada pustaka `{id}` @msg select some type first pilih beberapa teks terlebih dahulu +@msg kerning must be a number, "auto", or "optical" Kerning harus berupa angka, “auto”, atau “optical” @msg {_1} has no {_2} style {_1} tidak memiliki gaya {_2} @msg a layer couldn't be read satu lapisan tidak dapat dibaca @msg it has more than one artboard memiliki lebih dari satu artboard diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 34c18549d2..708378ba43 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1650,7 +1650,7 @@ file-filter Templates Modelli Keep the pasted color as a new swatch with a numbered name. Mantieni il colore incollato come nuovo campione con un nome numerato. Keep this row's colors (exclude) Mantieni i colori di questa riga (escludi) Keep: Mantieni: - Kerning (0 = Auto) Crenatura (0 = auto) + Kerning Crenatura Keyboard Increment Incremento da tastiera Keyboard Shortcut Conflicts Conflitti tra scelte rapide da tastiera Keyboard Shortcut Set Set di scelte rapide da tastiera @@ -2241,6 +2241,7 @@ file-filter Templates Modelli Open the URL in the web browser Apri l'URL nel browser web Opened with {} note(s): {} Aperto con note ({}): {} Open… Apri… + Optical Ottica Optical Margin Alignment Allineamento ottico dei margini Optimize for fast web view Ottimizza per visualizzazione web veloce Optimized Ottimizzato @@ -3883,6 +3884,7 @@ axis Both Entrambi # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. @msg no library `{id}` nessuna libreria `{id}` @msg select some type first seleziona prima del testo +@msg kerning must be a number, "auto", or "optical" La crenatura deve essere un numero, «auto» o «optical» @msg the selection has no gradient fill la selezione non ha una sfumatura di riempimento @msg the selection has no gradient stroke la selezione non ha una sfumatura di traccia @msg the selection has no pattern fill la selezione non ha un motivo di riempimento diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5d8e120742..628f0ec033 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1880,7 +1880,7 @@ font-technology Variable バリアブル Keep Plain Text テキストのみを保持 Keep both sides the same width 両側を同じ幅に保つ Keep this row's colors (exclude) この行のカラーを保持 (除外) - Kerning (0 = Auto) カーニング (0 = 自動) + Kerning カーニング Keyboard Increment キー入力 Keyboard Shortcut Conflicts キーボードショートカットの競合 Keyboard Shortcut Set キーボードショートカットセット @@ -2346,6 +2346,7 @@ font-technology Variable バリアブル Open the URL in the web browser URL を Web ブラウザーで開く Optimize for fast web view Web ビュー用に最適化 Optimized 最適化 + Optical オプティカル Options オプション Options for Selection… 選択項目のオプション… Options: オプション: @@ -4573,6 +4574,7 @@ swatch Bright Violet ビビッドバイオレット @msg choose a folder to export to 書き出し先のフォルダーを選択してください @msg the selection has no URL (or they differ) 選択したオブジェクトに URL がありません (または URL がそれぞれ異なります) @msg select some type first 先にテキストを選択してください +@msg kerning must be a number, "auto", or "optical" カーニングは数値、「auto」または「optical」にしてください @msg the selection has no gradient fill 選択したオブジェクトに塗りのグラデーションがありません @msg the selection has no gradient stroke 選択したオブジェクトに線のグラデーションがありません @msg the selection has no pattern fill 選択したオブジェクトに塗りのパターンがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index ab0f0704d5..4d44093f71 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1268,7 +1268,6 @@ lighting Light სინათლე Fractional Widths წილადი სიგანეები Hide Options პარამეტრების დამალვა Horizontal Scale % ჰორიზონტალური მასშტაბი % - Kerning (0 = Auto) კერნინგი (0 = ავტო) Leading სტრიქონთა დაშორება No Break გადატანის გარეშე Proportional Metrics პროპორციული მეტრიკა @@ -3082,6 +3081,7 @@ theme Appearance იერსახე Identify Objects By ობიექტების იდენტიფიკაცია: Include SVG Code SVG კოდის ჩართვა Italian იტალიური + Kerning კერნინგი Keyboard Increment კლავიატურის ბიჯი Language Options ენის პარამეტრები Large დიდი @@ -3110,6 +3110,7 @@ theme Appearance იერსახე On Paste ჩასმისას On Screen ეკრანზე Open Documents As Tabs დოკუმენტების ჩანართებად გახსნა + Optical ოპტიკური Options პარამეტრები Output All Blacks Accurately ყველა შავის ზუსტად გამოტანა Output All Blacks as Rich Black ყველა შავის მდიდარ შავად გამოტანა @@ -3647,6 +3648,7 @@ font-technology Variable ცვლადი @plural {n} stroke|{n} strokes კონტური: {n} @msg no library `{id}` ბიბლიოთეკა `{id}` არ არსებობს @msg select some type first ჯერ მონიშნეთ ტექსტი +@msg kerning must be a number, "auto", or "optical" კერნინგი უნდა იყოს რიცხვი, „auto“ ან „optical“ @msg the selection has no gradient fill მონიშნულს შევსების გრადიენტი არ აქვს @msg the selection has no gradient stroke მონიშნულს კონტურის გრადიენტი არ აქვს @msg the selection has no pattern fill მონიშნულს შევსების პატერნი არ აქვს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5da60d2476..dea1f8f503 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1909,7 +1909,7 @@ font-technology Variable 가변 Keep Plain Text 일반 텍스트 유지 Keep both sides the same width 양쪽 너비를 같게 유지 Keep this row's colors (exclude) 이 행의 색상 유지 (제외) - Kerning (0 = Auto) 커닝 (0 = 자동) + Kerning 커닝 Keyboard Increment 키보드 증분 Keyboard Shortcut Conflicts 단축키 충돌 Keyboard Shortcut Set 단축키 세트 @@ -2337,6 +2337,7 @@ font-technology Variable 가변 Open the URL in the web browser 웹 브라우저에서 URL 열기 Optimize for fast web view 빠른 웹 보기용으로 최적화 Optimized 최적화됨 + Optical 광학 Options 옵션 Options for Selection… 선택 항목 옵션… Options: 옵션: @@ -4501,6 +4502,7 @@ theme Appearance 외관 @msg choose a folder to export to 내보낼 폴더를 선택하세요 @msg the selection has no URL (or they differ) 선택 항목에 URL이 없거나 서로 다릅니다 @msg select some type first 먼저 문자를 선택하세요 +@msg kerning must be a number, "auto", or "optical" 커닝은 숫자, “auto” 또는 “optical”이어야 합니다 @msg the selection has no gradient fill 선택 항목에 칠 그레이디언트가 없습니다 @msg the selection has no gradient stroke 선택 항목에 선 그레이디언트가 없습니다 @msg the selection has no pattern fill 선택 항목에 칠 패턴이 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ee4e09b61f..19fdc86635 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1365,7 +1365,6 @@ lighting Light Licht Fractional Widths Fractionele breedtes Hide Options Opties verbergen Horizontal Scale % Horizontale schaal % - Kerning (0 = Auto) Kerning (0 = Auto) Leading Regelafstand No Break Niet afbreken Proportional Metrics Proportionele metingen @@ -3285,6 +3284,7 @@ theme Appearance Vormgeving Identify Objects By Objecten identificeren op Include SVG Code SVG-code opnemen Italian Italiaans + Kerning Kerning Keyboard Increment Toetsenbordincrement Language Options Taalopties Large Groot @@ -3313,6 +3313,7 @@ theme Appearance Vormgeving On Paste Bij plakken On Screen Op scherm Open Documents As Tabs Documenten openen als tabbladen + Optical Optisch Options Opties Output All Blacks Accurately Alle zwarttinten nauwkeurig uitvoeren Output All Blacks as Rich Black Alle zwarttinten uitvoeren als rijk zwart @@ -3895,6 +3896,7 @@ imageTrace Outline Contour @plural {n} stroke|{n} strokes {n} lijn|{n} lijnen @msg no library `{id}` geen bibliotheek `{id}` @msg select some type first selecteer eerst wat tekst +@msg kerning must be a number, "auto", or "optical" Kerning moet een getal, ‘auto’ of ‘optical’ zijn @msg {_1} has no {_2} style {_1} heeft geen {_2}stijl @msg a layer couldn't be read een laag kon niet worden gelezen @msg it has more than one artboard het heeft meer dan één tekengebied diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5c90b4d977..9debbef17a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1350,7 +1350,6 @@ lighting Light Światło Fractional Widths Szerokości ułamkowe Hide Options Ukryj opcje Horizontal Scale % Skala pozioma % - Kerning (0 = Auto) Kerning (0 = auto) Leading Interlinia No Break Bez podziału Proportional Metrics Metryka proporcjonalna @@ -3392,6 +3391,7 @@ theme Appearance Wygląd Identify Objects By Identyfikuj obiekty według Include SVG Code Dołącz kod SVG Italian Włoski + Kerning Kerning Keyboard Increment Przyrost klawiatury Language Options Opcje języka Large Duże @@ -3420,6 +3420,7 @@ theme Appearance Wygląd On Paste Przy wklejaniu On Screen Na ekranie Open Documents As Tabs Otwieraj dokumenty jako karty + Optical Optyczny Options Opcje Output All Blacks Accurately Wyprowadzaj wszystkie czernie dokładnie Output All Blacks as Rich Black Wyprowadzaj wszystkie czernie jako czerń głęboką @@ -3975,6 +3976,7 @@ imageTrace Outline Kontur @plural {n} stroke|{n} strokes {n} obrys|{n} obrysy|{n} obrysów @msg no library `{id}` brak biblioteki `{id}` @msg select some type first najpierw zaznacz tekst +@msg kerning must be a number, "auto", or "optical" Kerning musi być liczbą, „auto” lub „optical” @msg the selection has no gradient fill zaznaczenie nie ma gradientu wypełnienia @msg the selection has no gradient stroke zaznaczenie nie ma gradientu obrysu @msg the selection has no pattern fill zaznaczenie nie ma wzorka wypełnienia diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0694d8f183..e40d32fb13 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1400,7 +1400,7 @@ Keep Plain Text Manter Texto Simples Keep both sides the same width Manter os dois lados com a mesma largura Keep this row's colors (exclude) Manter as cores desta linha (excluir) - Kerning (0 = Auto) Kerning (0 = Automático) + Kerning Kerning Keyboard Increment Incremento do Teclado Keyboard Shortcut Conflicts Conflitos de Atalhos de Teclado Keyboard Shortcut Set Conjunto de Atalhos de Teclado @@ -1810,6 +1810,7 @@ Open password: Senha de abertura: Open the URL in the web browser Abra a URL no navegador da web Open… Abrir… + Optical Óptico Optical Margin Alignment Alinhamento de Margem Óptica Optimize for fast web view Otimizar para visualização rápida na web Optimized Otimizado @@ -3430,6 +3431,7 @@ axis Both Ambos Drag to the window's left edge to dock Arraste até a borda esquerda da janela para encaixar @msg no library `{id}` nenhuma biblioteca `{id}` @msg select some type first selecione algum texto primeiro +@msg kerning must be a number, "auto", or "optical" O kerning deve ser um número, “auto” ou “optical” @msg the selection has no gradient fill a seleção não tem gradiente de preenchimento @msg the selection has no gradient stroke a seleção não tem gradiente de traçado @msg the selection has no pattern fill a seleção não tem padrão de preenchimento diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 105ba72d17..7bfca518c4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1648,7 +1648,7 @@ file-filter Templates Шаблоны Keep the pasted color as a new swatch with a numbered name. Сохранять вставленный цвет как новый образец с номерным именем. Keep this row's colors (exclude) Сохранить цвета этой строки (исключить) Keep: Сохранять: - Kerning (0 = Auto) Кернинг (0 = авто) + Kerning Кернинг Keyboard Increment Приращение с клавиатуры Keyboard Shortcut Conflicts Конфликты сочетаний клавиш Keyboard Shortcut Set Набор сочетаний клавиш @@ -2237,6 +2237,7 @@ file-filter Templates Шаблоны Open the URL in the web browser Открыть URL в веб-браузере Opened with {} note(s): {} Открыто с примечаниями ({}) : {} Open… Открыть… + Optical Оптический Optical Margin Alignment Оптическое выравнивание полей Optimize for fast web view Оптимизировать для быстрого просмотра в web Optimized Оптимизировано @@ -3879,6 +3880,7 @@ axis Both Оба # names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are. @msg no library `{id}` нет библиотеки `{id}` @msg select some type first сначала выделите текст +@msg kerning must be a number, "auto", or "optical" Кернинг должен быть числом, «auto» или «optical» @msg the selection has no gradient fill у выделения нет градиентной заливки @msg the selection has no gradient stroke у выделения нет градиентной обводки @msg the selection has no pattern fill у выделения нет узорной заливки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4831119887..1bd22f672d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1587,7 +1587,7 @@ font-technology Variable Variabla Keep the pasted color as a new swatch with a numbered name. Behåll den inklistrade färgen som en ny färgruta med numrerat namn. Keep this row's colors (exclude) Behåll radens färger (undanta) Keep: Behåll: - Kerning (0 = Auto) Kerning (0 = auto) + Kerning Kerning Keyboard Increment Tangentbordssteg Keyboard Shortcut Conflicts Konflikter mellan kortkommandon Keyboard Shortcut Set Uppsättning kortkommandon @@ -2159,6 +2159,7 @@ font-technology Variable Variabla Open the URL in the web browser Öppna URL:en i webbläsaren Opened with {} note(s): {} Öppnad med {} anteckning(ar): {} Open… Öppna… + Optical Optisk Optical Margin Alignment Optisk marginaljustering Optimize for fast web view Optimera för snabb webbvisning Optimized Optimerad @@ -3761,6 +3762,7 @@ axis Both Båda Float Tool Group Gör verktygsgruppen flytande @msg no library `{id}` inget bibliotek `{id}` @msg select some type first markera någon text först +@msg kerning must be a number, "auto", or "optical" Kerning måste vara ett tal, ”auto” eller ”optical” @msg the selection has no gradient fill markeringen har ingen fyllnadsgradient @msg the selection has no gradient stroke markeringen har ingen konturgradient @msg the selection has no pattern fill markeringen har inget fyllnadsmönster diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 5e53f4fefe..41456bf052 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -576,7 +576,7 @@ fn character_panel_terms_agree_within_each_catalog() { for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { let (entries, _) = parse_entries(l.source); let row = |src: &str| entries.iter().find(|(ctx, s, _)| ctx.is_empty() && s == src).map(|(_, _, tr)| tr.to_lowercase()); - let kerning = row("Kerning (0 = Auto)").map(|tr| tr.split(" (").next().unwrap_or_default().trim().to_string()); + let kerning = row("Kerning"); let leading = row("Leading"); let tracking = row("Tracking"); for (a, b) in [(&kerning, &leading), (&kerning, &tracking), (&leading, &tracking)] { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 23bdb68391..deb3e95d78 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1474,7 +1474,7 @@ font-technology Variable Değişken Keep the pasted color as a new swatch with a numbered name. Yapıştırılan rengi numaralı bir adla yeni bir renk örneği olarak koruyun. Keep this row's colors (exclude) Bu satırın renklerini koru (hariç tut) Keep: Sakla: - Kerning (0 = Auto) Karakter Aralığı (0 = Otomatik) + Kerning Karakter aralığı Keyboard Increment Klavye Artışı Keyboard Shortcut Conflicts Klavye Kısayolu Çakışmaları Keyboard Shortcut Set Klavye Kısayol Seti @@ -2038,6 +2038,7 @@ shape Open Açık Open the URL in the web browser URL'yi web tarayıcısında açın Opened with {} note(s): {} {} notla açıldı: {} Open… Aç… + Optical Optik Optical Margin Alignment Optik Kenar Boşluğu Hizalaması Optimize for fast web view Hızlı web görünümü için optimize edin Optimized Optimize edilmiş @@ -3655,6 +3656,7 @@ axis Both Her İkisi Float Tool Group Araç Grubunu Yüzer Yap @msg no library `{id}` `{id}` kütüphanesi yok @msg select some type first önce bir tür seçin +@msg kerning must be a number, "auto", or "optical" Karakter aralığı sayı, “auto” veya “optical” olmalıdır @msg the selection has no gradient fill seçimin degrade dolgusu yok @msg the selection has no gradient stroke seçimin degrade konturu yok @msg the selection has no pattern fill seçimin desen dolgusu yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dde23c7422..d78f48b331 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1644,7 +1644,7 @@ file-filter Templates Шаблони Keep the pasted color as a new swatch with a numbered name. Зберігати вставлений колір як новий зразок із номерним ім’ям. Keep this row's colors (exclude) Зберегти кольори цього рядка (виключити) Keep: Зберігати: - Kerning (0 = Auto) Кернінг (0 = авто) + Kerning Кернінг Keyboard Increment Крок клавіатури Keyboard Shortcut Conflicts Конфлікти поєднань клавіш Keyboard Shortcut Set Набір клавіш @@ -2233,6 +2233,7 @@ file-filter Templates Шаблони Open the URL in the web browser Відкрити URL у веб-браузері Opened with {} note(s): {} Відкрито із примітками ({}) : {} Open… Відкрити… + Optical Оптичний Optical Margin Alignment Оптичне вирівнювання полів Optimize for fast web view Оптимізувати для швидкого перегляду web Optimized Оптимізовано @@ -3867,6 +3868,7 @@ axis Both Обидві Float Tool Group Від’єднати групу інструментів @msg no library `{id}` немає бібліотеки `{id}` @msg select some type first спочатку виділіть текст +@msg kerning must be a number, "auto", or "optical" Кернінг має бути числом, «auto» або «optical» @msg the selection has no gradient fill виділення не має градієнтної заливки @msg the selection has no gradient stroke виділення не має градієнтного обведення @msg the selection has no pattern fill виділення не має візерункової заливки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e060c09993..ade0a07aae 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1922,8 +1922,8 @@ file-filter Templates Mẫu Keep this row's colors (exclude) Giữ màu của hàng này (loại trừ) Keep visible surfaces only when expanding Chỉ giữ bề mặt hiển thị khi mở rộng Keep: Giữ: - Kerning (0 = Auto) Kerning (0 = Tự động) Key Color: Màu chủ: + Kerning Kerning Keyboard Increment Bước nhảy bàn phím Keyboard Shortcut Conflicts Xung đột phím tắt Keyboard Shortcut Set Bộ phím tắt @@ -2499,6 +2499,7 @@ file-filter Templates Mẫu “{name}” already exists. Replace it? “{name}” đã tồn tại. Thay thế tệp này? The name in the save panel was “{typed}”; VectorCraft added the file type's extension. Replacing the file overwrites its contents. Tên trong bảng lưu là “{typed}”, và VectorCraft đã thêm phần mở rộng của loại tệp. Thay thế tệp sẽ ghi đè nội dung của tệp. Open… Mở… + Optical Quang học Optical Margin Alignment Căn lề quang học Optimize for fast web view Tối ưu để xem web nhanh Optimized Đã tối ưu @@ -4696,6 +4697,7 @@ theme Appearance Giao diện @msg select paths or anchor points chọn đường dẫn hoặc điểm neo @msg select paths to join hãy chọn đường dẫn để nối @msg select some type first hãy chọn chữ trước +@msg kerning must be a number, "auto", or "optical" Kerning phải là số, “auto” hoặc “optical” @msg the selection has no gradient fill vùng chọn không có tô chuyển sắc @msg the selection has no gradient stroke vùng chọn không có nét chuyển sắc @msg the selection has no pattern fill vùng chọn không có tô họa tiết diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 65842950a7..acffa1e4e9 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1575,7 +1575,7 @@ file-filter Templates 模板 Keep the pasted color as a new swatch with a numbered name. 将粘贴的颜色保留为新色板,并以编号命名。 Keep this row's colors (exclude) 保留此行的颜色 (排除) Keep: 保留: - Kerning (0 = Auto) 字偶距 (0 = 自动) + Kerning 字偶距 Keyboard Increment 键盘增量 Keyboard Shortcut Conflicts 键盘快捷键冲突 Keyboard Shortcut Set 键盘快捷键组 @@ -2113,6 +2113,7 @@ file-filter Templates 模板 Opened with {} note(s): {} 已打开,附 {} 条附注:{} OpenType OpenType Open… 打开… + Optical 视觉 Optical Margin Alignment 视觉边界对齐 Optimize for fast web view 优化快速 Web 查看 Optimized 优化 @@ -4290,6 +4291,7 @@ imageTrace Outline 轮廓 @msg choose a folder to export to 请选择要导出到的文件夹 @msg the selection has no URL (or they differ) 所选对象没有 URL (或其 URL 各不相同) @msg select some type first 请先选择一些文字 +@msg kerning must be a number, "auto", or "optical" 字偶距必须是数字、“auto”或“optical” @msg the selection has no gradient fill 所选对象没有渐变填色 @msg the selection has no gradient stroke 所选对象没有渐变描边 @msg the selection has no pattern fill 所选对象没有图案填色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index fb06daa662..3b560be95b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1614,7 +1614,7 @@ file-filter Templates 範本 Keep the pasted color as a new swatch with a numbered name. 將貼上的顏色保留為新色票,並以編號命名。 Keep this row's colors (exclude) 保留此列的顏色 (排除) Keep: 保留: - Kerning (0 = Auto) 字距微調 (0 = 自動) + Kerning 字距微調 Keyboard Increment 鍵盤增量 Keyboard Shortcut Conflicts 鍵盤快速鍵衝突 Keyboard Shortcut Set 鍵盤快速鍵組 @@ -2228,6 +2228,7 @@ file-filter Templates 範本 @msg choose a folder to export to 請選擇要匯出至的資料夾 @msg the selection has no URL (or they differ) 選取範圍沒有 URL (或其 URL 各不相同) @msg select some type first 請先選取一些文字 +@msg kerning must be a number, "auto", or "optical" 字距微調必須是數字、「auto」或「optical」 @msg the selection has no gradient fill 選取範圍沒有漸層填色 @msg the selection has no gradient stroke 選取範圍沒有漸層筆畫 @msg the selection has no pattern fill 選取範圍沒有圖樣填色 @@ -3047,6 +3048,7 @@ file-filter Templates 範本 Opened with {} note(s): {} 已開啟,附 {} 則附註:{} OpenType OpenType Open… 開啟… + Optical 視覺 Optical Margin Alignment 視覺邊界對齊 Optimize for fast web view 最佳化以便快速網頁檢視 Optimized 最佳化 diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 91dc0a7410..82445374b3 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -222,7 +222,7 @@ fn char_cmd(app: &mut VectorcraftApp, cmd: &str, p: Value) { range_style(app, p); } -/// Set the Kerning field's `value` (a number or "auto"). At a caret in text the Type tool edits +/// Set the Kerning field's `value` (a number, "auto", or "optical"). At a caret in text the Type tool edits /// it is the pair kerning after the character before the caret, as Alt+←/→ steps it /// (`type.step`); nowhere to set at the start of the text. Else it is a character attribute like /// the others: the selected range, or all the text. @@ -244,6 +244,37 @@ fn set_kerning(app: &mut VectorcraftApp, value: Value) { app.run("text.setRangeStyle", json!({"id": id.0, "start": start, "end": a, "kerning": value})).ok(); } +/// The pair before the caret, in 1/1000 em, using the layout the canvas draws. +fn caret_kerning(app: &VectorcraftApp, ui: &Ui) -> Option<(f64, bool)> { + let (id, a, b) = text_editing(app)?; + if a != b { + return None; + } + let NodeKind::Text(t) = &app.session.active()?.doc.node(id)?.kind else { return None }; + let text = t.plain_text(); + let start = vectorcraft_text::edit::prev_char(&text, a); + if start >= a { + return None; + } + let style = vectorcraft_text::edit::style_at(&t.runs, start + 1); + if let Some(v) = style.kerning { + return Some((v, false)); + } + let state = app.session.active()?; + let key = (state.uid, state.revision, id, a); + let slot = ui.scope_id().with("caret-kerning"); + if let Some((cached_key, value)) = ui.ctx().data(|d| d.get_temp::<((u64, u64, NodeId, usize), f64)>(slot)) + && cached_key == key + { + return Some((value, true)); + } + let original = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let value = vectorcraft_engine::cmd::effective_kerning(vectorcraft_text::FontDb::global(), t, &original, start, a); + let value = value.round(); + ui.ctx().data_mut(|d| d.insert_temp(slot, (key, value))); + Some((value, true)) +} + /// The faces Type › Bold and Type › Italic switch to. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Face { @@ -637,14 +668,33 @@ pub(crate) fn metrics_grid(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, s: & match widgets::spin_field_auto(ui, "ch-lead", leading, Some(auto), unit, fw, 1.0, 0.1, &SIZE_PRESETS) { Some(SpinPick::Value(v)) => style(app, json!({"leading": v})), Some(SpinPick::Auto) => style(app, json!({"leading": "auto"})), + Some(SpinPick::Optical) => {} None => {} } }); ui.end_row(); - cell(ui, "VA", tl!("Kerning (0 = Auto)"), |ui| { - let kerning = shared(app, |s| s.kerning.unwrap_or(0.0)); - if let Some(v) = widgets::spin_plain(ui, "ch-kern", kerning, "", 0, fw, 10.0, -1000.0, &TRACKING_PRESETS) { - set_kerning(app, if v == 0.0 { json!("auto") } else { json!(v) }); + cell(ui, "VA", tl!("Kerning"), |ui| { + let mode = shared(app, |s| (s.optical_kerning, s.kerning)); + let caret = text_editing(app).is_some_and(|(_, a, b)| a == b); + let at_caret = if caret { caret_kerning(app, ui) } else { None }; + let kerning = at_caret.map(|(v, _)| v).or_else(|| mode.map(|(_, manual)| manual.unwrap_or(0.0))); + let automatic = mode.map(|(optical, manual)| !optical && manual.is_none()); + let optical = mode.map(|(optical, _)| optical); + match widgets::spin_kerning( + ui, + "ch-kern", + kerning, + automatic, + optical, + tl!("Optical"), + at_caret.is_some_and(|(_, auto)| auto), + fw, + &TRACKING_PRESETS, + ) { + Some(SpinPick::Value(v)) => set_kerning(app, json!(v)), + Some(SpinPick::Auto) => set_kerning(app, json!("auto")), + Some(SpinPick::Optical) => set_kerning(app, json!("optical")), + None => {} } }); cell(ui, "VA↔", tl!("Tracking"), |ui| { diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index fe5e53b3eb..61ec42a218 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -130,6 +130,38 @@ fn kerning_at_a_caret_sets_the_pair_not_the_whole_text() { assert_eq!((kerning(&app, 1), kerning(&app, 2), kerning(&app, 3)), (Some(-50.0), Some(30.0), Some(30.0))); } +#[test] +fn character_kerning_setter_and_automatic_pair_value() { + let german = crate::i18n::Lang::from_code("de").unwrap(); + assert!(crate::i18n::has(german, "Optical")); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.run("text.create", json!({"x": 20, "y": 50, "text": "III", "size": 100, "font": "JetBrains Mono"})).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 1, "end": 1})); + set_kerning(&mut app, json!("optical")); + assert!(text_style(&app).unwrap().0.optical_kerning); + let ctx = egui::Context::default(); + let mut shown = None; + ctx.run_ui(Default::default(), |ui| { + shown = caret_kerning(&app, ui); + }) + .textures_delta + .clear(); + let (value, automatic) = shown.unwrap(); + assert!(automatic && value != 0.0); + set_kerning(&mut app, json!(50)); + ctx.run_ui(Default::default(), |ui| { + shown = caret_kerning(&app, ui); + }) + .textures_delta + .clear(); + assert_eq!(shown, Some((50.0, false))); + app.session.set_tool_option("select", &json!({"start": 0, "end": 2})); + assert_eq!(shared(&app, |s| (s.optical_kerning, s.kerning)), None, "a mixed range shows a blank Kerning field"); +} + /// Highlight Kerning and Highlight Tracking show the Character panel and give its field the /// keyboard focus with the value selected: what is typed replaces it, and Enter applies it. /// Highlight Font Name opens the font family menu with its search field focused. Without diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index c6b855ffdc..30a6fa2b71 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -51,7 +51,7 @@ pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit} pub use numeric::{ SpinPick, mixed_field, mixed_field_named, num_field, num_field_named, num_field_within, opt_field, opt_field_named, range_field, range_field_named, range_field_stepped, size_field, size_field_named, slider, spin_field, spin_field_auto, spin_field_auto_named, - spin_field_named, spin_field_stops_named, spin_plain, spin_plain_named, + spin_field_named, spin_field_stops_named, spin_kerning, spin_plain, spin_plain_named, }; #[cfg(test)] use numeric::{decimal_point, share_of, spinner_step, step_through, step_to_multiple, within_a_millionth}; diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 1867eb271b..9244c32bf6 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -346,7 +346,7 @@ pub fn range_field_named( let places = decimals.min(6) as i32; let value = value.into().map(|v| within(v, &range)); let label = take_previous_label(ui); - bounded_field(ui, id, label, name, value, suffix, decimals, width, &range, None).map(|v| within(round_to(v, places), &range)) + bounded_field(ui, id, label, name, value, suffix, decimals, width, &range, None, false).map(|v| within(round_to(v, places), &range)) } /// [`range_field`] whose ↑/↓ and wheel take `step`'s steps instead of whole numbers (see @@ -366,7 +366,7 @@ pub fn range_field_stepped( let places = decimals.min(6) as i32; let value = value.into().map(|v| within(v, &range)); let label = take_previous_label(ui); - bounded_field(ui, id, label, None, value, suffix, decimals, width, &range, Some(step)).map(|v| within(round_to(v, places), &range)) + bounded_field(ui, id, label, None, value, suffix, decimals, width, &range, Some(step), false).map(|v| within(round_to(v, places), &range)) } /// [`plain_field`] for a value the selected objects may not share: `None` shows a blank field. @@ -385,7 +385,7 @@ pub fn mixed_field_named( width: f32, ) -> Option { let label = take_previous_label(ui); - bounded_field(ui, id, label, name, value, suffix, decimals, width, &ANY, None) + bounded_field(ui, id, label, name, value, suffix, decimals, width, &ANY, None, false) } /// [`mixed_field`] whose ↑/↓, wheel and scrub stop at `bounds`; ↑/↓ and the wheel take `step`'s steps @@ -403,6 +403,7 @@ fn bounded_field( width: f32, bounds: &RangeInclusive, step: Option f64>, + parentheses: bool, ) -> Option { let armed = take_armed_focus(ui, &id); let id = id_with(ui.scope_id(), id); @@ -412,9 +413,9 @@ fn bounded_field( let suffix = suffix.trim(); let buf = decimal_point(buf); let bare = if suffix.is_empty() { buf.to_string() } else { buf.replace(suffix, "") }; - vectorcraft_doc::parse_number(&bare.replace(['%', '°'], "")) + vectorcraft_doc::parse_number(&bare.replace(['%', '°', '(', ')'], "")) }; - let shown = value.map(show).unwrap_or_default(); + let shown = value.map(|v| if parentheses { format!("({})", show(v)) } else { show(v) }).unwrap_or_default(); take_dialog_focus(ui, id, &shown); if armed { focus_field(ui, id, &shown); @@ -508,7 +509,7 @@ pub fn spin_field_stops_named( presets: &[f64], ) -> Option { let label = take_previous_label(ui); - spin_generic(ui, label, value, None, width, step, min, presets, presets, &|v| unit.format(v), &mut |ui, fw, label| { + spin_generic(ui, label, value, None, None, None, width, step, min, presets, presets, &|v| unit.format(v), &mut |ui, fw, label| { unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, presets) }) .and_then(SpinPick::value) @@ -519,6 +520,7 @@ pub fn spin_field_stops_named( pub enum SpinPick { Value(f64), Auto, + Optical, } impl SpinPick { @@ -527,6 +529,7 @@ impl SpinPick { match self { SpinPick::Value(v) => Some(v), SpinPick::Auto => None, + SpinPick::Optical => None, } } } @@ -563,7 +566,7 @@ pub fn spin_field_auto_named( presets: &[f64], ) -> Option { let label = take_previous_label(ui); - spin_generic(ui, label, value, auto, width, step, min, presets, &[], &|v| unit.format(v), &mut |ui, fw, label| { + spin_generic(ui, label, value, auto, None, None, width, step, min, presets, &[], &|v| unit.format(v), &mut |ui, fw, label| { unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, &[]) }) } @@ -602,12 +605,43 @@ pub fn spin_plain_named( let label = take_previous_label(ui); let value = value.into(); let fmt = |v: f64| format!("{v}{suffix}"); - spin_generic(ui, label, value, None, width, step, min, presets, &[], &fmt, &mut |ui, fw, label| { - bounded_field(ui, id, label, name, value, suffix, decimals, fw, &(min..=f64::INFINITY), None) + spin_generic(ui, label, value, None, None, None, width, step, min, presets, &[], &fmt, &mut |ui, fw, label| { + bounded_field(ui, id, label, name, value, suffix, decimals, fw, &(min..=f64::INFINITY), None, false) }) .and_then(SpinPick::value) } +/// Kerning's numeric field and automatic method choices. +#[allow(clippy::too_many_arguments)] +pub fn spin_kerning( + ui: &mut Ui, + id: impl std::hash::Hash + Copy, + value: Option, + automatic: Option, + optical: Option, + optical_label: &str, + parentheses: bool, + width: f32, + presets: &[f64], +) -> Option { + let label = take_previous_label(ui); + spin_generic( + ui, + label, + value, + automatic, + optical, + Some(optical_label), + width, + 10.0, + -1000.0, + presets, + &[], + &|v| format!("{v}"), + &mut |ui, fw, label| bounded_field(ui, id, label, None, value, "", 0, fw, &(-1000.0..=f64::INFINITY), None, parentheses), + ) +} + type SpinField<'a> = dyn FnMut(&mut Ui, f32, Option) -> Option + 'a; #[allow(clippy::too_many_arguments)] @@ -616,6 +650,8 @@ fn spin_generic( label: Option, value: Option, auto: Option, + optical: Option, + optical_label: Option<&str>, width: f32, step: f64, min: f64, @@ -674,6 +710,11 @@ fn spin_generic( { out = Some(SpinPick::Auto); } + if let Some(on) = optical + && ui.selectable_label(on, optical_label.unwrap_or_default()).clicked() + { + out = Some(SpinPick::Optical); + } let current = value.filter(|_| auto != Some(true)); for p in presets { if ui.selectable_label(current.is_some_and(|v| (v - p).abs() < 1e-6), fmt(*p)).clicked() { diff --git a/docs/mcp.md b/docs/mcp.md index 0595340df1..129d7346c3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3217,7 +3217,8 @@ Pen's second anchor at (150, 431), in line with the square's centre. leading (↑/↓ in horizontal type, ←/→ in vertical type), and baseline shift (Shift+↑/↓ in horizontal type, Shift+→/← in vertical type). Mixed selected text objects use the horizontal mapping; Cmd/Ctrl makes five steps. `type.resetTracking` (Cmd+Alt+Q, `press_key {key: "Q", mods: {cmd: true, alt: true}}`) sets tracking to 0 and - kerning to Auto in the type objects in `ids`, the Type tool's selected text or the selected type objects; at a caret + clears manual kerning in the type objects in `ids`, the Type tool's selected text or the selected type objects, + keeping Optical; at a caret it resets only the kerning of the character before it. `type.resetHorizontalScale` (Cmd+Shift+X, `press_key {key: "X", mods: {cmd: true, shift: true}}`) sets the horizontal scale to 100%, as the Character panel shows it, in the same text; at a caret it leaves the text as it is. In the app, `type.highlightKerning` (Cmd+Alt+K), @@ -4918,6 +4919,16 @@ the paragraph's text now starts; when the text before `at` starts no list, nothi {"name":"run_command","arguments":{"command":"text.convertListToText","params":{}}} ``` +## Kerning + +`text.setRangeStyle {id, start, end, kerning}` (a range) and `text.setFormat {ids?, kerning}` +(the selected type) accept `kerning: "auto" | "optical" | number` (1/1000 em). Auto uses the font's +pair metrics; Optical spaces horizontal pairs from their glyph shapes. Vertical text uses font +metrics in either mode. A number sets a manual pair value, +replacing that pair's automatic correction while tracking remains additive. Choosing Optical keeps +existing manual pair values; choosing `"auto"` clears them. New text and files without an Optical setting use Auto. The Character +panel offers both automatic modes. + ## Small Caps, Superscript and Subscript `text.setFormat {smallCaps, position}` (the selected type, or `ids`) and `text.setRangeStyle {id, start, end, smallCaps, position}` (a range) set what the Character panel's Small Caps, Superscript and Subscript buttons and menu items set. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3d706ba6bb..e6645bbbce 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -633,7 +633,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With the Artboard tool, Cmd/Ctrl+A after a click on a row of the Artboards panel selects every artboard, as the macOS menu bar's Select All does then; the active artboard stays active, and the art's selection does not change. After a press outside the panel's list, Cmd/Ctrl+A selects every object again. It used to select every object after a click in the panel too. Public reference: [Select artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/select-artboards.html). - Cmd/Ctrl+/ (`appearance.addFill`) and Cmd/Ctrl+Alt+/ (`appearance.addStroke`) add a new fill and a new stroke to the selected objects, as the Appearance panel's Add New Fill and Add New Stroke buttons do, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for adding a new fill and a new stroke. Keyboard Shortcuts lists both under Window › Appearance. - Cmd/Ctrl+Alt+Shift+. and , (`type.size.increaseByFive`, `type.size.decreaseByFive`) step the font size of the selected type, or of the text the Type tool has selected, by five times the Size/Leading increment (Preferences › Type); Cmd/Ctrl+Shift+. and , still step it by one increment. - - Cmd/Ctrl+Alt+Q (`type.resetTracking`) sets the tracking of the selected type, or of the text the Type tool has selected, to 0 and its kerning to Auto (0 in the Character panel), in one undo step; at a caret it resets the kerning of the character before it. + - Cmd/Ctrl+Alt+Q (`type.resetTracking`) sets the tracking of the selected type, or of the text the Type tool has selected, to 0 and clears manual kerning while keeping the automatic method, in one undo step; at a caret it resets only the kerning of the character before it. - Cmd/Ctrl+Alt+K (`type.highlightKerning`) and Cmd/Ctrl+Alt+Shift+F (`type.highlightFontName`) show the Character panel and give its Kerning field the keyboard focus with the value selected, or open its font family menu with the search field focused, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for highlighting kerning and the font name field. The page lists the same key for selecting the tracking value; `type.highlightTracking` focuses the Tracking field the same way and has no default key in Keyboard Shortcuts. - Cmd/Ctrl+Alt+L (`ui.newLayer`) opens Layer Options for a new layer, as an Alt-click on the Layers panel's New Layer button does, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for adding a layer through the New Layer dialog box. OK adds the layer above the current layer, and Cancel adds none. Cmd/Ctrl+L still adds a layer without the dialog. - F8 (`ui.symbolOptions`) opens Symbol Options for a new symbol made from the selection, as the Symbols panel's New Symbol button does, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for making a new symbol. OK makes the symbol and puts an instance of it in place of the art, and Cancel makes none. With nothing selected, F8 opens no dialog, and the status bar says that nothing is selected. Shift+F8 and Cmd/Ctrl+F8 still show the Transform and Info panels. @@ -840,6 +840,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Vertical type spacing shortcuts:** The [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page gives Alt+Down/Up for kerning at a caret or tracking of selected text, Alt+Left/Right for leading, and Alt+Shift+Right/Left for baseline shift. Alt+Shift+Down/Up also steps kerning or tracking. Down increases kerning or tracking, Left increases leading, and Shift+Right increases baseline shift; the opposite arrows decrease them. Cmd/Ctrl makes five steps. Horizontal type keeps its existing mapping; mixed horizontal and vertical text-object selections take the horizontal mapping for both objects in one undo step. Selected vertical point, area and path type use the same directions. Tests: `spacing_arrows_follow_each_text_objects_orientation`, `alt_arrows_rotate_for_selected_vertical_type`, `mixed_type_objects_take_horizontal_spacing_chords_in_both_orders`, and `selected_vertical_area_and_path_type_use_vertical_spacing_chords`. - **Vertical punctuation:** fullwidth `!` (U+FF01) and `?` (U+FF1F) use their nominal glyph upright when no vertical alternate is present, following the Tu fallback in [Unicode UAX #50 §3.1](https://www.unicode.org/reports/tr50/#vo). Code-built test fonts cover point and area type with and without `vert` alternates, retain the rotated fallback for a bracket and long vowel mark, and leave horizontal type unchanged. Tests: `crates/text/src/tests/vertical.rs`. - Free Distort's dialog (Effect › Distort & Transform › Free Distort…) shows a box in the proportions of the first selected object's bounds with a handle on each corner. Dragging a handle moves that corner. A handle focused by a click or Tab moves 1% of the box with each arrow key, and 10% with Shift. Reset puts the four corners back on the box. The preview and OK run `effect.apply`, or `effect.setParams` when the dialog edits an applied effect, and the Appearance panel's inline editor opens the dialog with Edit…. Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 285 (PDF page 291). +- **Optical kerning:** Character and Properties offer Optical beside Auto for automatic pair spacing. The side-profile spacing method is VectorCraft's own. Optical keeps its mode across cosmetic style runs, and leaves manual pair values and additive tracking intact. Native documents retain the mode and pair overrides; old documents use Auto. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/engine/src/tests/textedit.rs`. - **Kerning across style runs:** characters that differ only in fill, stroke, underline, strikethrough, overprint, character style name, leading, baseline shift, rotation, Character Alignment, kerning, or tracking that keeps or drops ligatures alike are shaped together, so restyling one character keeps the font's kerning pairs with its neighbors. A character with manual kerning that follows one with automatic kerning keeps the font's kerning with it (unless All Caps or Small Caps sets it as two letters, as ß becomes SS), and its value replaces the font's kerning after it. A ligature does not form across a change of style, and a change of font, size or OpenType features still shapes the characters apart. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/text/src/tests/bidi.rs`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). diff --git a/docs/typography-lettering.md b/docs/typography-lettering.md index 373f92b964..588a91e77d 100644 --- a/docs/typography-lettering.md +++ b/docs/typography-lettering.md @@ -24,7 +24,7 @@ can use installed system fonts, while the web app uses the fonts supplied by its 6. Adjust **Font Size** (the field beside **T**) and **Tracking** (beside **VA↔**) in the Character panel. Hover a field's label to see its name. For example, enter `72 pt` for a large heading and try tracking `50` to spread its letters slightly. Positive tracking adds space; negative tracking - tightens it. **Leading** controls the spacing between lines; **Kerning (0 = Auto)** adjusts pairs. + tightens it. **Leading** controls the spacing between lines; **Kerning** adjusts pairs. 7. To change only part of the text, select **Type Tool**, click into the text and drag across the characters before using the Character panel. Press **Escape** when finished. Keep the text editable until its wording, font and spacing are settled. From 14100bfab2847625eb1d7280f8e97925fbcdf719 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 00:39:34 +0700 Subject: [PATCH 32/70] Character Styles: Style Options edits the name and Basic Character Formats Squashed from #4809 onto main. --- crates/engine/src/cmd/textstyles.rs | 157 ++++- crates/engine/src/cmd/textstyles/tests.rs | 239 +++++++- crates/ui-egui/src/dialogs.rs | 2 + .../ui-egui/src/dialogs/char_style_options.rs | 548 ++++++++++++++++++ crates/ui-egui/src/dialogs/new_text_style.rs | 53 +- crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + crates/ui-egui/src/menus/run.rs | 5 + crates/ui-egui/src/menus/state.rs | 6 +- crates/ui-egui/src/menus/ui_commands.rs | 12 + crates/ui-egui/src/panels/text_styles.rs | 8 +- .../ui-egui/src/panels/text_styles/tests.rs | 50 ++ docs/mcp.md | 16 + docs/target-app-parity.md | 3 +- 33 files changed, 1188 insertions(+), 37 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/char_style_options.rs diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index c1312fa9ba..30ccbfc7b7 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -8,7 +8,7 @@ use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{CharStyle, Document, NodeId, NodeKind, ParaStyle, TextStyleDef}; +use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TextStyleDef}; use super::typecmd::{refresh_bounds, text_targets}; use super::{CommandSpec, Result, Run, Session, bad, bool_or, has_doc, id_param, index, ok, str_param}; @@ -117,6 +117,14 @@ macro_rules! style_cmds { pub fn specs() -> Vec { let mut v = style_cmds!(Kind::Char, "charStyle", "Character Styles", "Character"); + v.push(spec( + "charStyle.edit", + "Edit Character Style", + &[], + "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides", + |s, p| edit_style(s, p, Kind::Char), + true, + )); v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph")); v } @@ -245,14 +253,16 @@ fn with_attrs(base: &T, attrs: &Map( cur: &T, attrs: fn(&T) -> Map, old: &Map, new: &Map, + base: &Map, ) -> T { let Some(full) = to_map(cur) else { return cur.clone() }; let mut m = attrs(cur); @@ -264,6 +274,14 @@ fn restyle( m.insert(k.clone(), v.clone()); } } + for (k, v) in old { + if !new.contains_key(k) + && m.get(k) == Some(v) + && let Some(base_value) = base.get(k) + { + m.insert(k.clone(), base_value.clone()); + } + } serde_json::from_value(Value::Object(m)).unwrap_or_else(|_| cur.clone()) } @@ -282,15 +300,47 @@ fn font_change(before: &CharStyle, mut st: CharStyle, attrs: &Map st } -/// Every text object id in the document. -fn all_text(d: &Document) -> Vec { - let mut v = vec![]; - d.walk(|n| { - if matches!(n.kind, NodeKind::Text(_)) { - v.push(n.id) +/// Change text in layers, symbols, graph designs, pattern tiles, saved pattern tiles restored by +/// Cancel, and brush art, including opacity masks in those trees. +fn each_text_mut(d: &mut Document, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> { + fn has_text(n: &Node) -> bool { + matches!(n.kind, NodeKind::Text(_)) + || n.extras().mask.as_ref().is_some_and(|mask| has_text(&mask.art)) + || n.children().is_some_and(|children| children.iter().any(|child| has_text(child))) + } + + fn visit(n: &mut Node, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> { + if let NodeKind::Text(t) = &mut n.kind { + f(t)?; } - }); - v + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && has_text(&mask.art) + { + visit(std::sync::Arc::make_mut(&mut mask.art), f)?; + } + for child in n.children_mut().into_iter().flatten() { + if has_text(child) { + visit(std::sync::Arc::make_mut(child), f)?; + } + } + Ok(()) + } + let trees = d.layers.iter_mut().chain(d.symbols.iter_mut().map(|s| &mut s.art)).chain(d.graph_designs.iter_mut().map(|g| &mut g.art)); + let patterns = d.patterns.iter_mut().chain(d.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())); + for root in trees.chain(patterns.flat_map(|p| &mut p.art)) { + if has_text(root) { + visit(std::sync::Arc::make_mut(root), f)?; + } + } + let mut brushes = vectorcraft_brush::library(d); + let original_brushes = brushes.clone(); + for art in brushes.iter_mut().flat_map(|b| b.art_mut()) { + visit(art, f)?; + } + if brushes != original_brushes { + vectorcraft_brush::store(d, &brushes); + } + Ok(()) } fn text_mut(d: &mut Document, id: NodeId) -> Option<&mut vectorcraft_doc::TextObject> { @@ -328,16 +378,20 @@ fn uses_of(uses: &std::collections::HashMap, usize>, kind: Kind, } /// Update every user of `name` from `old` to `new` attributes (overrides kept). -fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map, new: &Map) { +fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map, new: &Map) -> Result<()> { let target = (name != kind.normal()).then_some(name.to_string()); - for id in all_text(d) { - let Some(t) = text_mut(d, id) else { continue }; + let normal = kind.attrs(d, kind.normal()).unwrap_or_default(); + let base = match kind { + Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), &normal, &kind.cmd("edit"))?), + Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), &normal, &kind.cmd("edit"))?), + }; + each_text_mut(d, &mut |t| { let mut changed = false; match kind { Kind::Char => { for r in &mut t.runs { if r.style.style_name == target { - r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new), new); + r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new); changed = true; } } @@ -345,7 +399,7 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map { for pa in t.para_styles_mut() { if pa.style_name == target { - *pa = restyle(pa, para_attrs, old, new); + *pa = restyle(pa, para_attrs, old, new, &base); changed = true; } } @@ -354,7 +408,8 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map Option Map { + new_style_attrs(s, if para { Kind::Para } else { Kind::Char }) +} + /// Whether the document has a character (`para`: paragraph) style `name`, and its attributes. pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option> { if para { Kind::Para } else { Kind::Char }.attrs(d, name) @@ -567,13 +627,16 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { fn redefine_to(s: &mut Session, kind: Kind, name: &str, new_attrs: Map, verb: &str) -> Result { let d = &s.doc()?.doc; let old = kind.attrs(d, name).ok_or_else(|| bad(&kind.cmd(verb), format!("no style `{name}`")))?; + if new_attrs == old { + return ok(); + } let name = name.to_string(); s.edit_named("Redefine {name}", &name, name == kind.normal(), |d, _| { match kind.defs_mut(d).iter_mut().find(|s| s.name == name) { Some(def) => def.attrs = new_attrs.clone(), None => kind.defs_mut(d).push(TextStyleDef { name: name.clone(), attrs: new_attrs.clone() }), } - update_users(d, kind, &name, &old, &new_attrs); + update_users(d, kind, &name, &old, &new_attrs)?; Ok(()) })?; ok() @@ -591,6 +654,50 @@ fn set_attrs(s: &mut Session, p: &Value, kind: Kind) -> Result { redefine_to(s, kind, &name, attrs, "setAttrs") } +fn edit_style(s: &mut Session, p: &Value, kind: Kind) -> Result { + let c = kind.cmd("edit"); + let name = name_param(p, kind, "edit")?.to_string(); + let to = str_param(p, "to").ok_or_else(|| bad(&c, "missing `to`"))?.trim().to_string(); + let attrs = attrs_param(p, kind, "edit")?.ok_or_else(|| bad(&c, "missing `attrs`"))?; + let d = &s.doc()?.doc; + let old = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?; + if name == kind.normal() { + return Err(bad(&c, format!("`{name}` can't be edited this way"))); + } + if to.is_empty() { + return Err(bad(&c, "give the style a name")); + } + if to != name && kind.attrs(d, &to).is_some() { + return Err(bad(&c, format!("a style named `{to}` already exists"))); + } + if to == name && attrs == old { + return ok(); + } + s.edit(if kind == Kind::Char { "Character Style Options" } else { "Paragraph Style Options" }, |d, _| { + if let Some(def) = kind.defs_mut(d).iter_mut().find(|def| def.name == name) { + def.name = to.clone(); + def.attrs = attrs.clone(); + } + update_users(d, kind, &name, &old, &attrs)?; + if to != name { + each_text_mut(d, &mut |t| { + let fix = |style_name: &mut Option| { + if style_name.as_deref() == Some(name.as_str()) { + *style_name = Some(to.clone()); + } + }; + match kind { + Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)), + Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)), + } + Ok(()) + })?; + } + Ok(()) + })?; + ok() +} + fn duplicate(s: &mut Session, p: &Value, kind: Kind) -> Result { let name = name_param(p, kind, "duplicate")?.to_string(); let d = &s.doc()?.doc; @@ -619,8 +726,7 @@ fn rename(s: &mut Session, p: &Value, kind: Kind) -> Result { if let Some(def) = kind.defs_mut(d).iter_mut().find(|s| s.name == name) { def.name = to.clone(); } - for id in all_text(d) { - let Some(t) = text_mut(d, id) else { continue }; + each_text_mut(d, &mut |t| { let fix = |n: &mut Option| { if n.as_deref() == Some(name.as_str()) { *n = Some(to.clone()); @@ -630,7 +736,8 @@ fn rename(s: &mut Session, p: &Value, kind: Kind) -> Result { Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)), Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)), } - } + Ok(()) + })?; Ok(()) })?; ok() @@ -654,8 +761,7 @@ fn delete(s: &mut Session, p: &Value, kind: Kind) -> Result { } s.edit(if names.len() > 1 { "Delete Styles" } else { "Delete Style" }, |d, _| { kind.defs_mut(d).retain(|s| !names.contains(&s.name)); - for id in all_text(d) { - let Some(t) = text_mut(d, id) else { continue }; + each_text_mut(d, &mut |t| { let fix = |n: &mut Option| { if n.as_ref().is_some_and(|n| names.contains(n)) { *n = None; @@ -665,7 +771,8 @@ fn delete(s: &mut Session, p: &Value, kind: Kind) -> Result { Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)), Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)), } - } + Ok(()) + })?; Ok(()) })?; ok() diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 670e3bbb7a..46b52346de 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -15,6 +15,233 @@ fn runs(s: &Session, id: u64) -> Vec { } } +fn embedded_style(s: &Session, container: &str) -> (Option, f64, Option) { + let d = &s.doc().unwrap().doc; + let brushes = vectorcraft_brush::library(d); + let roots: Vec<&Node> = match container { + "symbol" => d.symbols.iter().map(|s| &*s.art).collect(), + "pattern" => d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a)).collect(), + "graph" => d.graph_designs.iter().map(|g| &*g.art).collect(), + "brush" => brushes.iter().flat_map(|b| b.art()).collect(), + _ => panic!("unknown container"), + }; + let mut found = None; + for root in roots { + vectorcraft_doc::swatches::walk_with_masks(root, &mut |n| { + if let NodeKind::Text(t) = &n.kind { + found = Some((t.runs[0].style.style_name.clone(), t.runs[0].style.size, t.para.style_name.clone())); + } + }); + } + found.unwrap() +} + +fn embedded_style_session(kind: &str, container: &str) -> Session { + let (mut s, id) = session_with_text("Styled"); + s.execute(&format!("{kind}Style.new"), &json!({"name": "Body", "attrs": if kind == "char" { json!({"size": 24}) } else { json!({}) }})).unwrap(); + s.execute(&format!("{kind}Style.apply"), &json!({"name": "Body", "id": id})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + match container { + "symbol" => { + let symbol = s.execute("symbol.new", &json!({"name": "Mark"})).unwrap(); + s.execute("edit.clear", &json!({"ids": [symbol["id"]]})).unwrap(); + } + "pattern" => { + s.execute("object.pattern.make", &json!({"edit": false})).unwrap(); + if s.doc().unwrap().doc.node(NodeId(id)).is_some() { + s.execute("edit.clear", &json!({"ids": [id]})).unwrap(); + } + } + "graph" => { + s.execute("graph.design", &json!({"new": "Bar"})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id]})).unwrap(); + } + "brush" => { + s.execute("brush.new", &json!({"type": "art", "name": "Lettering"})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id]})).unwrap(); + } + _ => panic!("unknown container"), + } + s +} + +#[test] +fn character_style_options_update_embedded_art() { + for container in ["symbol", "pattern", "graph", "brush"] { + let mut s = embedded_style_session("char", container); + assert_eq!(embedded_style(&s, container).0.as_deref(), Some("Body"), "{container}"); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Heading", "attrs": {"size": 18}})).unwrap(); + assert_eq!(embedded_style(&s, container).0.as_deref(), Some("Heading"), "{container}"); + assert_eq!(embedded_style(&s, container).1, 18.0, "{container}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{container}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before, "{container}"); + s.execute("edit.redo", &json!({})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("charStyle.delete", &json!({"name": "Heading"})).unwrap(); + assert_eq!(embedded_style(&s, container).0, None, "{container}"); + assert_eq!(embedded_style(&s, container).1, 18.0, "{container}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{container}"); + } +} + +#[test] +fn character_style_edit_survives_canceling_pattern_edit() { + let mut s = embedded_style_session("char", "pattern"); + let name = s.doc().unwrap().doc.patterns[0].name.clone(); + s.execute("object.pattern.edit", &json!({"name": name})).unwrap(); + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Heading", "attrs": {"size": 18}})).unwrap(); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + + assert_eq!(embedded_style(&s, "pattern").0.as_deref(), Some("Heading")); + assert_eq!(embedded_style(&s, "pattern").1, 18.0); +} + +#[test] +fn paragraph_style_rename_updates_symbol_art() { + let mut s = embedded_style_session("para", "symbol"); + assert_eq!(embedded_style(&s, "symbol").2.as_deref(), Some("Body")); + s.execute("paraStyle.rename", &json!({"name": "Body", "to": "Heading"})).unwrap(); + assert_eq!(embedded_style(&s, "symbol").2.as_deref(), Some("Heading")); +} + +#[test] +fn character_style_options_keep_text_free_layer_shared() { + let (mut s, id) = session_with_text("Styled"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + let empty_id = s.execute("layer.new", &json!({"name": "Empty"})).unwrap()["id"].as_u64().unwrap(); + let before = s.doc().unwrap().doc.layers.iter().find(|layer| layer.id == NodeId(empty_id)).unwrap().clone(); + + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Heading", "attrs": {"size": 18}})).unwrap(); + + let d = &s.doc().unwrap().doc; + let after = d.layers.iter().find(|layer| layer.id == NodeId(empty_id)).unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, after)); + assert_eq!(runs(&s, id)[0].style.style_name.as_deref(), Some("Heading")); + assert_eq!(runs(&s, id)[0].style.size, 18.0); +} + +#[test] +fn unchanged_style_options_keep_undo_and_redo_with_and_without_preview() { + for preview in [false, true] { + let (mut s, _) = session_with_text("Text"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 18, "leading": null}})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Other", "attrs": {}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let redo = s.doc().unwrap().history.redo.len(); + assert!(redo > 0); + let params = json!({"name": "Body", "to": " Body ", "attrs": {"size": 18.0, "leading": null}}); + if preview { + s.begin_interaction("Character Style Options").unwrap(); + s.preview("charStyle.edit", ¶ms).unwrap(); + s.commit_interaction().unwrap(); + } else { + s.execute("charStyle.edit", ¶ms).unwrap(); + } + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "preview={preview}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "preview={preview}"); + assert_eq!(s.doc().unwrap().history.redo.len(), redo, "preview={preview}"); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.char_styles.iter().any(|style| style.name == "Other")); + } +} + +#[test] +fn unchanged_style_attributes_keep_undo_and_redo_for_both_kinds() { + for (command, para) in [("charStyle", false), ("paraStyle", true)] { + let (mut s, _) = session_with_text("Text"); + let attrs = if para { json!({"space_before": 18}) } else { json!({"size": 18}) }; + s.execute(&format!("{command}.new"), &json!({"name": "Body", "attrs": attrs})).unwrap(); + s.execute(&format!("{command}.new"), &json!({"name": "Other", "attrs": {}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let redo = s.doc().unwrap().history.redo.len(); + assert!(redo > 0); + let attrs = if para { json!({"space_before": 18.0}) } else { json!({"size": 18.0}) }; + s.execute(&format!("{command}.setAttrs"), &json!({"name": "Body", "attrs": attrs})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{command}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{command}"); + assert_eq!(s.doc().unwrap().history.redo.len(), redo, "{command}"); + } +} + +#[test] +fn character_style_options_edit_applies_to_users_and_is_one_saved_undo_step() { + let (mut s, id) = session_with_text("First second"); + s.execute("charStyle.new", &json!({"name":"Body", "attrs":{"size":24.0,"tracking":20.0,"baseline_shift":3.0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name":"Body", "id":id, "start":0, "end":5})).unwrap(); + s.execute("charStyle.apply", &json!({"name":"Body", "id":id, "start":6, "end":12})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id":id,"start":6,"end":12,"size":31.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("charStyle.edit", &json!({"name":"Body","to":"Text","attrs":{"size":18.0,"tracking":40.0,"baseline_shift":3.0}})).unwrap(); + let changed = s.doc().unwrap().doc.clone(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!( + runs(&s, id).iter().map(|r| (r.style.style_name.as_deref(), r.style.size, r.style.tracking)).collect::>(), + [(Some("Text"), 18.0, 40.0), (None, 12.0, 0.0), (Some("Text"), 31.0, 40.0)] + ); + let future = s.execute("text.create", &json!({"x":20,"y":90,"text":""})).unwrap()["id"].as_u64().unwrap(); + s.execute("charStyle.apply", &json!({"name":"Text","id":future})).unwrap(); + s.execute("text.editRange", &json!({"id":future,"start":0,"end":0,"insert":"Later"})).unwrap(); + assert_eq!((runs(&s, future)[0].style.size, runs(&s, future)[0].style.tracking), (18.0, 40.0)); + let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!( + saved.char_styles.iter().find(|d| d.name == "Text").unwrap().attrs, + s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Text").unwrap().attrs + ); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, changed); +} + +#[test] +fn editing_character_style_clears_removed_size_without_losing_local_override() { + let (mut s, id) = session_with_text("One two"); + s.execute("charStyle.setAttrs", &json!({"name": NORMAL_CHAR, "attrs": {"size": 15.0}})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 7, "size": 31.0})).unwrap(); + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {}})).unwrap(); + let r = runs(&s, id); + assert_eq!((r[0].style.size, r[1].style.size), (15.0, 31.0)); +} + +#[test] +fn replacing_character_style_attrs_clears_removed_size() { + let (mut s, id) = session_with_text("Text"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {}})).unwrap(); + assert_eq!(runs(&s, id)[0].style.size, 12.0); +} + +#[test] +fn character_style_options_edit_validates_names_and_allows_case_changes() { + let (mut s, _) = session_with_text("Text"); + s.execute("charStyle.new", &json!({"name":"Body","attrs":{"size":24.0}})).unwrap(); + s.execute("charStyle.new", &json!({"name":"Other","attrs":{}})).unwrap(); + for (name, to, message) in + [(super::NORMAL_CHAR, "New", "can't be edited this way"), ("Body", " ", "give the style a name"), ("Body", "Other", "already exists")] + { + let error = s.execute("charStyle.edit", &json!({"name":name,"to":to,"attrs":{}})).unwrap_err().to_string(); + assert!(error.contains(message), "{error}"); + } + s.execute("charStyle.edit", &json!({"name":"Body","to":"body","attrs":{"size":18.0}})).unwrap(); + s.execute("charStyle.edit", &json!({"name":"body","to":" body ","attrs":{"size":20.0}})).unwrap(); + assert_eq!(s.doc().unwrap().doc.char_styles.iter().find(|style| style.name == "body").unwrap().attrs["size"], json!(20.0)); +} + #[test] fn char_style_new_apply_range_redefine_keeps_overrides() { let (mut s, id) = session_with_text("Hello world"); @@ -293,10 +520,10 @@ fn auto_leading_redefine_keeps_overrides_and_history() { s.execute("text.setStyle", &json!({"ids": [linked], "leading": "auto"})).unwrap(); s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"leading": 28}})).unwrap(); assert_eq!(ids.map(|id| runs(&s, id)[0].style.leading), [Some(28.0), None, Some(42.0)]); - // Omitting leading replaces the definition without resetting the text's leading. + // Omitting leading returns linked text to Auto and keeps local overrides. s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"tracking": 20}})).unwrap(); assert!(!s.doc().unwrap().doc.char_styles[0].attrs.contains_key("leading")); - assert_eq!(ids.map(|id| runs(&s, id)[0].style.leading), [Some(28.0), None, Some(42.0)]); + assert_eq!(ids.map(|id| runs(&s, id)[0].style.leading), [None, None, Some(42.0)]); } } @@ -308,7 +535,7 @@ fn settable() -> std::collections::BTreeSet { /// New and Redefine capture every paragraph attribute. A paragraph style redefined from a /// paragraph at the defaults gives its paragraphs the defaults back where they had the old /// definition's values, and `setAttrs` with a default value does too; local overrides, and -/// attributes `setAttrs` leaves out, stay. +/// attributes `setAttrs` leaves out return to the base value. #[test] fn para_style_redefined_to_the_defaults_updates_its_paragraphs() { use vectorcraft_doc::{Composer, HyphenationOptions}; @@ -335,11 +562,11 @@ fn para_style_redefined_to_the_defaults_updates_its_paragraphs() { assert_eq!(defined(&s, 0), settable::(), "Redefine captures every attribute"); s.execute("paraStyle.new", &json!({"name": "Copy", "id": local})).unwrap(); assert_eq!(defined(&s, 1), settable::(), "New captures every attribute"); - // Style options: a default value reaches the users too; an attribute left out stays as it is. + // Style options: a default value reaches users, and an attribute left out returns to base. s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"hyphenation": {"hyphen_limit": 3}, "composer": "singleLine"}})).unwrap(); assert_eq!((limits(&s), composers(&s)), ([3, 3, 4], [Composer::SingleLine; 3])); s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"composer": "everyLine"}})).unwrap(); - assert_eq!((limits(&s), composers(&s)), ([3, 3, 4], [Composer::EveryLine; 3])); + assert_eq!((limits(&s), composers(&s)), ([0, 0, 4], [Composer::EveryLine; 3])); assert_eq!(Value::Object(s.doc().unwrap().doc.para_styles[0].attrs.clone()), json!({"composer": "everyLine"})); } @@ -368,7 +595,7 @@ fn char_style_redefined_to_the_defaults_updates_its_text() { s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"kerning": 10, "charAlign": "emBoxTop"}})).unwrap(); assert_eq!((kerning(&s), aligns(&s)), ([Some(10.0), Some(10.0), Some(60.0)], [CharAlign::EmBoxTop; 3])); s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"charAlign": "romanBaseline"}})).unwrap(); - assert_eq!((kerning(&s), aligns(&s)), ([Some(10.0), Some(10.0), Some(60.0)], [CharAlign::RomanBaseline; 3])); + assert_eq!((kerning(&s), aligns(&s)), ([None, None, Some(60.0)], [CharAlign::RomanBaseline; 3])); assert_eq!(Value::Object(s.doc().unwrap().doc.char_styles[0].attrs.clone()), json!({"charAlign": "romanBaseline"})); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index b2a42af49b..a4eac70418 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -14,6 +14,7 @@ pub mod blend_options; mod brush_art_options; pub mod brush_delete; pub mod brush_options; +pub mod char_style_options; pub mod color_balance; pub mod color_guide_options; mod color_picker; @@ -306,6 +307,7 @@ registry! { GradientStop: ["gradientStop"] => gradient_stop::SPEC, ColorPicker: [color_picker::KIND] => color_picker::SPEC, GraphicStyleOptions: [graphic_style_options::KIND] => graphic_style_options::SPEC, + CharStyleOptions: [char_style_options::KIND] => char_style_options::SPEC, NewTextStyle: [new_text_style::KIND] => new_text_style::SPEC, EffectExists: [effect::EXISTS] => effect::EXISTS_SPEC, ColorGuideOptions: [color_guide_options::KIND] => color_guide_options::SPEC, diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs new file mode 100644 index 0000000000..848151ac54 --- /dev/null +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -0,0 +1,548 @@ +//! Character Style Options fields shared by editing and creating a character style. + +use serde_json::{Map, Value, json}; + +use super::{DialogSpec, form}; +use crate::VectorcraftApp; +use crate::state::Dialog; + +pub const KIND: &str = "charStyleOptions"; +const BASIC: &[&str] = &[ + "font_family", + "font_style", + "size", + "leading", + "kerning", + "tracking", + "all_caps", + "small_caps", + "position", + "underline", + "strikethrough", + "charAlign", +]; +const NUMBERS: &[&str] = &["size", "leading", "kerning", "tracking"]; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Character Style Options").into(), + body, + confirm, + preview: true, + inputs: |_| { + &[ + "name", + "font_family", + "font_style", + "size", + "leading", + "kerning", + "tracking", + "case", + "position", + "underline", + "strikethrough", + "charAlign", + "section", + ] + }, + min_width: 650.0, + ..DialogSpec::FORM +}; + +pub fn open(app: &mut VectorcraftApp, name: &str) -> Result { + crate::panels::character::end_typing(app); + let doc = &app.session.active().ok_or("no document open")?.doc; + let def = doc.char_styles.iter().find(|s| s.name == name).ok_or_else(|| format!("no character style `{name}`"))?; + let mut fields = fields_from_attrs(&def.attrs); + fields.insert("name".into(), json!(name)); + fields.insert("__style".into(), json!(name)); + fields.insert("__attrs".into(), json!(def.attrs)); + fields.insert("__smallCapsSize".into(), json!(doc.setup.small_caps_size)); + fields.insert("__superscript".into(), json!(doc.setup.superscript)); + fields.insert("__subscript".into(), json!(doc.setup.subscript)); + fields.insert("section".into(), json!("general")); + fields.insert("preview".into(), json!(true)); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + Ok(json!({"dialog": KIND})) +} + +pub(crate) fn fields_from_attrs(attrs: &Map) -> Map { + let mut fields = Map::new(); + for key in ["font_family", "font_style", "size", "leading", "kerning", "tracking", "underline", "strikethrough", "charAlign"] { + let value = attrs.get(key).cloned().unwrap_or(Value::Null); + let shown = if ["underline", "strikethrough"].contains(&key) { + value + } else if value.is_null() { + if attrs.contains_key(key) && ["leading", "kerning"].contains(&key) { json!("Auto") } else { json!("") } + } else { + value + }; + fields.insert(key.into(), shown); + } + fields.insert("case".into(), case_from_attrs(attrs).map_or(Value::Null, Value::from)); + fields.insert("position".into(), attrs.get("position").and_then(|v| v.get("kind")).cloned().unwrap_or(Value::Null)); + fields +} + +fn case_from_attrs(attrs: &Map) -> Option<&'static str> { + if attrs.get("all_caps") == Some(&json!(true)) { + Some("allCaps") + } else if attrs.get("small_caps").is_some_and(|v| !v.is_null()) { + Some("smallCaps") + } else if attrs.contains_key("all_caps") || attrs.contains_key("small_caps") { + Some("normal") + } else { + None + } +} + +fn optional_number(d: &Dialog, key: &str) -> Result, String> { + let label = match key { + "size" => tl!("Size"), + "leading" => tl!("Leading"), + "kerning" => tl!("Kerning"), + "tracking" => tl!("Tracking"), + _ => return Err("unknown character style number field".into()), + }; + match d.fields.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) if s.trim().is_empty() => Ok(None), + Some(Value::String(s)) if s.trim().eq_ignore_ascii_case("auto") && ["leading", "kerning"].contains(&key) => Ok(Some(Value::Null)), + Some(v) => { + let n = v + .as_f64() + .or_else(|| v.as_str().and_then(|s| s.trim().parse::().ok())) + .filter(|n| n.is_finite()) + .ok_or_else(|| format!("{label} must be a number"))?; + if ["size", "leading"].contains(&key) && n < 0.1 { + return Err(format!("{label} must be a number of at least 0.1")); + } + Ok(Some(json!(n))) + } + } +} + +pub(crate) fn edited_attrs(d: &Dialog) -> Result, String> { + let original = d.fields.get("__attrs").and_then(Value::as_object).cloned().unwrap_or_default(); + let original_fields = fields_from_attrs(&original); + let reset = d.bool("__resetBasic"); + let mut attrs = original.clone(); + for key in BASIC { + attrs.remove(*key); + } + for key in ["font_family", "font_style"] { + if let Some(v) = d.fields.get(key).and_then(Value::as_str).filter(|v| !v.trim().is_empty()) { + attrs.insert(key.into(), json!(v.trim())); + } + } + if reset || ["font_family", "font_style"].iter().any(|key| d.fields.get(*key) != original_fields.get(*key)) { + attrs.remove("font_version"); + attrs.remove("fontAxes"); + } + for key in NUMBERS { + if let Some(v) = optional_number(d, key)? { + attrs.insert((*key).into(), v); + } + } + for key in ["underline", "strikethrough"] { + if let Some(v) = d.fields.get(key).and_then(Value::as_bool) { + attrs.insert(key.into(), json!(v)); + } + } + if reset || d.fields.get("case").and_then(Value::as_str) != case_from_attrs(&original) { + match d.fields.get("case").and_then(Value::as_str) { + Some("allCaps") => { + attrs.insert("all_caps".into(), json!(true)); + attrs.insert("small_caps".into(), Value::Null); + } + Some("smallCaps") => { + attrs.insert("all_caps".into(), json!(false)); + attrs.insert( + "small_caps".into(), + original + .get("small_caps") + .filter(|v| v.is_number()) + .cloned() + .unwrap_or_else(|| d.fields.get("__smallCapsSize").cloned().unwrap_or_else(|| json!(70.0))), + ); + } + Some("normal") => { + attrs.insert("all_caps".into(), json!(false)); + attrs.insert("small_caps".into(), Value::Null); + } + _ => {} + } + } + if let Some(position) = d.fields.get("position").and_then(Value::as_str).filter(|v| !v.is_empty()) { + let value = if position == "normal" { + json!({"kind": "normal"}) + } else { + original.get("position").filter(|v| v.get("kind").and_then(Value::as_str) == Some(position)).cloned().unwrap_or_else(|| { + let metrics = d.fields.get(if position == "superscript" { "__superscript" } else { "__subscript" }); + json!({"kind": position, "size": metrics.and_then(|m| m.get("size")).cloned().unwrap_or(json!(58.3)), + "position": metrics.and_then(|m| m.get("position")).cloned().unwrap_or(json!(33.3))}) + }) + }; + attrs.insert("position".into(), value); + } + if let Some(align) = d.fields.get("charAlign").and_then(Value::as_str).filter(|v| !v.is_empty()) { + attrs.insert("charAlign".into(), json!(align)); + } + if !reset { + for key in BASIC { + let field = if ["all_caps", "small_caps"].contains(key) { "case" } else { key }; + if d.fields.get(field) == original_fields.get(field) { + attrs.remove(*key); + if let Some(value) = original.get(*key) { + attrs.insert((*key).into(), value.clone()); + } + } + } + } + Ok(attrs) +} + +pub(crate) fn reset_basic(d: &mut Dialog) { + d.fields.insert("__resetBasic".into(), json!(true)); + for key in ["font_family", "font_style", "size", "leading", "kerning", "tracking", "case", "position", "underline", "strikethrough", "charAlign"] + { + d.fields.insert( + key.into(), + if ["font_family", "font_style", "size", "leading", "kerning", "tracking"].contains(&key) { json!("") } else { Value::Null }, + ); + } +} + +pub fn reset_panel(app: &mut VectorcraftApp) -> Result { + let d = app.ui.dialog.as_mut().ok_or("no dialog open")?; + let character_new = d.kind == super::new_text_style::KIND && !d.bool("__para"); + if (d.kind != KIND && !character_new) || d.str("section") != "basic" { + return Err("the open dialog has no Reset".into()); + } + reset_basic(d); + Ok(json!({"dialog": d.kind})) +} + +fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[(&str, &str)]) { + let selected = d.fields.get(key).and_then(Value::as_str).unwrap_or("").to_string(); + let shown = options.iter().find(|(value, _)| *value == selected).map_or("", |(_, label)| *label); + let labels: Vec<&str> = std::iter::once(" ").chain(options.iter().map(|(_, label)| *label)).collect(); + if let Some(i) = crate::widgets::dropdown(ui, (KIND, key), shown, &labels, 190.0) { + d.fields.insert(key.into(), if i == 0 { Value::Null } else { options.get(i - 1).map_or(Value::Null, |(value, _)| json!(value)) }); + } +} + +pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { + egui::Grid::new("character-style-basic").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + for (key, caption) in [ + ("font_family", tl!("Font Family:")), + ("font_style", tl!("Font Style:")), + ("size", tl!("Size")), + ("leading", tl!("Leading")), + ("kerning", tl!("Kerning")), + ("tracking", tl!("Tracking")), + ] { + ui.label(caption); + if d.fields.get(key).is_some_and(Value::is_null) { + d.fields.insert(key.into(), json!("")); + } + form::text(ui, d, key, 190.0); + ui.end_row(); + } + ui.label(tl!("Case")); + choice(ui, d, "case", &[("normal", tl!("Normal")), ("allCaps", tl!("All Caps")), ("smallCaps", tl!("Small Caps"))]); + ui.end_row(); + ui.label(tl!("Position")); + choice(ui, d, "position", &[("normal", tl!("Normal")), ("superscript", tl!("Superscript")), ("subscript", tl!("Subscript"))]); + ui.end_row(); + for (key, caption) in [("underline", tl!("Underline")), ("strikethrough", tl!("Strikethrough"))] { + ui.label(""); + let value = d.fields.get(key).and_then(Value::as_bool); + if crate::widgets::check3(ui, caption, value, true) { + d.fields.insert( + key.into(), + match value { + None => json!(true), + Some(true) => json!(false), + Some(false) => Value::Null, + }, + ); + } + ui.end_row(); + } + ui.label(tl!("Standard Vertical Roman Alignment")); + choice( + ui, + d, + "charAlign", + &[ + ("romanBaseline", tl!("Roman Baseline")), + ("emBoxTop", tl!("Em Box Top/Right")), + ("emBoxCenter", tl!("Em Box Center")), + ("emBoxBottom", tl!("Em Box Bottom/Left")), + ("icfTop", tl!("ICF Top/Right")), + ("icfBottom", tl!("ICF Bottom/Left")), + ], + ); + ui.end_row(); + }); +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + ui.horizontal(|ui| { + ui.vertical(|ui| { + for (id, label) in [("general", tl!("General")), ("basic", tl!("Basic Character Formats"))] { + if ui.selectable_label(d.str("section") == id, label).clicked() { + d.fields.insert("section".into(), json!(id)); + } + } + }); + ui.separator(); + ui.vertical(|ui| { + if d.str("section") == "basic" { + basic_body(ui, d); + } else { + ui.horizontal(|ui| { + ui.label(tl!("Style Name:")); + form::text(ui, d, "name", 190.0); + }); + ui.separator(); + if let Ok(attrs) = edited_attrs(d) { + for (key, value) in attrs { + ui.label(format!("{}: {}", super::humanize(&key), value)); + } + } + } + }); + }); + ui.add_enabled_ui(d.str("section") == "basic", |ui| { + if ui.button(tl!("Reset Panel")).clicked() { + reset_basic(d); + } + }); + match edited_attrs(d) { + Ok(attrs) => { + let params = json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs}); + form::preview(app, ui, d, tl!("Character Style Options"), "charStyle.edit", params); + } + Err(why) => { + ui.add_space(6.0); + ui.colored_label(crate::theme::Tokens::get(ui.ctx()).error, crate::i18n::message(crate::i18n::current(), &why)); + } + } + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let attrs = edited_attrs(d)?; + form::commit_preview(app, "charStyle.edit", json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs})) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app + } + + fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + } + + #[test] + fn unchanged_basic_fields_preserve_original_keys() { + for attrs in [ + json!({"all_caps": false}), + json!({"all_caps": true}), + json!({"small_caps": 70.0}), + json!({"font_family": "Example", "font_style": "Regular", "font_version": "1", "size": 24, + "leading": null, "kerning": null, "tracking": 3, "underline": null, + "strikethrough": false, "position": {"kind": "normal", "size": 80}, "charAlign": null}), + ] { + let original = attrs.as_object().unwrap().clone(); + let mut fields = fields_from_attrs(&original); + fields.insert("__attrs".into(), attrs); + let d = Dialog { kind: KIND.into(), fields }; + assert_eq!(edited_attrs(&d).unwrap(), original); + } + let original = json!({"all_caps": false}).as_object().unwrap().clone(); + let mut fields = fields_from_attrs(&original); + fields.insert("__attrs".into(), json!(original)); + fields.insert("case".into(), json!("allCaps")); + let d = Dialog { kind: KIND.into(), fields }; + assert_eq!(edited_attrs(&d).unwrap(), json!({"all_caps": true, "small_caps": null}).as_object().unwrap().clone()); + } + + #[test] + fn unchanged_options_keep_local_small_caps_and_history() { + for preview in [false, true] { + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"all_caps": false}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 4, "smallCaps": true})).unwrap(); + let state = app.session.doc().unwrap(); + let before = state.doc.clone(); + let history = (state.history.undo.len(), state.history.redo.len()); + open(&mut app, "Body").unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(preview)); + if preview { + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + } + super::super::confirm(&mut app).unwrap(); + let state = app.session.doc().unwrap(); + assert_eq!(state.doc, before); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!( + state.doc.node(vectorcraft_doc::NodeId(id)).and_then(|node| match &node.kind { + vectorcraft_doc::NodeKind::Text(text) => text.runs.first().map(|run| run.style.small_caps), + _ => None, + }), + Some(Some(state.doc.setup.small_caps_size)) + ); + } + } + + #[test] + fn options_preview_cancel_reset_and_commit_keep_sparse_definition() { + let mut app = app(); + app.run("charStyle.new", json!({"name":"Body","attrs":{"size":24.0,"baseline_shift":3.0}})).unwrap(); + let id = app.run("text.create", json!({"x":10,"y":40,"text":"Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name":"Body","id":id})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + open(&mut app, "Body").unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("preview")); + assert!(app.run("ui.charStyleOptions.resetPanel", json!({})).is_err()); + assert!(app.ui.dialog.as_ref().unwrap().fields["underline"].is_null()); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("kerning"), ""); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("name".into(), json!("Revised")); + d.fields.insert("size".into(), json!(18)); + } + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].name, "Revised"); + super::super::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + open(&mut app, "Body").unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("section".into(), json!("basic")); + } + app.run("ui.charStyleOptions.resetPanel", json!({})).unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(edited_attrs(d).unwrap(), serde_json::from_value(json!({"baseline_shift":3.0})).unwrap()); + d.fields.insert("name".into(), json!("Revised")); + } + super::super::confirm(&mut app).unwrap(); + let state = app.session.doc().unwrap(); + assert_eq!(state.history.undo.len(), undo + 1); + assert_eq!(state.doc.char_styles[0].name, "Revised"); + assert_eq!(state.doc.char_styles[0].attrs, serde_json::from_value(json!({"baseline_shift":3.0})).unwrap()); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].name, "Revised"); + app.run("select.set", json!({"ids":[id]})).unwrap(); + app.run("ui.newCharStyle", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("size"), "12.0"); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("size".into(), json!(36.0)); + d.fields.insert("name".into(), json!("Future")); + } + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.char_styles.iter().find(|def| def.name == "Future").unwrap().attrs["size"], json!(36.0)); + } + + #[test] + fn invalid_numbers_name_the_visible_field() { + let mut d = Dialog::new(KIND, json!({})); + for (key, label) in [("size", "Size"), ("leading", "Leading"), ("kerning", "Kerning"), ("tracking", "Tracking")] { + d.fields.insert(key.into(), json!("not a number")); + assert_eq!(optional_number(&d, key).unwrap_err(), format!("{label} must be a number")); + } + } + + #[test] + fn size_and_leading_below_minimum_do_not_preview_or_commit() { + for (key, value) in [("size", json!(0)), ("size", json!(-2)), ("leading", json!(0.09)), ("leading", json!(-1))] { + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0, "leading": 28.0}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + open(&mut app, "Body").unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("name".into(), json!("Revised")); + d.fields.insert(key.into(), value); + assert!(edited_attrs(d).unwrap_err().contains("at least 0.1")); + } + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before, "{key} preview"); + assert!(super::super::confirm(&mut app).is_err(), "{key} confirm"); + assert_eq!(app.session.doc().unwrap().doc, before, "{key} confirm"); + } + } + + #[test] + fn invalid_number_keeps_last_valid_preview() { + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + open(&mut app, "Body").unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("name".into(), json!("Revised")); + d.fields.insert("size".into(), json!(18)); + } + frame(&mut app); + let valid = app.session.doc().unwrap().doc.clone(); + assert_eq!(valid.char_styles[0].name, "Revised"); + assert_eq!(valid.char_styles[0].attrs["size"], json!(18.0)); + app.ui.dialog.as_mut().unwrap().fields.insert("size".into(), json!("invalid")); + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc, valid); + } + + #[test] + fn script_positions_use_document_setup_in_existing_and_new_style_dialogs() { + let mut app = app(); + app.run( + "document.setup", + json!({"superscript": {"size": 67.0, "position": 22.0}, + "subscript": {"size": 72.0, "position": 18.0}}), + ) + .unwrap(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + open(&mut app, "Body").unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("position".into(), json!("superscript")); + assert_eq!( + edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap()["position"], + json!({"kind": "superscript", "size": 67.0, "position": 22.0}) + ); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].attrs["position"], json!({"kind": "superscript", "size": 67.0, "position": 22.0})); + app.run("ui.newCharStyle", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("position".into(), json!("subscript")); + assert_eq!(edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap()["position"], json!({"kind": "subscript", "size": 72.0, "position": 18.0})); + super::super::confirm(&mut app).unwrap(); + assert_eq!( + app.session.doc().unwrap().doc.char_styles.last().unwrap().attrs["position"], + json!({"kind": "subscript", "size": 72.0, "position": 18.0}) + ); + } +} diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index f945332e64..16ec9568d5 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -31,14 +31,60 @@ pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result bool { + if !para(d) { + ui.horizontal(|ui| { + ui.vertical(|ui| { + for (id, title) in [("general", tl!("General")), ("basic", tl!("Basic Character Formats"))] { + if ui.selectable_label(d.str("section") == id, title).clicked() { + d.fields.insert("section".into(), json!(id)); + } + } + }); + ui.separator(); + if d.str("section") == "basic" { + super::char_style_options::basic_body(ui, d); + } else { + ui.vertical(|ui| { + grid(ui, |ui| { + label(ui, tl!("Style Name:")); + form::text(ui, d, "name", 190.0); + ui.end_row(); + }); + if let Ok(attrs) = super::char_style_options::edited_attrs(d) { + for (key, value) in attrs { + ui.label(format!("{}: {}", super::humanize(&key), value)); + } + } + }); + } + }); + ui.add_enabled_ui(d.str("section") == "basic", |ui| { + if ui.button(tl!("Reset Panel")).clicked() { + super::char_style_options::reset_basic(d); + } + }); + return false; + } grid(ui, |ui| { label(ui, tl!("Style Name:")); form::text(ui, d, "name", 190.0); @@ -52,6 +98,9 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut params = d.fields.get("__target").filter(|t| t.is_object()).cloned().unwrap_or_else(|| json!({})); params["name"] = json!(d.str("name")); + if !para(d) { + params["attrs"] = Value::Object(super::char_style_options::edited_attrs(d)?); + } let r = app.run(if para(d) { "paraStyle.new" } else { "charStyle.new" }, params); if let Ok(v) = &r { app.ui.dialog = None; diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 442e051c03..87c2edac46 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5869,6 +5869,12 @@ anchor Points: Punts: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Color dels punts de la il·lustració + Basic Character Formats Formats bàsics de caràcters + Case Majúscules i minúscules + Kerning Interlletratge +@msg {label} must be a number {label} ha de ser un nombre +@msg {label} must be a number of at least 0.1 {label} ha de ser un nombre de com a mínim 0,1 +@msg no character style `{name}` No s'ha trobat l'estil de caràcter `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Bitò… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index aa88620f4d..3f9c07acd5 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5878,6 +5878,12 @@ anchor Points: Body: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Barva bodů podle kresby + Basic Character Formats Základní formáty znaků + Case Velikost písmen + Kerning Vyrovnání párů +@msg {label} must be a number {label} musí být číslo +@msg {label} must be a number of at least 0.1 {label} musí být číslo alespoň 0,1 +@msg no character style `{name}` styl znaků `{name}` neexistuje # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Dvoutón… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2d1e728453..f248421755 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5463,6 +5463,12 @@ anchor Points: Punkte: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Punktfarbe aus Grafik + Basic Character Formats Grundlegende Zeichenformate + Case Großschreibung + Kerning Unterschneidung +@msg {label} must be a number {label} muss eine Zahl sein +@msg {label} must be a number of at least 0.1 {label} muss eine Zahl von mindestens 0,1 sein +@msg no character style `{name}` Zeichenformat `{name}` nicht gefunden # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Duplex… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 16fe9435e1..eab0f70fa3 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5830,6 +5830,12 @@ anchor Points: Σημεία: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Χρώμα κουκκίδων από το γραφικό + Basic Character Formats Βασικές μορφές χαρακτήρων + Case Πεζά και κεφαλαία + Kerning Διαγραμμάτωση +@msg {label} must be a number Το {label} πρέπει να είναι αριθμός +@msg {label} must be a number of at least 0.1 Το {label} πρέπει να είναι αριθμός τουλάχιστον 0,1 +@msg no character style `{name}` Δεν βρέθηκε το στυλ χαρακτήρων `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Δίτονο… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d4d2d20eb3..5b7d317406 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5821,6 +5821,12 @@ anchor Points: Puntos: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Color de puntos de la ilustración + Basic Character Formats Formatos básicos de caracteres + Case Mayúsculas y minúsculas + Kerning Interletraje +@msg {label} must be a number {label} debe ser un número +@msg {label} must be a number of at least 0.1 {label} debe ser un número de al menos 0,1 +@msg no character style `{name}` No existe el estilo de carácter `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Duotono… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e080c8f98d..4f6a802ccd 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5909,6 +5909,12 @@ anchor Points: Pisteet: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Pisteiden väri kuvituksesta + Basic Character Formats Merkkien perusmuotoilut + Case Kirjainkoko + Kerning Merkkipariväli +@msg {label} must be a number {label} on oltava luku +@msg {label} must be a number of at least 0.1 {label} on oltava vähintään 0,1 +@msg no character style `{name}` Merkkityyliä `{name}` ei löytynyt # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Duotone… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index dd9cc259a2..57196f94ee 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5876,6 +5876,12 @@ anchor Points: Points : # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Couleur des points d’après l’illustration + Basic Character Formats Formats de caractère de base + Case Casse + Kerning Crénage +@msg {label} must be a number {label} doit être un nombre +@msg {label} must be a number of at least 0.1 {label} doit être un nombre d’au moins 0,1 +@msg no character style `{name}` Style de caractère `{name}` introuvable # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Bichromie… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 671a569caa..5e9b7a386b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5865,6 +5865,12 @@ anchor Points: Pontok: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Pontszín a grafikából + Basic Character Formats Alapvető karakterformátumok + Case Kis- és nagybetűk + Kerning Betűpárköz +@msg {label} must be a number {label}: szám kell +@msg {label} must be a number of at least 0.1 {label} legalább 0,1 értékű szám kell legyen +@msg no character style `{name}` A(z) `{name}` karakterstílus nem található # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Duplex… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 708378ba43..9c41f8daf0 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5497,6 +5497,12 @@ anchor Points: Punti: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Colore punti dalla grafica + Basic Character Formats Formati carattere di base + Case Maiuscole e minuscole + Kerning Crenatura +@msg {label} must be a number {label} deve essere un numero +@msg {label} must be a number of at least 0.1 {label} deve essere un numero di almeno 0,1 +@msg no character style `{name}` Stile di carattere `{name}` non trovato # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Bicromia… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 628f0ec033..6978094eee 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5563,6 +5563,12 @@ anchor Points: ポイント: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art ドットの色をアートから取得 + Basic Character Formats 基本文字形式 + Case 大文字と小文字 + Kerning カーニング +@msg {label} must be a number {label} には数値を指定してください +@msg {label} must be a number of at least 0.1 {label} には 0.1 以上の数値を指定してください +@msg no character style `{name}` 文字スタイル `{name}` が見つかりません # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… ダブルトーン… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 4d44093f71..545c5fc1e0 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5868,6 +5868,12 @@ anchor Points: წერტილები: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art წერტილების ფერი ნახატიდან + Basic Character Formats სიმბოლოს ძირითადი ფორმატები + Case ასოების რეგისტრი + Kerning კერნინგი +@msg {label} must be a number {label} უნდა იყოს რიცხვი +@msg {label} must be a number of at least 0.1 {label} უნდა იყოს მინიმუმ 0,1 +@msg no character style `{name}` სიმბოლოს სტილი `{name}` ვერ მოიძებნა # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… დუოტონი… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dea1f8f503..07b703658d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5460,6 +5460,12 @@ anchor Points: 포인트: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art 아트워크에서 점 색상 가져오기 + Basic Character Formats 기본 문자 형식 + Case 대소문자 + Kerning 커닝 +@msg {label} must be a number {label}은(는) 숫자여야 합니다 +@msg {label} must be a number of at least 0.1 {label}은(는) 0.1 이상의 숫자여야 합니다 +@msg no character style `{name}` 문자 스타일 `{name}`을 찾을 수 없습니다 # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… 이중톤… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 9debbef17a..8104acb32e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5733,6 +5733,12 @@ anchor Points: Punkty: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Kolor kropek z kompozycji + Basic Character Formats Podstawowe formaty znaków + Case Wielkość liter + Kerning Kerning +@msg {label} must be a number {label} musi być liczbą +@msg {label} must be a number of at least 0.1 {label} musi być liczbą co najmniej 0,1 +@msg no character style `{name}` Nie znaleziono stylu znakowego `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Dwutonowy… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e40d32fb13..dbccb87c74 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5796,6 +5796,12 @@ anchor Points: Pontos: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Cor dos Pontos da Arte + Basic Character Formats Formatos básicos de caracteres + Case Maiúsculas e minúsculas + Kerning Kerning +@msg {label} must be a number {label} deve ser um número +@msg {label} must be a number of at least 0.1 {label} deve ser um número de pelo menos 0,1 +@msg no character style `{name}` Estilo de caractere `{name}` não encontrado # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Duotom… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 7bfca518c4..9419aeb42d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5856,6 +5856,12 @@ anchor Points: Точки: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Цвет точек из рисунка + Basic Character Formats Основные форматы символов + Case Регистр + Kerning Кернинг +@msg {label} must be a number {label} должно быть числом +@msg {label} must be a number of at least 0.1 {label} должно быть числом не меньше 0,1 +@msg no character style `{name}` Стиль символов `{name}` не найден # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Дуплекс… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd22f672d..616c5f319a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5931,6 +5931,12 @@ shape Open Öppen # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Punktfärg från objekt + Basic Character Formats Grundläggande teckenformat + Case Skiftläge + Kerning Kerning +@msg {label} must be a number {label} måste vara ett tal +@msg {label} must be a number of at least 0.1 {label} måste vara ett tal på minst 0,1 +@msg no character style `{name}` Teckenformatet `{name}` hittades inte # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Duoton… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index deb3e95d78..7d84df263f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5836,6 +5836,12 @@ anchor Points: Noktalar: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Nokta Rengini Sanattan Al + Basic Character Formats Temel karakter biçimleri + Case Büyük küçük harf + Kerning Karakter aralığı +@msg {label} must be a number {label} bir sayı olmalıdır +@msg {label} must be a number of at least 0.1 {label} en az 0,1 olan bir sayı olmalıdır +@msg no character style `{name}` `{name}` karakter stili bulunamadı # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Çift Ton… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d78f48b331..aeaffaaac5 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5477,6 +5477,12 @@ anchor Points: Точки: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Колір точок із малюнка + Basic Character Formats Основні формати символів + Case Регістр + Kerning Кернінг +@msg {label} must be a number {label} має бути числом +@msg {label} must be a number of at least 0.1 {label} має бути числом не менше 0,1 +@msg no character style `{name}` Стиль символів `{name}` не знайдено # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Дуплекс… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index ade0a07aae..3f3292be39 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5479,6 +5479,12 @@ anchor Points: Điểm: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Màu chấm theo tác phẩm + Basic Character Formats Định dạng ký tự cơ bản + Case Chữ hoa và chữ thường + Kerning Điều chỉnh khoảng cách cặp chữ +@msg {label} must be a number {label} phải là một số +@msg {label} must be a number of at least 0.1 {label} phải là một số ít nhất bằng 0,1 +@msg no character style `{name}` Không tìm thấy kiểu ký tự `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Hai tông… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index acffa1e4e9..cf2ae14bff 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5720,6 +5720,12 @@ anchor Points: 点: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art 网点颜色取自图稿 + Basic Character Formats 基本字符格式 + Case 大小写 + Kerning 字偶间距 +@msg {label} must be a number {label} 必须是数字 +@msg {label} must be a number of at least 0.1 {label} 必须是至少 0.1 的数字 +@msg no character style `{name}` 找不到字符样式 `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… 双色调… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3b560be95b..f8c302079b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5516,6 +5516,12 @@ anchor Points: 點: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art 網點顏色取自圖稿 + Basic Character Formats 基本字元格式 + Case 大小寫 + Kerning 字偶間距 +@msg {label} must be a number {label} 必須是數字 +@msg {label} must be a number of at least 0.1 {label} 必須是至少 0.1 的數字 +@msg no character style `{name}` 找不到字元樣式 `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… 雙色調… diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index bb20fbbca5..5b83dc25b8 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -594,6 +594,11 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::open_color_picker(app, p), "ui.sampleScreenColor" => crate::screen_color::start(app, p), "ui.graphicStyleOptions" => crate::dialogs::graphic_style_options::open(app, s("name").as_deref()), + "ui.charStyleOptions" => match s("name") { + Some(name) => crate::dialogs::char_style_options::open(app, &name), + None => Err("missing `name`".into()), + }, + "ui.charStyleOptions.resetPanel" => crate::dialogs::char_style_options::reset_panel(app), "ui.newCharStyle" => crate::panels::text_styles::open_new(app, crate::panels::text_styles::Kind::Char), "ui.newParaStyle" => crate::panels::text_styles::open_new(app, crate::panels::text_styles::Kind::Para), "ui.symbolOptions" => { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index c1cdf4f59d..ad7f88c5c6 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -225,7 +225,11 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.missingFontsDialog" => !cfg!(target_arch = "wasm32") && app.session.active().is_some(), "ui.findFontsInFolder" => crate::picks::can(app, &crate::picks::PickRequest::Folder) && app.session.active().is_some(), "ui.swatchOptions" | "ui.newSwatch" | "ui.newColorGroup" => app.session.active().is_some(), - "ui.graphicStyleOptions" | "ui.newCharStyle" | "ui.newParaStyle" => app.session.active().is_some(), + "ui.graphicStyleOptions" | "ui.charStyleOptions" | "ui.newCharStyle" | "ui.newParaStyle" => app.session.active().is_some(), + "ui.charStyleOptions.resetPanel" => app.ui.dialog.as_ref().is_some_and(|d| { + (d.kind == crate::dialogs::char_style_options::KIND || (d.kind == crate::dialogs::new_text_style::KIND && !d.bool("__para"))) + && d.str("section") == "basic" + }), "ui.newArtboard" => app.session.active().is_some(), "ui.sampleScreenColor" => crate::screen_color::available(app), "ui.newBrush" => app.session.active().is_some(), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ba3e700c62..bd633da60e 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -657,6 +657,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{name?} open Graphic Style Options (dialog `graphicStyleOptions`, field `name`): for style `name` OK renames it (graphicStyle.rename); without, OK makes a new style of that name from the selection (graphicStyle.new)", ), + ( + "ui.charStyleOptions", + "Character Style Options", + "", + "{name} open Character Style Options (dialog `charStyleOptions`); OK runs charStyle.edit with name, to and sparse attrs in one undo step; Cancel restores a live preview", + ), + ( + "ui.charStyleOptions.resetPanel", + "Reset Panel", + "", + "{} clear the Basic Character Formats settings in the open Character Style Options or New Character Style dialog; available only on that section", + ), ( "ui.newCharStyle", "New Character Style…", diff --git a/crates/ui-egui/src/panels/text_styles.rs b/crates/ui-egui/src/panels/text_styles.rs index 8eebeae19f..1aca6039a1 100644 --- a/crates/ui-egui/src/panels/text_styles.rs +++ b/crates/ui-egui/src/panels/text_styles.rs @@ -375,8 +375,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { if menu_item(ui, &crate::i18n::fmt(tl!("{kind} Style Options…"), &[("kind", kind.what_label())]), user, false) && let Some(n) = &sel { - let label = format!("{} Style Options", kind.what()); - app.run("ui.paramDialog", json!({ "command": format!("{p}.rename"), "label": label, "params": { "name": n, "to": n } })).ok(); + if kind == Kind::Char { + app.run("ui.charStyleOptions", json!({ "name": n })).ok(); + } else { + let label = format!("{} Style Options", kind.what()); + app.run("ui.paramDialog", json!({ "command": format!("{p}.rename"), "label": label, "params": { "name": n, "to": n } })).ok(); + } } } diff --git a/crates/ui-egui/src/panels/text_styles/tests.rs b/crates/ui-egui/src/panels/text_styles/tests.rs index d20962461a..144e2d525f 100644 --- a/crates/ui-egui/src/panels/text_styles/tests.rs +++ b/crates/ui-egui/src/panels/text_styles/tests.rs @@ -291,6 +291,22 @@ fn panel_menu_duplicate_and_delete_update_the_highlighted_style() { } } +#[test] +fn character_style_options_menu_opens_format_sections() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + click_label(&ctx, &mut app, "Body", |app, ui| show(app, ui, Kind::Char)); + assert_eq!(click_label(&ctx, &mut app, " Character Style Options…", |app, ui| menu(app, ui, Kind::Char)), 1); + let dialog = app.ui.dialog.as_ref().unwrap(); + assert_eq!(dialog.kind, crate::dialogs::char_style_options::KIND); + assert_eq!(dialog.str("section"), "general"); + assert_eq!(dialog.str("size"), "24.0"); + assert!(dialog.bool("preview")); +} + /// In a panel scrolled to the top of a long list, the menu's Duplicate scrolls the copy's row into /// view, and so does the New button's `highlight_made` for the new style. #[test] @@ -866,6 +882,40 @@ fn alt_clicking_new_character_style_asks_for_its_name() { assert_eq!(text_editing(&app), Some((id, 3, 5)), "the Type selection stays"); } +#[test] +fn new_character_style_without_selection_uses_japanese_defaults() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.prefs.interface_language = "ja".into(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + assert!(app.session.japanese_interface()); + + for (name, size) in [("Default", None), ("Edited", Some(18))] { + crate::dialogs::new_text_style::open(&mut app, false, json!({})).unwrap(); + let dialog = app.ui.dialog.as_mut().unwrap(); + assert_eq!(dialog.fields["__attrs"]["charAlign"], "emBoxCenter"); + dialog.fields.insert("name".into(), json!(name)); + if let Some(size) = size { + dialog.fields.insert("size".into(), json!(size)); + } + crate::dialogs::confirm(&mut app).unwrap(); + let style = app.session.doc().unwrap().doc.char_styles.iter().find(|style| style.name == name).unwrap(); + assert_eq!(style.attrs.get("charAlign"), Some(&json!("emBoxCenter"))); + assert_eq!(style.attrs.get("size").cloned(), size.map(|value| json!(f64::from(value)))); + } + crate::dialogs::new_text_style::open(&mut app, false, json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!("basic")); + app.run("ui.charStyleOptions.resetPanel", json!({})).unwrap(); + let dialog = app.ui.dialog.as_ref().unwrap(); + assert!(!crate::dialogs::char_style_options::edited_attrs(dialog).unwrap().contains_key("charAlign")); + crate::dialogs::cancel(&mut app); + + crate::dialogs::new_text_style::open(&mut app, true, json!({})).unwrap(); + let dialog = app.ui.dialog.as_ref().unwrap(); + assert!(dialog.fields["__target"].get("attrs").is_none()); + assert!(dialog.fields.get("__attrs").is_none()); + crate::dialogs::cancel(&mut app); +} + /// The dialog highlights its new style and scrolls the matching panel to its row. #[test] fn a_style_made_in_the_new_style_dialog_is_highlighted() { diff --git a/docs/mcp.md b/docs/mcp.md index 129d7346c3..1557555237 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5109,6 +5109,22 @@ name and the Type tool's selection as it was when the dialog opened (else the se has, or an empty one, keeps the dialog open, and Cancel adds no style. A plain click on New still makes the style at once. +`ui.charStyleOptions {name}` opens Character Style Options for an existing named style. +Character Style Options uses `charStyle.edit {name, to, attrs}` to replace the name and complete sparse +attribute map in one undo step. `to` is trimmed and must be unique. The command updates text using the style +while preserving local overrides; Undo/Redo restores the definition and its users. The `charStyleOptions` +dialog exposes `name`, `font_family`, `font_style`, `size`, `leading`, `kerning`, `tracking`, `case`, +`position`, `underline`, `strikethrough`, `charAlign`, `section`, and `preview`. An empty field leaves its +attribute unset. `leading` and `kerning` also accept `Auto` to store an explicit automatic value. +The New Character Style dialog accepts the same character fields and starts with the selected text's +captured attributes. Without selected text, it starts with the character defaults for the interface language +(including `charAlign: "emBoxCenter"` in Japanese); changing a Basic field keeps other seeded attributes. +Without selected text, the New Paragraph Style dialog sends no `attrs`, and the engine gives the new style the +paragraph defaults for the interface language. Reset Panel in Basic Character +Formats removes those fields from the definition. +`ui.charStyleOptions.resetPanel {}` performs that reset when Basic Character Formats is selected in +either character-style dialog; it is disabled on General. + In the native file a text object's `para` holds the first paragraph's attributes and `paras` (left out when every paragraph is alike) one entry per paragraph, so older readers keep the first paragraph's. SVG export anchors each centred or right-aligned line on its own (``), and SVG import gives each line's paragraph its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e6645bbbce..caa6dbfb3c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -500,7 +500,8 @@ since 2026-10-01. - **COLR colour fonts:** v0 and v1 glyphs draw as vector layers (solid colours, linear and radial gradients, clips, blend modes, the foreground colour from the run's fill) on the canvas, as paths in SVG, EPS, legacy `.ai` and PDF with outlined text, as Type 3 text in PDF, and as editable groups with Create Outlines; sweep gradients and Porter-Duff compositing draw the glyph as an image. Measured by `tests_colr`, `render::tests_colrglyphs`, `pdf::tests::colr_glyphs_export_as_vector_art`, `svg/tests/it/colour_glyphs.rs`, `eps` `colr_glyphs_*`, `tests_pathops::create_outlines_turns_colr_glyphs_into_layer_groups`. Scores unchanged (estimated). - **OpenType SVG colour fonts:** each glyph's SVG document is read by the SVG importer (registered by the engine) into vector art in the run's colours, then drawn, exported and outlined as COLR glyphs are; PDF real text writes them as text that draws nothing and draws their art where they sit. Measured by `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`. Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). -- **Text styles redefined to the defaults:** New and Redefine Character Style and Paragraph Style capture every attribute of the selected text, including those at their defaults (Auto kerning, Roman baseline alignment, the default Hyphenation options, the Every-line Composer, no tab stops), and `charStyle.setAttrs` and `paraStyle.setAttrs` keep an attribute set to its default value. After a redefinition, text whose value still equals the old definition's takes the new value, a default included; local overrides and attributes the new definition leaves out stay. The style panels show "+" only where the text differs from its style, including type with Auto alignment. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). +- **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). +- **Text styles redefined to the defaults:** New and Redefine Character Style and Paragraph Style capture every attribute of the selected text, including those at their defaults (Auto kerning, Roman baseline alignment, the default Hyphenation options, the Every-line Composer, no tab stops), and `charStyle.setAttrs` and `paraStyle.setAttrs` keep an attribute set to its default value. After a redefinition, text whose value still equals the old definition's takes the new value, a default included; local overrides stay, and text that still has the old value of an attribute the new definition leaves out goes back to the Normal style's value. The style panels show "+" only where the text differs from its style, including type with Auto alignment. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Text styles dragged onto the panel's buttons:** a style dragged from the Character Styles or Paragraph Styles panel onto Create New Style is copied (`charStyle.duplicate`, `paraStyle.duplicate`, which name the copy ` copy`) and the copy is highlighted; dragged onto Delete it is deleted (`charStyle.delete`, `paraStyle.delete`); the Normal style is not deleted. Each drop is one undo step. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Auto Leading outside the layout:** a paragraph's Justification… › Auto Leading () also sets the Leading the Character panel shows for Auto type (blank where the selected paragraphs differ), the leading the Alt+↑/↓ nudge (`type.step`) steps from, each paragraph's own, and the lines Fill with Placeholder Text counts in area type. Evidence: `ParaStyle::effective_leading` (`crates/doc/src/text.rs` test `paragraph_effective_leading_follows_auto_leading`), `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading`. - **The text style panel menus' Duplicate and Delete:** in the Character Styles and Paragraph Styles panel menus, Duplicate highlights the copy, as Create New Style highlights the new style, and Delete leaves no style highlighted, as the Delete button does, so Duplicate, Clear Overrides, Redefine and Style Options are disabled until another style is clicked. A highlighted style that is renamed in Style Options or deleted by a command is no longer highlighted either. The tests `panels::text_styles::tests::panel_menu_duplicate_and_delete_update_the_highlighted_style` and `a_highlighted_style_that_is_no_longer_listed_is_not_highlighted` cover this. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). From 2f1404af228c7eba86d5c97a7123c6657144233f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sun, 1 Nov 2026 00:39:09 +0700 Subject: [PATCH 33/70] Optical kerning: shaped advances are read with get() --- crates/text/src/shape.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 5c69a6a935..ab547ef837 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -580,7 +580,7 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range< continue; } let mut start = i; - while start > 0 && glyphs[start - 1].byte == a.byte { + while start > 0 && glyphs.get(start - 1).is_some_and(|g| g.byte == a.byte) { start -= 1; } let mut end = i + 1; @@ -588,15 +588,16 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range< end += 1; } // A mark may precede its base inside either direction's shaped cluster. + let advance = |k: usize| shaped_advances.get(k).copied().unwrap_or(0.0); let first_base = glyphs[start..=i] .iter() .enumerate() - .max_by(|(a, _), (b, _)| shaped_advances[start + *a].total_cmp(&shaped_advances[start + *b])) + .max_by(|(a, _), (b, _)| advance(start + *a).total_cmp(&advance(start + *b))) .map_or(start, |(offset, _)| start + offset); let second_base = glyphs[i + 1..=end] .iter() .enumerate() - .max_by(|(a, _), (b, _)| shaped_advances[i + 1 + *a].total_cmp(&shaped_advances[i + 1 + *b])) + .max_by(|(a, _), (b, _)| advance(i + 1 + *a).total_cmp(&advance(i + 1 + *b))) .map_or(i + 1, |(offset, _)| i + 1 + offset); let (left_index, right_index, target, cluster_start, cluster_end) = if a.level.is_rtl() { (second_base, first_base, end, i + 1, end) } else { (first_base, second_base, i, start, i) }; From 939af8e255fb9f025e14bd4c4289bd81cdcac5e9 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sun, 1 Nov 2026 00:53:30 +0700 Subject: [PATCH 34/70] i18n: one Kerning row per catalog after the Character Styles and Kerning changes --- crates/ui-egui/src/i18n/ca.tsv | 1 - crates/ui-egui/src/i18n/cs.tsv | 1 - crates/ui-egui/src/i18n/de.tsv | 1 - crates/ui-egui/src/i18n/el.tsv | 1 - crates/ui-egui/src/i18n/es.tsv | 1 - crates/ui-egui/src/i18n/fi.tsv | 1 - crates/ui-egui/src/i18n/fr.tsv | 1 - crates/ui-egui/src/i18n/hu.tsv | 1 - crates/ui-egui/src/i18n/it.tsv | 1 - crates/ui-egui/src/i18n/ja.tsv | 1 - crates/ui-egui/src/i18n/ka.tsv | 1 - crates/ui-egui/src/i18n/ko.tsv | 1 - crates/ui-egui/src/i18n/pl.tsv | 1 - crates/ui-egui/src/i18n/pt-br.tsv | 1 - crates/ui-egui/src/i18n/ru.tsv | 1 - crates/ui-egui/src/i18n/sv.tsv | 1 - crates/ui-egui/src/i18n/tr.tsv | 1 - crates/ui-egui/src/i18n/uk.tsv | 1 - crates/ui-egui/src/i18n/vi.tsv | 1 - crates/ui-egui/src/i18n/zh-hans.tsv | 1 - crates/ui-egui/src/i18n/zh-hant.tsv | 1 - 21 files changed, 21 deletions(-) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 87c2edac46..9f8b0a55e4 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5871,7 +5871,6 @@ anchor Points: Punts: Dot Color from Art Color dels punts de la il·lustració Basic Character Formats Formats bàsics de caràcters Case Majúscules i minúscules - Kerning Interlletratge @msg {label} must be a number {label} ha de ser un nombre @msg {label} must be a number of at least 0.1 {label} ha de ser un nombre de com a mínim 0,1 @msg no character style `{name}` No s'ha trobat l'estil de caràcter `{name}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3f9c07acd5..2a9aeaf99b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5880,7 +5880,6 @@ anchor Points: Body: Dot Color from Art Barva bodů podle kresby Basic Character Formats Základní formáty znaků Case Velikost písmen - Kerning Vyrovnání párů @msg {label} must be a number {label} musí být číslo @msg {label} must be a number of at least 0.1 {label} musí být číslo alespoň 0,1 @msg no character style `{name}` styl znaků `{name}` neexistuje diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index f248421755..240bb8684d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5465,7 +5465,6 @@ anchor Points: Punkte: Dot Color from Art Punktfarbe aus Grafik Basic Character Formats Grundlegende Zeichenformate Case Großschreibung - Kerning Unterschneidung @msg {label} must be a number {label} muss eine Zahl sein @msg {label} must be a number of at least 0.1 {label} muss eine Zahl von mindestens 0,1 sein @msg no character style `{name}` Zeichenformat `{name}` nicht gefunden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index eab0f70fa3..a4057ea1dc 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5832,7 +5832,6 @@ anchor Points: Σημεία: Dot Color from Art Χρώμα κουκκίδων από το γραφικό Basic Character Formats Βασικές μορφές χαρακτήρων Case Πεζά και κεφαλαία - Kerning Διαγραμμάτωση @msg {label} must be a number Το {label} πρέπει να είναι αριθμός @msg {label} must be a number of at least 0.1 Το {label} πρέπει να είναι αριθμός τουλάχιστον 0,1 @msg no character style `{name}` Δεν βρέθηκε το στυλ χαρακτήρων `{name}` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5b7d317406..2a77b567a4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5823,7 +5823,6 @@ anchor Points: Puntos: Dot Color from Art Color de puntos de la ilustración Basic Character Formats Formatos básicos de caracteres Case Mayúsculas y minúsculas - Kerning Interletraje @msg {label} must be a number {label} debe ser un número @msg {label} must be a number of at least 0.1 {label} debe ser un número de al menos 0,1 @msg no character style `{name}` No existe el estilo de carácter `{name}` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 4f6a802ccd..44af5c9fb7 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5911,7 +5911,6 @@ anchor Points: Pisteet: Dot Color from Art Pisteiden väri kuvituksesta Basic Character Formats Merkkien perusmuotoilut Case Kirjainkoko - Kerning Merkkipariväli @msg {label} must be a number {label} on oltava luku @msg {label} must be a number of at least 0.1 {label} on oltava vähintään 0,1 @msg no character style `{name}` Merkkityyliä `{name}` ei löytynyt diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 57196f94ee..abc63175f4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5878,7 +5878,6 @@ anchor Points: Points : Dot Color from Art Couleur des points d’après l’illustration Basic Character Formats Formats de caractère de base Case Casse - Kerning Crénage @msg {label} must be a number {label} doit être un nombre @msg {label} must be a number of at least 0.1 {label} doit être un nombre d’au moins 0,1 @msg no character style `{name}` Style de caractère `{name}` introuvable diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 5e9b7a386b..db6960188e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5867,7 +5867,6 @@ anchor Points: Pontok: Dot Color from Art Pontszín a grafikából Basic Character Formats Alapvető karakterformátumok Case Kis- és nagybetűk - Kerning Betűpárköz @msg {label} must be a number {label}: szám kell @msg {label} must be a number of at least 0.1 {label} legalább 0,1 értékű szám kell legyen @msg no character style `{name}` A(z) `{name}` karakterstílus nem található diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 9c41f8daf0..618fce870f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5499,7 +5499,6 @@ anchor Points: Punti: Dot Color from Art Colore punti dalla grafica Basic Character Formats Formati carattere di base Case Maiuscole e minuscole - Kerning Crenatura @msg {label} must be a number {label} deve essere un numero @msg {label} must be a number of at least 0.1 {label} deve essere un numero di almeno 0,1 @msg no character style `{name}` Stile di carattere `{name}` non trovato diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6978094eee..30005d3c3a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5565,7 +5565,6 @@ anchor Points: ポイント: Dot Color from Art ドットの色をアートから取得 Basic Character Formats 基本文字形式 Case 大文字と小文字 - Kerning カーニング @msg {label} must be a number {label} には数値を指定してください @msg {label} must be a number of at least 0.1 {label} には 0.1 以上の数値を指定してください @msg no character style `{name}` 文字スタイル `{name}` が見つかりません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 545c5fc1e0..ff40a494d5 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5870,7 +5870,6 @@ anchor Points: წერტილები: Dot Color from Art წერტილების ფერი ნახატიდან Basic Character Formats სიმბოლოს ძირითადი ფორმატები Case ასოების რეგისტრი - Kerning კერნინგი @msg {label} must be a number {label} უნდა იყოს რიცხვი @msg {label} must be a number of at least 0.1 {label} უნდა იყოს მინიმუმ 0,1 @msg no character style `{name}` სიმბოლოს სტილი `{name}` ვერ მოიძებნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 07b703658d..d2f381afcb 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5462,7 +5462,6 @@ anchor Points: 포인트: Dot Color from Art 아트워크에서 점 색상 가져오기 Basic Character Formats 기본 문자 형식 Case 대소문자 - Kerning 커닝 @msg {label} must be a number {label}은(는) 숫자여야 합니다 @msg {label} must be a number of at least 0.1 {label}은(는) 0.1 이상의 숫자여야 합니다 @msg no character style `{name}` 문자 스타일 `{name}`을 찾을 수 없습니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8104acb32e..092e5e9447 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5735,7 +5735,6 @@ anchor Points: Punkty: Dot Color from Art Kolor kropek z kompozycji Basic Character Formats Podstawowe formaty znaków Case Wielkość liter - Kerning Kerning @msg {label} must be a number {label} musi być liczbą @msg {label} must be a number of at least 0.1 {label} musi być liczbą co najmniej 0,1 @msg no character style `{name}` Nie znaleziono stylu znakowego `{name}` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index dbccb87c74..d9a1a94f1e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5798,7 +5798,6 @@ anchor Points: Pontos: Dot Color from Art Cor dos Pontos da Arte Basic Character Formats Formatos básicos de caracteres Case Maiúsculas e minúsculas - Kerning Kerning @msg {label} must be a number {label} deve ser um número @msg {label} must be a number of at least 0.1 {label} deve ser um número de pelo menos 0,1 @msg no character style `{name}` Estilo de caractere `{name}` não encontrado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9419aeb42d..d364faf0a0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5858,7 +5858,6 @@ anchor Points: Точки: Dot Color from Art Цвет точек из рисунка Basic Character Formats Основные форматы символов Case Регистр - Kerning Кернинг @msg {label} must be a number {label} должно быть числом @msg {label} must be a number of at least 0.1 {label} должно быть числом не меньше 0,1 @msg no character style `{name}` Стиль символов `{name}` не найден diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 616c5f319a..e01793d233 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5933,7 +5933,6 @@ shape Open Öppen Dot Color from Art Punktfärg från objekt Basic Character Formats Grundläggande teckenformat Case Skiftläge - Kerning Kerning @msg {label} must be a number {label} måste vara ett tal @msg {label} must be a number of at least 0.1 {label} måste vara ett tal på minst 0,1 @msg no character style `{name}` Teckenformatet `{name}` hittades inte diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7d84df263f..32bb794bca 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5838,7 +5838,6 @@ anchor Points: Noktalar: Dot Color from Art Nokta Rengini Sanattan Al Basic Character Formats Temel karakter biçimleri Case Büyük küçük harf - Kerning Karakter aralığı @msg {label} must be a number {label} bir sayı olmalıdır @msg {label} must be a number of at least 0.1 {label} en az 0,1 olan bir sayı olmalıdır @msg no character style `{name}` `{name}` karakter stili bulunamadı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index aeaffaaac5..835a75efcf 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5479,7 +5479,6 @@ anchor Points: Точки: Dot Color from Art Колір точок із малюнка Basic Character Formats Основні формати символів Case Регістр - Kerning Кернінг @msg {label} must be a number {label} має бути числом @msg {label} must be a number of at least 0.1 {label} має бути числом не менше 0,1 @msg no character style `{name}` Стиль символів `{name}` не знайдено diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 3f3292be39..6da79b33ea 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5481,7 +5481,6 @@ anchor Points: Điểm: Dot Color from Art Màu chấm theo tác phẩm Basic Character Formats Định dạng ký tự cơ bản Case Chữ hoa và chữ thường - Kerning Điều chỉnh khoảng cách cặp chữ @msg {label} must be a number {label} phải là một số @msg {label} must be a number of at least 0.1 {label} phải là một số ít nhất bằng 0,1 @msg no character style `{name}` Không tìm thấy kiểu ký tự `{name}` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index cf2ae14bff..2912cf6d2a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5722,7 +5722,6 @@ anchor Points: 点: Dot Color from Art 网点颜色取自图稿 Basic Character Formats 基本字符格式 Case 大小写 - Kerning 字偶间距 @msg {label} must be a number {label} 必须是数字 @msg {label} must be a number of at least 0.1 {label} 必须是至少 0.1 的数字 @msg no character style `{name}` 找不到字符样式 `{name}` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f8c302079b..b814e29917 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5518,7 +5518,6 @@ anchor Points: 點: Dot Color from Art 網點顏色取自圖稿 Basic Character Formats 基本字元格式 Case 大小寫 - Kerning 字偶間距 @msg {label} must be a number {label} 必須是數字 @msg {label} must be a number of at least 0.1 {label} 必須是至少 0.1 的數字 @msg no character style `{name}` 找不到字元樣式 `{name}` From 777ad6765c772fa4c2b298a438c47b34ac858357 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 21:31:38 -0700 Subject: [PATCH 35/70] File formats: JPEG 2000 images open and place MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Open and File › Place read JP2 files and raw JPEG 2000 codestreams (.jpf, .jpx, .jp2, .j2k, .j2c, .jpc) through hayro-jpeg2000, and store the pixels as PNG. Gray, RGB, CMYK and ICC-tagged images, with or without alpha, are converted to RGBA. Several codestreams, JPX composition or layers, other color spaces, inconsistent or oversize palettes, inconsistent channel definitions, oversize tile grids and images past the pixel allowance are refused with a message before the pixels are decoded. The capture and display resolution boxes size the image: the box that comes last sets each axis, and an axis without a usable value uses 72 ppi. IccProfile::to_srgb_into converts a pixel with the cached transform and no heap allocation. --- ASSETS.md | 3 + Cargo.lock | 1 + crates/color/src/cms/icc.rs | 15 +- crates/engine/Cargo.toml | 1 + crates/engine/src/cmd/fileio.rs | 3 + crates/engine/src/cmd/fileio/formats.rs | 18 +- crates/engine/src/cmd/fileio/jp2read.rs | 279 +++++++++++++++++ crates/engine/src/cmd/fileio/load.rs | 6 + crates/engine/src/cmd/fileio/ppi.rs | 37 ++- crates/engine/src/cmd/fileio/tests_jp2read.rs | 293 ++++++++++++++++++ .../fixtures/jpeg2000/checker-300ppi.jp2 | Bin 0 -> 265 bytes .../tests/fixtures/jpeg2000/checker-raw.j2k | Bin 0 -> 154 bytes .../tests/fixtures/jpeg2000/checker.jp2 | Bin 0 -> 239 bytes crates/engine/tests/import_fuzz.rs | 25 ++ crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/file-format-parity.md | 4 +- docs/mcp.md | 4 +- docs/releasing.md | 2 +- docs/target-app-parity.md | 7 +- 40 files changed, 728 insertions(+), 14 deletions(-) create mode 100644 crates/engine/src/cmd/fileio/jp2read.rs create mode 100644 crates/engine/src/cmd/fileio/tests_jp2read.rs create mode 100644 crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2 create mode 100644 crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k create mode 100644 crates/engine/tests/fixtures/jpeg2000/checker.jp2 diff --git a/ASSETS.md b/ASSETS.md index 5bebefae63..3233c99d0e 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -345,6 +345,9 @@ Generated-in-code art is original and has no file to list. This covers the defau | `examples/ribbons.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | | `examples/feature-sheet.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | | `examples/perspective-city.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | +| `crates/engine/tests/fixtures/jpeg2000/checker.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `3de9c2bb5b8aaec241d939b795002a68eb3d50e41d51c43368000804ad3de057` | +| `crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `76fa51ab8ccbc2534098b26b8e7fe16dd886e2b6298ba52d06a6b1bde9b61d9e` | +| `crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `1b1aeed8975d3cdc832da6ecf5855852d07d0c490105121e61a8aefb31af009b` | ## Assets embedded by the PDF backend diff --git a/Cargo.lock b/Cargo.lock index 9362671b07..934be1b120 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6208,6 +6208,7 @@ dependencies = [ "craft-docpath", "crc32fast", "flate2", + "hayro-jpeg2000", "image", "kurbo 0.13.1", "log", diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 8201b8b97f..64f42f25b9 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -149,11 +149,20 @@ impl IccProfile { /// Device values (RGB / CMYK / Gray, 0..1) → sRGB. pub fn to_srgb(&self, v: &[f32], intent: Intent) -> Option<[f32; 3]> { + let mut src = [0.0f32; 4]; + let channels = self.channels(); + src.get_mut(..channels)?.iter_mut().zip(v.iter()).for_each(|(dst, value)| *dst = *value); + self.to_srgb_into(src.get(..channels)?, intent) + } + + /// Convert an exact-width device pixel using the cached transform and stack storage. + pub fn to_srgb_into(&self, v: &[f32], intent: Intent) -> Option<[f32; 3]> { + if v.len() != self.channels() { + return None; + } let xf = self.to_xf(intent)?; - let mut src = v.to_vec(); - src.resize(self.channels(), 0.0); let mut dst = [0.0f32; 3]; - xf.transform(&src, &mut dst).ok()?; + xf.transform(v, &mut dst).ok()?; Some(dst.map(|x| x.clamp(0.0, 1.0))) } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f495697ceb..7b1199277b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -36,6 +36,7 @@ vectorcraft-plugins = { workspace = true } vectorcraft-affinity = { workspace = true } vectorcraft-scriptcheck = { workspace = true } image = { workspace = true } +hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] } flate2 = { workspace = true } # The XML parts of Word documents placed as type (place/docx.rs). roxmltree = "0.21" diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index c8cb7218a7..7471ffb56a 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -33,6 +33,7 @@ pub(crate) mod imagemap; mod legacy_ai; mod load; pub(crate) use load::{MAX_RASTER_ALLOC, size_note}; +mod jp2read; mod metafile; mod naming; mod native; @@ -193,6 +194,8 @@ mod tests_psd; #[cfg(test)] mod tests_psdread; +#[cfg(test)] +mod tests_jp2read; #[cfg(test)] mod tests_pcxread; diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index f727215341..a1687e214f 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -491,6 +491,8 @@ pub const FORMATS: &[Format] = &[ reader("ps", "PostScript", &["ps"], "application/postscript", false), // ZSoft PCX images, read by `pcxread` and stored as PNG; exports don't write them. reader("pcx", "PCX", &["pcx"], "image/x-pcx", true), + // JP2 and raw codestreams are decoded to PNG; JPX composition is not supported. + reader("jpeg2000", "JPEG 2000", &["jpf", "jpx", "jp2", "j2k", "j2c", "jpc"], "image/jp2", true), ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). @@ -515,6 +517,12 @@ pub const OPEN_EXTS: &[&str] = &[ "icb", "vst", "pcx", + "jpf", + "jpx", + "jp2", + "j2k", + "j2c", + "jpc", "psd", "psb", "vctemplate", @@ -531,10 +539,10 @@ pub const OPEN_EXTS: &[&str] = &[ /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to /// raster editors, so Finder and file managers don't offer a vector app for them, and there is no -/// `.epsf`, `.ps`, Targa or PCX type (File › Open and Place still read them all). On Linux the +/// `.epsf`, `.ps`, Targa, PCX or JPEG 2000 type (File › Open and Place still read them all). On Linux the /// desktop entry's EPS type (shared-mime-info's) also covers `.epsf`, so file managers offer /// VectorCraft for it. -pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst", "pcx"]; +pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst", "pcx", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc"]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares /// `.png` with PNG, so `.png` comes once), in [`FORMATS`] order. @@ -581,6 +589,12 @@ pub const PLACE_EXTS: &[&str] = &[ "icb", "vst", "pcx", + "jpf", + "jpx", + "jp2", + "j2k", + "j2c", + "jpc", "psd", "psb", "vctemplate", diff --git a/crates/engine/src/cmd/fileio/jp2read.rs b/crates/engine/src/cmd/fileio/jp2read.rs new file mode 100644 index 0000000000..9e0752c2c5 --- /dev/null +++ b/crates/engine/src/cmd/fileio/jp2read.rs @@ -0,0 +1,279 @@ +//! JPEG 2000 JP2 and codestream images for File › Open and File › Place. The decoded image is +//! bounded before allocation and converted to RGBA for the common PNG storage path. + +use hayro_jpeg2000::{ColorSpace, DecodeSettings, DecoderContext, Image}; +use vectorcraft_color::cms::{IccProfile, Intent}; + +/// Recognize a JP2 signature box or the start of a raw codestream. The decoder checks the rest. +pub(super) fn is_jpeg2000(bytes: &[u8]) -> bool { + bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") || bytes.starts_with(b"\xff\x4f") +} + +/// Boxes at one JP2 nesting level. Invalid lengths stop the walk at that level. +pub(super) fn boxes(b: &[u8]) -> impl Iterator { + let mut at = 0usize; + std::iter::from_fn(move || { + let header = b.get(at..at.checked_add(8)?)?; + let size = u32::from_be_bytes(header.get(..4)?.try_into().ok()?); + let (length, head) = match size { + 0 => (b.len().checked_sub(at)?, 8usize), + 1 => (usize::try_from(u64::from_be_bytes(b.get(at.checked_add(8)?..at.checked_add(16)?)?.try_into().ok()?)).ok()?, 16usize), + n => (n as usize, 8usize), + }; + if length < head { + return None; + } + let end = at.checked_add(length)?; + let data = b.get(at.checked_add(head)?..end)?; + let ty = header.get(4..8)?; + at = end; + Some((ty, data)) + }) +} + +/// The decoder ignores JPX layers and composition and silently uses the last top-level jp2c. +fn unsupported_jpx_content(bytes: &[u8]) -> bool { + fn association_has_content(data: &[u8], depth: usize) -> bool { + if depth >= 16 { + return true; + } + boxes(data).any(|(ty, child)| { + matches!(ty, b"jp2c" | b"jpch" | b"jplh" | b"comp" | b"ftbl") || (ty == b"asoc" && association_has_content(child, depth + 1)) + }) + } + let mut codestreams = 0u8; + for (ty, data) in boxes(bytes) { + match ty { + b"jp2c" => { + codestreams = codestreams.saturating_add(1); + if codestreams > 1 { + return true; + } + } + b"jpch" | b"jplh" | b"comp" | b"ftbl" => return true, + b"asoc" if association_has_content(data, 0) => return true, + _ => {} + } + } + false +} + +/// The largest embedded ICC profile read. +const MAX_PROFILE: usize = 4 * 1024 * 1024; +/// A codestream numbers its tiles 0 to 65,534 (Isot in SOT, ITU-T T.800 A.4.2). +const MAX_TILES: u64 = 65_535; +/// Bytes the decoder keeps for each component of each tile before decoding any of them. +const TILE_COMPONENT_BYTES: u64 = 256; + +/// SIZ follows SOC in the codestream; Lsiz includes its two length bytes. Returns the component +/// count, the image size and the tile count. +fn codestream_size(bytes: &[u8]) -> Option<(u64, u32, u32, u64)> { + let stream = if bytes.starts_with(b"\xff\x4f") { bytes } else { boxes(bytes).find_map(|(ty, data)| (ty == b"jp2c").then_some(data))? }; + if stream.get(..4)? != b"\xff\x4f\xff\x51" { + return None; + } + let length = u16::from_be_bytes(stream.get(4..6)?.try_into().ok()?) as usize; + let count = u16::from_be_bytes(stream.get(40..42)?.try_into().ok()?) as usize; + if count == 0 || length != 38usize.checked_add(count.checked_mul(3)?)? || stream.get(4..4usize.checked_add(length)?)?.len() != length { + return None; + } + let be32 = |range: std::ops::Range| stream.get(range).and_then(|v| v.try_into().ok()).map(u32::from_be_bytes); + let width = be32(8..12)?.checked_sub(be32(16..20)?)?; + let height = be32(12..16)?.checked_sub(be32(20..24)?)?; + // Tiles across and down (T.800 B-5): the grid from the tile offset, in whole tiles. + let tiles = |grid: u32, offset: u32, tile: u32| match (grid.checked_sub(offset), tile) { + (Some(span), 1..) => Some(u64::from(span).div_ceil(u64::from(tile))), + _ => None, + }; + let across = tiles(be32(8..12)?, be32(32..36)?, be32(24..28)?)?; + let down = tiles(be32(12..16)?, be32(36..40)?, be32(28..32)?)?; + Some((count as u64, width, height, across.checked_mul(down)?)) +} + +/// One `jp2h` header with at most one palette, component mapping and channel definition box, so +/// the checks below read the boxes the decoder uses. +fn single_header_boxes(bytes: &[u8]) -> bool { + let mut headers = boxes(bytes).filter(|(ty, _)| *ty == b"jp2h"); + let (Some((_, header)), None) = (headers.next(), headers.next()) else { + return false; + }; + [b"pclr", b"cmap", b"cdef"].iter().all(|kind| boxes(header).filter(|(ty, _)| ty == kind).count() <= 1) +} + +/// The number of channel definitions in a JP2 `cdef` box, `None` without one. Only color channels +/// 1 to n, in any order, followed by at most one opacity channel for the whole image are read; +/// any other layout (premultiplied opacity, opacity before a color, an unassociated channel) gives +/// `Some(0)`, which no image matches. +fn channel_definitions(bytes: &[u8]) -> Option { + if bytes.starts_with(b"\xff\x4f") { + return None; + } + let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data))?; + let cdef = boxes(header).find_map(|(ty, data)| (ty == b"cdef").then_some(data))?; + let count = cdef.get(..2).and_then(|n| n.try_into().ok()).map_or(0, |n: [u8; 2]| usize::from(u16::from_be_bytes(n))); + let Some(entries) = cdef.get(2..).filter(|rest| count > 0 && rest.len() == count * 6) else { + return Some(0); + }; + // (channel, type, association) by channel. + let mut defs: Vec<[u16; 3]> = + entries.as_chunks::<6>().0.iter().map(|&[a, b, c, d, e, f]| [[a, b], [c, d], [e, f]].map(u16::from_be_bytes)).collect(); + defs.sort_unstable(); + let opacity = defs.last().is_some_and(|&[_, kind, association]| kind == 1 && association == 0); + let colors = defs.len() - usize::from(opacity); + let mut seen = vec![false; colors]; + let layout_ok = defs.iter().enumerate().all(|(i, &[channel, kind, association])| { + usize::from(channel) == i + && (i >= colors + || (kind == 0 + && usize::from(association).checked_sub(1).and_then(|slot| seen.get_mut(slot)).is_some_and(|s| !std::mem::replace(s, true)))) + }); + Some(if layout_ok { defs.len() as u64 } else { 0 }) +} + +/// The column count of a JP2 palette (`pclr`), `Ok(None)` without one. A component mapping (`cmap`) +/// beside it needs one entry per column, each naming a codestream component and, when it maps +/// through the palette, a palette column; anything else is `Err`. +fn palette_columns(bytes: &[u8], components: u64) -> Result, ()> { + if bytes.starts_with(b"\xff\x4f") { + return Ok(None); + } + let Some(header) = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)) else { + return Ok(None); + }; + let Some(palette) = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then_some(data)) else { + return Ok(None); + }; + let columns = palette.get(2).copied().ok_or(())?; + // Each column's descriptor: unsigned, 1 to 31 bits, as codestream samples are. + let depths = palette.get(3..3 + usize::from(columns)).ok_or(())?; + if columns == 0 || depths.iter().any(|&d| d & 0x80 != 0 || (d & 0x7f) + 1 > 31) { + return Err(()); + } + // Without a mapping the decoder maps every column from the first component. + let Some(mapping) = boxes(header).find_map(|(ty, data)| (ty == b"cmap").then_some(data)) else { + return Ok(Some(u64::from(columns))); + }; + if mapping.len() != usize::from(columns) * 4 { + return Err(()); + } + for &[c0, c1, kind, column] in mapping.as_chunks::<4>().0 { + let valid = u64::from(u16::from_be_bytes([c0, c1])) < components + && match kind { + 0 => true, + 1 => column < columns, + _ => false, + }; + if !valid { + return Err(()); + } + } + Ok(Some(u64::from(columns))) +} + +/// Decode within the raster allocation allowance, counting source samples, RGBA output, and +/// decoder intermediates. The decoder may need multiple full-sized component planes. +pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result { + if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && unsupported_jpx_content(bytes) { + return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()); + } + if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && !single_header_boxes(bytes) { + return Err("the JPEG 2000 file can't be read".into()); + } + let (codestream_channels, declared_w, declared_h, tile_count) = codestream_size(bytes).ok_or("the JPEG 2000 file can't be read")?; + if tile_count == 0 || tile_count > MAX_TILES { + return Err("the JPEG 2000 file can't be read".into()); + } + let declared_pixels = u64::from(declared_w).checked_mul(u64::from(declared_h)); + if declared_w == 0 + || declared_h == 0 + || declared_pixels.and_then(|n| n.checked_mul(codestream_channels)).and_then(|n| n.checked_mul(4)).is_none_or(|n| n > max_alloc) + || tile_count.checked_mul(codestream_channels).and_then(|n| n.checked_mul(TILE_COMPONENT_BYTES)).is_none_or(|n| n > max_alloc) + { + return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw")); + } + // The decoder copies an embedded profile (after a 3-byte `colr` header) when it reads the file. + let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap_or_default(); + if boxes(header).any(|(ty, data)| ty == b"colr" && data.len() > MAX_PROFILE + 3) { + return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()); + } + let palette = palette_columns(bytes, codestream_channels).map_err(|()| "the JPEG 2000 file can't be read")?; + // The decoder keeps each palette value in 8 bytes and each row in its own list. + let palette_rows = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then(|| data.get(..2)).flatten()); + if let (Some(columns), Some(&[r0, r1])) = (palette, palette_rows) + && u64::from(u16::from_be_bytes([r0, r1])) * (columns * 8 + 24) > max_alloc + { + return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw")); + } + let image = Image::new(bytes, &DecodeSettings::default()).map_err(|_| "the JPEG 2000 file can't be read")?; + let (w, h) = (image.width(), image.height()); + let color = image.color_space(); + let channels = match color { + ColorSpace::Gray => 1, + ColorSpace::RGB => 3, + ColorSpace::CMYK => 4, + ColorSpace::Icc { num_channels: 1 | 3 | 4, profile } if profile.len() <= MAX_PROFILE => color.num_channels(), + _ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()), + }; + let stride = u64::from(channels) + u64::from(image.has_alpha()); + // The decoder sizes its output by the palette's columns and writes one channel per mapping + // entry, so the columns, the entries and the output channels must all match. + if palette.is_some_and(|columns| columns != stride) { + return Err("the JPEG 2000 file can't be read".into()); + } + // The decoder reorders the channels by their definitions (`cdef`) and drops any channel without + // one, so a definition is needed for every channel it writes. + if channel_definitions(bytes).is_some_and(|count| count != stride || count != palette.unwrap_or(codestream_channels)) { + return Err("the JPEG 2000 file can't be read".into()); + } + let plane_channels = codestream_channels.max(stride).max(palette.unwrap_or(0)); + let too_large = || format!("an image of {w} × {h} pixels is too large to draw"); + let pixels = u64::from(w).checked_mul(u64::from(h)).ok_or_else(too_large)?; + let size = pixels.checked_mul(stride).ok_or_else(too_large)?; + let rgba_size = pixels.checked_mul(4).ok_or_else(too_large)?; + // hayro 0.3.5 keeps a f32 plane per component, including alpha, and a second + // f32 coefficient plane per component. Palette mapping or channel definitions + // can temporarily clone the component planes. Reserve another 8 bytes per + // pixel for IDWT and code-block scratch while samples and RGBA coexist. + let plane_bytes = pixels.checked_mul(plane_channels).and_then(|n| n.checked_mul(4)).ok_or_else(too_large)?; + let scratch_bytes = plane_bytes.checked_mul(2).and_then(|n| n.checked_add(pixels.checked_mul(8)?)).ok_or_else(too_large)?; + let working = + size.checked_add(rgba_size).and_then(|n| n.checked_add(plane_bytes)).and_then(|n| n.checked_add(scratch_bytes)).ok_or_else(too_large)?; + if w == 0 || h == 0 || working > max_alloc { + return Err(too_large()); + } + let len = usize::try_from(size).map_err(|_| too_large())?; + let mut samples = vec![0; len]; + image.decode_into(&mut samples, &mut DecoderContext::default()).map_err(|_| "the JPEG 2000 file can't be read")?; + let profile = match color { + ColorSpace::Icc { profile, .. } => { + Some(IccProfile::from_bytes(None, profile).map_err(|_| "the JPEG 2000 file has an unsupported color space or JPX content")?) + } + _ => None, + }; + let cms = vectorcraft_color::cms::active(); + let mut rgba = Vec::with_capacity(usize::try_from(rgba_size).map_err(|_| too_large())?); + for sample in samples.chunks_exact(stride as usize) { + let at = |i: usize| sample.get(i).copied().unwrap_or(0); + let rgb = match (color, profile.as_ref()) { + (ColorSpace::Gray, _) => [at(0); 3], + (ColorSpace::RGB, _) => [at(0), at(1), at(2)], + (ColorSpace::CMYK, _) => { + cms.cmyk_to_srgb([at(0), at(1), at(2), at(3)].map(|v| f32::from(v) / 255.0), false).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) + } + (ColorSpace::Icc { .. }, Some(profile)) => { + let mut values = [0.0f32; 4]; + for (dst, src) in values.iter_mut().zip(sample.iter().take(usize::from(channels))) { + *dst = f32::from(*src) / 255.0; + } + profile + .to_srgb_into(&values[..usize::from(channels)], Intent::RelativeColorimetric) + .ok_or("the JPEG 2000 file has an unsupported color space or JPX content")? + .map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) + } + _ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()), + }; + let [r, g, b] = rgb; + rgba.extend_from_slice(&[r, g, b, if image.has_alpha() { at(usize::from(channels)) } else { 255 }]); + } + image::RgbaImage::from_raw(w, h, rgba).ok_or_else(|| "the JPEG 2000 file can't be read".into()) +} diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index c2e58e39e7..0083130695 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -97,6 +97,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if psdread::is_psd(bytes) { return format(if psdread::is_psb(bytes) { "psb" } else { "psd" }); } + if super::jp2read::is_jpeg2000(bytes) { + return format("jpeg2000"); + } if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) { return Some(f); } @@ -631,6 +634,9 @@ pub fn raster_image(bytes: &[u8]) -> Result { let cms = vectorcraft_color::cms::active(); return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, ppi); } + if super::jp2read::is_jpeg2000(bytes) { + return as_png(super::jp2read::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi); + } let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?; if reader.format().is_none() && super::tgaread::is_targa(bytes) { reader.set_format(image::ImageFormat::Tga); diff --git a/crates/engine/src/cmd/fileio/ppi.rs b/crates/engine/src/cmd/fileio/ppi.rs index 61b7417567..fd2ffbf8c2 100644 --- a/crates/engine/src/cmd/fileio/ppi.rs +++ b/crates/engine/src/cmd/fileio/ppi.rs @@ -1,6 +1,6 @@ //! Image resolution metadata (pixels per inch): PNG `pHYs`, JPEG JFIF density or EXIF, TIFF and //! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo, a PCX -//! header's HDpi and VDpi. Place +//! header's HDpi and VDpi, or JP2 capture and display resolution boxes. Place //! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it //! as a `pHYs` chunk. @@ -24,12 +24,47 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { super::psdread::resolution(bytes) } else if super::pcxread::is_pcx(bytes) { super::pcxread::resolution(bytes) + } else if super::jp2read::is_jpeg2000(bytes) { + jp2(bytes) } else { None }; r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v))) } +fn jp2_axis(n: u16, d: u16, e: i8) -> Option { + if d == 0 { + return None; + } + let ppi = f64::from(n) / f64::from(d) * 10f64.powi(i32::from(e)) * INCH_M; + (ppi.is_finite() && (1.0..=100_000.0).contains(&ppi)).then_some(ppi) +} + +/// JP2 resolution is independent on each axis. Later capture or display boxes replace earlier +/// valid values for that axis; an invalid later axis leaves the earlier value intact. +fn jp2(b: &[u8]) -> Option<(f64, f64)> { + if !b.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") { + return Some((72.0, 72.0)); + } + let (mut x, mut y) = (None, None); + for (_, header) in super::jp2read::boxes(b).filter(|(ty, _)| *ty == b"jp2h") { + for (_, res) in super::jp2read::boxes(header).filter(|(ty, _)| *ty == b"res ") { + for (_, data) in super::jp2read::boxes(res).filter(|(ty, _)| *ty == b"resc" || *ty == b"resd") { + let Some([vn0, vn1, vd0, vd1, hn0, hn1, hd0, hd1, ve, he]): Option<[u8; 10]> = data.get(..10).and_then(|v| v.try_into().ok()) else { + continue; + }; + if let Some(value) = jp2_axis(u16::from_be_bytes([hn0, hn1]), u16::from_be_bytes([hd0, hd1]), he as i8) { + x = Some(value); + } + if let Some(value) = jp2_axis(u16::from_be_bytes([vn0, vn1]), u16::from_be_bytes([vd0, vd1]), ve as i8) { + y = Some(value); + } + } + } + } + Some((x.unwrap_or(72.0), y.unwrap_or(72.0))) +} + /// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either). fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> { b.get(at..at.checked_add(n)?) diff --git a/crates/engine/src/cmd/fileio/tests_jp2read.rs b/crates/engine/src/cmd/fileio/tests_jp2read.rs new file mode 100644 index 0000000000..54481c4038 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_jp2read.rs @@ -0,0 +1,293 @@ +//! JPEG 2000 Open, Place, pixel and resolution regressions using original synthetic fixtures. + +use serde_json::json; + +use super::jp2read::is_jpeg2000; +use super::*; + +const JP2: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker.jp2"); +const RAW: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker-raw.j2k"); +const PPI300: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker-300ppi.jp2"); +const COLORS: [[u8; 4]; 4] = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]]; + +fn pixels(bytes: &[u8]) -> Vec<[u8; 4]> { + let raster = load::raster_image(bytes).unwrap(); + image::load_from_memory(&raster.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() +} + +fn boxed(ty: &[u8; 4], data: &[u8]) -> Vec { + let mut out = ((data.len() + 8) as u32).to_be_bytes().to_vec(); + out.extend(ty); + out.extend(data); + out +} + +fn with_resolution(children: &[Vec]) -> Vec { + let mut file = JP2.to_vec(); + let at = file.windows(4).position(|w| w == b"jp2h").unwrap() - 4; + let old_len = u32::from_be_bytes(file[at..at + 4].try_into().unwrap()) as usize; + let mut header = file[at + 8..at + old_len].to_vec(); + if !children.is_empty() { + header.extend(boxed(b"res ", &children.concat())); + } + file.splice(at..at + old_len, boxed(b"jp2h", &header)); + file +} + +fn res(ty: &[u8; 4], vr: u16, hr: u16) -> Vec { + let mut data = Vec::new(); + for n in [vr, hr] { + data.extend(n.to_be_bytes()); + data.extend(254u16.to_be_bytes()); + } + data.extend([2, 2]); + boxed(ty, &data) +} + +#[test] +fn checker_opens_and_places_with_exact_pixels() { + for (name, bytes) in [("checker.jp2", JP2), ("checker-raw.j2k", RAW)] { + assert_eq!(pixels(bytes), COLORS, "{name}"); + let mut s = Session::new(); + let encoded = vectorcraft_format::base64_encode(bytes); + let opened = s.execute("document.open", &json!({"name": name, "dataBase64": encoded})).unwrap(); + assert_eq!(opened["format"], "jpeg2000"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(2.0, 2.0)); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::>(), COLORS); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let placed = s.execute("file.place", &json!({"name": name, "dataBase64": encoded})).unwrap(); + assert_eq!(placed["format"], "jpeg2000"); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::>(), COLORS); + assert!(load::texture_image(bytes).is_ok()); + } +} + +#[test] +fn signatures_and_every_extension() { + assert!(is_jpeg2000(JP2) && is_jpeg2000(RAW)); + for ext in ["jpf", "jpx", "jp2", "j2k", "j2c", "jpc"] { + assert_eq!(load::detect(&format!("a.{ext}"), b"invalid").map(|f| f.id), Some("jpeg2000")); + assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext)); + } + assert_eq!(load::detect("unknown.bin", JP2).map(|f| f.id), Some("jpeg2000")); + assert_eq!(load::detect("unknown.bin", RAW).map(|f| f.id), Some("jpeg2000")); +} + +#[test] +fn resolution_boxes_use_last_valid_axis_and_72_fallback() { + let check = |children: &[Vec], want: (f64, f64)| { + let file = with_resolution(children); + let got = ppi::resolution(&file).unwrap(); + assert!((got.0 - want.0).abs() < 0.01 && (got.1 - want.1).abs() < 0.01, "{got:?} != {want:?}"); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "a.jp2", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap(); + let size = s.doc().unwrap().doc.artboards[0].rect.size(); + assert!((size.width - 144.0 / want.0).abs() < 0.01 && (size.height - 144.0 / want.1).abs() < 0.01); + }; + check(&[], (72.0, 72.0)); + check(&[res(b"resc", 30000, 30000)], (300.0, 300.0)); + check(&[res(b"resd", 15000, 15000)], (150.0, 150.0)); + check(&[res(b"resc", 30000, 30000), res(b"resd", 15000, 15000)], (150.0, 150.0)); + check(&[res(b"resd", 15000, 15000), res(b"resc", 30000, 30000)], (300.0, 300.0)); + check(&[res(b"resc", 30000, 15000)], (150.0, 300.0)); + assert_eq!(ppi::resolution(RAW), Some((72.0, 72.0))); + assert!((ppi::resolution(PPI300).unwrap().0 - 300.0).abs() < 0.01); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "a.jp2", "dataBase64": vectorcraft_format::base64_encode(PPI300)})).unwrap(); + let size = s.doc().unwrap().doc.artboards[0].rect.size(); + assert!((size.width - 0.48).abs() < 0.001 && (size.height - 0.48).abs() < 0.001); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + let stored = ppi::resolution(&blob.bytes).unwrap(); + assert!((stored.0 - 300.0).abs() < 0.01 && (stored.1 - 300.0).abs() < 0.01); +} + +#[test] +fn malformed_resolution_and_image_data_are_bounded() { + let good = res(b"resc", 30000, 15000); + let mut zero = res(b"resd", 15000, 15000); + zero[10..12].copy_from_slice(&0u16.to_be_bytes()); + let got = ppi::resolution(&with_resolution(&[good.clone(), zero])).unwrap(); + assert!((got.0 - 150.0).abs() < 0.01 && (got.1 - 300.0).abs() < 0.01); + let short = boxed(b"resd", &[0; 9]); + assert!(ppi::resolution(&with_resolution(&[good.clone(), short])).unwrap().0 > 149.0); + assert_eq!(ppi::resolution(&with_resolution(&[boxed(b"resc", &[0; 9])])), Some((72.0, 72.0))); + let mut over = good.clone(); + over[..4].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(ppi::resolution(&with_resolution(&[over])), Some((72.0, 72.0))); + let mut outer_over = JP2.to_vec(); + let jp2h = outer_over.windows(4).position(|w| w == b"jp2h").unwrap() - 4; + outer_over[jp2h..jp2h + 4].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(ppi::resolution(&outer_over), Some((72.0, 72.0))); + let mut extended = Vec::from(1u32.to_be_bytes()); + extended.extend(b"resd"); + extended.extend(26u64.to_be_bytes()); + extended.extend(&res(b"resd", 15000, 30000)[8..]); + assert!(ppi::resolution(&with_resolution(&[extended])).unwrap().0 > 299.0); + let mut to_end = res(b"resd", 15000, 30000); + to_end[..4].copy_from_slice(&0u32.to_be_bytes()); + assert!(ppi::resolution(&with_resolution(&[to_end])).unwrap().0 > 299.0); + for bytes in [&JP2[..12], &RAW[..4], &JP2[..JP2.len() - 5]] { + assert!(load::raster_image(bytes).is_err()); + } + assert!(super::jp2read::decode(JP2, 8).is_err()); + // RGBA (16 bytes) and the float component planes (48 bytes) each fit; + // their concurrent allocation with samples and scratch does not. + assert!(super::jp2read::decode(JP2, 80).unwrap_err().contains("too large to draw")); + let mut huge = RAW.to_vec(); + huge[8..12].copy_from_slice(&100_000u32.to_be_bytes()); + huge[12..16].copy_from_slice(&100_000u32.to_be_bytes()); + assert!(load::raster_image(&huge).is_err()); + let mut jpx = JP2.to_vec(); + jpx.extend(boxed(b"jp2c", RAW)); + assert!(load::raster_image(&jpx).err().unwrap().to_string().contains("unsupported color space or JPX content")); + let mut layered = JP2.to_vec(); + layered.extend(boxed(b"jpch", &[])); + assert!(load::raster_image(&layered).err().unwrap().to_string().contains("unsupported color space or JPX content")); + let mut wrapped = JP2.to_vec(); + wrapped.extend(boxed(b"asoc", &boxed(b"jp2c", RAW))); + assert!(load::raster_image(&wrapped).err().unwrap().to_string().contains("unsupported color space or JPX content")); +} + +#[test] +fn compatible_jpx_brand_alone_keeps_checker_pixels() { + let mut branded = JP2.to_vec(); + branded[12..16].copy_from_slice(&24u32.to_be_bytes()); + branded.splice(32..32, b"jpx ".iter().copied()); + assert_eq!(pixels(&branded), COLORS); +} + +#[test] +fn codestream_component_count_bounds_decode_planes() { + assert_eq!(super::jp2read::decode(RAW, 1000).unwrap().pixels().map(|p| p.0).collect::>(), COLORS); + let mut many = RAW.to_vec(); + let component = many[42..45].to_vec(); + many.splice(42..42, component.repeat(17)); + many[4..6].copy_from_slice(&98u16.to_be_bytes()); // 38 + 3 * 20 + many[40..42].copy_from_slice(&20u16.to_be_bytes()); + assert!(super::jp2read::decode(&many, 1000).unwrap_err().contains("too large to draw")); + many[0..4].copy_from_slice(&[0, 0, 0, 0]); + assert!(super::jp2read::decode(&many, 1000).unwrap_err().contains("can't be read")); +} + +fn with_header_boxes(extra: &[Vec]) -> Vec { + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + let mut children = header.to_vec(); + children.extend(extra.concat()); + super::jp2read::boxes(JP2) + .map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>() + .concat() +} + +#[test] +fn channel_definitions_must_cover_every_channel() { + // (channel, type, association): color channels 1 to 3, an opacity channel (type 1). + let cdef = |defs: &[[u16; 3]]| { + let mut data = (defs.len() as u16).to_be_bytes().to_vec(); + data.extend(defs.iter().flatten().flat_map(|v| v.to_be_bytes())); + boxed(b"cdef", &data) + }; + assert_eq!(pixels(&with_header_boxes(&[cdef(&[[0, 0, 1], [1, 0, 2], [2, 0, 3]])])), COLORS); + // Channel 0 as green and channel 1 as red swap the two. + let swapped = [[0, 255, 0, 255], [255, 0, 0, 255], [0, 0, 255, 255], [255; 4]]; + assert_eq!(pixels(&with_header_boxes(&[cdef(&[[0, 0, 2], [1, 0, 1], [2, 0, 3]])])), swapped); + for defs in [ + vec![[0, 0, 1]], + vec![[0, 0, 1], [1, 0, 2], [2, 1, 0]], + vec![[0, 0, 1], [1, 0, 2], [2, 0, 3], [3, 1, 0]], + // Opacity first, a premultiplied opacity, a repeated color, an unassociated color. + vec![[0, 1, 0], [1, 0, 1], [2, 0, 2]], + vec![[0, 0, 1], [1, 0, 2], [2, 2, 0]], + vec![[0, 0, 1], [1, 0, 1], [2, 0, 3]], + vec![[0, 0, 1], [1, 0, 2], [2, 0, 0]], + ] { + assert!(load::raster_image(&with_header_boxes(&[cdef(&defs)])).err().unwrap().to_string().contains("can't be read"), "{defs:?}"); + } + // A second definition box, and a second header, are refused. + let full = cdef(&[[0, 0, 1], [1, 0, 2], [2, 0, 3]]); + assert!(load::raster_image(&with_header_boxes(&[full.clone(), cdef(&[[0, 0, 1]])])).err().unwrap().to_string().contains("can't be read")); + let mut two_headers = JP2.to_vec(); + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + two_headers.extend(boxed(b"jp2h", header)); + assert!(load::raster_image(&two_headers).err().unwrap().to_string().contains("can't be read")); +} + +#[test] +fn palette_needs_one_mapping_per_column() { + // 256 entries of three 8-bit columns, entry i being (i, i, i). + let mut palette = vec![1, 0, 3, 7, 7, 7]; + palette.extend((0..=255u8).flat_map(|i| [i; 3])); + let pclr = boxed(b"pclr", &palette); + let mut deep = vec![1, 0, 3, 7, 7, 31]; + deep.extend((0..=255u8).flat_map(|i| [i, i, 0, 0, 0, i])); + let deep = boxed(b"pclr", &deep); + let cmap = |entries: &[[u8; 4]]| boxed(b"cmap", &entries.concat()); + // Each component through its own column gives the same pixels. + let mapped = with_header_boxes(&[pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 0, 0]])]); + assert_eq!(pixels(&mapped), COLORS); + // 256 rows of three 8-byte values and a 24-byte list each (12,288 bytes) pass a 12,000-byte allowance. + assert!(super::jp2read::decode(&mapped, 12_000).unwrap_err().contains("too large to draw")); + for extra in [ + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 2], [0, 0, 1, 0]])], + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 9, 1, 2]])], + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 3]])], + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1]])], + // A 32-bit column. + vec![deep.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 2]])], + ] { + assert!(load::raster_image(&with_header_boxes(&extra)).err().unwrap().to_string().contains("can't be read")); + } +} + +#[test] +fn tile_grid_is_bounded_before_decoding() { + let tiled = |size: u32, tile: u32| { + let mut file = RAW.to_vec(); + file[8..12].copy_from_slice(&size.to_be_bytes()); + file[12..16].copy_from_slice(&size.to_be_bytes()); + file[24..28].copy_from_slice(&tile.to_be_bytes()); + file[28..32].copy_from_slice(&tile.to_be_bytes()); + file + }; + // 1,000 × 1,000 one-pixel tiles are more than a codestream can number. + assert!(super::jp2read::decode(&tiled(1000, 1), MAX_RASTER_ALLOC).unwrap_err().contains("can't be read")); + assert!(super::jp2read::decode(&tiled(2, 0), MAX_RASTER_ALLOC).unwrap_err().contains("can't be read")); + // 255 × 255 one-pixel tiles of three components need more than this allowance before decoding. + assert!(super::jp2read::decode(&tiled(255, 1), 1 << 20).unwrap_err().contains("too large to draw")); +} + +#[test] +fn cielab_images_are_refused() { + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + // Enumerated color space 14, CIELab, with its default range and offset. + let children = super::jp2read::boxes(header) + .map(|(ty, data)| if ty == b"colr" { boxed(b"colr", &[1, 0, 0, 0, 0, 0, 14]) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>(); + let file = super::jp2read::boxes(JP2) + .map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children.concat()) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>() + .concat(); + assert!(load::raster_image(&file).err().unwrap().to_string().contains("unsupported color space")); +} + +#[test] +fn embedded_srgb_profile_keeps_checker_pixels() { + let icc = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).unwrap(); + let mut colr_data = vec![2, 0, 0]; + colr_data.extend_from_slice(&icc); + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + let children = super::jp2read::boxes(header) + .map(|(ty, data)| if ty == b"colr" { boxed(b"colr", &colr_data) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>(); + let file = super::jp2read::boxes(JP2) + .map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children.concat()) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>() + .concat(); + assert_eq!(pixels(&file), COLORS); + // A profile past 4 MiB is refused before the decoder reads the file. + let mut big = vec![2, 0, 0]; + big.resize(3 + 4 * 1024 * 1024 + 1, 0); + assert!(super::jp2read::decode(&with_header_boxes(&[boxed(b"colr", &big)]), MAX_RASTER_ALLOC).unwrap_err().contains("unsupported color space")); +} diff --git a/crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2 b/crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2 new file mode 100644 index 0000000000000000000000000000000000000000..60f2c24239522c67e548ace2a185ab3a0597eda1 GIT binary patch literal 265 zcmZQzVBpCLP*C9IYUg5LU=T?wsVvAUFj4@r8KAT~kj?;d#WFKeihwi|7&CLQ18D{Z z{^b0eB1SM%07yy|r4}myX(1q;tf$Pt2*P05ML=Vc|NH+BWY7omA;y52AOfTaq7W>^ z%+AONLH~moc))UOOiT=n|6>@$6dXJ}0?^R^6b1nXMxVs8WHVzuLp?(SqyG~aKt5t% c&;{z63}&Ga)1R?0+`r$z!La@S3&a1L09t`7jQ{`u literal 0 HcmV?d00001 diff --git a/crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k b/crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k new file mode 100644 index 0000000000000000000000000000000000000000..0e2196656bb1737c0ffcb707260f718b20c62299 GIT binary patch literal 154 zcmezG|38pHp8*7zpcu?yU|M^goD!2PnwMz{bSH!1zCgK}^BH!y^C< z{ZC;KU|{q~EK4>s)-%*IG%)%y_egg-? L`U5Ns|8D{SZk#8K literal 0 HcmV?d00001 diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 12eaf13d64..10109e1ec3 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -1781,6 +1781,31 @@ proptest! { // ---------- SVG saved with hidden layers and editing data ---------- +proptest! { + #![proptest_config(config())] + + /// Mutated JP2 boxes and raw codestream markers must return errors rather than unwind. + #[test] + fn mutated_jpeg2000_files_do_not_panic(raw in any::(), cut in 0usize..300, edits in prop::collection::vec((0usize..300, any::()), 0..8)) { + let (name, mut bytes) = if raw { + ("a.j2k", include_bytes!("fixtures/jpeg2000/checker-raw.j2k").to_vec()) + } else { + ("a.jp2", include_bytes!("fixtures/jpeg2000/checker.jp2").to_vec()) + }; + for (at, byte) in edits { + if let Some(slot) = bytes.get_mut(at) { *slot = byte; } + } + bytes.truncate(cut); + let result = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + let params = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("document.open", ¶ms)); + let _ = no_panic(s.execute("file.place", ¶ms)); + }); + prop_assert!(result.is_ok(), "{name}: panicked: {:?}", result.err()); + } +} + /// The rich document with a hidden layer, saved as SVG with its editing data. fn saved_svg() -> String { let mut d = rich_doc(); diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 311580ce5e..d5f5e6dad5 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4862,6 +4862,8 @@ imageTrace Outline Obris @msg the PCX file is cut short PCX datoteka je skraćena @msg the PCX file's header is damaged zaglavlje PCX datoteke je oštećeno @msg PCX files with {bits}-bit pixels in {planes} planes can't be read PCX datoteke s {bits}-bitnim pikselima u {planes} ravni nije moguće pročitati +@msg the JPEG 2000 file can't be read datoteku JPEG 2000 nije moguće pročitati +@msg the JPEG 2000 file has an unsupported color space or JPX content datoteka JPEG 2000 ima nepodržan prostor boja ili JPX sadržaj @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD slika je prevelika za čitanje ({_1} × {_2} piksela) @msg zipped 32-bit PSD image data with prediction can't be read zipovani 32-bitni PSD podaci slike s predviđanjem ne mogu se pročitati @msg {depth}-bit PSD files in this colour mode can't be read {depth}-bitne PSD datoteke u ovom načinu boja ne mogu se pročitati diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 9f8b0a55e4..4f2d7c6164 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6006,6 +6006,8 @@ breakText Glyphs Glifs Gap 4 Separació 4 Dash 5 Guió 5 Gap 5 Separació 5 +@msg the JPEG 2000 file can't be read no es pot llegir el fitxer JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content el fitxer JPEG 2000 té un espai de color o contingut JPX no compatible @msg You must choose a side pattern. Heu de triar un patró lateral. @msg invalid pattern tile choice opció de mosaic de patró no vàlida @msg no pattern named `{choice}` no hi ha cap patró anomenat `{choice}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 2a9aeaf99b..ab09e818aa 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4900,6 +4900,8 @@ imageTrace Outline Obrys @msg the PCX file is cut short soubor PCX je useknutý @msg the PCX file's header is damaged hlavička souboru PCX je poškozená @msg PCX files with {bits}-bit pixels in {planes} planes can't be read soubory PCX s {bits}bitovými obrazovými body v {planes} rovinách nelze přečíst +@msg the JPEG 2000 file can't be read soubor JPEG 2000 nelze přečíst +@msg the JPEG 2000 file has an unsupported color space or JPX content soubor JPEG 2000 obsahuje nepodporovaný barevný prostor nebo obsah JPX @msg the PSD image is too large to read ({_1} × {_2} pixels) obraz PSD je příliš velký na přečtení ({_1} × {_2} obrazových bodů) @msg zipped 32-bit PSD image data with prediction can't be read zazipovaná 32bitová obrazová data PSD s predikcí nelze přečíst @msg {depth}-bit PSD files in this colour mode can't be read {depth}bitové soubory PSD v tomto barevném režimu nelze přečíst diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 240bb8684d..80bd277fd3 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4640,6 +4640,8 @@ theme Appearance Erscheinungsbild @msg the PCX file is cut short die PCX-Datei ist unvollständig @msg the PCX file's header is damaged der Dateikopf der PCX-Datei ist beschädigt @msg PCX files with {bits}-bit pixels in {planes} planes can't be read PCX-Dateien mit {bits}-Bit-Pixeln in {planes} Ebenen können nicht gelesen werden +@msg the JPEG 2000 file can't be read die JPEG-2000-Datei kann nicht gelesen werden +@msg the JPEG 2000 file has an unsupported color space or JPX content die JPEG-2000-Datei enthält einen nicht unterstützten Farbraum oder JPX-Inhalt @msg the PSD image is too large to read ({_1} × {_2} pixels) das PSD-Bild ist zu groß zum Lesen ({_1} × {_2} Pixel) @msg zipped 32-bit PSD image data with prediction can't be read ZIP-komprimierte 32-Bit-PSD-Bilddaten mit Vorhersage können nicht gelesen werden @msg {depth}-bit PSD files in this colour mode can't be read {depth}-Bit-PSD-Dateien in diesem Farbmodus können nicht gelesen werden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a4057ea1dc..bcea580dda 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4581,6 +4581,8 @@ theme Appearance Εμφάνιση @msg the PCX file is cut short το αρχείο PCX είναι περικομμένο @msg the PCX file's header is damaged η κεφαλίδα του αρχείου PCX είναι κατεστραμμένη @msg PCX files with {bits}-bit pixels in {planes} planes can't be read τα αρχεία PCX με εικονοστοιχεία {bits} bit σε {planes} επίπεδα δεν διαβάζονται +@msg the JPEG 2000 file can't be read δεν είναι δυνατή η ανάγνωση του αρχείου JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content το αρχείο JPEG 2000 έχει μη υποστηριζόμενο χρωματικό χώρο ή περιεχόμενο JPX @msg the PSD image is too large to read ({_1} × {_2} pixels) η εικόνα PSD είναι πολύ μεγάλη για ανάγνωση ({_1} × {_2} εικονοστοιχεία) @msg zipped 32-bit PSD image data with prediction can't be read τα συμπιεσμένα δεδομένα εικόνας PSD 32 bit με πρόβλεψη δεν διαβάζονται @msg {depth}-bit PSD files in this colour mode can't be read τα αρχεία PSD {depth} bit δεν διαβάζονται σε αυτήν τη λειτουργία χρώματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2a77b567a4..e9555f3241 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4621,6 +4621,8 @@ axis Both Ambos @msg the PCX file is cut short el archivo PCX está incompleto @msg the PCX file's header is damaged el encabezado del archivo PCX está dañado @msg PCX files with {bits}-bit pixels in {planes} planes can't be read los archivos PCX con píxeles de {bits} bits en {planes} planos no se pueden leer +@msg the JPEG 2000 file can't be read no se puede leer el archivo JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content el archivo JPEG 2000 tiene un espacio de color o contenido JPX no compatible @msg the PSD image is too large to read ({_1} × {_2} pixels) la imagen PSD es demasiado grande para leerla ({_1} × {_2} píxeles) @msg zipped 32-bit PSD image data with prediction can't be read no se pueden leer datos de imagen PSD de 32 bits comprimidos en ZIP con predicción @msg {depth}-bit PSD files in this colour mode can't be read los archivos PSD de {depth} bits en este modo de color no se pueden leer diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 44af5c9fb7..58f8157bad 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4803,6 +4803,8 @@ imageTrace Outline Ääriviiva @msg the PCX file is cut short tämä PCX-tiedosto on katkennut @msg the PCX file's header is damaged PCX-tiedoston otsake on vahingoittunut @msg PCX files with {bits}-bit pixels in {planes} planes can't be read PCX-tiedostoja, joissa on {bits}-bittisiä pikseleitä {planes} tasossa, ei voi lukea +@msg the JPEG 2000 file can't be read tätä JPEG 2000 -tiedostoa ei voi lukea +@msg the JPEG 2000 file has an unsupported color space or JPX content tässä JPEG 2000 -tiedostossa on tukematon väriavaruus tai JPX-sisältö @msg the PSD image is too large to read ({_1} × {_2} pixels) tämä PSD-kuva on liian suuri luettavaksi ({_1} × {_2} pikseliä) @msg zipped 32-bit PSD image data with prediction can't be read ennustusta käyttävää zip-pakattua 32-bittistä PSD-kuvadataa ei voi lukea @msg {depth}-bit PSD files in this colour mode can't be read tässä väritilassa olevia {depth}-bittisiä PSD-tiedostoja ei voi lukea diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index abc63175f4..818a363e6a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4631,6 +4631,8 @@ axis Both Les deux @msg the PCX file is cut short le fichier PCX est tronqué @msg the PCX file's header is damaged l'en-tête du fichier PCX est endommagé @msg PCX files with {bits}-bit pixels in {planes} planes can't be read les fichiers PCX à pixels de {bits} bits sur {planes} plans ne peuvent pas être lus +@msg the JPEG 2000 file can't be read le fichier JPEG 2000 ne peut pas être lu +@msg the JPEG 2000 file has an unsupported color space or JPX content le fichier JPEG 2000 contient un espace colorimétrique ou un contenu JPX non pris en charge @msg the PSD image is too large to read ({_1} × {_2} pixels) l'image PSD est trop grande pour être lue ({_1} × {_2} pixels) @msg zipped 32-bit PSD image data with prediction can't be read les données d'image PSD 32 bits compressées en ZIP avec prédiction ne peuvent pas être lues @msg {depth}-bit PSD files in this colour mode can't be read les fichiers PSD {depth} bits dans ce mode colorimétrique ne peuvent pas être lus diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index db6960188e..6bb3bf986f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5144,6 +5144,8 @@ imageTrace Outline Körvonal @msg the PCX file is cut short a PCX-fájl csonka @msg the PCX file's header is damaged a PCX-fájl fejléce sérült @msg PCX files with {bits}-bit pixels in {planes} planes can't be read a {bits} bites pixeleket {planes} síkban tároló PCX-fájlok nem olvashatók +@msg the JPEG 2000 file can't be read a JPEG 2000 fájl nem olvasható +@msg the JPEG 2000 file has an unsupported color space or JPX content a JPEG 2000 fájl nem támogatott színteret vagy JPX-tartalmat tartalmaz @msg the PSD image is too large to read ({_1} × {_2} pixels) a PSD-kép túl nagy a beolvasáshoz ({_1} × {_2} pixel) @msg the Save PDF dialog didn't open a PDF mentése párbeszédablak nem nyílt meg @msg the scale is not a usable number a méretarány nem használható szám diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 618fce870f..ce6b0d70a1 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4661,6 +4661,8 @@ axis Both Entrambi @msg the PCX file is cut short il file PCX è troncato @msg the PCX file's header is damaged l'intestazione del file PCX è danneggiata @msg PCX files with {bits}-bit pixels in {planes} planes can't be read i file PCX con pixel a {bits} bit in {planes} piani non possono essere letti +@msg the JPEG 2000 file can't be read impossibile leggere il file JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content il file JPEG 2000 contiene uno spazio colore o un contenuto JPX non supportato @msg the PSD image is too large to read ({_1} × {_2} pixels) l'immagine PSD è troppo grande per essere letta ({_1} × {_2} pixel) @msg zipped 32-bit PSD image data with prediction can't be read i dati immagine PSD a 32 bit compressi ZIP con previsione non possono essere letti @msg {depth}-bit PSD files in this colour mode can't be read i file PSD a {depth} bit in questo metodo colore non possono essere letti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 30005d3c3a..69caf7f3a0 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4703,6 +4703,8 @@ swatch Bright Violet ビビッドバイオレット @msg the PCX file is cut short PCX ファイルが途中で切れています @msg the PCX file's header is damaged PCX ファイルのヘッダーが壊れています @msg PCX files with {bits}-bit pixels in {planes} planes can't be read {planes} プレーンに {bits} bit のピクセルを持つ PCX ファイルは読み込めません +@msg the JPEG 2000 file can't be read JPEG 2000 ファイルを読み込めません +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 ファイルには未対応の色空間または JPX コンテンツがあります @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 画像が大きすぎて読み込めません({_1} × {_2} ピクセル) @msg zipped 32-bit PSD image data with prediction can't be read 予測付き ZIP 圧縮の 32 bit PSD 画像データは読み込めません @msg {depth}-bit PSD files in this colour mode can't be read このカラーモードの {depth} bit PSD ファイルは読み込めません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index ff40a494d5..134cc18084 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4340,6 +4340,8 @@ font-technology Variable ცვლადი @msg the PCX file is cut short PCX ფაილი შეკვეცილია @msg the PCX file's header is damaged PCX ფაილის სათაური დაზიანებულია @msg PCX files with {bits}-bit pixels in {planes} planes can't be read {planes} სიბრტყეში {bits}-ბიტიანი პიქსელების მქონე PCX ფაილების წაკითხვა ვერ ხერხდება +@msg the JPEG 2000 file can't be read JPEG 2000 ფაილის წაკითხვა შეუძლებელია +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 ფაილს აქვს მხარდაუჭერელი ფერთა სივრცე ან JPX შიგთავსი @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD გამოსახულება ზედმეტად დიდია წასაკითხად ({_1} × {_2} პიქსელი) @msg zipped 32-bit PSD image data with prediction can't be read zip-ით შეკუმშული 32-ბიტიანი PSD გამოსახულების მონაცემების წაკითხვა პროგნოზირებით ვერ ხერხდება @msg {depth}-bit PSD files in this colour mode can't be read ამ ფერის რეჟიმში {depth}-ბიტიანი PSD ფაილების წაკითხვა ვერ ხერხდება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index d2f381afcb..6a12ca3638 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4631,6 +4631,8 @@ theme Appearance 외관 @msg the PCX file is cut short PCX 파일이 잘려 있습니다 @msg the PCX file's header is damaged PCX 파일의 헤더가 손상되었습니다 @msg PCX files with {bits}-bit pixels in {planes} planes can't be read {planes}개 평면에 {bits}비트 픽셀이 있는 PCX 파일은 읽을 수 없습니다 +@msg the JPEG 2000 file can't be read JPEG 2000 파일을 읽을 수 없습니다 +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 파일에 지원되지 않는 색 공간 또는 JPX 콘텐츠가 있습니다 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 이미지가 너무 커서 읽을 수 없습니다({_1} × {_2}픽셀) @msg zipped 32-bit PSD image data with prediction can't be read 예측이 적용된 ZIP 압축 32비트 PSD 이미지 데이터는 읽을 수 없습니다 @msg {depth}-bit PSD files in this colour mode can't be read 이 색상 모드의 {depth}비트 PSD 파일은 읽을 수 없습니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 092e5e9447..c153223376 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4727,6 +4727,8 @@ imageTrace Outline Kontur @msg the PCX file is cut short plik PCX jest ucięty @msg the PCX file's header is damaged nagłówek pliku PCX jest uszkodzony @msg PCX files with {bits}-bit pixels in {planes} planes can't be read nie można odczytać plików PCX z {bits}-bitowymi pikselami w {planes} płaszczyznach +@msg the JPEG 2000 file can't be read nie można odczytać pliku JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content plik JPEG 2000 zawiera nieobsługiwaną przestrzeń barw lub zawartość JPX @msg the PSD image is too large to read ({_1} × {_2} pixels) obraz PSD jest zbyt duży, aby go odczytać ({_1} × {_2} pikseli) @msg zipped 32-bit PSD image data with prediction can't be read nie można odczytać spakowanych 32-bitowych danych obrazu PSD z predykcją @msg {depth}-bit PSD files in this colour mode can't be read nie można odczytać {depth}-bitowych plików PSD w tym trybie koloru diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index d9a1a94f1e..4fd8e2bc5c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4164,6 +4164,8 @@ axis Both Ambos @msg the PCX file is cut short o arquivo PCX está incompleto @msg the PCX file's header is damaged o cabeçalho do arquivo PCX está danificado @msg PCX files with {bits}-bit pixels in {planes} planes can't be read arquivos PCX com pixels de {bits} bits em {planes} planos não podem ser lidos +@msg the JPEG 2000 file can't be read não é possível ler o arquivo JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content o arquivo JPEG 2000 contém um espaço de cores ou conteúdo JPX sem suporte @msg the PSD image is too large to read ({_1} × {_2} pixels) a imagem PSD é grande demais para ser lida ({_1} × {_2} pixels) @msg zipped 32-bit PSD image data with prediction can't be read dados de imagem PSD de 32 bits compactados em zip com previsão não podem ser lidos @msg {depth}-bit PSD files in this colour mode can't be read arquivos PSD de {depth} bits neste modo de cor não podem ser lidos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d364faf0a0..122bf5939b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4659,6 +4659,8 @@ axis Both Оба @msg the PCX file is cut short файл PCX обрезан @msg the PCX file's header is damaged заголовок файла PCX повреждён @msg PCX files with {bits}-bit pixels in {planes} planes can't be read файлы PCX с {bits}-битными пикселями в {planes} плоскостях не читаются +@msg the JPEG 2000 file can't be read не удается прочитать файл JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content файл JPEG 2000 содержит неподдерживаемое цветовое пространство или содержимое JPX @msg the PSD image is too large to read ({_1} × {_2} pixels) изображение PSD слишком велико для чтения ({_1} × {_2} пикс.) @msg zipped 32-bit PSD image data with prediction can't be read 32-битные данные изображения PSD со сжатием ZIP с предсказанием не читаются @msg {depth}-bit PSD files in this colour mode can't be read {depth}-битные файлы PSD в этом цветовом режиме не читаются diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e01793d233..711f1eab46 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4538,6 +4538,8 @@ axis Both Båda @msg the PCX file is cut short PCX-filen är avkortad @msg the PCX file's header is damaged PCX-filens huvud är skadat @msg PCX files with {bits}-bit pixels in {planes} planes can't be read PCX-filer med {bits}-bitars pixlar i {planes} plan kan inte läsas +@msg the JPEG 2000 file can't be read JPEG 2000-filen kan inte läsas +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000-filen har en färgrymd eller ett JPX-innehåll som inte stöds @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD-bilden är för stor för att läsas ({_1} × {_2} pixlar) @msg zipped 32-bit PSD image data with prediction can't be read zippad 32-bitars PSD-bilddata med prediktion kan inte läsas @msg {depth}-bit PSD files in this colour mode can't be read {depth}-bitars PSD-filer i det här färgläget kan inte läsas diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 32bb794bca..5f69d1acb6 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4381,6 +4381,8 @@ axis Both Her İkisi @msg the PCX file is cut short PCX dosyası kısa kesildi @msg the PCX file's header is damaged PCX dosyasının başlığı bozuk @msg PCX files with {bits}-bit pixels in {planes} planes can't be read {planes} düzlemde {bits}-bit pikseller içeren PCX dosyaları okunamaz +@msg the JPEG 2000 file can't be read JPEG 2000 dosyası okunamıyor +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 dosyasında desteklenmeyen bir renk alanı veya JPX içeriği var @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD görüntüsü okunamayacak kadar büyük ({_1} × {_2} piksel) @msg zipped 32-bit PSD image data with prediction can't be read Tahmin içeren sıkıştırılmış 32 bit PSD görüntü verileri okunamıyor @msg {depth}-bit PSD files in this colour mode can't be read Bu renk modunda {depth}-bit PSD dosyaları okunamaz diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 835a75efcf..eb9d140161 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4645,6 +4645,8 @@ axis Both Обидві @msg the PCX file is cut short файл PCX обрізаний @msg the PCX file's header is damaged заголовок файлу PCX пошкоджений @msg PCX files with {bits}-bit pixels in {planes} planes can't be read файли PCX з {bits}-бітними пікселями в {planes} площинах не читаються +@msg the JPEG 2000 file can't be read не вдається прочитати файл JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content файл JPEG 2000 містить непідтримуваний колірний простір або вміст JPX @msg the PSD image is too large to read ({_1} × {_2} pixels) зображення PSD завелике для читання ({_1} × {_2} пікс.) @msg zipped 32-bit PSD image data with prediction can't be read 32-бітні дані зображення PSD зі стисненням ZIP із передбаченням не читаються @msg {depth}-bit PSD files in this colour mode can't be read {depth}-бітні файли PSD у цьому колірному режимі не читаються diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 6da79b33ea..f6b926e07f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4801,6 +4801,8 @@ theme Appearance Giao diện @msg the PCX file is cut short tệp PCX bị cắt ngắn @msg the PCX file's header is damaged phần đầu của tệp PCX bị hỏng @msg PCX files with {bits}-bit pixels in {planes} planes can't be read tệp PCX có điểm ảnh {bits}-bit trong {planes} mặt phẳng không thể đọc được +@msg the JPEG 2000 file can't be read không thể đọc tệp JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content tệp JPEG 2000 có không gian màu hoặc nội dung JPX không được hỗ trợ @msg the PSD image is too large to read ({_1} × {_2} pixels) ảnh PSD quá lớn để đọc ({_1} × {_2} pixel) @msg the Save PDF dialog didn't open hộp thoại Lưu PDF không mở @msg the scale is not a usable number tỷ lệ không phải là số dùng được diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2912cf6d2a..96b5fbe0df 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4417,6 +4417,8 @@ imageTrace Outline 轮廓 @msg the PCX file is cut short PCX 文件不完整 @msg the PCX file's header is damaged PCX 文件头已损坏 @msg PCX files with {bits}-bit pixels in {planes} planes can't be read 无法读取 {planes} 个平面中含 {bits} 位像素的 PCX 文件 +@msg the JPEG 2000 file can't be read 无法读取 JPEG 2000 文件 +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 文件包含不受支持的色彩空间或 JPX 内容 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 图像过大,无法读取 ({_1} × {_2} 像素) @msg zipped 32-bit PSD image data with prediction can't be read 无法读取带预测的 ZIP 压缩 32 位 PSD 图像数据 @msg {depth}-bit PSD files in this colour mode can't be read 无法读取此颜色模式下的 {depth} 位 PSD 文件 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b814e29917..147c3b0432 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2349,6 +2349,8 @@ file-filter Templates 範本 @msg the PCX file is cut short PCX 檔案不完整 @msg the PCX file's header is damaged PCX 檔案標頭已損毀 @msg PCX files with {bits}-bit pixels in {planes} planes can't be read 無法讀取 {planes} 個平面中含 {bits} 位元像素的 PCX 檔案 +@msg the JPEG 2000 file can't be read 無法讀取 JPEG 2000 檔案 +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 檔案包含不支援的色彩空間或 JPX 內容 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 影像過大,無法讀取 ({_1} × {_2} 像素) @msg zipped 32-bit PSD image data with prediction can't be read 無法讀取使用預測的 ZIP 壓縮 32 位元 PSD 影像資料 @msg {depth}-bit PSD files in this colour mode can't be read 無法讀取此色彩模式的 {depth} 位元 PSD 檔案 diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index c01f0005e5..2d687384cb 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -17,7 +17,7 @@ from the public specifications, and users' own `.ai` files are used locally only | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 26 | missing: FreeHand, CorelDRAW, DWG, HEIC/HEIF, JPEG 2000, PICT, Pixar, Word `.doc`, PS | +| Formats opened or placed | ~30 | 27 | missing: FreeHand, CorelDRAW, DWG, HEIC/HEIF, PICT, Pixar, Word `.doc`, PS | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (no Illustrator editing data) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 17 | missing: DWG, 3D (OBJ/USDA/glTF); extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | @@ -105,8 +105,8 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (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) | | | HEIC / HEIF | open, place | no | no | | -| JPEG 2000 | open, place | no | no | | | PCX | open, place | yes (1 bit in the header palette's first two colors, black and white without them; 1 bit in two to four planes and 4 bits with up to 16 colors; 2 bits in the CGA colors the header's CGA palette settings pick; 8 bits with the 256-color palette, gray without one; 24-bit color in three planes) | no | the header's HDpi and VDpi size the image; a file of another depth or plane count, cut short or past the pixel allowance is refused with a message; tests in `crates/engine/src/cmd/fileio/tests_pcxread.rs` and `crates/engine/tests/import_fuzz.rs` | +| JPEG 2000 | open, place | yes (JP2 and raw codestream images; multiple codestreams and JPX composition or layers are refused) | no | `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c`, `.jpc`; resolution uses the last valid `resc` or `resd` value on each axis, or 72 ppi; bounded decoding; `tests_jp2read.rs` | | PICT, Pixar PXR | open, place (legacy) | no | no | rarely used | | FreeHand `.fh*` | open (legacy) | no | no | | | CorelDRAW `.cdr` | open | no | no | | diff --git a/docs/mcp.md b/docs/mcp.md index 1557555237..719ac6d40c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -427,7 +427,7 @@ objects' fills or strokes differ (`fillMixed` / `strokeMixed`, drawn as a "?" pr | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. Includes UI commands such as `view.*` and `window.*` in remote mode. | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. | -| `open_file` | `{path}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PNG, JPEG, GIF, WebP, TIFF, BMP, Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, PSD/PSB (an image opens as a document of its pixel size; a Photoshop file as its merged image). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). `run_command document.formats` lists the formats. | +| `open_file` | `{path}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PNG, JPEG, GIF, WebP, TIFF, BMP, Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), PSD/PSB (an image opens as a document of its pixel size; a Photoshop file as its merged image). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), and `preview: true` embeds a PNG of the first artboard. `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version` or `preview` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version` or `preview`). `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warning for a top-level `compress`, `version` or `preview`. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. 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 Background Save preference. | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF and WMF write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`); `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | @@ -3685,7 +3685,7 @@ image `object.rasterize` makes with the same options. ## Glass textures Glass (`distort.glass`) takes an image file as its surface in `params.textureImage`, as `{path}` or -`{name?, dataBase64}`: a PNG, JPEG, GIF, WebP, TIFF, BMP, Targa, PSD, PSB or PCX file, decoded within the pixel allowance the +`{name?, dataBase64}`: a PNG, JPEG, GIF, WebP, TIFF, BMP, Targa, PSD, PSB, PCX or JPEG 2000 file, decoded within the pixel allowance the renderer draws images in, counted as RGBA. `effect.apply` and `effect.setParams` store the image's gray levels in the effect as a grayscale PNG in base64 and set `texture: "loaded"` unless the params give a `texture`. `effect.list` reports the stored string, and a command given that string stores it unchanged. Any other string, a file that is not an image, or an image past diff --git a/docs/releasing.md b/docs/releasing.md index 449729420c..1ec5c221c4 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -164,7 +164,7 @@ to the target triple, so host build scripts aren't affected. AppStream metainfo, the MIME type for VectorCraft documents, the icons and the licence files. **Document types.** The desktop entry's `MimeType` lists every format File › Open reads but PSD, -PSB, `.ps` PostScript, Targa and PCX, so file managers list VectorCraft under Open With for them. +PSB, `.ps` PostScript, Targa, PCX and JPEG 2000, so file managers list VectorCraft under Open With for them. `ai.storyteller.vectorcraft.mime.xml` declares the types that shared-mime-info lacks: VectorCraft documents and templates, `.ait` templates and Affinity files (`application/x-affinity`). An `.af` file gets the Affinity type by its content, and `.afdesign` and `.afpub` files by their extension. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index caa6dbfb3c..6f0a426b26 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -144,7 +144,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | 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 panel row context menus and Collect for Export (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 Arrange | 9–14 | estimated; 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), guides lost (#779), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC/JPEG 2000 import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 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. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), guides lost (#779), 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 | 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. | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; 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 Arrange | 9–14 | estimated | | 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), distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | @@ -536,7 +536,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Artboard deletion keys:** Delete/Backspace delete selected boards in one Undo step, retaining the original first board in the current order when all are selected, as in the public [Delete artboards guide](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html). The last board and active drags stay protected; neither key clears selected artwork. Headless shortcut regressions in `tests/distortkeys.rs` cover reordered boards, artwork, saved state and Undo/Redo. - **Locked artboards:** a click in the Artboards panel's lock column locks or unlocks an artboard in one undo step (`artboard.setProps {index, locked}`), and the native format saves the lock. The Artboard tool doesn't move, copy, resize or delete a locked artboard, Rearrange and Fit to Artwork Bounds leave it as it is, and its name isn't edited on the canvas. The art on it (each object whose bounds overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, `select.set`, `select.all` and the tools pass over it, and commands that act on the selection leave it; art drawn or pasted onto it stays selected and editable until the selection leaves it out. Tests in `crates/doc/src/lib.rs`, `tests/panelcmds.rs`, `xform/artboard.rs`, `panels/artboards.rs` and `canvas.rs` cover them. Public references: [Lock artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/lock-artboards.html) and [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/). - **Linux RPM packaging:** 64-bit runtime capabilities replace Fedora-specific required package names (#1275); glibc 2.35, libm and libgcc_s are declared alongside dynamically loaded xkbcommon and Vulkan/EGL. Generated x86_64/aarch64 metadata and isolated synthetic-provider resolution checked; real-distro install/start-up QA remains pending. -- **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa and PCX, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/main.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. +- **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa, PCX and JPEG 2000, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/tests.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. - **Architecture:** 19+ crates with enforced layering (`cargo xtask layers`). Every action is a command (~400 engine + ~50 UI). Undo is unlimited via structural sharing. `command.batch` runs several commands as one transaction. - **Automation:** @@ -1059,6 +1059,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EPS export with Use Artboards writes a central EPS file of the whole document, bounded by its visible art, beside the file of each artboard when it writes two or more artboards; a document with no visible art gets only the artboard files (`crates/engine/src/cmd/fileio/tests_eps.rs`). - 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`). - 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`). + - JPEG 2000 JP2 and raw codestream images open and place from `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c` and `.jpc`. The last valid `resc` or `resd` resolution value wins on each axis; 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`). - 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`). - 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`). @@ -1169,7 +1170,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 or PCX 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. +- **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 or JPEG 2000 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. - **Bounded effect length inputs (#4638):** Effect dialog fields with defined length ranges (such as Color Halftone Max Radius 4..127 pt) clamp immediately on commit and reject invalid inputs visibly with an accent highlight without reverting to sub-minimum values. - **Raster effects after document and view changes:** a cached drop shadow, outer glow or filtered content is made again when something its content reads from outside the object changes: a pattern's art or tiling, a symbol shown inside another symbol, a brush definition, an image's pixels, the raster resolution (De-Interlace), Page Knockout Group, the substitution highlights (Highlight Substituted Fonts and Highlight Alternate Glyphs in Preferences › Type, Highlight Substituted Glyphs in Document Setup), a layer's Dim Images, the color settings, the fonts, Pixel Preview, Anti-aliased Artwork, Overprint Preview and isolation mode. A thumbnail under Color Halftone or Mezzotint is made again when the document's color mode changes. Raster effects (blur, shadow, glow, grain) drawn after a pattern, radial or freeform gradient fill export at their place and size (#1541, fixes #1536). From f8bba3388e2fc546f24387eedc2087ca2acffeba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 15:50:14 -0700 Subject: [PATCH 36/70] Batch: data set files name by File + Number, File + Data Set Name or Data Set Name The Batch dialog has a File Name choice for a Data Sets source, starting with File + Number (`source001`), as well as File + Data Set Name (`source_Alpha`) and Data Set Name (`Alpha`). `action.batch` takes it as `datasetFileNaming`; a call without it keeps File + Data Set Name, and a folder source ignores it. An unknown value is an error. A data set output whose name already exists in the destination folder now takes the next free `-2`, `-3` suffix instead of replacing the file, and a Windows device name under Data Set Name gets a trailing `-`. --- crates/engine/src/cmd/fileio/action_batch.rs | 212 ++++++++++++++++++- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/ui-egui/src/dialogs/action_batch.rs | 135 +++++++++--- crates/ui-egui/src/i18n/bg.tsv | 5 + crates/ui-egui/src/i18n/bs.tsv | 5 + crates/ui-egui/src/i18n/ca.tsv | 5 + crates/ui-egui/src/i18n/cs.tsv | 5 + crates/ui-egui/src/i18n/da.tsv | 5 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 5 + crates/ui-egui/src/i18n/es.tsv | 5 + crates/ui-egui/src/i18n/fi.tsv | 5 + crates/ui-egui/src/i18n/fr.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 5 + crates/ui-egui/src/i18n/id.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 5 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ka.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/nl.tsv | 5 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 5 + crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/sv.tsv | 5 + crates/ui-egui/src/i18n/tr.tsv | 5 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/vi.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 5 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + docs/mcp.md | 25 ++- docs/target-app-parity.md | 2 + 31 files changed, 452 insertions(+), 54 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index d1db603025..f2310962ee 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -93,7 +93,7 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { }; match source { "folder" => batch_folder(s, C, p, override_open, &run), - "datasets" => batch_datasets(s, C, &run), + "datasets" => batch_datasets(s, C, &run, p), _ => Err(bad(C, "`source` must be `folder` or `datasets`")), } } @@ -134,10 +134,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: } #[cfg(not(target_arch = "wasm32"))] -fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { - use super::distinct_names; - use super::screens::file_part; - +fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>, p: &Value) -> Result { let st = s.doc()?; let names: Vec = st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect(); if names.is_empty() { @@ -147,11 +144,8 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets"))); } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); - // Data set files are named File + Data Set Name (helpx, for Override Save/Export; the folder - // destination uses the same name). `file_part` writes the characters Windows does not allow in a - // file name (`/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters) in the data set's - // name as `-`, and `distinct_names` adds `-2`, `-3`… to a name an earlier data set used. - let stems = distinct_names(names.iter().map(|name| format!("{doc_stem}_{}", file_part(name)))); + let naming = p.get("datasetFileNaming").map_or("fileDataSetName", |v| v.as_str().unwrap_or("")); + let stems = dataset_stems(&names, &doc_stem, naming, run)?; let steps = filter_steps(run.steps, true, false); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); @@ -240,6 +234,68 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou } } +/// Builds the three data set naming forms, replaces unsafe name characters, and adds `-2`, `-3` +/// suffixes when a stem was used earlier or its output already exists in the destination folder. +#[cfg(not(target_arch = "wasm32"))] +fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>) -> Result> { + use super::screens::{file_part, safe_file_name}; + + if !matches!(naming, "fileNumber" | "fileDataSetName" | "dataSetName") { + return Err(bad("action.batch", "`datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName`")); + } + let bases = names.iter().enumerate().map(|(i, name)| { + let safe = file_part(name); + let safe_data_set = safe_file_name(&safe); + match naming { + "fileNumber" => format!("{doc_stem}{:03}", i + 1), + "dataSetName" if !safe_data_set.is_empty() => safe_data_set, + "dataSetName" => format!("{doc_stem}{:03}", i + 1), + _ => format!("{doc_stem}_{safe}"), + } + }); + let extensions = dataset_output_extensions(run); + let mut taken = std::collections::HashSet::new(); + let mut stems = Vec::with_capacity(bases.len()); + for base in bases { + let mut candidate = base.clone(); + let mut suffix = 2; + while taken.contains(&candidate.to_lowercase()) || dataset_output_exists(run.dest_folder, &candidate, &extensions) { + if suffix > 10_000 { + return Err(bad("action.batch", "no free data set file name in destination folder")); + } + candidate = format!("{base}-{suffix}"); + suffix += 1; + } + taken.insert(candidate.to_lowercase()); + stems.push(candidate); + } + Ok(stems) +} + +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_extensions(run: &Run<'_>) -> Vec { + let mut extensions = Vec::new(); + if run.destination == "folder" { + extensions.push("vectorcraft".to_string()); + } + for step in run.steps { + let id = step.get("command").and_then(Value::as_str).unwrap_or(""); + let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + || (run.override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection")); + if writes { + let ext = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); + extensions.push(ext.map_or_else(|| "vectorcraft".to_string(), format_extension)); + } + } + extensions +} + +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_exists(folder: Option<&str>, stem: &str, extensions: &[String]) -> bool { + let Some(folder) = folder else { return false }; + extensions.iter().any(|ext| std::path::Path::new(folder).join(format!("{stem}.{ext}")).exists()) +} + /// Save when the extension is a Save format; otherwise export (PNG, JPEG…). /// `as_copy`: `file.saveCopy` so the open document keeps its path (data-set batches). #[cfg(not(target_arch = "wasm32"))] @@ -548,6 +604,142 @@ mod tests { s } + fn named_batch(s: &mut Session, dest: &std::path::Path, naming: Option<&str>) -> Value { + let mut p = json!({ + "source": "datasets", "destination": "folder", "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "object.unlockAll", "params": {}}] + }); + if let Some(naming) = naming { + p["datasetFileNaming"] = json!(naming); + } + s.execute("action.batch", &p).unwrap() + } + + #[test] + fn batch_data_set_naming_choices_and_omitted_default() { + for (i, (naming, want)) in [ + (Some("fileNumber"), ["source001.vectorcraft", "source002.vectorcraft"]), + (Some("fileDataSetName"), ["source_Alpha.vectorcraft", "source_Beta.vectorcraft"]), + (Some("dataSetName"), ["Alpha.vectorcraft", "Beta.vectorcraft"]), + (None, ["source_Alpha.vectorcraft", "source_Beta.vectorcraft"]), + ] + .into_iter() + .enumerate() + { + let dest = tmp(&format!("choice-{i}")); + let mut s = with_data_sets(&["Alpha", "Beta"]); + let saved = tmp(&format!("saved-{i}")).join("source.vectorcraft"); + s.execute("document.save", &json!({"path": saved.to_string_lossy()})).unwrap(); + let r = named_batch(&mut s, &dest, naming); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&dest), want, "{naming:?}: {r}"); + } + } + + #[test] + fn batch_file_number_uses_three_digits_through_500() { + let names: Vec = (1..=500).map(|n| format!("Set {n}")).collect(); + let run = Run { + label: "Test", + steps: &[], + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: None, + }; + let stems = dataset_stems(&names, "source", "fileNumber", &run).unwrap(); + for n in [1, 2, 10, 100, 500] { + assert_eq!(stems[n - 1], format!("source{n:03}")); + } + } + + #[test] + fn batch_unsaved_data_set_names_and_empty_fallback() { + let dest = tmp("unsaved-number"); + let mut s = with_data_sets(&["Alpha"]); + assert_eq!(named_batch(&mut s, &dest, Some("fileNumber"))["failed"], 0); + assert_eq!(file_names(&dest), ["Untitled001.vectorcraft"]); + let dest = tmp("unsaved-name"); + assert_eq!(named_batch(&mut s, &dest, Some("fileDataSetName"))["failed"], 0); + assert_eq!(file_names(&dest), ["Untitled_Alpha.vectorcraft"]); + let run = Run { + label: "Test", + steps: &[], + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: None, + }; + assert_eq!(dataset_stems(&[String::new()], "Untitled", "dataSetName", &run).unwrap(), ["Untitled001"]); + assert_eq!(dataset_stems(&[" ".to_string()], "Untitled", "dataSetName", &run).unwrap(), ["Untitled001"]); + } + + #[test] + fn batch_data_set_name_collisions_and_existing_files() { + let clear = tmp("choice-collision-clear"); + let mut s = with_data_sets(&["a:b", "a-b"]); + let r = named_batch(&mut s, &clear, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&clear), ["a-b-2.vectorcraft", "a-b.vectorcraft"]); + let dest = tmp("choice-collision"); + std::fs::write(dest.join("a-b.vectorcraft"), b"keep").unwrap(); + let mut s = with_data_sets(&["a:b", "a-b"]); + let r = named_batch(&mut s, &dest, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(dest.join("a-b.vectorcraft")).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["a-b-2.vectorcraft", "a-b-3.vectorcraft", "a-b.vectorcraft"]); + } + + #[test] + fn batch_data_set_name_avoids_windows_device_files() { + let dest = tmp("choice-device"); + let mut s = with_data_sets(&["CON"]); + let r = named_batch(&mut s, &dest, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&dest), ["CON-.vectorcraft"]); + } + + #[test] + fn batch_override_export_keeps_existing_output() { + let dest = tmp("choice-existing-export"); + std::fs::write(dest.join("Alpha.svg"), b"keep").unwrap(); + let mut s = with_data_sets(&["Alpha"]); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.export", "params": {"format": "svg"}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(dest.join("Alpha.svg")).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-2.svg", "Alpha.svg"]); + } + + #[test] + fn batch_rejects_unknown_data_set_naming_but_ignores_it_for_folders() { + let mut s = with_data_sets(&["Alpha"]); + let e = s + .execute("action.batch", &json!({"source": "datasets", "datasetFileNaming": "other", "commands": [{"command": "object.unlockAll"}]})) + .unwrap_err(); + let msg = e.to_string(); + for value in ["fileNumber", "fileDataSetName", "dataSetName"] { + assert!(msg.contains(value), "{msg}"); + } + assert!( + s.execute("action.batch", &json!({"source": "datasets", "datasetFileNaming": 7, "commands": [{"command": "object.unlockAll"}]})).is_err() + ); + let src = tmp("folder-ignore-src"); + write_svg(&src, "one.svg", "#f00"); + let r = s.execute("action.batch", &json!({"source": "folder", "folder": src.to_string_lossy(), "datasetFileNaming": "other", "commands": [{"command": "object.unlockAll"}]})).unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + } + #[test] fn batch_keeps_data_set_files_inside_the_destination_folder() { let root = tmp("set-names-root"); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index abd6857adc..ba39d0bdb1 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document (source: datasets; File + Data Set Name for the folder destination and Override Save/Export, with `/`, `\\`, `:`, `<`, `>`, `\"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and `-2`, `-3`… added to a name already used). Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or present in the destination folder gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", always, action_batch::action_batch ), diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 01c27b98aa..3464fad755 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -21,26 +21,28 @@ pub fn open(app: &mut VectorcraftApp, set: usize, action: usize) -> Result Value { + json!({ + "set": set, + "action": action, + "actionName": name, + "source": "folder", + "datasetFileNaming": "fileNumber", + "folder": "", + "includeSubdirs": false, + "destination": "folder", + "destinationFolder": "", + "overrideOpen": true, + "overrideSave": true, + "overrideExport": true, + "stopOnError": true, + }) +} + fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new(d.str("actionName")).color(t.text_strong)); @@ -58,6 +60,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { form::check(ui, d, "includeSubdirs", "Include All Subdirectories"); } else { ui.label(egui::RichText::new(tl!("Uses every data set of the open document.")).size(11.5).color(t.text_dim)); + form::choice( + ui, + d, + "datasetFileNaming", + "File Name:", + (LABEL, 200.0), + &[("fileNumber", "File + Number"), ("fileDataSetName", "File + Data Set Name"), ("dataSetName", "Data Set Name")], + ); } ui.add_space(8.0); @@ -95,23 +105,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if source == "datasets" && app.session.active().is_none() { return Err("open a document with data sets".into()); } - let mut params = json!({ - "commands": commands, - "label": a.name, - "source": source, - "destination": destination, - "overrideOpen": d.bool("overrideOpen"), - "overrideSave": d.bool("overrideSave"), - "overrideExport": d.bool("overrideExport"), - "stopOnError": d.bool("stopOnError"), - "includeSubdirs": d.bool("includeSubdirs"), - }); - if source == "folder" { - params["folder"] = json!(d.str("folder")); - } - if destination == "folder" { - params["destinationFolder"] = json!(d.str("destinationFolder")); - } + let params = params(d, &a.name, commands); let r = app.run("action.batch", params)?; app.ui.dialog = None; let count = r["count"].as_u64().unwrap_or(0); @@ -123,3 +117,76 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } Ok(r) } + +fn params(d: &Dialog, action_name: &str, commands: Vec) -> Value { + let source = d.str("source"); + let destination = d.str("destination"); + let mut params = json!({ + "commands": commands, + "label": action_name, + "source": source, + "destination": destination, + "overrideOpen": d.bool("overrideOpen"), + "overrideSave": d.bool("overrideSave"), + "overrideExport": d.bool("overrideExport"), + "stopOnError": d.bool("stopOnError"), + "includeSubdirs": d.bool("includeSubdirs"), + }); + if source == "folder" { + params["folder"] = json!(d.str("folder")); + } else if source == "datasets" { + params["datasetFileNaming"] = json!(d.str("datasetFileNaming")); + } + if destination == "folder" { + params["destinationFolder"] = json!(d.str("destinationFolder")); + } + params +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn shown(source: &str) -> Vec { + fn collect(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, out)), + _ => {} + } + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); + d.fields["source"] = json!(source); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut frame = ctx.run_ui(Default::default(), |ui| { + body(&mut app, ui, &mut d); + }); + frame.textures_delta.clear(); + let mut labels = vec![]; + frame.shapes.iter().for_each(|shape| collect(&shape.shape, &mut labels)); + labels + } + + #[test] + fn file_name_choice_shows_only_for_data_sets() { + assert!(shown("datasets").iter().any(|label| label == "File Name:")); + assert!(shown("datasets").iter().any(|label| label == "File + Number")); + assert!(!shown("folder").iter().any(|label| label == "File Name:")); + } + + #[test] + fn data_set_naming_params_follow_dialog_choice() { + let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); + assert_eq!(d.str("datasetFileNaming"), "fileNumber"); + d.fields["source"] = json!("datasets"); + for choice in ["fileNumber", "fileDataSetName", "dataSetName"] { + d.fields["datasetFileNaming"] = json!(choice); + assert_eq!(params(&d, "Test", vec![])["datasetFileNaming"], choice); + } + d.fields["source"] = json!("folder"); + assert!(params(&d, "Test", vec![]).get("datasetFileNaming").is_none()); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index fbb0019ec4..0becb7e965 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5860,6 +5860,11 @@ breakText Glyphs Глифи @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` трябва да е lines, paragraphs, words или glyphs, а не {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` трябва да е "line" или "paragraph", а не {other} @msg `align` must be "left", "center" or "right", not {other} `align` трябва да е "left", "center" или "right", а не {other} + File + Number Файл + номер + File + Data Set Name Файл + име на набора от данни + Data Set Name Име на набора от данни +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` трябва да е `fileNumber`, `fileDataSetName` или `dataSetName` +@msg no free data set file name in destination folder Няма свободно име за файл на набор от данни в целевата папка # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Mode Режим diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d5f5e6dad5..b1635dc7bf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5869,6 +5869,11 @@ swatch Yellow Green Žuto-zelena Position: Položaj: Font Size: Veličina fonta: shape Open Otvoren + File + Number Datoteka + broj + File + Data Set Name Datoteka + naziv skupa podataka + Data Set Name Naziv skupa podataka +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` mora biti `fileNumber`, `fileDataSetName` ili `dataSetName` +@msg no free data set file name in destination folder Nema slobodnog naziva datoteke skupa podataka u odredišnoj mapi # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Retract Handles Uvuci ručke diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 4f2d7c6164..b875d10672 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5966,6 +5966,11 @@ breakText Glyphs Glifs @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` ha de ser lines, paragraphs, words o glyphs, no {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` ha de ser "line" o "paragraph", no {other} @msg `align` must be "left", "center" or "right", not {other} `align` ha de ser "left", "center" o "right", no {other} + File + Number Fitxer + número + File + Data Set Name Fitxer + nom del conjunt de dades + Data Set Name Nom del conjunt de dades +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` ha de ser `fileNumber`, `fileDataSetName` o `dataSetName` +@msg no free data set file name in destination folder No hi ha cap nom de fitxer de conjunt de dades lliure a la carpeta de destinació # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Efectes de traçat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ab09e818aa..6452812168 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5977,6 +5977,11 @@ breakText Glyphs Glyfy @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` musí být lines, paragraphs, words nebo glyphs, ne {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` musí být "line" nebo "paragraph", ne {other} @msg `align` must be "left", "center" or "right", not {other} `align` musí být "left", "center" nebo "right", ne {other} + File + Number Soubor + číslo + File + Data Set Name Soubor + název sady dat + Data Set Name Název sady dat +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` musí být `fileNumber`, `fileDataSetName` nebo `dataSetName` +@msg no free data set file name in destination folder V cílové složce není volný název souboru sady dat # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Efekty cesty diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b7c6e23fda..fb80dcc0c7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5875,6 +5875,11 @@ breakText Glyphs Glyffer @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` skal være lines, paragraphs, words eller glyphs, ikke {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` skal være "line" eller "paragraph", ikke {other} @msg `align` must be "left", "center" or "right", not {other} `align` skal være "left", "center" eller "right", ikke {other} + File + Number Fil + nummer + File + Data Set Name Fil + datasætnavn + Data Set Name Datasætnavn +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` skal være `fileNumber`, `fileDataSetName` eller `dataSetName` +@msg no free data set file name in destination folder Intet ledigt filnavn til datasættet i destinationsmappen # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Kurveeffekter diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 80bd277fd3..1ea0d5f0d9 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5562,6 +5562,11 @@ breakText Glyphs Glyphen @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` muss lines, paragraphs, words oder glyphs sein, nicht {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` muss "line" oder "paragraph" sein, nicht {other} @msg `align` must be "left", "center" or "right", not {other} `align` muss "left", "center" oder "right" sein, nicht {other} + File + Number Datei + Nummer + File + Data Set Name Datei + Datensatzname + Data Set Name Datensatzname +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` muss `fileNumber`, `fileDataSetName` oder `dataSetName` sein +@msg no free data set file name in destination folder Kein freier Dateiname für den Datensatz im Zielordner # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Pfadeffekte diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bcea580dda..383e9b4343 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5929,6 +5929,11 @@ breakText Glyphs Γλύφοι @msg `by` must be lines, paragraphs, words or glyphs, not {other} το `by` πρέπει να είναι lines, paragraphs, words ή glyphs, όχι {other} @msg `kind` must be "line" or "paragraph", not {other} το `kind` πρέπει να είναι "line" ή "paragraph", όχι {other} @msg `align` must be "left", "center" or "right", not {other} το `align` πρέπει να είναι "left", "center" ή "right", όχι {other} + File + Number Αρχείο + αριθμός + File + Data Set Name Αρχείο + όνομα συνόλου δεδομένων + Data Set Name Όνομα συνόλου δεδομένων +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` Το `datasetFileNaming` πρέπει να είναι `fileNumber`, `fileDataSetName` ή `dataSetName` +@msg no free data set file name in destination folder Δεν υπάρχει διαθέσιμο όνομα αρχείου συνόλου δεδομένων στον φάκελο προορισμού # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Mode Λειτουργία diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e9555f3241..80d54c074e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5920,6 +5920,11 @@ breakText Glyphs Glifos @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` debe ser lines, paragraphs, words o glyphs, no {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` debe ser "line" o "paragraph", no {other} @msg `align` must be "left", "center" or "right", not {other} `align` debe ser "left", "center" o "right", no {other} + File + Number Archivo + número + File + Data Set Name Archivo + nombre del conjunto de datos + Data Set Name Nombre del conjunto de datos +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` debe ser `fileNumber`, `fileDataSetName` o `dataSetName` +@msg no free data set file name in destination folder No hay un nombre de archivo libre para el conjunto de datos en la carpeta de destino # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Efectos de trazado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 58f8157bad..ef924d1731 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6008,6 +6008,11 @@ breakText Glyphs Merkit @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` on oltava lines, paragraphs, words tai glyphs, ei {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` on oltava "line" tai "paragraph", ei {other} @msg `align` must be "left", "center" or "right", not {other} `align` on oltava "left", "center" tai "right", ei {other} + File + Number Tiedosto + numero + File + Data Set Name Tiedosto + tietojoukon nimi + Data Set Name Tietojoukon nimi +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming`-arvon on oltava `fileNumber`, `fileDataSetName` tai `dataSetName` +@msg no free data set file name in destination folder Kohdekansiossa ei ole vapaata tietojoukon tiedostonimeä # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Polkutehosteet diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 818a363e6a..7d5fe46b1e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5975,6 +5975,11 @@ breakText Glyphs Glyphes @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` doit valoir lines, paragraphs, words ou glyphs, et non {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` doit valoir "line" ou "paragraph", et non {other} @msg `align` must be "left", "center" or "right", not {other} `align` doit valoir "left", "center" ou "right", et non {other} + File + Number Fichier + numéro + File + Data Set Name Fichier + nom du jeu de données + Data Set Name Nom du jeu de données +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` doit être `fileNumber`, `fileDataSetName` ou `dataSetName` +@msg no free data set file name in destination folder Aucun nom de fichier libre pour le jeu de données dans le dossier de destination # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Effets de tracé diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 6bb3bf986f..0d71cbb8ae 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5964,6 +5964,11 @@ breakText Glyphs Glifák @msg `by` must be lines, paragraphs, words or glyphs, not {other} a `by` értéke lines, paragraphs, words vagy glyphs lehet, nem {other} @msg `kind` must be "line" or "paragraph", not {other} a `kind` értéke "line" vagy "paragraph" lehet, nem {other} @msg `align` must be "left", "center" or "right", not {other} az `align` értéke "left", "center" vagy "right" lehet, nem {other} + File + Number Fájl + szám + File + Data Set Name Fájl + adatkészlet neve + Data Set Name Adatkészlet neve +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` A `datasetFileNaming` értéke `fileNumber`, `fileDataSetName` vagy `dataSetName` lehet +@msg no free data set file name in destination folder Nincs szabad adatkészlet-fájlnév a célmappában # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Útvonaleffektusok diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 664551a1fa..bfa0660240 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5875,6 +5875,11 @@ breakText Glyphs Glif @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` harus lines, paragraphs, words, atau glyphs, bukan {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` harus "line" atau "paragraph", bukan {other} @msg `align` must be "left", "center" or "right", not {other} `align` harus "left", "center", atau "right", bukan {other} + File + Number File + nomor + File + Data Set Name File + nama set data + Data Set Name Nama set data +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` harus `fileNumber`, `fileDataSetName`, atau `dataSetName` +@msg no free data set file name in destination folder Tidak ada nama file set data yang tersedia di folder tujuan # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Efek jalur diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce6b0d70a1..2c587de487 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5596,6 +5596,11 @@ breakText Glyphs Glifi @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` deve essere lines, paragraphs, words o glyphs, non {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` deve essere "line" o "paragraph", non {other} @msg `align` must be "left", "center" or "right", not {other} `align` deve essere "left", "center" o "right", non {other} + File + Number File + numero + File + Data Set Name File + nome set di dati + Data Set Name Nome set di dati +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` deve essere `fileNumber`, `fileDataSetName` o `dataSetName` +@msg no free data set file name in destination folder Nessun nome file libero per il set di dati nella cartella di destinazione # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Effetti tracciato diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 69caf7f3a0..0326a5c841 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5662,6 +5662,11 @@ breakText Glyphs 字形 @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` は lines、paragraphs、words、glyphs のいずれかにしてください({other} は使用できません) @msg `kind` must be "line" or "paragraph", not {other} `kind` は "line" または "paragraph" にしてください({other} は使用できません) @msg `align` must be "left", "center" or "right", not {other} `align` は "left"、"center"、"right" のいずれかにしてください({other} は使用できません) + File + Number ファイル名 + 番号 + File + Data Set Name ファイル名 + データセット名 + Data Set Name データセット名 +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` は `fileNumber`、`fileDataSetName`、`dataSetName` のいずれかである必要があります +@msg no free data set file name in destination folder 保存先フォルダーに使用可能なデータセットのファイル名がありません # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects パス効果 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 134cc18084..b34d095505 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5967,6 +5967,11 @@ breakText Glyphs გლიფები @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` უნდა იყოს lines, paragraphs, words ან glyphs და არა {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` უნდა იყოს "line" ან "paragraph" და არა {other} @msg `align` must be "left", "center" or "right", not {other} `align` უნდა იყოს "left", "center" ან "right" და არა {other} + File + Number ფაილი + ნომერი + File + Data Set Name ფაილი + მონაცემთა ნაკრების სახელი + Data Set Name მონაცემთა ნაკრების სახელი +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` უნდა იყოს `fileNumber`, `fileDataSetName` ან `dataSetName` +@msg no free data set file name in destination folder დანიშნულების საქაღალდეში მონაცემთა ნაკრებისთვის თავისუფალი ფაილის სახელი არ არის # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects ტრაექტორიის ეფექტები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 6a12ca3638..5e7e7db024 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5559,6 +5559,11 @@ breakText Glyphs 글리프 @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by`는 lines, paragraphs, words 또는 glyphs여야 합니다({other}는 사용할 수 없음) @msg `kind` must be "line" or "paragraph", not {other} `kind`는 "line" 또는 "paragraph"여야 합니다({other}는 사용할 수 없음) @msg `align` must be "left", "center" or "right", not {other} `align`은 "left", "center" 또는 "right"여야 합니다({other}는 사용할 수 없음) + File + Number 파일 + 번호 + File + Data Set Name 파일 + 데이터 세트 이름 + Data Set Name 데이터 세트 이름 +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming`은 `fileNumber`, `fileDataSetName` 또는 `dataSetName`이어야 합니다 +@msg no free data set file name in destination folder 대상 폴더에 사용할 수 있는 데이터 세트 파일 이름이 없습니다 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects 패스 효과 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 19fdc86635..504ecae137 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5919,6 +5919,11 @@ breakText Glyphs Glyphs @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` moet lines, paragraphs, words of glyphs zijn, niet {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` moet "line" of "paragraph" zijn, niet {other} @msg `align` must be "left", "center" or "right", not {other} `align` moet "left", "center" of "right" zijn, niet {other} + File + Number Bestand + nummer + File + Data Set Name Bestand + naam gegevensset + Data Set Name Naam gegevensset +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` moet `fileNumber`, `fileDataSetName` of `dataSetName` zijn +@msg no free data set file name in destination folder Geen vrije bestandsnaam voor de gegevensset in de doelmap # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Padeffecten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index c153223376..fffff07ae6 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5832,6 +5832,11 @@ breakText Glyphs Glify @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` musi mieć wartość lines, paragraphs, words lub glyphs, a nie {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` musi mieć wartość "line" lub "paragraph", a nie {other} @msg `align` must be "left", "center" or "right", not {other} `align` musi mieć wartość "left", "center" lub "right", a nie {other} + File + Number Plik + numer + File + Data Set Name Plik + nazwa zestawu danych + Data Set Name Nazwa zestawu danych +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` musi mieć wartość `fileNumber`, `fileDataSetName` lub `dataSetName` +@msg no free data set file name in destination folder Brak wolnej nazwy pliku zestawu danych w folderze docelowym # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Efekty ścieżki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4fd8e2bc5c..aab46d1911 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5895,6 +5895,11 @@ breakText Glyphs Glifos @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` deve ser lines, paragraphs, words ou glyphs, não {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` deve ser "line" ou "paragraph", não {other} @msg `align` must be "left", "center" or "right", not {other} `align` deve ser "left", "center" ou "right", não {other} + File + Number Arquivo + número + File + Data Set Name Arquivo + nome do conjunto de dados + Data Set Name Nome do conjunto de dados +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` deve ser `fileNumber`, `fileDataSetName` ou `dataSetName` +@msg no free data set file name in destination folder Não há nome de arquivo livre para o conjunto de dados na pasta de destino # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Distance Distância diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 122bf5939b..a516437a62 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5955,6 +5955,11 @@ breakText Glyphs Глифы @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` должен быть lines, paragraphs, words или glyphs, а не {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` должен быть "line" или "paragraph", а не {other} @msg `align` must be "left", "center" or "right", not {other} `align` должен быть "left", "center" или "right", а не {other} + File + Number Файл + номер + File + Data Set Name Файл + имя набора данных + Data Set Name Имя набора данных +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` должно быть `fileNumber`, `fileDataSetName` или `dataSetName` +@msg no free data set file name in destination folder В папке назначения нет свободного имени файла для набора данных # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Эффекты контура diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 711f1eab46..a98780bcf2 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6030,6 +6030,11 @@ breakText Glyphs Glyfer @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` måste vara lines, paragraphs, words eller glyphs, inte {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` måste vara "line" eller "paragraph", inte {other} @msg `align` must be "left", "center" or "right", not {other} `align` måste vara "left", "center" eller "right", inte {other} + File + Number Fil + nummer + File + Data Set Name Fil + datauppsättningens namn + Data Set Name Datauppsättningens namn +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` måste vara `fileNumber`, `fileDataSetName` eller `dataSetName` +@msg no free data set file name in destination folder Inget ledigt filnamn för datauppsättningen i målmappen # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Baneffekter diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 5f69d1acb6..4d543f0270 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5935,6 +5935,11 @@ breakText Glyphs Glifler @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by`, lines, paragraphs, words veya glyphs olmalı, {other} değil @msg `kind` must be "line" or "paragraph", not {other} `kind`, "line" veya "paragraph" olmalı, {other} değil @msg `align` must be "left", "center" or "right", not {other} `align`, "left", "center" veya "right" olmalı, {other} değil + File + Number Dosya + numara + File + Data Set Name Dosya + veri kümesi adı + Data Set Name Veri kümesi adı +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` değeri `fileNumber`, `fileDataSetName` veya `dataSetName` olmalıdır +@msg no free data set file name in destination folder Hedef klasörde veri kümesi için boş bir dosya adı yok # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Yol Efektleri diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index eb9d140161..6942907990 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5576,6 +5576,11 @@ breakText Glyphs Гліфи @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` має бути lines, paragraphs, words або glyphs, а не {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` має бути "line" або "paragraph", а не {other} @msg `align` must be "left", "center" or "right", not {other} `align` має бути "left", "center" або "right", а не {other} + File + Number Файл + номер + File + Data Set Name Файл + назва набору даних + Data Set Name Назва набору даних +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` має бути `fileNumber`, `fileDataSetName` або `dataSetName` +@msg no free data set file name in destination folder У папці призначення немає вільного імені файлу набору даних # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Ефекти контуру diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f6b926e07f..1c3c493879 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5578,6 +5578,11 @@ breakText Glyphs Glyph @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` phải là lines, paragraphs, words hoặc glyphs, không phải {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` phải là "line" hoặc "paragraph", không phải {other} @msg `align` must be "left", "center" or "right", not {other} `align` phải là "left", "center" hoặc "right", không phải {other} + File + Number Tệp + số + File + Data Set Name Tệp + tên tập dữ liệu + Data Set Name Tên tập dữ liệu +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` phải là `fileNumber`, `fileDataSetName` hoặc `dataSetName` +@msg no free data set file name in destination folder Không có tên tệp tập dữ liệu còn trống trong thư mục đích # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Hiệu ứng đường dẫn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 96b5fbe0df..a85bc1a63a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5819,6 +5819,11 @@ breakText Glyphs 字形 @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` 必须是 lines、paragraphs、words 或 glyphs,而不是 {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` 必须是 "line" 或 "paragraph",而不是 {other} @msg `align` must be "left", "center" or "right", not {other} `align` 必须是 "left"、"center" 或 "right",而不是 {other} + File + Number 文件 + 编号 + File + Data Set Name 文件 + 数据集名称 + Data Set Name 数据集名称 +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` 必须是 `fileNumber`、`fileDataSetName` 或 `dataSetName` +@msg no free data set file name in destination folder 目标文件夹中没有可用的数据集文件名 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects 路径效果 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 147c3b0432..7fe82d929f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5615,6 +5615,11 @@ breakText Glyphs 字符 @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` 必須是 lines、paragraphs、words 或 glyphs,而不是 {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` 必須是 "line" 或 "paragraph",而不是 {other} @msg `align` must be "left", "center" or "right", not {other} `align` 必須是 "left"、"center" 或 "right",而不是 {other} + File + Number 檔案 + 編號 + File + Data Set Name 檔案 + 資料集名稱 + Data Set Name 資料集名稱 +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` 必須是 `fileNumber`、`fileDataSetName` 或 `dataSetName` +@msg no free data set file name in destination folder 目的地資料夾中沒有可用的資料集檔案名稱 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects 路徑效果 diff --git a/docs/mcp.md b/docs/mcp.md index 719ac6d40c..1b5c7e3c6a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1622,12 +1622,13 @@ already walks Image Trace. Short agent entry points: `%`). 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. - 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 - Export end the file name of a step with `format` in that `format`, in lower case and without a leading dot, when it - is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), and otherwise in the - format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). A step without `format` keeps the - source file's extension (`.vectorcraft` over data sets). + destinationFolder?, datasetFileNaming?: fileNumber|fileDataSetName|dataSetName, 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 Export end + the file name of a step with `format` in that `format`, in lower case and without a leading dot, + when it is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), + and otherwise in the format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). + A step without `format` keeps the source file's extension (`.vectorcraft` over data sets). - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace settings, such as `colours`, is an error that names it and the nearest setting (`colors`), as for a command's own keys. @@ -2963,10 +2964,16 @@ earlier step deleted the active artboard when it was the last one), the step get remote mode, MCP's `run_command` calls and each step of the `command_batch` tool get the active artboard too. The Actions panel plays an action as a `command.batch`. The Actions panel menu's Batch… runs `action.batch`: the same steps on every readable file in a folder (or every data set of the open document), with -destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. Over data sets, the folder -destination and the overrides name each file after the document and the data set (`_.`). +destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. For a Data Sets source, +`datasetFileNaming` chooses File + Number (`source001`), File + Data Set Name (`source_Alpha`), or Data Set Name +(`Alpha`). An omitted parameter keeps File + Data Set Name for existing callers; the dialog starts with File + +Number. A folder source ignores this parameter. The folder destination and overridden Save/Export paths use the +chosen stem with the output format's extension. An empty data set name under Data Set Name falls back to the +document stem plus its three-digit ordinal. Batch writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and -adds `-2`, `-3`… to a name an earlier data set used (compared without case). Caps: 500 files or data sets, 8 +adds the next free `-2`, `-3` suffix to a stem already used in the batch or whose generated output path exists in +the destination folder before the batch starts. Under Data Set Name, VectorCraft also makes Windows device names +safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 files or data sets, 8 folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6f0a426b26..bcc92a39b0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -548,6 +548,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. + - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output name already in the destination folder gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). + - 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 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, 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`). - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). From 1b4c050bd3781f5e9266f6d785dc9b0577cc6ad7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 17:18:03 -0700 Subject: [PATCH 37/70] Batch: check existing data set outputs only in a folder the batch may read and write The `-2`, `-3` suffix for a data set output that already exists is now looked up only when the destination folder and the output path pass the read and write access checks, so a call cannot learn which files exist in a folder it may not use. The lookup uses only extensions of formats the app knows, without path separators or `..`, and only paths whose parent is the destination folder. A step whose `format` is unknown keeps its own path instead of being pointed into the destination folder. A data set or document named `.` or `..` gets the `Untitled` stem with its three-digit number. --- crates/engine/src/cmd/fileio/action_batch.rs | 155 ++++++++++++++++++- crates/engine/src/cmd/fileio/commands.rs | 2 +- docs/mcp.md | 8 +- docs/target-app-parity.md | 2 +- 4 files changed, 154 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index f2310962ee..307f43174d 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -221,7 +221,7 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou "folder" => { let folder = run.dest_folder.ok_or_else(|| bad("action.batch", "missing destination folder"))?; let out_ext = if ext.is_empty() { "vectorcraft" } else { ext }; - let out = std::path::Path::new(folder).join(format!("{stem}.{out_ext}")); + let out = output_path(folder, stem, out_ext).ok_or_else(|| bad("action.batch", "unsafe destination file name"))?; let out = out.to_string_lossy().into_owned(); // When `close` is false (data sets), write a copy so the template keeps its path. write_result(s, &out, out_ext, !close)?; @@ -235,7 +235,8 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou } /// Builds the three data set naming forms, replaces unsafe name characters, and adds `-2`, `-3` -/// suffixes when a stem was used earlier or its output already exists in the destination folder. +/// suffixes when a stem was used earlier or its output already exists in a folder the batch may +/// read and write. #[cfg(not(target_arch = "wasm32"))] fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>) -> Result> { use super::screens::{file_part, safe_file_name}; @@ -243,13 +244,16 @@ fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>) if !matches!(naming, "fileNumber" | "fileDataSetName" | "dataSetName") { return Err(bad("action.batch", "`datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName`")); } + let doc_stem = safe_file_name(doc_stem); + let doc_stem = if doc_stem.is_empty() || matches!(doc_stem.as_str(), "." | "..") { "Untitled" } else { &doc_stem }; let bases = names.iter().enumerate().map(|(i, name)| { let safe = file_part(name); let safe_data_set = safe_file_name(&safe); + let ordinal = format!("{doc_stem}{:03}", i + 1); match naming { - "fileNumber" => format!("{doc_stem}{:03}", i + 1), + "fileNumber" => ordinal, "dataSetName" if !safe_data_set.is_empty() => safe_data_set, - "dataSetName" => format!("{doc_stem}{:03}", i + 1), + "dataSetName" => ordinal, _ => format!("{doc_stem}_{safe}"), } }); @@ -283,8 +287,15 @@ fn dataset_output_extensions(run: &Run<'_>) -> Vec { let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) || (run.override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection")); if writes { - let ext = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); - extensions.push(ext.map_or_else(|| "vectorcraft".to_string(), format_extension)); + let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); + let ext = match format { + Some(format) if super::format(format).is_some() => format_extension(format), + Some(_) => continue, + None => "vectorcraft".to_string(), + }; + if safe_extension(&ext) { + extensions.push(ext); + } } } extensions @@ -293,7 +304,36 @@ fn dataset_output_extensions(run: &Run<'_>) -> Vec { #[cfg(not(target_arch = "wasm32"))] fn dataset_output_exists(folder: Option<&str>, stem: &str, extensions: &[String]) -> bool { let Some(folder) = folder else { return false }; - extensions.iter().any(|ext| std::path::Path::new(folder).join(format!("{stem}.{ext}")).exists()) + if super::may_read(folder).is_err() || super::may_write(folder).is_err() { + return false; + } + extensions.iter().any(|ext| { + output_path(folder, stem, ext).is_some_and(|path| { + let path_text = path.to_string_lossy(); + super::may_read(&path_text).is_ok() && super::may_write(&path_text).is_ok() && path.exists() + }) + }) +} + +/// Returns whether an extension is safe to use in an output file name. +#[cfg(not(target_arch = "wasm32"))] +fn safe_extension(ext: &str) -> bool { + !ext.is_empty() && !ext.contains(['/', '\\', ':']) && !ext.contains("..") +} + +/// Returns a path inside the destination folder for a safe stem and extension. +#[cfg(not(target_arch = "wasm32"))] +fn output_path(folder: &str, stem: &str, ext: &str) -> Option { + use std::path::Path; + if stem.is_empty() || matches!(stem, "." | "..") || stem.contains(['/', '\\']) || !safe_extension(ext) { + return None; + } + let name = format!("{stem}.{ext}"); + if name.contains(['/', '\\']) { + return None; + } + let path = Path::new(folder).join(name); + (path.parent() == Some(Path::new(folder))).then_some(path) } /// Save when the extension is a Save format; otherwise export (PNG, JPEG…). @@ -341,7 +381,10 @@ fn rewrite_paths( Some(f) => format_extension(f), None => default_ext.to_string(), }; - let file = std::path::Path::new(folder).join(format!("{stem}.{ext}")); + if params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()).is_some_and(|f| super::format(f).is_none()) { + return c; + } + let Some(file) = output_path(folder, stem, &ext) else { return c }; params.insert("path".into(), json!(file.to_string_lossy())); if let Some(o) = c.as_object_mut() { o.insert("params".into(), Value::Object(params)); @@ -721,6 +764,102 @@ mod tests { assert_eq!(file_names(&dest), ["Alpha-2.svg", "Alpha.svg"]); } + #[test] + fn batch_does_not_probe_a_denied_destination() { + let allowed = tmp("probe-allowed"); + let denied = tmp("probe-denied"); + std::fs::write(denied.join("Alpha.svg"), b"private").unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[allowed.as_path()], &[allowed.as_path()]).unwrap().unwrap(); + let steps = [json!({"command": "document.export", "params": {"format": "svg"}})]; + let folder = denied.to_string_lossy().into_owned(); + let run = Run { + label: "Test", + steps: &steps, + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: Some(&folder), + }; + crate::file_access::confine(Some(&roots), || { + assert_eq!(dataset_stems(&["Alpha".into()], "source", "dataSetName", &run).unwrap(), ["Alpha"]); + let mut s = with_data_sets(&["Alpha"]); + let result = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", "destination": "none", + "destinationFolder": folder, "overrideExport": true, + "commands": steps, + }), + ) + .unwrap(); + assert!(!result.to_string().contains("Alpha-2"), "{result}"); + }); + } + + #[test] + fn batch_does_not_probe_unknown_format_paths() { + let root = tmp("probe-format"); + let folder = root.join("out"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(root.join("outside"), b"private").unwrap(); + for format in ["../outside", "x/../../outside", "..\\..\\outside"] { + let steps = [json!({"command": "document.export", "params": {"format": format}})]; + let folder = folder.to_string_lossy().into_owned(); + let run = Run { + label: "Test", + steps: &steps, + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: Some(&folder), + }; + assert_eq!( + dataset_stems(&["Alpha".into()], "source", "dataSetName", &run).unwrap_or_else(|e| panic!("{format}: {e}")), + ["Alpha"], + "{format}" + ); + assert_eq!(rewrite_paths(&steps, false, true, Some(&folder), "Alpha", "vectorcraft"), steps, "{format}"); + } + } + + #[test] + fn batch_probe_and_dot_names_stay_in_destination() { + let root = tmp("probe-parent"); + let folder = root.join("out"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(root.join("outside.svg"), b"private").unwrap(); + let folder = folder.to_string_lossy().into_owned(); + let run = Run { + label: "Test", + steps: &[], + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: Some(&folder), + }; + assert_eq!(dataset_stems(&[".".into(), "..".into()], ".", "dataSetName", &run).unwrap(), ["Untitled001", "Untitled002"]); + assert_eq!(dataset_stems(&["Alpha".into()], "..", "fileNumber", &run).unwrap(), ["Untitled001"]); + let output = root.join("named"); + let mut s = with_data_sets(&[".", ".."]); + let r = named_batch(&mut s, &output, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&output), ["Untitled001.vectorcraft", "Untitled002.vectorcraft"]); + } + + #[test] + fn batch_probe_rejects_parent_escape() { + let root = tmp("probe-parent-only"); + let folder = root.join("out"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(root.join("outside.svg"), b"private").unwrap(); + let folder = folder.to_string_lossy().into_owned(); + assert!(!dataset_output_exists(Some(&folder), "../outside", &["svg".into()])); + } + #[test] fn batch_rejects_unknown_data_set_naming_but_ignores_it_for_folders() { let mut s = with_data_sets(&["Alpha"]); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index ba39d0bdb1..9c6861f555 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or present in the destination folder gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", always, action_batch::action_batch ), diff --git a/docs/mcp.md b/docs/mcp.md index 1b5c7e3c6a..996cee88b1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1629,6 +1629,8 @@ already walks Image Trace. Short agent entry points: when it is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), and otherwise in the format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). A step without `format` keeps the source file's extension (`.vectorcraft` over data sets). + An output already in a destination folder gets the next free `-2`, `-3` suffix only when the batch + may read and write that folder. - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace settings, such as `colours`, is an error that names it and the nearest setting (`colors`), as for a command's own keys. @@ -2972,9 +2974,9 @@ chosen stem with the output format's extension. An empty data set name under Dat document stem plus its three-digit ordinal. Batch writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds the next free `-2`, `-3` suffix to a stem already used in the batch or whose generated output path exists in -the destination folder before the batch starts. Under Data Set Name, VectorCraft also makes Windows device names -safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 files or data sets, 8 -folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, +a destination folder the batch may read and write before it starts. Under Data Set Name, VectorCraft also makes +Windows device names safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 +files or data sets, 8 folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection tool, a Shift-click on an empty spot inside an artboard makes it active and keeps the selection. Choosing the Artboard diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bcc92a39b0..0634080f47 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -548,7 +548,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output name already in the destination folder gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). + - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). - 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 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, 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`). From c55e4a226ea1607a1350279179b74ec2f28893d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 18:56:42 -0700 Subject: [PATCH 38/70] Batch: pass the data set naming choice in the batch run The naming choice reaches batch_datasets as a field of the run, and the short Batch entry in docs/mcp.md is back to main's text; the longer Batch section names datasetFileNaming and when an existing output gets a suffix. --- crates/engine/src/cmd/fileio/action_batch.rs | 14 ++++++--- docs/mcp.md | 33 +++++++++----------- 2 files changed, 25 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 307f43174d..565710f9e5 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -34,6 +34,7 @@ struct Run<'a> { override_export: bool, destination: &'a str, dest_folder: Option<&'a str>, + dataset_file_naming: &'a str, } /// Play `commands` on each source file or data set. @@ -90,10 +91,11 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { override_export: bool_or(p, "overrideExport", true), destination, dest_folder: dest_folder.as_deref(), + dataset_file_naming: p.get("datasetFileNaming").map_or("fileDataSetName", |v| v.as_str().unwrap_or("")), }; match source { "folder" => batch_folder(s, C, p, override_open, &run), - "datasets" => batch_datasets(s, C, &run, p), + "datasets" => batch_datasets(s, C, &run), _ => Err(bad(C, "`source` must be `folder` or `datasets`")), } } @@ -134,7 +136,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: } #[cfg(not(target_arch = "wasm32"))] -fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>, p: &Value) -> Result { +fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { let st = s.doc()?; let names: Vec = st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect(); if names.is_empty() { @@ -144,8 +146,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>, p: &Value) -> Resul return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets"))); } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); - let naming = p.get("datasetFileNaming").map_or("fileDataSetName", |v| v.as_str().unwrap_or("")); - let stems = dataset_stems(&names, &doc_stem, naming, run)?; + let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run)?; let steps = filter_steps(run.steps, true, false); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); @@ -690,6 +691,7 @@ mod tests { override_export: true, destination: "none", dest_folder: None, + dataset_file_naming: "fileDataSetName", }; let stems = dataset_stems(&names, "source", "fileNumber", &run).unwrap(); for n in [1, 2, 10, 100, 500] { @@ -714,6 +716,7 @@ mod tests { override_export: true, destination: "none", dest_folder: None, + dataset_file_naming: "fileDataSetName", }; assert_eq!(dataset_stems(&[String::new()], "Untitled", "dataSetName", &run).unwrap(), ["Untitled001"]); assert_eq!(dataset_stems(&[" ".to_string()], "Untitled", "dataSetName", &run).unwrap(), ["Untitled001"]); @@ -780,6 +783,7 @@ mod tests { override_export: true, destination: "none", dest_folder: Some(&folder), + dataset_file_naming: "fileDataSetName", }; crate::file_access::confine(Some(&roots), || { assert_eq!(dataset_stems(&["Alpha".into()], "source", "dataSetName", &run).unwrap(), ["Alpha"]); @@ -815,6 +819,7 @@ mod tests { override_export: true, destination: "none", dest_folder: Some(&folder), + dataset_file_naming: "fileDataSetName", }; assert_eq!( dataset_stems(&["Alpha".into()], "source", "dataSetName", &run).unwrap_or_else(|e| panic!("{format}: {e}")), @@ -840,6 +845,7 @@ mod tests { override_export: true, destination: "none", dest_folder: Some(&folder), + dataset_file_naming: "fileDataSetName", }; assert_eq!(dataset_stems(&[".".into(), "..".into()], ".", "dataSetName", &run).unwrap(), ["Untitled001", "Untitled002"]); assert_eq!(dataset_stems(&["Alpha".into()], "..", "fileNumber", &run).unwrap(), ["Untitled001"]); diff --git a/docs/mcp.md b/docs/mcp.md index 996cee88b1..bee6b96813 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1622,15 +1622,12 @@ already walks Image Trace. Short agent entry points: `%`). 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. - Batch: `action.batch {commands, source?: folder|datasets, folder?, destination?: none|saveAndClose|folder, - destinationFolder?, datasetFileNaming?: fileNumber|fileDataSetName|dataSetName, 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 Export end - the file name of a step with `format` in that `format`, in lower case and without a leading dot, - when it is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), - and otherwise in the format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). - A step without `format` keeps the source file's extension (`.vectorcraft` over data sets). - An output already in a destination folder gets the next free `-2`, `-3` suffix only when the batch - may read and write that 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 + Export end the file name of a step with `format` in that `format`, in lower case and without a leading dot, when it + is one of the format's extensions (`.svg` and `SVG` give `.svg`, `.JPEG` gives `.jpeg`), and otherwise in the + format's first extension (`png8` gives `.png`, `template` gives `.vctemplate`). A step without `format` keeps the + source file's extension (`.vectorcraft` over data sets). - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace settings, such as `colours`, is an error that names it and the nearest setting (`colors`), as for a command's own keys. @@ -2967,15 +2964,15 @@ remote mode, MCP's `run_command` calls and each step of the `command_batch` tool Actions panel plays an action as a `command.batch`. The Actions panel menu's Batch… runs `action.batch`: the same steps on every readable file in a folder (or every data set of the open document), with destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. For a Data Sets source, -`datasetFileNaming` chooses File + Number (`source001`), File + Data Set Name (`source_Alpha`), or Data Set Name -(`Alpha`). An omitted parameter keeps File + Data Set Name for existing callers; the dialog starts with File + -Number. A folder source ignores this parameter. The folder destination and overridden Save/Export paths use the -chosen stem with the output format's extension. An empty data set name under Data Set Name falls back to the -document stem plus its three-digit ordinal. -Batch writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and -adds the next free `-2`, `-3` suffix to a stem already used in the batch or whose generated output path exists in -a destination folder the batch may read and write before it starts. Under Data Set Name, VectorCraft also makes -Windows device names safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 +`datasetFileNaming?: fileNumber | fileDataSetName | dataSetName` chooses File + Number (`source001`), +File + Data Set Name (`source_Alpha`), or Data Set Name (`Alpha`). An omitted parameter keeps File + Data Set Name +for existing callers; the dialog starts with File + Number. A folder source ignores this parameter. The folder +destination and overridden Save/Export paths use the chosen stem with the output format's extension. An empty data +set name under Data Set Name falls back to the document stem plus its three-digit ordinal. Batch writes `/`, `\`, +`:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds the next free `-2`, +`-3` suffix to a stem already used in the batch (compared without case). An output already in a destination folder +gets the next free suffix only when the batch may read and write that folder before it starts. Under Data Set Name, +VectorCraft makes Windows device names safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 files or data sets, 8 folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection From 483c191e242c3e3bf8edfdf0a9c21aa600a13477 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 19:13:07 -0700 Subject: [PATCH 39/70] Batch: keep a backslash in a source file name on Linux and macOS Destination and Override Save/Export paths reject only the current platform's path separators, so a folder batch writes `a\b.svg` into the destination folder on systems where that is one file name. --- crates/engine/src/cmd/fileio/action_batch.rs | 72 +++++++++++++++++++- 1 file changed, 70 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 565710f9e5..6481191efd 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -326,11 +326,11 @@ fn safe_extension(ext: &str) -> bool { #[cfg(not(target_arch = "wasm32"))] fn output_path(folder: &str, stem: &str, ext: &str) -> Option { use std::path::Path; - if stem.is_empty() || matches!(stem, "." | "..") || stem.contains(['/', '\\']) || !safe_extension(ext) { + if stem.is_empty() || matches!(stem, "." | "..") || stem.contains(std::path::is_separator) || !safe_extension(ext) { return None; } let name = format!("{stem}.{ext}"); - if name.contains(['/', '\\']) { + if name.contains(std::path::is_separator) { return None; } let path = Path::new(folder).join(name); @@ -511,6 +511,74 @@ mod tests { assert!(dest.join("b.svg").is_file(), "b.svg written"); } + #[cfg(unix)] + #[test] + fn batch_folder_keeps_backslash_in_source_file_name() { + let src = tmp("backslash-src"); + let dest = tmp("backslash-dest"); + write_svg(&src, "a\\b.svg", "#f00"); + let mut s = Session::new(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "folder", + "folder": src.to_string_lossy(), + "destination": "folder", + "destinationFolder": dest.to_string_lossy(), + "stopOnError": true, + "commands": [{"command": "object.unlockAll", "params": {}}] + }), + ) + .unwrap(); + assert_eq!(r["count"], 1, "{r}"); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(r["stopped"], false, "{r}"); + assert!(dest.join("a\\b.svg").is_file(), "{r}"); + } + + #[cfg(unix)] + #[test] + fn batch_folder_override_export_keeps_backslash_in_source_file_name() { + let src = tmp("backslash-export-src"); + let dest = tmp("backslash-export-dest"); + write_svg(&src, "a\\b.svg", "#f00"); + let mut s = Session::new(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "folder", + "folder": src.to_string_lossy(), + "destination": "folder", + "destinationFolder": dest.to_string_lossy(), + "stopOnError": true, + "commands": [{"command": "document.export", "params": {"format": "svg"}}] + }), + ) + .unwrap(); + assert_eq!(r["count"], 1, "{r}"); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(r["stopped"], false, "{r}"); + assert_eq!(file_names(&dest), ["a\\b.svg"], "{r}"); + } + + #[test] + fn output_path_accepts_only_platform_file_name_separators() { + let folder = tmp("output-path"); + let folder = folder.to_string_lossy(); + let backslash = output_path(&folder, "a\\b", "svg"); + #[cfg(windows)] + assert!(backslash.is_none()); + #[cfg(not(windows))] + assert_eq!(backslash, Some(std::path::Path::new(folder.as_ref()).join("a\\b.svg"))); + for stem in ["a/b", ".", "..", ""] { + assert!(output_path(&folder, stem, "svg").is_none(), "{stem:?}"); + } + #[cfg(windows)] + assert_eq!(std::path::Path::new("a\\b.svg").file_stem(), Some(std::ffi::OsStr::new("b"))); + } + #[test] fn batch_skips_open_steps_when_override_open() { let src = tmp("open"); From 5dcc65d69a377bd783f5dce05c9f469090812b2b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 20:59:11 -0700 Subject: [PATCH 40/70] Batch: keep existing artboard files when choosing data set file names When a step can write one file per artboard (Save in the native, template or .ai formats, or Export in SVG, EPS, the raster formats, DXF, EMF, WMF or .ai) and the document has more than one artboard, an existing file with one of the stem's artboard file names now gives the data set the next free -2, -3 suffix, as the stem's own file does. Names a data set's outputs will take are also reserved for the later data sets of the same batch. --- crates/engine/src/cmd/fileio/action_batch.rs | 246 +++++++++++++++++-- docs/mcp.md | 6 +- 2 files changed, 227 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 6481191efd..1caa98db7d 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -146,7 +146,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets"))); } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); - let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run)?; + let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?; let steps = filter_steps(run.steps, true, false); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); @@ -239,7 +239,7 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou /// suffixes when a stem was used earlier or its output already exists in a folder the batch may /// read and write. #[cfg(not(target_arch = "wasm32"))] -fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>) -> Result> { +fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Result> { use super::screens::{file_part, safe_file_name}; if !matches!(naming, "fileNumber" | "fileDataSetName" | "dataSetName") { @@ -258,13 +258,19 @@ fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>) _ => format!("{doc_stem}_{safe}"), } }); - let extensions = dataset_output_extensions(run); + let outputs = dataset_output_extensions(run, doc); let mut taken = std::collections::HashSet::new(); + let mut reserved = std::collections::HashSet::new(); let mut stems = Vec::with_capacity(bases.len()); for base in bases { let mut candidate = base.clone(); let mut suffix = 2; - while taken.contains(&candidate.to_lowercase()) || dataset_output_exists(run.dest_folder, &candidate, &extensions) { + while taken.contains(&candidate.to_lowercase()) + || dataset_output_paths(run.dest_folder, &candidate, &outputs, doc) + .iter() + .any(|path| reserved.contains(&path.to_string_lossy().to_lowercase())) + || dataset_output_exists(run.dest_folder, &candidate, &outputs, doc) + { if suffix > 10_000 { return Err(bad("action.batch", "no free data set file name in destination folder")); } @@ -272,16 +278,27 @@ fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>) suffix += 1; } taken.insert(candidate.to_lowercase()); + reserved + .extend(dataset_output_paths(run.dest_folder, &candidate, &outputs, doc).into_iter().map(|path| path.to_string_lossy().to_lowercase())); stems.push(candidate); } Ok(stems) } #[cfg(not(target_arch = "wasm32"))] -fn dataset_output_extensions(run: &Run<'_>) -> Vec { - let mut extensions = Vec::new(); +struct DatasetOutput { + ext: String, + artboards: bool, + joiner: &'static str, +} + +/// Lists step output extensions and reserves artboard file names when the document has multiple artboards. +/// Per-artboard names count for vectorcraft, template, AI and AIT saves and SVG, SVGZ, EPS, raster, DXF, EMF, WMF and AI exports. +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Vec { + let mut outputs = Vec::new(); if run.destination == "folder" { - extensions.push("vectorcraft".to_string()); + outputs.push(DatasetOutput { ext: "vectorcraft".into(), artboards: false, joiner: "-" }); } for step in run.steps { let id = step.get("command").and_then(Value::as_str).unwrap_or(""); @@ -295,27 +312,75 @@ fn dataset_output_extensions(run: &Run<'_>) -> Vec { None => "vectorcraft".to_string(), }; if safe_extension(&ext) { - extensions.push(ext); + let format_id = format.and_then(super::format).map(|f| f.id).unwrap_or("vectorcraft"); + let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs"); + let artboards = doc.artboards.len() > 1 + && if is_save { + matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") + } else { + id == "document.export" + && matches!( + format_id, + "svg" + | "svgz" + | "eps" + | "png" + | "jpg" + | "webp" + | "gif" + | "png8" + | "tiff" + | "bmp" + | "tga" + | "psd" + | "dxf" + | "emf" + | "wmf" + | "ai" + ) + }; + outputs.push(DatasetOutput { ext, artboards, joiner: if format_id == "eps" { "_" } else { "-" } }); } } } - extensions + outputs } #[cfg(not(target_arch = "wasm32"))] -fn dataset_output_exists(folder: Option<&str>, stem: &str, extensions: &[String]) -> bool { +fn dataset_output_exists(folder: Option<&str>, stem: &str, outputs: &[DatasetOutput], doc: &vectorcraft_doc::Document) -> bool { let Some(folder) = folder else { return false }; if super::may_read(folder).is_err() || super::may_write(folder).is_err() { return false; } - extensions.iter().any(|ext| { - output_path(folder, stem, ext).is_some_and(|path| { - let path_text = path.to_string_lossy(); - super::may_read(&path_text).is_ok() && super::may_write(&path_text).is_ok() && path.exists() - }) + dataset_output_paths(Some(folder), stem, outputs, doc).iter().any(|path| { + let path_text = path.to_string_lossy(); + super::may_read(&path_text).is_ok() && super::may_write(&path_text).is_ok() && path.exists() }) } +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_paths(folder: Option<&str>, stem: &str, outputs: &[DatasetOutput], doc: &vectorcraft_doc::Document) -> Vec { + let Some(folder) = folder else { return Vec::new() }; + let boards: Vec<_> = (0..doc.artboards.len()).collect(); + let mut parts = super::artboard_file_names(doc, &boards); + for board in boards { + parts.extend(super::artboard_file_names(doc, &[board])); + } + let mut paths = Vec::new(); + for output in outputs { + if !safe_extension(&output.ext) || super::format(&output.ext).is_none() { + continue; + } + paths.extend(output_path(folder, stem, &output.ext)); + if output.artboards { + for part in &parts { + paths.extend(output_path(folder, &format!("{stem}{}{part}", output.joiner), &output.ext)); + } + } + } + paths +} + /// Returns whether an extension is safe to use in an output file name. #[cfg(not(target_arch = "wasm32"))] fn safe_extension(ext: &str) -> bool { @@ -761,7 +826,7 @@ mod tests { dest_folder: None, dataset_file_naming: "fileDataSetName", }; - let stems = dataset_stems(&names, "source", "fileNumber", &run).unwrap(); + let stems = dataset_stems(&names, "source", "fileNumber", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(); for n in [1, 2, 10, 100, 500] { assert_eq!(stems[n - 1], format!("source{n:03}")); } @@ -786,8 +851,8 @@ mod tests { dest_folder: None, dataset_file_naming: "fileDataSetName", }; - assert_eq!(dataset_stems(&[String::new()], "Untitled", "dataSetName", &run).unwrap(), ["Untitled001"]); - assert_eq!(dataset_stems(&[" ".to_string()], "Untitled", "dataSetName", &run).unwrap(), ["Untitled001"]); + assert_eq!(dataset_stems(&[String::new()], "Untitled", "dataSetName", &run, &s.doc().unwrap().doc).unwrap(), ["Untitled001"]); + assert_eq!(dataset_stems(&[" ".to_string()], "Untitled", "dataSetName", &run, &s.doc().unwrap().doc).unwrap(), ["Untitled001"]); } #[test] @@ -835,6 +900,126 @@ mod tests { assert_eq!(file_names(&dest), ["Alpha-2.svg", "Alpha.svg"]); } + #[test] + fn batch_artboard_export_keeps_existing_output() { + let dest = tmp("choice-existing-artboard-export"); + let existing = dest.join("Alpha-Artboard-1.png"); + std::fs::write(&existing, b"keep").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.export", "params": {"format": "png", "useArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-2-Artboard-1.png", "Alpha-2-Artboard-2.png", "Alpha-Artboard-1.png"]); + } + + #[test] + fn batch_remembered_separate_artboards_keeps_existing_output() { + let source = tmp("choice-remembered-separate-source"); + let dest = tmp("choice-remembered-separate-dest"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("document.save", &json!({"path": source.join("source.vectorcraft").to_string_lossy(), "separateArtboards": true})).unwrap(); + assert!(source.join("source-Artboard-1.vectorcraft").exists()); + let existing = dest.join("Alpha-Artboard-1.vectorcraft"); + std::fs::write(&existing, b"keep").unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save"}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!( + file_names(&dest), + ["Alpha-2-Artboard-1.vectorcraft", "Alpha-2-Artboard-2.vectorcraft", "Alpha-2.vectorcraft", "Alpha-Artboard-1.vectorcraft",] + ); + } + + #[test] + fn batch_pdf_export_ignores_artboard_named_file() { + let dest = tmp("choice-pdf-artboard-name"); + let existing = dest.join("Alpha-Artboard-1.pdf"); + std::fs::write(&existing, b"keep").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.export", "params": {"format": "pdf"}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-Artboard-1.pdf", "Alpha.pdf"]); + } + + #[test] + fn batch_separate_artboards_ignores_unrelated_extension() { + let dest = tmp("choice-separate-unrelated-extension"); + let unrelated = dest.join("Alpha-photo.png"); + std::fs::write(&unrelated, b"keep").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {"separateArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(unrelated).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-Artboard-1.vectorcraft", "Alpha-Artboard-2.vectorcraft", "Alpha-photo.png", "Alpha.vectorcraft"]); + } + + #[test] + fn batch_separate_artboards_reserves_prior_output_names() { + let dest = tmp("choice-separate-reserved"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha-Artboard-1"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {"separateArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert!(dest.join("Alpha-Artboard-1.vectorcraft").exists()); + assert!(dest.join("Alpha-Artboard-1-2.vectorcraft").exists()); + } + #[test] fn batch_does_not_probe_a_denied_destination() { let allowed = tmp("probe-allowed"); @@ -854,7 +1039,10 @@ mod tests { dataset_file_naming: "fileDataSetName", }; crate::file_access::confine(Some(&roots), || { - assert_eq!(dataset_stems(&["Alpha".into()], "source", "dataSetName", &run).unwrap(), ["Alpha"]); + assert_eq!( + dataset_stems(&["Alpha".into()], "source", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(), + ["Alpha"] + ); let mut s = with_data_sets(&["Alpha"]); let result = s .execute( @@ -890,7 +1078,8 @@ mod tests { dataset_file_naming: "fileDataSetName", }; assert_eq!( - dataset_stems(&["Alpha".into()], "source", "dataSetName", &run).unwrap_or_else(|e| panic!("{format}: {e}")), + dataset_stems(&["Alpha".into()], "source", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)) + .unwrap_or_else(|e| panic!("{format}: {e}")), ["Alpha"], "{format}" ); @@ -915,8 +1104,14 @@ mod tests { dest_folder: Some(&folder), dataset_file_naming: "fileDataSetName", }; - assert_eq!(dataset_stems(&[".".into(), "..".into()], ".", "dataSetName", &run).unwrap(), ["Untitled001", "Untitled002"]); - assert_eq!(dataset_stems(&["Alpha".into()], "..", "fileNumber", &run).unwrap(), ["Untitled001"]); + assert_eq!( + dataset_stems(&[".".into(), "..".into()], ".", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(), + ["Untitled001", "Untitled002"] + ); + assert_eq!( + dataset_stems(&["Alpha".into()], "..", "fileNumber", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(), + ["Untitled001"] + ); let output = root.join("named"); let mut s = with_data_sets(&[".", ".."]); let r = named_batch(&mut s, &output, Some("dataSetName")); @@ -931,7 +1126,12 @@ mod tests { std::fs::create_dir_all(&folder).unwrap(); std::fs::write(root.join("outside.svg"), b"private").unwrap(); let folder = folder.to_string_lossy().into_owned(); - assert!(!dataset_output_exists(Some(&folder), "../outside", &["svg".into()])); + assert!(!dataset_output_exists( + Some(&folder), + "../outside", + &[DatasetOutput { ext: "svg".into(), artboards: false, joiner: "-" }], + &vectorcraft_doc::Document::new(100.0, 80.0), + )); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index bee6b96813..f904715027 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2971,8 +2971,10 @@ destination and overridden Save/Export paths use the chosen stem with the output set name under Data Set Name falls back to the document stem plus its three-digit ordinal. Batch writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds the next free `-2`, `-3` suffix to a stem already used in the batch (compared without case). An output already in a destination folder -gets the next free suffix only when the batch may read and write that folder before it starts. Under Data Set Name, -VectorCraft makes Windows device names safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 +gets the next free suffix only when the batch may read and write that folder before it starts. When a step can write +one file per artboard and the document has several artboards, a file with one of those artboard file names for the +stem counts too. Under Data Set Name, VectorCraft makes Windows device names safe (`CON` becomes `CON-`). This is +VectorCraft's naming behavior. Caps: 500 files or data sets, 8 folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection From 6f0d5f509f1076f9df6365b157d52941a4667b01 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 01:04:34 -0700 Subject: [PATCH 41/70] i18n: package, missing-font, missing-link and CSS counts use each language's plural forms MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Package status and question, the missing-links note, the Missing Fonts and Find Linked Files search counts, the modified-links questions, Apply to All, and the CSS Properties panel's notes no longer use a fixed "(s)" or plural template. They use the plural rows of each catalog, so "1 linked file not found" and Czech "Nenalezeny 2 propojené soubory" read correctly. The searched line is built from two plural phrases, "{n} folder" and "{n} file", in a "{folders} and {files} searched" frame. Package rows that joined the note to the folder without a space now keep the space. --- crates/ui-egui/src/dialogs/missing_fonts.rs | 20 ++++++----- .../src/dialogs/missing_fonts/tests.rs | 23 +++++++++++++ crates/ui-egui/src/dialogs/missing_links.rs | 34 ++++++++++++++++--- crates/ui-egui/src/dialogs/package.rs | 28 +++++++++------ crates/ui-egui/src/dialogs/tests_package.rs | 23 +++++++++++-- crates/ui-egui/src/i18n/bg.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/bs.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/ca.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/cs.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/da.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/de.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/el.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/es.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/fi.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/fr.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/hu.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/id.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/it.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/ja.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/ka.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/ko.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/nl.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/pl.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/pt-br.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/ru.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/sv.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/tr.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/uk.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/vi.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/zh-hans.tsv | 32 +++++++++-------- crates/ui-egui/src/i18n/zh-hant.tsv | 32 +++++++++-------- crates/ui-egui/src/panels/css_properties.rs | 9 ++--- .../src/panels/tests_css_properties.rs | 27 +++++++++++++++ docs/target-app-parity.md | 1 + 34 files changed, 575 insertions(+), 422 deletions(-) diff --git a/crates/ui-egui/src/dialogs/missing_fonts.rs b/crates/ui-egui/src/dialogs/missing_fonts.rs index 16fa10bea8..205e4fa98e 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts.rs @@ -337,19 +337,21 @@ pub(super) fn progress(ui: &mut egui::Ui, d: &Dialog) { widgets::dim_name(ui, &crate::i18n::message(crate::i18n::current(), e)); } if let Some(s) = d.fields.get("searched") { - let (folders, files) = (s["folders"].to_string(), s["files"].to_string()); - widgets::dim_name( - ui, - &crate::i18n::fmt(tl!("{folders} folder(s) and {files} file(s) searched"), &[("folders", &folders), ("files", &files)]), - ); + let folders = crate::i18n::tn(s["folders"].as_u64().unwrap_or(0), "{n} folder", "{n} folders"); + let files = crate::i18n::tn(s["files"].as_u64().unwrap_or(0), "{n} file", "{n} files"); + widgets::dim_name(ui, &crate::i18n::fmt(tl!("{folders} and {files} searched"), &[("folders", &folders), ("files", &files)])); } - let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).filter(|n| *n > 0).map(|n| n.to_string()); + let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).filter(|n| *n > 0); if let Some(n) = count("skipped") { - let text = tl!("{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones"); - widgets::dim_name(ui, &crate::i18n::fmt(text, &[("count", &n)])); + let text = crate::i18n::tn( + n, + "{n} folder skipped, such as another app's or the system's folder or a hidden one", + "{n} folders skipped, such as other apps' and the system's folders and hidden ones", + ); + widgets::dim_name(ui, &text); } if let Some(n) = count("unreadable") { - widgets::dim_name(ui, &crate::i18n::fmt(tl!("{count} folder(s) or file(s) couldn't be read"), &[("count", &n)])); + widgets::dim_name(ui, &crate::i18n::tn(n, "{n} folder or file couldn't be read", "{n} folders or files couldn't be read")); } if matches!(d.fields.get("stopped").and_then(Value::as_str), Some("time" | "limit")) { widgets::dim_label(ui, tl!("The search stopped at its limit: search a smaller folder.")); diff --git a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs index 20266d97b3..c2b2a4e6c8 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -328,6 +328,29 @@ fn files_go_with_their_fonts_by_name() { assert_eq!((d.str("state"), &d.fields["chosen"]), ("done".to_string(), &json!([]))); } +/// A folder search's counts use the forms the language's plural rule picks for each count. +#[test] +fn search_counts_use_each_count_form() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut progress_text = |code: &str, n: u64| { + crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); + let d = Dialog::new(KIND, json!({"state": "done", "searched": {"folders": n, "files": n}, "unreadable": n})); + let text = crate::tests_labels::painted_text(&mut app, |_, ui| progress(ui, &d)); + crate::i18n::set_current(crate::i18n::Lang::EN); + text + }; + let text = progress_text("en", 1); + assert!(text.contains("1 folder and 1 file searched") && text.contains("1 folder or file couldn't be read"), "{text}"); + for (n, searched, unreadable) in [ + (1, "Prohledáno: 1 složka, 1 soubor", "Nepodařilo se přečíst 1 složku nebo soubor"), + (2, "Prohledáno: 2 složky, 2 soubory", "Nepodařilo se přečíst 2 složky nebo soubory"), + (5, "Prohledáno: 5 složek, 5 souborů", "Nepodařilo se přečíst 5 složek nebo souborů"), + ] { + let text = progress_text("cs", n); + assert!(text.contains(searched) && text.contains(unreadable), "{n}: {text}"); + } +} + #[test] fn the_web_says_how_many_fonts_are_missing() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/missing_links.rs b/crates/ui-egui/src/dialogs/missing_links.rs index b717057698..fe6a804860 100644 --- a/crates/ui-egui/src/dialogs/missing_links.rs +++ b/crates/ui-egui/src/dialogs/missing_links.rs @@ -75,17 +75,23 @@ pub(super) fn ask_next(app: &mut VectorcraftApp, rest: Vec, modified: Vec /// With Update Links: Ask When Modified, offer to read the modified linked files `ids` again. fn ask_update(app: &mut VectorcraftApp, ids: Vec) { - ask(app, ids, tl!("{count} linked image(s) changed since this document was saved. Show the new versions?")); + ask( + app, + ids, + "{n} linked image changed since this document was saved. Show the new version?", + "{n} linked images changed since this document was saved. Show the new versions?", + ); } /// The same offer for linked files another app changed while the document is open /// ([`vectorcraft_engine::link_watch`]). #[cfg(not(target_arch = "wasm32"))] pub(crate) fn ask_update_changed(app: &mut VectorcraftApp, ids: Vec) { - ask(app, ids, tl!("{count} linked image(s) changed on disk. Show the new versions?")); + ask(app, ids, "{n} linked image changed on disk. Show the new version?", "{n} linked images changed on disk. Show the new versions?"); } -fn ask(app: &mut VectorcraftApp, ids: Vec, question: &str) { +/// Ask about the modified linked files `ids`; `one` and `other` are the English forms of the question. +fn ask(app: &mut VectorcraftApp, ids: Vec, one: &str, other: &str) { if ids.is_empty() { return; } @@ -93,7 +99,7 @@ fn ask(app: &mut VectorcraftApp, ids: Vec, question: &str) { app.status(format!("{} linked image(s) changed on disk: Update Links shows the new versions", ids.len())); return; } - let detail = crate::i18n::fmt(question, &[("count", &ids.len().to_string())]); + let detail = crate::i18n::tn(ids.len() as u64, one, other); super::confirm::ask(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids })); } @@ -133,7 +139,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if rest > 0 { ui.add_space(10.0); let all = d.bool("applyToAll"); - let label = crate::i18n::fmt(tl!("Apply to All ({count} more missing)"), &[("count", &rest.to_string())]); + let label = crate::i18n::tn(rest as u64, "Apply to All ({n} more missing)", "Apply to All ({n} more missing)"); if widgets::check(ui, &label, all, true) { d.fields.insert("applyToAll".into(), json!(!all)); } @@ -262,6 +268,24 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + /// The question about modified linked files uses the form the language's plural rule picks for + /// the count. + #[test] + fn the_modified_links_question_uses_each_count_form() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut question = |code: &str, n: u64| { + crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); + ask_update(&mut app, (0..n).map(|id| json!(id)).collect()); + let detail = app.ui.dialog.take().map(|d| d.str("detail")); + crate::i18n::set_current(crate::i18n::Lang::EN); + detail.unwrap_or_default() + }; + assert_eq!(question("en", 1), "1 linked image changed since this document was saved. Show the new version?"); + assert_eq!(question("cs", 1), "Od uložení dokumentu se změnil 1 propojený obrázek. Zobrazit novou verzi?"); + assert_eq!(question("cs", 2), "Od uložení dokumentu se změnily 2 propojené obrázky. Zobrazit nové verze?"); + assert_eq!(question("cs", 5), "Od uložení dokumentu se změnilo 5 propojených obrázků. Zobrazit nové verze?"); + } + #[test] fn apply_to_all_replaces_the_others_from_the_same_folder() { let (mut app, dir, _) = opened_without_links("all"); diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 839f763835..9c2b3deb97 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -155,32 +155,38 @@ fn packaged(app: &mut VectorcraftApp, r: Result, web: bool, later // The fonts left out: their license doesn't allow it, or they aren't on this computer. let fonts = r["skippedFonts"].as_array().into_iter().flatten().filter_map(|f| f["font"].as_str()).collect::>().join(", "); let shown_note = package_status_note(missing, &fonts); - let n_s = n.to_string(); + let n = n as u64; if web { let (name, data) = (r["name"].as_str().unwrap_or("package.zip"), r["dataBase64"].as_str().unwrap_or_default()); let bytes = vectorcraft_format::base64_decode(data).ok_or("the package came back damaged")?; io::write_named(app, None, name, &bytes)?; let status = if shown_note.is_empty() { - crate::i18n::fmt(tl!("Packaged {n} file(s)"), &[("n", &n_s)]) + crate::i18n::tn(n, "Packaged {n} file", "Packaged {n} files") } else { - crate::i18n::fmt(tl!("Packaged {n} file(s) {note}"), &[("n", &n_s), ("note", &shown_note)]) + crate::i18n::fmt(&crate::i18n::tn(n, "Packaged {n} file {note}", "Packaged {n} files {note}"), &[("note", &shown_note)]) }; app.status(status); return Ok(r); } let folder = r["folder"].as_str().unwrap_or_default().to_string(); let status = if shown_note.is_empty() { - crate::i18n::fmt(tl!("Packaged {n} file(s) in {folder}"), &[("n", &n_s), ("folder", &folder)]) + crate::i18n::fmt(&crate::i18n::tn(n, "Packaged {n} file in {folder}", "Packaged {n} files in {folder}"), &[("folder", &folder)]) } else { - crate::i18n::fmt(tl!("Packaged {n} file(s) in {folder} {note}"), &[("n", &n_s), ("folder", &folder), ("note", &shown_note)]) + crate::i18n::fmt( + &crate::i18n::tn(n, "Packaged {n} file in {folder} {note}", "Packaged {n} files in {folder} {note}"), + &[("folder", &folder), ("note", &shown_note)], + ) }; app.status(status); let detail = if shown_note.is_empty() { - crate::i18n::fmt(tl!("{count} file(s) in {folder}. Show the package folder?"), &[("count", &n_s), ("folder", &folder)]) + crate::i18n::fmt( + &crate::i18n::tn(n, "{n} file in {folder}. Show the package folder?", "{n} files in {folder}. Show the package folder?"), + &[("folder", &folder)], + ) } else { crate::i18n::fmt( - tl!("{count} file(s) in {folder} {note}. Show the package folder?"), - &[("count", &n_s), ("folder", &folder), ("note", &shown_note)], + &crate::i18n::tn(n, "{n} file in {folder} {note}. Show the package folder?", "{n} files in {folder} {note}. Show the package folder?"), + &[("folder", &folder), ("note", &shown_note)], ) }; if app.ui.dialog.is_none() { @@ -189,12 +195,12 @@ fn packaged(app: &mut VectorcraftApp, r: Result, web: bool, later Ok(r) } -/// Parenthetical notes after the folder path in a package status (`(2 linked file(s) not found)` …), +/// Parenthetical notes after the folder path in a package status (`(2 linked files not found)` …), /// joined with spaces and without a leading space (#3494). -fn package_status_note(missing: usize, fonts: &str) -> String { +pub(super) fn package_status_note(missing: usize, fonts: &str) -> String { let mut parts = Vec::new(); if missing > 0 { - parts.push(format!("({})", crate::i18n::fmt(tl!("{count} linked file(s) not found"), &[("count", &missing.to_string())]))); + parts.push(format!("({})", crate::i18n::tn(missing as u64, "{n} linked file not found", "{n} linked files not found"))); } if !fonts.is_empty() { parts.push(format!("({})", crate::i18n::fmt(tl!("fonts not copied: {fonts}"), &[("fonts", fonts)]))); diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index cd34213afe..22c5e2a357 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -167,7 +167,7 @@ fn edits_after_ok_do_not_reach_the_package() { gate.open(); background::wait_all(&mut app); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("package")); - assert!(app.ui.status.starts_with("Packaged 3 file(s) in "), "{}", app.ui.status); + assert!(app.ui.status.starts_with("Packaged 3 files in "), "{}", app.ui.status); let files = files.lock().unwrap(); let (_, bytes) = files.iter().find(|(p, _)| p.ends_with("card.vectorcraft")).unwrap(); assert_eq!(vectorcraft_format::load(bytes).unwrap().node_count(), nodes, "the document as it was at OK"); @@ -213,7 +213,7 @@ fn a_dirty_documents_save_is_written_before_its_package() { release.join().unwrap(); assert_eq!(written(&files), [doc]); assert!(app.background.jobs.is_empty() && !app.session.active().unwrap().is_dirty()); - assert!(app.ui.status.starts_with("Packaged 3 file(s) in "), "the package's status came last: {}", app.ui.status); + assert!(app.ui.status.starts_with("Packaged 3 files in "), "the package's status came last: {}", app.ui.status); } #[test] @@ -254,7 +254,7 @@ fn the_web_downloads_a_zip() { assert!(!frame(&mut app).contains("Location:"), "no folder to choose"); confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); - assert!(app.ui.status.contains("Packaged") && app.ui.status.contains("file(s)"), "{}", app.ui.status); + assert!(app.ui.status.contains("Packaged") && app.ui.status.contains("files"), "{}", app.ui.status); let got = got.borrow(); assert_eq!(got.len(), 1); assert_eq!(got[0].0, "card Folder.zip"); @@ -285,6 +285,23 @@ fn fonts_left_out_of_the_package_are_named() { assert!(app.ui.status.contains(gone), "{}", app.ui.status); } +/// The note on linked files left out of a package uses the form the language's plural rule picks +/// for the count. +#[test] +fn the_missing_links_note_uses_each_count_form() { + let note = |code: &str, missing: usize| { + crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); + let note = package::package_status_note(missing, ""); + crate::i18n::set_current(crate::i18n::Lang::EN); + note + }; + assert_eq!(note("en", 1), "(1 linked file not found)"); + assert_eq!(note("en", 2), "(2 linked files not found)"); + assert_eq!(note("cs", 1), "(Nenalezen 1 propojený soubor)"); + assert_eq!(note("cs", 2), "(Nenalezeny 2 propojené soubory)"); + assert_eq!(note("cs", 5), "(Nenalezeno 5 propojených souborů)"); +} + #[test] fn package_status_without_notes_has_no_extra_spaces() { let dir = Folder::new("spaces"); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 0becb7e965..fd7a177514 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -203,7 +203,7 @@ font-technology Variable Променливи Apply Paragraph Style Прилагане на стил на абзац Apply SVG Filter… Прилагане на SVG филтър… Apply to All Прилагане към всички - Apply to All ({count} more missing) Прилагане към всички (още {count} липсващи) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Прилагане към всички (още {n} липсващ)|Прилагане към всички (още {n} липсващи) Arc Дъга Arc Lower… Дъга надолу… Arc Tool Инструмент „Дъга“ @@ -2217,7 +2217,7 @@ font-technology Variable Променливи Package Пакет Package collects a saved document with its linked files and fonts. Пакетът събира запазен документ заедно с неговите свързани файлове и шрифтове. Package created Пакетът е създаден - Packaged {n} file(s) in {folder} {note} Пакетирани са {n} файла в {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Пакетиран е {n} файл в {folder} {note}|Пакетирани са {n} файла в {folder} {note} Packaged {n} file(s){note} Пакетирани са {n} файла{note} Package… Пакет… Page Страница @@ -2534,9 +2534,11 @@ font-technology Variable Променливи Stop Спиране Searching… Търсене… Not found Няма намерени резултати - {folders} folder(s) and {files} file(s) searched Претърсени са {folders} папки и {files} файла - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Пропуснати са {count} папки (като системни папки, папки на други приложения и скрити папки) - {count} folder(s) or file(s) couldn't be read {count} папки или файла не можаха да бъдат прочетени + {folders} and {files} searched Претърсени са {folders} и {files} +@plural {n} folder|{n} folders {n} папка|{n} папки +@plural {n} file|{n} files {n} файл|{n} файла +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Пропусната е {n} папка (като системни папки, папки на други приложения и скрити папки)|Пропуснати са {n} папки (като системни папки, папки на други приложения и скрити папки) +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} папка или файл не можа да бъде прочетен|{n} папки или файла не можаха да бъдат прочетени The search stopped at its limit: search a smaller folder. Търсенето спре поради достигане на лимита: потърсете в по-малка папка. Copy only fonts you own or are licensed to install. Копирайте само шрифтове, които притежавате или имате лиценз да инсталирате. VectorCraft copies the fonts to {folder}. VectorCraft копира шрифтовете в {folder}. @@ -3604,13 +3606,13 @@ font-technology Variable Променливи Zoom Tool Инструмент „Мащаб“ Zoom with Mouse Wheel Мащабиране с колелцето на мишката Scrub Numeric Fields by Dragging Плъзгане на числени полета чрез влачене - {count} file(s) in {folder} {note}. Show the package folder? {count} файл(а) в {folder}{note}. Показване на папката на пакета? - {count} linked file(s) not found {count} свързан(и) файл(а) не са намерени +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} файл в {folder} {note}. Показване на папката на пакета?|{n} файла в {folder} {note}. Показване на папката на пакета? +@plural {n} linked file not found|{n} linked files not found {n} свързан файл не е намерен|{n} свързани файла не са намерени fonts not copied: {fonts} некопирани шрифтове: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} свързано(и) изображение(я) е/са променено(и) след запазването на този документ. Показване на новите версии? - {count} linked image(s) changed on disk. Show the new versions? {count} свързано(и) изображение(я) е/са променено(и) на диска. Показване на новите версии? - {count} more rules: Export writes every one. {count} още правила: Експортът записва всяко едно. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} ненаименувани обекта са пропуснати: наименувайте ги или включете „Ненаименувани обекти“ в менюто на панела. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} свързано изображение е променено след запазването на този документ. Показване на новата версия?|{n} свързани изображения са променени след запазването на този документ. Показване на новите версии? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} свързано изображение е променено на диска. Показване на новата версия?|{n} свързани изображения са променени на диска. Показване на новите версии? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Още {n} правило: Експортът го записва.|Още {n} правила: Експортът записва всяко едно. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} ненаименуван обект е пропуснат: наименувайте го или включете „Ненаименувани обекти“ в менюто на панела.|{n} ненаименувани обекта са пропуснати: наименувайте ги или включете „Ненаименувани обекти“ в менюто на панела. {effect} is already applied {effect} вече е приложен {format} Options Опции за {format} {kind} Gradient {kind} градиент @@ -5505,10 +5507,10 @@ axis Y Axis Y ос @msg Packaged {n} file(s) in {folder} Пакетирани са {n} файла в {folder} @msg Packaged {n} file(s) {note} Пакетирани са {n} файла {note} @msg Packaged {n} file(s) Пакетирани са {n} файла - Packaged {n} file(s) Пакетирани са {n} файла - Packaged {n} file(s) in {folder} Пакетирани са {n} файла в {folder} - Packaged {n} file(s) {note} Пакетирани са {n} файла {note} - {count} file(s) in {folder}. Show the package folder? {count} файл(а) в {folder}. Показване на папката на пакета? +@plural Packaged {n} file|Packaged {n} files Пакетиран е {n} файл|Пакетирани са {n} файла +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Пакетиран е {n} файл в {folder}|Пакетирани са {n} файла в {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Пакетиран е {n} файл {note}|Пакетирани са {n} файла {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} файл в {folder}. Показване на папката на пакета?|{n} файла в {folder}. Показване на папката на пакета? Clockwise По часовниковата стрелка Dither Дитъринг Fine noise hides banding in the gradient fill Фин шум скрива ивиците в градиентната запълка diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index b1635dc7bf..0ff4eeeb64 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -662,7 +662,7 @@ 1 Layer 1 sloj Libraries Biblioteke Links Veze - {count} linked image(s) changed on disk. Show the new versions? Povezanih slika promijenjenih na disku: {count}. Prikazati nove verzije? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Povezanih slika promijenjenih na disku: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih na disku: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih na disku: {n}. Prikazati nove verzije? Update Changed Links Ažuriraj promijenjene veze @msg Updated {_1} linked file(s) changed on disk Ažurirano povezanih datoteka promijenjenih na disku: {_1} Magic Wand Čarobni štapić @@ -1482,8 +1482,8 @@ lighting Light Svjetlo Select objects to see their CSS, or Generate CSS for the whole document. Odaberite objekte da vidite njihov CSS ili Generiši CSS za cijeli dokument. The selected objects have no CSS of their own (see below). Odabrani objekti nemaju vlastiti CSS (vidi ispod). Units: {units} Jedinice: {units} - {count} more rules: Export writes every one. Još pravila: {count}; izvoz zapisuje svako. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Izostavljeno neimenovanih objekata: {count}; imenujte ih ili uključite Neimenovani objekti u meniju panela. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Još pravila: {n}; izvoz zapisuje svako.|Još pravila: {n}; izvoz zapisuje svako.|Još pravila: {n}; izvoz zapisuje svako. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Izostavljeno neimenovanih objekata: {n}; imenujte ih ili uključite Neimenovani objekti u meniju panela.|Izostavljeno neimenovanih objekata: {n}; imenujte ih ili uključite Neimenovani objekti u meniju panela.|Izostavljeno neimenovanih objekata: {n}; imenujte ih ili uključite Neimenovani objekti u meniju panela. All Categories Sve kategorije Repeat Objects Ponovi objekte Save… Sačuvaj… @@ -2376,19 +2376,21 @@ lighting Light Svjetlo Stop Zaustavi Searching… Pretraga… Not found Nije pronađeno - {folders} folder(s) and {files} file(s) searched Pretraženo foldera: {folders}, datoteka: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Preskočeno foldera: {count}, npr. foldera drugih aplikacija, sistemskih i skrivenih - {count} folder(s) or file(s) couldn't be read Foldera ili datoteka koje nije moguće pročitati: {count} + {folders} and {files} searched Pretraženo: {folders}, {files} +@plural {n} folder|{n} folders {n} folder|{n} foldera|{n} foldera +@plural {n} file|{n} files {n} datoteka|{n} datoteke|{n} datoteka +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Preskočeno foldera: {n}, npr. foldera drugih aplikacija, sistemskih i skrivenih|Preskočeno foldera: {n}, npr. foldera drugih aplikacija, sistemskih i skrivenih|Preskočeno foldera: {n}, npr. foldera drugih aplikacija, sistemskih i skrivenih +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Foldera ili datoteka koje nije moguće pročitati: {n}|Foldera ili datoteka koje nije moguće pročitati: {n}|Foldera ili datoteka koje nije moguće pročitati: {n} The search stopped at its limit: search a smaller folder. Pretraga se zaustavila na svom ograničenju: pretražite manji folder. Copy only fonts you own or are licensed to install. Kopirajte samo fontove koje posjedujete ili imate licencu za instaliranje. VectorCraft copies the fonts to {folder}. VectorCraft kopira fontove u {folder}. - Apply to All ({count} more missing) Primijeni na sve (još {count} nedostaje) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Primijeni na sve (još {n} nedostaje)|Primijeni na sve (još {n} nedostaju)|Primijeni na sve (još {n} nedostaje) Ignore Zanemari Linked File Not Found Povezana datoteka nije pronađena Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Zamijenite je drugom datotekom ili je zanemarite: njene slike i dalje prikazuju pregled sačuvan s dokumentom. Replace… Zamijeni… Update Modified Links Ažuriraj izmijenjene veze - {count} linked image(s) changed since this document was saved. Show the new versions? Povezanih slika promijenjenih otkako je dokument sačuvan: {count}. Prikazati nove verzije? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? Povezanih slika promijenjenih otkako je dokument sačuvan: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih otkako je dokument sačuvan: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih otkako je dokument sačuvan: {n}. Prikazati nove verzije? Dialog Dijalog Convert Process to Global Pretvori procesne u globalne Create From: Kreiraj iz: @@ -2427,12 +2429,12 @@ lighting Light Svjetlo Fonts whose licence doesn't allow embedding are not copied. Fontovi čija licenca ne dozvoljava ugrađivanje ne kopiraju se. Package collects a saved document with its linked files and fonts. Paket prikuplja sačuvani dokument s njegovim povezanim datotekama i fontovima. Package created Paket je kreiran - Packaged {n} file(s) in {folder} {note} Upakovano datoteka u {folder}: {n} {note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Upakovano datoteka u {folder}: {n} {note}|Upakovano datoteka u {folder}: {n} {note}|Upakovano datoteka u {folder}: {n} {note} Packaged {n} file(s){note} Upakovano datoteka: {n}{note} Relink Linked Files to the Document Ponovo poveži povezane datoteke s dokumentom Save the document first? Prvo sačuvati dokument? - {count} file(s) in {folder} {note}. Show the package folder? Datoteka u {folder}: {count} {note}. Prikazati folder paketa? - {count} linked file(s) not found Povezanih datoteka nije pronađeno: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Datoteka u {folder}: {n} {note}. Prikazati folder paketa?|Datoteka u {folder}: {n} {note}. Prikazati folder paketa?|Datoteka u {folder}: {n} {note}. Prikazati folder paketa? +@plural {n} linked file not found|{n} linked files not found Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n} fonts not copied: {fonts} fontovi nisu kopirani: {fonts} Built-in presets are read-only: New… starts an editable copy. Ugrađeni predlošci su samo za čitanje: Novo… započinje kopiju koja se može uređivati. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} na radnoj ploči predstavlja {real} {unit} u sceni. @@ -5525,10 +5527,10 @@ axis Y Axis Y osa @msg Packaged {n} file(s) in {folder} Upakovano datoteka u {folder}: {n} @msg Packaged {n} file(s) {note} Upakovano datoteka: {n} {note} @msg Packaged {n} file(s) Upakovano datoteka: {n} - Packaged {n} file(s) Upakovano datoteka: {n} - Packaged {n} file(s) in {folder} Upakovano datoteka u {folder}: {n} - Packaged {n} file(s) {note} Upakovano datoteka: {n} {note} - {count} file(s) in {folder}. Show the package folder? Datoteka u {folder}: {count}. Prikazati folder paketa? +@plural Packaged {n} file|Packaged {n} files Upakovano datoteka: {n}|Upakovano datoteka: {n}|Upakovano datoteka: {n} +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Upakovano datoteka u {folder}: {n}|Upakovano datoteka u {folder}: {n}|Upakovano datoteka u {folder}: {n} +@plural Packaged {n} file {note}|Packaged {n} files {note} Upakovano datoteka: {n} {note}|Upakovano datoteka: {n} {note}|Upakovano datoteka: {n} {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? Datoteka u {folder}: {n}. Prikazati folder paketa?|Datoteka u {folder}: {n}. Prikazati folder paketa?|Datoteka u {folder}: {n}. Prikazati folder paketa? Clockwise U smjeru kazaljke na satu Dither Dithering Fine noise hides banding in the gradient fill Fini šum skriva trake u gradijentnoj ispuni diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index b875d10672..04608e692c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -320,7 +320,7 @@ Apply Paragraph Style Aplica l’estil de paràgraf Apply SVG Filter… Aplica el filtre SVG… Apply to All Aplica-ho a tot - Apply to All ({count} more missing) Aplica-ho a tot ({count} més que falten) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Aplica-ho a tot ({n} més que falta)|Aplica-ho a tot ({n} més que falten) Apply {name} Aplica {name} Approximate path Aproxima el traçat Arabic Àrab @@ -2812,10 +2812,10 @@ Package Empaqueta Package collects a saved document with its linked files and fonts. L’empaquetatge recull un document desat amb els fitxers enllaçats i els tipus de lletra. Package created Empaquetatge creat - Packaged {n} file(s) S’han empaquetat {n} fitxers - Packaged {n} file(s) in {folder} S’han empaquetat {n} fitxers a {folder} - Packaged {n} file(s) in {folder} {note} S’han empaquetat {n} fitxers a {folder} {note} - Packaged {n} file(s) {note} S’han empaquetat {n} fitxers {note} +@plural Packaged {n} file|Packaged {n} files S’ha empaquetat {n} fitxer|S’han empaquetat {n} fitxers +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} S’ha empaquetat {n} fitxer a {folder}|S’han empaquetat {n} fitxers a {folder} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} S’ha empaquetat {n} fitxer a {folder} {note}|S’han empaquetat {n} fitxers a {folder} {note} +@plural Packaged {n} file {note}|Packaged {n} files {note} S’ha empaquetat {n} fitxer {note}|S’han empaquetat {n} fitxers {note} Packaged {n} file(s){note} S’han empaquetat {n} fitxers{note} Package… Empaqueta… Page Pàgina @@ -4653,19 +4653,21 @@ Zoom to Selection Amplia a la selecció Zoom Tool Eina de zoom Zoom with Mouse Wheel Zoom amb la roda del ratolí - {count} file(s) in {folder} {note}. Show the package folder? {count} fitxer(s) a {folder} {note}. Voleu mostrar la carpeta del paquet? - {count} file(s) in {folder}. Show the package folder? {count} fitxer(s) a {folder}. Voleu mostrar la carpeta del paquet? - {count} folder(s) or file(s) couldn't be read No s’han pogut llegir {count} carpeta(es) o fitxer(s) - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones S’han omès {count} carpeta(es), com ara les d’altres aplicacions, les del sistema i les ocultes - {count} linked file(s) not found No s’han trobat {count} fitxer(s) enllaçat(s) - {count} linked image(s) changed on disk. Show the new versions? {count} imatge(s) enllaçada(es) han canviat al disc. Voleu mostrar les versions noves? - {count} linked image(s) changed since this document was saved. Show the new versions? {count} imatge(s) enllaçada(es) han canviat des que es va desar aquest document. Voleu mostrar les versions noves? - {count} more rules: Export writes every one. {count} regles més: l’exportació les escriu totes. +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fitxer a {folder} {note}. Voleu mostrar la carpeta del paquet?|{n} fitxers a {folder} {note}. Voleu mostrar la carpeta del paquet? +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fitxer a {folder}. Voleu mostrar la carpeta del paquet?|{n} fitxers a {folder}. Voleu mostrar la carpeta del paquet? +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read No s’ha pogut llegir {n} carpeta o fitxer|No s’han pogut llegir {n} carpetes o fitxers +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones S’ha omès {n} carpeta, com ara les d’altres aplicacions, les del sistema i les ocultes|S’han omès {n} carpetes, com ara les d’altres aplicacions, les del sistema i les ocultes +@plural {n} linked file not found|{n} linked files not found No s’ha trobat {n} fitxer enllaçat|No s’han trobat {n} fitxers enllaçats +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} imatge enllaçada ha canviat al disc. Voleu mostrar la versió nova?|{n} imatges enllaçades han canviat al disc. Voleu mostrar les versions noves? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} imatge enllaçada ha canviat des que es va desar aquest document. Voleu mostrar la versió nova?|{n} imatges enllaçades han canviat des que es va desar aquest document. Voleu mostrar les versions noves? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regla més: l’exportació l’escriu.|{n} regles més: l’exportació les escriu totes. {count} of {total} artboards {count} de {total} taulers - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. S’han omès {count} objectes sense nom: poseu-los un nom o activeu Objectes sense nom al menú del panell. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. S’ha omès {n} objecte sense nom: poseu-li un nom o activeu Objectes sense nom al menú del panell.|S’han omès {n} objectes sense nom: poseu-los un nom o activeu Objectes sense nom al menú del panell. {effect} is already applied {effect} ja està aplicat {file}, line {line} {file}, línia {line} - {folders} folder(s) and {files} file(s) searched S’han cercat {folders} carpeta(es) i {files} fitxer(s) + {folders} and {files} searched S’han cercat {folders} i {files} +@plural {n} folder|{n} folders {n} carpeta|{n} carpetes +@plural {n} file|{n} files {n} fitxer|{n} fitxers {format} Options Opcions de {format} {kind} Gradient Degradat {kind} {kind} Style Options… Opcions d’estil de {kind}… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6452812168..28929b1cf8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -672,7 +672,7 @@ 1 Layer 1 vrstva Libraries Knihovny Links Propojení - {count} linked image(s) changed on disk. Show the new versions? Počet propojených obrázků změněných na disku: {count}. Zobrazit nové verze? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Na disku se změnil {n} propojený obrázek. Zobrazit novou verzi?|Na disku se změnily {n} propojené obrázky. Zobrazit nové verze?|Na disku se změnilo {n} propojených obrázků. Zobrazit nové verze? Update Changed Links Aktualizovat změněná propojení @msg Updated {_1} linked file(s) changed on disk Aktualizováno propojených souborů změněných na disku: {_1} Magic Wand Kouzelná hůlka @@ -1505,8 +1505,8 @@ lighting Light Světlo Select objects to see their CSS, or Generate CSS for the whole document. Vyberte objekty, abyste viděli jejich CSS, nebo vygenerujte CSS pro celý dokument. The selected objects have no CSS of their own (see below). Vybrané objekty nemají vlastní CSS (viz níže). Units: {units} Jednotky: {units} - {count} more rules: Export writes every one. Další pravidla ({count}): Export zapíše všechna. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Vynecháno nepojmenovaných objektů: {count}. Pojmenujte je, nebo v nabídce panelu zapněte Nepojmenované objekty. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Další {n} pravidlo: Export ho zapíše.|Další {n} pravidla: Export zapíše všechna.|Dalších {n} pravidel: Export zapíše všechna. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Vynechán {n} nepojmenovaný objekt. Pojmenujte ho, nebo v nabídce panelu zapněte Nepojmenované objekty.|Vynechány {n} nepojmenované objekty. Pojmenujte je, nebo v nabídce panelu zapněte Nepojmenované objekty.|Vynecháno {n} nepojmenovaných objektů. Pojmenujte je, nebo v nabídce panelu zapněte Nepojmenované objekty. All Categories Všechny kategorie Repeat Objects Objekty opakování Save… Uložit… @@ -2403,19 +2403,21 @@ lighting Light Světlo Stop Zastavit Searching… Hledání… Not found Nenalezeno - {folders} folder(s) and {files} file(s) searched Prohledáno složek: {folders}, souborů: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Přeskočeno složek: {count} (např. složky jiných aplikací, systému a skryté složky) - {count} folder(s) or file(s) couldn't be read Nepodařilo se přečíst složek nebo souborů: {count} + {folders} and {files} searched Prohledáno: {folders}, {files} +@plural {n} folder|{n} folders {n} složka|{n} složky|{n} složek +@plural {n} file|{n} files {n} soubor|{n} soubory|{n} souborů +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Přeskočena {n} složka (např. složky jiných aplikací, systému a skryté složky)|Přeskočeny {n} složky (např. složky jiných aplikací, systému a skryté složky)|Přeskočeno {n} složek (např. složky jiných aplikací, systému a skryté složky) +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Nepodařilo se přečíst {n} složku nebo soubor|Nepodařilo se přečíst {n} složky nebo soubory|Nepodařilo se přečíst {n} složek nebo souborů The search stopped at its limit: search a smaller folder. Hledání se zastavilo na limitu: prohledejte menší složku. Copy only fonts you own or are licensed to install. Kopírujte jen písma, která vlastníte nebo máte licenci instalovat. VectorCraft copies the fonts to {folder}. VectorCraft zkopíruje písma do {folder}. - Apply to All ({count} more missing) Použít na všechny (chybí ještě {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Použít na všechny (chybí ještě {n})|Použít na všechny (chybí ještě {n})|Použít na všechny (chybí ještě {n}) Ignore Ignorovat Linked File Not Found Propojený soubor nebyl nalezen Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Nahraďte jej jiným souborem, nebo jej ignorujte: jeho obrázky dál zobrazují náhled uložený s dokumentem. Replace… Nahradit… Update Modified Links Aktualizovat upravená propojení - {count} linked image(s) changed since this document was saved. Show the new versions? Počet propojených obrázků změněných od uložení dokumentu: {count}. Zobrazit nové verze? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? Od uložení dokumentu se změnil {n} propojený obrázek. Zobrazit novou verzi?|Od uložení dokumentu se změnily {n} propojené obrázky. Zobrazit nové verze?|Od uložení dokumentu se změnilo {n} propojených obrázků. Zobrazit nové verze? Dialog Dialogové okno Convert Process to Global Převést procesní na globální Create From: Vytvořit z: @@ -2454,12 +2456,12 @@ lighting Light Světlo Fonts whose licence doesn't allow embedding are not copied. Písma, jejichž licence nepovoluje vkládání, se nekopírují. Package collects a saved document with its linked files and fonts. Sbalení shromáždí uložený dokument s jeho propojenými soubory a písmy. Package created Balíček vytvořen - Packaged {n} file(s) in {folder} {note} Zabaleno souborů: {n} do {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Zabalen {n} soubor do {folder} {note}|Zabaleny {n} soubory do {folder} {note}|Zabaleno {n} souborů do {folder} {note} Packaged {n} file(s){note} Zabaleno souborů: {n}{note} Relink Linked Files to the Document Znovu propojit propojené soubory s dokumentem Save the document first? Nejprve uložit dokument? - {count} file(s) in {folder} {note}. Show the package folder? Souborů: {count} v {folder}{note}. Zobrazit složku balíčku? - {count} linked file(s) not found Nenalezeno propojených souborů: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} soubor v {folder} {note}. Zobrazit složku balíčku?|{n} soubory v {folder} {note}. Zobrazit složku balíčku?|{n} souborů v {folder} {note}. Zobrazit složku balíčku? +@plural {n} linked file not found|{n} linked files not found Nenalezen {n} propojený soubor|Nenalezeny {n} propojené soubory|Nenalezeno {n} propojených souborů fonts not copied: {fonts} nezkopírovaná písma: {fonts} Built-in presets are read-only: New… starts an editable copy. Vestavěná přednastavení jsou jen pro čtení: Nový… vytvoří kopii, kterou lze upravit. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} na pracovní ploše odpovídá {real} {unit} ve scéně. @@ -5594,10 +5596,10 @@ axis Y Axis osa Y @msg Packaged {n} file(s) in {folder} Zabaleno souborů: {n} do {folder} @msg Packaged {n} file(s) {note} Zabaleno souborů: {n} {note} @msg Packaged {n} file(s) Zabaleno souborů: {n} - Packaged {n} file(s) Zabaleno souborů: {n} - Packaged {n} file(s) in {folder} Zabaleno souborů: {n} do {folder} - Packaged {n} file(s) {note} Zabaleno souborů: {n} {note} - {count} file(s) in {folder}. Show the package folder? Souborů: {count} v {folder}. Zobrazit složku balíčku? +@plural Packaged {n} file|Packaged {n} files Zabalen {n} soubor|Zabaleny {n} soubory|Zabaleno {n} souborů +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Zabalen {n} soubor do {folder}|Zabaleny {n} soubory do {folder}|Zabaleno {n} souborů do {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Zabalen {n} soubor {note}|Zabaleny {n} soubory {note}|Zabaleno {n} souborů {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} soubor v {folder}. Zobrazit složku balíčku?|{n} soubory v {folder}. Zobrazit složku balíčku?|{n} souborů v {folder}. Zobrazit složku balíčku? Clockwise Ve směru hodinových ručiček Dither Rozptýlení Fine noise hides banding in the gradient fill Jemný šum skryje pruhy ve výplni přechodem diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index fb80dcc0c7..cd1eb284af 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -624,7 +624,7 @@ 1 Layer 1 lag Libraries Biblioteker Links Links - {count} linked image(s) changed on disk. Show the new versions? {count} linket billede(r) er ændret på disken. Vis de nye versioner? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} linket billede er ændret på disken. Vis den nye version?|{n} linkede billeder er ændret på disken. Vis de nye versioner? Update Changed Links Opdatér ændrede links @msg Updated {_1} linked file(s) changed on disk Opdaterede {_1} linket fil(er) ændret på disken Magic Wand Magisk tryllestav @@ -1419,8 +1419,8 @@ lighting Light Lys Select objects to see their CSS, or Generate CSS for the whole document. Markér objekter for at se deres CSS, eller generér CSS for hele dokumentet. The selected objects have no CSS of their own (see below). De markerede objekter har ingen egen CSS (se nedenfor). Units: {units} Enheder: {units} - {count} more rules: Export writes every one. {count} flere regler: Eksport skriver hver enkelt. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} unavngivne objekter udeladt: giv dem navne, eller aktivér Unavngivne objekter i panelmenuen. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regel mere: Eksport skriver den.|{n} flere regler: Eksport skriver hver enkelt. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} unavngivet objekt udeladt: giv det et navn, eller aktivér Unavngivne objekter i panelmenuen.|{n} unavngivne objekter udeladt: giv dem navne, eller aktivér Unavngivne objekter i panelmenuen. All Categories Alle kategorier Repeat Objects Gentagelsesobjekter Save… Gem… @@ -2196,19 +2196,21 @@ lighting Light Lys Stop Stop Searching… Søger… Not found Ikke fundet - {folders} folder(s) and {files} file(s) searched {folders} mappe(r) og {files} fil(er) gennemsøgt - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} mappe(r) sprunget over, f.eks. andre apps' og systemets mapper samt skjulte mapper - {count} folder(s) or file(s) couldn't be read {count} mappe(r) eller fil(er) kunne ikke læses + {folders} and {files} searched {folders} og {files} gennemsøgt +@plural {n} folder|{n} folders {n} mappe|{n} mapper +@plural {n} file|{n} files {n} fil|{n} filer +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} mappe sprunget over, f.eks. andre apps' og systemets mapper samt skjulte mapper|{n} mapper sprunget over, f.eks. andre apps' og systemets mapper samt skjulte mapper +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} mappe eller fil kunne ikke læses|{n} mapper eller filer kunne ikke læses The search stopped at its limit: search a smaller folder. Søgningen stoppede ved sin grænse: søg i en mindre mappe. Copy only fonts you own or are licensed to install. Kopiér kun skrifttyper, du ejer eller har licens til at installere. VectorCraft copies the fonts to {folder}. VectorCraft kopierer skrifttyperne til {folder}. - Apply to All ({count} more missing) Anvend på alle ({count} flere mangler) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Anvend på alle ({n} mere mangler)|Anvend på alle ({n} flere mangler) Ignore Ignorér Linked File Not Found Linket fil blev ikke fundet Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Erstat den med en anden fil, eller ignorér den: dens billeder viser stadig den forhåndsvisning, der er gemt sammen med dokumentet. Replace… Erstat… Update Modified Links Opdatér ændrede links - {count} linked image(s) changed since this document was saved. Show the new versions? {count} linkede billede(r) er ændret, siden dette dokument blev gemt. Vis de nye versioner? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} linket billede er ændret, siden dette dokument blev gemt. Vis den nye version?|{n} linkede billeder er ændret, siden dette dokument blev gemt. Vis de nye versioner? Dialog Dialog Convert Process to Global Konvertér procesfarve til global Create From: Opret ud fra: @@ -2247,12 +2249,12 @@ lighting Light Lys Fonts whose licence doesn't allow embedding are not copied. Skrifttyper, hvis licens ikke tillader indlejring, kopieres ikke. Package collects a saved document with its linked files and fonts. Pakning samler et gemt dokument med dets linkede filer og skrifttyper. Package created Pakke oprettet - Packaged {n} file(s) in {folder} {note} Pakkede {n} fil(er) i {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Pakkede {n} fil i {folder} {note}|Pakkede {n} filer i {folder} {note} Packaged {n} file(s){note} Pakkede {n} fil(er){note} Relink Linked Files to the Document Genopret link til dokumentets linkede filer Save the document first? Gem dokumentet først? - {count} file(s) in {folder} {note}. Show the package folder? {count} fil(er) i {folder}{note}. Vis pakkemappen? - {count} linked file(s) not found {count} linkede fil(er) ikke fundet +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fil i {folder} {note}. Vis pakkemappen?|{n} filer i {folder} {note}. Vis pakkemappen? +@plural {n} linked file not found|{n} linked files not found {n} linket fil ikke fundet|{n} linkede filer ikke fundet fonts not copied: {fonts} skrifttyper ikke kopieret: {fonts} Built-in presets are read-only: New… starts an editable copy. Indbyggede forudindstillinger er skrivebeskyttede: Ny… starter en redigerbar kopi. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} på tegnebrættet svarer til {real} {unit} i scenen. @@ -5520,10 +5522,10 @@ axis Y Axis Y-akse @msg Packaged {n} file(s) in {folder} Pakkede {n} fil(er) i {folder} @msg Packaged {n} file(s) {note} Pakkede {n} fil(er) {note} @msg Packaged {n} file(s) Pakkede {n} fil(er) - Packaged {n} file(s) Pakkede {n} fil(er) - Packaged {n} file(s) in {folder} Pakkede {n} fil(er) i {folder} - Packaged {n} file(s) {note} Pakkede {n} fil(er) {note} - {count} file(s) in {folder}. Show the package folder? {count} fil(er) i {folder}. Vis pakkemappen? +@plural Packaged {n} file|Packaged {n} files Pakkede {n} fil|Pakkede {n} filer +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Pakkede {n} fil i {folder}|Pakkede {n} filer i {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Pakkede {n} fil {note}|Pakkede {n} filer {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fil i {folder}. Vis pakkemappen?|{n} filer i {folder}. Vis pakkemappen? Clockwise Med uret Dither Dither Fine noise hides banding in the gradient fill Fin støj skjuler striber i gradientfyldet diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1ea0d5f0d9..00b281ec71 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -192,7 +192,7 @@ font-technology Variable Variabel Apply Paragraph Style Absatzformat anwenden Apply SVG Filter… SVG-Filter anwenden… Apply to All Auf alle anwenden - Apply to All ({count} more missing) Auf alle anwenden ({count} weitere fehlen) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Auf alle anwenden ({n} weitere fehlt)|Auf alle anwenden ({n} weitere fehlen) Arc Bogen Arc Lower… Bogen unten… Arc Tool Bogen-Werkzeug @@ -2230,7 +2230,7 @@ file-filter Templates Vorlagen Package Verpacken Package collects a saved document with its linked files and fonts. „Verpacken“ sammelt ein gespeichertes Dokument mit seinen verknüpften Dateien und Schriften. Package created Paket erstellt - Packaged {n} file(s) in {folder} {note} {n} Datei(en) in {folder} verpackt{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} Datei in {folder} verpackt {note}|{n} Dateien in {folder} verpackt {note} Packaged {n} file(s){note} {n} Datei(en) verpackt{note} Package… Verpacken… Page Seite @@ -2554,9 +2554,11 @@ mark-style Japanese Japanisch Stop Stoppen Searching… Suche läuft… Not found Nicht gefunden - {folders} folder(s) and {files} file(s) searched {folders} Ordner und {files} Datei(en) durchsucht - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} Ordner übersprungen, etwa Ordner anderer Apps und des Systems sowie versteckte Ordner - {count} folder(s) or file(s) couldn't be read {count} Ordner oder Datei(en) konnten nicht gelesen werden + {folders} and {files} searched {folders} und {files} durchsucht +@plural {n} folder|{n} folders {n} Ordner|{n} Ordner +@plural {n} file|{n} files {n} Datei|{n} Dateien +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} Ordner übersprungen, etwa Ordner anderer Apps und des Systems sowie versteckte Ordner|{n} Ordner übersprungen, etwa Ordner anderer Apps und des Systems sowie versteckte Ordner +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} Ordner oder Datei konnte nicht gelesen werden|{n} Ordner oder Dateien konnten nicht gelesen werden The search stopped at its limit: search a smaller folder. Die Suche hat ihr Limit erreicht: Durchsuchen Sie einen kleineren Ordner. Copy only fonts you own or are licensed to install. Kopieren Sie nur Schriften, die Ihnen gehören oder für deren Installation Sie eine Lizenz haben. VectorCraft copies the fonts to {folder}. VectorCraft kopiert die Schriften nach {folder}. @@ -3591,12 +3593,12 @@ effect Points Punkte Zoom Tool Zoom-Werkzeug Zoom with Mouse Wheel Mit Mausrad zoomen Scrub Numeric Fields by Dragging Zahlenfelder durch Ziehen ändern - {count} file(s) in {folder} {note}. Show the package folder? {count} Datei(en) in {folder} {note}. Paketordner anzeigen? - {count} linked file(s) not found {count} verknüpfte Datei(en) nicht gefunden +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} Datei in {folder} {note}. Paketordner anzeigen?|{n} Dateien in {folder} {note}. Paketordner anzeigen? +@plural {n} linked file not found|{n} linked files not found {n} verknüpfte Datei nicht gefunden|{n} verknüpfte Dateien nicht gefunden fonts not copied: {fonts} nicht kopierte Schriften: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} verknüpfte(s) Bild(er) wurde(n) seit dem Speichern dieses Dokuments geändert. Die neuen Versionen anzeigen? - {count} more rules: Export writes every one. {count} weitere Regeln: Der Export schreibt alle. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} unbenannte Objekte ausgelassen: Benennen Sie sie oder aktivieren Sie „Unbenannte Objekte“ im Bedienfeldmenü. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} verknüpftes Bild wurde seit dem Speichern dieses Dokuments geändert. Die neue Version anzeigen?|{n} verknüpfte Bilder wurden seit dem Speichern dieses Dokuments geändert. Die neuen Versionen anzeigen? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} weitere Regel: Der Export schreibt sie.|{n} weitere Regeln: Der Export schreibt alle. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} unbenanntes Objekt ausgelassen: Benennen Sie es oder aktivieren Sie „Unbenannte Objekte“ im Bedienfeldmenü.|{n} unbenannte Objekte ausgelassen: Benennen Sie sie oder aktivieren Sie „Unbenannte Objekte“ im Bedienfeldmenü. {effect} is already applied {effect} ist bereits angewendet {format} Options {format}-Optionen {kind} Gradient Verlauf ({kind}) @@ -4580,7 +4582,7 @@ theme Appearance Erscheinungsbild @msg Imported library {name} Bibliothek {name} importiert # Linked files changed on disk. Update Changed Links Geänderte Verknüpfungen aktualisieren - {count} linked image(s) changed on disk. Show the new versions? {count} verknüpfte(s) Bild(er) wurde(n) auf dem Datenträger geändert. Neue Versionen anzeigen? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} verknüpftes Bild wurde auf dem Datenträger geändert. Neue Version anzeigen?|{n} verknüpfte Bilder wurden auf dem Datenträger geändert. Neue Versionen anzeigen? @msg Updated {_1} linked file(s) changed on disk {_1} auf dem Datenträger geänderte verknüpfte Datei(en) aktualisiert # Window: the system's title bar (Windows, Linux). System Title Bar Systemtitelleiste @@ -5175,10 +5177,10 @@ axis Y Axis Y-Achse @msg Packaged {n} file(s) in {folder} {n} Datei(en) in {folder} verpackt @msg Packaged {n} file(s) {note} {n} Datei(en) verpackt {note} @msg Packaged {n} file(s) {n} Datei(en) verpackt - Packaged {n} file(s) {n} Datei(en) verpackt - Packaged {n} file(s) in {folder} {n} Datei(en) in {folder} verpackt - Packaged {n} file(s) {note} {n} Datei(en) verpackt {note} - {count} file(s) in {folder}. Show the package folder? {count} Datei(en) in {folder}. Paketordner anzeigen? +@plural Packaged {n} file|Packaged {n} files {n} Datei verpackt|{n} Dateien verpackt +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} Datei in {folder} verpackt|{n} Dateien in {folder} verpackt +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} Datei verpackt {note}|{n} Dateien verpackt {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} Datei in {folder}. Paketordner anzeigen?|{n} Dateien in {folder}. Paketordner anzeigen? Clockwise Im Uhrzeigersinn Dither Dithering Fine noise hides banding in the gradient fill Feines Rauschen verbirgt Streifen in der Verlaufsfläche diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 383e9b4343..2ff75d2053 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -196,7 +196,7 @@ font-technology Variable Μεταβλητές Apply Paragraph Style Εφαρμογή στυλ παραγράφου Apply SVG Filter… Εφαρμογή φίλτρου SVG… Apply to All Εφαρμογή σε όλα - Apply to All ({count} more missing) Εφαρμογή σε όλα (λείπουν ακόμη {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Εφαρμογή σε όλα (λείπει ακόμη {n})|Εφαρμογή σε όλα (λείπουν ακόμη {n}) Arc Τόξο Arc Lower… Κάτω τόξο… Arc Tool Τόξο (Arc Tool) @@ -2928,7 +2928,7 @@ theme Appearance Εμφάνιση Override Character Color Παράκαμψη χρώματος χαρακτήρων Package collects a saved document with its linked files and fonts. Η συσκευασία συγκεντρώνει ένα αποθηκευμένο έγγραφο μαζί με συνδεδεμένα αρχεία και γραμματοσειρές. Package created Η συσκευασία δημιουργήθηκε - Packaged {n} file(s) in {folder} {note} Συσκευάστηκαν {n} αρχεία στον φάκελο {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Συσκευάστηκε {n} αρχείο στον φάκελο {folder} {note}|Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} {note} Packaged {n} file(s){note} Συσκευάστηκαν {n} αρχεία{note} Page Σελίδα Page information Πληροφορίες σελίδας @@ -3157,9 +3157,11 @@ theme Appearance Εμφάνιση Find Fonts Εύρεση γραμματοσειρών Searching… Αναζήτηση… Not found Δεν βρέθηκε - {folders} folder(s) and {files} file(s) searched Έγινε αναζήτηση σε {folders} φακέλους και {files} αρχεία - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Παραλείφθηκαν {count} φάκελοι, όπως φάκελοι άλλων εφαρμογών, του συστήματος και κρυφοί φάκελοι - {count} folder(s) or file(s) couldn't be read Δεν ήταν δυνατή η ανάγνωση {count} φακέλων ή αρχείων + {folders} and {files} searched Έγινε αναζήτηση: {folders}, {files} +@plural {n} folder|{n} folders {n} φάκελος|{n} φάκελοι +@plural {n} file|{n} files {n} αρχείο|{n} αρχεία +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Παραλείφθηκε {n} φάκελος, όπως φάκελοι άλλων εφαρμογών, του συστήματος και κρυφοί φάκελοι|Παραλείφθηκαν {n} φάκελοι, όπως φάκελοι άλλων εφαρμογών, του συστήματος και κρυφοί φάκελοι +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Δεν ήταν δυνατή η ανάγνωση {n} φακέλου ή αρχείου|Δεν ήταν δυνατή η ανάγνωση {n} φακέλων ή αρχείων The search stopped at its limit: search a smaller folder. Η αναζήτηση έφτασε στο όριό της: επιλέξτε μικρότερο φάκελο. Copy only fonts you own or are licensed to install. Αντιγράψτε μόνο γραμματοσειρές που σας ανήκουν ή έχετε άδεια να εγκαταστήσετε. VectorCraft copies the fonts to {folder}. Το VectorCraft αντιγράφει τις γραμματοσειρές στον φάκελο {folder}. @@ -3922,13 +3924,13 @@ theme Appearance Εμφάνιση Zoom to Selection Ζουμ στην επιλογή Zoom with Mouse Wheel Ζουμ με τον τροχό του ποντικιού Scrub Numeric Fields by Dragging Ρύθμιση αριθμητικών πεδίων με σύρσιμο - {count} file(s) in {folder} {note}. Show the package folder? {count} αρχεία στον φάκελο {folder}{note}. Να εμφανιστεί ο φάκελος συσκευασίας; - {count} linked file(s) not found Δεν βρέθηκαν {count} συνδεδεμένα αρχεία +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} αρχείο στον φάκελο {folder} {note}. Να εμφανιστεί ο φάκελος συσκευασίας;|{n} αρχεία στον φάκελο {folder} {note}. Να εμφανιστεί ο φάκελος συσκευασίας; +@plural {n} linked file not found|{n} linked files not found Δεν βρέθηκε {n} συνδεδεμένο αρχείο|Δεν βρέθηκαν {n} συνδεδεμένα αρχεία fonts not copied: {fonts} γραμματοσειρές που δεν αντιγράφηκαν: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} συνδεδεμένες εικόνες άλλαξαν μετά την αποθήκευση του εγγράφου. Να εμφανιστούν οι νέες εκδόσεις; - {count} linked image(s) changed on disk. Show the new versions? {count} συνδεδεμένες εικόνες άλλαξαν στον δίσκο. Να εμφανιστούν οι νέες εκδόσεις; - {count} more rules: Export writes every one. {count} ακόμη κανόνες: η εξαγωγή περιλαμβάνει όλους. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Παραλείφθηκαν {count} αντικείμενα χωρίς όνομα: ονομάστε τα ή ενεργοποιήστε τα Αντικείμενα χωρίς όνομα από το μενού του πίνακα. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} συνδεδεμένη εικόνα άλλαξε μετά την αποθήκευση του εγγράφου. Να εμφανιστεί η νέα έκδοση;|{n} συνδεδεμένες εικόνες άλλαξαν μετά την αποθήκευση του εγγράφου. Να εμφανιστούν οι νέες εκδόσεις; +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} συνδεδεμένη εικόνα άλλαξε στον δίσκο. Να εμφανιστεί η νέα έκδοση;|{n} συνδεδεμένες εικόνες άλλαξαν στον δίσκο. Να εμφανιστούν οι νέες εκδόσεις; +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} ακόμη κανόνας: η εξαγωγή τον περιλαμβάνει.|{n} ακόμη κανόνες: η εξαγωγή περιλαμβάνει όλους. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Παραλείφθηκε {n} αντικείμενο χωρίς όνομα: ονομάστε το ή ενεργοποιήστε τα Αντικείμενα χωρίς όνομα από το μενού του πίνακα.|Παραλείφθηκαν {n} αντικείμενα χωρίς όνομα: ονομάστε τα ή ενεργοποιήστε τα Αντικείμενα χωρίς όνομα από το μενού του πίνακα. {effect} is already applied Το εφέ {effect} έχει ήδη εφαρμοστεί {format} Options Επιλογές {format} {kind} Gradient Ντεγκραντέ {kind} @@ -5546,10 +5548,10 @@ axis Y Axis Άξονας Y @msg Packaged {n} file(s) in {folder} Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} @msg Packaged {n} file(s) {note} Συσκευάστηκαν {n} αρχεία {note} @msg Packaged {n} file(s) Συσκευάστηκαν {n} αρχεία - Packaged {n} file(s) Συσκευάστηκαν {n} αρχεία - Packaged {n} file(s) in {folder} Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} - Packaged {n} file(s) {note} Συσκευάστηκαν {n} αρχεία {note} - {count} file(s) in {folder}. Show the package folder? {count} αρχεία στον φάκελο {folder}. Να εμφανιστεί ο φάκελος συσκευασίας; +@plural Packaged {n} file|Packaged {n} files Συσκευάστηκε {n} αρχείο|Συσκευάστηκαν {n} αρχεία +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Συσκευάστηκε {n} αρχείο στον φάκελο {folder}|Συσκευάστηκαν {n} αρχεία στον φάκελο {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Συσκευάστηκε {n} αρχείο {note}|Συσκευάστηκαν {n} αρχεία {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} αρχείο στον φάκελο {folder}. Να εμφανιστεί ο φάκελος συσκευασίας;|{n} αρχεία στον φάκελο {folder}. Να εμφανιστεί ο φάκελος συσκευασίας; Clockwise Δεξιόστροφα Dither Πρόσθεση θορύβου Fine noise hides banding in the gradient fill Ο λεπτός θόρυβος κρύβει τις λωρίδες στο γέμισμα ντεγκραντέ diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 80d54c074e..693173a181 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -217,7 +217,7 @@ font-technology Variable Variables Apply Paragraph Style Aplicar estilo de párrafo Apply SVG Filter… Aplicar filtro SVG… Apply to All Aplicar a todo - Apply to All ({count} more missing) Aplicar a todo (faltan {count} más) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Aplicar a todo (falta {n} más)|Aplicar a todo (faltan {n} más) Arc Arco Arc Lower… Arco inferior… Arc Tool Herramienta Arco @@ -2272,7 +2272,7 @@ font-technology Variable Variables Package Empaquetar Package collects a saved document with its linked files and fonts. Empaquetar reúne un documento guardado con sus archivos vinculados y fuentes. Package created Paquete creado - Packaged {n} file(s) in {folder} {note} Se empaquetaron {n} archivo(s) en {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Se empaquetó {n} archivo en {folder} {note}|Se empaquetaron {n} archivos en {folder} {note} Packaged {n} file(s){note} Se empaquetaron {n} archivo(s){note} Package… Empaquetar… Page Página @@ -2592,9 +2592,11 @@ font-technology Variable Variables Stop Detener Searching… Buscando… Not found No se encontró - {folders} folder(s) and {files} file(s) searched Se buscó en {folders} carpeta(s) y {files} archivo(s) - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Se omitieron {count} carpeta(s), como las de otras aplicaciones y del sistema y las ocultas - {count} folder(s) or file(s) couldn't be read No se pudieron leer {count} carpeta(s) o archivo(s) + {folders} and {files} searched Se buscó en {folders} y {files} +@plural {n} folder|{n} folders {n} carpeta|{n} carpetas +@plural {n} file|{n} files {n} archivo|{n} archivos +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Se omitió {n} carpeta, como las de otras aplicaciones y del sistema y las ocultas|Se omitieron {n} carpetas, como las de otras aplicaciones y del sistema y las ocultas +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read No se pudo leer {n} carpeta o archivo|No se pudieron leer {n} carpetas o archivos The search stopped at its limit: search a smaller folder. La búsqueda se detuvo en su límite: busca en una carpeta más pequeña. Copy only fonts you own or are licensed to install. Copia solo fuentes que te pertenezcan o cuya licencia te permita instalarlas. VectorCraft copies the fonts to {folder}. VectorCraft copia las fuentes en {folder}. @@ -3676,13 +3678,13 @@ font-technology Variable Variables Zoom Tool Herramienta Zoom Zoom with Mouse Wheel Zoom con la rueda del mouse Scrub Numeric Fields by Dragging Ajustar campos numéricos arrastrando - {count} file(s) in {folder} {note}. Show the package folder? {count} archivo(s) en {folder}{note}. ¿Mostrar la carpeta del paquete? - {count} linked file(s) not found No se encontraron {count} archivo(s) vinculado(s) +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} archivo en {folder} {note}. ¿Mostrar la carpeta del paquete?|{n} archivos en {folder} {note}. ¿Mostrar la carpeta del paquete? +@plural {n} linked file not found|{n} linked files not found No se encontró {n} archivo vinculado|No se encontraron {n} archivos vinculados fonts not copied: {fonts} fuentes no copiadas: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} imagen(es) vinculada(s) cambiaron desde que se guardó este documento. ¿Mostrar las versiones nuevas? - {count} linked image(s) changed on disk. Show the new versions? {count} imagen(es) vinculada(s) cambiaron en el disco. ¿Mostrar las versiones nuevas? - {count} more rules: Export writes every one. {count} reglas más: Exportar las escribe todas. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Se omitieron {count} objetos sin nombre: ponles nombre o activa Objetos sin nombre en el menú del panel. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} imagen vinculada cambió desde que se guardó este documento. ¿Mostrar la versión nueva?|{n} imágenes vinculadas cambiaron desde que se guardó este documento. ¿Mostrar las versiones nuevas? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} imagen vinculada cambió en el disco. ¿Mostrar la versión nueva?|{n} imágenes vinculadas cambiaron en el disco. ¿Mostrar las versiones nuevas? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regla más: Exportar la escribe.|{n} reglas más: Exportar las escribe todas. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Se omitió {n} objeto sin nombre: ponle nombre o activa Objetos sin nombre en el menú del panel.|Se omitieron {n} objetos sin nombre: ponles nombre o activa Objetos sin nombre en el menú del panel. {effect} is already applied {effect} ya está aplicado {format} Options Opciones de {format} {kind} Gradient Degradado {kind} @@ -5536,10 +5538,10 @@ axis Y Axis Eje Y @msg Packaged {n} file(s) in {folder} Se empaquetaron {n} archivo(s) en {folder} @msg Packaged {n} file(s) {note} Se empaquetaron {n} archivo(s) {note} @msg Packaged {n} file(s) Se empaquetaron {n} archivo(s) - Packaged {n} file(s) Se empaquetaron {n} archivo(s) - Packaged {n} file(s) in {folder} Se empaquetaron {n} archivo(s) en {folder} - Packaged {n} file(s) {note} Se empaquetaron {n} archivo(s) {note} - {count} file(s) in {folder}. Show the package folder? {count} archivo(s) en {folder}. ¿Mostrar la carpeta del paquete? +@plural Packaged {n} file|Packaged {n} files Se empaquetó {n} archivo|Se empaquetaron {n} archivos +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Se empaquetó {n} archivo en {folder}|Se empaquetaron {n} archivos en {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Se empaquetó {n} archivo {note}|Se empaquetaron {n} archivos {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} archivo en {folder}. ¿Mostrar la carpeta del paquete?|{n} archivos en {folder}. ¿Mostrar la carpeta del paquete? Clockwise En sentido horario Dither Tramado Fine noise hides banding in the gradient fill Un ruido fino oculta las bandas del relleno de degradado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ef924d1731..2d86cc5f7f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -663,7 +663,7 @@ 1 Layer 1 taso Libraries Kirjastot Links Linkit - {count} linked image(s) changed on disk. Show the new versions? {count} linkitettyä kuvaa muuttui levyllä. Näytetäänkö uudet versiot? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} linkitetty kuva muuttui levyllä. Näytetäänkö uusi versio?|{n} linkitettyä kuvaa muuttui levyllä. Näytetäänkö uudet versiot? Update Changed Links Päivitä muuttuneet linkit @msg Updated {_1} linked file(s) changed on disk Päivitettiin {_1} levyllä muuttunutta linkitettyä tiedostoa Magic Wand Taikasauva @@ -1479,8 +1479,8 @@ lighting Light Valo Select objects to see their CSS, or Generate CSS for the whole document. Valitse objektit, niin näet niiden CSS:n, tai luo CSS koko asiakirjalle. The selected objects have no CSS of their own (see below). Valituilla objekteilla ei ole omaa CSS:ää (katso alta). Units: {units} Yksiköt: {units} - {count} more rules: Export writes every one. {count} sääntöä lisää: vienti kirjoittaa ne kaikki. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} nimetöntä objektia jätetty pois: nimeä ne tai ota Nimettömät objektit käyttöön paneelin valikosta. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} sääntö lisää: vienti kirjoittaa sen.|{n} sääntöä lisää: vienti kirjoittaa ne kaikki. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} nimetön objekti jätetty pois: nimeä se tai ota Nimettömät objektit käyttöön paneelin valikosta.|{n} nimetöntä objektia jätetty pois: nimeä ne tai ota Nimettömät objektit käyttöön paneelin valikosta. All Categories Kaikki luokat Repeat Objects Toisto-objektit Save… Tallenna… @@ -2348,19 +2348,21 @@ lighting Light Valo Stop Pysäytä Searching… Haetaan… Not found Ei löytynyt - {folders} folder(s) and {files} file(s) searched Haettu {folders} kansio(ta) ja {files} tiedosto(a) - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} kansio(ta) ohitettu, kuten muiden sovellusten ja järjestelmän kansiot sekä piilotetut kansiot - {count} folder(s) or file(s) couldn't be read {count} kansiota tai tiedostoa ei voitu lukea + {folders} and {files} searched Haettu {folders} ja {files} +@plural {n} folder|{n} folders {n} kansio|{n} kansiota +@plural {n} file|{n} files {n} tiedosto|{n} tiedostoa +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} kansio ohitettu, kuten muiden sovellusten ja järjestelmän kansiot sekä piilotetut kansiot|{n} kansiota ohitettu, kuten muiden sovellusten ja järjestelmän kansiot sekä piilotetut kansiot +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} kansiota tai tiedostoa ei voitu lukea|{n} kansiota tai tiedostoa ei voitu lukea The search stopped at its limit: search a smaller folder. Haku pysähtyi rajaansa: hae pienemmästä kansiosta. Copy only fonts you own or are licensed to install. Kopioi vain fontteja, jotka omistat tai joiden asentamiseen sinulla on lisenssi. VectorCraft copies the fonts to {folder}. VectorCraft kopioi fontit kansioon {folder}. - Apply to All ({count} more missing) Käytä kaikkiin ({count} muuta puuttuu) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Käytä kaikkiin ({n} muu puuttuu)|Käytä kaikkiin ({n} muuta puuttuu) Ignore Ohita Linked File Not Found Linkitettyä tiedostoa ei löydy Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Korvaa se toisella tiedostolla tai ohita se: sen kuvissa näkyy asiakirjaan tallennettu esikatselu. Replace… Korvaa… Update Modified Links Päivitä muokatut linkit - {count} linked image(s) changed since this document was saved. Show the new versions? {count} linkitettyä kuvaa on muuttunut asiakirjan tallentamisen jälkeen. Näytetäänkö uudet versiot? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} linkitetty kuva on muuttunut asiakirjan tallentamisen jälkeen. Näytetäänkö uusi versio?|{n} linkitettyä kuvaa on muuttunut asiakirjan tallentamisen jälkeen. Näytetäänkö uudet versiot? Dialog Valintaikkuna Convert Process to Global Muunna prosessivärit globaaleiksi Create From: Luo kohteesta: @@ -2399,12 +2401,12 @@ lighting Light Valo Fonts whose licence doesn't allow embedding are not copied. Fontteja, joiden lisenssi ei salli upottamista, ei kopioida. Package collects a saved document with its linked files and fonts. Paketointi kokoaa tallennetun asiakirjan sekä sen linkitetyt tiedostot ja fontit. Package created Paketti luotu - Packaged {n} file(s) in {folder} {note} Paketoitiin {n} tiedosto(a) kansioon {folder} {note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Paketoitiin {n} tiedosto kansioon {folder} {note}|Paketoitiin {n} tiedostoa kansioon {folder} {note} Packaged {n} file(s){note} Paketoitu {n} tiedosto(a){note} Relink Linked Files to the Document Linkitä linkitetyt tiedostot uudelleen asiakirjaan Save the document first? Tallennetaanko asiakirja ensin? - {count} file(s) in {folder} {note}. Show the package folder? {count} tiedosto(a) kansiossa {folder} {note}. Näytetäänkö pakettikansio? - {count} linked file(s) not found {count} linkitettyä tiedostoa ei löytynyt +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} tiedosto kansiossa {folder} {note}. Näytetäänkö pakettikansio?|{n} tiedostoa kansiossa {folder} {note}. Näytetäänkö pakettikansio? +@plural {n} linked file not found|{n} linked files not found {n} linkitettyä tiedostoa ei löytynyt|{n} linkitettyä tiedostoa ei löytynyt fonts not copied: {fonts} fontteja ei kopioitu: {fonts} Built-in presets are read-only: New… starts an editable copy. Sisäiset esiasetukset ovat vain luku -tilassa: Uusi… luo muokattavan kopion. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} piirtoalustalla vastaa {real} {unit} näkymässä. @@ -5625,10 +5627,10 @@ axis Y Axis Y-akseli @msg Packaged {n} file(s) in {folder} Paketoitiin {n} tiedosto(a) kansioon {folder} @msg Packaged {n} file(s) {note} Paketoitiin {n} tiedosto(a) {note} @msg Packaged {n} file(s) Paketoitiin {n} tiedosto(a) - Packaged {n} file(s) Paketoitiin {n} tiedosto(a) - Packaged {n} file(s) in {folder} Paketoitiin {n} tiedosto(a) kansioon {folder} - Packaged {n} file(s) {note} Paketoitiin {n} tiedosto(a) {note} - {count} file(s) in {folder}. Show the package folder? {count} tiedosto(a) kansiossa {folder}. Näytetäänkö pakettikansio? +@plural Packaged {n} file|Packaged {n} files Paketoitiin {n} tiedosto|Paketoitiin {n} tiedostoa +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Paketoitiin {n} tiedosto kansioon {folder}|Paketoitiin {n} tiedostoa kansioon {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Paketoitiin {n} tiedosto {note}|Paketoitiin {n} tiedostoa {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} tiedosto kansiossa {folder}. Näytetäänkö pakettikansio?|{n} tiedostoa kansiossa {folder}. Näytetäänkö pakettikansio? Clockwise Myötäpäivään Dither Rasterointi Fine noise hides banding in the gradient fill Hieno kohina piilottaa raidat liukuväritäytöstä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 7d5fe46b1e..29cb4e6d1c 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -218,7 +218,7 @@ font-technology Variable Variables Apply Paragraph Style Appliquer le style de paragraphe Apply SVG Filter… Appliquer un filtre SVG… Apply to All Appliquer à tous - Apply to All ({count} more missing) Appliquer à tous ({count} autres manquants) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Appliquer à tous ({n} autre manquant)|Appliquer à tous ({n} autres manquants) Arc Arc Arc Lower… Arc inférieur… Arc Tool Outil Arc @@ -2270,7 +2270,7 @@ font-technology Variable Variables Package Assembler Package collects a saved document with its linked files and fonts. Assembler rassemble un document enregistré avec ses fichiers liés et ses polices. Package created Assemblage créé - Packaged {n} file(s) in {folder} {note} {n} fichier(s) assemblé(s) dans {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} fichier assemblé dans {folder} {note}|{n} fichiers assemblés dans {folder} {note} Packaged {n} file(s){note} {n} fichier(s) assemblé(s){note} Package… Assembler… Page Page @@ -2590,9 +2590,11 @@ font-technology Variable Variables Stop Arrêter Searching… Recherche… Not found Introuvable - {folders} folder(s) and {files} file(s) searched {folders} dossier(s) et {files} fichier(s) parcourus - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} dossier(s) ignoré(s), comme ceux d’autres apps et du système et les dossiers masqués - {count} folder(s) or file(s) couldn't be read {count} dossier(s) ou fichier(s) illisible(s) + {folders} and {files} searched {folders} et {files} parcourus +@plural {n} folder|{n} folders {n} dossier|{n} dossiers +@plural {n} file|{n} files {n} fichier|{n} fichiers +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} dossier ignoré, comme ceux d’autres apps et du système et les dossiers masqués|{n} dossiers ignorés, comme ceux d’autres apps et du système et les dossiers masqués +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} dossier ou fichier illisible|{n} dossiers ou fichiers illisibles The search stopped at its limit: search a smaller folder. La recherche s’est arrêtée à sa limite : recherchez dans un dossier plus petit. Copy only fonts you own or are licensed to install. Ne copiez que des polices qui vous appartiennent ou dont la licence vous autorise l’installation. VectorCraft copies the fonts to {folder}. VectorCraft copie les polices dans {folder}. @@ -3674,13 +3676,13 @@ font-technology Variable Variables Zoom Tool Outil Zoom Zoom with Mouse Wheel Zoom avec la molette de la souris Scrub Numeric Fields by Dragging Modifier les champs numériques en faisant glisser - {count} file(s) in {folder} {note}. Show the package folder? {count} fichier(s) dans {folder}{note}. Afficher le dossier de l’assemblage ? - {count} linked file(s) not found {count} fichier(s) lié(s) introuvable(s) +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fichier dans {folder} {note}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder} {note}. Afficher le dossier de l’assemblage ? +@plural {n} linked file not found|{n} linked files not found {n} fichier lié introuvable|{n} fichiers liés introuvables fonts not copied: {fonts} polices non copiées : {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} image(s) liée(s) modifiée(s) depuis l’enregistrement de ce document. Afficher les nouvelles versions ? - {count} linked image(s) changed on disk. Show the new versions? {count} image(s) liée(s) modifiée(s) sur le disque. Afficher les nouvelles versions ? - {count} more rules: Export writes every one. {count} règles de plus : Exporter les écrit toutes. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} objets sans nom omis : nommez-les ou activez Objets sans nom dans le menu du panneau. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} image liée modifiée depuis l’enregistrement de ce document. Afficher la nouvelle version ?|{n} images liées modifiées depuis l’enregistrement de ce document. Afficher les nouvelles versions ? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} image liée modifiée sur le disque. Afficher la nouvelle version ?|{n} images liées modifiées sur le disque. Afficher les nouvelles versions ? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} règle de plus : Exporter l’écrit.|{n} règles de plus : Exporter les écrit toutes. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} objet sans nom omis : nommez-le ou activez Objets sans nom dans le menu du panneau.|{n} objets sans nom omis : nommez-les ou activez Objets sans nom dans le menu du panneau. {effect} is already applied {effect} est déjà appliqué {format} Options Options {format} {kind} Gradient Dégradé {kind} @@ -5592,10 +5594,10 @@ axis Y Axis Axe Y @msg Packaged {n} file(s) in {folder} {n} fichier(s) assemblé(s) dans {folder} @msg Packaged {n} file(s) {note} {n} fichier(s) assemblé(s) {note} @msg Packaged {n} file(s) {n} fichier(s) assemblé(s) - Packaged {n} file(s) {n} fichier(s) assemblé(s) - Packaged {n} file(s) in {folder} {n} fichier(s) assemblé(s) dans {folder} - Packaged {n} file(s) {note} {n} fichier(s) assemblé(s) {note} - {count} file(s) in {folder}. Show the package folder? {count} fichier(s) dans {folder}. Afficher le dossier de l’assemblage ? +@plural Packaged {n} file|Packaged {n} files {n} fichier assemblé|{n} fichiers assemblés +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} fichier assemblé dans {folder}|{n} fichiers assemblés dans {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} fichier assemblé {note}|{n} fichiers assemblés {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fichier dans {folder}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder}. Afficher le dossier de l’assemblage ? Clockwise Sens horaire Dither Simulation Fine noise hides banding in the gradient fill Un bruit fin masque les bandes du fond en dégradé diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0d71cbb8ae..74a25582c0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -300,7 +300,7 @@ font-technology Variable Változó Apply Paragraph Style Bekezdésstílus alkalmazása Apply SVG Filter… SVG-szűrő alkalmazása… Apply to All Alkalmazás az összesre - Apply to All ({count} more missing) Alkalmazás mindegyikre (további hiányzók: {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Alkalmazás mindegyikre (további hiányzók: {n}) Approximate path Útvonal közelítése Arabic Arab Arc Ív @@ -2754,7 +2754,7 @@ file-filter Templates Sablonok Package Csomagolás Package collects a saved document with its linked files and fonts. A csomagolás egy mentett dokumentumot a csatolt fájljaival és betűtípusaival együtt gyűjt össze. Package created A csomag elkészült - Packaged {n} file(s) in {folder} {note} Becsomagolt fájlok: {n}, mappa: {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Becsomagolt fájlok: {n}, mappa: {folder} {note} Packaged {n} file(s){note} Becsomagolt fájlok: {n}{note} Package… Csomagolás… Page Oldal @@ -4406,16 +4406,18 @@ mark-style Japanese Japán Zoom to Selection Nagyítás a kijelölésre Zoom Tool Nagyító Zoom with Mouse Wheel Nagyítás egérgörgővel - {count} file(s) in {folder} {note}. Show the package folder? Fájlok: {count}, mappa: {folder}{note}. Megnyitod a csomag mappáját? - {count} folder(s) or file(s) couldn't be read Nem olvasható mappák vagy fájlok: {count} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Kihagyott mappák: {count} (például más alkalmazások, a rendszer és a rejtett mappák) - {count} linked file(s) not found Nem található csatolt fájlok: {count} - {count} linked image(s) changed on disk. Show the new versions? A lemezen módosult csatolt képek: {count}. Megjelenítsük az új változatokat? - {count} linked image(s) changed since this document was saved. Show the new versions? A dokumentum mentése óta módosult csatolt képek: {count}. Megjelenítsük az új változatokat? - {count} more rules: Export writes every one. További szabályok: {count}. Az exportálás mindet kiírja. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Kimaradt névtelen objektumok: {count}. Nevezd el őket, vagy kapcsold be a panelmenüben a Névtelen objektumok elemet. +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Fájlok: {n}, mappa: {folder} {note}. Megnyitod a csomag mappáját? +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Nem olvasható mappák vagy fájlok: {n} +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Kihagyott mappák: {n} (például más alkalmazások, a rendszer és a rejtett mappák) +@plural {n} linked file not found|{n} linked files not found Nem található csatolt fájlok: {n} +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? A lemezen módosult csatolt képek: {n}. Megjelenítsük az új változatokat? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? A dokumentum mentése óta módosult csatolt képek: {n}. Megjelenítsük az új változatokat? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. További szabályok: {n}. Az exportálás mindet kiírja. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Kimaradt névtelen objektumok: {n}. Nevezd el őket, vagy kapcsold be a panelmenüben a Névtelen objektumok elemet. {effect} is already applied Már alkalmazva: {effect} - {folders} folder(s) and {files} file(s) searched Átkeresett mappák: {folders}, fájlok: {files} + {folders} and {files} searched Átkeresve: {folders} és {files} +@plural {n} folder|{n} folders {n} mappa +@plural {n} file|{n} files {n} fájl {format} Options Formátumbeállítások: {format} {kind} Gradient Színátmenet: {kind} gradient-kind Radial Körkörös @@ -5580,10 +5582,10 @@ axis Y Axis Y tengely @msg Packaged {n} file(s) in {folder} Becsomagolt fájlok: {n}, mappa: {folder} @msg Packaged {n} file(s) {note} Becsomagolt fájlok: {n} {note} @msg Packaged {n} file(s) Becsomagolt fájlok: {n} - Packaged {n} file(s) Becsomagolt fájlok: {n} - Packaged {n} file(s) in {folder} Becsomagolt fájlok: {n}, mappa: {folder} - Packaged {n} file(s) {note} Becsomagolt fájlok: {n} {note} - {count} file(s) in {folder}. Show the package folder? Fájlok: {count}, mappa: {folder}. Megnyitod a csomag mappáját? +@plural Packaged {n} file|Packaged {n} files Becsomagolt fájlok: {n} +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Becsomagolt fájlok: {n}, mappa: {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Becsomagolt fájlok: {n} {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? Fájlok: {n}, mappa: {folder}. Megnyitod a csomag mappáját? Clockwise Óramutató járásával megegyező Dither Árnyalatkeverés Fine noise hides banding in the gradient fill A finom zaj elrejti a sávokat a színátmenetes kitöltésben diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index bfa0660240..f8bee41744 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -624,7 +624,7 @@ 1 Layer 1 lapisan Libraries Pustaka Links Tautan - {count} linked image(s) changed on disk. Show the new versions? {count} gambar tertaut di disk telah berubah. Tampilkan versi baru? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} gambar tertaut di disk telah berubah. Tampilkan versi baru? Update Changed Links Perbarui tautan yang berubah @msg Updated {_1} linked file(s) changed on disk Telah memperbarui {_1} berkas tertaut yang berubah di disk Magic Wand Tongkat ajaib @@ -1419,8 +1419,8 @@ lighting Light Cahaya Select objects to see their CSS, or Generate CSS for the whole document. Pilih objek untuk melihat CSS-nya, atau buat CSS untuk seluruh dokumen. The selected objects have no CSS of their own (see below). Objek terpilih tidak memiliki CSS tersendiri (lihat di bawah). Units: {units} Unit: {units} - {count} more rules: Export writes every one. {count} aturan lagi: Ekspor menuliskan semuanya. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} objek tanpa nama tidak disertakan: beri nama, atau aktifkan Objek Tanpa Nama di menu panel. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} aturan lagi: Ekspor menuliskan semuanya. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} objek tanpa nama tidak disertakan: beri nama, atau aktifkan Objek Tanpa Nama di menu panel. All Categories Semua kategori Repeat Objects Objek pengulangan Save… Simpan… @@ -2196,19 +2196,21 @@ lighting Light Cahaya Stop Hentikan Searching… Mencari… Not found Tidak ditemukan - {folders} folder(s) and {files} file(s) searched {folders} folder dan {files} file telah dicari - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} folder dilewati, seperti folder aplikasi lain, folder sistem, dan folder tersembunyi - {count} folder(s) or file(s) couldn't be read {count} folder atau file tidak dapat dibaca + {folders} and {files} searched {folders} dan {files} telah dicari +@plural {n} folder|{n} folders {n} folder +@plural {n} file|{n} files {n} file +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} folder dilewati, seperti folder aplikasi lain, folder sistem, dan folder tersembunyi +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} folder atau file tidak dapat dibaca The search stopped at its limit: search a smaller folder. Pencarian berhenti pada batasnya: cari folder yang lebih kecil. Copy only fonts you own or are licensed to install. Salin hanya font yang Anda miliki atau yang dilisensikan untuk dipasang. VectorCraft copies the fonts to {folder}. VectorCraft menyalin font ke {folder}. - Apply to All ({count} more missing) Terapkan ke semua ({count} lagi hilang) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Terapkan ke semua ({n} lagi hilang) Ignore Abaikan Linked File Not Found File tertaut tidak ditemukan Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Ganti dengan file lain, atau abaikan: gambarnya tetap menampilkan pratinjau yang tersimpan bersama dokumen. Replace… Ganti… Update Modified Links Perbarui tautan yang diubah - {count} linked image(s) changed since this document was saved. Show the new versions? {count} gambar tertaut berubah sejak dokumen ini disimpan. Tampilkan versi barunya? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} gambar tertaut berubah sejak dokumen ini disimpan. Tampilkan versi barunya? Dialog Dialog Convert Process to Global Konversi proses ke global Create From: Buat dari: @@ -2247,12 +2249,12 @@ lighting Light Cahaya Fonts whose licence doesn't allow embedding are not copied. Font yang lisensinya tidak mengizinkan penyematan tidak disalin. Package collects a saved document with its linked files and fonts. Package mengumpulkan dokumen tersimpan beserta file dan font yang tertaut. Package created Paket dibuat - Packaged {n} file(s) in {folder} {note} {n} file dipaketkan dalam {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} file dipaketkan dalam {folder} {note} Packaged {n} file(s){note} {n} file dipaketkan{note} Relink Linked Files to the Document Tautkan ulang file tertaut ke dokumen Save the document first? Simpan dokumen terlebih dahulu? - {count} file(s) in {folder} {note}. Show the package folder? {count} file dalam {folder}{note}. Tampilkan folder paket? - {count} linked file(s) not found {count} file tertaut tidak ditemukan +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} file dalam {folder} {note}. Tampilkan folder paket? +@plural {n} linked file not found|{n} linked files not found {n} file tertaut tidak ditemukan fonts not copied: {fonts} font tidak disalin: {fonts} Built-in presets are read-only: New… starts an editable copy. Preset bawaan bersifat hanya-baca: Baru… memulai salinan yang dapat diedit. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} pada artboard mewakili {real} {unit} dalam scene. @@ -5520,10 +5522,10 @@ axis Y Axis Sumbu Y @msg Packaged {n} file(s) in {folder} Berhasil mengemas {n} file di {folder} @msg Packaged {n} file(s) {note} Berhasil mengemas {n} file {note} @msg Packaged {n} file(s) Berhasil mengemas {n} file - Packaged {n} file(s) Berhasil mengemas {n} file - Packaged {n} file(s) in {folder} Berhasil mengemas {n} file di {folder} - Packaged {n} file(s) {note} Berhasil mengemas {n} file {note} - {count} file(s) in {folder}. Show the package folder? {count} file dalam {folder}. Tampilkan folder paket? +@plural Packaged {n} file|Packaged {n} files Berhasil mengemas {n} file +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Berhasil mengemas {n} file di {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Berhasil mengemas {n} file {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} file dalam {folder}. Tampilkan folder paket? Clockwise Searah jarum jam Dither Dither Fine noise hides banding in the gradient fill Derau halus menyembunyikan pita warna pada isian gradien diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2c587de487..5fd0ed4b79 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -217,7 +217,7 @@ font-technology Variable Variabili Apply Paragraph Style Applica stile paragrafo Apply SVG Filter… Applica filtro SVG… Apply to All Applica a tutti - Apply to All ({count} more missing) Applica a tutti (ne mancano altri {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Applica a tutti (ne manca ancora {n})|Applica a tutti (ne mancano altri {n}) Arc Arco Arc Lower… Arco inferiore… Arc Tool Strumento Arco @@ -2299,7 +2299,7 @@ file-filter Templates Modelli Package Crea pacchetto Package collects a saved document with its linked files and fonts. Il comando Crea pacchetto raccoglie un documento salvato insieme ai file collegati e ai font. Package created Pacchetto creato - Packaged {n} file(s) in {folder} {note} Pacchetto creato con {n} file in {folder} {note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Pacchetto creato con {n} file in {folder} {note}|Pacchetto creato con {n} file in {folder} {note} Packaged {n} file(s){note} Pacchetto creato con {n} file{note} Package… Crea pacchetto… Page Pagina @@ -2623,9 +2623,11 @@ mark-style Japanese Giapponese Stop Interrompi Searching… Ricerca in corso… Not found Non trovato - {folders} folder(s) and {files} file(s) searched Cartelle cercate: {folders}, file: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Cartelle saltate: {count}, ad esempio quelle di altre app e di sistema e quelle nascoste - {count} folder(s) or file(s) couldn't be read Cartelle o file non leggibili: {count} + {folders} and {files} searched Cercato in {folders} e {files} +@plural {n} folder|{n} folders {n} cartella|{n} cartelle +@plural {n} file|{n} files {n} file|{n} file +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Cartelle saltate: {n}, ad esempio quelle di altre app e di sistema e quelle nascoste|Cartelle saltate: {n}, ad esempio quelle di altre app e di sistema e quelle nascoste +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Cartelle o file non leggibili: {n}|Cartelle o file non leggibili: {n} The search stopped at its limit: search a smaller folder. La ricerca si è fermata al suo limite: cerca in una cartella più piccola. Copy only fonts you own or are licensed to install. Copia solo font di tua proprietà o con una licenza che ti consente di installarli. VectorCraft copies the fonts to {folder}. VectorCraft copia i font in {folder}. @@ -3711,13 +3713,13 @@ mark-style Japanese Giapponese Zoom Tool Strumento Zoom Zoom with Mouse Wheel Zoom con la rotellina del mouse Scrub Numeric Fields by Dragging Regola i campi numerici trascinando - {count} file(s) in {folder} {note}. Show the package folder? {count} file in {folder} {note}. Vuoi mostrare la cartella del pacchetto? - {count} linked file(s) not found File collegati non trovati: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} file in {folder} {note}. Vuoi mostrare la cartella del pacchetto?|{n} file in {folder} {note}. Vuoi mostrare la cartella del pacchetto? +@plural {n} linked file not found|{n} linked files not found File collegati non trovati: {n}|File collegati non trovati: {n} fonts not copied: {fonts} font non copiati: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? Immagini collegate modificate dopo il salvataggio di questo documento: {count}. Vuoi mostrare le nuove versioni? - {count} linked image(s) changed on disk. Show the new versions? Immagini collegate modificate su disco: {count}. Vuoi mostrare le nuove versioni? - {count} more rules: Export writes every one. Altre {count} regole: Esporta le scrive tutte. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} oggetti senza nome esclusi: assegna loro un nome o attiva Oggetti senza nome nel menu del pannello. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? Immagini collegate modificate dopo il salvataggio di questo documento: {n}. Vuoi mostrare le nuove versioni?|Immagini collegate modificate dopo il salvataggio di questo documento: {n}. Vuoi mostrare le nuove versioni? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Immagini collegate modificate su disco: {n}. Vuoi mostrare le nuove versioni?|Immagini collegate modificate su disco: {n}. Vuoi mostrare le nuove versioni? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regola in più: Esporta la scrive.|Altre {n} regole: Esporta le scrive tutte. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} oggetto senza nome escluso: assegnagli un nome o attiva Oggetti senza nome nel menu del pannello.|{n} oggetti senza nome esclusi: assegna loro un nome o attiva Oggetti senza nome nel menu del pannello. {effect} is already applied L'effetto {effect} è già applicato {format} Options Opzioni {format} {kind} Gradient Sfumatura {kind} @@ -5209,10 +5211,10 @@ axis Y Axis Asse Y @msg Packaged {n} file(s) in {folder} Pacchetto creato con {n} file in {folder} @msg Packaged {n} file(s) {note} Pacchetto creato con {n} file {note} @msg Packaged {n} file(s) Pacchetto creato con {n} file - Packaged {n} file(s) Pacchetto creato con {n} file - Packaged {n} file(s) in {folder} Pacchetto creato con {n} file in {folder} - Packaged {n} file(s) {note} Pacchetto creato con {n} file {note} - {count} file(s) in {folder}. Show the package folder? {count} file in {folder}. Vuoi mostrare la cartella del pacchetto? +@plural Packaged {n} file|Packaged {n} files Pacchetto creato con {n} file|Pacchetto creato con {n} file +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Pacchetto creato con {n} file in {folder}|Pacchetto creato con {n} file in {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Pacchetto creato con {n} file {note}|Pacchetto creato con {n} file {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} file in {folder}. Vuoi mostrare la cartella del pacchetto?|{n} file in {folder}. Vuoi mostrare la cartella del pacchetto? Clockwise In senso orario Dither Dithering Fine noise hides banding in the gradient fill Un rumore fine nasconde le bande nel riempimento sfumato diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 0326a5c841..57715d1363 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -954,7 +954,7 @@ font-technology Variable バリアブル Apply Last Gradient 最後のグラデーションを適用 Apply Paragraph Style 段落スタイルを適用 Apply to All すべてに適用 - Apply to All ({count} more missing) すべてに適用 (ほかに {count} 個が見つかりません) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) すべてに適用 (ほかに {n} 個が見つかりません) Arc 円弧 Arc Tool 円弧ツール Area / Path Type エリア内文字/パス上文字 @@ -2618,9 +2618,11 @@ mark-style Japanese 日本式 Stop 停止 Searching… 検索中… Not found 見つかりません - {folders} folder(s) and {files} file(s) searched {folders} 個のフォルダーと {files} 個のファイルを検索しました - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} 個のフォルダーをスキップしました(他のアプリやシステムのフォルダー、隠しフォルダーなど) - {count} folder(s) or file(s) couldn't be read {count} 個のフォルダーまたはファイルを読み込めませんでした + {folders} and {files} searched {folders} と {files} を検索しました +@plural {n} folder|{n} folders {n} 個のフォルダー +@plural {n} file|{n} files {n} 個のファイル +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} 個のフォルダーをスキップしました(他のアプリやシステムのフォルダー、隠しフォルダーなど) +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} 個のフォルダーまたはファイルを読み込めませんでした The search stopped at its limit: search a smaller folder. 検索は上限で停止しました。より小さなフォルダーを検索してください。 Copy only fonts you own or are licensed to install. 所有しているフォント、またはインストールするライセンスがあるフォントだけをコピーしてください。 VectorCraft copies the fonts to {folder}. VectorCraft はフォントを {folder} にコピーします。 @@ -3305,13 +3307,13 @@ mark-style Japanese 日本式 the preset プリセット tile {number} タイル {number} to → - {count} file(s) in {folder} {note}. Show the package folder? {folder} に {count} 個のファイル{note}。パッケージフォルダーを表示しますか? - {count} linked file(s) not found リンクファイルが {count} 個見つかりません +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} に {n} 個のファイル{note}。パッケージフォルダーを表示しますか? +@plural {n} linked file not found|{n} linked files not found リンクファイルが {n} 個見つかりません fonts not copied: {fonts} コピーされなかったフォント:{fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? 保存後に {count} 個のリンク画像が変更されています。新しいバージョンを表示しますか? - {count} linked image(s) changed on disk. Show the new versions? {count} 個のリンク画像がディスク上で変更されました。新しいバージョンを表示しますか? - {count} more rules: Export writes every one. ほかに {count} 個のルールがあります。書き出しにはすべて含まれます。 - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 名前のないオブジェクト {count} 個を除外しました。名前を付けるか、パネルメニューで「名前のないオブジェクト」をオンにしてください。 +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? 保存後に {n} 個のリンク画像が変更されています。新しいバージョンを表示しますか? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} 個のリンク画像がディスク上で変更されました。新しいバージョンを表示しますか? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. ほかに {n} 個のルールがあります。書き出しにはすべて含まれます。 +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 名前のないオブジェクト {n} 個を除外しました。名前を付けるか、パネルメニューで「名前のないオブジェクト」をオンにしてください。 {effect} is already applied {effect} はすでに適用されています {format} Options {format} オプション {kind} Gradient {kind}グラデーション @@ -3583,7 +3585,7 @@ file-filter Templates テンプレート Output Black 出力ブラック Output White 出力ホワイト Output › Mode 出力 › モード - Packaged {n} file(s) in {folder} {note} {folder} に {n} 個のファイルをパッケージしました{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {folder} に {n} 個のファイルをパッケージしました{note} Packaged {n} file(s){note} {n} 個のファイルをパッケージしました{note} Page information ページ情報 Paragraph Style 段落スタイル @@ -5275,10 +5277,10 @@ axis Y Axis Y 軸 @msg Packaged {n} file(s) in {folder} {n} 個のファイルを {folder} にパッケージしました @msg Packaged {n} file(s) {note} {n} 個のファイルをパッケージしました {note} @msg Packaged {n} file(s) {n} 個のファイルをパッケージしました - Packaged {n} file(s) {n} 個のファイルをパッケージしました - Packaged {n} file(s) in {folder} {n} 個のファイルを {folder} にパッケージしました - Packaged {n} file(s) {note} {n} 個のファイルをパッケージしました {note} - {count} file(s) in {folder}. Show the package folder? {folder} に {count} 個のファイル。パッケージフォルダーを表示しますか? +@plural Packaged {n} file|Packaged {n} files {n} 個のファイルをパッケージしました +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} 個のファイルを {folder} にパッケージしました +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} 個のファイルをパッケージしました {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {folder} に {n} 個のファイル。パッケージフォルダーを表示しますか? Clockwise 時計回り Dither ディザ Fine noise hides banding in the gradient fill 細かいノイズでグラデーションの塗りの縞を目立たなくします diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b34d095505..423d50a0af 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -566,7 +566,7 @@ Layers შრეები Libraries ბიბლიოთეკა Links ბმულები - {count} linked image(s) changed on disk. Show the new versions? დისკზე შეიცვალა დაკავშირებული გამოსახულებები ({count}). ვაჩვენო ახალი ვერსიები? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? დისკზე შეიცვალა დაკავშირებული გამოსახულებები ({n}). ვაჩვენო ახალი ვერსიები? Update Changed Links შეცვლილი ბმულების განახლება @msg Updated {_1} linked file(s) changed on disk განახლდა დისკზე შეცვლილი დაკავშირებული ფაილები: {_1} Magic Wand ჯადოსნური ჯოხი @@ -1336,8 +1336,8 @@ lighting Light სინათლე Select objects to see their CSS, or Generate CSS for the whole document. მონიშნეთ ობიექტები მათი CSS-ის სანახავად, ან შექმენით CSS მთელი დოკუმენტისთვის. The selected objects have no CSS of their own (see below). მონიშნულ ობიექტებს საკუთარი CSS არ აქვს (იხ. ქვემოთ). Units: {units} ერთეულები: {units} - {count} more rules: Export writes every one. კიდევ წესები: {count}. ექსპორტი ყველას ჩაწერს. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. გამოტოვებულია უსახელო ობიექტები: {count}. დაარქვით მათ სახელი ან პანელის მენიუში ჩართეთ „უსახელო ობიექტები“. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. კიდევ წესები: {n}. ექსპორტი ყველას ჩაწერს. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. გამოტოვებულია უსახელო ობიექტები: {n}. დაარქვით მათ სახელი ან პანელის მენიუში ჩართეთ „უსახელო ობიექტები“. All Categories ყველა კატეგორია Repeat Objects გამეორების ობიექტები Save… შენახვა… @@ -2093,19 +2093,21 @@ lighting Light სინათლე Stop შეწყვეტა Searching… ძიება… Not found ვერ მოიძებნა - {folders} folder(s) and {files} file(s) searched მოიძებნა საქაღალდეები: {folders}, ფაილები: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones გამოტოვებული საქაღალდეები: {count} — მაგ. სხვა აპლიკაციების, სისტემის და დამალული საქაღალდეები - {count} folder(s) or file(s) couldn't be read ვერ წაიკითხა საქაღალდეები ან ფაილები: {count} + {folders} and {files} searched მოიძებნა: {folders}, {files} +@plural {n} folder|{n} folders {n} საქაღალდე +@plural {n} file|{n} files {n} ფაილი +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones გამოტოვებული საქაღალდეები: {n} — მაგ. სხვა აპლიკაციების, სისტემის და დამალული საქაღალდეები +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read ვერ წაიკითხა საქაღალდეები ან ფაილები: {n} The search stopped at its limit: search a smaller folder. ძიება ზღვარზე შეჩერდა: მოძებნეთ უფრო პატარა საქაღალდეში. Copy only fonts you own or are licensed to install. დააკოპირეთ მხოლოდ ის შრიფტები, რომლებიც გეკუთვნით ან რომელთა დაყენების ლიცენზია გაქვთ. VectorCraft copies the fonts to {folder}. VectorCraft შრიფტებს აკოპირებს აქ: {folder}. - Apply to All ({count} more missing) ყველაზე გამოყენება (კიდევ დაკარგული: {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) ყველაზე გამოყენება (კიდევ დაკარგული: {n}) Ignore უგულებელყოფა Linked File Not Found დაკავშირებული ფაილი ვერ მოიძებნა Replace it with another file, or ignore it: its images keep showing the preview saved with the document. ჩაანაცვლეთ სხვა ფაილით ან უგულებელყავით: მისი გამოსახულებები დოკუმენტთან შენახულ წინასწარ ხედს აჩვენებს. Replace… ჩანაცვლება… Update Modified Links შეცვლილი ბმულების განახლება - {count} linked image(s) changed since this document was saved. Show the new versions? დოკუმენტის შენახვის შემდეგ შეიცვალა დაკავშირებული გამოსახულებები: {count}. ვაჩვენოთ ახალი ვერსიები? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? დოკუმენტის შენახვის შემდეგ შეიცვალა დაკავშირებული გამოსახულებები: {n}. ვაჩვენოთ ახალი ვერსიები? Dialog დიალოგი Convert Process to Global პროცესულის გლობალურად გარდაქმნა Create From: შექმნის წყარო: @@ -2143,12 +2145,12 @@ lighting Light სინათლე Fonts whose licence doesn't allow embedding are not copied. შრიფტები, რომელთა ლიცენზია ჩაშენების უფლებას არ იძლევა, არ კოპირდება. Package collects a saved document with its linked files and fonts. შეფუთვა აგროვებს შენახულ დოკუმენტს მის დაკავშირებულ ფაილებთან და შრიფტებთან ერთად. Package created შეფუთვა შეიქმნა - Packaged {n} file(s) in {folder} {note} შეიფუთა ფაილები: {n}, ადგილი: {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} შეიფუთა ფაილები: {n}, ადგილი: {folder} {note} Packaged {n} file(s){note} შეიფუთა ფაილები: {n}{note} Relink Linked Files to the Document დაკავშირებული ფაილების დოკუმენტთან ხელახლა დაკავშირება Save the document first? ჯერ შევინახოთ დოკუმენტი? - {count} file(s) in {folder} {note}. Show the package folder? ფაილები: {count}, ადგილი: {folder}{note}. ვაჩვენოთ შეფუთვის საქაღალდე? - {count} linked file(s) not found ვერ მოიძებნა დაკავშირებული ფაილები: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? ფაილები: {n}, ადგილი: {folder} {note}. ვაჩვენოთ შეფუთვის საქაღალდე? +@plural {n} linked file not found|{n} linked files not found ვერ მოიძებნა დაკავშირებული ფაილები: {n} fonts not copied: {fonts} არ დაკოპირდა შრიფტები: {fonts} Built-in presets are read-only: New… starts an editable copy. ჩაშენებული პრესეტები მხოლოდ წასაკითხია: „ახალი…“ ქმნის რედაქტირებად ასლს. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} სამუშაო დაფაზე სცენაში {real} {unit}-ს შეესაბამება. @@ -5506,10 +5508,10 @@ axis Y Axis Y ღერძი @msg Packaged {n} file(s) in {folder} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} @msg Packaged {n} file(s) {note} შეფუთულია ფაილი ({n}) {note} @msg Packaged {n} file(s) შეფუთულია ფაილი ({n}) - Packaged {n} file(s) შეფუთულია ფაილი ({n}) - Packaged {n} file(s) in {folder} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} - Packaged {n} file(s) {note} შეფუთულია ფაილი ({n}) {note} - {count} file(s) in {folder}. Show the package folder? ფაილები: {count}, ადგილი: {folder}. ვაჩვენოთ შეფუთვის საქაღალდე? +@plural Packaged {n} file|Packaged {n} files შეფუთულია ფაილი ({n}) +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} შეფუთულია ფაილი ({n}) საქაღალდეში {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} შეფუთულია ფაილი ({n}) {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? ფაილები: {n}, ადგილი: {folder}. ვაჩვენოთ შეფუთვის საქაღალდე? Create PDF layers from top-level layers PDF-ის ფენების შექმნა ზედა დონის ფენებიდან @msg this kind of brush has no options dialog yet ამ ტიპის ფუნჯს პარამეტრების დიალოგი ჯერ არ აქვს Drag art, colors and text styles here to reuse them across documents. Libraries are stored on this machine — no account required. გადმოათრიეთ აქ გრაფიკა, ფერები და ტექსტის სტილები, რომ სხვა დოკუმენტებშიც გამოიყენოთ. ბიბლიოთეკები ამ კომპიუტერზე ინახება — ანგარიში არ არის საჭირო. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5e7e7db024..9be4625826 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -945,7 +945,7 @@ font-technology Variable 가변 Apply Last Gradient 마지막 그레이디언트 적용 Apply Paragraph Style 단락 스타일 적용 Apply to All 모두에 적용 - Apply to All ({count} more missing) 모두에 적용(누락 {count}개 더 있음) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) 모두에 적용(누락 {n}개 더 있음) Arc 호 Arc Tool 호 도구 Area / Path Type 영역/패스 문자 @@ -2608,9 +2608,11 @@ mark-style Japanese 일본식 Stop 중지 Searching… 검색 중… Not found 찾을 수 없음 - {folders} folder(s) and {files} file(s) searched 폴더 {folders}개, 파일 {files}개 검색함 - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones 다른 앱과 시스템 폴더, 숨김 폴더 등 {count}개 폴더 건너뜀 - {count} folder(s) or file(s) couldn't be read 폴더 또는 파일 {count}개를 읽을 수 없음 + {folders} and {files} searched {folders}, {files} 검색함 +@plural {n} folder|{n} folders 폴더 {n}개 +@plural {n} file|{n} files 파일 {n}개 +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones 다른 앱과 시스템 폴더, 숨김 폴더 등 {n}개 폴더 건너뜀 +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read 폴더 또는 파일 {n}개를 읽을 수 없음 The search stopped at its limit: search a smaller folder. 검색이 한도에서 중단됨: 더 작은 폴더를 검색하세요. Copy only fonts you own or are licensed to install. 소유했거나 설치 라이선스가 있는 글꼴만 복사하세요. VectorCraft copies the fonts to {folder}. VectorCraft가 글꼴을 {folder}에 복사합니다. @@ -3295,13 +3297,13 @@ mark-style Japanese 일본식 the preset 프리셋 tile {number} 타일 {number} to ~ - {count} file(s) in {folder} {note}. Show the package folder? {folder}에 파일 {count}개{note}. 패키지 폴더를 표시하시겠습니까? - {count} linked file(s) not found 연결된 파일 {count}개를 찾을 수 없습니다 +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder}에 파일 {n}개 {note}. 패키지 폴더를 표시하시겠습니까? +@plural {n} linked file not found|{n} linked files not found 연결된 파일 {n}개를 찾을 수 없습니다 fonts not copied: {fonts} 복사되지 않은 글꼴: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? 이 문서를 저장한 이후 연결된 이미지 {count}개가 변경되었습니다. 새 버전을 표시하시겠습니까? - {count} linked image(s) changed on disk. Show the new versions? 연결된 이미지 {count}개가 디스크에서 변경되었습니다. 새 버전을 표시하시겠습니까? - {count} more rules: Export writes every one. 규칙 {count}개 더 있음: 내보내기 시 모두 기록됩니다. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 이름 없는 개체 {count}개가 제외되었습니다. 이름을 지정하거나 패널 메뉴에서 이름 없는 개체를 켜십시오. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? 이 문서를 저장한 이후 연결된 이미지 {n}개가 변경되었습니다. 새 버전을 표시하시겠습니까? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 연결된 이미지 {n}개가 디스크에서 변경되었습니다. 새 버전을 표시하시겠습니까? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. 규칙 {n}개 더 있음: 내보내기 시 모두 기록됩니다. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 이름 없는 개체 {n}개가 제외되었습니다. 이름을 지정하거나 패널 메뉴에서 이름 없는 개체를 켜십시오. {effect} is already applied {effect}이(가) 이미 적용되어 있습니다 {format} Options {format} 옵션 {kind} Gradient {kind} 그레이디언트 @@ -3572,7 +3574,7 @@ file-filter Templates 템플릿 Output Black 출력 검정 Output White 출력 흰색 Output › Mode 출력 › 모드 - Packaged {n} file(s) in {folder} {note} {folder}에 파일 {n}개를 패키지했습니다{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {folder}에 파일 {n}개를 패키지했습니다 {note} Packaged {n} file(s){note} 파일 {n}개를 패키지했습니다{note} Page information 페이지 정보 Paragraph Style 단락 스타일 @@ -5172,10 +5174,10 @@ axis Y Axis Y축 @msg Packaged {n} file(s) in {folder} {folder}에 파일 {n}개를 패키지했습니다 @msg Packaged {n} file(s) {note} 파일 {n}개를 패키지했습니다 {note} @msg Packaged {n} file(s) 파일 {n}개를 패키지했습니다 - Packaged {n} file(s) 파일 {n}개를 패키지했습니다 - Packaged {n} file(s) in {folder} {folder}에 파일 {n}개를 패키지했습니다 - Packaged {n} file(s) {note} 파일 {n}개를 패키지했습니다 {note} - {count} file(s) in {folder}. Show the package folder? {folder}에 파일 {count}개. 패키지 폴더를 표시하시겠습니까? +@plural Packaged {n} file|Packaged {n} files 파일 {n}개를 패키지했습니다 +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {folder}에 파일 {n}개를 패키지했습니다 +@plural Packaged {n} file {note}|Packaged {n} files {note} 파일 {n}개를 패키지했습니다 {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {folder}에 파일 {n}개. 패키지 폴더를 표시하시겠습니까? Clockwise 시계 방향 Dither 디더 Fine noise hides banding in the gradient fill 미세한 노이즈로 그레이디언트 칠의 띠를 감춥니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 504ecae137..1a12b403ef 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -638,7 +638,7 @@ 1 Layer 1 laag Libraries Bibliotheken Links Koppelingen - {count} linked image(s) changed on disk. Show the new versions? {count} gekoppelde afbeelding(en) gewijzigd op de schijf. Nieuwe versies tonen? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} gekoppelde afbeelding gewijzigd op de schijf. Nieuwe versie tonen?|{n} gekoppelde afbeeldingen gewijzigd op de schijf. Nieuwe versies tonen? Update Changed Links Gewijzigde koppelingen bijwerken @msg Updated {_1} linked file(s) changed on disk Bijgewerkt: {_1} gekoppelde bestand(en) gewijzigd op de schijf Magic Wand Magische toverstaf @@ -1433,8 +1433,8 @@ lighting Light Licht Select objects to see their CSS, or Generate CSS for the whole document. Selecteer objecten om hun CSS te zien, of Genereer CSS voor het hele document. The selected objects have no CSS of their own (see below). De geselecteerde objecten hebben geen eigen CSS (zie hieronder). Units: {units} Eenheden: {units} - {count} more rules: Export writes every one. {count} regels meer: Export schrijft ze allemaal. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} naamloze objecten weggelaten: geef ze een naam, of zet Naamloze objecten aan in het paneelmenu. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regel meer: Export schrijft hem.|{n} regels meer: Export schrijft ze allemaal. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} naamloos object weggelaten: geef het een naam, of zet Naamloze objecten aan in het paneelmenu.|{n} naamloze objecten weggelaten: geef ze een naam, of zet Naamloze objecten aan in het paneelmenu. All Categories Alle categorieën Repeat Objects Herhalingsobjecten Save… Opslaan… @@ -2210,19 +2210,21 @@ lighting Light Licht Stop Stoppen Searching… Zoeken… Not found Niet gevonden - {folders} folder(s) and {files} file(s) searched {folders} map(pen) en {files} bestand(en) doorzocht - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} map(pen) overgeslagen, zoals mappen van andere apps, van het systeem en verborgen mappen - {count} folder(s) or file(s) couldn't be read {count} map(pen) of bestand(en) konden niet worden gelezen + {folders} and {files} searched {folders} en {files} doorzocht +@plural {n} folder|{n} folders {n} map|{n} mappen +@plural {n} file|{n} files {n} bestand|{n} bestanden +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} map overgeslagen, zoals mappen van andere apps, van het systeem en verborgen mappen|{n} mappen overgeslagen, zoals mappen van andere apps, van het systeem en verborgen mappen +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} map of bestand kon niet worden gelezen|{n} mappen of bestanden konden niet worden gelezen The search stopped at its limit: search a smaller folder. De zoekopdracht is gestopt bij de limiet: doorzoek een kleinere map. Copy only fonts you own or are licensed to install. Kopieer alleen lettertypen die je bezit of waarvoor je een licentie hebt om ze te installeren. VectorCraft copies the fonts to {folder}. VectorCraft kopieert de lettertypen naar {folder}. - Apply to All ({count} more missing) Op alles toepassen (er ontbreken nog {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Op alles toepassen (er ontbreekt nog {n})|Op alles toepassen (er ontbreken nog {n}) Ignore Negeren Linked File Not Found Gekoppeld bestand niet gevonden Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Vervang het door een ander bestand of negeer het: de afbeeldingen blijven de voorbeeldweergave tonen die met het document is opgeslagen. Replace… Vervangen… Update Modified Links Gewijzigde koppelingen bijwerken - {count} linked image(s) changed since this document was saved. Show the new versions? {count} gekoppelde afbeelding(en) zijn gewijzigd sinds dit document is opgeslagen. De nieuwe versies weergeven? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} gekoppelde afbeelding is gewijzigd sinds dit document is opgeslagen. De nieuwe versie weergeven?|{n} gekoppelde afbeeldingen zijn gewijzigd sinds dit document is opgeslagen. De nieuwe versies weergeven? Dialog Dialoogvenster Convert Process to Global Proces omzetten naar globaal Create From: Maken van: @@ -2261,12 +2263,12 @@ lighting Light Licht Fonts whose licence doesn't allow embedding are not copied. Lettertypen waarvan de licentie insluiten niet toestaat, worden niet gekopieerd. Package collects a saved document with its linked files and fonts. Verpakken verzamelt een opgeslagen document met zijn gekoppelde bestanden en lettertypen. Package created Pakket gemaakt - Packaged {n} file(s) in {folder} {note} {n} bestand(en) verpakt in {folder} {note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} bestand verpakt in {folder} {note}|{n} bestanden verpakt in {folder} {note} Packaged {n} file(s){note} {n} bestand(en) verpakt{note} Relink Linked Files to the Document Gekoppelde bestanden opnieuw koppelen aan het document Save the document first? Wil je het document eerst opslaan? - {count} file(s) in {folder} {note}. Show the package folder? {count} bestand(en) in {folder} {note}. De pakketmap openen? - {count} linked file(s) not found {count} gekoppelde bestand(en) niet gevonden +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} bestand in {folder} {note}. De pakketmap openen?|{n} bestanden in {folder} {note}. De pakketmap openen? +@plural {n} linked file not found|{n} linked files not found {n} gekoppeld bestand niet gevonden|{n} gekoppelde bestanden niet gevonden fonts not copied: {fonts} niet gekopieerde lettertypen: {fonts} Built-in presets are read-only: New… starts an editable copy. Ingebouwde voorinstellingen zijn alleen-lezen: Nieuw… start een bewerkbare kopie. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} op het tekenbord staat voor {real} {unit} in de scène. @@ -5564,10 +5566,10 @@ axis Y Axis Y-as @msg Packaged {n} file(s) in {folder} {n} bestand(en) verpakt in {folder} @msg Packaged {n} file(s) {note} {n} bestand(en) verpakt {note} @msg Packaged {n} file(s) {n} bestand(en) verpakt - Packaged {n} file(s) {n} bestand(en) verpakt - Packaged {n} file(s) in {folder} {n} bestand(en) verpakt in {folder} - Packaged {n} file(s) {note} {n} bestand(en) verpakt {note} - {count} file(s) in {folder}. Show the package folder? {count} bestand(en) in {folder}. De pakketmap openen? +@plural Packaged {n} file|Packaged {n} files {n} bestand verpakt|{n} bestanden verpakt +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} bestand verpakt in {folder}|{n} bestanden verpakt in {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} bestand verpakt {note}|{n} bestanden verpakt {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} bestand in {folder}. De pakketmap openen?|{n} bestanden in {folder}. De pakketmap openen? Clockwise Met de klok mee Dither Dither Fine noise hides banding in the gradient fill Fijne ruis verbergt banden in de verloopvulling diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index fffff07ae6..1113eddd45 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -620,7 +620,7 @@ Layers Warstwy Libraries Biblioteki Links Łącza - {count} linked image(s) changed on disk. Show the new versions? Połączone obrazy zmienione na dysku: {count}. Pokazać nowe wersje? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Połączone obrazy zmienione na dysku: {n}. Pokazać nowe wersje?|Połączone obrazy zmienione na dysku: {n}. Pokazać nowe wersje?|Połączone obrazy zmienione na dysku: {n}. Pokazać nowe wersje? Update Changed Links Aktualizuj zmienione łącza @msg Updated {_1} linked file(s) changed on disk Zaktualizowano połączone pliki zmienione na dysku: {_1} Magic Wand Różdżka @@ -1419,8 +1419,8 @@ lighting Light Światło Select objects to see their CSS, or Generate CSS for the whole document. Zaznacz obiekty, aby zobaczyć ich CSS, lub wygeneruj CSS całego dokumentu. The selected objects have no CSS of their own (see below). Zaznaczone obiekty nie mają własnego CSS (patrz niżej). Units: {units} Jednostki: {units} - {count} more rules: Export writes every one. Więcej reguł: {count}. Eksport zapisze wszystkie. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Pominięto obiekty bez nazwy: {count}. Nadaj im nazwy lub włącz Obiekty bez nazwy w menu panelu. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Więcej reguł: {n}. Eksport zapisze wszystkie.|Więcej reguł: {n}. Eksport zapisze wszystkie.|Więcej reguł: {n}. Eksport zapisze wszystkie. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Pominięto obiekty bez nazwy: {n}. Nadaj im nazwy lub włącz Obiekty bez nazwy w menu panelu.|Pominięto obiekty bez nazwy: {n}. Nadaj im nazwy lub włącz Obiekty bez nazwy w menu panelu.|Pominięto obiekty bez nazwy: {n}. Nadaj im nazwy lub włącz Obiekty bez nazwy w menu panelu. All Categories Wszystkie kategorie Repeat Objects Obiekty powtórzenia Save… Zapisz… @@ -2319,19 +2319,21 @@ lighting Light Światło Stop Zatrzymaj Searching… Wyszukiwanie… Not found Nie znaleziono - {folders} folder(s) and {files} file(s) searched Przeszukano foldery: {folders} i pliki: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Pominięte foldery: {count} — np. foldery innych aplikacji, systemowe i ukryte - {count} folder(s) or file(s) couldn't be read Nie udało się odczytać folderów lub plików: {count} + {folders} and {files} searched Przeszukano {folders} i {files} +@plural {n} folder|{n} folders {n} folder|{n} foldery|{n} folderów +@plural {n} file|{n} files {n} plik|{n} pliki|{n} plików +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Pominięte foldery: {n} — np. foldery innych aplikacji, systemowe i ukryte|Pominięte foldery: {n} — np. foldery innych aplikacji, systemowe i ukryte|Pominięte foldery: {n} — np. foldery innych aplikacji, systemowe i ukryte +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Nie udało się odczytać folderów lub plików: {n}|Nie udało się odczytać folderów lub plików: {n}|Nie udało się odczytać folderów lub plików: {n} The search stopped at its limit: search a smaller folder. Wyszukiwanie zatrzymało się na limicie: przeszukaj mniejszy folder. Copy only fonts you own or are licensed to install. Kopiuj tylko czcionki, które posiadasz lub masz licencję na ich instalację. VectorCraft copies the fonts to {folder}. VectorCraft kopiuje czcionki do {folder}. - Apply to All ({count} more missing) Zastosuj do wszystkich (brakuje jeszcze: {count}) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Zastosuj do wszystkich (brakuje jeszcze: {n})|Zastosuj do wszystkich (brakuje jeszcze: {n})|Zastosuj do wszystkich (brakuje jeszcze: {n}) Ignore Ignoruj Linked File Not Found Nie znaleziono połączonego pliku Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Zastąp go innym plikiem lub zignoruj: jego obrazy nadal będą pokazywać podgląd zapisany w dokumencie. Replace… Zastąp… Update Modified Links Aktualizuj zmodyfikowane łącza - {count} linked image(s) changed since this document was saved. Show the new versions? Połączone obrazy zmienione od zapisania dokumentu: {count}. Pokazać nowe wersje? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? Połączone obrazy zmienione od zapisania dokumentu: {n}. Pokazać nowe wersje?|Połączone obrazy zmienione od zapisania dokumentu: {n}. Pokazać nowe wersje?|Połączone obrazy zmienione od zapisania dokumentu: {n}. Pokazać nowe wersje? Dialog Okno dialogowe Convert Process to Global Konwertuj triadowe na globalne Create From: Utwórz z: @@ -2369,12 +2371,12 @@ lighting Light Światło Fonts whose licence doesn't allow embedding are not copied. Czcionki, których licencja nie zezwala na osadzanie, nie są kopiowane. Package collects a saved document with its linked files and fonts. Pakowanie zbiera zapisany dokument wraz z połączonymi plikami i czcionkami. Package created Utworzono pakiet - Packaged {n} file(s) in {folder} {note} Spakowane pliki: {n} w {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Spakowane pliki: {n} w {folder} {note}|Spakowane pliki: {n} w {folder} {note}|Spakowane pliki: {n} w {folder} {note} Packaged {n} file(s){note} Spakowane pliki: {n}{note} Relink Linked Files to the Document Połącz ponownie połączone pliki z dokumentem Save the document first? Najpierw zapisać dokument? - {count} file(s) in {folder} {note}. Show the package folder? Pliki: {count} w {folder}{note}. Pokazać folder pakietu? - {count} linked file(s) not found Nie znaleziono połączonych plików: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Pliki: {n} w {folder} {note}. Pokazać folder pakietu?|Pliki: {n} w {folder} {note}. Pokazać folder pakietu?|Pliki: {n} w {folder} {note}. Pokazać folder pakietu? +@plural {n} linked file not found|{n} linked files not found Nie znaleziono połączonych plików: {n}|Nie znaleziono połączonych plików: {n}|Nie znaleziono połączonych plików: {n} fonts not copied: {fonts} nieskopiowane czcionki: {fonts} Built-in presets are read-only: New… starts an editable copy. Wbudowane ustawienia są tylko do odczytu: Nowe… tworzy edytowalną kopię. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} na obszarze kompozycji odpowiada {real} {unit} w scenie. @@ -5448,10 +5450,10 @@ axis Y Axis Oś Y @msg Packaged {n} file(s) in {folder} Spakowane pliki: {n} w {folder} @msg Packaged {n} file(s) {note} Spakowane pliki: {n} {note} @msg Packaged {n} file(s) Spakowane pliki: {n} - Packaged {n} file(s) Spakowane pliki: {n} - Packaged {n} file(s) in {folder} Spakowane pliki: {n} w {folder} - Packaged {n} file(s) {note} Spakowane pliki: {n} {note} - {count} file(s) in {folder}. Show the package folder? Pliki: {count} w {folder}. Pokazać folder pakietu? +@plural Packaged {n} file|Packaged {n} files Spakowane pliki: {n}|Spakowane pliki: {n}|Spakowane pliki: {n} +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Spakowane pliki: {n} w {folder}|Spakowane pliki: {n} w {folder}|Spakowane pliki: {n} w {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Spakowane pliki: {n} {note}|Spakowane pliki: {n} {note}|Spakowane pliki: {n} {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? Pliki: {n} w {folder}. Pokazać folder pakietu?|Pliki: {n} w {folder}. Pokazać folder pakietu?|Pliki: {n} w {folder}. Pokazać folder pakietu? Clockwise Zgodnie z ruchem wskazówek zegara Dither Rozpraszanie Fine noise hides banding in the gradient fill Drobny szum ukrywa pasy w wypełnieniu gradientem diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index aab46d1911..129533e078 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -212,7 +212,7 @@ Apply Paragraph Style Aplicar Estilo de Parágrafo Apply SVG Filter… Aplicar Filtro SVG… Apply to All Aplicar a Todos - Apply to All ({count} more missing) Aplicar a Todos ({count} mais faltando) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Aplicar a Todos ({n} mais faltando)|Aplicar a Todos ({n} mais faltando) Arc Arco Arc Lower… Arco Inferior… Arc Tool Ferramenta Arco @@ -2144,9 +2144,11 @@ Stop Parar Searching… Pesquisando… Not found Não encontrado - {folders} folder(s) and {files} file(s) searched {folders} pasta(s) e {files} arquivo(s) pesquisados - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} pasta(s) ignorada(s), como as de outros aplicativos e do sistema e as ocultas - {count} folder(s) or file(s) couldn't be read {count} pasta(s) ou arquivo(s) não puderam ser lidos + {folders} and {files} searched {folders} e {files} pesquisados +@plural {n} folder|{n} folders {n} pasta|{n} pastas +@plural {n} file|{n} files {n} arquivo|{n} arquivos +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} pasta ignorada, como as de outros aplicativos e do sistema e as ocultas|{n} pastas ignoradas, como as de outros aplicativos e do sistema e as ocultas +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} pasta ou arquivo não pôde ser lido|{n} pastas ou arquivos não puderam ser lidos The search stopped at its limit: search a smaller folder. A pesquisa parou no limite: pesquise uma pasta menor. Copy only fonts you own or are licensed to install. Copie apenas fontes que sejam suas ou que você tenha licença para instalar. VectorCraft copies the fonts to {folder}. O VectorCraft copia as fontes para {folder}. @@ -2866,7 +2868,7 @@ Update Link Atualizar Link Update Links Atualizar Links Update Changed Links Atualizar Links alterados - {count} linked image(s) changed on disk. Show the new versions? {count} imagem(ns) vinculada(s) alterada(s) no disco. Mostrar as novas versões? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} imagem vinculada alterada no disco. Mostrar a nova versão?|{n} imagens vinculadas alteradas no disco. Mostrar as novas versões? @msg Updated {_1} linked file(s) changed on disk {_1} arquivo(s) vinculado(s) alterado(s) no disco atualizado(s) Update Modified Links Atualizar Links Modificados Use Use @@ -3015,12 +3017,12 @@ the preset o predefinido tile {number} bloco {number} to para - {count} file(s) in {folder} {note}. Show the package folder? {count} arquivo(s) em {folder}{note}. Mostrar a pasta do pacote? - {count} linked file(s) not found {count} arquivo(s) vinculado(s) não encontrado(s) +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} arquivo em {folder} {note}. Mostrar a pasta do pacote?|{n} arquivos em {folder} {note}. Mostrar a pasta do pacote? +@plural {n} linked file not found|{n} linked files not found {n} arquivo vinculado não encontrado|{n} arquivos vinculados não encontrados fonts not copied: {fonts} fontes não copiadas: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} imagem(ns) vinculada(s) alterada(s) desde que este documento foi salvo. Mostrar as novas versões? - {count} more rules: Export writes every one. {count} regras a mais: a Exportação escreve cada uma. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} objetos sem nome deixados de fora: nomeie-os, ou ative Objetos Sem Nome no menu do painel. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} imagem vinculada alterada desde que este documento foi salvo. Mostrar a nova versão?|{n} imagens vinculadas alteradas desde que este documento foi salvo. Mostrar as novas versões? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regra a mais: a Exportação a escreve.|{n} regras a mais: a Exportação escreve cada uma. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} objeto sem nome deixado de fora: nomeie-o, ou ative Objetos Sem Nome no menu do painel.|{n} objetos sem nome deixados de fora: nomeie-os, ou ative Objetos Sem Nome no menu do painel. {effect} is already applied {effect} já está aplicado {format} Options Opções de {format} {kind} Gradient Gradiente de {kind} @@ -4588,7 +4590,7 @@ axis Both Ambos Output Black Preto de Saída Output White Branco de Saída Output › Mode Saída › Modo - Packaged {n} file(s) in {folder} {note} {n} arquivo(s) empacotado(s) em {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} arquivo empacotado em {folder} {note}|{n} arquivos empacotados em {folder} {note} Packaged {n} file(s){note} {n} arquivo(s) empacotado(s){note} Page information Informações da página Paragraph Style Estilo de Parágrafo @@ -5511,10 +5513,10 @@ axis Y Axis Eixo Y @msg Packaged {n} file(s) in {folder} {n} arquivo(s) empacotado(s) em {folder} @msg Packaged {n} file(s) {note} {n} arquivo(s) empacotado(s) {note} @msg Packaged {n} file(s) {n} arquivo(s) empacotado(s) - Packaged {n} file(s) {n} arquivo(s) empacotado(s) - Packaged {n} file(s) in {folder} {n} arquivo(s) empacotado(s) em {folder} - Packaged {n} file(s) {note} {n} arquivo(s) empacotado(s) {note} - {count} file(s) in {folder}. Show the package folder? {count} arquivo(s) em {folder}. Mostrar a pasta do pacote? +@plural Packaged {n} file|Packaged {n} files {n} arquivo empacotado|{n} arquivos empacotados +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} arquivo empacotado em {folder}|{n} arquivos empacotados em {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} arquivo empacotado {note}|{n} arquivos empacotados {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} arquivo em {folder}. Mostrar a pasta do pacote?|{n} arquivos em {folder}. Mostrar a pasta do pacote? Clockwise Sentido horário Dither Dither Fine noise hides banding in the gradient fill Um ruído fino esconde as faixas do preenchimento em gradiente diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a516437a62..a735dbb079 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -215,7 +215,7 @@ font-technology Variable Вариативные Apply Paragraph Style Применить стиль абзаца Apply SVG Filter… Применить фильтр SVG… Apply to All Применить ко всем - Apply to All ({count} more missing) Применить ко всем (ещё {count} отсутствуют) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Применить ко всем (ещё {n} отсутствует)|Применить ко всем (ещё {n} отсутствуют)|Применить ко всем (ещё {n} отсутствуют) Arc Дуга Arc Lower… Дуга снизу… Arc Tool Инструмент «Дуга» @@ -2295,7 +2295,7 @@ file-filter Templates Шаблоны Package Упаковать Package collects a saved document with its linked files and fonts. Упаковка собирает сохранённый документ с его связанными файлами и шрифтами. Package created Пакет создан - Packaged {n} file(s) in {folder} {note} Упаковано файлов: {n} в {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Упаковано файлов: {n} в {folder} {note}|Упаковано файлов: {n} в {folder} {note}|Упаковано файлов: {n} в {folder} {note} Packaged {n} file(s){note} Упаковано файлов: {n}{note} Package… Упаковать… Page Страница @@ -2619,9 +2619,11 @@ mark-style Japanese Японский Stop Остановить Searching… Поиск… Not found Не найдено - {folders} folder(s) and {files} file(s) searched Просмотрено папок: {folders}, файлов: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Пропущено папок: {count}, например папки других приложений и системы и скрытые папки - {count} folder(s) or file(s) couldn't be read Не удалось прочитать папок или файлов: {count} + {folders} and {files} searched Просмотрено: {folders}, {files} +@plural {n} folder|{n} folders {n} папка|{n} папки|{n} папок +@plural {n} file|{n} files {n} файл|{n} файла|{n} файлов +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Пропущено папок: {n}, например папки других приложений и системы и скрытые папки|Пропущено папок: {n}, например папки других приложений и системы и скрытые папки|Пропущено папок: {n}, например папки других приложений и системы и скрытые папки +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Не удалось прочитать папок или файлов: {n}|Не удалось прочитать папок или файлов: {n}|Не удалось прочитать папок или файлов: {n} The search stopped at its limit: search a smaller folder. Поиск остановился на пределе: выберите папку поменьше. Copy only fonts you own or are licensed to install. Копируйте только шрифты, которые принадлежат вам или которые вы вправе устанавливать по лицензии. VectorCraft copies the fonts to {folder}. VectorCraft копирует шрифты в {folder}. @@ -3707,13 +3709,13 @@ mark-style Japanese Японский Zoom Tool Инструмент «Масштаб» Zoom with Mouse Wheel Масштабировать колесом мыши Scrub Numeric Fields by Dragging Изменять числовые поля перетаскиванием - {count} file(s) in {folder} {note}. Show the package folder? Файлов: {count} в {folder}{note}. Показать папку пакета? - {count} linked file(s) not found Не найдено связанных файлов: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Файлов: {n} в {folder} {note}. Показать папку пакета?|Файлов: {n} в {folder} {note}. Показать папку пакета?|Файлов: {n} в {folder} {note}. Показать папку пакета? +@plural {n} linked file not found|{n} linked files not found Не найдено связанных файлов: {n}|Не найдено связанных файлов: {n}|Не найдено связанных файлов: {n} fonts not copied: {fonts} шрифты не скопированы: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? Связанных изображений ({count}) изменились с момента сохранения этого документа. Показать новые версии? - {count} linked image(s) changed on disk. Show the new versions? Связанных изображений ({count}) изменились на диске. Показать новые версии? - {count} more rules: Export writes every one. Ещё правил: {count}: экспорт записывает все. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Пропущено объектов без имени: {count}: назовите их или включите «Объекты без имени» в меню панели. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} связанное изображение изменилось с момента сохранения этого документа. Показать новую версию?|{n} связанных изображения изменились с момента сохранения этого документа. Показать новые версии?|{n} связанных изображений изменились с момента сохранения этого документа. Показать новые версии? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} связанное изображение изменилось на диске. Показать новую версию?|{n} связанных изображения изменились на диске. Показать новые версии?|{n} связанных изображений изменились на диске. Показать новые версии? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Ещё правил: {n}: экспорт записывает все.|Ещё правил: {n}: экспорт записывает все.|Ещё правил: {n}: экспорт записывает все. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Пропущено объектов без имени: {n}: назовите их или включите «Объекты без имени» в меню панели.|Пропущено объектов без имени: {n}: назовите их или включите «Объекты без имени» в меню панели.|Пропущено объектов без имени: {n}: назовите их или включите «Объекты без имени» в меню панели. {effect} is already applied {effect} уже применён {format} Options Параметры {format} {kind} Gradient Градиент {kind} @@ -5205,10 +5207,10 @@ axis Y Axis Ось Y @msg Packaged {n} file(s) in {folder} Упаковано файлов: {n} в {folder} @msg Packaged {n} file(s) {note} Упаковано файлов: {n} {note} @msg Packaged {n} file(s) Упаковано файлов: {n} - Packaged {n} file(s) Упаковано файлов: {n} - Packaged {n} file(s) in {folder} Упаковано файлов: {n} в {folder} - Packaged {n} file(s) {note} Упаковано файлов: {n} {note} - {count} file(s) in {folder}. Show the package folder? Файлов: {count} в {folder}. Показать папку пакета? +@plural Packaged {n} file|Packaged {n} files Упаковано файлов: {n}|Упаковано файлов: {n}|Упаковано файлов: {n} +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Упаковано файлов: {n} в {folder}|Упаковано файлов: {n} в {folder}|Упаковано файлов: {n} в {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Упаковано файлов: {n} {note}|Упаковано файлов: {n} {note}|Упаковано файлов: {n} {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? Файлов: {n} в {folder}. Показать папку пакета?|Файлов: {n} в {folder}. Показать папку пакета?|Файлов: {n} в {folder}. Показать папку пакета? Clockwise По часовой стрелке Dither Дизеринг Fine noise hides banding in the gradient fill Мелкий шум скрывает полосы в градиентной заливке diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index a98780bcf2..20d412a5ec 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -205,7 +205,7 @@ font-technology Variable Variabla Apply Paragraph Style Använd styckestil Apply SVG Filter… Använd SVG-filter… Apply to All Använd på alla - Apply to All ({count} more missing) Använd på alla ({count} till saknas) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Använd på alla ({n} till saknas)|Använd på alla ({n} till saknas) Arc Båge Arc Lower… Nedre båge… Arc Tool Bågverktyg @@ -2217,7 +2217,7 @@ font-technology Variable Variabla Package Paketera Package collects a saved document with its linked files and fonts. Paketera samlar ett sparat dokument med dess länkade filer och typsnitt. Package created Paketet har skapats - Packaged {n} file(s) in {folder} {note} Paketerade {n} fil(er) i {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Paketerade {n} fil i {folder} {note}|Paketerade {n} filer i {folder} {note} Packaged {n} file(s){note} Paketerade {n} fil(er){note} Package… Paketera… Page Sida @@ -2534,9 +2534,11 @@ font-technology Variable Variabla Stop Stoppa Searching… Söker… Not found Hittades inte - {folders} folder(s) and {files} file(s) searched {folders} mapp(ar) och {files} fil(er) genomsökta - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} mapp(ar) överhoppade, t.ex. andra appars och systemets mappar samt dolda mappar - {count} folder(s) or file(s) couldn't be read {count} mapp(ar) eller fil(er) kunde inte läsas + {folders} and {files} searched {folders} och {files} genomsökta +@plural {n} folder|{n} folders {n} mapp|{n} mappar +@plural {n} file|{n} files {n} fil|{n} filer +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} mapp överhoppad, t.ex. andra appars och systemets mappar samt dolda mappar|{n} mappar överhoppade, t.ex. andra appars och systemets mappar samt dolda mappar +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} mapp eller fil kunde inte läsas|{n} mappar eller filer kunde inte läsas The search stopped at its limit: search a smaller folder. Sökningen stoppades vid sin gräns: sök i en mindre mapp. Copy only fonts you own or are licensed to install. Kopiera bara typsnitt som du äger eller har licens att installera. VectorCraft copies the fonts to {folder}. VectorCraft kopierar typsnitten till {folder}. @@ -3604,13 +3606,13 @@ font-technology Variable Variabla Zoom Tool Zoomverktyg Zoom with Mouse Wheel Zooma med mushjulet Scrub Numeric Fields by Dragging Ändra numeriska fält genom att dra - {count} file(s) in {folder} {note}. Show the package folder? {count} fil(er) i {folder}{note}. Visa paketmappen? - {count} linked file(s) not found {count} länkad(e) fil(er) hittades inte +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fil i {folder} {note}. Visa paketmappen?|{n} filer i {folder} {note}. Visa paketmappen? +@plural {n} linked file not found|{n} linked files not found {n} länkad fil hittades inte|{n} länkade filer hittades inte fonts not copied: {fonts} typsnitt som inte kopierats: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} länkad(e) bild(er) har ändrats sedan dokumentet sparades. Visa de nya versionerna? - {count} linked image(s) changed on disk. Show the new versions? {count} länkad(e) bild(er) har ändrats på disken. Visa de nya versionerna? - {count} more rules: Export writes every one. {count} regler till: Exportera skriver alla. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} namnlösa objekt utelämnade: namnge dem eller aktivera Namnlösa objekt i panelmenyn. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} länkad bild har ändrats sedan dokumentet sparades. Visa den nya versionen?|{n} länkade bilder har ändrats sedan dokumentet sparades. Visa de nya versionerna? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} länkad bild har ändrats på disken. Visa den nya versionen?|{n} länkade bilder har ändrats på disken. Visa de nya versionerna? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regel till: Exportera skriver den.|{n} regler till: Exportera skriver alla. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} namnlöst objekt utelämnat: namnge det eller aktivera Namnlösa objekt i panelmenyn.|{n} namnlösa objekt utelämnade: namnge dem eller aktivera Namnlösa objekt i panelmenyn. {effect} is already applied {effect} används redan {format} Options {format}-alternativ {kind} Gradient {kind} gradient @@ -5618,10 +5620,10 @@ axis Y Axis Y-axel @msg Packaged {n} file(s) in {folder} Paketerade {n} fil(er) i {folder} @msg Packaged {n} file(s) {note} Paketerade {n} fil(er) {note} @msg Packaged {n} file(s) Paketerade {n} fil(er) - Packaged {n} file(s) Paketerade {n} fil(er) - Packaged {n} file(s) in {folder} Paketerade {n} fil(er) i {folder} - Packaged {n} file(s) {note} Paketerade {n} fil(er) {note} - {count} file(s) in {folder}. Show the package folder? {count} fil(er) i {folder}. Visa paketmappen? +@plural Packaged {n} file|Packaged {n} files Paketerade {n} fil|Paketerade {n} filer +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Paketerade {n} fil i {folder}|Paketerade {n} filer i {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Paketerade {n} fil {note}|Paketerade {n} filer {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fil i {folder}. Visa paketmappen?|{n} filer i {folder}. Visa paketmappen? Clockwise Medurs Dither Dithering Fine noise hides banding in the gradient fill Fint brus döljer bandningen i gradientfyllningen diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 4d543f0270..ce569f47b5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -202,7 +202,7 @@ font-technology Variable Değişken Apply Paragraph Style Paragraf Stilini Uygula Apply SVG Filter… SVG Filtresini Uygula… Apply to All Tümüne Uygula - Apply to All ({count} more missing) Tümüne Uygula ({count} daha eksik) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Tümüne Uygula ({n} daha eksik) Arc Yay Arc Lower… Ark Alt… Arc Tool Yay Aracı @@ -2095,7 +2095,7 @@ shape Open Açık Package Paket Package collects a saved document with its linked files and fonts. Paket, kayıtlı bir belgeyi bağlantılı dosyaları ve yazı tipleriyle birlikte toplar. Package created Paket oluşturuldu - Packaged {n} file(s) in {folder} {note} {folder}{note} biçiminde paketlenmiş {n} dosyası/dosyaları +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} {n} dosya {folder} klasörüne paketlendi {note} Packaged {n} file(s){note} Paketlenmiş {n} dosyası/dosyaları{note} Package… Paket… Page Sayfa @@ -2411,9 +2411,11 @@ shape Open Açık Stop Durdur Searching… Aranıyor… Not found Bulunamadı - {folders} folder(s) and {files} file(s) searched {folders} klasör(ler)i ve {files} dosya(lar)ı arandı - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Diğer uygulamaların ve sistemin klasörleri ve gizli klasörleri gibi {count} klasörleri atlandı - {count} folder(s) or file(s) couldn't be read {count} klasör(ler)i veya dosya(lar) okunamadı + {folders} and {files} searched {folders} ve {files} arandı +@plural {n} folder|{n} folders {n} klasör +@plural {n} file|{n} files {n} dosya +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Diğer uygulamaların ve sistemin klasörleri ve gizli klasörler gibi {n} klasör atlandı +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} klasör veya dosya okunamadı The search stopped at its limit: search a smaller folder. Arama sınırda durdu: daha küçük bir klasörde arama yapın. Copy only fonts you own or are licensed to install. Yalnızca sahip olduğunuz veya yükleme lisansına sahip olduğunuz yazı tiplerini kopyalayın. VectorCraft copies the fonts to {folder}. VectorCraft yazı tiplerini {folder}'ye kopyalar. @@ -3498,13 +3500,13 @@ shape Open Açık Zoom Tool Yakınlaştırma Aracı Zoom with Mouse Wheel Fare Tekerleği ile Yakınlaştırma Scrub Numeric Fields by Dragging Sayısal Alanları Sürükleyerek Fırçalayın - {count} file(s) in {folder} {note}. Show the package folder? {folder}{note} içindeki {count} dosyası/dosyaları. Paket klasörü gösterilsin mi? - {count} linked file(s) not found {count} bağlantılı dosya(lar) bulunamadı +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} içinde {n} dosya {note}. Paket klasörü gösterilsin mi? +@plural {n} linked file not found|{n} linked files not found {n} bağlantılı dosya bulunamadı fonts not copied: {fonts} kopyalanmayan yazı tipleri: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} bağlantılı görseller bu belgenin kaydedilmesinden bu yana değiştirildi. Yeni sürümler gösterilsin mi? - {count} linked image(s) changed on disk. Show the new versions? {count} bağlantılı görseller diskte değiştirildi. Yeni sürümler gösterilsin mi? - {count} more rules: Export writes every one. {count} daha fazla kural: Dışa aktarma her birini yazar. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} adsız nesneler dışarıda bırakıldı: bunlara ad verin veya panel menüsünde Adsız Nesneler'i açın. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} bağlantılı görsel bu belgenin kaydedilmesinden bu yana değiştirildi. Yeni sürümler gösterilsin mi? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} bağlantılı görsel diskte değiştirildi. Yeni sürümler gösterilsin mi? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} kural daha: Dışa aktarma her birini yazar. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} adsız nesne dışarıda bırakıldı: bunlara ad verin veya panel menüsünde Adsız Nesneler'i açın. {effect} is already applied {effect} zaten uygulandı {format} Options {format} Seçenekleri {kind} Gradient {kind} Degrade @@ -5548,10 +5550,10 @@ axis Y Axis Y ekseni Drop Artwork Çizimi Bırak @msg {key} must be [x, y] with finite coordinates {key}, sonlu koordinatlı [x, y] olmalı @msg ids must contain 1–10000 object ids ids 1–10000 nesne kimliği içermeli - Packaged {n} file(s) Paketlenmiş {n} dosyası/dosyaları - Packaged {n} file(s) in {folder} {folder} biçiminde paketlenmiş {n} dosyası/dosyaları - Packaged {n} file(s) {note} Paketlenmiş {n} dosyası/dosyaları {note} - {count} file(s) in {folder}. Show the package folder? {folder} içindeki {count} dosyası/dosyaları. Paket klasörü gösterilsin mi? +@plural Packaged {n} file|Packaged {n} files {n} dosya paketlendi +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} dosya {folder} klasörüne paketlendi +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} dosya paketlendi {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {folder} içinde {n} dosya. Paket klasörü gösterilsin mi? Clockwise Saat yönünde Dither Titreme Fine noise hides banding in the gradient fill İnce gürültü, degrade dolgudaki bantları gizler diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 6942907990..dc4d1c4775 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -211,7 +211,7 @@ font-technology Variable Варіативні Apply Paragraph Style Застосувати стиль абзацу Apply SVG Filter… Застосувати фільтр SVG… Apply to All Застосувати до всіх - Apply to All ({count} more missing) Застосувати до всіх (ще {count} відсутні) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Застосувати до всіх (ще {n} відсутній)|Застосувати до всіх (ще {n} відсутні)|Застосувати до всіх (ще {n} відсутні) Arc Дуга Arc Lower… Дуга знизу… Arc Tool Інструмент «Дуга» @@ -2291,7 +2291,7 @@ file-filter Templates Шаблони Package Упакувати Package collects a saved document with its linked files and fonts. Упаковка збирає збережений документ із його пов’язаними файлами та шрифтами. Package created Пакет створено - Packaged {n} file(s) in {folder} {note} Упаковано файли: {n} {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Упаковано файли: {n} {folder} {note}|Упаковано файли: {n} {folder} {note}|Упаковано файли: {n} {folder} {note} Packaged {n} file(s){note} Упаковано файли: {n}{note} Package… Упакувати… Page Сторінка @@ -2615,9 +2615,11 @@ mark-style Japanese Японський Stop Зупинити Searching… Пошук… Not found Не знайдено - {folders} folder(s) and {files} file(s) searched Переглянуто папок: {folders}, файлів: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Пропущено папок: {count}, зокрема папки інших програм і системи та приховані папки - {count} folder(s) or file(s) couldn't be read Не вдалося прочитати папок або файлів: {count} + {folders} and {files} searched Переглянуто: {folders}, {files} +@plural {n} folder|{n} folders {n} папка|{n} папки|{n} папок +@plural {n} file|{n} files {n} файл|{n} файли|{n} файлів +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Пропущено папок: {n}, зокрема папки інших програм і системи та приховані папки|Пропущено папок: {n}, зокрема папки інших програм і системи та приховані папки|Пропущено папок: {n}, зокрема папки інших програм і системи та приховані папки +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Не вдалося прочитати папок або файлів: {n}|Не вдалося прочитати папок або файлів: {n}|Не вдалося прочитати папок або файлів: {n} The search stopped at its limit: search a smaller folder. Пошук зупинився на межі: виберіть меншу папку. Copy only fonts you own or are licensed to install. Копіюйте лише шрифти, які належать вам або які ви маєте право встановлювати за ліцензією. VectorCraft copies the fonts to {folder}. VectorCraft копіює шрифти в {folder}. @@ -3704,13 +3706,13 @@ effect Points Точки Zoom Tool Інструмент «Масштаб» Zoom with Mouse Wheel Масштабувати колесом миші Scrub Numeric Fields by Dragging Змінювати числові поля перетягуванням - {count} file(s) in {folder} {note}. Show the package folder? файлів: {count} {folder}{note}. Показати папку пакета? - {count} linked file(s) not found не знайдено пов’язаних файлів: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? файлів: {n} {folder} {note}. Показати папку пакета?|файлів: {n} {folder} {note}. Показати папку пакета?|файлів: {n} {folder} {note}. Показати папку пакета? +@plural {n} linked file not found|{n} linked files not found не знайдено пов’язаних файлів: {n}|не знайдено пов’язаних файлів: {n}|не знайдено пов’язаних файлів: {n} fonts not copied: {fonts} шрифти не скопійовано: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? пов’язані зображення ({count}) змінилися з моменту збереження цього документа. Показати нові версії? - {count} linked image(s) changed on disk. Show the new versions? пов’язані зображення ({count}) змінилися на диску. Показати нові версії? - {count} more rules: Export writes every one. ще правил: {count}: експорт записує все. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. пропущено об’єкти без імені: {count}: назвіть їх або увімкніть «Об’єкти без імені» у меню панелі. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? пов’язані зображення ({n}) змінилися з моменту збереження цього документа. Показати нові версії?|пов’язані зображення ({n}) змінилися з моменту збереження цього документа. Показати нові версії?|пов’язані зображення ({n}) змінилися з моменту збереження цього документа. Показати нові версії? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? пов’язані зображення ({n}) змінилися на диску. Показати нові версії?|пов’язані зображення ({n}) змінилися на диску. Показати нові версії?|пов’язані зображення ({n}) змінилися на диску. Показати нові версії? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. ще правил: {n}: експорт записує все.|ще правил: {n}: експорт записує все.|ще правил: {n}: експорт записує все. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. пропущено об’єкти без імені: {n}: назвіть їх або увімкніть «Об’єкти без імені» у меню панелі.|пропущено об’єкти без імені: {n}: назвіть їх або увімкніть «Об’єкти без імені» у меню панелі.|пропущено об’єкти без імені: {n}: назвіть їх або увімкніть «Об’єкти без імені» у меню панелі. {effect} is already applied {effect} вже застосований {format} Options параметри {format} {kind} Gradient градієнт {kind} @@ -5189,10 +5191,10 @@ axis Y Axis Вісь Y @msg Packaged {n} file(s) in {folder} Упаковано файли: {n} {folder} @msg Packaged {n} file(s) {note} Упаковано файли: {n} {note} @msg Packaged {n} file(s) Упаковано файли: {n} - Packaged {n} file(s) Упаковано файли: {n} - Packaged {n} file(s) in {folder} Упаковано файли: {n} {folder} - Packaged {n} file(s) {note} Упаковано файли: {n} {note} - {count} file(s) in {folder}. Show the package folder? файлів: {count} {folder}. Показати папку пакета? +@plural Packaged {n} file|Packaged {n} files Упаковано файли: {n}|Упаковано файли: {n}|Упаковано файли: {n} +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Упаковано файли: {n} {folder}|Упаковано файли: {n} {folder}|Упаковано файли: {n} {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Упаковано файли: {n} {note}|Упаковано файли: {n} {note}|Упаковано файли: {n} {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? файлів: {n} {folder}. Показати папку пакета?|файлів: {n} {folder}. Показати папку пакета?|файлів: {n} {folder}. Показати папку пакета? Clockwise За годинниковою стрілкою Dither Дизеринг Fine noise hides banding in the gradient fill Дрібний шум приховує смуги в градієнтній заливці diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1c3c493879..90cc10d9a5 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -235,7 +235,7 @@ font-technology Variable Biến thiên Apply Paragraph Style Áp dụng kiểu đoạn văn Apply SVG Filter… Áp dụng bộ lọc SVG… Apply to All Áp dụng cho tất cả - Apply to All ({count} more missing) Áp dụng cho tất cả ({count} còn thiếu) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Áp dụng cho tất cả ({n} còn thiếu) Approximate path Đường dẫn xấp xỉ Arabic Ả Rập Arc Cung @@ -2562,7 +2562,7 @@ file-filter Templates Mẫu Package Gói Package collects a saved document with its linked files and fonts. Gói thu thập tài liệu đã lưu cùng tệp liên kết và phông chữ. Package created Đã tạo gói - Packaged {n} file(s) in {folder} {note} Đã đóng gói {n} tệp trong {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} Đã đóng gói {n} tệp trong {folder} {note} Packaged {n} file(s){note} Đã đóng gói {n} tệp{note} Package… Gói… Page Trang @@ -4067,16 +4067,18 @@ mark-style Japanese Kiểu Nhật Zoom to Selection Thu phóng đến vùng chọn Zoom Tool Công cụ thu phóng Zoom with Mouse Wheel Thu phóng bằng con lăn chuột - {count} file(s) in {folder} {note}. Show the package folder? {count} tệp trong {folder}{note}. Hiện thư mục gói? - {count} folder(s) or file(s) couldn't be read {count} thư mục hoặc tệp không thể đọc được - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Đã bỏ qua {count} thư mục, chẳng hạn thư mục của ứng dụng khác, thư mục hệ thống và thư mục ẩn - {count} linked file(s) not found Không tìm thấy {count} tệp liên kết - {count} linked image(s) changed on disk. Show the new versions? {count} ảnh liên kết đã thay đổi trên đĩa. Hiện phiên bản mới? - {count} linked image(s) changed since this document was saved. Show the new versions? {count} ảnh liên kết đã thay đổi kể từ khi lưu tài liệu. Hiện phiên bản mới? - {count} more rules: Export writes every one. Còn {count} quy tắc nữa: Xuất sẽ ghi tất cả. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} đối tượng chưa đặt tên bị bỏ qua: hãy đặt tên hoặc bật Đối tượng chưa đặt tên trong menu bảng. +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} tệp trong {folder} {note}. Hiện thư mục gói? +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} thư mục hoặc tệp không thể đọc được +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Đã bỏ qua {n} thư mục, chẳng hạn thư mục của ứng dụng khác, thư mục hệ thống và thư mục ẩn +@plural {n} linked file not found|{n} linked files not found Không tìm thấy {n} tệp liên kết +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} ảnh liên kết đã thay đổi trên đĩa. Hiện phiên bản mới? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} ảnh liên kết đã thay đổi kể từ khi lưu tài liệu. Hiện phiên bản mới? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Còn {n} quy tắc nữa: Xuất sẽ ghi tất cả. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} đối tượng chưa đặt tên bị bỏ qua: hãy đặt tên hoặc bật Đối tượng chưa đặt tên trong menu bảng. {effect} is already applied {effect} đã được áp dụng - {folders} folder(s) and {files} file(s) searched Đã tìm kiếm {folders} thư mục và {files} tệp + {folders} and {files} searched Đã tìm kiếm {folders} và {files} +@plural {n} folder|{n} folders {n} thư mục +@plural {n} file|{n} files {n} tệp {format} Options Tùy chọn {format} {kind} Gradient Chuyển sắc {kind} gradient-kind Radial Hướng tâm @@ -5191,10 +5193,10 @@ axis Y Axis Trục Y @msg Packaged {n} file(s) in {folder} Đã đóng gói {n} tệp trong {folder} @msg Packaged {n} file(s) {note} Đã đóng gói {n} tệp {note} @msg Packaged {n} file(s) Đã đóng gói {n} tệp - Packaged {n} file(s) Đã đóng gói {n} tệp - Packaged {n} file(s) in {folder} Đã đóng gói {n} tệp trong {folder} - Packaged {n} file(s) {note} Đã đóng gói {n} tệp {note} - {count} file(s) in {folder}. Show the package folder? {count} tệp trong {folder}. Hiện thư mục gói? +@plural Packaged {n} file|Packaged {n} files Đã đóng gói {n} tệp +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Đã đóng gói {n} tệp trong {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Đã đóng gói {n} tệp {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} tệp trong {folder}. Hiện thư mục gói? Clockwise Theo chiều kim đồng hồ Dither Dither Fine noise hides banding in the gradient fill Nhiễu mịn che dải màu trong vùng tô chuyển sắc diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a85bc1a63a..7c930a444f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -162,7 +162,7 @@ Apply Paragraph Style 应用段落样式 Apply SVG Filter… 应用 SVG 滤镜… Apply to All 应用到全部 - Apply to All ({count} more missing) 全部应用 (另有 {count} 个缺失) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) 全部应用 (另有 {n} 个缺失) Arc 弧形 Arc Lower… 下弧形… Arc Tool 弧形工具 @@ -2169,7 +2169,7 @@ file-filter Templates 模板 Package 打包 Package collects a saved document with its linked files and fonts. 打包会将已存储的文件连同其链接文件与字体一并收集。 Package created 已创建打包 - Packaged {n} file(s) in {folder} {note} 已将 {n} 个文件打包于 {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} 已将 {n} 个文件打包于 {folder}{note} Packaged {n} file(s){note} 已打包 {n} 个文件{note} Package… 打包… Page 页面 @@ -2494,9 +2494,11 @@ font-script Japanese 汉字 Stop 停止 Searching… 正在搜索… Not found 未找到 - {folders} folder(s) and {files} file(s) searched 已搜索 {folders} 个文件夹、{files} 个文件 - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones 已跳过 {count} 个文件夹,例如其他应用程序和系统的文件夹,以及隐藏的文件夹 - {count} folder(s) or file(s) couldn't be read 有 {count} 个文件夹或文件无法读取 + {folders} and {files} searched 已搜索 {folders}、{files} +@plural {n} folder|{n} folders {n} 个文件夹 +@plural {n} file|{n} files {n} 个文件 +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones 已跳过 {n} 个文件夹,例如其他应用程序和系统的文件夹,以及隐藏的文件夹 +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read 有 {n} 个文件夹或文件无法读取 The search stopped at its limit: search a smaller folder. 搜索已达上限而停止:请搜索较小的文件夹。 Copy only fonts you own or are licensed to install. 只复制您拥有或已获得安装许可的字体。 VectorCraft copies the fonts to {folder}. VectorCraft 会将字体复制到 {folder}。 @@ -3377,7 +3379,7 @@ font-script Japanese 汉字 Update Link 更新链接 Update Links 更新链接 Update Changed Links 更新已更改的链接 - {count} linked image(s) changed on disk. Show the new versions? 有 {count} 个链接图像已在磁盘上更改。要显示新版本吗? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 有 {n} 个链接图像已在磁盘上更改。要显示新版本吗? @msg Updated {_1} linked file(s) changed on disk 已更新 {_1} 个在磁盘上更改的链接文件 @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 链接的图片在找到其文件之前显示文件中存储的低分辨率预览:请在“链接”面板中重新链接 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 框架高度不足以容纳所显示字体一行的区域文字已加高框架 ({_1}):否则文字不会显示 @@ -3551,12 +3553,12 @@ font-script Japanese 汉字 Zoom Tool 缩放工具 Zoom with Mouse Wheel 使用鼠标滚轮缩放 Scrub Numeric Fields by Dragging 拖动以调整数值字段 - {count} file(s) in {folder} {note}. Show the package folder? {folder} 中有 {count} 个文件{note}。要显示打包文件夹吗? - {count} linked file(s) not found 找不到 {count} 个链接文件 +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} 中有 {n} 个文件{note}。要显示打包文件夹吗? +@plural {n} linked file not found|{n} linked files not found 找不到 {n} 个链接文件 fonts not copied: {fonts} 未复制的字体:{fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? 自存储此文档后,有 {count} 个链接图像已更改。要显示新版本吗? - {count} more rules: Export writes every one. 另有 {count} 条规则:导出时会全部写出。 - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 已略过 {count} 个未命名对象:请为它们命名,或在面板菜单中开启“未命名对象”。 +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? 自存储此文档后,有 {n} 个链接图像已更改。要显示新版本吗? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. 另有 {n} 条规则:导出时会全部写出。 +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 已略过 {n} 个未命名对象:请为它们命名,或在面板菜单中开启“未命名对象”。 {effect} is already applied 已应用 {effect} {format} Options {format} 选项 {kind} Gradient {kind}渐变 @@ -5433,10 +5435,10 @@ axis Y Axis Y 轴 @msg Packaged {n} file(s) in {folder} 已将 {n} 个文件打包到 {folder} @msg Packaged {n} file(s) {note} 已打包 {n} 个文件 {note} @msg Packaged {n} file(s) 已打包 {n} 个文件 - Packaged {n} file(s) 已打包 {n} 个文件 - Packaged {n} file(s) in {folder} 已将 {n} 个文件打包到 {folder} - Packaged {n} file(s) {note} 已打包 {n} 个文件 {note} - {count} file(s) in {folder}. Show the package folder? {folder} 中有 {count} 个文件。要显示打包文件夹吗? +@plural Packaged {n} file|Packaged {n} files 已打包 {n} 个文件 +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} 已将 {n} 个文件打包到 {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} 已打包 {n} 个文件 {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {folder} 中有 {n} 个文件。要显示打包文件夹吗? Clockwise 顺时针 Dither 仿色 Fine noise hides banding in the gradient fill 细微杂色可隐藏渐变填色中的色带 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7fe82d929f..b3cfda873a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -175,7 +175,7 @@ font-technology Variable 可變 Apply Paragraph Style 套用段落樣式 Apply SVG Filter… 套用 SVG 濾鏡… Apply to All 全部套用 - Apply to All ({count} more missing) 全部套用 (另有 {count} 個遺失) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) 全部套用 (另有 {n} 個遺失) Arc 弧形 Arc Lower… 下弧形… Arc Tool 弧形工具 @@ -3108,7 +3108,7 @@ file-filter Templates 範本 Package 封裝 Package collects a saved document with its linked files and fonts. 封裝會將已儲存的文件連同其連結檔案與字體一併收集。 Package created 已建立封裝 - Packaged {n} file(s) in {folder} {note} 已將 {n} 個檔案封裝於 {folder}{note} +@plural Packaged {n} file in {folder} {note}|Packaged {n} files in {folder} {note} 已將 {n} 個檔案封裝於 {folder}{note} Packaged {n} file(s){note} 已封裝 {n} 個檔案{note} Package… 封裝… Page 頁面 @@ -3435,9 +3435,11 @@ font-script Japanese 漢字 Stop 停止 Searching… 搜尋中… Not found 找不到 - {folders} folder(s) and {files} file(s) searched 已搜尋 {folders} 個資料夾、{files} 個檔案 - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones 已略過 {count} 個資料夾,例如其他應用程式和系統的資料夾,以及隱藏的資料夾 - {count} folder(s) or file(s) couldn't be read 有 {count} 個資料夾或檔案無法讀取 + {folders} and {files} searched 已搜尋 {folders}、{files} +@plural {n} folder|{n} folders {n} 個資料夾 +@plural {n} file|{n} files {n} 個檔案 +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones 已略過 {n} 個資料夾,例如其他應用程式和系統的資料夾,以及隱藏的資料夾 +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read 有 {n} 個資料夾或檔案無法讀取 The search stopped at its limit: search a smaller folder. 搜尋已達上限而停止:請搜尋較小的資料夾。 Copy only fonts you own or are licensed to install. 只複製您擁有或已取得安裝授權的字體。 VectorCraft copies the fonts to {folder}. VectorCraft 會將字體複製到 {folder}。 @@ -4359,7 +4361,7 @@ font-script Japanese 漢字 Update Link 更新連結 Update Links 更新連結 Update Changed Links 更新已變更的連結 - {count} linked image(s) changed on disk. Show the new versions? 有 {count} 個連結影像已在磁碟上變更。要顯示新版本嗎? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 有 {n} 個連結影像已在磁碟上變更。要顯示新版本嗎? @msg Updated {_1} linked file(s) changed on disk 已更新 {_1} 個在磁碟上變更的連結檔案 @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 連結的圖片在找到其檔案之前顯示檔案中儲存的低解析度預覽:請在「連結」面板中重新連結 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 框架高度不足以容納所顯示字體一行的區域文字已加高框架 ({_1}):否則文字不會顯示 @@ -4533,12 +4535,12 @@ font-script Japanese 漢字 Zoom Tool 縮放工具 Zoom with Mouse Wheel 使用滑鼠滾輪縮放 Scrub Numeric Fields by Dragging 拖曳以調整數值欄位 - {count} file(s) in {folder} {note}. Show the package folder? {folder} 中有 {count} 個檔案{note}。要顯示封裝資料夾嗎? - {count} linked file(s) not found 找不到 {count} 個連結檔案 +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} 中有 {n} 個檔案{note}。要顯示封裝資料夾嗎? +@plural {n} linked file not found|{n} linked files not found 找不到 {n} 個連結檔案 fonts not copied: {fonts} 未複製的字體:{fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? 自儲存此文件後,有 {count} 個連結影像已變更。要顯示新版本嗎? - {count} more rules: Export writes every one. 另有 {count} 條規則:匯出時會全部寫出。 - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 已略過 {count} 個未命名物件:請為它們命名,或在面板選單中開啟「未命名物件」。 +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? 自儲存此文件後,有 {n} 個連結影像已變更。要顯示新版本嗎? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. 另有 {n} 條規則:匯出時會全部寫出。 +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 已略過 {n} 個未命名物件:請為它們命名,或在面板選單中開啟「未命名物件」。 {effect} is already applied 已套用 {effect} {format} Options {format} 選項 {kind} Gradient {kind}漸層 @@ -5228,10 +5230,10 @@ axis Y Axis Y 軸 @msg Packaged {n} file(s) in {folder} 已將 {n} 個檔案封裝到 {folder} @msg Packaged {n} file(s) {note} 已封裝 {n} 個檔案 {note} @msg Packaged {n} file(s) 已封裝 {n} 個檔案 - Packaged {n} file(s) 已封裝 {n} 個檔案 - Packaged {n} file(s) in {folder} 已將 {n} 個檔案封裝到 {folder} - Packaged {n} file(s) {note} 已封裝 {n} 個檔案 {note} - {count} file(s) in {folder}. Show the package folder? {folder} 中有 {count} 個檔案。要顯示封裝資料夾嗎? +@plural Packaged {n} file|Packaged {n} files 已封裝 {n} 個檔案 +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} 已將 {n} 個檔案封裝到 {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} 已封裝 {n} 個檔案 {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {folder} 中有 {n} 個檔案。要顯示封裝資料夾嗎? Clockwise 順時針 Dither 仿色 Fine noise hides banding in the gradient fill 細微雜色可隱藏漸層填色中的色帶 diff --git a/crates/ui-egui/src/panels/css_properties.rs b/crates/ui-egui/src/panels/css_properties.rs index 5b0fe407a4..97e270e3c8 100644 --- a/crates/ui-egui/src/panels/css_properties.rs +++ b/crates/ui-egui/src/panels/css_properties.rs @@ -129,12 +129,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); }); let notes = (shown.more > 0) - .then(|| crate::i18n::fmt(tl!("{count} more rules: Export writes every one."), &[("count", &shown.more.to_string())])) + .then(|| crate::i18n::tn(shown.more as u64, "{n} more rule: Export writes it.", "{n} more rules: Export writes every one.")) .into_iter() .chain((shown.skipped > 0).then(|| { - crate::i18n::fmt( - tl!("{count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu."), - &[("count", &shown.skipped.to_string())], + crate::i18n::tn( + shown.skipped, + "{n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.", + "{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu.", ) })) .chain(shown.warnings.iter().map(|w| sentence(w))); diff --git a/crates/ui-egui/src/panels/tests_css_properties.rs b/crates/ui-egui/src/panels/tests_css_properties.rs index 1034daeb33..a23f108eb2 100644 --- a/crates/ui-egui/src/panels/tests_css_properties.rs +++ b/crates/ui-egui/src/panels/tests_css_properties.rs @@ -61,6 +61,33 @@ fn generate_css_shows_the_document_while_nothing_is_selected() { assert!(text.contains(".rectangle {") && text.contains(".ellipse {") && text.contains("border-radius: 50%;"), "{text}"); } +/// The note on unnamed objects left out uses the form the language's plural rule picks for the +/// count. +#[test] +fn the_unnamed_objects_note_uses_each_count_form() { + let note = |code: &str, n: u64| { + let (mut app, _) = app(); + for i in 1..n { + app.run("shape.rectangle", json!({"x": 10 + 40 * i, "y": 50, "width": 30, "height": 20})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); + let text = painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), OPTIONS, CssOptions { unnamed: false, ..CssOptions::default() }); + show(app, ui); + }); + crate::i18n::set_current(crate::i18n::Lang::EN); + text + }; + let text = note("en", 1); + assert!(text.contains("1 unnamed object left out: name it,"), "{text}"); + for (n, want) in [(1, "Vynechán 1 nepojmenovaný objekt."), (2, "Vynechány 2 nepojmenované objekty."), (5, "Vynecháno 5 nepojmenovaných objektů.")] + { + let text = note("cs", n); + assert!(text.contains(want), "{n}: {text}"); + } +} + #[test] fn the_panel_menu_lists_the_actions_and_options() { let (mut app, _) = app(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0634080f47..af17606c0e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -587,6 +587,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Czech render-site labels: desktop/web file filters, diagnostics, suggested preset names and contributor tooltips/plurals now use catalog lookups; gradients have Czech adjective agreement and printer marks have a separate context (PDF/Print and Summary). Search, Home, toolbar/panel tooltips and Preferences already look up their labels. Every complete catalog has rows for these labels and for the Roman and Japanese printer mark styles. Evidence: `i18n::tests::czech_render_site_follow_up`, `i18n::tests::complete_catalogs_translate_render_site_labels`, `dialogs::tests_modal::printer_mark_labels_are_distinct_from_language_names`; see [localization-parity.md](localization-parity.md). - The History panel, Edit › Undo and Edit › Redo translate the names of the steps that apply or redefine a character or paragraph style and of the step that redefines a graphic style: each such step keeps its template (`Apply {name}`, `Redefine {name}`, `Redefine Graphic Style “{name}”`) and the style's name, every complete catalog has a row for each template, and the panel and the menu show the style's name as the document holds it, except the Normal styles' names, which they show in the interface language (`steps_named_after_a_style_list_the_template_around_the_name`, `undo_and_redo_name_a_style_step_around_the_style_name`). - Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Korean, Vietnamese, German, Spanish, French, Italian, Polish, Brazilian Portuguese, Russian, Ukrainian, Georgian and Catalan ship complete, and Czech covers every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a Language preference and, on macOS, a VectorCraft ▸ Language menu. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins). + The counts that Package's status and question, the folder search of Missing Fonts and Find Linked Files, the modified and missing linked file prompts and the CSS Properties panel's notes show use the interface language's plural forms instead of a fixed "(s)" form. Evidence: `the_missing_links_note_uses_each_count_form` in `crates/ui-egui/src/dialogs/tests_package.rs`, `the_modified_links_question_uses_each_count_form` in `crates/ui-egui/src/dialogs/missing_links.rs`, `search_counts_use_each_count_form` in `crates/ui-egui/src/dialogs/missing_fonts/tests.rs` and `the_unnamed_objects_note_uses_each_count_form` in `crates/ui-egui/src/panels/tests_css_properties.rs`. - Edit › Undo and Edit › Redo, in the in-window and native menus, name the step in the interface language as the History panel lists it (`panels::history::step_name`), so when the catalog has no plain row for a step named after an effect, such as Feather, the menu shows the translation of the effect's menu row without its ellipsis (`undo_and_redo_name_the_step_as_the_history_panel_does`). - The History panel translates the undo step names the engine, the tools and the shell write as literals: the untranslated report (`untranslated_report`) lists any a complete catalog lacks, and a step whose catalog row exists only with an ellipsis (such as an effect's menu name) shows that row without the ellipsis. - The History panel menu has Step Backward and Step Forward, which run Edit › Undo and Edit › Redo and are disabled when there is no step to undo or redo, and Set History Limit…, which opens Preferences at Performance, where History States is set. Not done: a new document from the selected state. From 89ca9d9a255cfa54aa99fbd11f66c6de328e2aa6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 21:16:48 -0700 Subject: [PATCH 42/70] Batch: keep an existing artboard file of a one-artboard Separate Artboards save A save in the native, template or .ai formats with separateArtboards writes an artboard file even when the document has one artboard, so an existing file with that name now gives the data set the next free suffix too. --- crates/engine/src/cmd/fileio/action_batch.rs | 89 ++++++++++++++------ docs/mcp.md | 7 +- 2 files changed, 66 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 1caa98db7d..e11b6adcd6 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -292,8 +292,9 @@ struct DatasetOutput { joiner: &'static str, } -/// Lists step output extensions and reserves artboard file names when the document has multiple artboards. -/// Per-artboard names count for vectorcraft, template, AI and AIT saves and SVG, SVGZ, EPS, raster, DXF, EMF, WMF and AI exports. +/// Lists step output extensions and reserves artboard file names for saves with any artboard or +/// exports with multiple artboards. Per-artboard names count for vectorcraft, template, AI and AIT +/// saves and SVG, SVGZ, EPS, raster, DXF, EMF, WMF and AI exports. #[cfg(not(target_arch = "wasm32"))] fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Vec { let mut outputs = Vec::new(); @@ -314,31 +315,31 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document) -> if safe_extension(&ext) { let format_id = format.and_then(super::format).map(|f| f.id).unwrap_or("vectorcraft"); let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs"); - let artboards = doc.artboards.len() > 1 - && if is_save { - matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") - } else { - id == "document.export" - && matches!( - format_id, - "svg" - | "svgz" - | "eps" - | "png" - | "jpg" - | "webp" - | "gif" - | "png8" - | "tiff" - | "bmp" - | "tga" - | "psd" - | "dxf" - | "emf" - | "wmf" - | "ai" - ) - }; + let artboards = if is_save { + !doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") + } else { + doc.artboards.len() > 1 + && id == "document.export" + && matches!( + format_id, + "svg" + | "svgz" + | "eps" + | "png" + | "jpg" + | "webp" + | "gif" + | "png8" + | "tiff" + | "bmp" + | "tga" + | "psd" + | "dxf" + | "emf" + | "wmf" + | "ai" + ) + }; outputs.push(DatasetOutput { ext, artboards, joiner: if format_id == "eps" { "_" } else { "-" } }); } } @@ -952,6 +953,40 @@ mod tests { ); } + #[test] + fn batch_single_artboard_save_keeps_existing_artboard_file() { + let source = tmp("choice-single-artboard-source"); + let dest = tmp("choice-single-artboard-dest"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 1})).unwrap(); + s.execute( + "document.save", + &json!({ + "path": source.join("source.vectorcraft").to_string_lossy(), + "separateArtboards": true + }), + ) + .unwrap(); + assert!(source.join("source-Artboard-1.vectorcraft").exists()); + + let existing = dest.join("Alpha-Artboard-1.vectorcraft"); + std::fs::write(&existing, b"keep").unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {"separateArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-2-Artboard-1.vectorcraft", "Alpha-2.vectorcraft", "Alpha-Artboard-1.vectorcraft"]); + } + #[test] fn batch_pdf_export_ignores_artboard_named_file() { let dest = tmp("choice-pdf-artboard-name"); diff --git a/docs/mcp.md b/docs/mcp.md index f904715027..a03d5db9f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2971,9 +2971,10 @@ destination and overridden Save/Export paths use the chosen stem with the output set name under Data Set Name falls back to the document stem plus its three-digit ordinal. Batch writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds the next free `-2`, `-3` suffix to a stem already used in the batch (compared without case). An output already in a destination folder -gets the next free suffix only when the batch may read and write that folder before it starts. When a step can write -one file per artboard and the document has several artboards, a file with one of those artboard file names for the -stem counts too. Under Data Set Name, VectorCraft makes Windows device names safe (`CON` becomes `CON-`). This is +gets the next free suffix only when the batch may read and write that folder before it starts. A save in VectorCraft, +template, AI or AIT format counts artboard file names when the document has any artboard; a per-artboard export +counts them when the document has several artboards. +Under Data Set Name, VectorCraft makes Windows device names safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 files or data sets, 8 folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, From 28014a9fed3243ec1a780774704fb3d4d32360b0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 01:11:36 -0700 Subject: [PATCH 43/70] i18n: French one-item count forms keep the no-break space before ? and : --- crates/ui-egui/src/i18n/fr.tsv | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 29cb4e6d1c..a93869adf7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3676,13 +3676,13 @@ font-technology Variable Variables Zoom Tool Outil Zoom Zoom with Mouse Wheel Zoom avec la molette de la souris Scrub Numeric Fields by Dragging Modifier les champs numériques en faisant glisser -@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fichier dans {folder} {note}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder} {note}. Afficher le dossier de l’assemblage ? +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fichier dans {folder} {note}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder} {note}. Afficher le dossier de l’assemblage ? @plural {n} linked file not found|{n} linked files not found {n} fichier lié introuvable|{n} fichiers liés introuvables fonts not copied: {fonts} polices non copiées : {fonts} -@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} image liée modifiée depuis l’enregistrement de ce document. Afficher la nouvelle version ?|{n} images liées modifiées depuis l’enregistrement de ce document. Afficher les nouvelles versions ? -@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} image liée modifiée sur le disque. Afficher la nouvelle version ?|{n} images liées modifiées sur le disque. Afficher les nouvelles versions ? -@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} règle de plus : Exporter l’écrit.|{n} règles de plus : Exporter les écrit toutes. -@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} objet sans nom omis : nommez-le ou activez Objets sans nom dans le menu du panneau.|{n} objets sans nom omis : nommez-les ou activez Objets sans nom dans le menu du panneau. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} image liée modifiée depuis l’enregistrement de ce document. Afficher la nouvelle version ?|{n} images liées modifiées depuis l’enregistrement de ce document. Afficher les nouvelles versions ? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} image liée modifiée sur le disque. Afficher la nouvelle version ?|{n} images liées modifiées sur le disque. Afficher les nouvelles versions ? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} règle de plus : Exporter l’écrit.|{n} règles de plus : Exporter les écrit toutes. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} objet sans nom omis : nommez-le ou activez Objets sans nom dans le menu du panneau.|{n} objets sans nom omis : nommez-les ou activez Objets sans nom dans le menu du panneau. {effect} is already applied {effect} est déjà appliqué {format} Options Options {format} {kind} Gradient Dégradé {kind} @@ -5597,7 +5597,7 @@ axis Y Axis Axe Y @plural Packaged {n} file|Packaged {n} files {n} fichier assemblé|{n} fichiers assemblés @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {n} fichier assemblé dans {folder}|{n} fichiers assemblés dans {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} {n} fichier assemblé {note}|{n} fichiers assemblés {note} -@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fichier dans {folder}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder}. Afficher le dossier de l’assemblage ? +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fichier dans {folder}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder}. Afficher le dossier de l’assemblage ? Clockwise Sens horaire Dither Simulation Fine noise hides banding in the gradient fill Un bruit fin masque les bandes du fond en dégradé From 62401182e6919c60b8859ad68a917fc3bd403fea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:08:33 -0700 Subject: [PATCH 44/70] i18n: an English package status is translated after a language switch, in each language's plural form MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The package status now says "file" or "files", and the catalogs' `@msg` rows for it still matched only the old "file(s)" text, so a status written in English stayed in English after a switch to another language. - Catalogs take a new `@msgplural` row: the English one|other forms as the source and the language's plural forms as the translation. The `{n}` value picks the form, so Czech shows "Zabaleny 3 soubory" for 3 files and "Zabaleno 5 souborů" for 5. - Every catalog replaces its four package status rows with `@msgplural` rows. The row for a status with a note finds the note by its opening parenthesis, so a folder name with spaces stays whole. - `package_status` builds the status line for the folder and the web download. --- crates/ui-egui/src/dialogs/package.rs | 31 ++++++++--------- crates/ui-egui/src/dialogs/tests_package.rs | 34 +++++++++++++++++++ crates/ui-egui/src/i18n.rs | 7 +++- crates/ui-egui/src/i18n/bg.tsv | 8 ++--- crates/ui-egui/src/i18n/bs.tsv | 8 ++--- crates/ui-egui/src/i18n/ca.tsv | 8 ++--- crates/ui-egui/src/i18n/catalog.rs | 37 +++++++++++++++------ crates/ui-egui/src/i18n/cs.tsv | 8 ++--- crates/ui-egui/src/i18n/da.tsv | 8 ++--- crates/ui-egui/src/i18n/de.tsv | 8 ++--- crates/ui-egui/src/i18n/el.tsv | 8 ++--- crates/ui-egui/src/i18n/es.tsv | 8 ++--- crates/ui-egui/src/i18n/fi.tsv | 8 ++--- crates/ui-egui/src/i18n/fr.tsv | 8 ++--- crates/ui-egui/src/i18n/hu.tsv | 8 ++--- crates/ui-egui/src/i18n/id.tsv | 8 ++--- crates/ui-egui/src/i18n/it.tsv | 8 ++--- crates/ui-egui/src/i18n/ja.tsv | 8 ++--- crates/ui-egui/src/i18n/ka.tsv | 8 ++--- crates/ui-egui/src/i18n/ko.tsv | 8 ++--- crates/ui-egui/src/i18n/nl.tsv | 8 ++--- crates/ui-egui/src/i18n/pl.tsv | 8 ++--- crates/ui-egui/src/i18n/pt-br.tsv | 8 ++--- crates/ui-egui/src/i18n/ru.tsv | 8 ++--- crates/ui-egui/src/i18n/sv.tsv | 8 ++--- crates/ui-egui/src/i18n/tests.rs | 19 ++++++++++- crates/ui-egui/src/i18n/tr.tsv | 8 ++--- crates/ui-egui/src/i18n/uk.tsv | 8 ++--- crates/ui-egui/src/i18n/vi.tsv | 8 ++--- crates/ui-egui/src/i18n/zh-hans.tsv | 8 ++--- crates/ui-egui/src/i18n/zh-hant.tsv | 8 ++--- 31 files changed, 205 insertions(+), 131 deletions(-) diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 9c2b3deb97..5b49be69eb 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -160,24 +160,11 @@ fn packaged(app: &mut VectorcraftApp, r: Result, web: bool, later let (name, data) = (r["name"].as_str().unwrap_or("package.zip"), r["dataBase64"].as_str().unwrap_or_default()); let bytes = vectorcraft_format::base64_decode(data).ok_or("the package came back damaged")?; io::write_named(app, None, name, &bytes)?; - let status = if shown_note.is_empty() { - crate::i18n::tn(n, "Packaged {n} file", "Packaged {n} files") - } else { - crate::i18n::fmt(&crate::i18n::tn(n, "Packaged {n} file {note}", "Packaged {n} files {note}"), &[("note", &shown_note)]) - }; - app.status(status); + app.status(package_status(n, None, &shown_note)); return Ok(r); } let folder = r["folder"].as_str().unwrap_or_default().to_string(); - let status = if shown_note.is_empty() { - crate::i18n::fmt(&crate::i18n::tn(n, "Packaged {n} file in {folder}", "Packaged {n} files in {folder}"), &[("folder", &folder)]) - } else { - crate::i18n::fmt( - &crate::i18n::tn(n, "Packaged {n} file in {folder} {note}", "Packaged {n} files in {folder} {note}"), - &[("folder", &folder), ("note", &shown_note)], - ) - }; - app.status(status); + app.status(package_status(n, Some(&folder), &shown_note)); let detail = if shown_note.is_empty() { crate::i18n::fmt( &crate::i18n::tn(n, "{n} file in {folder}. Show the package folder?", "{n} files in {folder}. Show the package folder?"), @@ -195,6 +182,20 @@ fn packaged(app: &mut VectorcraftApp, r: Result, web: bool, later Ok(r) } +/// The status bar's line for a package of `n` files written to `folder` (`None`: the web's +/// download), followed by `note` from [`package_status_note`] when it isn't empty. Each catalog +/// also has `@msgplural` rows for the English line, shown after a language switch; they find the note +/// after the folder by its opening `(`, so a folder name with spaces stays whole. +pub(super) fn package_status(n: u64, folder: Option<&str>, note: &str) -> String { + let (one, other) = match (folder.is_some(), note.is_empty()) { + (false, true) => ("Packaged {n} file", "Packaged {n} files"), + (false, false) => ("Packaged {n} file {note}", "Packaged {n} files {note}"), + (true, true) => ("Packaged {n} file in {folder}", "Packaged {n} files in {folder}"), + (true, false) => ("Packaged {n} file in {folder} {note}", "Packaged {n} files in {folder} {note}"), + }; + crate::i18n::fmt(&crate::i18n::tn(n, one, other), &[("folder", folder.unwrap_or_default()), ("note", note)]) +} + /// Parenthetical notes after the folder path in a package status (`(2 linked files not found)` …), /// joined with spaces and without a leading space (#3494). pub(super) fn package_status_note(missing: usize, fonts: &str) -> String { diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index 22c5e2a357..91d95d922a 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -302,6 +302,40 @@ fn the_missing_links_note_uses_each_count_form() { assert_eq!(note("cs", 5), "(Nenalezeno 5 propojených souborů)"); } +/// A package status written in English, for one file or several, with or without a folder and a +/// note, is translated by every catalog when the status bar shows it after a language switch, in +/// the form the language's plural rule picks for the count, and a folder whose name has a space +/// keeps its whole name. +#[test] +fn an_english_package_status_is_translated_after_a_language_switch() { + use crate::i18n::{Lang, message}; + let mut statuses = vec![]; + for n in [1, 3] { + for folder in [None, Some("/out/card Folder")] { + for note in ["", "(fonts not copied: Mono)"] { + statuses.push(package::package_status(n, folder, note)); + } + } + } + assert!(statuses.contains(&"Packaged 1 file in /out/card Folder".to_string()), "{statuses:?}"); + assert!(statuses.contains(&"Packaged 3 files".to_string()), "{statuses:?}"); + for lang in Lang::all().filter(|l| l.code() != "en") { + for s in &statuses { + let shown = message(lang, s); + assert!(!shown.starts_with("Packaged"), "{}: {shown}", lang.code()); + // A space in the folder's name stays in the path, with or without a note. + assert_eq!(s.contains("/out/card Folder"), shown.contains("/out/card Folder"), "{}: {shown}", lang.code()); + } + } + let cs = Lang::from_code("cs").unwrap(); + assert_eq!(message(cs, "Packaged 1 file in /out"), "Zabalen 1 soubor do /out"); + assert_eq!(message(cs, "Packaged 3 files in /out"), "Zabaleny 3 soubory do /out"); + assert_eq!(message(cs, "Packaged 5 files in /out"), "Zabaleno 5 souborů do /out"); + let de = Lang::from_code("de").unwrap(); + assert_eq!(message(de, "Packaged 1 file"), "1 Datei verpackt"); + assert_eq!(message(de, "Packaged 3 files in /out"), "3 Dateien in /out verpackt"); +} + #[test] fn package_status_without_notes_has_no_extra_spaces() { let dir = Folder::new("spaces"); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index af85867d85..dee009b768 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -23,6 +23,8 @@ //! message itself stays English (the control channel, MCP and tests read it); `@msg` catalog //! rows hold whole messages or templates such as `Couldn't open {name}: {e}`, and the values in //! the placeholders are translated in turn (the reason after `: {e}` is often a message too). +//! A `@msgplural` row is a template with a count: its source holds the English `one|other` +//! forms, its translation the language's plural forms, and the `{n}` value picks the form. mod catalog; @@ -651,7 +653,10 @@ pub fn message(lang: Lang, s: &str) -> String { } fn message_at(lang: Lang, s: &str, depth: usize) -> String { - let Some((template, caps)) = lang.catalog().message(s) else { return s.to_string() }; + let Some((forms, caps)) = lang.catalog().message_forms(s) else { return s.to_string() }; + let count = caps.iter().find(|(k, _)| *k == "n").and_then(|(_, v)| v.parse::().ok()); + let form = count.map_or(forms.len().saturating_sub(1), |n| (lang.0.plural)(n).min(forms.len().saturating_sub(1))); + let Some(template) = forms.get(form) else { return s.to_string() }; let values: Vec<(&str, String)> = caps.into_iter().map(|(k, v)| (k, if depth > 1 { message_at(lang, v, depth - 1) } else { v.to_string() })).collect(); let args: Vec<(&str, &str)> = values.iter().map(|(k, v)| (*k, v.as_str())).collect(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index fd7a177514..0afca3ee6d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3833,7 +3833,7 @@ axis Both И двете @msg PDF settings are not an object Настройките за PDF не са обект @msg PDF security settings are not an object Настройките за сигурност на PDF не са обект @msg PDF writer error: {0} Грешка на PDF записа: {0} -@msg Packaged {n} file(s) in {folder} {note} Пакетирани са {n} файла в {folder}{note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Пакетиран е {n} файл в {folder} ({note}|Пакетирани са {n} файла в {folder} ({note} @msg Packaged {n} file(s){note} Пакетирани са {n} файла{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Прегледът в браузър изисква настолното приложение (уеб версията изтегля файловете вместо това) @msg Release Guides: no guides Освобождаване на водачи: няма водачи @@ -5504,9 +5504,9 @@ theme Appearance Външен вид Slope: Наклон: axis X Axis X ос axis Y Axis Y ос -@msg Packaged {n} file(s) in {folder} Пакетирани са {n} файла в {folder} -@msg Packaged {n} file(s) {note} Пакетирани са {n} файла {note} -@msg Packaged {n} file(s) Пакетирани са {n} файла +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Пакетиран е {n} файл в {folder}|Пакетирани са {n} файла в {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Пакетиран е {n} файл {note}|Пакетирани са {n} файла {note} +@msgplural Packaged {n} file|Packaged {n} files Пакетиран е {n} файл|Пакетирани са {n} файла @plural Packaged {n} file|Packaged {n} files Пакетиран е {n} файл|Пакетирани са {n} файла @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Пакетиран е {n} файл в {folder}|Пакетирани са {n} файла в {folder} @plural Packaged {n} file {note}|Packaged {n} files {note} Пакетиран е {n} файл {note}|Пакетирани са {n} файла {note} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 0ff4eeeb64..9ce6565b97 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4199,7 +4199,7 @@ imageTrace Outline Obris @msg PDF settings are not an object PDF postavke nisu objekat @msg PDF security settings are not an object PDF sigurnosne postavke nisu objekat @msg PDF writer error: {0} greška PDF zapisivača: {0} -@msg Packaged {n} file(s) in {folder} {note} Upakovano datoteka u {folder}: {n} {note} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} Upakovano datoteka u {folder}: {n} ({note} @msg Packaged {n} file(s){note} Upakovano datoteka: {n}{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Pregledaj u pregledniku zahtijeva desktop aplikaciju (web umjesto toga preuzima datoteke) @msg Release Guides: no guides Oslobodi vodilice: nema vodilica @@ -5524,9 +5524,9 @@ mark-style Japanese Japanski Slope: Nagib: axis X Axis X osa axis Y Axis Y osa -@msg Packaged {n} file(s) in {folder} Upakovano datoteka u {folder}: {n} -@msg Packaged {n} file(s) {note} Upakovano datoteka: {n} {note} -@msg Packaged {n} file(s) Upakovano datoteka: {n} +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Upakovano datoteka u {folder}: {n} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Upakovano datoteka: {n} {note} +@msgplural Packaged {n} file|Packaged {n} files Upakovano datoteka: {n} @plural Packaged {n} file|Packaged {n} files Upakovano datoteka: {n}|Upakovano datoteka: {n}|Upakovano datoteka: {n} @plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Upakovano datoteka u {folder}: {n}|Upakovano datoteka u {folder}: {n}|Upakovano datoteka u {folder}: {n} @plural Packaged {n} file {note}|Packaged {n} files {note} Upakovano datoteka: {n} {note}|Upakovano datoteka: {n} {note}|Upakovano datoteka: {n} {note} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 04608e692c..f6e37996d2 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5258,10 +5258,10 @@ @msg Opened with {_1} note(s): {_2} Obert amb {_1} nota(es): {_2} @msg Opened {url} Obert {url} @msg Outline Stroke: no stroked paths selected Contorneja el traç: no hi ha cap traçat amb traç seleccionat -@msg Packaged {n} file(s) Empaquetat {n} fitxer(s) -@msg Packaged {n} file(s) in {folder} Empaquetats {n} fitxer(s) a {folder} -@msg Packaged {n} file(s) in {folder} {note} Empaquetats {n} fitxer(s) a {folder} {note} -@msg Packaged {n} file(s) {note} Empaquetats {n} fitxer(s) {note} +@msgplural Packaged {n} file|Packaged {n} files S’ha empaquetat {n} fitxer|S’han empaquetat {n} fitxers +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} S’ha empaquetat {n} fitxer a {folder}|S’han empaquetat {n} fitxers a {folder} +@msgplural Packaged {n} file in {folder} ({note}|Packaged {n} files in {folder} ({note} S’ha empaquetat {n} fitxer a {folder} ({note}|S’han empaquetat {n} fitxers a {folder} ({note} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} S’ha empaquetat {n} fitxer {note}|S’han empaquetat {n} fitxers {note} @msg Packaged {n} file(s){note} Empaquetats {n} fitxer(s){note} @msg Packaging {_1} Empaquetant {_1} @msg page size {w} × {h} mida de pàgina {w} × {h} diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs index a79ce351a2..1be460212a 100644 --- a/crates/ui-egui/src/i18n/catalog.rs +++ b/crates/ui-egui/src/i18n/catalog.rs @@ -15,7 +15,8 @@ pub struct Catalog { plurals: HashMap>, /// status and error messages without placeholders (`@msg`): English → translation messages: HashMap, - /// status and error messages with `{name}` placeholders (`@msg`), most specific first + /// status and error messages with `{name}` placeholders (`@msg`, and each English form of a + /// `@msgplural` row), most specific first templates: Vec