diff --git a/AGENTS.md b/AGENTS.md index bac119a742..2e02266c6d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator- For the crates you changed: `cargo fmt`, `cargo clippy -p --all-targets`, `cargo xtask test` or `cargo nextest run -p `. Repository-wide steps when they apply: `cargo xtask assets`, `cargo xtask brands`, `cargo xtask layers`, `cargo xtask wasm`. `cargo xtask ci` runs all of them. Workspace lints (`unsafe_code = "deny"`, no `unwrap`/`expect`/`panic!` outside tests) are in `Cargo.toml`. ### Paths and conventions -- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. +- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. Doc tests are built without the workspace lints, so every library root carries `#![doc(test(attr(forbid(unsafe_code))))]` (`deny` in a crate without `#![forbid(unsafe_code)]`), and `cargo xtask layers` reports a root without it. - Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, symbols and patterns. - Fonts: [storytold/craft-fonts](https://github.com/storytold/craft-fonts) through the optional `CRAFT_FONTS_DIR` build option, read by `crates/text/build.rs`; everything builds with it empty. - Crash handling: `vectorcraft_engine::guard` wraps every entry point. Hostile-input tests: `crates/engine/tests/{import_fuzz,command_sweep}.rs`, `crates/format/tests/prop_format.rs`, `crates/mcp/tests/protocol_props.rs`. diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 64a596e5ba..519056ba0c 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -143,7 +143,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option std::process::ExitCode { Some(pen) => spec.pen(pen), None => spec, }; - embed::install(ctx, spec, &vectorcraft_ui_egui::ui_fonts()).map_err(|e| e.to_string())?; - egui_extras::install_image_loaders(ctx); let folders = settings.lock().get().ui.last_folders.clone(); let wake = { let ctx = ctx.clone(); @@ -882,7 +880,6 @@ fn main() -> std::process::ExitCode { .settings(Arc::new(settings.clone())) .files(files.clone()) .build(); - host.clone().install(ctx); let mut session = Session::new(); // The profiles loaded before come back before the preferences name any of them. prefs_dir::attach_profile_store(&mut session); @@ -907,12 +904,16 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_proof_setups(&mut session); prefs_dir::attach_script_data(&mut session); let mut app = VectorcraftApp::new(session, services(winit_window.clone())); + load_prefs(&mut app, &settings); + let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, app.ui_language(), None); + embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?; + egui_extras::install_image_loaders(ctx); + host.clone().install(ctx); app.host = Arc::new(host); app.adopt_context(&cc.egui_ctx); // A nightly is updated by the Launcher: it never checks for a stable release, which // would install this program's own updater over the nightly build. app.set_startup_update_check(!nightly); - load_prefs(&mut app, &settings); safe_mode::after_start(&mut app, stopped); // Loads started later (a preference change, the end of Safe Mode) are waited for, // after the launch's own. diff --git a/assets/cursors/cursor-pen-convert.svg b/assets/cursors/cursor-pen-convert.svg index fa78f562ef..79e29af75d 100644 --- a/assets/cursors/cursor-pen-convert.svg +++ b/assets/cursors/cursor-pen-convert.svg @@ -1 +1,5 @@ - + + + + + diff --git a/assets/cursors/cursor-pen-curvature.svg b/assets/cursors/cursor-pen-curvature.svg index 94ba1708b5..b8d4bd3650 100644 --- a/assets/cursors/cursor-pen-curvature.svg +++ b/assets/cursors/cursor-pen-curvature.svg @@ -1 +1,5 @@ - + + + + + diff --git a/assets/cursors/cursor-pen-join.svg b/assets/cursors/cursor-pen-join.svg index 3dd7ce7f6e..05a020bb12 100644 --- a/assets/cursors/cursor-pen-join.svg +++ b/assets/cursors/cursor-pen-join.svg @@ -1 +1,6 @@ - + + + + + + diff --git a/assets/cursors/cursor-pen-new.svg b/assets/cursors/cursor-pen-new.svg index 6690b1ffd6..a27dc0ddae 100644 --- a/assets/cursors/cursor-pen-new.svg +++ b/assets/cursors/cursor-pen-new.svg @@ -1 +1,8 @@ - + + + + + + + + diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs index e14c1439a7..1a69aeed48 100644 --- a/crates/affinity/src/lib.rs +++ b/crates/affinity/src/lib.rs @@ -1,6 +1,7 @@ //! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so //! the corpus tests and fuzz targets under it, and the CI job that runs them, still build. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub use craft_affinity::*; diff --git a/crates/apischema/src/lib.rs b/crates/apischema/src/lib.rs index cff749e84f..e78cde4ecb 100644 --- a/crates/apischema/src/lib.rs +++ b/crates/apischema/src/lib.rs @@ -18,6 +18,7 @@ //! //! The crate knows no command and depends on no other VectorCraft crate. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use std::fmt; diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 85dfc8e084..fffdd4f797 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -9,6 +9,7 @@ //! [`stroke_pieces`] is the single source of brush geometry: the renderer paints the pieces it //! returns (caching them per node) and `object.expandBrush` inserts them as real objects. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod calli; mod colorize; diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index c272376668..73e30bd2a9 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -23,6 +23,7 @@ //! - `import`: the reader, entities to art, blocks to symbols. //! - `dwg`: DWG drawings converted to DXF by craft-dwg, in a child process on desktop builds. //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. +#![doc(test(attr(deny(unsafe_code))))] mod aci; pub mod dwg; diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 5bb4c88985..03aa259281 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -3,6 +3,7 @@ //! Colours keep the model the user picked them in (RGB, CMYK, Gray, Lab; HSB is a UI view of RGB), //! so documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`]. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod blend; pub mod cms; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index cb8f077dae..8fe1cef218 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -4,6 +4,7 @@ //! [`Document::node_mut`], which clones only the nodes on the path from the root to the edited node. //! Keeping the previous `Document` value around is therefore a cheap undo snapshot. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod appearance; pub mod assets; diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index aef398c64e..c2be1804db 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -33,6 +33,7 @@ //! noise (`seed` parameter, default 0); the random Pixelate filters hash their pattern's cells, //! anchored at the object's centre. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod adjust; diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 9a5be1fc4f..3a3c981229 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -903,7 +903,7 @@ pub struct SymbolOptions { impl SymbolOptions { /// The options `d` keeps for symbol `name`. - fn of(d: &Document, name: &str) -> Self { + pub(in crate::cmd) fn of(d: &Document, name: &str) -> Self { Self { size: stored_natural_size(d, name), registration: d.symbol_registration(name), @@ -914,7 +914,7 @@ impl SymbolOptions { } /// Make them the options of `d`'s symbol `name`. - fn give(&self, d: &mut Document, name: &str) { + pub(in crate::cmd) fn give(&self, d: &mut Document, name: &str) { set_natural_size(d, name, self.size); d.set_symbol_registration(name, self.registration); d.set_symbol_export_type(name, self.export_type); diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index b9f304ddf4..bff15c6540 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -10,9 +10,12 @@ //! custom character sets: //! . +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + use serde_json::{Map, Value, json}; use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX}; -use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet}; +use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, Document, Node, NodeKind}; use vectorcraft_text::FontDb; use super::fileio::{read_file_head, write_file}; @@ -77,6 +80,166 @@ pub fn specs() -> Vec { ] } +/// Every stored family name, including regeneration settings and retained style defaults. +/// Planning reads a private clone so gathering names never changes the destination. +fn family_names(d: &Document) -> Result> { + let mut view = d.clone(); + let mut names = BTreeSet::new(); + let mut note = |family: &mut String| { + names.insert(family.to_lowercase()); + }; + super::textstyles::each_text_mut(&mut view, &mut |text| { + for run in &mut text.runs { + note(&mut run.style.font_family); + } + Ok(()) + })?; + for style in view.char_styles.iter_mut().chain(view.para_styles.iter_mut()) { + if let Some(Value::String(family)) = style.attrs.get_mut("font_family") { + note(family); + } + } + let mut graphs = Vec::new(); + view.visit_stored(|node, _| { + if node.extras().graph.is_some() { + graphs.push(node.id); + } + }); + for id in graphs { + if let Some(node) = view.stored_node_mut(id) { + graph_families(node, &mut note); + } + } + fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) { + graph_families(node, note); + if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) { + brush_graphs(Arc::make_mut(&mut mask.art), note); + } + for child in node.children_mut().into_iter().flatten() { + brush_graphs(Arc::make_mut(child), note); + } + } + for art in vectorcraft_brush::library(&view).iter_mut().flat_map(|brush| brush.art_mut()) { + brush_graphs(art, &mut note); + } + Ok(names) +} + +fn graph_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) { + if let Some(graph) = node.extras_if_any().and_then(|extras| extras.graph.as_deref_mut()) { + let labels = &mut graph.label_styles; + for style in [&mut labels.values, &mut labels.categories, &mut labels.legend].into_iter().flatten() { + visit(&mut style.font_family); + } + } +} + +/// Family fields held directly by one node; the adoption walker owns tree/resource traversal. +pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) { + if let NodeKind::Text(text) = &mut node.kind { + for run in &mut text.runs { + visit(&mut run.style.font_family); + } + } + graph_families(node, visit); +} + +/// A fully checked incoming-only rename map and the destination's prospective definitions. +pub(super) struct CompositeImport { + names: BTreeMap, + pub(super) combined: Vec, +} + +impl CompositeImport { + pub(super) fn rename(&self, family: &mut String) -> bool { + if let Some(name) = self.names.get(&family.to_lowercase()) { + let changed = family.as_str() != name.as_str(); + *family = name.clone(); + changed + } else { + false + } + } +} + +fn composite_alias(base: &str, reserved: &BTreeSet, cmd: &str) -> Result { + let db = FontDb::global(); + let mut number = 2_u64; + loop { + let suffix = format!(" {number}"); + let stem: String = base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())).collect(); + let name = format!("{}{suffix}", stem.trim_end()); + if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str()) + && !reserved.contains(&name.to_lowercase()) + && !db.has_installed_family(&name) + { + return Ok(name); + } + number = number.checked_add(1).ok_or_else(|| bad(cmd, "no free name for a placed composite font"))?; + } +} + +/// Plan used incoming definitions before changing either document or the font database. +/// Keep existing meanings even for an uninstalled family that destination art still names. +pub(super) fn plan_import(source: Vec, source_families: BTreeSet, target: &Document, cmd: &str) -> Result { + if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX { + return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); + } + let mut source_names = BTreeSet::new(); + for font in &source { + font.check().map_err(|why| bad(cmd, why))?; + if !source_names.insert(font.name.to_lowercase()) { + return Err(bad(cmd, format!("two incoming composite fonts are named `{}`", font.name))); + } + } + let target_families = family_names(target)?; + let mut target_taken = target_families.clone(); + for font in target.composite_fonts.iter() { + target_taken.insert(font.name.to_lowercase()); + target_taken.extend(font.part_fonts().map(str::to_lowercase)); + } + let mut reserved = source_families; + reserved.extend(target_families); + for font in source.iter().chain(target.composite_fonts.iter()) { + reserved.insert(font.name.to_lowercase()); + reserved.extend(font.part_fonts().map(str::to_lowercase)); + } + let db = FontDb::global(); + let mut names = BTreeMap::new(); + let mut combined = target.composite_fonts.to_vec(); + for font in source { + let equivalent = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom; + let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equivalent); + let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name)); + if needs_alias { + // A repeated import reuses its already-installed equal alias. + reused = target.composite_fonts.iter().find(equivalent); + } + let name = match reused { + Some(other) => other.name.clone(), + None if needs_alias => composite_alias(&font.name, &reserved, cmd)?, + None => font.name.clone(), + }; + reserved.insert(name.to_lowercase()); + names.insert(font.name.to_lowercase(), name.clone()); + if reused.is_none() { + combined.push(CompositeFont { name, ..font }); + } + } + // A source document may currently lend fonts to the database. Validate the prospective + // document, not composite names temporarily registered by a different document. + if combined.len() > COMPOSITE_FONTS_MAX { + return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); + } + if let Some(font) = combined.iter().find(|font| db.has_installed_family(&font.name)) { + return Err(bad(cmd, format!("`{}` is the name of an installed font", font.name))); + } + if CompositeFont::usable(&combined).is_some() { + return Err(bad(cmd, "the composite fonts in the placed art and document cannot stand together")); + } + Ok(CompositeImport { names, combined }) +} + /// Register the active document's composite fonts in the font database, and remove the ones the /// other open documents (or an earlier active document) defined. Run after each command and when /// another document takes the front, so an undo, a revert, an opened or closed file or a document diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 5d849cfed2..60a7aaba29 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -5,6 +5,7 @@ //! own stacks, groups and layers included (layers through `ids`), or with `target: "contents"` //! the objects inside them (see `appearance`). +use std::collections::HashSet; use std::sync::Arc; use serde_json::{Value, json}; @@ -115,7 +116,7 @@ fn effect_specs() -> Vec { "Move Effect", [], None, - "{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", + "{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (different appearances allow only a reorder within the same shared fill or stroke, or within identical object effect lists; a graph design's art given first still requires equal appearances)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", has_doc, move_effect ), @@ -678,6 +679,35 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&ids) })) } +impl Session { + /// Can the Appearance panel reorder shared effects on the exact subjects it displays? + /// A generated graph design or a selection normalized to different objects has no matching row. + pub fn can_reorder_selected_effects(&self) -> bool { + let Ok(st) = self.doc() else { return false }; + let Ok(roots) = edit_targets(self, &Value::Null, "effect.move") else { return false }; + let selected: HashSet<_> = st.selection.subjects().iter().copied().collect(); + roots.len() == selected.len() && roots.iter().all(|id| selected.contains(id) && st.doc.is_editable(*id)) + } +} + +/// Resolves a same-list reorder for objects whose appearances differ. Every object must share the +/// complete ordered object effect list or the same fill/stroke row, with its effects, before editing. +fn shared_reorder_slots(d: &Document, ids: &[NodeId], source: ItemTarget, anchor: usize) -> Option>> { + let mut seen = HashSet::with_capacity(ids.len()); + let mut appearances: Vec<&vectorcraft_doc::Appearance> = + ids.iter().map(|id| d.node(*id).filter(|_| seen.insert(*id) && d.is_editable(*id)).map(|n| &*n.appearance)).collect::>()?; + let first = *appearances.get(anchor)?; + if source == ItemTarget::Top { + return appearances.iter().all(|ap| ap.effects == first.effects).then(|| vec![None; appearances.len()]); + } + let item = source.effects_item(first, "effect.move").ok()??; + appearances.swap(0, anchor); + let shared = SharedStack::of(&appearances); + let mut slots = (0..appearances.len()).map(|k| shared.item_in(item, k).map(Some)).collect::>>()?; + slots.swap(0, anchor); + Some(slots) +} + /// `effect.move`: moves (with `copy`: copies) effect `from`, or the effects `from` lists as one block in their order, to `to` in its own list or in `toItem`'s. fn move_effect(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.move"; @@ -694,17 +724,30 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src }; let copy = switch_or(p, "copy", false, C)?; let roots = edit_targets(s, p, C)?; - // Where an aligned effect would go in each of several different stacks isn't one place. - if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &roots)) { - return Err(bad(C, "effects of objects whose appearances differ can't be moved together")); - } + let reference = design_reference(s, p, C)?; + let d = &s.doc()?.doc; + let slots = if aligned(p, C)? && super::appearance::appearances_differ(d, &with_reference(reference, &roots)) { + // An omitted item and a numbered item can use different anchors and still name the same row. + let shared = (!copy && reference.is_none()) + .then(|| { + shared_reorder_slots(d, &roots, src, src.anchor(s, &roots)) + .filter(|source| src == dst || shared_reorder_slots(d, &roots, dst, dst.anchor(s, &roots)).as_ref() == Some(source)) + }) + .flatten(); + Some(shared.ok_or_else(|| bad(C, "effects of objects whose appearances differ can't be moved together"))?) + } else { + None + }; // Where the effect landed in each object it moved in, in the order of `ids`. let mut landed = vec![]; let ids = s.edit(if copy { "Duplicate Effect" } else { "Move Effect" }, |d, _| { let mut done = vec![]; - for id in &roots { + for (k, id) in roots.iter().enumerate() { let Some(n) = d.node_mut(*id) else { continue }; - let (si, di) = (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?); + let (si, di) = match &slots { + Some(slots) => (slots[k], slots[k]), + None => (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?), + }; let Some(fx) = n.appearance.effects_mut(si).filter(|fx| from.iter().all(|i| *i < fx.len())) else { continue }; // Taken out from the top down, so the lower positions stay valid; put back in order. let mut taken: Vec = from.iter().rev().filter_map(|&i| if copy { fx.get(i).cloned() } else { Some(fx.remove(i)) }).collect(); diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 7329d2f02d..9d145853b9 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -578,7 +578,7 @@ fn art_of<'a>(nodes: impl Iterator>) -> Vec { } /// The art as one object of `d` (its resources added), at its natural size and position. -fn build(d: &mut Document, l: Loaded, link: Option) -> Node { +fn build(d: &mut Document, l: Loaded, link: Option) -> Result { let mut node = match l.art { Art::Image(img, clip) => { let (sx, sy) = pt_per_px(img.ppi); @@ -613,7 +613,7 @@ fn build(d: &mut Document, l: Loaded, link: Option) -> Node { Art::Text(t) => Node::new(d.alloc_id(), NodeKind::Text(Box::new(text::area_text(t, l.natural, &d.setup)))), Art::Document(s, link, bounding) => document::node(d, &s, link, bounding), Art::Vector { src, mut nodes, clip } => { - adopt::adopt(d, &src, &mut nodes); + adopt::adopt(d, &src, &mut nodes, PLACE)?; let mut children: Vec> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect(); if let Some(r) = clip { children.insert(0, Arc::new(clip_path(d.alloc_id(), r))); @@ -622,7 +622,7 @@ fn build(d: &mut Document, l: Loaded, link: Option) -> Node { } }; node.name = Some(l.name); - node + Ok(node) } /// `node` moved and scaled by `m` as a whole: strokes, effects and pattern tiles go along. @@ -817,22 +817,86 @@ impl Session { if self.doc()?.uid != read.job.doc { return Err(bad(PLACE, NOT_ACTIVE)); } - let params = read.job.params.clone(); if let Some(old) = read.job.old { - let st = self.doc()?; - // Deleted, changed, or another object with its id: an undo that removes the object frees - // its id for the next object made. - if st.doc.node(old) != read.job.replaced.as_ref() { + // Keep the asynchronous target check against the drawing currently on show. + if self.doc()?.doc.node(old) != read.job.replaced.as_ref() { return Err(bad(PLACE, "replace: the object to replace was changed or deleted")); } + } + let params = read.job.params.clone(); + // Provisional reselection and placement are one outside command. Deferring their + // notifications must not make an asynchronous handoff part of an unrelated tool drag. + if self.depth == 0 && !self.previewing && !self.in_tool_actions { + self.command_with_settled_warnings(|s| s.outside_interaction(PLACE, ¶ms, |s| s.place_read_handoff(read, ¶ms))) + } else { + self.place_read_handoff(read, ¶ms) + } + } + + fn place_read_handoff(&mut self, read: PlaceRead, params: &Value) -> Result { + let mut rollback = None; + let mut reselect = None; + if let Some(old) = read.job.old { + let st = self.doc()?; if st.selection.objects != [old] || st.selection.symbol_part.is_some() { - self.execute("select.set", &json!({ "ids": [old.0] }))?; + // Adoption may now fail. Its provisional selection must not escape that error. + rollback = Some(( + self.active, + st.clone(), + self.paint.clone(), + self.fill_active, + self.pending_paint.clone(), + self.active_appearance_item.clone(), + self.batch_paint_docs.clone(), + self.journal.len(), + self.journal.held(), + )); + self.journal.hold(Some(self.journal.first_kept())); + reselect = Some(old); } } - self.place_hand_off = Some(read); - let r = self.execute(PLACE, ¶ms); + let outer_tool_actions = self.in_tool_actions; + if reselect.is_some() { + self.in_tool_actions = true; + } + let result = (|| { + if let Some(old) = reselect { + self.execute("select.set", &json!({ "ids": [old.0] }))?; + } + self.place_hand_off = Some(read); + self.execute(PLACE, params) + })(); self.place_hand_off = None; - r + if let Some((active, before, paint, fill_active, pending, appearance, paint_docs, journal, held)) = rollback { + if result.is_err() { + if let Some(st) = self.docs.iter_mut().find(|st| st.uid == before.uid) { + let revision = st.revision.max(before.revision); + *st = before; + st.revision = revision + 1; + } + self.active = active; + self.paint = paint; + self.fill_active = fill_active; + self.pending_paint = pending; + self.active_appearance_item = appearance; + self.batch_paint_docs = paint_docs; + self.journal.truncate(journal); + for group in self.docs.iter_mut().filter_map(|st| st.undo_group.as_mut()) { + group.journal.retain(|&(n, _)| n < journal); + group.steps.retain(|&(n, _)| n < journal); + } + self.clear_deferred_overlay_cache(); + self.decoded_images.empty(); + self.sync_front_profiles(); + super::compositefonts::sync(self); + } + self.journal.hold(held); + } + if reselect.is_some() { + self.in_tool_actions = outer_tool_actions; + self.after_command(result.is_ok().then_some(PLACE)); + } + result } } @@ -998,7 +1062,7 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")), } let (id, size, slice_ids) = s.edit("Place", |d, sel| { - let mut node = transformed(build(d, loaded, link), m); + let mut node = transformed(build(d, loaded, link)?, m); if let Some((old_image, (_, q, _))) = distorted { node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?; } @@ -1266,7 +1330,7 @@ fn thumbnail_png(l: Loaded, px: f64) -> Result { let natural = l.natural; let mut d = Document::new(natural.width().max(1.0), natural.height().max(1.0)); let layer = d.layers.first().map(|l| l.id); - let node = build(&mut d, l, None); + let node = build(&mut d, l, None)?; d.insert(layer, 0, node)?; let k = px.clamp(1.0, MAX_THUMBNAIL) / natural.width().max(natural.height()).max(1e-9); let png = vectorcraft_render::Renderer::new().render_region(&d, natural, k, false).to_png().map_err(EngineError::Other)?; diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index f64a6a6874..483503f190 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -5,13 +5,16 @@ //! defines differently keeps its colour, unlinked. Text styles are left as they are: the art carries //! its own formatting. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use vectorcraft_brush::{Brush, BrushKind}; use vectorcraft_color::Paint; use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol}; +use super::super::Result; +use super::super::clipboard::SymbolOptions; +use super::super::compositefonts::{CompositeImport, node_families, plan_import}; use super::unique_name; /// Visit `n` and every descendant (children and opacity-mask art) mutably. @@ -52,9 +55,56 @@ fn paint_refs(p: &mut Paint, f: &mut impl FnMut(Ref)) { }); } +/// Visit only the records the shared reader accepted, in their original order. Consuming +/// each accepted record once also leaves ignored duplicate surfaces and capped records alone. +fn accepted_graphic_refs( + list: &mut serde_json::Value, + accepted: Vec, + parse: impl Fn(&serde_json::Value) -> Option, + f: &mut impl FnMut(Ref), +) { + let Some(list) = list.as_array_mut() else { return }; + let mut accepted = accepted.into_iter().peekable(); + for value in list { + let Some(next) = accepted.peek() else { break }; + if parse(value).as_ref() != Some(next) { + continue; + } + let _ = accepted.next(); + if let Some(serde_json::Value::String(symbol)) = value.get_mut("symbol") { + f(Ref::Symbol(symbol)); + } + } +} + +/// Symbol references in accepted Graphics and Map Art records, including fill/stroke effects. +/// Each stored name is visited once, so a rename cannot feed a second rename in the same map. +fn appearance_graphic_refs(appearance: &mut vectorcraft_doc::Appearance, f: &mut impl FnMut(Ref)) { + use vectorcraft_render::effects as fx; + + if fx::appearance_graphic_symbols(appearance).is_empty() { + return; + } + let (effects, items) = (&mut appearance.effects, &mut appearance.items); + for effect in effects.iter_mut().chain(items.iter_mut().flat_map(|item| item.effects_mut())) { + if fx::takes_graphics(&effect.id) { + let accepted = fx::mapped_graphics(&effect.params); + if let Some(list) = effect.params.get_mut(fx::GRAPHICS) { + accepted_graphic_refs(list, accepted, |value| fx::MappedGraphic::from_value(value).ok(), f); + } + } else if fx::takes_map_art(&effect.id) { + let accepted = fx::surface_maps(&effect.params); + if let Some(list) = effect.params.get_mut(fx::MAP_ART) { + accepted_graphic_refs(list, accepted, |value| fx::SurfaceMap::from_value(value).ok(), f); + } + } + } +} + /// Every resource reference in `n` and its descendants. fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) { each_mut(n, &mut |n| { + appearance_graphic_refs(&mut n.appearance, f); for it in &mut n.appearance.items { match it { AppearanceItem::Fill(fl) => paint_refs(&mut fl.paint, f), @@ -71,6 +121,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) { for r in &mut t.runs { paint_refs(&mut r.style.fill, f); paint_refs(&mut r.style.stroke, f); + if let Some(inline) = &mut r.inline { + f(Ref::Symbol(&mut inline.symbol)); + } } if let Some(fonts) = &mut t.file_fonts { fonts.map_keys(|key| f(Ref::Image(key))); @@ -81,6 +134,14 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) { NodeKind::SymbolInstance { symbol, .. } => f(Ref::Symbol(symbol)), _ => {} } + if let Some(extras) = n.extras_if_any() { + extras + .symbol_overrides + .iter_mut() + .flat_map(|override_| [&mut override_.fill, &mut override_.stroke]) + .flatten() + .for_each(|paint| paint_refs(paint, f)); + } // A color-masked image's masked pixels come along, and the key they were made from // follows the image's. if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) { @@ -162,7 +223,16 @@ fn canon(dst: &Document, n: &Node) -> Node { own.images.insert(k.clone(), blob.clone()); } } - own.reid(n) + let mut canonical = own.reid(n); + // Derived layout caches do not define the stored art's resource identity. + each_mut(&mut canonical, &mut |node| { + if let NodeKind::Text(text) = &mut node.kind { + text.cached_bounds = None; + text.cached_baselines.clear(); + text.cached_ink = None; + } + }); + canonical } /// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])? @@ -220,12 +290,273 @@ fn brush_art(b: &mut Brush) -> Vec<&mut Node> { } } -/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point -/// `nodes` at the names they got. -pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { +/// Apply the final resource-name plan to one incoming reference. +fn rename_ref(r: Ref<'_>, maps: [&Renames; 5]) { + let (map, key) = match r { + Ref::Image(key) => (maps[0], key), + Ref::Symbol(key) => (maps[1], key), + Ref::Pattern(key) => (maps[2], key), + Ref::Brush(key) => (maps[3], key), + Ref::Swatch(link) => { + if let Some((new, _)) = link.as_deref().and_then(|key| maps[4].get(key)) { + *link = new.clone(); + } + return; + } + }; + if let Some((Some(new), _)) = map.get(key.as_str()) { + *key = new.clone(); + } +} + +#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] +enum ResourceKind { + Symbol, + Pattern, + Brush, +} + +type ResourceKey = (ResourceKind, String); + +/// A source definition's dependencies whose planned names have not been finalized yet. +fn pending_dependencies(key: &ResourceKey, src: &Document, brushes: &[Brush], pending: &BTreeSet) -> BTreeSet { + let mut dependencies = BTreeSet::new(); + let mut note = |r: Ref<'_>| { + let key = match r { + Ref::Symbol(name) => (ResourceKind::Symbol, name.clone()), + Ref::Pattern(name) => (ResourceKind::Pattern, name.clone()), + Ref::Brush(name) => (ResourceKind::Brush, name.clone()), + Ref::Image(_) | Ref::Swatch(_) => return, + }; + if pending.contains(&key) { + dependencies.insert(key); + } + }; + match key.0 { + ResourceKind::Symbol => { + if let Some(symbol) = src.symbols.iter().find(|symbol| symbol.name == key.1) { + refs(&mut (*symbol.art).clone(), &mut note); + } + } + ResourceKind::Pattern => { + if let Some(pattern) = src.pattern(&key.1) { + for art in &pattern.art { + refs(&mut (**art).clone(), &mut note); + } + } + } + ResourceKind::Brush => { + if let Some(mut brush) = brushes.iter().find(|brush| brush.name == key.1).cloned() { + for art in brush_art(&mut brush) { + refs(art, &mut note); + } + } + } + } + dependencies +} + +/// Prefer the original name, then only canonical numbered variants from `unique_name`. +/// A free original name keeps its planned copy; another incoming name is never stolen. +fn matching_name(base: &str, definitions: &[T], used: &[String], name: impl Fn(&T) -> &str, same: impl Fn(&T) -> bool) -> Option { + let original = definitions.iter().find(|definition| name(definition) == base)?; + if same(original) { + return Some(base.to_string()); + } + let prefix = format!("{base} "); + let mut seen = BTreeSet::new(); + let mut aliases: Vec<_> = definitions + .iter() + .filter_map(|definition| { + let candidate = name(definition); + // Match the first definition, as the document name lookups do. + if !seen.insert(candidate.to_string()) { + return None; + } + let suffix = candidate.strip_prefix(&prefix)?; + if suffix.starts_with('0') || !suffix.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + let number = suffix.parse::().ok()?; + (number >= 2 && !used.iter().any(|used| used == candidate)).then_some((number, definition)) + }) + .collect(); + aliases.sort_unstable_by_key(|(number, _)| *number); + aliases.into_iter().find_map(|(_, definition)| same(definition).then(|| name(definition).to_string())) +} + +/// Compare final incoming content, not the original references or destination's resource name. +fn reusable_name( + key: &ResourceKey, + dst: &Document, + src: &Document, + src_brushes: &[Brush], + dst_brushes: &[Brush], + used: &Used, + maps: [&Renames; 5], +) -> Option { + match key.0 { + ResourceKind::Symbol => { + let source = src.symbols.iter().find(|symbol| symbol.name == key.1)?; + let mut incoming = source.clone(); + refs(Arc::make_mut(&mut incoming.art), &mut |r| rename_ref(r, maps)); + matching_name( + &key.1, + &dst.symbols, + &used.symbols, + |symbol| &symbol.name, + |candidate| { + let mut normalized = candidate.clone(); + normalized.name = incoming.name.clone(); + same_symbol(dst, &normalized, &incoming) && SymbolOptions::of(dst, &candidate.name) == SymbolOptions::of(src, &source.name) + }, + ) + } + ResourceKind::Pattern => { + let mut incoming = src.pattern(&key.1)?.clone(); + for art in &mut incoming.art { + refs(Arc::make_mut(art), &mut |r| rename_ref(r, maps)); + } + matching_name( + &key.1, + &dst.patterns, + &used.patterns, + |pattern| &pattern.name, + |candidate| { + let mut normalized = candidate.clone(); + normalized.name = incoming.name.clone(); + same_pattern(dst, &normalized, &incoming) + }, + ) + } + ResourceKind::Brush => { + let mut incoming = src_brushes.iter().find(|brush| brush.name == key.1)?.clone(); + for art in brush_art(&mut incoming) { + refs(art, &mut |r| rename_ref(r, maps)); + *art = canon(dst, art); + } + matching_name( + &key.1, + dst_brushes, + &used.brushes, + |brush| &brush.name, + |candidate| { + let mut normalized = candidate.clone(); + normalized.name = incoming.name.clone(); + for art in brush_art(&mut normalized) { + *art = canon(dst, art); + } + normalized == incoming + }, + ) + } + } +} + +/// Finalize each copied definition only after its copied dependencies. Each key/edge is +/// processed once; a cycle (and its unresolved parents) conservatively keeps the planned copies. +fn reuse_remapped_resources( + dst: &Document, + src: &Document, + src_brushes: &[Brush], + dst_brushes: &[Brush], + used: &Used, + fixed: [&Renames; 2], + changing: [&mut Renames; 3], +) { + let [symbols, patterns, brushes] = changing; + let mut pending = BTreeSet::new(); + for (kind, map) in [(ResourceKind::Symbol, &*symbols), (ResourceKind::Pattern, &*patterns), (ResourceKind::Brush, &*brushes)] { + pending.extend(map.iter().filter(|(_, (_, copy))| *copy).map(|(name, _)| (kind, name.clone()))); + } + let mut waiting = BTreeMap::new(); + let mut parents: BTreeMap> = BTreeMap::new(); + let mut ready = BTreeSet::new(); + for key in &pending { + let dependencies = pending_dependencies(key, src, src_brushes, &pending); + if dependencies.is_empty() { + ready.insert(key.clone()); + } + waiting.insert(key.clone(), dependencies.len()); + for dependency in dependencies { + parents.entry(dependency).or_default().push(key.clone()); + } + } + while let Some(key) = ready.pop_first() { + let maps = [fixed[0], &*symbols, &*patterns, &*brushes, fixed[1]]; + if let Some(name) = reusable_name(&key, dst, src, src_brushes, dst_brushes, used, maps) { + let map = match key.0 { + ResourceKind::Symbol => &mut *symbols, + ResourceKind::Pattern => &mut *patterns, + ResourceKind::Brush => &mut *brushes, + }; + map.insert(key.1.clone(), (Some(name), false)); + } + for parent in parents.remove(&key).into_iter().flatten() { + if let Some(count) = waiting.get_mut(&parent) { + *count -= 1; + if *count == 0 { + ready.insert(parent); + } + } + } + } +} + +/// Remap only incoming users before resource equality decides whether to share or copy. +/// Report actual family renaming for the final copied-resource reuse phase. +fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, brushes: &mut [Brush], plan: &CompositeImport) -> (Document, bool) { + let mut staged = src.clone(); + let mut aliased = false; + for node in nodes.iter_mut() { + each_mut(node, &mut |node| { + node_families(node, &mut |family| { + aliased |= plan.rename(family); + }); + }); + } + for symbol in staged.symbols.iter_mut().filter(|symbol| used.symbols.contains(&symbol.name)) { + each_mut(Arc::make_mut(&mut symbol.art), &mut |node| { + node_families(node, &mut |family| { + aliased |= plan.rename(family); + }); + }); + } + for pattern in staged.patterns.iter_mut().filter(|pattern| used.patterns.contains(&pattern.name)) { + for art in &mut pattern.art { + each_mut(Arc::make_mut(art), &mut |node| { + node_families(node, &mut |family| { + aliased |= plan.rename(family); + }); + }); + } + } + for brush in brushes.iter_mut().filter(|brush| used.brushes.contains(&brush.name)) { + for art in brush_art(brush) { + each_mut(art, &mut |node| { + node_families(node, &mut |family| { + aliased |= plan.rename(family); + }); + }); + } + } + (staged, aliased) +} + +/// Discover the incoming resource frontier and its composite-font users before planning +/// names or changing either document. Resource order and the no-composite fast path stay shared. +fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec, BTreeSet) { let mut used = Used::default(); + let composites = !src.composite_fonts.is_empty(); + let mut families = BTreeSet::new(); + let mut note_family = |name: &mut String| { + families.insert(name.to_lowercase()); + }; for n in nodes.iter_mut() { refs(n, &mut |r| used.note(r)); + if composites { + each_mut(n, &mut |node| node_families(node, &mut note_family)); + } } let src_brushes = vectorcraft_brush::library(src); // Symbol, pattern and brush art and tint swatches can use more resources (the lists grow while @@ -254,8 +585,29 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { } for mut a in art { refs(&mut a, &mut |r| used.note(r)); + if composites { + each_mut(&mut a, &mut |node| node_families(node, &mut note_family)); + } } } + (used, src_brushes, families) +} + +/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point +/// `nodes` at the names they got. +pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> { + let (used, mut src_brushes, families) = collect_resources(src, nodes); + let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::>(); + // All representability/validation errors precede incoming or destination mutation. + let plan = if fonts.is_empty() { None } else { Some(plan_import(fonts, families, dst, cmd)?) }; + let staged; + let mut aliased = false; + let src = if let Some(plan) = &plan { + (staged, aliased) = remap_composite_families(src, nodes, &used, &mut src_brushes, plan); + &staged + } else { + src + }; let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c)); // Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it @@ -264,7 +616,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { &used.symbols, |n| src.symbols.iter().find(|s| s.name == n), |n| dst.symbols.iter().find(|s| s.name == n), - |a, b| same_symbol(dst, a, b), + |a, b| same_symbol(dst, a, b) && SymbolOptions::of(dst, &a.name) == SymbolOptions::of(src, &b.name), |c| dst.symbols.iter().any(|s| s.name == c), ); let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some()); @@ -330,23 +682,14 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c)); } - let mut rename = |r: Ref| { - let (map, k) = match r { - Ref::Image(k) => (&images, k), - Ref::Symbol(k) => (&symbols, k), - Ref::Pattern(k) => (&patterns, k), - Ref::Brush(k) => (&brushes, k), - Ref::Swatch(link) => { - if let Some((new, _)) = link.as_deref().and_then(|k| swatches.get(k)) { - *link = new.clone(); - } - return; - } - }; - if let Some((Some(new), _)) = map.get(k.as_str()) { - *k = new.clone(); - } - }; + if aliased || symbols.values().any(|(_, copy)| *copy) { + reuse_remapped_resources(dst, src, &src_brushes, &dst_brushes, &used, [&images, &swatches], [&mut symbols, &mut patterns, &mut brushes]); + } + + if let Some(plan) = plan { + dst.composite_fonts = plan.combined.into(); + } + let mut rename = |r: Ref| rename_ref(r, [&images, &symbols, &patterns, &brushes, &swatches]); for n in nodes.iter_mut() { refs(n, &mut rename); } @@ -375,6 +718,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { // The art takes ids of `dst`: those of `src` may name objects of `dst` already. def.art = Arc::new(dst.reid(&def.art)); dst.symbols.push(def); + SymbolOptions::of(src, old).give(dst, new); } } for (old, new) in copies(&patterns) { @@ -406,4 +750,5 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { dst.swatches.push(w); } } + Ok(()) } diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index f24242ed70..fe9279ac69 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -178,6 +178,10 @@ fn opened_document_art( super::super::links::resolve(&mut l.doc, super::super::links::LinkBase::file(path), false, false); } l.doc.drop_edit_modes(); + // Measure and crop in this source's composite fonts, not those of the front document. + // The existing thread-local loan restores its caller's context on every return or unwind. + let source_fonts = l.doc.composite_fonts.clone(); + let _source_fonts = vectorcraft_text::FontDb::global().lend_document_composite_fonts(&source_fonts); // The native file does not store type's layout bounds. Measure them before cropping or // copying the art, so the placed group keeps the positions of aligned point type. for warning in crate::Session::refresh_text_bounds(&mut l.doc) { @@ -544,7 +548,7 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> { let a = document_art(p.link.name(), &bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, cmd)?; let m = p.art_xf(a.frame).ok_or_else(|| bad(cmd, format!("object {} has no size", id.0)))?; let mut nodes = a.nodes; - super::adopt::adopt(d, &a.doc, &mut nodes); + super::adopt::adopt(d, &a.doc, &mut nodes, cmd)?; let mut children: Vec> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect(); if let Some(r) = a.clip { children.insert(0, Arc::new(super::clip_path(d.alloc_id(), r))); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f0c1e2dc53..7b6b840682 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -5,6 +5,7 @@ //! server all go through [`Session::execute`]. Tools (pointer gestures) are hosted here too and //! reduce to commands, so every gesture is journaled and replayable. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod cmd; pub mod file_access; diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 05908c8616..12f8cbe879 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -661,6 +661,7 @@ impl Session { self.pending_paint = None; // The previous preview's Assign Profile is undone with it. self.sync_front_profiles(); + cmd::compositefonts::sync(self); let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params)); let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p)); // A selected object's converted appearance must not replace the current paints while @@ -877,6 +878,7 @@ impl Session { deselect_hidden(&menu, &st.doc, &mut st.selection); // A canceled preview's Assign Profile is undone with it. self.sync_front_profiles(); + cmd::compositefonts::sync(self); // With New Art Has Basic Appearance off, new art takes the appearance of the selection as // the document has it again, not as a preview left it. An interaction that changed only the // defaults (`defaultsOnly: true`) leaves the defaults it began with. diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 94b943120a..25a9b278b1 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -25,6 +25,12 @@ fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value { } impl Session { + /// Run a command callback and keep warnings from every preview it settles or restores. + pub(crate) fn command_with_settled_warnings(&mut self, f: impl FnOnce(&mut Self) -> Result) -> Result { + let (r, settled) = self.collect_settled_warnings(f); + r.map(|v| with_settled_warnings(v, &settled)) + } + /// `spec`'s `enabled` with `ids` selected instead of the selection, which is then put back. fn enabled_with_selection(&mut self, spec: &CommandSpec, ids: Vec) -> std::result::Result<(), String> { let Some(d) = self.active_mut() else { return (spec.enabled)(self) }; @@ -121,10 +127,9 @@ impl Session { // A preview that a top-level command applied first (a drag with Real-time Drawing off, kept // before Undo) reports its warning in the command's result. let r = if self.depth == 0 { - let (r, settled) = self.collect_settled_warnings(|s| { + self.command_with_settled_warnings(|s| { if outside { s.outside_interaction(id, params, |s| s.execute_spec(spec, id, params)) } else { s.execute_spec(spec, id, params) } - }); - r.map(|v| with_settled_warnings(v, &settled)) + }) } else { self.execute_spec(spec, id, params) }; @@ -253,6 +258,10 @@ impl Session { // after an undone or redone Assign Profile, a failed or panicked command's documents put // back, and a batch step, before the next step converts through them. self.sync_front_profiles(); + if self.depth != 0 { + // The next batch step can measure/outline definitions this step adopted. + cmd::compositefonts::sync(self); + } if r.is_err() && self.depth == 0 { self.batch_paint_docs.clear(); // A failed or panicked command's documents are put back: type is drawn in their diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index b967e6e3ed..8cb96c6a8a 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -888,6 +888,44 @@ fn apply_reports_the_index_in_the_object_whose_row_it_names() { assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(1)), "a's row 0 holds two effects"); } +#[test] +fn aligned_effect_move_uses_the_shared_fill_or_stroke_in_each_target() { + let mut s = session(); + let (a, b) = reversed_pair(&mut s); + for (id, item) in [(a, 1), (b, 2)] { + for effect in ["distort.twist", "distort.roughen"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "item": item, "effect": effect})); + } + } + run(&mut s, "select.set", json!({"ids": [b.0, a.0]})); + let appearances = |s: &Session| [a, b].map(|id| node(s, id).appearance.clone()); + let before = appearances(&s); + for (params, reply_item) in [(json!({"from": 1, "to": 0, "aligned": true}), 2), (json!({"from": 1, "to": 0, "toItem": 1, "aligned": true}), 1)] { + run(&mut s, "appearance.setActiveItem", json!({"index": 2})); + let moved = run(&mut s, "effect.move", params); + assert_eq!(moved["item"], json!(reply_item), "the reply addresses the destination's anchor"); + assert_eq!(moved["index"], json!(0)); + for (appearance, item) in appearances(&s).iter().zip([1, 2]) { + let ids: Vec<_> = appearance.effects_at(Some(item)).unwrap().iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, ["distort.roughen", "distort.twist"]); + assert!(appearance.effects_at(Some(0)).unwrap().is_empty()); + } + run(&mut s, "edit.undo", json!({})); + assert_eq!(appearances(&s), before); + } + + run(&mut s, "appearance.setActiveItem", json!({"index": 2})); + for destination in [0, 2] { + assert!(s.execute("effect.move", &json!({"from": 1, "to": 0, "toItem":destination, "aligned":true})).is_err()); + assert_eq!(appearances(&s), before, "a different or invalid destination must not change either list"); + } + + run(&mut s, "effect.apply", json!({"ids": [a.0], "item": 1, "effect": "stylize.feather"})); + let before = appearances(&s); + assert!(s.execute("effect.move", &json!({"ids": [b.0, a.0], "fromItem": 2, "from": 1, "to": 0, "aligned": true})).is_err()); + assert_eq!(appearances(&s), before, "no effect moves if a target lacks the shared row"); +} + /// `effect.move`'s reply names where the effect landed in the object whose row the active item is /// (the first selected object), also when that object paints above the others. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 05dde4c156..37d1282f26 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -409,11 +409,14 @@ impl Session { /// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when /// the Selection tool keeps a Cmd press on a selected object to select the object behind it /// (Selection & Anchor Display › Command Click to Select Objects Behind), which an earlier Cmd - /// press armed ([`Self::behind_armed`]). + /// press armed ([`Self::behind_armed`]); none either when the active tool keeps the press + /// ([`vectorcraft_tools::Tool::keeps_cmd_press`]), as Direct Selection keeps one on a shown + /// direction handle to mirror the opposite handle. fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> { let id = self.lent_tool(self.tool.id(), mods)?; let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p)); - (!behind).then_some(id) + let kept = !behind && self.with_tool_cx(view, |t, cx| t.keeps_cmd_press(cx, p, *mods)); + (!behind && !kept).then_some(id) } /// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks diff --git a/crates/engine/tests/it/direct_handle_mirror.rs b/crates/engine/tests/it/direct_handle_mirror.rs index bfe8db75a0..732319f675 100644 --- a/crates/engine/tests/it/direct_handle_mirror.rs +++ b/crates/engine/tests/it/direct_handle_mirror.rs @@ -332,6 +332,70 @@ fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() { assert_eq!(s.doc().unwrap().history.undo.len(), before.undo); } +#[test] +fn direct_handle_cmd_held_before_pressing_a_handle_mirrors_instead_of_moving_the_path() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = node(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + let end = Point::new(180.0, 100.0); + pointer(&mut s, PointerKind::Down, end, cmd()); + assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a shown handle is not lent to the Selection tool"); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(s.tool_id(), "directSelection"); +} + +#[test] +fn direct_handle_cmd_shift_held_before_pressing_a_handle_constrains_and_mirrors() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = node(&s, id); + let p = anchor(&s, id).p; + let shifted = Mods { shift: true, ..cmd() }; + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), shifted); + assert_eq!(s.tool_id(), "directSelection"); + let raw = Point::new(180.0, 150.0); + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(anchor(&s, id), constrained(p, raw), AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, raw, shifted); +} + +#[test] +fn direct_handle_cmd_press_on_a_handle_under_a_bounding_box_handle_still_lends_selection() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + // A second object widens the selection's bounding box so its top-middle handle lands on the + // curve's outgoing handle end at (180, 100). + let rect = run(&mut s, "path.create", json!({"anchors": [{"x": 330, "y": 150}, {"x": 340, "y": 150}, {"x": 340, "y": 200}], "closed": true})); + run(&mut s, "select.set", json!({"ids": [id.0, rect["id"]]})); + let boxed = ViewInfo { show_bbox: true, ..view() }; + let end = Point::new(180.0, 100.0); + s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y).with_mods(cmd()), boxed).unwrap(); + assert_eq!(s.tool_id(), "selection", "the bounding box handle keeps the press for the lent Selection tool"); + s.pointer(&PointerEvent::new(PointerKind::Up, end.x, end.y).with_mods(cmd()), boxed).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); +} + +#[test] +fn direct_handle_cmd_alt_before_pressing_a_handle_still_lends_group_selection() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let a = anchor(&s, id); + let both = Mods { alt: true, ..cmd() }; + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), both); + assert_eq!(s.tool_id(), "groupSelection", "Cmd+Alt keeps its Group Selection loan on a handle"); + pointer(&mut s, PointerKind::Up, Point::new(180.0, 100.0), both); + assert_eq!(s.tool_id(), "directSelection"); + assert_eq!(anchor(&s, id), a); +} + #[test] fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() { let mut s = session(); @@ -490,6 +554,22 @@ fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() { assert_content(&s, &after); } +#[test] +fn direct_handle_cmd_held_before_pressing_a_blend_spine_handle_mirrors() { + let mut s = session(); + let id = blend(&mut s); + let (a, keys, _) = blend_state(&s, id); + pointer(&mut s, PointerKind::Down, a.h_out, cmd()); + assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a spine handle is not lent to the Selection tool"); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + pointer(&mut s, PointerKind::Up, q, cmd()); + let (after, after_keys, _) = blend_state(&s, id); + near(after.p, a.p); + assert_mirrored(after, q, AnchorKind::Smooth); + assert_eq!(after_keys, keys, "the key objects did not move"); +} + #[test] fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() { let mut s = session(); diff --git a/crates/engine/tests/it/several_handles.rs b/crates/engine/tests/it/several_handles.rs index 7b5469c278..45b2e39f19 100644 --- a/crates/engine/tests/it/several_handles.rs +++ b/crates/engine/tests/it/several_handles.rs @@ -119,6 +119,78 @@ fn picked_handles_stay_picked_after_they_are_dragged() { near(anchor(&s, id, 2).h_in, Point::new(310.0, 170.0)); } +/// With two handles picked, Cmd/Ctrl held before the press on one of them drags that handle alone +/// and mirrors its opposite handle; the other picked handle stays where it is. +#[test] +fn a_cmd_drag_of_one_of_two_picked_handles_mirrors_its_opposite_handle() { + let (mut s, id) = session(); + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + click(&mut s, Point::new(300.0, 140.0), shift()); + let cmd = Mods { cmd: true, ..Mods::default() }; + drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd); + assert_eq!(s.tool_id(), "directSelection"); + let a = anchor(&s, id, 1); + near(a.h_out, Point::new(180.0, 160.0)); + near(a.h_in, Point::new(20.0, 40.0)); + assert_eq!(a.kind, AnchorKind::Smooth); + near(anchor(&s, id, 2).h_in, Point::new(300.0, 140.0)); +} + +/// Both handles stay picked after a Cmd/Ctrl drag of one of them: a drag of the other without +/// Cmd/Ctrl then moves both. +#[test] +fn picked_handles_stay_picked_after_a_cmd_drag_of_one_of_them() { + let (mut s, id) = session(); + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + click(&mut s, Point::new(300.0, 140.0), shift()); + let cmd = Mods { cmd: true, ..Mods::default() }; + drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd); + drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default()); + near(anchor(&s, id, 1).h_out, Point::new(190.0, 160.0)); + near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0)); +} + +/// Both handles stay picked after a Cmd/Ctrl+Shift drag of one of them, and after Escape during +/// one. +#[test] +fn picked_handles_stay_picked_after_a_cmd_shift_drag_of_one_of_them() { + for escape in [false, true] { + let (mut s, id) = session(); + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + click(&mut s, Point::new(300.0, 140.0), shift()); + let cmd_shift = Mods { cmd: true, shift: true, ..Mods::default() }; + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd_shift); + pointer(&mut s, PointerKind::Drag, Point::new(220.0, 100.0), cmd_shift); + if escape { + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + } + pointer(&mut s, PointerKind::Up, Point::new(220.0, 100.0), cmd_shift); + let x = if escape { 180.0 } else { 220.0 }; + near(anchor(&s, id, 1).h_out, Point::new(x, 100.0)); + drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default()); + near(anchor(&s, id, 1).h_out, Point::new(x + 10.0, 100.0)); + near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0)); + } +} + +/// Escape during a Cmd/Ctrl drag of one of two picked handles puts the handle back and leaves both +/// picked. +#[test] +fn escape_during_a_cmd_drag_of_a_picked_handle_keeps_both_picked() { + let (mut s, id) = session(); + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + click(&mut s, Point::new(300.0, 140.0), shift()); + let cmd = Mods { cmd: true, ..Mods::default() }; + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd); + pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + pointer(&mut s, PointerKind::Up, Point::new(180.0, 160.0), cmd); + near(anchor(&s, id, 1).h_out, Point::new(180.0, 100.0)); + drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default()); + near(anchor(&s, id, 1).h_out, Point::new(190.0, 100.0)); + near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0)); +} + /// A Shift-click on a picked handle takes it away, and Escape lets every picked handle go: a drag /// then moves only the handle pressed. #[test] diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs new file mode 100644 index 0000000000..55f1f4976f --- /dev/null +++ b/crates/engine/tests/native_composite_adoption.rs @@ -0,0 +1,1343 @@ +//! Native placement must keep the composite fonts its editable art uses, without changing the destination's meanings. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::Path; +use std::sync::{Mutex, MutexGuard}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{CompositeFont, Document, Node, NodeId, NodeKind}; +use vectorcraft_engine::Session; +use vectorcraft_testkit::TempDir; +use vectorcraft_text::FontDb; + +struct FontContext { + fonts: Vec, + _lock: MutexGuard<'static, ()>, +} + +impl FontContext { + fn hold() -> Self { + static LOCK: Mutex<()> = Mutex::new(()); + let lock = LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let db = FontDb::global(); + assert!(db.face("Source Sans 3", "Regular").is_some(), "CONTROL: the bundled test face is available"); + Self { fonts: registered_fonts(), _lock: lock } + } +} + +impl Drop for FontContext { + fn drop(&mut self) { + let db = FontDb::global(); + for name in db.composite_font_names() { + if CompositeFont::named(&self.fonts, &name).is_none() { + db.remove_composite_font(&name); + } + } + for font in &self.fonts { + db.set_composite_font(font); + } + } +} + +fn registered_fonts() -> Vec { + let db = FontDb::global(); + db.composite_font_names().iter().map(|name| (*db.composite_font(name).unwrap()).clone()).collect() +} + +fn document(session: &Session) -> &Document { + &session.doc().expect("CONTROL: an active document").doc +} + +fn destination(fonts: &[CompositeFont]) -> Session { + let mut session = Session::new(); + session.add_document(Document::new(100.0, 80.0), None); + session.execute("type.compositeFonts.set", &json!({"fonts": fonts})).unwrap(); + session +} + +fn font_document(font: &CompositeFont) -> Document { + let unused = CompositeFont::new(format!("{} Unused", font.name), "Source Sans 3", "Regular"); + let mut session = destination(&[font.clone(), unused]); + session.execute("text.create", &json!({"x": 4, "y": 16, "text": "Ab", "font": font.name})).unwrap(); + let doc = document(&session).clone(); + // Leave the fixture's name cold through an ordinary public edit, not a registry injection. + session.execute("type.compositeFonts.set", &json!({"fonts": []})).unwrap(); + doc +} + +fn write_native(path: &Path, source: &Document) -> Document { + let options = vectorcraft_format::SaveOptions { include_linked: true, precision: None, ..Default::default() }; + let bytes = vectorcraft_format::save_with(source, &options).unwrap(); + std::fs::write(path, &bytes).unwrap(); + let loaded = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(loaded.composite_fonts, source.composite_fonts, "CONTROL: native fixture keeps its definitions"); + loaded +} + +fn place(session: &mut Session, path: &Path, linked: bool) -> NodeId { + let reply = session.execute("file.place", &json!({"path": path, "link": linked, "at": [30, 25]})).unwrap(); + assert_eq!(reply["linked"], linked, "CONTROL: the intended public placement route"); + let id = NodeId(reply["ids"][0].as_u64().unwrap()); + if linked { + session.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + } + id +} + +fn placed_family(session: &Session, id: NodeId) -> String { + let root = document(session).node(id).unwrap(); + let mut families = Vec::new(); + root.walk(&mut |node| { + if let NodeKind::Text(text) = &node.kind { + families.extend(text.runs.iter().filter(|run| run.text == "Ab").map(|run| run.style.font_family.clone())); + } + }); + assert_eq!(families.len(), 1, "CONTROL: the one source lettering run remains editable"); + families.pop().unwrap() +} + +fn kept_text(session: &mut Session, font: &CompositeFont) -> (NodeId, Node) { + let reply = session.execute("text.create", &json!({"x": 2, "y": 12, "text": "Destination", "font": font.name})).unwrap(); + let id = NodeId(reply["id"].as_u64().unwrap()); + (id, document(session).node(id).unwrap().clone()) +} + +#[test] +fn native_composite_meanings_survive_editable_and_embedded_placement() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite"); + let path = dir.join("lettering.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionLettering", "Source Sans 3", "Regular"); + write_native(&path, &font_document(&incoming)); + for linked in [false, true] { + // No definition, an exact-name equal definition, and an exact-name conflicting definition. + for state in 0..3 { + let mut existing = incoming.clone(); + if state == 2 { + existing.parts.roman.size = 125.0; + } + let mut fonts = Vec::new(); + if state == 1 { + fonts.push(CompositeFont { name: "NativeAdoptionEquivalentOtherName".into(), ..incoming.clone() }); + } + if state != 0 { + fonts.push(existing.clone()); + } + let mut session = destination(&fonts); + let kept = (state != 0).then(|| kept_text(&mut session, &existing)); + let id = place(&mut session, &path, linked); + let name = placed_family(&session, id); + let imported = CompositeFont::named(&document(&session).composite_fonts, &name) + .expect("REGRESSION: editable native art must retain the meaning of its named composite font"); + assert_eq!((&imported.parts, &imported.custom), (&incoming.parts, &incoming.custom)); + assert_eq!(CompositeFont::same_name(&name, &incoming.name), state != 2); + assert_eq!(document(&session).composite_fonts.len(), if state == 0 { 1 } else { 2 }); + if let Some((id, art)) = kept { + assert_eq!(document(&session).node(id), Some(&art)); + assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &existing.name), Some(&existing)); + } + } + } +} + +#[test] +fn native_composite_alias_is_reused_without_changing_destination_art() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-repeat"); + let path = dir.join("lettering.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionRepeated", "Source Sans 3", "Regular"); + write_native(&path, &font_document(&incoming)); + for linked in [false, true] { + let mut existing = incoming.clone(); + existing.parts.roman.size = 125.0; + let mut session = destination(std::slice::from_ref(&existing)); + let (kept_id, kept_art) = kept_text(&mut session, &existing); + let first = place(&mut session, &path, linked); + let alias = placed_family(&session, first); + assert!(!CompositeFont::same_name(&alias, &incoming.name), "a real conflict requires an alias"); + let first_definition = CompositeFont::named(&document(&session).composite_fonts, &alias).unwrap().clone(); + let count = document(&session).composite_fonts.len(); + let second = place(&mut session, &path, linked); + assert_eq!(placed_family(&session, second), alias, "repeated art reuses the same meaning, without assuming alias spelling"); + assert_eq!(document(&session).composite_fonts.len(), count); + assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &alias), Some(&first_definition)); + assert_eq!(document(&session).node(kept_id), Some(&kept_art)); + assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &existing.name), Some(&existing)); + } +} + +fn snapshot(session: &Session) -> Value { + let state = session.doc().unwrap(); + json!({"document": &*state.doc, "selection": state.selection, + "undo": state.history.undo.len(), "redo": state.history.redo.len(), + "journal": session.journal.iter().cloned().collect::>(), + "journalFirst": session.journal.first_kept(), "journalHeld": session.journal.held()}) +} + +fn plain_text(session: &Session, id: NodeId) -> String { + let NodeKind::Text(text) = &document(session).node(id).unwrap().kind else { + panic!("CONTROL: the live text object remains"); + }; + text.plain_text() +} + +fn select_type_range(session: &mut Session, id: NodeId) -> (vectorcraft_engine::ViewInfo, Value) { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + let view = vectorcraft_engine::ViewInfo::default(); + session.select_tool("type", view).unwrap(); + let bounds = document(session).bounds_of(&[id], false).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + session.pointer(&PointerEvent::new(kind, bounds.x1 - 1.0, bounds.center().y), view).unwrap(); + } + session.tool_key(ToolKey::Home, Mods::default(), view).unwrap(); + for _ in 0..2 { + session.tool_key(ToolKey::Right, Mods { shift: true, ..Mods::default() }, view).unwrap(); + } + let options = session.tool_options(); + assert_eq!(options["editing"], id.0); + assert_eq!((options["start"].clone(), options["end"].clone()), (json!(0), json!(2))); + assert_eq!(options["typing"], false, "CONTROL: a real selected range, with no pending typing"); + assert!(!session.in_interaction()); + (view, options) +} + +#[test] +fn native_composite_limit_errors_are_atomic_for_place_embed_and_async_replace() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-limit"); + let path = dir.join("one-more-font.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionOneMore", "Source Sans 3", "Regular"); + write_native(&path, &font_document(&incoming)); + let full: Vec<_> = (0..vectorcraft_doc::text::COMPOSITE_FONTS_MAX) + .map(|i| CompositeFont::new(format!("NativeAdoptionHeld{i}"), "Source Sans 3", "Regular")) + .collect(); + for linked in [false, true] { + let mut session = destination(&full); + let (command, params) = if linked { + let placed = session.execute("file.place", &json!({"path": path, "link": true})).unwrap(); + assert_eq!(placed["linked"], true); + ("links.embed", json!({"ids": placed["ids"]})) + } else { + ("file.place", json!({"path": path, "link": false})) + }; + let before = snapshot(&session); + let registry = registered_fonts(); + let error = session.execute(command, ¶ms).expect_err("REGRESSION: the prospective document exceeds its real composite-font cap"); + assert!(error.to_string().contains("256") && error.to_string().contains("composite"), "the intended cap error: {error}"); + assert_eq!(snapshot(&session), before, "failed adoption preserves art, resources, selection, history and journal"); + assert_eq!(registered_fonts(), registry); + } + // The public async handoff must not leave its provisional reselection behind on this new failure. + let mut session = destination(&full); + let a = session.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 10, "height": 10})).unwrap()["id"].clone(); + let b = NodeId( + session.execute("text.create", &json!({"x": 40, "y": 50, "text": "Bravo", "font": "Source Sans 3", "size": 20})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + session.execute("select.set", &json!({"ids": [a]})).unwrap(); + let read = session.prepare_place(&json!({"path": path, "link": false, "replace": true})).unwrap().read().unwrap(); + let (view, options) = select_type_range(&mut session, b); + let before = snapshot(&session); + let error = session.place_read(read).expect_err("CONTROL: prepared bytes reach the same prospective-font cap"); + assert!(error.to_string().contains("256") && error.to_string().contains("composite")); + assert_eq!(snapshot(&session), before, "failed completion restores the later selection and original replay journal"); + assert_eq!(session.tool_id(), "type"); + assert_eq!(session.tool_options(), options, "provisional reselection must not end the actual Type range/caret"); + assert!(session.tool_wants_text()); + session.tool_text("Z", view).unwrap(); + assert_eq!(plain_text(&session, b), "Zavo", "next typing still replaces the selected Br range"); + session.tool_text("!", view).unwrap(); + assert_eq!(plain_text(&session, b), "Z!avo", "continued typing uses the retained new caret"); + session.keep_typing().unwrap(); + assert_eq!(plain_text(&session, b), "Z!avo"); +} + +#[test] +fn native_composite_import_is_independent_of_unrelated_lent_font_names() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-loan"); + let path = dir.join("lettering.vectorcraft"); + let part = "NativeAdoptionMissingPhysicalFace"; + let incoming = CompositeFont::new("NativeAdoptionWithMissingFace", part, "Regular"); + write_native(&path, &font_document(&incoming)); + let mut session = destination(&[]); + let foreign = CompositeFont::new(part, "Source Sans 3", "Regular"); + let db = FontDb::global(); + let _loan = db.lend_document_composite_fonts(std::slice::from_ref(&foreign)); + assert_eq!(*db.composite_font(part).unwrap(), foreign, "CONTROL: another drawn document lends that name on this thread"); + let id = place(&mut session, &path, false); + let name = placed_family(&session, id); + let imported = CompositeFont::named(&document(&session).composite_fonts, &name).unwrap(); + assert_eq!((&imported.parts, &imported.custom), (&incoming.parts, &incoming.custom)); + assert!(CompositeFont::named(&document(&session).composite_fonts, part).is_none(), "the unrelated loan is not adopted"); + assert_eq!(*db.composite_font(part).unwrap(), foreign, "the caller's loan remains intact"); +} + +fn outline_paths(session: &Session, reply: &Value) -> Vec { + let mut paths = Vec::new(); + for id in reply["ids"].as_array().unwrap() { + document(session).node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |node| { + if let NodeKind::Path { path, .. } = &node.kind { + paths.push(path.clone()); + } + }); + } + assert!(!paths.is_empty(), "CONTROL: real source lettering produced outlines"); + paths +} + +#[test] +fn native_composite_fonts_reach_later_batch_outline_steps() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-batch"); + let path = dir.join("scaled-lettering.vectorcraft"); + let mut incoming = CompositeFont::new("NativeAdoptionBatch", "Source Sans 3", "Regular"); + incoming.parts.roman.size = 125.0; + let source = write_native(&path, &font_document(&incoming)); + let mut text = None; + source.layers[0].walk(&mut |node| { + if let NodeKind::Text(value) = &node.kind { + text = Some((**value).clone()); + } + }); + let text = text.unwrap(); + let db = FontDb::global(); + let intended = { + let _loan = db.lend_document_composite_fonts(std::slice::from_ref(&incoming)); + vectorcraft_text::layout(db, &text) + }; + let fallback = { + let _loan = db.lend_document_composite_fonts(&[]); + vectorcraft_text::layout(db, &text) + }; + assert!((intended.bounds.width() - fallback.bounds.width()).abs() > 0.1, "CONTROL: this source distinguishes intended and fallback glyphs"); + let mut old = incoming.clone(); + old.parts.roman.size = 100.0; + let mut batch = destination(std::slice::from_ref(&old)); + let (kept_id, kept_art) = kept_text(&mut batch, &old); + let reply = batch + .execute( + "command.batch", + &json!({"commands": [ + {"command": "file.place", "params": {"path": path, "link": false, "at": [30,25]}}, + {"command": "type.createOutlines", "params": {}} + ]}), + ) + .unwrap(); + let actual = outline_paths(&batch, &reply["results"][1]); + let imported = document(&batch) + .composite_fonts + .iter() + .find(|font| font.parts == incoming.parts && font.custom == incoming.custom) + .expect("CONTROL: this batch adopted the distinct 125% meaning"); + assert!(!CompositeFont::same_name(&imported.name, &old.name)); + assert_eq!(document(&batch).node(kept_id), Some(&kept_art)); + assert_eq!(CompositeFont::named(&document(&batch).composite_fonts, &old.name), Some(&old)); + // Run the ordinary control only after the cold batch, so it cannot prewarm the imported alias. + let mut ordinary = destination(std::slice::from_ref(&old)); + place(&mut ordinary, &path, false); + let reply = ordinary.execute("type.createOutlines", &json!({})).unwrap(); + assert_eq!(actual, outline_paths(&ordinary, &reply), "batch layout must see the imported meaning before top-level synchronization"); +} + +fn menu_has(reply: &Value, name: &str) -> bool { + reply["families"].as_array().unwrap().iter().any(|family| family.as_str().is_some_and(|f| f.eq_ignore_ascii_case(name))) +} + +#[test] +fn native_composite_preview_fonts_follow_cancel_replacement_commit_and_undo() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-preview"); + let path = dir.join("lettering.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionPreview", "Source Sans 3", "Regular"); + write_native(&path, &font_document(&incoming)); + let held = CompositeFont::new("NativeAdoptionPreviewHeld", "Source Sans 3", "Regular"); + for boundary in 0..3 { + let mut session = destination(std::slice::from_ref(&held)); + let before = document(&session).clone(); + let registry = registered_fonts(); + assert!(!menu_has(&session.execute("text.fontList", &json!({})).unwrap(), &incoming.name)); + session.begin_interaction("Preview native lettering").unwrap(); + session + .preview( + "command.batch", + &json!({"commands": [ + {"command": "file.place", "params": {"path": path, "link": false}} + ]}), + ) + .unwrap(); + assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &incoming.name), Some(&incoming)); + assert_eq!(*FontDb::global().composite_font(&incoming.name).unwrap(), incoming); + match boundary { + 0 => { + session.cancel_interaction().unwrap(); + assert_eq!(registered_fonts(), registry, "cancel restores the registry before another command can hide a leak"); + } + 1 => { + let next = session.preview("text.fontList", &json!({})).unwrap(); + assert!(!menu_has(&next, &incoming.name), "the first consumer after replacing a preview must not see its old font"); + assert_eq!(registered_fonts(), registry); + session.cancel_interaction().unwrap(); + } + _ => { + session.commit_interaction().unwrap(); + assert_eq!(*FontDb::global().composite_font(&incoming.name).unwrap(), incoming, "commit keeps the imported meaning"); + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(registered_fonts(), registry, "Undo restores the pre-preview font meanings"); + } + } + assert_eq!(document(&session), &before); + assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &held.name), Some(&held)); + } +} + +#[test] +fn native_composite_alias_forced_symbol_copy_keeps_all_symbol_options() { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-symbol"); + let path = dir.join("symbol-lettering.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionSymbolFont", "Source Sans 3", "Regular"); + let mut builder = Session::new(); + builder.add_document(font_document(&incoming), None); + let mut text_id = None; + document(&builder).layers[0].walk(&mut |node| { + if matches!(&node.kind, NodeKind::Text(_)) { + assert!(text_id.replace(node.id).is_none(), "CONTROL: exactly one source lettering object"); + } + }); + let symbol = "NativeAdoptionLetteringSymbol"; + builder + .execute( + "symbol.new", + &json!({ + "name": symbol, "ids": [text_id.unwrap().0], "registration": 0, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.2, 0.3, 0.25, 0.15], "alignToPixelGrid": true + }), + ) + .unwrap(); + let source = write_native(&path, document(&builder)); + let options = Clipboard::from_document(&source).symbol_options.get(symbol).unwrap().clone(); + assert!(options.size.is_some(), "CONTROL: the real symbol constructor recorded its natural size"); + assert_eq!(options.registration, vectorcraft_doc::SymbolRegistration(0)); + assert_eq!(options.export_type, vectorcraft_doc::SymbolExportType::Graphic); + assert_eq!(options.nine_slice, vectorcraft_doc::SymbolNineSlice::new(0.2, 0.3, 0.25, 0.15)); + assert!(options.pixel_aligned); + + for linked in [false, true] { + let mut target = source.clone(); + let index = target.composite_fonts.iter().position(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap(); + target.composite_fonts[index].parts.roman.size = 125.0; + let held_font = target.composite_fonts[index].clone(); + assert_eq!(target.symbols, source.symbols, "CONTROL: identical symbol names and art before only the font meaning changes"); + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let held_options = Clipboard::from_document(&before).symbol_options.get(symbol).unwrap().clone(); + assert_eq!(held_options, options, "CONTROL: options also match; the font alias alone must force the new copy"); + + let id = place(&mut session, &path, linked); + let mut used_symbols = Vec::new(); + document(&session).node(id).unwrap().walk(&mut |node| { + if let NodeKind::SymbolInstance { symbol, .. } = &node.kind { + used_symbols.push(symbol.clone()); + } + }); + assert_eq!(used_symbols.len(), 1); + let copied_name = &used_symbols[0]; + assert_ne!(copied_name.as_str(), symbol, "the import must not reuse art whose same family name has a different meaning here"); + let copied = document(&session).symbols.iter().find(|definition| &definition.name == copied_name).unwrap(); + let mut families = Vec::new(); + copied.art.walk(&mut |node| { + if let NodeKind::Text(text) = &node.kind { + families.extend(text.runs.iter().filter(|run| run.text == "Ab").map(|run| run.style.font_family.clone())); + } + }); + assert_eq!(families.len(), 1); + assert!(!CompositeFont::same_name(&families[0], &incoming.name)); + let adopted = CompositeFont::named(&document(&session).composite_fonts, &families[0]).unwrap(); + assert_eq!((&adopted.parts, &adopted.custom), (&incoming.parts, &incoming.custom)); + let after = Clipboard::from_document(document(&session)); + assert_eq!(after.symbol_options.get(copied_name), Some(&options), "the alias-forced copy preserves all five option fields"); + assert_eq!(after.symbol_options.get(symbol), Some(&held_options)); + assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &incoming.name), Some(&held_font)); + assert_eq!( + document(&session).symbols.iter().find(|definition| definition.name == symbol), + before.symbols.iter().find(|definition| definition.name == symbol) + ); + for layer in &before.layers { + for child in layer.children().unwrap() { + assert_eq!(document(&session).node(child.id), Some(child.as_ref()), "existing destination art remains exact"); + } + } + assert_eq!(document(&session).symbols.len(), before.symbols.len() + 1); + let first_symbols = document(&session).symbols.clone(); + let first_fonts = document(&session).composite_fonts.clone(); + let first_resources = native_resource_counts(document(&session)); + let repeated = place(&mut session, &path, linked); + let repeated_name = only_symbol_name(document(&session).node(repeated).unwrap()); + assert_eq!(&repeated_name, copied_name, "repeating the import reuses the actual first symbol alias"); + assert_eq!(symbol_font_family(document(&session), &repeated_name), families[0]); + assert_eq!(native_resource_counts(document(&session)), first_resources, "repetition adds art, not more resources"); + assert_eq!(document(&session).symbols, first_symbols); + assert_eq!(document(&session).composite_fonts, first_fonts); + assert_original_native_art(document(&session), &before); + } +} + +fn only_symbol_name(root: &Node) -> String { + let mut names = Vec::new(); + root.walk(&mut |node| { + if let NodeKind::SymbolInstance { symbol, .. } = &node.kind { + names.push(symbol.clone()); + } + }); + assert_eq!(names.len(), 1, "CONTROL: one instance at this level of the native symbol chain"); + names.pop().unwrap() +} + +fn symbol_font_family(doc: &Document, symbol: &str) -> String { + let art = &doc.symbols.iter().find(|definition| definition.name == symbol).unwrap().art; + let mut names = Vec::new(); + art.walk(&mut |node| { + if let NodeKind::Text(text) = &node.kind { + names.extend(text.runs.iter().filter(|run| run.text == "Ab").map(|run| run.style.font_family.clone())); + } + }); + assert_eq!(names.len(), 1, "CONTROL: the inner symbol retains editable source lettering"); + names.pop().unwrap() +} + +fn native_resource_counts(doc: &Document) -> Value { + json!({"fonts": doc.composite_fonts.len(), "symbols": doc.symbols.len(), "patterns": doc.patterns.len(), + "images": doc.images.len(), "graphicStyles": doc.graphic_styles.len(), "charStyles": doc.char_styles.len(), + "paraStyles": doc.para_styles.len(), "swatches": doc.swatches.len(), "groups": doc.swatch_groups.len(), + "graphDesigns": doc.graph_designs.len(), "brushes": vectorcraft_brush::library(doc).len()}) +} + +fn assert_original_native_art(doc: &Document, before: &Document) { + for symbol in &before.symbols { + assert_eq!(doc.symbols.iter().find(|definition| definition.name == symbol.name), Some(symbol)); + } + for font in &before.composite_fonts { + assert_eq!(CompositeFont::named(&doc.composite_fonts, &font.name), Some(font)); + } + for pattern in &before.patterns { + assert_eq!(doc.pattern(&pattern.name), Some(pattern), "the original destination pattern meaning is unchanged"); + } + for brush in vectorcraft_brush::library(before) { + assert_eq!(vectorcraft_brush::find(doc, &brush.name), Some(brush), "the original stored brush meaning is unchanged"); + } + for layer in &before.layers { + for child in layer.children().unwrap() { + assert_eq!(doc.node(child.id), Some(child.as_ref()), "the pre-existing destination art is unchanged"); + } + } +} + +fn pattern_in_symbol(doc: &Document, symbol: &str) -> String { + let art = &doc.symbols.iter().find(|definition| definition.name == symbol).unwrap().art; + let mut names = Vec::new(); + art.walk(&mut |node| { + if let vectorcraft_color::Paint::Pattern { pattern, .. } = node.appearance.fill_paint() { + names.push(pattern.clone()); + } + }); + assert_eq!(names.len(), 1, "CONTROL: one pattern dependency in the inner symbol"); + names.pop().unwrap() +} + +fn pattern_font_family(doc: &Document, pattern: &str) -> String { + let mut names = Vec::new(); + for root in &doc.pattern(pattern).unwrap().art { + root.walk(&mut |node| { + if let NodeKind::Text(text) = &node.kind { + names.extend(text.runs.iter().filter(|run| run.text == "Ab").map(|run| run.style.font_family.clone())); + } + }); + } + assert_eq!(names.len(), 1, "CONTROL: the pattern holds the one editable source lettering run"); + names.pop().unwrap() +} + +fn brush_in_symbol(doc: &Document, symbol: &str) -> String { + let art = &doc.symbols.iter().find(|definition| definition.name == symbol).unwrap().art; + let mut names = Vec::new(); + art.walk(&mut |node| { + if let Some(brush) = node.appearance.stroke().and_then(|stroke| stroke.brush.as_ref()) { + names.push(brush.clone()); + } + }); + assert_eq!(names.len(), 1, "CONTROL: one brush dependency in the inner symbol"); + names.pop().unwrap() +} + +fn brush_font_family(doc: &Document, name: &str) -> String { + let brush = vectorcraft_brush::find(doc, name).unwrap(); + let vectorcraft_brush::BrushKind::Art(brush) = &brush.kind else { + panic!("CONTROL: the imported resource remains an art brush"); + }; + assert_eq!(brush.width, 137.0, "the brush retains the non-default width chosen by its creator"); + let mut names = Vec::new(); + brush.art.walk(&mut |node| { + if let NodeKind::Text(text) = &node.kind { + names.extend(text.runs.iter().filter(|run| run.text == "Ab").map(|run| run.style.font_family.clone())); + } + }); + assert_eq!(names.len(), 1, "CONTROL: the brush library, not document art, holds the editable source lettering"); + names.pop().unwrap() +} + +const NESTED_INNER: &str = "NativeAdoptionInner"; +const NESTED_OUTER: &str = "NativeAdoptionOuter"; +const NESTED_PATTERN: &str = "NativeAdoptionPatternText"; +const NESTED_BRUSH: &str = "NativeAdoptionBrushText"; + +// Build the same nested native artifact for each direct, pattern-backed or brush-backed case. +fn nested_native_source(path: &std::path::Path, incoming: &CompositeFont, dependency: usize) -> (Session, Document) { + let inner = NESTED_INNER; + let outer = NESTED_OUTER; + let mut builder = Session::new(); + builder.add_document(font_document(incoming), None); + let mut text_id = None; + document(&builder).layers[0].walk(&mut |node| { + if matches!(&node.kind, NodeKind::Text(_)) { + assert!(text_id.replace(node.id).is_none()); + } + }); + let pattern_name = NESTED_PATTERN; + let brush_name = NESTED_BRUSH; + if dependency != 0 { + if dependency == 1 { + builder.execute("object.pattern.make", &json!({"ids":[text_id.unwrap().0],"name":pattern_name,"edit":false})).unwrap(); + } else { + builder + .execute( + "brush.new", + &json!({"type":"art","name":brush_name,"ids":[text_id.unwrap().0], + "params":{"width":137.0}}), + ) + .unwrap(); + } + let mut doc = document(&builder).clone(); + doc.remove(text_id.unwrap()).unwrap(); + let id = doc.alloc_id(); + let appearance = if dependency == 1 { + vectorcraft_doc::Appearance::basic(vectorcraft_doc::pattern::pattern_paint(pattern_name), vectorcraft_color::Paint::None, 0.0) + } else { + let mut appearance = vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::None, + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + 1.0, + ); + appearance.stroke_mut().unwrap().brush = Some(brush_name.into()); + appearance + }; + let rectangle = Node::path(id, vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 20.0)), appearance); + std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().push(std::sync::Arc::new(rectangle)); + doc.fix_next_id(); + builder = Session::new(); + builder.add_document(doc, None); + text_id = Some(id); + } + let made = builder + .execute( + "symbol.new", + &json!({ + "name": inner, "ids": [text_id.unwrap().0], "registration": 0, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.2,0.3,0.25,0.15], "alignToPixelGrid": true + }), + ) + .unwrap(); + builder + .execute( + "symbol.new", + &json!({ + "name": outer, "ids": [made["id"]], "registration": 8, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.1,0.2,0.3,0.25], "alignToPixelGrid": true + }), + ) + .unwrap(); + let source = write_native(path, document(&builder)); + (builder, source) +} + +// Check one complete inline or embedded import and its repeat against the same source artifact. +fn assert_nested_alias_roundtrip( + source: &Document, + source_options: &std::collections::BTreeMap, + path: &Path, + incoming: &CompositeFont, + dependency: usize, + linked: bool, +) { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let inner = NESTED_INNER; + let outer = NESTED_OUTER; + let pattern_name = NESTED_PATTERN; + let brush_name = NESTED_BRUSH; + let mut target = source.clone(); + let font = target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap(); + font.parts.roman.size = 125.0; + assert_eq!(target.symbols, source.symbols, "CONTROL: only the meaning of the existing font differs"); + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let id = place(&mut session, path, linked); + let copied_outer = only_symbol_name(document(&session).node(id).unwrap()); + assert_ne!(copied_outer, outer); + let outer_art = &document(&session).symbols.iter().find(|definition| definition.name == copied_outer).unwrap().art; + let copied_inner = only_symbol_name(outer_art); + assert_ne!(copied_inner, inner, "the child follows its aliased composite-font meaning"); + let copied_pattern = (dependency == 1).then(|| pattern_in_symbol(document(&session), &copied_inner)); + let copied_brush = (dependency == 2).then(|| brush_in_symbol(document(&session), &copied_inner)); + let family = if let Some(pattern) = &copied_pattern { + assert_ne!(pattern.as_str(), pattern_name, "the pattern also gets a new meaning under the font alias"); + pattern_font_family(document(&session), pattern) + } else if let Some(brush) = &copied_brush { + assert_ne!(brush.as_str(), brush_name, "the stored brush gets its own aliased font meaning"); + brush_font_family(document(&session), brush) + } else { + symbol_font_family(document(&session), &copied_inner) + }; + assert!(!CompositeFont::same_name(&family, &incoming.name)); + let definition = CompositeFont::named(&document(&session).composite_fonts, &family).unwrap(); + assert_eq!((&definition.parts, &definition.custom), (&incoming.parts, &incoming.custom)); + let imported_options = Clipboard::from_document(document(&session)).symbol_options; + assert_eq!(imported_options.get(&copied_inner), source_options.get(inner)); + assert_eq!(imported_options.get(&copied_outer), source_options.get(outer), "indirect parent copies keep all five option fields"); + assert_eq!(imported_options.get(inner), source_options.get(inner)); + assert_eq!(imported_options.get(outer), source_options.get(outer)); + assert_original_native_art(document(&session), &before); + assert_eq!(document(&session).symbols.len(), before.symbols.len() + 2); + + let first_symbols = document(&session).symbols.clone(); + let first_fonts = document(&session).composite_fonts.clone(); + let first_resources = native_resource_counts(document(&session)); + let first_brushes = vectorcraft_brush::library(document(&session)); + let repeated = place(&mut session, path, linked); + let repeated_outer = only_symbol_name(document(&session).node(repeated).unwrap()); + let repeated_art = &document(&session).symbols.iter().find(|definition| definition.name == repeated_outer).unwrap().art; + assert_eq!(repeated_outer, copied_outer); + assert_eq!(only_symbol_name(repeated_art), copied_inner, "repeat also reuses the actual mapped child name"); + if let Some(pattern) = &copied_pattern { + assert_eq!(pattern_in_symbol(document(&session), &copied_inner), *pattern); + assert_eq!(pattern_font_family(document(&session), pattern), family); + } else if let Some(brush) = &copied_brush { + assert_eq!(brush_in_symbol(document(&session), &copied_inner), *brush); + assert_eq!(brush_font_family(document(&session), brush), family); + } else { + assert_eq!(symbol_font_family(document(&session), &copied_inner), family); + } + assert_eq!(native_resource_counts(document(&session)), first_resources); + assert_eq!(document(&session).symbols, first_symbols); + assert_eq!(document(&session).composite_fonts, first_fonts); + assert_eq!(vectorcraft_brush::library(document(&session)), first_brushes); + assert_original_native_art(document(&session), &before); +} + +#[test] +fn native_composite_nested_alias_copies_keep_outer_and_inner_options_and_reuse() { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-nested"); + let incoming = CompositeFont::new("NativeAdoptionNestedFont", "Source Sans 3", "Regular"); + for dependency in 0..3 { + let path = dir.join(format!("nested-lettering-{dependency}.vectorcraft")); + let inner = NESTED_INNER; + let outer = NESTED_OUTER; + let (_builder, source) = nested_native_source(&path, &incoming, dependency); + let source_options = Clipboard::from_document(&source).symbol_options; + for (name, registration, guides) in [ + (inner, 0, vectorcraft_doc::SymbolNineSlice::new(0.2, 0.3, 0.25, 0.15)), + (outer, 8, vectorcraft_doc::SymbolNineSlice::new(0.1, 0.2, 0.3, 0.25)), + ] { + let options = source_options.get(name).unwrap(); + assert!(options.size.is_some()); + assert_eq!(options.registration, vectorcraft_doc::SymbolRegistration(registration)); + assert_eq!(options.export_type, vectorcraft_doc::SymbolExportType::Graphic); + assert_eq!(options.nine_slice, guides); + assert!(options.pixel_aligned); + } + for linked in [false, true] { + assert_nested_alias_roundtrip(&source, &source_options, &path, &incoming, dependency, linked); + } + } +} + +#[test] +fn native_composite_async_replace_is_independent_of_an_unrelated_live_tool_drag() { + use vectorcraft_geom::Rect; + use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-drag"); + let path = dir.join("replacement.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionDrag", "Source Sans 3", "Regular"); + write_native(&path, &font_document(&incoming)); + let view = vectorcraft_engine::ViewInfo { smart_guides: false, ..Default::default() }; + for cancel in [true, false] { + let mut session = Session::new(); + session.prefs.real_time_drawing = true; + session.add_document(Document::new(400.0, 400.0), None); + let a = session.execute("shape.rectangle", &json!({"x":10,"y":10,"width":20,"height":20})).unwrap(); + let a = NodeId(a["id"].as_u64().unwrap()); + let b = session.execute("shape.rectangle", &json!({"x":100,"y":100,"width":40,"height":40})).unwrap(); + let b = NodeId(b["id"].as_u64().unwrap()); + let old_a = document(&session).node(a).unwrap().clone(); + let old_b = document(&session).node(b).unwrap().clone(); + session.execute("select.set", &json!({"ids":[a.0]})).unwrap(); + let read = session.prepare_place(&json!({"path":path,"link":false,"replace":true})).unwrap().read().unwrap(); + session.execute("select.set", &json!({"ids":[b.0]})).unwrap(); + session.select_tool("selection", view).unwrap(); + let steps = session.doc().unwrap().history.undo.len(); + session.pointer(&PointerEvent::new(PointerKind::Down, 120.0, 120.0), view).unwrap(); + session.pointer(&PointerEvent::new(PointerKind::Drag, 140.0, 130.0), view).unwrap(); + assert!(session.in_interaction(), "CONTROL: actual selection-tool pointer actions began a drag"); + assert_eq!(session.tool_id(), "selection"); + assert_eq!(session.doc().unwrap().selection.objects, vec![b]); + assert_eq!(document(&session).bounds_of(&[b], false), Some(Rect::new(120.0, 110.0, 160.0, 150.0))); + assert_eq!(session.doc().unwrap().history.undo.len(), steps, "CONTROL: this is still an uncommitted tool preview"); + + let reply = session.place_read(read).expect("CONTROL: the native replacement succeeds while a different object is dragged"); + let replacement = NodeId(reply["ids"][0].as_u64().unwrap()); + let published = document(&session).node(replacement).unwrap().clone(); + let completed_steps = session.doc().unwrap().history.undo.len(); + assert_ne!(document(&session).node(a), Some(&old_a)); + assert!(session.in_interaction(), "the unrelated tool drag remains live after external completion"); + session.pointer(&PointerEvent::new(PointerKind::Drag, 170.0, 150.0), view).unwrap(); + if cancel { + session.tool_key(ToolKey::Escape, Mods::default(), view).unwrap(); + } + session.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 150.0), view).unwrap(); + assert!(!session.in_interaction()); + assert_eq!(document(&session).node(replacement), Some(&published), "cancel/release of B must keep the published replacement of A"); + assert_eq!(completed_steps, steps + 1, "the completion has its own undo step before the drag ends"); + if cancel { + assert_eq!(document(&session).node(b), Some(&old_b)); + assert_eq!(session.doc().unwrap().history.undo.len(), steps + 1); + } else { + assert_eq!(document(&session).bounds_of(&[b], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0))); + assert_eq!(session.doc().unwrap().history.undo.len(), steps + 2, "commit creates a separate drag step"); + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(document(&session).node(b), Some(&old_b)); + assert_eq!(document(&session).node(replacement), Some(&published), "first Undo removes only the drag"); + } + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(document(&session).node(a), Some(&old_a), "the next Undo independently restores the replaced target"); + assert_ne!(document(&session).node(replacement), Some(&published), "Undo removes the replacement meaning even if an id is reused"); + assert_eq!(document(&session).node(b), Some(&old_b)); + } +} + +#[test] +fn native_composite_mapped_symbol_art_shares_only_matching_options() { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-mapped-options"); + let path = dir.join("mapped-options.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionMappedOptions", "Source Sans 3", "Regular"); + assert_native_source_font_geometry(&dir.join("source-geometry.vectorcraft"), &incoming); + let mut builder = Session::new(); + builder.add_document(font_document(&incoming), None); + let children = document(&builder).layers[0].children().unwrap(); + assert_eq!(children.len(), 1, "CONTROL: the one source lettering object"); + let text_id = children[0].id; + let symbol = "NativeAdoptionMappedOptionsSymbol"; + builder + .execute( + "symbol.new", + &json!({ + "name": symbol, "ids": [text_id.0], "registration": 0, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.2, 0.3, 0.25, 0.15], "alignToPixelGrid": true + }), + ) + .unwrap(); + let source = write_native(&path, document(&builder)); + let source_options = Clipboard::from_document(&source).symbol_options.get(symbol).unwrap().clone(); + for linked in [false, true] { + let mut target = source.clone(); + let font = target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap(); + font.parts.roman.size = 125.0; + let mut seed = Session::new(); + seed.add_document(target, None); + let first = place(&mut seed, &path, linked); + let alias_symbol = only_symbol_name(document(&seed).node(first).unwrap()); + let alias_family = symbol_font_family(document(&seed), &alias_symbol); + assert_ne!(alias_symbol, symbol); + assert!(!CompositeFont::same_name(&alias_family, &incoming.name)); + for matching_options in [false, true] { + let mut target = document(&seed).clone(); + let definition = target.symbols.iter_mut().find(|definition| definition.name == symbol).unwrap(); + // The original-name art now already uses the equivalent font selected by the import. + let NodeKind::Text(text) = &mut std::sync::Arc::make_mut(&mut definition.art).kind else { + panic!("CONTROL: the one source lettering object stays text in its symbol"); + }; + for run in &mut text.runs { + if CompositeFont::same_name(&run.style.font_family, &incoming.name) { + run.style.font_family = alias_family.clone(); + } + } + assert_eq!(symbol_font_family(&target, symbol), alias_family); + if !matching_options { + // Public document storage keeps natural size separately from the symbol's art. + target.unknown.get_mut(vectorcraft_doc::SYMBOL_SIZES).unwrap().as_object_mut().unwrap().remove(symbol); + target.set_symbol_registration(symbol, vectorcraft_doc::SymbolRegistration(8)); + target.set_symbol_export_type(symbol, vectorcraft_doc::SymbolExportType::default()); + target.set_symbol_nine_slice(symbol, None); + target.set_symbol_pixel_aligned(symbol, false); + } + let held_options = Clipboard::from_document(&target).symbol_options.get(symbol).unwrap().clone(); + if matching_options { + assert_eq!(held_options, source_options, "CONTROL: equal art and options may still share the original name"); + } else { + assert_ne!(held_options.size, source_options.size); + assert_ne!(held_options.registration, source_options.registration); + assert_ne!(held_options.export_type, source_options.export_type); + assert_ne!(held_options.nine_slice, source_options.nine_slice); + assert_ne!(held_options.pixel_aligned, source_options.pixel_aligned); + } + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let resources = native_resource_counts(&before); + let id = place(&mut session, &path, linked); + let imported = only_symbol_name(document(&session).node(id).unwrap()); + let expected = if matching_options { symbol } else { alias_symbol.as_str() }; + assert_eq!(imported, expected, "matching art must not capture different incoming symbol options"); + assert_eq!(symbol_font_family(document(&session), &imported), alias_family); + let options = Clipboard::from_document(document(&session)).symbol_options; + assert_eq!(options.get(&imported), Some(&source_options)); + assert_eq!(options.get(symbol), Some(&held_options)); + assert_eq!(native_resource_counts(document(&session)), resources); + assert_original_native_art(document(&session), &before); + let repeated = place(&mut session, &path, linked); + assert_eq!(only_symbol_name(document(&session).node(repeated).unwrap()), imported); + assert_eq!(native_resource_counts(document(&session)), resources); + assert_original_native_art(document(&session), &before); + } + } +} + +// The native reader must measure its own composite meanings before cropping, not the front document's. +fn assert_native_source_font_geometry(path: &Path, incoming: &CompositeFont) { + write_native(path, &font_document(incoming)); + for linked in [false, true] { + let mut ordinary_placement = None; + let mut ordinary_destination_width = None; + for scale in [100.0, 125.0] { + let mut existing = incoming.clone(); + existing.parts.roman.size = scale; + let mut session = destination(std::slice::from_ref(&existing)); + let (kept_id, kept_art) = kept_text(&mut session, &existing); + let kept_width = kept_art.geometric_bounds().unwrap().width(); + if let Some(width) = ordinary_destination_width { + assert!(kept_width > width, "CONTROL: the destination really measures this same font family at the larger size"); + } else { + ordinary_destination_width = Some(kept_width); + } + let reply = session.execute("file.place", &json!({"path": path, "link": linked, "crop": "bounding", "at": [30, 25]})).unwrap(); + assert_eq!(reply["linked"], linked); + let id = NodeId(reply["ids"][0].as_u64().unwrap()); + if linked { + session.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + } + let doc = document(&session); + let family = placed_family(&session, id); + let font = CompositeFont::named(&doc.composite_fonts, &family).unwrap(); + assert_eq!((&font.parts, &font.custom), (&incoming.parts, &incoming.custom)); + assert_eq!(CompositeFont::same_name(&family, &incoming.name), scale == 100.0); + let bounds = doc.node(id).unwrap().geometric_bounds_with(&doc.symbol_boxes()).unwrap(); + assert!(bounds.width() > 0.0 && bounds.height() > 0.0); + if let Some(expected) = ordinary_placement { + assert_eq!(bounds, expected, "bounding placement keeps source geometry under a conflicting destination font meaning"); + } else { + ordinary_placement = Some(bounds); + } + assert_eq!(doc.node(kept_id), Some(&kept_art), "source measurement does not alter the existing destination artwork"); + assert_eq!(CompositeFont::named(&doc.composite_fonts, &existing.name), Some(&existing)); + } + } +} + +#[test] +fn native_symbol_options_reuse_without_composite_fonts() { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-no-font-options"); + let path = dir.join("plain-symbol.vectorcraft"); + let mut builder = Session::new(); + builder.add_document(Document::new(100.0, 80.0), None); + let text = builder.execute("text.create", &json!({"x": 4, "y": 16, "text": "Ab", "font": "Source Sans 3"})).unwrap(); + let symbol = "NativeNoFontOptionsSymbol"; + builder + .execute( + "symbol.new", + &json!({"name": symbol, "ids": [text["id"]], "registration": 0, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.2, 0.3, 0.25, 0.15], "alignToPixelGrid": true}), + ) + .unwrap(); + let source = write_native(&path, document(&builder)); + assert!(source.composite_fonts.is_empty(), "CONTROL: no font-family alias can enable resource finalization"); + let source_options = Clipboard::from_document(&source).symbol_options.get(symbol).unwrap().clone(); + for linked in [false, true] { + for matching_options in [false, true] { + let mut target = source.clone(); + if !matching_options { + target.unknown.get_mut(vectorcraft_doc::SYMBOL_SIZES).unwrap().as_object_mut().unwrap().remove(symbol); + target.set_symbol_registration(symbol, vectorcraft_doc::SymbolRegistration(8)); + target.set_symbol_export_type(symbol, vectorcraft_doc::SymbolExportType::default()); + target.set_symbol_nine_slice(symbol, None); + target.set_symbol_pixel_aligned(symbol, false); + } + let held_options = Clipboard::from_document(&target).symbol_options.get(symbol).unwrap().clone(); + if matching_options { + assert_eq!(held_options, source_options); + } else { + assert_ne!(held_options.size, source_options.size); + assert_ne!(held_options.registration, source_options.registration); + assert_ne!(held_options.export_type, source_options.export_type); + assert_ne!(held_options.nine_slice, source_options.nine_slice); + assert_ne!(held_options.pixel_aligned, source_options.pixel_aligned); + } + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let first = place(&mut session, &path, linked); + let name = only_symbol_name(document(&session).node(first).unwrap()); + assert_eq!(name == symbol, matching_options, "equal options share; different options retain a separate definition"); + let options = Clipboard::from_document(document(&session)).symbol_options; + assert_eq!(options.get(&name), Some(&source_options)); + assert_eq!(options.get(symbol), Some(&held_options)); + assert_eq!(document(&session).symbols.len(), before.symbols.len() + usize::from(!matching_options)); + assert!(document(&session).composite_fonts.is_empty()); + assert_original_native_art(document(&session), &before); + let resources = native_resource_counts(document(&session)); + let second = place(&mut session, &path, linked); + assert_eq!(only_symbol_name(document(&session).node(second).unwrap()), name, "repeat reuses the actual first alias"); + assert_eq!(native_resource_counts(document(&session)), resources); + assert_original_native_art(document(&session), &before); + } + } +} + +#[test] +fn native_source_without_composites_ignores_front_font_meaning() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-empty-source-fonts"); + let path = dir.join("undefined-family.vectorcraft"); + let mut font = CompositeFont::new("NativeEmptySourceFamily", "Source Sans 3", "Regular"); + let mut source = font_document(&font); + source.composite_fonts = Vec::new().into(); + let source = write_native(&path, &source); + assert!(source.composite_fonts.is_empty()); + let params = json!({"path": path, "crop": "bounding"}); + let mut control = destination(&[]); + let expected = control.execute("file.place.info", ¶ms).unwrap(); + assert!(expected["width"].as_f64().unwrap() > 0.0 && expected["height"].as_f64().unwrap() > 0.0); + font.parts.roman.size = 125.0; + let mut front = destination(std::slice::from_ref(&font)); + let (kept, art) = kept_text(&mut front, &font); + let before = document(&front).clone(); + let registered = FontDb::global().composite_font(&font.name).unwrap(); + assert_eq!(&*registered, &font, "CONTROL: the front document really declares the conflicting meaning"); + let actual = front.execute("file.place.info", ¶ms).unwrap(); + assert_eq!(actual["width"], expected["width"], "bounding reads must not borrow a family absent from the source"); + assert_eq!(actual["height"], expected["height"]); + assert_eq!(actual["warnings"], expected["warnings"]); + assert_eq!(document(&front), &before, "a source-size query does not edit the front document"); + assert_eq!(document(&front).node(kept), Some(&art)); + assert_eq!(&*FontDb::global().composite_font(&font.name).unwrap(), &font, "source measurement restores the front meaning"); + // The file's undefined family is not given a new alias or post-adoption policy by this query test. +} + +fn native_mapping_source(path: &Path, incoming: &CompositeFont, location: usize, classic: bool, mixed: bool) -> (Session, Document) { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, Effect}; + use vectorcraft_geom::{Affine, Rect}; + + let (builder, mut source) = nested_native_source(path, incoming, 0); + let outer = only_symbol_name(&source.layers[0]); + let outer_art = &source.symbols.iter().find(|definition| definition.name == outer).unwrap().art; + let symbol = only_symbol_name(outer_art); + std::sync::Arc::make_mut(&mut source.layers[0]).children_mut().unwrap().clear(); + let entry = if classic { json!({"surface": 1, "symbol": symbol}) } else { json!({"symbol": symbol}) }; + let rejected = if classic { json!({"surface": 2, "symbol": symbol, "scaleX": 0}) } else { json!({"symbol": symbol, "scale": 0}) }; + if classic { + vectorcraft_render::effects::SurfaceMap::from_value(&entry).unwrap(); + assert!(vectorcraft_render::effects::SurfaceMap::from_value(&rejected).is_err()); + } else { + vectorcraft_render::effects::MappedGraphic::from_value(&entry).unwrap(); + assert!(vectorcraft_render::effects::MappedGraphic::from_value(&rejected).is_err()); + } + let effect = Effect { + id: if classic { vectorcraft_render::effects::CLASSIC_EXTRUDE } else { vectorcraft_render::effects::ROTATE }.into(), + params: if classic { + json!({"mapArt": [entry, rejected, {"surface": 1, "symbol": symbol}], "graphics": [{"symbol": symbol}]}) + } else { + json!({"graphics": [entry, rejected], "mapArt": [{"surface": 1, "symbol": symbol}]}) + }, + visible: true, + }; + let mut carrier = Node::path( + source.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(2.0, 2.0, 22.0, 22.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0), + ); + match location { + 0 => carrier.appearance.effects.push(effect), + 1 => carrier.appearance.fill_mut().unwrap().effects.push(effect), + _ => carrier.appearance.stroke_mut().unwrap().effects.push(effect), + } + assert_eq!(vectorcraft_render::effects::appearance_graphic_symbols(&carrier.appearance), vec![symbol.clone()]); + let mut added = vec![std::sync::Arc::new(carrier)]; + if mixed { + let xf = Affine::translate((40.0, 40.0)) * Affine::scale(0.1); + added.push(std::sync::Arc::new(Node::new(source.alloc_id(), NodeKind::SymbolInstance { symbol, xf }))); + } + std::sync::Arc::make_mut(&mut source.layers[0]).children_mut().unwrap().extend(added); + source.fix_next_id(); + (builder, source) +} + +fn one_mapping_effect(root: &Node) -> vectorcraft_doc::Effect { + let mut effects = Vec::new(); + root.walk(&mut |node| { + effects.extend(node.appearance.effects.iter().cloned()); + for item in &node.appearance.items { + effects.extend(item.effects().iter().cloned()); + } + }); + assert_eq!(effects.len(), 1, "CONTROL: one own/fill/stroke mapping effect, not rendered output"); + effects.pop().unwrap() +} + +fn assert_native_mapping_roundtrip(source: &Document, path: &Path, incoming: &CompositeFont, classic: bool, mixed: bool, linked: bool) { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let key = if classic { "mapArt" } else { "graphics" }; + let original_effect = one_mapping_effect(&source.layers[0]); + let original = original_effect.params[key][0]["symbol"].as_str().unwrap(); + let source_options = Clipboard::from_document(source).symbol_options.get(original).unwrap().clone(); + let mut target = source.clone(); + target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap().parts.roman.size = 125.0; + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let first = place(&mut session, path, linked); + let effect = one_mapping_effect(document(&session).node(first).unwrap()); + let mapped = effect.params[key][0]["symbol"].as_str().unwrap(); + assert_ne!(mapped, original, "the accepted mapping must follow incoming art, not the conflicting destination symbol"); + let family = symbol_font_family(document(&session), mapped); + assert!(!CompositeFont::same_name(&family, &incoming.name)); + let font = CompositeFont::named(&document(&session).composite_fonts, &family).unwrap(); + assert_eq!((&font.parts, &font.custom), (&incoming.parts, &incoming.custom)); + assert_eq!(Clipboard::from_document(document(&session)).symbol_options.get(mapped), Some(&source_options)); + let mut expected = original_effect.clone(); + expected.params[key][0]["symbol"] = json!(mapped); + assert_eq!(effect, expected, "rejected records, duplicate surfaces and inactive keys retain their original fields"); + if mixed { + assert_eq!(only_symbol_name(document(&session).node(first).unwrap()), mapped, "ordinary and mapped users follow the same copy"); + } + assert_original_native_art(document(&session), &before); + let resources = native_resource_counts(document(&session)); + let repeated = place(&mut session, path, linked); + assert_eq!(one_mapping_effect(document(&session).node(repeated).unwrap()), effect); + assert_eq!(native_resource_counts(document(&session)), resources); + assert_original_native_art(document(&session), &before); +} + +#[test] +fn native_mapped_effect_symbols_keep_incoming_font_and_options() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-mapped-fonts"); + let incoming = CompositeFont::new("NativeMappedFont", "Source Sans 3", "Regular"); + // Three distinct storage seams, rather than an effect/backend matrix. + for (location, classic, mixed) in [(0, false, false), (1, true, false), (2, true, true)] { + let path = dir.join(format!("mapped-{location}.vectorcraft")); + let (_builder, source) = native_mapping_source(&path, &incoming, location, classic, mixed); + let source = write_native(&path, &source); + for linked in [false, true] { + assert_native_mapping_roundtrip(&source, &path, &incoming, classic, mixed, linked); + } + } +} + +fn one_inline_art(root: &Node) -> vectorcraft_doc::InlineArt { + let mut found = Vec::new(); + root.walk(&mut |node| { + if let NodeKind::Text(text) = &node.kind { + found.extend(text.runs.iter().filter_map(|run| run.inline.clone())); + } + }); + assert_eq!(found.len(), 1, "CONTROL: one inline-only symbol reference"); + found.pop().unwrap() +} + +fn assert_inline_native_roundtrip(source: &Document, path: &Path, incoming: &CompositeFont, linked: bool) { + let original = one_inline_art(&source.layers[0]); + let source_size = source.unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|sizes| sizes.get(&original.symbol)); + let mut target = source.clone(); + target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap().parts.roman.size = 125.0; + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let id = place(&mut session, path, linked); + let imported = one_inline_art(document(&session).node(id).unwrap()); + assert_ne!(imported.symbol, original.symbol, "inline art must not resolve to the destination's different font meaning"); + assert_eq!((imported.scale, imported.baseline_shift), (original.scale, original.baseline_shift)); + let family = symbol_font_family(document(&session), &imported.symbol); + assert!(!CompositeFont::same_name(&family, &incoming.name)); + let font = CompositeFont::named(&document(&session).composite_fonts, &family).unwrap(); + assert_eq!((&font.parts, &font.custom), (&incoming.parts, &incoming.custom)); + let imported_doc = document(&session); + assert_eq!(imported_doc.unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|sizes| sizes.get(&imported.symbol)), source_size); + assert_eq!(imported_doc.symbol_registration(&imported.symbol), source.symbol_registration(&original.symbol)); + assert_eq!(imported_doc.symbol_export_type(&imported.symbol), source.symbol_export_type(&original.symbol)); + assert_eq!(imported_doc.symbol_nine_slice(&imported.symbol), source.symbol_nine_slice(&original.symbol)); + assert_eq!(imported_doc.symbol_pixel_aligned(&imported.symbol), source.symbol_pixel_aligned(&original.symbol)); + assert_original_native_art(document(&session), &before); + let resources = native_resource_counts(document(&session)); + let second = place(&mut session, path, linked); + let repeated = one_inline_art(document(&session).node(second).unwrap()); + assert_eq!(repeated.symbol, imported.symbol); + assert_eq!((repeated.scale, repeated.baseline_shift), (original.scale, original.baseline_shift)); + assert_eq!(native_resource_counts(document(&session)), resources); + assert_original_native_art(document(&session), &before); +} + +#[test] +fn native_inline_symbol_keeps_incoming_font_and_options() { + use vectorcraft_doc::{InlineArt, TextRun}; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-inline-font"); + let path = dir.join("inline-lettering.vectorcraft"); + let incoming = CompositeFont::new("NativeInlineFont", "Source Sans 3", "Regular"); + let (mut builder, source) = nested_native_source(&path, &incoming, 0); + let outer = only_symbol_name(&source.layers[0]); + let outer_art = &source.symbols.iter().find(|definition| definition.name == outer).unwrap().art; + let inner = only_symbol_name(outer_art); + let ids = document(&builder).layers[0].children().unwrap().iter().map(|node| node.id.0).collect::>(); + builder.execute("edit.clear", &json!({"ids": ids})).unwrap(); + let made = builder.execute("text.create", &json!({"x": 10, "y": 30, "text": "X", "font": "Source Sans 3"})).unwrap(); + let mut source = document(&builder).clone(); + let NodeKind::Text(text) = &mut source.node_mut(NodeId(made["id"].as_u64().unwrap())).unwrap().kind else { + panic!("CONTROL: public text.create produces the inline holder"); + }; + let style = text.runs[0].style.clone(); + assert!(!CompositeFont::same_name(&style.font_family, &incoming.name)); + let mut inline = InlineArt::new(inner); + inline.scale = 1.25; + inline.baseline_shift = 2.0; + text.runs = vec![TextRun::inline(inline, style)]; + let source = write_native(&path, &source); + let mut ordinary = false; + source.layers[0].walk(&mut |node| ordinary |= matches!(node.kind, NodeKind::SymbolInstance { .. })); + assert!(!ordinary, "CONTROL: no ordinary instance seeds the inline symbol dependency"); + for linked in [false, true] { + assert_inline_native_roundtrip(&source, &path, &incoming, linked); + } +} + +fn one_pattern_override(root: &Node) -> vectorcraft_doc::SymbolOverride { + let mut found = Vec::new(); + root.walk(&mut |node| found.extend(node.extras().symbol_overrides.iter().cloned())); + assert_eq!(found.len(), 1, "CONTROL: one stored dynamic override"); + found.pop().unwrap() +} + +fn override_pattern(override_: &vectorcraft_doc::SymbolOverride) -> String { + use vectorcraft_color::Paint; + + let Some(Paint::Pattern { pattern: fill, .. }) = &override_.fill else { panic!("CONTROL: a pattern fill override") }; + let Some(Paint::Pattern { pattern: stroke, .. }) = &override_.stroke else { panic!("CONTROL: a pattern stroke override") }; + assert_eq!(fill, stroke); + fill.clone() +} + +fn assert_override_native_roundtrip(source: &Document, path: &Path, incoming: &CompositeFont, linked: bool) { + use vectorcraft_color::Paint; + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let original = one_pattern_override(&source.layers[0]); + let original_pattern = override_pattern(&original); + let symbol = only_symbol_name(&source.layers[0]); + let options = Clipboard::from_document(source).symbol_options.get(&symbol).unwrap().clone(); + let mut target = source.clone(); + target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap().parts.roman.size = 125.0; + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let first = place(&mut session, path, linked); + let imported = one_pattern_override(document(&session).node(first).unwrap()); + let pattern = override_pattern(&imported); + assert_ne!(pattern, original_pattern, "override-only pattern art follows the incoming composite meaning"); + let family = pattern_font_family(document(&session), &pattern); + assert!(!CompositeFont::same_name(&family, &incoming.name)); + let font = CompositeFont::named(&document(&session).composite_fonts, &family).unwrap(); + assert_eq!((&font.parts, &font.custom), (&incoming.parts, &incoming.custom)); + let mut expected = original.clone(); + for paint in [&mut expected.fill, &mut expected.stroke].into_iter().flatten() { + let Paint::Pattern { pattern: name, .. } = paint else { panic!("CONTROL: both override paints are patterns") }; + *name = pattern.clone(); + } + assert_eq!(imported, expected, "override paths, transforms, opacity and blend retain their source values"); + let used_symbol = only_symbol_name(document(&session).node(first).unwrap()); + assert_eq!(used_symbol, symbol, "plain base symbol still shares its unchanged art and options"); + assert_eq!(Clipboard::from_document(document(&session)).symbol_options.get(&used_symbol), Some(&options)); + assert_original_native_art(document(&session), &before); + let resources = native_resource_counts(document(&session)); + let repeated = place(&mut session, path, linked); + assert_eq!(one_pattern_override(document(&session).node(repeated).unwrap()), imported); + assert_eq!(native_resource_counts(document(&session)), resources); + assert_original_native_art(document(&session), &before); +} + +#[test] +fn native_symbol_override_patterns_keep_incoming_font_meaning() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, SymbolOverride}; + use vectorcraft_geom::Affine; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-override-font"); + let path = dir.join("override-lettering.vectorcraft"); + let incoming = CompositeFont::new("NativeOverrideFont", "Source Sans 3", "Regular"); + let (_builder, mut source) = nested_native_source(&path, &incoming, 1); + let outer = only_symbol_name(&source.layers[0]); + let outer_art = &source.symbols.iter().find(|definition| definition.name == outer).unwrap().art; + let inner = only_symbol_name(outer_art); + let pattern = pattern_in_symbol(&source, &inner); + let base = source.symbols.iter_mut().find(|definition| definition.name == inner).unwrap(); + base.dynamic = true; + std::sync::Arc::make_mut(&mut base.art).appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0).into(); + std::sync::Arc::make_mut(&mut source.layers[0]).children_mut().unwrap().clear(); + let mut instance = + Node::new(source.alloc_id(), NodeKind::SymbolInstance { symbol: inner.clone(), xf: Affine::translate((40.0, 40.0)) * Affine::scale(0.1) }); + instance.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + instance.extras_mut().symbol_overrides.push(SymbolOverride { + path: vec![], + fill: Some(vectorcraft_doc::pattern::pattern_paint(&pattern)), + stroke: Some(Paint::Pattern { pattern, xf: Affine::scale(2.0) }), + opacity: Some(0.65), + blend: None, + }); + let base = &source.symbols.iter().find(|definition| definition.name == inner).unwrap().art; + let effective = vectorcraft_doc::symbol_overrides::instance_art(base, &instance); + let override_ = &instance.extras().symbol_overrides[0]; + assert_eq!(Some(effective.appearance.fill_paint()), override_.fill); + assert_eq!(Some(effective.appearance.stroke().unwrap().paint.clone()), override_.stroke); + std::sync::Arc::make_mut(&mut source.layers[0]).children_mut().unwrap().push(std::sync::Arc::new(instance)); + source.fix_next_id(); + let source = write_native(&path, &source); + for linked in [false, true] { + assert_override_native_roundtrip(&source, &path, &incoming, linked); + } +} diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index aaeb97ccf4..d4c7e1e449 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -8,7 +8,7 @@ use vectorcraft_doc::{ Appearance, AppearanceItem, Artboard, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, OpacityMask, StrokeLayer, Symbol, }; -use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; +use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape, shapes}; use super::*; @@ -1020,6 +1020,167 @@ fn hidden_layers_open_hidden() { assert!(text.contains("%AI5_NumLayers: 3\n%AI5_OpenViewLayers: 776\n"), "{text}"); } +fn dash_painted_nodes(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + match &n.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } => out.push((**n).clone()), + _ => { + if let Some(children) = n.children() { + dash_painted_nodes(children, out); + } + } + } + } +} + +/// Original synthetic rectangle, independent of the artwork in #10476. +fn dash_compat_document(pattern: Vec) -> Document { + let mut doc = Document::new(200.0, 100.0); + let mut stroke = StrokeLayer::new(solid(Color::BLACK), 4.0); + stroke.dash = Some(Dash { pattern, offset: 2.5, align_corners: false }); + stroke.overprint = true; + let ap = Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.0, 1.0, 0.0)))), AppearanceItem::Stroke(stroke)], + ..Appearance::default() + }; + let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 180.0, 80.0)), ap); + doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap(); + doc +} + +fn ai_dash_outputs(doc: &Document) -> Vec<(String, Vec, Document)> { + let out = export_ai_editing(doc, &opts()).unwrap(); + let legacy = crate::export_legacy_ai(doc, &crate::LegacyAiOptions::default()).unwrap(); + let legacy_back = crate::import(&legacy.bytes).unwrap().document; + vec![ + (String::from_utf8(out.program).unwrap().replace("\r\n", "\n"), out.warnings, read_back(doc)), + (String::from_utf8(legacy.bytes).unwrap().replace("\r\n", "\n"), legacy.warnings, legacy_back), + ] +} + +#[test] +fn ai_dash_lists_reduce_repetitions_and_keep_small_patterns_editable() { + for (pattern, emitted) in [ + (vec![33.5673; 5], "[33.5673] 2.5 d"), + (vec![33.5673; 10], "[33.5673] 2.5 d"), + (vec![3.0, 2.0, 1.0, 3.0, 2.0, 1.0, 3.0, 2.0, 1.0], "[3 2 1] 2.5 d"), + (vec![0.25], "[0.25] 2.5 d"), + (vec![0.25, 0.5], "[0.25 0.5] 2.5 d"), + (vec![3.0, 2.0, 1.0], "[3 2 1] 2.5 d"), + (vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0], "[3 2 1 2 3 4] 2.5 d"), + ] { + let doc = dash_compat_document(pattern.clone()); + for (text, warnings, back) in ai_dash_outputs(&doc) { + assert!(text.contains(emitted), "{pattern:?}: missing {emitted}: {text}"); + assert!(warnings.is_empty(), "{pattern:?}: {warnings:?}"); + let mut art = vec![]; + dash_painted_nodes(&back.layers, &mut art); + assert_eq!(art.len(), 1); + let st = art[0].appearance.stroke().unwrap(); + assert_eq!(st.width, 4.0); + assert!(st.overprint); + assert_eq!(st.dash.as_ref().unwrap().offset, 2.5); + let got = &st.dash.as_ref().unwrap().pattern; + for i in 0..pattern.len() * got.len() * 2 { + assert_eq!(pattern[i % pattern.len()], got[i % got.len()]); + } + assert!(art[0].appearance.fill().is_some()); + } + assert_eq!(doc.layers[0].children().unwrap()[0].appearance.stroke().unwrap().dash.as_ref().unwrap().pattern, pattern); + } +} + +#[test] +fn ai_dash_lists_that_exceed_six_effective_lengths_are_outlined_with_a_warning() { + for pattern in [vec![3.0, 2.0, 1.0, 2.0, 3.0], vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0], vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]] { + let doc = dash_compat_document(pattern); + let original = &doc.layers[0].children().unwrap()[0]; + let path = original.path_data().unwrap(); + let expected = vectorcraft_effects::stroke::outline_region(path, FillRule::NonZero, original.appearance.stroke().unwrap()).to_bezpath(); + for (text, warnings, back) in ai_dash_outputs(&doc) { + assert!(warnings.iter().any(|w| w.contains("filled outlines")), "{warnings:?}"); + assert!( + !text.lines().filter(|l| l.ends_with(" d")).any(|l| { + let array = l.rsplit_once('[').unwrap().1.split(']').next().unwrap(); + let n = array.split_whitespace().count(); + n > 6 || (n % 2 == 1 && n * 2 > 6) + }), + "{text}" + ); + let mut art = vec![]; + dash_painted_nodes(&back.layers, &mut art); + assert!(art.iter().all(|n| n.appearance.stroke().is_none()), "{art:?}"); + assert_eq!(art.len(), 2, "fill and outlined stroke keep their paint order"); + assert_eq!(art[0].appearance.fill().unwrap().paint, solid(Color::rgb(0.0, 1.0, 0.0))); + let fill = art[1].appearance.fill().unwrap(); + assert_eq!(fill.paint, solid(Color::BLACK)); + assert!(fill.overprint); + let got = art[1].stroke_path().unwrap(); + for y in 5..85 { + for x in 5..185 { + let p = vectorcraft_geom::Point::new(f64::from(x) + 0.123, f64::from(y) + 0.123); + assert_eq!(got.winding(p) != 0, expected.winding(p) != 0, "at {p:?}"); + } + } + } + } +} + +#[test] +fn ai_dash_lists_in_linked_styles_also_respect_the_reader_limit() { + for (pattern, live) in [(vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], false), (vec![33.5673; 5], true)] { + let mut doc = dash_compat_document(pattern); + let n = Arc::make_mut(&mut Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap()[0]); + n.appearance.stroke_mut().unwrap().overprint = false; + n.extras_mut().graphic_style = Some(7); + let mut style = vectorcraft_doc::GraphicStyle::new("Dashed", (*n.appearance).clone()); + style.id = 7; + doc.graphic_styles.push(style); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let text = String::from_utf8(out.program).unwrap(); + assert!(!text.contains("[3 2 1 2 3 4 5 6]"), "a style dictionary must not keep an incompatible dash list"); + if live { + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert!(text.contains("1 (Dashed) XW"), "an equivalent dash representation keeps the style link"); + assert!(text.contains("[33.5673] 2.5 d")); + } else { + assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings); + } + } +} + +#[test] +fn ai_dash_lists_in_legacy_text_reduce_or_outline_without_becoming_solid() { + use vectorcraft_doc::{CharStyle, TextObject}; + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + // Existing licensed test face, with original single-letter artwork. + vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()); + for (pattern, live) in [(vec![33.5673; 5], true), (vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], false)] { + let mut doc = Document::new(200.0, 100.0); + let st = CharStyle { + font_family: HEIGHT_FAMILY.into(), + size: 48.0, + fill: solid(Color::rgb(0.0, 1.0, 0.0)), + stroke: solid(Color::BLACK), + stroke_width: 2.0, + stroke_dash: Some(Dash { pattern, offset: 2.5, align_corners: false }), + ..CharStyle::default() + }; + let t = TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "T", st); + let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap(); + let out = crate::export_legacy_ai(&doc, &crate::LegacyAiOptions::default()).unwrap(); + let text = String::from_utf8(out.bytes).unwrap().replace("\r\n", "\n"); + assert_eq!(text.contains("0 To\n"), live, "irreducible type strokes must take the outline fallback"); + if live { + assert!(text.contains("[33.5673] 2.5 d")); + } else { + assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings); + assert!(text.matches("\nf\n").count() >= 2, "the glyph's fill and dashed stroke are both painted"); + } + } +} + /// A 200 × 100 document of a gradient fill, a compound path, an image and a symbol instance, and /// what the data holds as plain paths: type. fn unsupported() -> Document { diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 020b7bd901..eee71cf6d2 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -71,7 +71,7 @@ pub(super) const LIVE: &str = "repeats, placed documents, intertwines and distorted images are written as their art in the editing data for other apps"; pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort nested 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps"; pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps"; -pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; +pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, complex dash patterns, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; pub(super) const ITEM_TRANSPARENCY: &str = "the opacity and blending modes of single fills and strokes are left out of the editing data for other apps"; pub(super) const LAYER_MASKS: &str = "opacity masks on layers are left out of the editing data for other apps"; diff --git a/crates/eps/src/ai_editing/writer/blends.rs b/crates/eps/src/ai_editing/writer/blends.rs index b73749b214..11dad18d4c 100644 --- a/crates/eps/src/ai_editing/writer/blends.rs +++ b/crates/eps/src/ai_editing/writer/blends.rs @@ -364,7 +364,7 @@ fn plain_key(k: &Node) -> bool { && i.effects().is_empty() && i.opacity() >= 1.0 && i.blend() == BlendMode::Normal - && !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s) || !dash_read_back(s)) + && !matches!(i, AppearanceItem::Stroke(s) if !crate::ai_ops::plain_stroke(s) || !dash_read_back(s)) }); plain &= kind && fills <= 1 && strokes <= 1 && order && quiet && n.appearance.effects.is_empty() && n.extras().mask.is_none(); }); diff --git a/crates/eps/src/ai_editing/writer/brushes.rs b/crates/eps/src/ai_editing/writer/brushes.rs index c24dbdf1d7..9bd9457de5 100644 --- a/crates/eps/src/ai_editing/writer/brushes.rs +++ b/crates/eps/src/ai_editing/writer/brushes.rs @@ -258,7 +258,7 @@ fn plain_within(art: &Node, masks: u32) -> bool { && i.opacity() >= 1.0 && i.blend() == BlendMode::Normal && matches!(i.paint(), Paint::Solid { .. } | Paint::None) - && !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s)) + && !matches!(i, AppearanceItem::Stroke(s) if !crate::ai_ops::plain_stroke(s)) }); // A group's own fills and strokes aren't written. let group_paint = matches!(n.kind, NodeKind::Group { .. }) && items.iter().any(|i| !i.paint().is_none()); @@ -519,7 +519,7 @@ impl Writer<'_> { let name = st.brush.as_deref()?; self.brush_set(); let (plugin, kind) = self.live_brush(name).map(|b| (b.plugin, b.brush.kind.clone()))?; - if !matches!(st.paint, Paint::Solid { .. }) || st.overprint { + if !matches!(st.paint, Paint::Solid { .. }) || st.overprint || !ai_ops::dash_fits(st) { return None; } let ops = self.color_ops(&st.paint, true); diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index f1573c39ba..b97dd593cb 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -8,7 +8,6 @@ use vectorcraft_color::gradient::GradientGeom; use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; use vectorcraft_doc::{AppearanceItem, FillLayer, PatternDef, StrokeLayer, TileType}; -use vectorcraft_effects::stroke; use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2}; use super::{MAX_NEST, Writer, Xy}; @@ -367,7 +366,7 @@ impl Writer<'_> { /// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can /// write it)? pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool { - self.direct(&s.paint) && stroke::is_plain(s) + self.direct(&s.paint) && crate::ai_ops::plain_stroke(s) } /// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index 27ddf48be0..03f7e4b0e1 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -404,7 +404,7 @@ impl Writer<'_> { if st.brush.is_some() { return self.brush_filter(s, st, visible); } - if !matches!(st.paint, Paint::Solid { .. }) || st.overprint { + if !matches!(st.paint, Paint::Solid { .. }) || st.overprint || !ai_ops::dash_fits(st) { return None; } let ops = self.color_ops(&st.paint, true); @@ -1077,6 +1077,16 @@ pub(in crate::ai_editing) fn same_appearance(a: &Appearance, b: &Appearance) -> let below = ap.items.iter().take(ci).filter(|i| !i.paint().is_none()).count(); ap.items.retain(|i| !i.paint().is_none()); ap.contents_index = (below > 0).then_some(below); + // The writer shortens repeated dash lists without changing their painted period. + // Compare those representations equally so a linked style can stay live. + for i in &mut ap.items { + if let AppearanceItem::Stroke(st) = i + && let Some(d) = st.dash.as_mut().filter(|d| d.is_dashed()) + && let Some(pattern) = ai_ops::dash_pattern(&d.pattern) + { + d.pattern = pattern.to_vec(); + } + } for e in ap.effects.iter_mut().chain(ap.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) { e.params = normalized_params(e); } diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index b6941e4730..8255a3447a 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -425,8 +425,8 @@ fn plain_wrap_art(n: &Node, styled: &HashMap>) -> bool { let painted = || match super::visible_items(n).as_slice() { [] => true, [AppearanceItem::Fill(f)] => solid(&f.paint), - [AppearanceItem::Stroke(s)] => solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s), - [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s), + [AppearanceItem::Stroke(s)] => solid(&s.paint) && crate::ai_ops::plain_stroke(s), + [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && crate::ai_ops::plain_stroke(s), _ => false, }; let whole = |p: &PathData| p.subpaths.iter().all(|sp| sp.anchors.len() >= 2); diff --git a/crates/eps/src/ai_ops.rs b/crates/eps/src/ai_ops.rs index 9d0ff5ddc0..afc0d2ae71 100644 --- a/crates/eps/src/ai_ops.rs +++ b/crates/eps/src/ai_ops.rs @@ -179,7 +179,28 @@ pub(crate) fn window_samples(samples: &[u8], w: u32, channels: usize, [x0, y0, x out } -/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`. +/// The shortest equivalent dash list the AI reader can hold. Odd lists repeat twice before +/// dash/gap parity repeats. Keep at most six effective lengths: longer lists can make the +/// reader reject the entire file (#10476). Compare exactly, so no dash or gap changes length. +pub(crate) fn dash_pattern(pattern: &[f64]) -> Option<&[f64]> { + (1..=pattern.len().min(6)) + .filter(|n| n % 2 == 0 || *n <= 3) + .find(|n| pattern.len().is_multiple_of(*n) && pattern.iter().enumerate().all(|(i, v)| *v == pattern[i % n])) + .map(|n| &pattern[..n]) +} + +/// Invalid or empty dashes already draw solid; valid dashes need an exact short representation. +pub(crate) fn dash_fits(st: &StrokeLayer) -> bool { + st.dash.as_ref().filter(|d| d.is_dashed()).is_none_or(|d| dash_pattern(&d.pattern).is_some()) +} + +/// A plain AI stroke, including the reader's dash-list limit. Other strokes use filled outlines. +pub(crate) fn plain_stroke(st: &StrokeLayer) -> bool { + vectorcraft_effects::stroke::is_plain(st) && dash_fits(st) +} + +/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`. Callers check +/// [`dash_fits`] first; irreducible longer patterns belong in their outline fallback. pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) { let cap = match st.cap { LineCap::Butt => ps::LineCap::Butt, @@ -191,6 +212,6 @@ pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) { LineJoin::Round => ps::LineJoin::Round, LineJoin::Bevel => ps::LineJoin::Bevel, }; - let dash = st.dash.as_ref().filter(|d| d.is_dashed()).map(|d| (d.pattern.as_slice(), d.offset)); + let dash = st.dash.as_ref().filter(|d| d.is_dashed()).and_then(|d| dash_pattern(&d.pattern).map(|p| (p, d.offset))); ps::push_line_style(s, st.width, cap, join, st.miter_limit, dash); } diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 8fbfcf3e83..a41c7dc442 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -125,8 +125,7 @@ const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in pro const PERCEPTUAL_STOPS: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)"; /// Wedges a conic gradient is written as: one a degree. const CONIC_WEDGES: usize = 360; -const STROKES: &str = - "strokes a plain line can't draw (inside or outside the path, variable width, gradients, brushes, arrowheads) are written as filled outlines"; +const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, complex dash patterns, gradients, brushes, arrowheads) are written as filled outlines"; const IMAGE_ALPHA: &str = "transparent image pixels are written over white"; const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents, intertwines and distorted images are written as their art"; const DEEP_DISTORTED: &str = diff --git a/crates/eps/src/legacy_ai/encoding.rs b/crates/eps/src/legacy_ai/encoding.rs index a1c40ca28f..65825a6b2e 100644 --- a/crates/eps/src/legacy_ai/encoding.rs +++ b/crates/eps/src/legacy_ai/encoding.rs @@ -1,7 +1,7 @@ use super::writer::Writer; use super::{ Affine, AreaOptions, BezPath, CharPosition, CharStyle, CompositeFont, Document, Gradient, GradientKind, Paint, ParaStyle, PathAlign, PathEffect, - StrokeLayer, TextKind, TextObject, Write, latin, ps, stroke, + StrokeLayer, TextKind, TextObject, Write, latin, ps, }; /// A gradient definition: `%AI5_BeginGradient: (name)`, `(name) type stops Bd`, `[`, the stops @@ -111,6 +111,9 @@ pub(super) fn holds_as_text(t: &TextObject) -> bool { r.inline.is_none() && solid(&r.style.fill) && solid(&r.style.stroke) + // Long dash lists can reject the entire AI file. Keep their glyph paint by + // taking the existing type-outline path instead of writing a solid stroke. + && (!r.style.has_stroke() || crate::ai_ops::dash_fits(&r.style.stroke_layer())) && (if r.style.all_caps { r.text.to_uppercase() } else { r.text.clone() }).chars().all(|c| latin::encode(c).is_some()) }) } @@ -221,5 +224,5 @@ pub(super) fn direct_fill(p: &Paint) -> bool { /// Can stroke `s` be written as the stroke of a path object (a plain line of a colour)? pub(super) fn direct_stroke(s: &StrokeLayer) -> bool { - matches!(s.paint, Paint::Solid { .. }) && stroke::is_plain(s) + matches!(s.paint, Paint::Solid { .. }) && crate::ai_ops::plain_stroke(s) } diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index d8b9a96295..6813b300aa 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -34,6 +34,7 @@ //! - `ai_graph`: the records of a live graph those two write around its group. //! - `gradient_key`: the key those two find gradient definitions by. //! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing. +#![doc(test(attr(deny(unsafe_code))))] mod ai_editing; mod ai_graph; diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 9975527f78..c7157df94d 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -37,6 +37,7 @@ //! already; [`save_with`] writes a version 1 document with them negated back for an older file //! version ([`vectorcraft_doc::twist`]). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #[cfg(not(target_arch = "wasm32"))] mod atomic; diff --git a/crates/geom/src/hit.rs b/crates/geom/src/hit.rs index fea760b548..2624f0a1a9 100644 --- a/crates/geom/src/hit.rs +++ b/crates/geom/src/hit.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; -use kurbo::{BezPath, ParamCurveNearest, PathEl, Point, Rect, Shape}; +use kurbo::{BezPath, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Shape}; use crate::path::{FillRule, PathData}; @@ -104,13 +104,51 @@ fn closed(path: &BezPath) -> Cow<'_, BezPath> { /// Distance from `p` to the nearest point on the path outline. pub fn distance_to_outline(path: &BezPath, p: Point) -> f64 { - path.segments().map(|s| s.nearest(p, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt() + path.segments().map(|s| nearest_distance_sq(s, p)).fold(f64::INFINITY, f64::min).sqrt() } /// Is `p` within `tol` of the path's stroke of width `width`? pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool { - let quick = path.bounding_box().inflate(width / 2.0 + tol, width / 2.0 + tol); - quick.contains(p) && distance_to_outline(path, p) <= width / 2.0 + tol + let radius = width / 2.0 + tol; + if !path.bounding_box().inflate(radius, radius).contains(p) { + return false; + } + if !radius.is_finite() { + return distance_to_outline(path, p) <= radius; + } + + // Keep candidates whose squared distance could underflow near a zero radius. + let search_radius = radius.max(f64::MIN_POSITIVE.sqrt()); + path.segments().any(|segment| !curve_outside_reach(segment, p, search_radius) && nearest_distance_sq(segment, p).sqrt() <= radius) +} + +// A Bézier stays inside the bounds of its control points. A line projection is +// already cheap, so only check the bounds before running a curve solver. +fn curve_outside_reach(segment: PathSeg, p: Point, radius: f64) -> bool { + let bounds = match segment { + PathSeg::Line(_) => return false, + PathSeg::Quad(q) => Rect::from_points(q.p0, q.p1).union_pt(q.p2), + PathSeg::Cubic(c) => Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3), + }; + outside_axis(p.x, radius, bounds.x0, bounds.x1) || outside_axis(p.y, radius, bounds.y0, bounds.y1) +} + +fn outside_axis(p: f64, radius: f64, low: f64, high: f64) -> bool { + // Leave room for rounding in the curve evaluation and the distance comparison. + let scale = p.abs().max(low.abs()).max(high.abs()).max(radius); + let padded = radius + 8.0 * f64::EPSILON * scale; + p < low - padded || p > high + padded +} + +fn nearest_distance_sq(segment: PathSeg, p: Point) -> f64 { + #[cfg(test)] + OUTLINE_NEAREST_CALLS.with(|count| count.set(count.get() + 1)); + segment.nearest(p, 1e-9).distance_sq +} + +#[cfg(test)] +thread_local! { + static OUTLINE_NEAREST_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Does the path touch the rect: an anchor inside it, or a segment crossing its edges? Used for @@ -185,6 +223,53 @@ mod tests { assert!(!stroke_contains(&p, 2.0, 0.0, Point::new(12.0, 5.0))); } + #[test] + fn stroke_hit_skips_distant_curves_without_changing_results() { + let mut path = BezPath::new(); + for i in 0..96 { + let x = f64::from(i) * 16.0; + path.move_to((x, 0.0)); + path.curve_to((x + 1.0, 4.0), (x + 2.0, -4.0), (x + 3.0, 0.0)); + } + path.move_to((512.0, 0.0)); + path.quad_to((513.0, 4.0), (514.0, 0.0)); + + for (point, expected_hit, expected_calls) in [(Point::new(512.0, 0.0), true, 1), (Point::new(520.0, 0.0), false, 0)] { + assert_eq!(distance_to_outline(&path, point) <= 0.5, expected_hit); + assert!(path.bounding_box().contains(point)); + OUTLINE_NEAREST_CALLS.with(|count| count.set(0)); + assert_eq!(stroke_contains(&path, 0.0, 0.5, point), expected_hit); + assert_eq!(OUTLINE_NEAREST_CALLS.with(std::cell::Cell::get), expected_calls); + } + + assert_stroke_hits_at_cutoff(); + } + + fn assert_stroke_hits_at_cutoff() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((0.0, 0.0)); + path.quad_to((4.0, 8.0), (8.0, 0.0)); + path.curve_to((12.0, 8.0), (16.0, -4.0), (20.0, 0.0)); + path.close_path(); + path.move_to((2.0, -3.0)); + path.line_to((2.0, -3.0)); + + for transform in [kurbo::Affine::IDENTITY, kurbo::Affine::new([-2.0, 1.0, 0.0, 1.0, 10.0, 1e8])] { + let transformed = transform * path.clone(); + for x in -2..23 { + for y in -5..9 { + let point = transform * Point::new(f64::from(x), f64::from(y)); + let distance = distance_to_outline(&transformed, point); + for radius in [distance.next_down(), distance, distance.next_up(), 0.0, 1.5] { + let inside = transformed.bounding_box().inflate(radius, radius).contains(point); + assert_eq!(stroke_contains(&transformed, 0.0, radius, point), inside && distance <= radius, "{point:?}, {radius}"); + } + } + } + } + } + #[test] fn evenodd_hole() { let mut outer = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 3f11c71062..8a4cb4f7fb 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -6,6 +6,7 @@ //! //! Coordinates are document points (1/72 in), y pointing down. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod anchors; pub mod arc; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index a720940b06..77b3e00856 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -131,6 +131,7 @@ //! `await` (ECMA-262 2017 section 25.5, ). //! An `await` suspends its function's frame until the value settles, and a promise job resumes it. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod ast; mod builtins; diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index efc9d44830..7e104e85f2 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -13,6 +13,7 @@ //! //! Entry points: [`Server::serve`] (stdio loop) and [`Server::handle_line`] (one message). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod backend; mod headless; diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index df23cbb073..66f3c4327b 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -26,6 +26,7 @@ //! formats. //! //! The app walks its document and maps its drawing operations to the shared writers. +#![doc(test(attr(deny(unsafe_code))))] #[cfg(test)] mod bytes; diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index da7960af0f..0190233191 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -5,6 +5,7 @@ //! Béziers, and the pieces it splits curves into are refitted afterwards so results carry few //! anchors. See the crate README for the API overview. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod boolean; diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index b3b5de36a4..a093ecc9c0 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -1,5 +1,7 @@ use std::collections::HashMap; +use vectorcraft_geom::Vec2; + use super::exporter::{UNDECODED, address, blend, color, constant_mask, cover, in_range, norm, rects_overlap, rule, to_path, writable, xf}; use super::{ Affine, AppearanceItem, BezPath, BlendMode, Document, Exporter, Fill, FillRule, GradientKind, LineCap, LineJoin, Mark, Node, NodeKind, @@ -19,6 +21,37 @@ fn brushed(b: Option, reach: f64) -> Option { if reach > 0.0 { b.map(|b| b.inflate(reach, reach)) } else { b } } +/// Can the patch shade its own outline without folding across it? The differences of adjacent +/// tensor control points bound each directional derivative in a convex cone. If every pair of +/// derivatives has the same strict orientation, averaging them along any segment keeps them +/// independent, so distinct parameter points cannot map to the same point. +fn unfolded_patch(points: [(f32, f32); 12]) -> bool { + let p = points.map(|(x, y)| Vec2::new(f64::from(x), f64::from(y))); + let top = [p[0], p[11], p[10], p[9]]; + let bottom = [p[3], p[4], p[5], p[6]]; + let left = [p[0], p[1], p[2], p[3]]; + let right = [p[9], p[8], p[7], p[6]]; + // Raise the linear blending terms of the Coons surface to cubic degree in each direction. + let net: [[Vec2; 4]; 4] = std::array::from_fn(|row| { + let v = row as f64 / 3.0; + std::array::from_fn(|col| { + let u = col as f64 / 3.0; + let bilinear = (p[0] * (1.0 - u) + p[9] * u) * (1.0 - v) + (p[3] * (1.0 - u) + p[6] * u) * v; + top[col] * (1.0 - v) + bottom[col] * v + left[row] * (1.0 - u) + right[row] * u - bilinear + }) + }); + let du: [[Vec2; 3]; 4] = std::array::from_fn(|row| std::array::from_fn(|col| net[row][col + 1] - net[row][col])); + let dv: [[Vec2; 4]; 3] = std::array::from_fn(|row| std::array::from_fn(|col| net[row + 1][col] - net[row][col])); + let orientation = du[0][0].cross(dv[0][0]).signum(); + du.into_iter().flatten().all(|u| { + dv.iter().flatten().all(|v| { + let cross = u.cross(*v) * orientation; + // Keep near-parallel directions on the existing clipped path through PDF quantization. + cross > 0.0 && cross * cross > 1e-12 * u.hypot2() * v.hypot2() + }) + }) +} + #[cfg(test)] std::thread_local! { /// The objects this thread has measured for the walk and for the links (tests). @@ -542,7 +575,7 @@ impl Exporter<'_> { } } - /// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading filling its outline (ISO 32000-1, + /// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading (ISO 32000-1, /// 8.7.4.5.7): each patch blends its corner colours bilinearly, as the canvas draws it, and /// the viewer or RIP does so smoothly at its own resolution. Cutting the mesh into flat quads /// instead banded, left seams between them, and made files with many meshes very large. @@ -560,7 +593,6 @@ impl Exporter<'_> { if !writable(s, Affine::IDENTITY, bounds) { return false; } - let Some(path) = to_path(s, &m.outline().to_bezpath()) else { return false }; let page: Vec = m.points.iter().map(|p| self.page_color(&p.color)).collect(); let mixed = page.windows(2).any(|w| w[0].model() != w[1].model()); let rgb = page.iter().any(|c| matches!(c, vectorcraft_color::Color::Rgb { .. } | vectorcraft_color::Color::Lab { .. })); @@ -584,6 +616,14 @@ impl Exporter<'_> { patches.push(krilla::paint::MeshPatch { points, colors, opacities: [NormalizedF32::ONE; 4] }); } } + // An unfolded single patch shades its own outline. Filling that exact outline makes some + // readers antialias it twice and leave seams where patches touch. Keep the outline for + // folded geometry and for meshes with more than one patch, which can overlap themselves. + let bounds_path = match patches.as_slice() { + [patch] if unfolded_patch(patch.points) => to_path(s, &bounds.inflate(1.0, 1.0).to_path(0.1)), + _ => None, + }; + let Some(path) = bounds_path.or_else(|| to_path(s, &m.outline().to_bezpath())) else { return false }; let mesh = krilla::paint::MeshGradient { patches, transform: xf(Affine::IDENTITY), anti_alias: false }; s.set_stroke(None); s.set_fill(Some(Fill { paint: mesh.into(), opacity: NormalizedF32::ONE, rule: krilla::paint::FillRule::NonZero })); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 2dc6f1ec0a..a7118fd37a 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -42,6 +42,7 @@ //! security handler, the algorithm following the compatibility ([`Encryption`]); either password //! opens an encrypted file. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod editing; mod encrypt; diff --git a/crates/pdf/src/tests/mesh_export.rs b/crates/pdf/src/tests/mesh_export.rs index b2e8ecb2f6..b36926da21 100644 --- a/crates/pdf/src/tests/mesh_export.rs +++ b/crates/pdf/src/tests/mesh_export.rs @@ -2,12 +2,16 @@ //! viewer blends each patch's corner colours smoothly, instead of the mesh being cut into small //! flat-coloured paths that band, show seams and make the file large. +use craft::pdf::syntax::content::{TypedIter, ops::TypedInstruction}; +use craft::pdf::syntax::object::{Name, Object}; use vectorcraft_color::Color; use vectorcraft_doc::live::{GradientMesh, MeshAppearance}; use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; use vectorcraft_testkit::raster::{assert_similar, render_artboard}; +use super::import_fidelity::stream; use crate::*; /// A 200 × 200 pt document with a 2 × 2 mesh over (20, 20)–(180, 180), its nine points coloured @@ -44,6 +48,76 @@ fn kinds(d: &Document) -> (usize, usize) { (meshes, paths) } +fn import_patches(boundaries: &[[(u8, u8); 12]]) -> Document { + use std::fmt::Write as _; + let mut data = String::new(); + for boundary in boundaries { + data.push_str("00"); // Every patch supplies all its vertices. + for (x, y) in boundary { + write!(data, "{x:02X}{y:02X}").unwrap(); + } + data.push_str(&"28465A".repeat(4)); + } + data.push('>'); + let shading = stream( + "/ShadingType 6 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 \ + /Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode", + &data, + ); + let page = PdfPage { + resources: format!("/Shading << /Mesh {} 0 R >>", first_extra(1)), + ..PdfPage::new(100.0, 100.0, "q 0.8 0 0 0.8 10 10 cm /Mesh sh Q") + }; + let imported = import(&pdf_with(&[page], &[&shading], None)).unwrap(); + assert_eq!(kinds(&imported).0, boundaries.len()); + imported +} + +fn has_curved_outline(bytes: &[u8]) -> bool { + let output = crate::pages::open(bytes, None).unwrap(); + let pages = output.pages(); + let has_curve = |content: &[u8]| { + let mut ops = TypedIter::new(content); + while let Some(op) = ops.next() { + if matches!(op, TypedInstruction::CubicTo(_) | TypedInstruction::CubicStartTo(_) | TypedInstruction::CubicEndTo(_)) { + return true; + } + } + false + }; + if has_curve(pages.iter().next().unwrap().page_stream().unwrap()) { + return true; + } + output.objects().into_iter().any(|object| match object { + Object::Stream(form) if form.dict().get::>(b"Subtype").is_some_and(|name| name.as_ref() == b"Form") => { + has_curve(&form.decoded().unwrap()) + } + _ => false, + }) +} + +#[test] +fn joined_opaque_pdf_meshes_keep_their_shading_edges_on_export() { + // The same cubic, in opposite directions, is the two patches' inner edge. + let imported = import_patches(&[ + [(10, 95), (10, 65), (10, 35), (10, 5), (25, 5), (40, 5), (55, 5), (61, 30), (41, 70), (45, 95), (35, 95), (22, 95)], + [(45, 95), (41, 70), (61, 30), (55, 5), (68, 5), (82, 5), (90, 5), (90, 35), (90, 65), (90, 95), (75, 95), (60, 95)], + ]); + let bytes = export(&imported, &PdfOptions::default()).unwrap(); + assert!(!has_curved_outline(&bytes), "the writer must leave the shared curved edge to the shading itself"); + let reimported = import(&bytes).unwrap(); + assert_eq!(kinds(&reimported).0, 2, "both patches still export as vector shadings"); + assert_similar(&render_artboard(&imported), &render_artboard(&reimported), 6.0, 0.01); +} + +#[test] +fn folded_pdf_mesh_still_uses_its_outline() { + let imported = + import_patches(&[[(10, 95), (92, 65), (93, 35), (10, 5), (25, 5), (40, 5), (90, 5), (4, 30), (3, 70), (90, 95), (65, 95), (42, 95)]]); + let bytes = export(&imported, &PdfOptions::default()).unwrap(); + assert!(has_curved_outline(&bytes), "a rectangle would expose folded paint outside the intended outline"); +} + #[test] fn a_gradient_mesh_is_written_as_a_smooth_patch_shading() { let d = doc(rgb, 1.0); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index c9c0e89521..4f79939c62 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -42,6 +42,7 @@ //! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each //! run, with the same input, output, permissions and budgets. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod deferred; pub mod dialog; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4358cc180d..f2b76c525d 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5,6 +5,7 @@ //! (multiple fills/strokes, opacity, blend modes, stroke alignment, dashes), clip groups, //! gradients, images and text (via `vectorcraft-text` glyph outlines). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod brush_fx; diff --git a/crates/scriptcheck/src/lib.rs b/crates/scriptcheck/src/lib.rs index 9460048684..868752339a 100644 --- a/crates/scriptcheck/src/lib.rs +++ b/crates/scriptcheck/src/lib.rs @@ -22,6 +22,7 @@ //! keeps open brackets and the levels of an XML literal on capped stacks. Its work is linear in the //! input's size, and no input can overflow the stack. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod analyze; mod catalog; diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 222b90b25c..109b3a938a 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -100,6 +100,7 @@ //! letter and word spacing become character attributes (line breaks, kerning, baseline shift, //! rotation and style names). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use craft_svg::tree::usvg; mod css; diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index fa7b39aa9d..fd86ad3c89 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -22,6 +22,7 @@ // apply here. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod ai; pub mod ase; diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index 28b2dc2662..0714822b7b 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -171,10 +171,13 @@ mod tests { let expected: Vec<_> = ["Noto Sans Arabic", "Noto Sans Thai", "Noto Sans Georgian"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); assert_eq!(startup, expected); - // Korean and Devanagari faces are fetched only on demand, never at startup or in the - // background queue every session runs. + // Korean, Devanagari and Gujarati faces are fetched only on demand, never at startup or in + // the background queue every session runs. let demand: Vec<_> = WEB_FONTS.iter().filter(|w| w.demand).map(|w| w.family).collect(); - let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); + let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari", "Noto Sans Gujarati"] + .into_iter() + .filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)) + .collect(); assert_eq!(demand, expected); assert!(WEB_FONTS.iter().all(|w| !(w.startup && w.demand))); } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 25e44392d6..4723f1ffcd 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -9,6 +9,7 @@ //! //! Frames (`TextKind::Area`) and paths (`TextKind::OnPath`) are interpreted in text space. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod bitmap; mod colr; diff --git a/crates/text/web-fonts.txt b/crates/text/web-fonts.txt index d46cfe41c5..67144e95ad 100644 --- a/crates/text/web-fonts.txt +++ b/crates/text/web-fonts.txt @@ -3,10 +3,11 @@ # startup = fetched before the app starts (fallbacks the first frame needs) # background = fetched after the app starts (fonts users pick by name) # demand = fetched only when the interface language or the interface's own text needs one of -# the face's scripts (Korean, Hindi) +# the face's scripts (Korean, Hindi, Gujarati) # Read by build.rs (the WEB_FONTS table) and `cargo xtask web-fonts` (copies the files, a Trunk hook). startup | Noto Sans Arabic | Regular startup | Noto Sans Thai | Regular startup | Noto Sans Georgian | Regular demand | NanumGothic | Regular demand | Noto Sans Devanagari | Regular +demand | Noto Sans Gujarati | Regular diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index f561c0b7c6..37768ea651 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -7,6 +7,7 @@ //! //! [`fold`] finds the panels and hinges of a flat packaging blank from its fold lines. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod fold; mod solid; diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index c1c4bcbfb2..cf3551fc19 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -110,6 +110,8 @@ struct HandlePress { moved: bool, /// The picked handles when the press began. picked: PickedHandles, + /// A mirroring Cmd/Ctrl press on one of several picked handles: they stay picked after its drag. + keeps_picks: bool, } #[derive(Clone, Debug)] @@ -1046,6 +1048,33 @@ impl Tool for DirectSelectionTool { self.lent_cmd = value.as_bool().unwrap_or(false); } } + /// A Cmd/Ctrl press without Alt on the end of a shown direction handle (a path's, type on a + /// path's or a selected blend spine anchor's) stays with Direct Selection, so the drag mirrors + /// the opposite handle ([`DirectSelectionTool::mirrors`]). A press on a handle of the bounding + /// box the lent Selection tool shows still goes to that tool, and so does a press anywhere else, + /// including one that a press of the tool gives to something it checks before the handles (a + /// corner widget, a bracket of type on a path, a gradient mesh point). + fn keeps_cmd_press(&self, cx: &ToolContext, p: Point, mods: Mods) -> bool { + if self.group || mods.alt || crate::select::bbox_handle_at(cx, p) { + return false; + } + let point = cx.point_tol(); + // The order of the checks is the order `pointer` tries them in on a press. + let ev = PointerEvent::new(PointerKind::Down, p.x, p.y).with_mods(mods); + if CornerDrag::hit(cx, &ev, true).is_some_and(|c| !(c.on_unpicked() && c.widget_center().is_some_and(|w| yields_to_point(cx, p, w)))) { + return false; + } + if !over_path_type_anchor(cx, p) && BracketDrag::hit_any(cx, &ev).is_some() { + return false; + } + if self.spine.filter(|(id, _)| cx.selection.contains(*id)).and_then(|sel| hit_spine_handle(cx, sel, p, point)).is_some() { + return true; + } + if self.mesh.hit(cx, &cx.selection.objects, p).is_some() { + return false; + } + hit_handle(cx, p, point).is_some() + } /// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh /// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved /// goes back and the tool waits for the next press (#1743). @@ -1087,13 +1116,16 @@ impl Tool for DirectSelectionTool { self.mesh.cancel(); // The frame anchors or handles a cancelled drag held stay selected. let frame = matches!(self.state, State::TypeArea { .. }) && !self.frame.is_empty(); - let handles = matches!(self.state, State::Handles { .. }); + let kept = self.handle_press.take().filter(|press| press.keeps_picks && matches!(self.state, State::Handle { .. })); + let handles = matches!(self.state, State::Handles { .. }) || kept.is_some(); + if let Some(press) = kept { + self.handles = press.picked; + } self.state = State::Idle; self.guides.clear(); (self.anchor_snap, self.copy_snap, self.move_snap) = (None, None, None); self.last_location = None; (self.click, self.click_segment, self.click_group, self.frame_click) = (None, None, None, None); - self.handle_press = None; match (frame, handles) { (true, _) => vec![Action::Cancel, Action::Notify(FRAME_PICKED.into())], (_, true) => vec![Action::Cancel, Action::Notify(HANDLES_PICKED.into())], @@ -1896,9 +1928,11 @@ impl DirectSelectionTool { self.state = State::Handle { id, si, ai, out, drag: Some(drag) }; vec![Action::Preview("path.setHandle".into(), params)] } - /// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift on one of two or - /// more picked handles (`picks`, as they were before the press), a drag moves them all; any - /// other press drags that handle alone, as before handles could be picked. + /// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift or a mirroring + /// Cmd/Ctrl ([`Self::mirrors`]) on one of two or more picked handles (`picks`, as they were + /// before the press), a drag moves them all; any other press drags that handle alone, as before + /// handles could be picked, so a Cmd/Ctrl drag mirrors its opposite handle. The picked handles + /// stay picked after such a Cmd/Ctrl or Cmd/Ctrl+Shift drag of one of them. fn press_handle( &mut self, cx: &ToolContext, @@ -1931,8 +1965,11 @@ impl DirectSelectionTool { }; let handle = (id, (si, ai, out)); let on = picks.get(&id).is_some_and(|set| set.contains(&handle.1)); - let several = on && !ev.mods.shift && picks.values().map(BTreeSet::len).sum::() > 1; - let begin = if several { + let one_of_several = on && picks.values().map(BTreeSet::len).sum::() > 1; + let among_several = one_of_several && !ev.mods.shift; + // A mirroring drag keeps the picks with Shift held too. + let keeps_picks = one_of_several && self.mirrors(ev); + let begin = if among_several && !keeps_picks { let items = picks.iter().flat_map(|(id, set)| set.iter().map(|h| (*id, *h))).collect(); self.state = State::Handles { handle, from, start: p, items, began: false }; self.handles = picks.clone(); @@ -1942,7 +1979,7 @@ impl DirectSelectionTool { self.state = State::Handle { id, si, ai, out, drag }; vec![Action::Begin("Reshape".into())] }; - self.handle_press = Some(HandlePress { handle, at: p, shift: ev.mods.shift, moved: false, picked: picks }); + self.handle_press = Some(HandlePress { handle, at: p, shift: ev.mods.shift, moved: false, picked: picks, keeps_picks }); begin } /// The release of a press on one of several picked handles: a drag commits, and the picked @@ -1957,10 +1994,18 @@ impl DirectSelectionTool { self.handles = BTreeMap::from([(handle.0, BTreeSet::from([handle.1]))]); vec![Action::Notify(HANDLES_PICKED.into())] } - /// After the release of a press on a handle that did not drag: a click picks the handle alone, - /// and a Shift-click adds it to the picked handles or takes it away. + /// After the release of a press on a handle: a click picks the handle alone, and a Shift-click + /// adds it to the picked handles or takes it away. A mirroring drag of one of several picked + /// handles leaves them all picked. fn pick_clicked_handle(&mut self) -> Option { - let press = self.handle_press.take().filter(|press| !press.moved)?; + let press = self.handle_press.take()?; + if press.moved { + if !press.keeps_picks { + return None; + } + self.handles = press.picked; + return Some(Action::Notify(HANDLES_PICKED.into())); + } let (id, h) = press.handle; let mut picked = if press.shift { press.picked } else { BTreeMap::new() }; let set = picked.entry(id).or_default(); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 5a32145ec0..bee869a8e8 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -6,6 +6,7 @@ //! and journal entry. One-shot `Exec` actions run immediately. This makes every gesture replayable //! by the control channel and MCP, and keeps tools testable without a UI. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; pub mod bbox; @@ -278,6 +279,12 @@ pub trait Tool: Send { fn hover_object(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Option { None } + /// Does a press at `p` with Cmd/Ctrl and `mods` held stay with the tool, instead of going to + /// the selection tool the session lends for Cmd/Ctrl? Direct Selection keeps a press on a shown + /// direction handle, where Cmd/Ctrl mirrors the opposite handle. + fn keeps_cmd_press(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> bool { + false + } /// What the Info panel shows for the tool as it is now: the drag in progress (a move of the /// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear /// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show. diff --git a/crates/trace/src/lib.rs b/crates/trace/src/lib.rs index 7bb59c79b1..02acf76de0 100644 --- a/crates/trace/src/lib.rs +++ b/crates/trace/src/lib.rs @@ -46,6 +46,7 @@ //! it, so each enclosed outline is fitted once. An area that holds a transparent pixel or a color //! left out stays a hole. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod centerline; mod contour; diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 416cc2c6d2..654e9492b2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -11,7 +11,7 @@ use craft::ui::docking::IconGroupSeparator; use craft::ui::list::{CommandHighlight, ThumbRows}; use craft::ui::menu::{MenuTitleLook, MenuTitlePad}; use craft::ui::patterns::form_dialogs::PresetCardLook; -use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey}; +use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey, WordsOverride, with_env}; use craft::ui::runtime::frame::{FrameInput, FrameOutput}; use craft::ui::runtime::toast::{self, Toast}; use craft::ui::runtime::windows::WindowHost; @@ -471,6 +471,9 @@ impl VectorcraftApp { let lang = self.ui_language(); if self.host.lang() != lang { self.host = Arc::new(self.host.with_lang(lang)); + if let Some(ctx) = &self.ui_ctx { + crate::ui_fonts::follow_language(ctx, lang); + } } let native_ppp = self.ui_ctx.as_ref().map_or(1.0, |ctx| ctx.pixels_per_point() / ctx.zoom_factor()); // The canvas steps through the zoom stops of the current window's display. @@ -772,7 +775,7 @@ impl VectorcraftApp { let mut control_bar_place = chrome::control_bar_place(&self.ui); // PLAN: assumed `chrome::window_title(&VectorcraftApp) -> String` (shell-01 A1 names the call, no row gives its signature; shell-w9). let window_title = chrome::window_title(self); - let shown = AppShell::new(WindowKey::main()) + let shell = AppShell::new(WindowKey::main()) .title_bar_if(true, |_| None, chrome::app_bar) .options_bar( self.ui.control_bar, @@ -802,8 +805,11 @@ impl VectorcraftApp { .body(|ui, cx, app: &mut VectorcraftApp| { panel_docking::show(app, ui, cx.shell().is_some_and(|shell| shell.panels_hidden())); crate::place::window_files(app, ui); - }) - .show(ui, self); + }); + // The shell shows the window's dialogs under these words. Temporary: removed once the craft-libs pin includes + // storytold/craft-libs#4891 and #5291 (`dialogs::shell_words`). + let words = dialogs::shell_words(self).map(WordsOverride::Overlay); + let shown = with_env(ui, |env| env.words = words, |ui| shell.show(ui, self)); chrome::set_control_bar_place(&mut self.ui, control_bar_place); if shown.screen_mode != given { self.ui.follow_screen_mode(shown.screen_mode); diff --git a/crates/ui-egui/src/canvas/home.rs b/crates/ui-egui/src/canvas/home.rs index 5034e23f17..b7d6620836 100644 --- a/crates/ui-egui/src/canvas/home.rs +++ b/crates/ui-egui/src/canvas/home.rs @@ -1,12 +1,13 @@ use craft::behavior::{ColumnWidth, IconId}; +use craft::i18n::WordSet as _; use craft::ui::buttons::{Link, LinkLook}; use craft::ui::contract::{Bind, Gap, Pad, Props as _, Show as _, ShowContainer as _, clicked}; use craft::ui::display::Text; use craft::ui::layout::CellAlign; use craft::ui::layout_components::{Grid, Stack}; -use craft::ui::runtime::env::{Env, Overrides, with_env}; +use craft::ui::runtime::env::{Env, Overrides, WordRows, WordsOverride, with_env}; use craft::ui::sections::Section; -use craft::ui::shell::{RecentFile, StartAction, StartLayout, StartLink, StartPlace, StartScreen, Template}; +use craft::ui::shell::{RecentFile, ShellWords, StartAction, StartLayout, StartLink, StartPlace, StartScreen, Template}; use craft::ui::style::{SurfaceKind, TypeRole}; use super::{Ui, VectorcraftApp, json}; @@ -45,9 +46,14 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { } let mut pressed = None; let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min))); - // Production's community links read in the accent alone, with no underline. - let plain_links = |overrides: &mut Overrides| { + let words = recent_words(app.ui_language()); + // Production's community links read in the accent alone, with no underline, and the recent files are headed + // "Recent Files". + let set_env = |overrides: &mut Overrides| { overrides.values.set(LinkLook::Plain); + if let Some(words) = words { + overrides.words = Some(WordsOverride::Overlay(words)); + } }; // Learn follows the presets, which stand right under New and Open as in production 0.24.1. let start = StartScreen::new(Bind::bound(&mut app.ui.home_view), Bind::bound(&mut app.ui.home_sort), &recent) @@ -62,7 +68,7 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { .links(&links) .links_title(tl!("Community")) .section(StartPlace::AfterSections, |ui, _| learn(ui, &mut pressed)); - let out = with_env(&mut child, plain_links, |ui| start.show(ui)); + let out = with_env(&mut child, set_env, |ui| start.show(ui)); for action in out.actions { run_action(app, action); } @@ -73,6 +79,17 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { } } +/// VectorCraft's heading for the Home screen's recent files, "Recent Files", over the framework's "Recent". Outside +/// English, a language whose catalog does not translate it keeps the framework's translation. +// Workaround for craft-libs#4890: once the craft-libs pin includes it, the start screen's `recent_title` heads the +// list, and this word row is removed. +fn recent_words(lang: crate::i18n::Lang) -> Option { + const ENGLISH: &str = "Recent Files"; + let shown = crate::i18n::tr(lang, ENGLISH); + let word = ShellWords::word("startScreen.recent")?; + (lang == crate::i18n::Lang::EN || shown != ENGLISH).then(|| WordRows::new().row(word, shown)) +} + /// What the start screen's user did. A command that fails says why in the status bar (#6160). fn run_action(app: &mut VectorcraftApp, action: StartAction) { fn run(app: &mut VectorcraftApp, id: &str, params: serde_json::Value) { diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index f4c1d52986..a0554f26bb 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -45,3 +45,40 @@ fn every_cursor_icon_the_app_names_is_in_its_set() { } } } + +/// Painted cursors use the SVG's alpha as ink. Drawing the vent in white makes it solid ink. +#[test] +fn the_painted_pen_nibs_keep_their_breather_holes() { + use craft::ui::primitives::{painted_image, register_app_icons}; + use craft::ui::runtime::env::Env; + use craft::ui::style::rgba_color; + + register_app_icons(&crate::icons::APP_ICONS); + register_app_icons(&CURSOR_ICONS); + crate::testing::ui_context() + .run_ui(Default::default(), |ui| { + let env = Env::of(ui); + let tokens = env.tokens.tokens(); + let ink = rgba_color(tokens.color.overlay.cursor); + let is_ink = |px: &[u8]| px[3] >= 240 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8); + let scale = 4.0; + let from_art_units = tokens.size.icon.md * scale / 24.0; + for c in [Cursor::Pen, Cursor::PenConvert, Cursor::PenJoin, Cursor::Curvature] { + let cb::Cursor::Painted(painted @ PaintedCursor::Tool { hotspot, .. }) = tool_cursor(c) else { + panic!("{c:?} must have painted tool art"); + }; + let image = painted_image(&env, &painted, scale).expect("the cursor fits in its bitmap"); + let [hx, hy] = image.hotspot.map(f32::from); + let pixel = |x: f32, y: f32| { + let x = (hx + (x - hotspot.x) * from_art_units).round() as usize; + let y = (hy + (y - hotspot.y) * from_art_units).round() as usize; + let i = (y * usize::from(image.size[0]) + x) * 4; + &image.rgba[i..i + 4] + }; + assert!(is_ink(pixel(9.5, 13.2)), "{c:?}: the nib body is ink"); + assert!(!is_ink(pixel(6.62, 12.86)), "{c:?}: the vent must break up the ink"); + } + }) + .textures_delta + .clear(); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index eee24e9a47..de49632c4c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -189,6 +189,15 @@ pub(crate) use export_for_screens::{ }; pub(crate) use new_document::preset_name; pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document}; + +/// The words the window's shell shows its dialogs under: the rows of the open dialogs whose framework words VectorCraft +/// changes for now (`print::title_words`, `new_document::name_words`), or `None` when no such dialog is open. +pub(crate) fn shell_words(app: &crate::VectorcraftApp) -> Option { + [print::title_words(app), new_document::name_words(app)] + .into_iter() + .flatten() + .reduce(|rows, more| more.iter().fold(rows, |rows, (word, text)| rows.row(word, text))) +} pub use png_options::open as open_raster_options; pub use save_pdf::{open as open_save_pdf, open_preset as open_pdf_preset}; pub use tools::open_tool_dialog; diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 213f96b27a..bad3e0044c 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -9,7 +9,8 @@ //! The dialog's fields, as `ui.dialog.set` reads and writes them, are `file.new`'s params //! (`name` is the document's name, `width`, `height` (pt), `units`, `artboards`, `artboardLayout`, //! `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi`, `previewMode`, -//! `alignNewObjectsToPixelGrid`, `profile`), plus `basedOn`, the preset the fields were filled from. +//! `alignNewObjectsToPixelGrid`, `profile`), plus `basedOn`, the preset the fields were filled from, and +//! `basedOnUnits`, the units of that preset or Recent entry (null when the fields were edited). //! The dialog opens in Preferences › Units › General, also on a Recent entry made in other units //! (one in pixels, or a saved preset in the units it was saved in, keeps its units); units chosen in //! the Units list or set with `ui.dialog.set` stay when a card is picked. @@ -34,7 +35,7 @@ use craft::ui::patterns::form_dialogs::{ use craft::ui::patterns::presets::{GroupPath, NamedPresetEvent, PresetLibrary}; use craft::ui::pickers::Select; use craft::ui::popover::Popover; -use craft::ui::runtime::env::{Env, Label, LengthUnits, UnitKind}; +use craft::ui::runtime::env::{Env, Label, LengthUnits, UnitKind, WordRows}; use craft::ui::sections::Section; use craft::ui::style::TypeRole; use craft::ui::text::{LinkMode, LinkedWords, NumberField, follow_equal, link_toggle}; @@ -96,9 +97,14 @@ pub(crate) struct VcNewDocument { /// The orientation automation set, which [`DocumentSettings::note_set`] turns the page to: read back from the /// fields, the width and height carry the orientation, so the one listed with them is not applied. turn: Option, + /// The units of the card or Recent entry the settings were filled from, which can differ from the units shown: + /// Recent keeps one entry per size and units, so these tell two entries of one size apart. None once a field + /// other than the units or the orientation was edited in Preset Details. + entry_units: Option, } -/// The same document whatever orientation a set asked for: `turn` is spent by the set that gave it. +/// The same document whatever orientation a set asked for: `turn` is spent by the set that gave it, and +/// `entry_units` only says which card the settings came from. impl PartialEq for VcNewDocument { fn eq(&self, other: &Self) -> bool { (&self.title, &self.settings) == (&other.title, &other.settings) @@ -108,7 +114,7 @@ impl PartialEq for VcNewDocument { impl VcNewDocument { /// `settings` as they are, with an empty document name (a card's value). fn of(settings: DocSettings) -> Self { - Self { title: String::new(), settings, turn: None } + Self { title: String::new(), settings, turn: None, entry_units: None } } /// The fields as `ui.dialog.set` and `file.new` name them. @@ -117,6 +123,7 @@ impl VcNewDocument { if let Value::Object(m) = &mut v { m.insert("name".into(), json!(self.title)); m.insert("basedOn".into(), json!(self.settings.name)); + m.insert("basedOnUnits".into(), json!(self.entry_units.map(Unit::label))); } v } @@ -134,7 +141,11 @@ impl VcNewDocument { let mut settings = read(&sizes)?; settings.name = value.get("basedOn").and_then(Value::as_str).unwrap_or(CUSTOM).to_owned(); let title = value.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(); - Ok(Self { title, settings, turn }) + let entry_units = match value.get("basedOnUnits") { + None | Some(Value::Null) => None, + Some(u) => Some(u.as_str().and_then(Unit::named).ok_or_else(|| format!("basedOnUnits: unknown units `{u}`"))?), + }; + Ok(Self { title, settings, turn, entry_units }) } } @@ -245,8 +256,10 @@ impl DocumentSettings for VcNewDocument { .map(|recent| { let s = &recent.settings; // The entry the fields were filled from shows the units chosen in Preset Details, which - // the new document will have (#2078); the others keep their own. - let chosen = (s.name.as_str(), s.width, s.height) == (now.name.as_str(), now.width, now.height); + // the new document will have (#2078); the others keep their own. Two entries of one size + // differ in their units, so only the one in the units the fields came from is that entry. + let from = cx.values.entry_units.unwrap_or(now.units); + let chosen = (s.name.as_str(), s.width, s.height, s.units) == (now.name.as_str(), now.width, now.height, from); let shown = DocSettings { units: if chosen { now.units } else { s.units }, ..s.clone() }; DocumentCard::new(text(preset_name(&s.name)), shown.size_label(), recent.clone(), CardSource::Recent) }) @@ -262,6 +275,7 @@ impl DocumentSettings for VcNewDocument { fn apply_card(&mut self, card: &DocumentCard, _setup: &Setup, memory: &mut Memory) { let units = self.settings.units; self.settings = card.settings.settings.clone(); + self.entry_units = Some(self.settings.units); if memory.units_chosen { self.settings.units = units; } @@ -377,6 +391,7 @@ impl DocumentSettings for VcNewDocument { after.units = before.units; if !turned && after != before { values.settings.name = CUSTOM.into(); + values.entry_units = None; cx.drop_card(); } if let Some(o) = picked { @@ -401,7 +416,7 @@ fn built_in_card(preset: &DocSettings, values: &VcNewDocument, orientation: Opti std::mem::swap(&mut s.width, &mut s.height); } let line = s.size_label(); - let value = VcNewDocument { title: values.title.clone(), settings: s, turn: None }; + let value = VcNewDocument { title: values.title.clone(), settings: s, turn: None, entry_units: None }; DocumentCard::new(text(preset_name(&preset.name)), line, value, CardSource::preset(None)) } @@ -677,7 +692,8 @@ fn first_settings(app: &VectorcraftApp, category: &str) -> Option let as_saved = newdoc::find(&app.session, &first.name).is_some_and(|p| p.units == first.units); let own = !category.eq_ignore_ascii_case("Recent") || first.units == Unit::Pixels || as_saved; let units = if own { first.units } else { app.session.default_units() }; - Some(VcNewDocument { title: app.session.peek_untitled().to_string(), settings: DocSettings { units, ..first }, turn: None }) + let entry_units = Some(first.units); + Some(VcNewDocument { title: app.session.peek_untitled().to_string(), settings: DocSettings { units, ..first }, turn: None, entry_units }) } /// The settings New Document opens on. @@ -686,9 +702,18 @@ fn offered(app: &VectorcraftApp) -> VcNewDocument { title: app.session.peek_untitled().to_string(), settings: DocSettings { units: app.session.default_units(), ..DocSettings::default() }, turn: None, + entry_units: None, }) } +/// The words that name New Document's name field "Document Name" while the dialog is open, for the window's shell to +/// show its dialogs under. The framework names the field "Name". Temporary: this is removed once the craft-libs pin +/// includes storytold/craft-libs#5291, which names the field and gives Save Document Preset its save icon. +pub(crate) fn name_words(app: &VectorcraftApp) -> Option { + let open = app.dialogs()?.with(|host| host.is_open::>()); + open.then(|| WordRows::new().row(craft::i18n::Word::keyed("newDocument.name", "Name"), tl!("Document Name"))) +} + /// Open New Document on the most recent settings (or Letter), named after the next untitled /// document, in Preferences › Units › General. pub fn open(app: &mut VectorcraftApp) { @@ -705,11 +730,11 @@ pub fn open(app: &mut VectorcraftApp) { let mut saved = PresetLibrary::new(); for preset in &app.session.prefs.new_doc_presets { // The engine keeps names the library refuses (an empty one); such a preset is not offered here. - saved.add(&GroupPath::root(), &preset.name, VcNewDocument { title: preset.name.clone(), settings: preset.clone(), turn: None }).ok(); + saved.add(&GroupPath::root(), &preset.name, VcNewDocument { title: preset.name.clone(), ..VcNewDocument::of(preset.clone()) }).ok(); } let recent: Vec = app.session.prefs.recent_new_docs.iter().cloned().map(VcNewDocument::of).collect(); let mut dialog = HostedNewDocument::::new(&ctx, first, move |options| { - NewDocumentDialog::over(Bind::bound(options)).categories(categories.clone()).setup(setup.clone()) + NewDocumentDialog::over(Bind::bound(options)).categories(categories.clone()).setup(setup.clone()).saved_after_recent(true).recent_items(true) }) .saved(saved) .recent(recent); @@ -1238,6 +1263,38 @@ mod tests { } } + /// Recent is headed as the recent documents it lists, and Saved is the second tab, right after Recent; before, + /// Recent read "Blank Document Presets (n)" and Saved was the last tab. + #[test] + fn recent_heads_its_documents_and_saved_follows_it() { + use egui::accesskit::Role; + let mut app = app(); + app.run("file.new", json!({"preset": "Letter"})).unwrap(); + app.run("file.new", json!({"preset": "Web 1920×1080"})).unwrap(); + open(&mut app); + let out = laid_out(&mut app); + let drawn: Vec = crate::tests_labels::text_shapes(&out).into_iter().map(|(t, _)| t.galley.text().to_uppercase()).collect(); + assert!(drawn.iter().any(|t| t == "YOUR RECENT ITEMS (2)"), "Recent counts its two documents: {drawn:?}"); + assert!(!drawn.iter().any(|t| t.starts_with("BLANK DOCUMENT PRESETS")), "Recent is not headed as presets: {drawn:?}"); + // The Home screen behind the dialog has tabs of its own: only the dialog's are read. + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let by_id: std::collections::HashMap<_, _> = nodes.iter().map(|(id, n)| (*id, n)).collect(); + let mut stack: Vec<_> = nodes.iter().filter(|(_, n)| n.role() == Role::Dialog).map(|(id, _)| *id).collect(); + let mut tabs = Vec::new(); + while let Some(id) = stack.pop() { + if let Some(node) = by_id.get(&id) { + if let (Role::Tab, Some(label), Some(b)) = (node.role(), node.label(), node.bounds()) { + tabs.push((b.x0, label.to_owned())); + } + stack.extend(node.children().iter().copied()); + } + } + tabs.sort_by(|a, b| a.0.total_cmp(&b.0)); + let order: Vec<&str> = tabs.iter().map(|(_, label)| label.as_str()).collect(); + assert!(order.len() > 2, "the dialog's tabs: {order:?}"); + assert_eq!(order[..2], ["Recent", "Saved"], "Saved follows Recent: {order:?}"); + } + #[test] fn a_preset_fills_the_details_and_create_makes_the_document() { let mut app = app(); @@ -1543,8 +1600,7 @@ mod tests { let card = |units| DocumentCard::new("Card", "line", VcNewDocument::of(entry(units)), CardSource::Recent); let setup = Setup::default(); - let mut doc = - VcNewDocument { title: "Mine".into(), settings: DocSettings { units: Unit::Millimeters, ..DocSettings::default() }, turn: None }; + let mut doc = VcNewDocument { title: "Mine".into(), ..VcNewDocument::of(DocSettings { units: Unit::Millimeters, ..DocSettings::default() }) }; let mut memory = Memory::default(); doc.apply_card(&card(Unit::Inches), &setup, &mut memory); assert_eq!((doc.settings.units, doc.title.as_str()), (Unit::Inches, "Mine"), "a saved preset keeps its own units, the name stays"); @@ -1560,6 +1616,50 @@ mod tests { assert_eq!(shown.settings.settings.units, Unit::Millimeters, "the cards follow the chosen units"); } + /// Recent keeps an A4 made in pixels and one made in millimeters as two entries. Only the card the fields came + /// from shows the units in Preset Details (the newest entry, opened in the general units unless it is in pixels); + /// the other card keeps its own units, also after the units are set from outside the dialog. + #[test] + fn recent_entries_of_one_size_in_two_units_show_two_sizes() { + let a4 = newdoc::find(&Session::new(), "A4").unwrap(); + let entry = |units| DocSettings { units, ..a4.clone() }; + let label = |units| entry(units).size_label(); + let count = |panel: &Panel, units| panel.painted(&label(units)).len(); + let opened = |newest, older| { + let mut app = app(); + general_units(&mut app, "Points"); + app.session.prefs.recent_new_docs = vec![entry(newest), entry(older)]; + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app()); + panel + }; + for (newest, older, shown) in [(Unit::Pixels, Unit::Millimeters, Unit::Pixels), (Unit::Millimeters, Unit::Pixels, Unit::Points)] { + let mut panel = opened(newest, older); + panel.frame(); + panel.frame(); + assert_eq!(fields(&panel.app())["units"], json!(shown.label())); + assert_eq!(fields(&panel.app())["basedOnUnits"], json!(newest.label())); + assert_eq!(count(&panel, shown), 1, "the newest entry shows the units of the fields: {:?}", panel.texts()); + assert_eq!(count(&panel, older), 1, "the older entry keeps its own units: {:?}", panel.texts()); + + set(&panel.app(), "units", json!("Inches")).unwrap(); + panel.frame(); + assert_eq!(count(&panel, Unit::Inches), 1, "the chosen units reach the newest entry only: {:?}", panel.texts()); + assert_eq!(count(&panel, older), 1, "the older entry still keeps its own units: {:?}", panel.texts()); + + // The same set before the dialog's first frame. + let mut panel = opened(newest, older); + set(&panel.app(), "units", json!("Inches")).unwrap(); + panel.frame(); + panel.frame(); + assert_eq!(count(&panel, Unit::Inches), 1, "a set before the first frame reaches the newest entry: {:?}", panel.texts()); + assert_eq!(count(&panel, older), 1, "and leaves the older entry in its own units: {:?}", panel.texts()); + } + let panel = opened(Unit::Pixels, Unit::Millimeters); + assert!(set(&panel.app(), "basedOnUnits", json!("Furlongs")).is_err(), "unknown units are refused"); + } + /// Edit opens a profile as a document and closes the dialog, Reset does not; the rows list every /// profile and say which were edited. #[test] @@ -1658,6 +1758,16 @@ mod tests { nodes.iter().find(|(r, n, _)| *r == role && n == name).map(|(_, _, b)| *b).unwrap_or_else(|| panic!("no {role:?} {name}")) } + /// The name field is named Document Name; before, screen readers read it as plain Name. + #[test] + fn new_document_names_its_name_field_document_name() { + use egui::accesskit::Role; + let nodes = dialog_nodes(1280.0, 900.0); + let field = |name: &str| nodes.iter().any(|(role, label, _)| *role == Role::TextInput && label == name); + assert!(field("Document Name"), "a text field named Document Name"); + assert!(!field("Name"), "no text field named plain Name"); + } + /// Every Preset Details label stands above its field, at the field's left edge; before, Width, Height, /// Orientation, Artboards, the Bleed sides and Background Contents sat right-aligned beside their fields. #[test] diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 4863a67cb3..b55edcbe6d 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -33,7 +33,7 @@ use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKi use craft::ui::patterns::presets::{NamedPresetEvent, PresetError, PresetRow}; use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook}; use craft::ui::primitives::IconSpec; -use craft::ui::runtime::env::{LengthUnits, UnitKind}; +use craft::ui::runtime::env::{LengthUnits, UnitKind, WordRows}; use craft::ui::shell::WindowDialogs; use craft::ui::text::{LinkMode, LinkedFields, NumberField, SelectableText}; use serde_json::{Map, Value, json}; @@ -518,6 +518,15 @@ pub(super) fn settings(fields: &DialogFields) -> Value { Value::Object(nested(p)) } +/// The words that title File › Print "Print" while the Print dialog is open in Print mode, for the window's shell to +/// show its dialogs under. The framework titles a dialog in sections "Print Settings". Temporary: this is removed, and +/// the dialog is titled with `HostedPrint::title`, once the craft-libs pin includes storytold/craft-libs#4891. +pub(crate) fn title_words(app: &VectorcraftApp) -> Option { + app.print_dialog.open.as_ref().filter(|open| open.mode == PrintMode::Print)?; + let title = craft::i18n::Word::keyed("printDialog.title", "Print Settings"); + Some(WordRows::new().row(title, tl!("Print"))) +} + /// The work of the open dialog, once per frame: the printer list, Setup…, the preview, the placement the preview was /// dragged to, the presets and OK. pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 9340f14350..7f99bc817b 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -143,6 +143,42 @@ fn pages(pdf: &[u8]) -> usize { vectorcraft_pdf::info(pdf, None).unwrap().pages.len() } +/// The texts the whole window paints, with where each is drawn, once the open dialog has faded in (each frame is a +/// quarter second on). +fn window_texts(app: &mut VectorcraftApp) -> Vec<(String, egui::Rect)> { + let ctx = ctx(app); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)); + let mut texts = vec![]; + for k in 0..4 { + let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() }; + let out = crate::testing::app_frame(app, &ctx, raw); + texts = crate::tests_labels::text_shapes(&out) + .into_iter() + .map(|(t, transform)| (t.galley.text().to_string(), transform * t.galley.rect.translate(t.pos.to_vec2()))) + .collect(); + } + texts +} + +#[test] +fn the_print_dialog_is_titled_print_and_the_preset_editor_keeps_its_title() { + let (mut printing, _) = app(); + printing.run("file.print", json!({})).unwrap(); + let texts = window_texts(&mut printing); + let painted = |texts: &[(String, egui::Rect)], text: &str| texts.iter().filter(|(t, _)| t == text).map(|(_, r)| *r).collect::>(); + assert!(painted(&texts, "Print Settings").is_empty(), "the Print dialog is not titled Print Settings: {texts:?}"); + let preset_row = painted(&texts, "Print Preset"); + let preset_row = preset_row.first().expect("the Print Preset row is shown"); + // The title sits above the dialog's first row; the Print button sits below it. + assert!(painted(&texts, "Print").iter().any(|title| title.bottom() <= preset_row.top()), "the dialog is titled Print: {texts:?}"); + + // The preset editor keeps the framework's title. + let (mut editing, _) = app(); + editing.run("ui.printPresetDialog", json!({"preset": vectorcraft_engine::cmd::printpresets::DEFAULT_PRESET})).unwrap(); + let texts = window_texts(&mut editing); + assert!(!painted(&texts, "Print Settings").is_empty(), "the preset editor is titled Print Settings: {texts:?}"); +} + #[test] fn print_sends_every_page_to_the_chosen_printer_and_keeps_the_settings() { let (mut app, jobs) = app(); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 5ea3433c56..b515cb802e 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -74,17 +74,33 @@ static EMBEDDED: &Embedded = &[ /// The codes of [`EMBEDDED`] the interface offers. Browsers cannot use the native installed-font /// fallback, so on the web a language whose text would be missing-glyph boxes (Gujarati without a -/// bundled Gujarati face) is not offered, including when restoring a preference. Arabic is kept -/// unavailable to users until the shared catalog in `storytold/craft-i18n` is consumed. +/// Gujarati face, see [`has_gujarati_face`]) is not offered, including when restoring a preference. +/// Arabic is kept unavailable to users until the shared catalog in `storytold/craft-i18n` is consumed. fn offered_codes(web: bool, gujarati_font: bool) -> Vec<&'static str> { EMBEDDED.iter().map(|(code, ..)| *code).filter(|code| *code != "ar" && (*code != "gu" || !web || gujarati_font)).collect() } +/// Whether the interface has a Gujarati face: an embedded craft-fonts face, or on the web a face +/// the interface font stack serves (`SERVED_FONTS`, the `startup` and `demand` lines of +/// `crates/text/web-fonts.txt`) and fetches when Gujarati text needs it. +fn has_gujarati_face() -> bool { + #[cfg(target_arch = "wasm32")] + let served = vectorcraft_text::SERVED_FONTS.iter().map(|f| f.scripts); + #[cfg(not(target_arch = "wasm32"))] + let served = std::iter::empty(); + has_gujarati_face_in(vectorcraft_text::CRAFT_FONTS, served) +} + +/// [`has_gujarati_face`] for the given embedded faces and the scripts of each served face. +fn has_gujarati_face_in<'a>(embedded: &[vectorcraft_text::EmbeddedFace], mut served: impl Iterator) -> bool { + embedded.iter().any(|f| f.has_script("Gujr")) || served.any(|scripts| scripts.contains(&"Gujr")) +} + /// The one catalog set of the process, built on first use. fn shared_cell() -> &'static Arc { static SHARED: OnceLock> = OnceLock::new(); SHARED.get_or_init(|| { - let offered = offered_codes(cfg!(target_arch = "wasm32"), vectorcraft_text::CRAFT_FONTS.iter().any(|f| f.has_script("Gujr"))); + let offered = offered_codes(cfg!(target_arch = "wasm32"), has_gujarati_face()); let (i18n, problems) = I18n::new(EMBEDDED, &offered); for problem in problems { log::warn!("vectorcraft: interface language catalog: {problem}"); diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index cdbc54b58d..b3910b0442 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -159,6 +159,23 @@ fn gujarati_web_selection_requires_a_bundled_interface_font() { assert!(codes(true, false).contains(&"hi".to_string())); } +/// The web build embeds no Gujarati face, but serves Noto Sans Gujarati on demand: the web's +/// served faces are the `startup` and `demand` lines of `crates/text/web-fonts.txt`, so the web +/// offers Gujarati. Checked where the craft-fonts checkout has the face. +#[test] +fn web_offers_gujarati_with_the_served_gujarati_face() { + if !vectorcraft_text::CRAFT_FONTS.iter().any(|f| f.has_script("Gujr")) { + eprintln!("skipped: built without craft-fonts, or one without a Gujarati face"); + return; + } + let served = || vectorcraft_text::WEB_FONTS.iter().filter(|w| w.startup || w.demand).map(|w| w.scripts); + let web_embedded: Vec<_> = vectorcraft_text::CRAFT_FONTS.iter().filter(|f| !f.has_script("Gujr")).copied().collect(); + let font = has_gujarati_face_in(&web_embedded, served()); + assert!(font, "a served Gujarati face counts on the web"); + assert!(offered_codes(true, font).contains(&"gu")); + assert!(!has_gujarati_face_in(&web_embedded, std::iter::empty()), "without it, nothing draws Gujarati on the web"); +} + /// A numbered built-in name shows its name before the number translated and the number as it /// is; a name with a row of its own uses that row, and any other name comes back unchanged. #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index dd16e84471..8cedd51928 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4,6 +4,7 @@ //! (view/window) here and everything else to the engine. The same entry point serves menus, //! shortcuts, the command palette ([`palette`], Help › Search Commands…) and the control channel ([`control`]). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] /// VectorCraft as craft-update knows it, with its 128 px icon and accent colour: the update /// prompt shows both, and an AppImage's menu entry gets the icon. @@ -130,7 +131,7 @@ pub use caches::{CacheKey, CanvasCache, LivePaintGapsCache, Perf, PlacedKey, Pri #[cfg(test)] pub(crate) use services::browsable_url; pub use services::{DownloadFn, ExistsFn, Inbox, ReadFn, SaveStreamFn, SaveWriteFn, ScreenDensity, ScreenPpi, Services, WriteFn}; -pub use ui_fonts::ui_fonts; +pub use ui_fonts::{configure_ui_fonts, ui_fonts}; pub struct VectorcraftApp { pub session: Session, diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 8f28023e0a..c6c791b645 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -474,7 +474,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let pass = pass.into_inner(); if let Some(list) = shown.inner { let opener = list.response.clone(); - apply_list(app, node.as_deref(), &order, selection, list); + apply_list(app, node.as_deref(), &order, mix, selection, list); if let (Some(key), Some(n)) = (app.ui.appearance_panel.menu, node.as_deref()) { row_menu(app, ui, &opener, n, key); } @@ -530,8 +530,7 @@ fn object_row_label(app: &VectorcraftApp, summary: Option<&Summary>, mixed: bool } } -/// The list over `rows` (`order` their keys), bound to `selection`. A mixed selection's rows don't -/// drag: where one would go in each of the different stacks isn't one place. +/// The list over `rows` (`order` their keys), bound to `selection`. fn show_list( ui: &mut Ui, cx: &RowCx<'_>, @@ -555,10 +554,11 @@ fn show_list( .deletable(true) .selection(Bind::bound(selection)) .can_drag(|key: &RowKey| key.drags()); - if let Some(n) = cx.node.filter(|_| cx.mix.is_none()) { + if let Some(n) = cx.node { + let mix = cx.mix; list = list .reorder(ReorderRule::new().copy_with(CopyKeys::Alt).into_groups()) - .accepts(move |drag: &ListDrag, over: Option<&RowKey>, insert: usize| accepts(n, order, drag, over, insert, copy)); + .accepts(move |drag: &ListDrag, over: Option<&RowKey>, insert: usize| accepts(n, order, mix, drag, over, insert, copy)); } list.show_items(ui, rows, &mut |key, item| build_row(cx, *key, item)) } @@ -569,6 +569,7 @@ fn apply_list( app: &mut VectorcraftApp, node: Option<&Node>, order: &[RowKey], + mix: Option<&Mixed>, selection: Selection, list: CollectionResponse, ) { @@ -610,7 +611,7 @@ fn apply_list( delete_selected(app, node, sel).ok(); } if let Some(mv) = moved { - reorder(app, n, order, &mv); + reorder(app, n, order, mix, &mv); } } @@ -1192,7 +1193,14 @@ fn mixed(app: &VectorcraftApp) -> Option { } let aps: Vec<&vectorcraft_doc::Appearance> = nodes.iter().map(|n| &*n.appearance).collect(); let fills_differ = rest.iter().any(|n| n.appearance.fill_paint() != first.appearance.fill_paint()); - Some(Mixed { shared: vectorcraft_doc::appearance::SharedStack::of(&aps), transparency, fills_differ }) + let object_effects_match = rest.iter().all(|n| n.appearance.effects == first.appearance.effects); + Some(Mixed { + shared: vectorcraft_doc::appearance::SharedStack::of(&aps), + transparency, + fills_differ, + object_effects_match, + effect_targets_match: app.session.can_reorder_selected_effects(), + }) } /// A mixed selection as the panel lists it ([`mixed`]). @@ -1203,6 +1211,10 @@ struct Mixed { transparency: bool, /// Their topmost fills differ: the object row shows no fill chip. fills_differ: bool, + /// All objects have the same complete, ordered object effect list. + object_effects_match: bool, + /// The command edits the same subjects whose rows the panel shows. + effect_targets_match: bool, } /// The selection's [`object_label`] and [`mixed`] summary for the active document as of one @@ -1673,17 +1685,40 @@ fn delete_selected(app: &mut VectorcraftApp, node: Option<&Node>, sel: Sel) -> R /// Whether the rows of `drag` may land before position `insert` of `order` (`over`: the row under /// the pointer, which takes them when it holds rows): a drop that moves or copies them /// ([`reorder_command`]). -fn accepts(n: &Node, order: &[RowKey], drag: &ListDrag, over: Option<&RowKey>, insert: usize, copy: bool) -> bool { +fn accepts(n: &Node, order: &[RowKey], mix: Option<&Mixed>, drag: &ListDrag, over: Option<&RowKey>, insert: usize, copy: bool) -> bool { let before = order.get(..insert).map_or(0, |rows| rows.iter().filter(|key| drag.keys.contains(key)).count()); let mv = ReorderMove::new(drag.grabbed, drag.keys.clone(), insert.saturating_sub(before), copy); let into = over.copied().filter(|key| key.has_children()).map(|key| mv.clone().in_group(Some(key))); - reorder_command(n, order, &mv).is_some() || into.is_some_and(|mv| reorder_command(n, order, &mv).is_some()) + reorder_for_selection(n, order, mix, &mv).is_some() || into.is_some_and(|mv| reorder_for_selection(n, order, mix, &mv).is_some()) +} + +/// A mixed selection has an unambiguous destination only within a list that all its objects share. +fn reorder_for_selection(n: &Node, order: &[RowKey], mix: Option<&Mixed>, mv: &ReorderMove) -> Option<(&'static str, Value)> { + let (cmd, params) = reorder_command(n, order, mv)?; + let Some(mix) = mix else { return Some((cmd, params)) }; + let (item, _) = mv.key.effect()?; + let shared = item.map_or(mix.object_effects_match, |i| mix.shared.has_item(i)); + (cmd == "effect.move" && !mv.copy && mix.effect_targets_match && shared && params["fromItem"] == params["toItem"]).then_some((cmd, params)) } /// Runs the reorder `mv` of the rows `order` of `n` and picks the moved rows (the copies), the /// grabbed one the lead; a moved Contents row keeps its selection. -fn reorder(app: &mut VectorcraftApp, n: &Node, order: &[RowKey], mv: &ReorderMove) { - let Some((cmd, params)) = reorder_command(n, order, mv) else { return }; +fn reorder(app: &mut VectorcraftApp, n: &Node, order: &[RowKey], mix: Option<&Mixed>, mv: &ReorderMove) { + let Some((cmd, mut params)) = reorder_for_selection(n, order, mix, mv) else { return }; + if mix.is_some() { + if let Some((Some(item), _)) = mv.key.effect() { + // The panel shows the first selected object's rows. The engine's implicit active + // item uses that same anchor, even when another target paints first. + if app.session.appearance_item() != Some(item) && app.run("appearance.setActiveItem", json!({"index": item})).is_err() { + return; + } + if let Some(fields) = params.as_object_mut() { + fields.remove("fromItem"); + fields.remove("toItem"); + } + } + params = aligned(app, params); + } let Ok(result) = app.run(cmd, params.clone()) else { return }; let Some((kind, grabbed)) = mv.key.sel().rows() else { return }; let mut set: Vec = mv.keys.iter().filter_map(|key| key.sel().rows().map(|(_, k)| k)).collect(); @@ -1808,6 +1843,20 @@ fn items_move( Some(("appearance.moveItem", params)) } +/// An edge between rows in an expanded fill or stroke can report that item as its parent. +/// A drop immediately after the item header still means append to its effects. +fn item_effect_gap(remaining: &[RowKey], gap: usize, item: usize) -> Option { + let above = gap.checked_sub(1).and_then(|at| remaining.get(at)).copied(); + if above == Some(RowKey::Item(item)) { + return None; + } + let index = |key: Option| match key { + Some(RowKey::ItemEffect(row, index)) if row == item => Some(index), + _ => None, + }; + index(remaining.get(gap).copied()).or_else(|| index(above).map(|at| at + 1)) +} + /// The effects `set` (ascending) of list `from_item` moved or copied to `gap` of `remaining`. fn effects_move( n: &Node, @@ -1818,7 +1867,11 @@ fn effects_move( mv: &ReorderMove, ) -> Option<(&'static str, Value)> { let (item, pos) = match mv.parent { - Some(RowKey::Item(i)) => (Some(i), n.appearance.effects_at(Some(i))?.len()), + Some(RowKey::Item(i)) => { + let end = n.appearance.effects_at(Some(i))?.len(); + let pos = if from_item == Some(i) && !mv.copy { item_effect_gap(remaining, gap, i).unwrap_or(end) } else { end }; + (Some(i), pos) + } Some(key) => key.effect()?, None => { let above = gap.checked_sub(1).and_then(|at| remaining.get(at)).copied(); diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 5c601967d3..becf9ecc3c 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -353,6 +353,8 @@ fn drops_pick_the_command() { (mv(&[item(1)], 3, false, None), None), (mv(&[item(1)], 3, false, Some(ItemEffect(1, 0))), None), (mv(&[ItemEffect(1, 0)], 5, false, None), effects(json!({"from": 0, "fromItem": 1, "to": 1, "toItem": 1, "copy": false}))), + (mv(&[ItemEffect(1, 1)], 4, false, Some(item(1))), effects(json!({"from": 1, "fromItem": 1, "to": 0, "toItem": 1, "copy": false}))), + (mv(&[ItemEffect(1, 0)], 3, false, Some(item(1))), effects(json!({"from": 0, "fromItem": 1, "to": 1, "toItem": 1, "copy": false}))), (mv(&[ItemEffect(1, 0)], 4, false, None), None), (mv(&[ItemEffect(1, 1)], 5, true, Some(item(0))), effects(json!({"from": 1, "fromItem": 1, "to": 0, "toItem": 0, "copy": true}))), (mv(&[ItemEffect(1, 1)], 7, false, None), effects(json!({"from": 1, "fromItem": 1, "to": 1, "toItem": null, "copy": false}))), @@ -362,8 +364,8 @@ fn drops_pick_the_command() { assert_eq!(reorder_command(&path, &order, &moved), want, "{moved:?}"); } let drag = |keys: &[RowKey]| ListDrag::new(egui::Id::NULL, keys.to_vec(), keys[0]); - assert!(accepts(&path, &order, &drag(&[effect(0)]), Some(&item(0)), 2, false), "into a fill's row"); - assert!(!accepts(&path, &order, &drag(&[effect(0)]), Some(&Object), 1, false), "where it is"); + assert!(accepts(&path, &order, None, &drag(&[effect(0)]), Some(&item(0)), 2, false), "into a fill's row"); + assert!(!accepts(&path, &order, None, &drag(&[effect(0)]), Some(&Object), 1, false), "where it is"); // A group listed top-down S3, FA*, Contents, S1*, F0 (paint order F0 S1 FA S3, Contents above // two), FA and S1 dragged together. @@ -419,7 +421,7 @@ fn drops_pick_the_command() { ] { assert_eq!(reorder_command(&group, &order, &moved), want, "{moved:?}"); } - assert!(!accepts(&group, &order, &drag(&[Contents]), Some(&Contents), 3, false), "where it is"); + assert!(!accepts(&group, &order, None, &drag(&[Contents]), Some(&Contents), 3, false), "where it is"); } #[test] @@ -604,6 +606,74 @@ fn a_mixed_selection_lists_what_its_objects_share() { assert!(panel.shows("Mixed Objects")); } +#[test] +fn a_mixed_selection_reorders_its_identical_object_effect_lists() { + let mut app = app_with_a_selected_rectangle(); + let a = node(&app).id; + let b = app.run("shape.rectangle", json!({"x": 50, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"ids": [b], "color": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [a.0, b]})).unwrap(); + for effect in ["distort.twist", "distort.roughen"] { + app.run("effect.apply", json!({"effect": effect, "item": null})).unwrap(); + } + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let order = |app: &VectorcraftApp| { + [a, NodeId(b)] + .map(|id| app.session.active().unwrap().doc.node(id).unwrap().appearance.effects.iter().map(|e| e.id.clone()).collect::>()) + }; + let before = order(&app); + let undo = steps(&app); + let mut panel = Panel::new(app, show); + assert!(panel.shows("Mixed Appearances")); + let drag = |panel: &mut Panel| { + let from = crate::panels::tests_appearance::row_spot(panel, &effect_row_label("distort.roughen")); + let above = panel.rect(&effect_row_label("distort.twist")); + panel.drag_between(from, egui::pos2(from.x, above.top() + 1.0), egui::Modifiers::NONE); + }; + drag(&mut panel); + { + let mut app = panel.app(); + assert_eq!(order(&app), [vec!["distort.roughen", "distort.twist"], vec!["distort.roughen", "distort.twist"]]); + assert_eq!(steps(&app), undo + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(order(&app), before); + app.run("effect.apply", json!({"ids": [b], "effect": "stylize.feather", "item": null})).unwrap(); + } + let before = order(&panel.app()); + drag(&mut panel); + assert_eq!(order(&panel.app()), before, "a common prefix does not make both lists reorderable"); +} + +#[test] +fn a_mixed_selection_reorders_shared_stroke_effects_at_different_item_indices() { + let mut app = app_with_a_selected_rectangle(); + let a = node(&app).id; + let b = app.run("shape.rectangle", json!({"x": 50, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("appearance.addFill", json!({})).unwrap(); + app.run("appearance.moveItem", json!({"from": 2, "to": 0})).unwrap(); + app.run("appearance.setItem", json!({"index": 0, "color": "#ff0000"})).unwrap(); + for (id, item) in [(a.0, 1), (b, 2)] { + for effect in ["distort.twist", "distort.roughen"] { + app.run("effect.apply", json!({"ids": [id], "item": item, "effect": effect})).unwrap(); + } + } + app.run("select.set", json!({"ids": [b, a.0]})).unwrap(); + app.ui.appearance_panel.open.insert(RowKey::Item(2)); + + let mut panel = Panel::new(app, show); + let from = crate::panels::tests_appearance::row_spot(&mut panel, &effect_row_label("distort.roughen")); + let above = panel.rect(&effect_row_label("distort.twist")); + panel.drag_between(from, egui::pos2(from.x, above.top() + 1.0), egui::Modifiers::NONE); + let app = panel.app(); + let doc = &app.session.active().unwrap().doc; + for (id, item) in [(a, 1), (NodeId(b), 2)] { + let effects = doc.node(id).unwrap().appearance.effects_at(Some(item)).unwrap(); + assert_eq!(effects.iter().map(|effect| effect.id.as_str()).collect::>(), ["distort.roughen", "distort.twist"]); + } + assert_eq!(app.ui.appearance_panel.selection.lead, Some(RowKey::ItemEffect(2, 0))); +} + /// The [`summary`] the canvas cache holds for the active document, checked field by field against /// what [`object_label`] and [`mixed`] work out from scratch. fn fresh_summary(app: &mut VectorcraftApp) -> Arc { diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index ba0c6cf7a3..759051fa29 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -6,7 +6,7 @@ //! //! The mode follows the colour's own model: the last mode picked comes back for colours in its model //! and the defaults for new art, and the app keeps it between sessions. Alt on the spectrum, a chip -//! or a recent colour targets the inactive proxy (the framework's `PanelTarget::Background`); +//! or a recent colour targets the inactive proxy; //! Cmd/Ctrl-clicking the spectrum recolours (Complement, with Shift Invert). //! //! `ui.colorPanel` picks a mode, shows or hides the options and checks or unchecks Show Recent @@ -432,12 +432,11 @@ fn recolor(app: &mut VectorcraftApp, tgt: &Target, invert: bool, behind: bool) { } } -/// Run what the panel reported this pass on the document: the edits (the inactive proxy for a -/// `Background` target), the Tint row, None, a recolour click and the proxy's own events. The +/// Run the panel's edits, Tint row, None, recolour clicks and proxy events on the document. The /// gradient stop popover, which embeds the panel, hands its output here too. pub(crate) fn apply_output(app: &mut VectorcraftApp, out: &ColorPanelOutput) { let tgt = target_now(app); - apply_with(app, &tgt, out); + apply_with(app, &tgt, PanelTarget::Foreground, out); } /// [`target`] with the "?" state of [`mixed_now`], for callers without the panel's pass. @@ -445,9 +444,9 @@ pub(crate) fn target_now(app: &VectorcraftApp) -> Target { target_with(app, mixed_now(app)) } -fn apply_with(app: &mut VectorcraftApp, tgt: &Target, out: &ColorPanelOutput) { +fn apply_with(app: &mut VectorcraftApp, tgt: &Target, active: PanelTarget, out: &ColorPanelOutput) { for (which, event) in &out.edits { - let behind = matches!(which, PanelTarget::Background); + let behind = *which != active; apply_event(app, event, &EditPath::Preview, &mut |app, picked: &PickedColor, phase| { choose(app, tgt, picked_color(picked), phase, behind); }); @@ -462,7 +461,7 @@ fn apply_with(app: &mut VectorcraftApp, tgt: &Target, out: &ColorPanelOutput) { }); } if let Some(which) = out.none { - let cmd = super::proxy_cmd(app, matches!(which, PanelTarget::Background)); + let cmd = super::proxy_cmd(app, which != active); app.run(cmd, json!({"none": true})).ok(); } if let Some(r) = out.recolor { @@ -549,16 +548,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (fill, stroke) = super::current_paints(app); let (fill_well, fill_color) = well(tl!("Fill"), &fill, fill_mixed); let (stroke_well, stroke_color) = well(tl!("Stroke"), &stroke, stroke_mixed); - let fill_active = app.session.fill_active; - let colors = if fill_active { [fill_color, stroke_color] } else { [stroke_color, fill_color] }; - let active = if fill_active { Well::Primary } else { Well::Secondary }; + // The shared panel uses fixed slots for both the displayed colors and its edit targets. + let (active, active_target) = + if app.session.fill_active { (Well::Primary, PanelTarget::Foreground) } else { (Well::Secondary, PanelTarget::Background) }; let edited = tgt.color().map(|c| PickedColor::in_model(srgba(&c), model_values(&c))); let rows = shown(app, &tgt); let printable = gamut(app); let stored: Vec = app.session.recent_colors.to_vec(); let chips: Vec = stored.iter().map(srgba).collect(); let before = app.ui.color_panel; - let out = ColorPanel::new(Bind::bound(&mut app.ui.color_panel), colors) + let out = ColorPanel::new(Bind::bound(&mut app.ui.color_panel), [fill_color, stroke_color]) .layout(LAYOUT) .wells([fill_well, stroke_well], Bind::given(active)) .edited(edited) @@ -570,7 +569,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .working_rgb(&WorkingRgb) .show(ui); // PLAN: a click on a recent chip reports only its sRGB, so a CMYK recent colour paints as RGB; co.K18 needs the edit to name the chip. - apply_with(app, &tgt, &out); + apply_with(app, &tgt, active_target, &out); let now = app.ui.color_panel.mode; // Shift-click on the spectrum cycles the mode inside the panel; the colour follows it here. if now != before.mode && picked_mode(now).is_some() { diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index d354702ef2..d66bb205cc 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -429,3 +429,36 @@ fn the_wells_show_a_gradient_and_none_as_the_tools_proxy_does() { assert!(color.shows_value(well), "the Color panel shows a well that reads as {well:?}"); } } + +#[test] +fn the_color_panel_edits_the_selected_stroke_well_without_changing_fill() { + use crate::tests::panel_harness::Panel; + + let mut app = app(); + app.run("paint.setFill", json!({"color": "#224466"})).unwrap(); + app.run("paint.setStroke", json!({"color": "#aa5522"})).unwrap(); + app.run("paint.toggleActive", json!({"fill": true})).unwrap(); + let mut panel = Panel::new(app, show); + let (fill, stroke) = paints_hex(&panel.app()); + let fill_well = panel.rect("Fill"); + let stroke_well = panel.rect("Stroke"); + let stroke_hit = egui::pos2(stroke_well.center().x, (fill_well.bottom() + stroke_well.bottom()) / 2.0); + assert!(stroke_well.contains(stroke_hit) && !fill_well.contains(stroke_hit), "click the exposed part of Stroke"); + panel.click_at(stroke_hit); + assert!(!panel.app().session.fill_active, "the Color panel made Stroke active"); + panel.click("Black"); + assert_eq!(paints_hex(&panel.app()), (fill.clone(), "#000000".into())); + assert_ne!(stroke, "#000000"); + + panel.click_with("White", egui::Modifiers::ALT); + assert_eq!(paints_hex(&panel.app()), ("#ffffff".into(), "#000000".into())); + assert!(!panel.app().session.fill_active, "Alt edits Fill without activating it"); + + panel.click("None"); + assert_eq!(paints_hex(&panel.app()), ("#ffffff".into(), String::new())); + + panel.click("Fill"); + assert!(panel.app().session.fill_active); + panel.click("Black"); + assert_eq!(paints_hex(&panel.app()), ("#000000".into(), String::new())); +} diff --git a/crates/ui-egui/src/panels/retype.rs b/crates/ui-egui/src/panels/retype.rs index 16d607393c..697d80a2b8 100644 --- a/crates/ui-egui/src/panels/retype.rs +++ b/crates/ui-egui/src/panels/retype.rs @@ -7,15 +7,17 @@ //! list stays after the selection changes, so choosing a font in it sets that font on the live text //! selected then, as the font menus do. The sample field sets the text the samples show, and the //! panel menu sets their size; Reset Retype Panel clears the list. `retype.find`, `retype.list`, -//! `retype.preview` and `retype.reset` do the same. +//! `retype.preview` and `retype.reset` do the same. A font's menu (a secondary click on its row, or +//! Shift+F10 on the focused row) selects the row and holds Apply Font, which sets that font as a +//! click does, then the panel menu's sample sizes and Reset Retype Panel. use craft::behavior::{EditEvent, Mixed, keyed}; use craft::keymap::CommandRef; use craft::ui::buttons::{Button, Link}; -use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _}; +use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::display::{Divider, Shade, Text}; use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize}; -use craft::ui::menu::PanelRow; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::primitives::ContentPainterCx; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::style::Variant; @@ -50,7 +52,7 @@ const SIZES: [(Size, &str, ThumbSize); 3] = [(Size::Small, "small", ThumbSize::Small), (Size::Medium, "medium", ThumbSize::Medium), (Size::Large, "large", ThumbSize::Large)]; /// One font in the list. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Found { pub family: String, pub style: String, @@ -114,21 +116,47 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let on_white = app.session.prefs.font_samples_on_white; let indexed: Vec<(usize, &Found)> = view.fonts.iter().enumerate().collect(); let source = keyed(&indexed, |(at, _)| *at); - // A click activates a row, so the same row chosen again sets its font again. - let list = List::::new(tl!("Matching fonts")).select(SelectMode::Single).activate(ActivateOn::Click).show_items( - ui, - &source, - &mut |key, _| { + // The rows are keyed by place, so a list with other fonts, or another document, is another + // list: a row's menu closes rather than act on the font that took its place. + let document = app.session.active().map(|st| st.uid); + // A click activates a row, so the same row chosen again sets its font again. A secondary + // click selects its row and asks for the row's menu; it does not activate the row. + let list = List::::new(tl!("Matching fonts")) + .id(ui.scope_id().with(("matching-fonts", document, &view.fonts))) + .select(SelectMode::Single) + .activate(ActivateOn::Click) + .row_menu() + .show_items(ui, &source, &mut |key, _| { let (family, style) = indexed.get(*key).map_or(("", ""), |(_, f)| (f.family.as_str(), f.style.as_str())); ListRow::new(format!("{family} {style}")).thumb_aspect(size, ThumbAspect::new(8, 1), move |cx: &ContentPainterCx, rect: Rect| { crate::font_menu::paint_family_sample(cx, rect, family, style, sample, on_white); }) - }, - ); - let chosen = list.events.iter().find_map(|e| match e { + }); + let mut chosen = list.events.iter().find_map(|e| match e { CollectionEvent::Activate(at) => view.fonts.get(*at), _ => None, }); + if let Some(request) = list.menu + && let Some(f) = view.fonts.get(request.key) + { + // Apply Font is off while choosing the font would set it on nothing. + let live = live_text_selected(app); + Menu::context(format!("{} {}", f.family, f.style), &list.response).show(ui, |ui, _| { + if MenuItem::new(tl!("Apply Font")).enabled(live).show(ui).ran { + chosen = Some(f); + } + Divider::horizontal().show(ui); + for (size, name, _) in SIZES { + if MenuItem::new(size_label(size)).check(view.size == size).show(ui).ran { + run = Some(("retype.preview", json!({ "size": name }))); + } + } + Divider::horizontal().show(ui); + if MenuItem::new(tl!("Reset Retype Panel")).show(ui).ran { + run = Some(("retype.reset", json!({}))); + } + }); + } if let Some(f) = chosen && live_text_selected(app) { diff --git a/crates/ui-egui/src/panels/retype/tests.rs b/crates/ui-egui/src/panels/retype/tests.rs index 992147064c..198f4cb2b9 100644 --- a/crates/ui-egui/src/panels/retype/tests.rs +++ b/crates/ui-egui/src/panels/retype/tests.rs @@ -232,3 +232,125 @@ fn choosing_a_listed_font_sets_it_on_the_selected_live_text() { click(&mut app, &ctx, "Source Serif 4 Regular"); assert!(app.session.active().unwrap().doc == before); } + +/// Live text in Source Sans 3, selected, and a list of two fonts → the app and the text's id. +fn listed_with_live_text() -> (VectorcraftApp, u64) { + let mut app = app(); + let font = |family: &str, style: &str| super::Found { family: family.into(), style: style.into(), matched: 1 }; + app.ui.retype.searched = true; + app.ui.retype.fonts = vec![font("Source Sans 3", "Bold"), font("Source Serif 4", "Regular")]; + let t = app.session.execute("text.create", &json!({"x": 10, "y": 300, "text": "live", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + select(&mut app, &[t]); + (app, t) +} + +fn family_of(app: &VectorcraftApp, id: u64) -> String { + let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text") }; + text.first_style().font_family.clone() +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +const SERIF: &str = "Source Serif 4 Regular"; +const SANS: &str = "Source Sans 3 Bold"; + +#[test] +fn a_fonts_menu_selects_its_row_without_setting_the_font() { + use craft::ui::contract::Role; + + let (app, t) = listed_with_live_text(); + let mut panel = Panel::new(app, show); + let undo = undo_len(&panel.app()); + panel.secondary_click(SERIF); + assert!(panel.menu_item_enabled("Apply Font"), "live text is selected"); + assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "the secondary click sets no font"); + assert_eq!(undo_len(&panel.app()), undo); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.frame(); + assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM)); + assert!(panel.selected(SERIF), "the row the menu opened on is selected"); + assert!(!panel.selected(SANS)); + assert_eq!(family_of(&panel.app(), t), "Source Sans 3"); +} + +#[test] +fn apply_font_sets_the_rows_font_on_the_live_text_in_one_undo_step() { + let (app, t) = listed_with_live_text(); + let mut panel = Panel::new(app, show); + let undo = undo_len(&panel.app()); + // A menu opened on another row first, then closed: the menu acts on the row it opened on last. + panel.secondary_click(SANS); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.secondary_click(SERIF); + panel.click_menu_item("Apply Font"); + assert_eq!(family_of(&panel.app(), t), "Source Serif 4", "the font of the row the menu opened on"); + assert_eq!(undo_len(&panel.app()), undo + 1); +} + +#[test] +fn apply_font_is_off_without_live_text() { + let (mut app, t) = listed_with_live_text(); + select(&mut app, &[]); + let mut panel = Panel::new(app, show); + panel.secondary_click(SERIF); + assert!(!panel.menu_item_enabled("Apply Font")); + assert!(panel.menu_item_enabled("Reset Retype Panel"), "the panel's own items stay on"); + assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "text that is not selected keeps its font"); +} + +#[test] +fn the_fonts_menu_sets_the_sample_size_and_resets_the_panel() { + use craft::behavior::Mixed; + use craft::ui::contract::Role; + + let (app, _) = listed_with_live_text(); + let mut panel = Panel::new(app, show); + let before = panel.app().ui.retype.size; + let (other, label) = if before == Size::Large { (Size::Small, "Small") } else { (Size::Large, "Large") }; + panel.secondary_click(SERIF); + panel.click_role(label, Role::MENU_ITEM_CHECK_BOX); + assert_eq!(panel.app().ui.retype.size, other, "the size changed to the one chosen"); + panel.secondary_click(SERIF); + assert_eq!(panel.toggled(label), Some(Mixed::Same(true)), "the size chosen is checked"); + panel.click_menu_item("Reset Retype Panel"); + assert!(!panel.app().ui.retype.searched, "the list is cleared"); + assert_eq!(panel.app().ui.retype.size, other, "the size stays"); +} + +#[test] +fn keyboard_opens_the_fonts_menu_and_escape_returns_focus() { + use craft::ui::contract::Role; + + let (app, t) = listed_with_live_text(); + let mut panel = Panel::new(app, show); + panel.focus(SERIF); + panel.key(egui::Key::F10, egui::Modifiers::SHIFT); + panel.frame(); + assert!(panel.menu_item_enabled("Apply Font")); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.frame(); + assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM)); + assert!(panel.focused(SERIF)); + assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "opening and closing the menu sets no font"); +} + +#[test] +fn the_fonts_menu_closes_when_the_list_or_the_document_changes() { + use craft::ui::contract::Role; + + let (app, _) = listed_with_live_text(); + let mut panel = Panel::new(app, show); + panel.secondary_click(SERIF); + assert!(panel.shows_role("Apply Font", Role::MENU_ITEM)); + // Another search puts another font in the row's place. + panel.app().ui.retype.fonts.reverse(); + panel.frame(); + assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM)); + panel.secondary_click(SERIF); + assert!(panel.shows_role("Apply Font", Role::MENU_ITEM)); + panel.app().run("file.new", json!({"width": 300, "height": 200})).unwrap(); + panel.frame(); + assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM)); +} diff --git a/crates/ui-egui/src/tests/home.rs b/crates/ui-egui/src/tests/home.rs index 904de40932..50991b8d8c 100644 --- a/crates/ui-egui/src/tests/home.rs +++ b/crates/ui-egui/src/tests/home.rs @@ -164,6 +164,27 @@ fn home_lists_recent_files_and_a_click_opens_one() { assert!(!app.ui.status.is_empty(), "a file that can't be opened says so"); } +/// The Home screen heads its recent files "Recent Files", in the interface language where the catalog translates it. +#[test] +fn home_heads_the_recent_files_recent_files() { + use crate::i18n::LangExt as _; + let shown = |lang: &str| { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.session.prefs.interface_language = lang.into(); + app.ui.recent_files = vec![std::env::temp_dir().join("vectorcraft-home-heading").join("Drawing.svg").to_string_lossy().into_owned()]; + home_screen(app) + }; + let home = shown("en"); + assert!(home.shows("Recent Files"), "the recent files are headed Recent Files"); + assert!(!home.shows("Recent"), "not Recent alone"); + let home = shown("de"); + let de = crate::i18n::Lang::from_code("de").expect("German is registered"); + let german = crate::i18n::tr(de, "Recent Files"); + // Without a German row for Recent Files, the framework's heading stays. + let heading = if german == "Recent Files" { crate::i18n::tr_id(de, "startScreen.recent", "Recent") } else { german }; + assert!(home.shows(heading), "German shows {heading}"); +} + /// The Home screen has a Learn section: every tutorial of the Learn panel under its skill. A /// tutorial shows the Learn panel at its steps and no document is opened; the Quick skill guide /// shows its list of skills. diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 7521da7d8c..65d23c6d3e 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -510,6 +510,11 @@ impl Panel { self.fixture.tree().focused_key() == self.look(name).node } + /// Whether the row or item named `name` reports itself selected. + pub(crate) fn selected(&self, name: &str) -> bool { + self.fixture.tree().selected_of(self.look(name).node).unwrap_or(false) + } + /// Whether the zero-based control of `role` has focus, including rows with identical names. pub(crate) fn focused_nth(&self, role: craft::ui::contract::Role, index: usize) -> bool { self.fixture.tree().focused_key() == self.look_nth(role, index).node diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index 0e00238ab4..24260dc24c 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -1,10 +1,12 @@ //! The app's interface font stack: the craft faces it embeds (Japanese, Georgian, Devanagari, //! Gujarati), JetBrains Mono for monospace, and the framework's loader for every other script. -//! The stack is installed once by the shell (`embed::install`). +//! The shell installs the stack at startup and refreshes it when the interface language changes. use std::sync::Arc; -use craft::ui::fonts::{Family, I18nScripts, SEMIBOLD, UiFonts}; +use craft::ui::fonts::{Family, FontFetcher, I18nScripts, SEMIBOLD, UiFonts}; + +use crate::i18n::{Lang, LangExt}; /// The interface fonts configuration. Characters no face covers are looked up in the installed /// system fonts on native; the web build has the faces its server offers instead. @@ -22,6 +24,49 @@ pub fn ui_fonts() -> UiFonts<'static> { } } +#[derive(Clone)] +struct FontSelection { + language: Lang, + fetcher: Option>, +} + +impl FontSelection { + fn fonts(&self) -> UiFonts<'static> { + let fonts = ui_fonts().ui_language(self.language.code()); + match &self.fetcher { + Some(fetcher) => fonts.fetcher(Arc::clone(fetcher)), + None => fonts, + } + } +} + +fn font_selection_id() -> egui::Id { + egui::Id::unique("vectorcraft-interface-font-selection") +} + +/// Builds the shell's initial font configuration and keeps its language and font fetcher with +/// this context so they can be reused when the interface language changes. +pub fn configure_ui_fonts(ctx: &egui::Context, language: Lang, fetcher: Option>) -> UiFonts<'static> { + let selection = FontSelection { language, fetcher }; + let fonts = selection.fonts(); + ctx.data_mut(|data| data.insert_temp(font_selection_id(), Some(selection))); + fonts +} + +pub(crate) fn follow_language(ctx: &egui::Context, language: Lang) { + let changed = ctx.data_mut(|data| { + let selection = data.get_temp_mut_or_default::>(font_selection_id()).as_mut()?; + if selection.language == language { + return None; + } + selection.language = language; + Some(selection.clone()) + }); + if let Some(selection) = changed { + selection.fonts().install(ctx); + } +} + #[cfg(test)] mod tests { use craft::ui::fonts::{FontRef, Sample, UiFonts, assert_covers, missing_glyphs}; @@ -44,6 +89,28 @@ mod tests { assert_covers(&ui_fonts().stack(), [Sample::new("hi", "hindi", HINDI)]); } + /// The face the web serves for Gujarati (a `demand` line of `crates/text/web-fonts.txt`) draws + /// every Gujarati character of the Gujarati catalog on its own, as on the web, which has no + /// other Gujarati face. + #[test] + fn web_gujarati_face_covers_the_gujarati_catalog() { + if !embeds("Gujr") { + eprintln!("skipped: built without craft-fonts, or one without a Gujarati face"); + return; + } + let served: Vec<_> = vectorcraft_text::CRAFT_FONTS + .iter() + .filter(|f| { + vectorcraft_text::WEB_FONTS.iter().any(|w| w.demand && w.scripts.contains(&"Gujr") && w.family == f.family && w.style == f.style) + }) + .copied() + .collect(); + assert!(!served.is_empty(), "the web serves a Gujarati face (a `demand` line of web-fonts.txt)"); + let gujarati: String = include_str!("i18n/gu.tsv").chars().filter(|c| ('\u{0A80}'..='\u{0AFF}').contains(c)).collect(); + assert!(!gujarati.is_empty()); + assert_covers(&UiFonts::new(&I18nScripts).craft_faces(&served).stack(), [Sample::new("gu", "gu.tsv", &gujarati)]); + } + #[test] fn japanese_renders_with_the_craft_fonts_without_installed_fonts() { if !embeds("Jpan") { @@ -53,6 +120,37 @@ mod tests { assert_covers(&ui_fonts().stack(), [Sample::new("ja", "japanese", JAPANESE)]); } + #[test] + fn han_fonts_follow_the_interface_language() { + if !embeds("Hans") || !embeds("Jpan") { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + } + let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + app.session.prefs.interface_language = "zh-hans".into(); + configure_ui_fonts(&ctx, app.ui_language(), None).install(&ctx); + + for (language, preferred, alternate) in [ + (None, "Noto Sans CJK SC", "BIZ UDPGothic"), + (Some("ja"), "BIZ UDPGothic", "Noto Sans CJK SC"), + (Some("zh-hans"), "Noto Sans CJK SC", "BIZ UDPGothic"), + ] { + if let Some(language) = language { + crate::menus::run_ui_command(&mut app, "app.language", &serde_json::json!({"lang": language})).unwrap().unwrap(); + } + crate::testing::part_frame(&mut app, &ctx, egui::RawInput::default(), |_, ui| { + ui.ctx().fonts(|fonts| { + let chain = &fonts.definitions().families[&egui::FontFamily::Proportional]; + let index = |family: &str| { + chain.iter().position(|face| face.starts_with(family)).unwrap_or_else(|| panic!("missing {family} in {chain:?}")) + }; + assert!(index(preferred) < index(alternate), "expected {preferred} before {alternate} in {chain:?}"); + }); + }); + } + } + #[test] fn the_ui_works_without_the_craft_fonts() { let stack = UiFonts::new(&I18nScripts).stack(); diff --git a/docs/gaps.md b/docs/gaps.md index 10c5f8c549..6f6dd5f11c 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,7 +1,7 @@ # Gaps > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-02 · **Change:** minor (G12: SVG Interactivity event rows have an item menu (Remove Event, Clear Events, Link JavaScript Files…); scores and estimates unchanged; previously: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-02 · **Change:** minor (G12: Retype panel font rows have an item context menu (Apply Font, sample sizes, Reset Retype Panel); scores and estimates unchanged; previously: G12: SVG Interactivity event rows have an item menu (Remove Event, Clear Events, Link JavaScript Files…); scores and estimates unchanged; previously: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. @@ -81,6 +81,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | G12: Retype panel font rows have an item context menu: a secondary click or Shift+F10 selects the row and offers Apply Font (what a click on the row does; off without live text selected), the panel menu's Small, Medium and Large sample sizes and Reset Retype Panel; the menu closes when the list or the document changes. Headless regressions: `panels::retype::tests`. Scores and estimates unchanged. | | 2026-12-02 | minor | G12: SVG Interactivity event rows have an item menu: a right-click (or Shift+F10 on the focused row) picks that event and offers Remove Event (`svgInteractivity.removeEvent` for that row, one undo step), Clear Events (`svgInteractivity.clearEvents`, enabled like the panel menu row) and Link JavaScript Files… (`ui.javascriptFilesDialog`). Headless regressions: `panels::svg_interactivity::tests`. Scores and estimates unchanged. | | 2026-11-25 | minor | Document Info › Objects: total enclosed area (`pathArea` in pt²) for closed and compound paths (holes subtracted per fill rule; guides and open paths left out) and formatted Path Area in document units, beyond reference panel (#6965). Worked out only when the request covers Objects (`pathArea` null otherwise or with `pathArea: false`); the panel asks for it only while Objects or All Categories is shown. Tests: `info_gives_the_paths_total_area`, `info_works_out_the_path_area_only_for_the_objects_category`, `the_path_area_is_worked_out_only_while_objects_is_shown`, `format_area_formats_and_trims_cleanly`. Scores and estimates unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | @@ -190,7 +191,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate. -- **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without the modifier. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. The existing Control/Command-before-press Selection-tool loan is unchanged, and the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain. +- **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without the modifier. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. Control/Command held before pressing the end of a shown direction handle also mirrors: that press stays with Direct Selection, while a press anywhere else, or on a handle of the bounding box, is still lent to the Selection tool. The Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain. - **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. @@ -560,6 +561,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +- **Done (2026-12-02):** Retype panel font rows have an item context menu ([apply Retype suggested fonts to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html)). A secondary click, or Shift+F10 on the focused row, selects that row without setting its font and offers **Apply Font**, which sets the row's font on the selected live text as a click does, in one undo step, and is off while no live text is selected; then the panel menu's **Small**, **Medium** and **Large** sample sizes (`retype.preview`, the current one checked) and **Reset Retype Panel** (`retype.reset`). The menu closes when the list or the document changes, so it never acts on the font that took its row's place. Headless regressions: `panels::retype::tests::a_fonts_menu_selects_its_row_without_setting_the_font`, `apply_font_sets_the_rows_font_on_the_live_text_in_one_undo_step`, `apply_font_is_off_without_live_text`, `the_fonts_menu_sets_the_sample_size_and_resets_the_panel`, `keyboard_opens_the_fonts_menu_and_escape_returns_focus` and `the_fonts_menu_closes_when_the_list_or_the_document_changes`. Other G12 gaps remain; scores and estimates unchanged. + - **Done (2026-12-02):** SVG Interactivity event rows have an item context menu. A right-click on an event row, or Shift+F10 on the focused row, picks that event and offers **Remove Event** (`svgInteractivity.removeEvent` for that row, one undo step, announced like the footer's Remove Selected Entry), **Clear Events** (`svgInteractivity.clearEvents`, enabled under the same rule as the panel menu row) and **Link JavaScript Files…** (`ui.javascriptFilesDialog`). The menu closes when its row leaves the list or the document changes. Headless regressions: `panels::svg_interactivity::tests::row_menu_picks_its_row_and_removes_that_event_in_one_undo_step`, `row_menu_offers_the_panel_menu_and_footer_commands`, `keyboard_row_menu_opens_on_the_focused_row_and_escape_returns_focus` and `row_menu_closes_when_its_row_disappears_or_the_document_changes`. Other G12 gaps remain; scores and estimates unchanged. - Glyphs cells have an item context menu. A character offers **Insert Glyph** at the Type caret or in selected text. A glyph without a mapped character offers **Apply Alternate** for the character selected with the Type tool. The menu uses the same actions as Enter and double-click and disables the item when its text target cannot accept the glyph. @@ -958,7 +961,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** Arabic catalog and right-to-left layout; current gaps in other catalogs and native review; Hindi wording/layout review. The web build fetches NanumGothic for Korean and Noto Sans - Devanagari for Hindi when the interface needs them (`crates/text/web-fonts.txt`, `demand`). + Devanagari for Hindi and Noto Sans Gujarati for Gujarati when the interface needs them + (`crates/text/web-fonts.txt`, `demand`). Hindi now has a catalog and the pinned egui fork shapes Devanagari. Indonesian already has a catalog (see [localization-parity.md](localization-parity.md)); it is not an absent language. - **Estimate:** 50–85 h plus human review (Brazilian Portuguese completed 2026-10-14). @@ -1059,6 +1063,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | G16: Web: Gujarati can be selected as the interface language; the web fetches Noto Sans Gujarati when the interface needs it (`crates/text/web-fonts.txt`, `demand`), as it does Noto Sans Devanagari for Hindi. Status/error messages remain partial. Scores and estimates unchanged. | | 2026-11-27 | minor | G4 type: Language packs (#4936): spelling and hyphenation read the packs installed in the Craft apps' shared font store, and `proof.packs`, `proof.installPack` and `proof.removePack` list, install and remove them (installs need downloading on, which only the person turns on); a Preferences page to install them and the missing-pack bar remain; scores and estimates unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index fe10d21a97..428fbec0f6 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -24,7 +24,7 @@ English) in-app help, and the docs are English. (`bflatastic`), with community contributors adding or correcting (German by `dwetscher`, Japanese and Traditional Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded as reviewed by native speakers; the contributor approved all 387 later Gujarati additions on 2026-11-14. -> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, but the web startup list contains no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged. +> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so Gujarati can be selected on the web. Scores and estimates unchanged. ## The thirteen key languages @@ -34,7 +34,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | Simplified Chinese (Mandarin) | `zh-hans` | 9,625 rows, 3,735 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`) | all (the untranslated report lists 237 messages without a row for it) | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) | | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (3,770 `@msg` and 55 `@msgplural` rows, counted 2026-11-18: the untranslated report lists 269 messages without a Spanish row, 236 in its own section and 33 that all 24 checked languages lack) | Latin | no | full | — (review) | | Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | -| Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback (Noto Sans Gujarati, in the pinned CI/release fonts); not in the web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | +| Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback (Noto Sans Gujarati, in the pinned CI/release fonts); the web fetches Noto Sans Gujarati when the interface needs it | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages | | Arabic | `ar` | preparatory registration (native name العربية) and 6-form CLDR plural probe only; translations maintained upstream in `storytold/craft-i18n` (`locales/ar/vectorcraft.tsv`) and not yet consumed | none (UI not exposed pending shared catalog) | document text: existing bidirectional layout and paragraph direction; interface UI: not exposed pending shared catalog, with full shell mirroring pending STD-I18N-001 | — (preparatory) | preparatory (not exposed) | 15–20 | | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | | Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | @@ -101,6 +101,7 @@ font for the web build. | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | Gujarati (`gu`): Web: Gujarati can be selected as the interface language; the web fetches Noto Sans Gujarati when the interface needs it (`crates/text/web-fonts.txt`, `demand`), as it does Noto Sans Devanagari for Hindi. Status/error messages remain partial. Scores and estimates unchanged. | | 2026-11-25 | patch | Arabic (`ar`): preparatory registration and 6-form CLDR plural routing; kept unavailable to users pending upstream `storytold/craft-i18n` catalog | | 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. | | 2026-11-12 | minor | Gujarati (`gu`): reviewed by a native speaker; zero/one singular plurals (CLDR); Gujarati craft-fonts faces join the UI fonts; strings added on main since branching translated (4,286 rows) | diff --git a/docs/mcp.md b/docs/mcp.md index af13970bc4..cc0e00cf5f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7129,7 +7129,8 @@ act on several fills/strokes at once, and `appearance.showAllHidden` makes every visible again. In remote mode, `effect.dialog {effect, index, item}` opens an applied effect's dialog prefilled (`ui.dialog.confirm` runs `effect.setParams`); see the control protocol for the "already applied" question. `effect.move` rejects a `copy` value that is not a boolean, and every command that takes `aligned` rejects an `aligned` -value that is not a boolean. +value that is not a boolean. With `aligned: true`, objects with different appearances can reorder effects within an +identical object effect list or within a shared fill or stroke. Copies and moves between lists require equal appearances. Effect dialogs use the targeted object, group, or layer shown in Appearance. The Transform dialog previews valid numbers as they are typed, including Copies, distances with units, and rotation. With Preview off, changes apply diff --git a/docs/roadmap.md b/docs/roadmap.md index 2ebf5da5d3..4b1a90f724 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -28,7 +28,7 @@ > Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged. -> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged. +> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so Gujarati can be selected on the web. Scores and estimates unchanged. ## Feature submission evidence @@ -169,7 +169,7 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V Hindi interface follow-up (2026-11-06): the catalog and zero/one plural rule are implemented; native wording review, layout checks and a web Devanagari font remain. [Notes](localization-hi.md). -Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule are implemented. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and a bundled Gujarati web font remains to be supplied. +Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule are implemented. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. Since 2026-12-02 the web fetches Noto Sans Gujarati when the interface needs it, so Gujarati can be selected on the web. ## Current focus @@ -214,7 +214,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | -| M14 follow-up | Gujarati interface (#6613) | 🟡 Zero/one singular plurals and desktop font fallback; 4,673 contributor-reviewed rows, including 387 approved additions with 11 wording corrections; status/error messages remain partial and pinned fonts lack a Gujarati face | Included above | +| M14 follow-up | Gujarati interface (#6613) | 🟡 Zero/one singular plurals and desktop font fallback; 4,673 contributor-reviewed rows, including 387 approved additions with 11 wording corrections; status/error messages remain partial; the web fetches Noto Sans Gujarati on demand | Included above | | | **Total to full parity** (one agent; from [target-app-parity.md](target-app-parity.md)) | | **~360–590** | Milestone estimates predate the 2026-10-10 re-measure for M1–M14; the area table in @@ -254,6 +254,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | Gujarati (`gu`): Web: Gujarati can be selected as the interface language; the web fetches Noto Sans Gujarati when the interface needs it (`crates/text/web-fonts.txt`, `demand`), as it does Noto Sans Devanagari for Hindi. Status/error messages remain partial. Scores and estimates unchanged. | | 2026-11-26 | minor | #8744: native-canvas sampler-owned release/Zoom regression source, retaining ordinary navigation, dock rejection, accepted sampling, document/selection/paint/history controls and no idle replay. Runtime pending; scores, gaps and hours unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ca1b87ce3e..abbd173117 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -37,7 +37,7 @@ Native saves on Unix flush the destination directory after writing or replacing > Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged. -> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged. +> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so Gujarati can be selected on the web. Scores and estimates unchanged. ## Feature submission evidence @@ -1277,7 +1277,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Swedish messages (2026-11-13): the Swedish (`sv`) catalog has an `@msg` row for 464 of the 628 status and error messages the untranslated report listed for it; 162 messages that no complete-message catalog translates, 36 composite font errors among them, are not translated yet, and two unknown-parameter errors that start with the `{within}` placeholder stay in English, as does `{name} must be {lo}–{hi}{unit} (got {v})`, whose existing row can't match because two of its placeholders sit side by side; the rows keep their placeholders, backticked names, quoted values and command ids; native review remains; scores and estimates unchanged. - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and workspaces keep the setting. A floating Tools panel dropped on the canvas's left edge, right of panels docked on the left, docks there and turns the setting on, and one dropped on the window's left edge docks there and turns it off; with no panels docked on the left, a drop leaves the setting as it is (#7837). Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_dropped_on_a_left_edge_dock_there_and_the_setting_follows`, `tools_dropped_where_the_left_edges_overlap_keep_the_setting`, `tools_dropped_beside_a_collapsed_left_dock_follow_the_strip_dropped_on`). - Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md). - - Gujarati (2026-11-14, #6613): `gu` has 4,673 catalog rows, zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial; the pinned fonts and web startup list have no Gujarati face, so web selection remains unavailable until one is bundled. Current-head validation is recorded in the PR; scores and estimates unchanged. + - Gujarati (2026-11-14, #6613): `gu` has 4,673 catalog rows, zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. Since 2026-12-02 the web fetches Noto Sans Gujarati when the interface needs it, so Gujarati can be selected on the web. Current-head validation is recorded in the PR; scores and estimates unchanged. - Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged. - Hindi word senses (2026-11-13): 85 labels and messages use the interface sense of their English: Desired is वांछित and the range message keeps both comparisons, rulers are रूलर, text characters कैरेक्टर, vector points पॉइंट, fills फ़िल्स and High Contrast उच्च कंट्रास्ट; the glossary test rejects the unrelated senses in every row; native review remains; scores and estimates unchanged. - Hindi terms (2026-11-13): every row that names a variable (data merge, variable fonts and widths, environment variables) says वेरिएबल, and joining paths, anchor points, point type and lines says जोड़ें instead of शामिल हों, which stays for joining the community; a test checks both terms in every row; scores and estimates unchanged. @@ -3443,6 +3443,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | Gujarati (`gu`): Web: Gujarati can be selected as the interface language; the web fetches Noto Sans Gujarati when the interface needs it (`crates/text/web-fonts.txt`, `demand`), as it does Noto Sans Devanagari for Hindi. Status/error messages remain partial. Scores and estimates unchanged. | | 2026-11-26 | minor | #8744: native-canvas sampler-owned release/Zoom regression source, retaining ordinary navigation, dock rejection, accepted sampling, document/selection/paint/history controls and no idle replay. Runtime pending; scores, gaps and hours unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d73ae6bfd7..a1fdfe43f7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,7 +1,7 @@ # UI and interaction parity > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-02 · **Change:** minor (G12: SVG Interactivity event rows have an item menu; scores and estimates unchanged; earlier: RFC-0052 Headless section, all unknown; earlier: Ctrl/Cmd+arrow fine nudge, #5258; scores and estimates unchanged; previously: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: 3D effect options: unchanged values preserve the document and add no Undo; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-02 · **Change:** minor (G12: Retype panel font rows have an item context menu (Apply Font, sample sizes, Reset Retype Panel); scores and estimates unchanged; previously: G12: SVG Interactivity event rows have an item menu; scores and estimates unchanged; earlier: RFC-0052 Headless section, all unknown; earlier: Ctrl/Cmd+arrow fine nudge, #5258; scores and estimates unchanged; previously: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: 3D effect options: unchanged values preserve the document and add no Undo; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. > @@ -82,6 +82,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| | 2026-12-02 | minor | Canvas context menu: rows for edit, group, path, type, view and artboard commands show a leading icon from the app's icon set, so a row can be found by its shape; rows without a fitting glyph stay text only (#4602); scores and estimates unchanged | +| 2026-12-02 | minor | Retype panel (G12): font rows have an item context menu: a secondary click or Shift+F10 selects the row and offers Apply Font (what a click on the row does; off without live text selected), the panel menu's Small, Medium and Large sample sizes and Reset Retype Panel; the menu closes when the list or the document changes. Headless regressions: `panels::retype::tests`. Scores and estimates unchanged. | | 2026-12-02 | minor | Headless (RFC-0052) column on the Summary table and every behaviour table: 365 unknown, with marking rules | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | @@ -283,7 +284,7 @@ Every parity table on this page has a Headless column: the Summary table (12 are | Drag a curved segment to bend it, a straight one to move its anchors | done | | unknown | | Drag by an anchor of a path selected whole moves the whole path; Alt-drag by an anchor or a segment copies it, Alt toggles the copy during the drag, and the copy snaps by the anchor pressed, onto the original too | done | #1104 | unknown | | Handles shown are the handles that drag; tolerance from Selection & Anchor Display | done | #494 | unknown | -| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/it/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | unknown | +| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag or held before pressing the handle (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan away from handle ends and on bounding box handles, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/it/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | unknown | | Show handles when multiple anchors are selected; Highlight anchors on mouse over; anchor and handle size | done | Preferences › Selection & Anchor Display | unknown | | Convert selected anchors to corner/smooth from the Control bar and Properties | done | | unknown | | Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; #3380 (deletion only): disconnected survivors of an ordinary contour become independent selected sibling objects, while multi-subpath paths and compound members stay intact; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes all selected surviving objects; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the surviving objects selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor | unknown | @@ -555,7 +556,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Appearance panel row context menu (G12) | done | Right-clicking a stroke or fill row offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide/Show Stroke / Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide/Show Effect; root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets it first before opening the context menu. Tests: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance`. | unknown | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | unknown | | SVG Interactivity event row item menu (G12) | done | Right-clicking an event row (or Shift+F10 on the focused row) picks that event and offers Remove Event, Clear Events and Link JavaScript Files…, the same commands as the footer and the panel menu; the menu closes when its row leaves the list or the document or artwork selection changes. `panels::svg_interactivity::tests::row_menu_picks_its_row_and_removes_that_event_in_one_undo_step`, `row_menu_offers_the_panel_menu_and_footer_commands`, `keyboard_row_menu_opens_on_the_focused_row_and_escape_returns_focus`, `row_menu_closes_when_its_row_disappears_or_the_document_changes` | unknown | -| Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). Installed fonts not loaded yet are compared too, read in the background with Cancel (`retype.cancelSearch`). Opening it from the Type menu, the context menu, and the Properties panel for outlined shapes (the Properties panel Quick Action opens it for text selections only), filtering by font source and favorites, near matches and text in images are missing (#4934) | unknown | +| Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). A row's context menu (secondary click or Shift+F10) selects it and offers Apply Font, off without live text, the three sample sizes and Reset Retype Panel (`panels::retype::tests`). Installed fonts not loaded yet are compared too, read in the background with Cancel (`retype.cancelSearch`). Opening it from the Type menu, the context menu, and the Properties panel for outlined shapes (the Properties panel Quick Action opens it for text selections only), filtering by font source and favorites, near matches and text in images are missing (#4934) | unknown | | Comments, Version History panels | missing | cloud features (out of scope) | unknown | | Blend panel (30.7) | partial | Window › Blend provides Type (Ease In, Ease Out, Ease In Out, Ease Out In), Ramp 0–100% and independent color Shift, alongside the existing blend controls. Easing is disabled without a spine. Original polynomial distributions approximate the publicly documented behavior. On-canvas Appearance and Easing widgets set Shift and Ramp; a blend without a spine shows the Appearance widget alone. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) | unknown | | Gradient panel: Dither (30.0) | done | Dither box under the stops (`paint.editGradient` `dither`); dimmed behind the Stroke proxy, fills only; `panels::gradient` test | unknown | diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs new file mode 100644 index 0000000000..ece5ccfe45 --- /dev/null +++ b/xtask/src/doc_tests.rs @@ -0,0 +1,367 @@ +//! Every library's doc tests deny unsafe code. +//! +//! Rustdoc compiles each doc test as a crate of its own, without the workspace's `[lints]` table +//! and without the library's own `#![forbid(unsafe_code)]`, so an `unsafe` block in a doc comment +//! passes `cargo test --doc`. Rustdoc adds the attributes in `#![doc(test(attr(...)))]` to every +//! doc test, so each library root carries `#![doc(test(attr(forbid(unsafe_code))))]`, or +//! `deny` where the library itself relies on the workspace's `deny`. `cargo xtask layers` runs +//! this check. + +use serde_json::Value; +use std::path::Path; + +/// Crate roots larger than this are reported instead of read. +const MAX_ROOT_BYTES: u64 = 8 * 1024 * 1024; + +/// The problems found in the workspace's library roots, one line each. +pub fn check(meta: &Value) -> Result, String> { + let pkgs = meta["packages"].as_array().ok_or("metadata: no packages array")?; + let root = Path::new(meta["workspace_root"].as_str().unwrap_or_default()); + let mut out = Vec::new(); + for p in pkgs { + let name = p["name"].as_str().ok_or("package without name")?; + for t in p["targets"].as_array().into_iter().flatten() { + let kinds: Vec<&str> = t["kind"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + let doc_tested = t["doctest"].as_bool() == Some(true) && kinds.iter().any(|k| matches!(*k, "lib" | "rlib" | "proc-macro")); + if !doc_tested { + continue; + } + let path = t["src_path"].as_str().ok_or_else(|| format!("{name}: library target without src_path"))?; + if let Some(problem) = check_root(name, root, Path::new(path))? { + out.push(problem); + } + } + } + out.sort(); + Ok(out) +} + +fn check_root(name: &str, root: &Path, path: &Path) -> Result, String> { + let shown = path.strip_prefix(root).unwrap_or(path).display(); + let len = std::fs::metadata(path).map_err(|e| format!("{shown}: {e}"))?.len(); + if len > MAX_ROOT_BYTES { + return Ok(Some(format!("{name}: {shown} is larger than {MAX_ROOT_BYTES} bytes"))); + } + let src = std::fs::read_to_string(path).map_err(|e| format!("{shown}: {e}"))?; + Ok(problem(&src).map(|p| format!("{name}: {shown}: {p}"))) +} + +/// What a library root is missing, or `None` when its doc tests deny unsafe code at least as +/// strictly as the library does. +fn problem(src: &str) -> Option<&'static str> { + let attrs = inner_attributes(src); + let forbids = attrs.iter().any(|a| sets_level(a, &["forbid"])); + match doc_test_level(&attrs) { + Some(Level::Forbid) => None, + _ if forbids => Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]"), + Some(Level::Deny) => None, + _ => Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]"), + } +} + +/// A lint level that rustdoc can add to every doc test. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Level { + Allow, + Deny, + Forbid, +} + +/// The lint attributes that set a level, and the level each one sets for this check. +const LEVELS: [(&str, Level); 5] = + [("forbid", Level::Forbid), ("deny", Level::Deny), ("allow", Level::Allow), ("warn", Level::Allow), ("expect", Level::Allow)]; + +/// The `unsafe_code` level that the `#![doc(test(attr(...)))]` attributes leave in force, read in +/// order. A later `allow`, `warn` or `expect` lowers an earlier `deny`, and nothing lowers a +/// `forbid`. The check does not evaluate `cfg_attr` conditions: a `deny` or `forbid` inside +/// `cfg_attr(...)` does not count, and an `allow`, `warn` or `expect` inside one lowers the level. +fn doc_test_level(attrs: &[String]) -> Option { + let mut level = None; + for doc in attrs.iter().filter_map(|a| args(a, "doc")) { + for test in items(doc).into_iter().filter_map(|i| args(i, "test")) { + for attr in items(test).into_iter().filter_map(|i| args(i, "attr")) { + for lint in items(attr) { + let direct = LEVELS.into_iter().find_map(|(name, l)| args(lint, name).is_some_and(names_unsafe_code).then_some(l)); + let next = direct.or_else(|| sets_level(lint, &["allow", "warn", "expect"]).then_some(Level::Allow)); + if let Some(next) = next + && level != Some(Level::Forbid) + { + level = Some(next); + } + } + } + } + } + level +} + +/// Whether `attr` is one of the lint attributes `names` applied to `unsafe_code`, directly or +/// inside `cfg_attr(...)`, whatever its condition. +fn sets_level(attr: &str, names: &[&str]) -> bool { + if names.iter().any(|name| args(attr, name).is_some_and(names_unsafe_code)) { + return true; + } + args(attr, "cfg_attr").is_some_and(|inner| items(inner).into_iter().skip(1).any(|a| sets_level(a, names))) +} + +/// The argument list of `item` when it is exactly `name(...)`. +fn args<'a>(item: &'a str, name: &str) -> Option<&'a str> { + let rest = item.strip_prefix(name)?.strip_prefix('(')?.strip_suffix(')')?; + let mut depth = 0usize; + for ch in rest.chars() { + match ch { + '(' => depth += 1, + ')' if depth == 0 => return None, + ')' => depth -= 1, + _ => {} + } + } + (depth == 0).then_some(rest) +} + +/// The comma-separated items of a list such as `deny(warnings),forbid(unsafe_code)`, split only +/// at the top level. +fn items(list: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut depth = 0usize; + let mut item_start = 0; + for (k, ch) in list.char_indices().chain(std::iter::once((list.len(), ','))) { + match ch { + '(' => depth += 1, + ')' => depth = depth.saturating_sub(1), + ',' if depth == 0 => { + if k > item_start { + out.push(&list[item_start..k]); + } + item_start = k + 1; + } + _ => {} + } + } + out +} + +/// The body of every crate-level `#![...]` attribute in `src`, without whitespace, read across +/// line breaks. Attributes inside braces (a module, a function) are skipped, comments are +/// skipped, and string and character literals are read as empty. +fn inner_attributes(src: &str) -> Vec { + let code: Vec = code_only(src).chars().filter(|c| !c.is_whitespace()).collect(); + let mut out = Vec::new(); + let mut braces = 0usize; + let mut i = 0; + while i + 2 < code.len() { + if code[i] == '{' { + braces += 1; + } else if code[i] == '}' { + braces = braces.saturating_sub(1); + } + if braces > 0 || code[i] != '#' || code[i + 1] != '!' || code[i + 2] != '[' { + i += 1; + continue; + } + let start = i + 3; + let mut depth = 1usize; + let mut j = start; + while j < code.len() && depth > 0 { + match code[j] { + '[' => depth += 1, + ']' => depth -= 1, + _ => {} + } + j += 1; + } + if depth > 0 { + break; + } + out.push(code[start..j - 1].iter().collect()); + i = j; + } + out +} + +/// `src` with line and (nested) block comments replaced by a space, and the contents of string, +/// raw string (including raw byte and raw C string) and character literals removed. +fn code_only(src: &str) -> String { + let c: Vec = src.chars().collect(); + let mut out = String::with_capacity(src.len()); + let mut i = 0; + while i < c.len() { + let next = c.get(i + 1).copied(); + let ident_before = i > 0 && (c[i - 1].is_alphanumeric() || c[i - 1] == '_'); + match c[i] { + '/' if next == Some('/') => { + while i < c.len() && c[i] != '\n' { + i += 1; + } + out.push(' '); + } + '/' if next == Some('*') => { + let mut depth = 0usize; + while i < c.len() { + if c[i] == '/' && c.get(i + 1) == Some(&'*') { + depth += 1; + i += 2; + } else if c[i] == '*' && c.get(i + 1) == Some(&'/') { + depth = depth.saturating_sub(1); + i += 2; + if depth == 0 { + break; + } + } else { + i += 1; + } + } + out.push(' '); + } + 'r' | 'b' | 'c' if !ident_before && raw_string_hashes(&c, i).is_some() => { + let (open, hashes) = raw_string_hashes(&c, i).unwrap_or((i, 0)); + let mut j = open + 1; + while j < c.len() && !(c[j] == '"' && (1..=hashes).all(|k| c.get(j + k) == Some(&'#'))) { + j += 1; + } + out.push_str("\"\""); + i = j + 1 + hashes; + } + '"' => { + let mut j = i + 1; + while j < c.len() && c[j] != '"' { + j += if c[j] == '\\' { 2 } else { 1 }; + } + out.push_str("\"\""); + i = j + 1; + } + '\'' if next == Some('\\') => { + let mut j = i + 3; + while j < c.len() && c[j] != '\'' { + j += 1; + } + out.push_str("''"); + i = j + 1; + } + '\'' if c.get(i + 2) == Some(&'\'') => { + out.push_str("''"); + i += 3; + } + ch => { + out.push(ch); + i += 1; + } + } + } + out +} + +/// For a raw string literal starting at `i` (`r"`, `r#"`, `br"`, `cr"`...), the index of its +/// opening quote and its number of `#`s. +fn raw_string_hashes(c: &[char], i: usize) -> Option<(usize, usize)> { + let mut j = i; + if matches!(c.get(j), Some('b' | 'c')) { + j += 1; + } + if c.get(j) != Some(&'r') { + return None; + } + j += 1; + let hashes = c[j..].iter().take_while(|&&ch| ch == '#').count(); + (c.get(j + hashes) == Some(&'"')).then_some((j + hashes, hashes)) +} + +/// Whether a lint list such as `unsafe_code,unused_must_use` names `unsafe_code`. +fn names_unsafe_code(list: &str) -> bool { + items(list).contains(&"unsafe_code") +} + +#[cfg(test)] +mod tests { + use super::problem; + + const NEEDS_DENY: Option<&str> = Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]"); + const NEEDS_FORBID: Option<&str> = Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]"); + + #[test] + fn a_forbidding_library_needs_forbid_in_its_doc_tests() { + assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None); + assert_eq!(problem("#![forbid(unsafe_code)]\n"), NEEDS_FORBID); + assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), NEEDS_FORBID); + } + + #[test] + fn a_library_on_the_workspace_deny_needs_deny_or_forbid() { + assert_eq!(problem("//! Docs.\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); + assert_eq!(problem("#![doc(test(attr(forbid(unsafe_code))))]\n"), None); + assert_eq!(problem("//! Docs.\npub fn f() {}\n"), NEEDS_DENY); + } + + #[test] + fn comments_other_lints_and_allow_do_not_count() { + assert_eq!(problem("// #![doc(test(attr(deny(unsafe_code))))]\n"), NEEDS_DENY); + assert_eq!(problem("//! `#![doc(test(attr(deny(unsafe_code))))]`\n"), NEEDS_DENY); + assert_eq!(problem("#![doc(test(attr(allow(unsafe_code))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![doc(test(attr(deny(warnings))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![deny(unsafe_code)]\n"), NEEDS_DENY); + assert_eq!(problem("// #![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); + assert_eq!(problem("#![forbid(unsafe_code)]\n// #![doc(test(attr(forbid(unsafe_code))))]\n"), NEEDS_FORBID); + } + + #[test] + fn attributes_inside_a_module_do_not_count() { + assert_eq!(problem("mod tests {\n #![doc(test(attr(deny(unsafe_code))))]\n}\n"), NEEDS_DENY); + assert_eq!(problem("#![forbid(unsafe_code)]\nmod a { #![doc(test(attr(forbid(unsafe_code))))] }\n"), NEEDS_FORBID); + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\nmod a { #![forbid(unsafe_code)] }\n"), None); + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\nmod a {\n fn f() {}\n}\n"), None); + } + + #[test] + fn spacing_and_other_attributes_in_the_list_are_accepted() { + assert_eq!(problem("#![doc(test(attr(deny(warnings), forbid( unsafe_code ))))]\n#![forbid(unsafe_code)]\n"), None); + } + + #[test] + fn block_comments_and_string_literals_do_not_count() { + assert_eq!(problem("#![forbid(unsafe_code)]\n/*\n#![doc(test(attr(forbid(unsafe_code))))]\n*/\n"), NEEDS_FORBID); + assert_eq!(problem("/* /* nested */ #![doc(test(attr(deny(unsafe_code))))] */\n"), NEEDS_DENY); + assert_eq!(problem("const S: &str = \"#![doc(test(attr(deny(unsafe_code))))]\";\n"), NEEDS_DENY); + assert_eq!(problem("const S: &str = r#\"#![doc(test(attr(deny(unsafe_code))))]\"#;\n"), NEEDS_DENY); + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\nconst S: &CStr = cr#\"\" #![forbid(unsafe_code)] \"#;\n"), None); + assert_eq!(problem("const Q: char = '\\'';\nconst S: &str = \"/*\";\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); + } + + #[test] + fn an_attribute_may_span_several_lines() { + assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(\n forbid(unsafe_code)\n)))]\n"), None); + assert_eq!(problem("#![forbid(\n unsafe_code\n)]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None); + } + + #[test] + fn grouped_lint_lists_are_read_item_by_item() { + let grouped = "#![forbid(unsafe_code, unused_must_use)]\n"; + assert_eq!(problem(&format!("{grouped}#![doc(test(attr(deny(unsafe_code))))]\n")), NEEDS_FORBID); + assert_eq!(problem(&format!("{grouped}#![doc(test(attr(forbid(unused_must_use, unsafe_code))))]\n")), None); + assert_eq!(problem("#![forbid(unsafe_code_extra)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); + assert_eq!(problem("#![doc(test(attr(deny(not_unsafe_code))))]\n"), NEEDS_DENY); + } + + #[test] + fn a_lint_inside_cfg_attr_does_not_count() { + assert_eq!(problem("#![doc(test(attr(cfg_attr(any(), deny(unsafe_code)))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(cfg_attr(any(), forbid(unsafe_code)))))]\n"), NEEDS_FORBID); + assert_eq!(problem("#![doc(test(no_crate_inject, attr(deny(unsafe_code))))]\n"), None); + } + + #[test] + fn cfg_attr_can_only_lower_the_doc_tests_or_raise_the_library() { + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), cfg_attr(all(), allow(unsafe_code)))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), cfg_attr(test, cfg_attr(all(), warn(unsafe_code))))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![cfg_attr(all(), forbid(unsafe_code))]\n#![doc(test(attr(deny(unsafe_code))))]\n"), NEEDS_FORBID); + assert_eq!(problem("#![cfg_attr(all(), forbid(unsafe_code))]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None); + assert_eq!(problem("#![cfg_attr(forbid, deny(unsafe_code))]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); + } + + #[test] + fn a_later_allow_lowers_deny_but_not_forbid() { + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), allow(unsafe_code))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\n#![doc(test(attr(warn(unsafe_code))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![doc(test(attr(allow(unsafe_code), deny(unsafe_code))))]\n"), None); + assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(forbid(unsafe_code), allow(unsafe_code))))]\n"), None); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 2152369254..a09949f548 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -9,6 +9,7 @@ mod brands; mod bundle; mod cache_units; mod cursors; +mod doc_tests; mod grant_sites; mod ico; mod layers; @@ -200,7 +201,8 @@ pub fn metadata() -> Result { } fn cmd_layers() -> Result<(), String> { - let crates = layers::from_metadata(&metadata()?)?; + let meta = metadata()?; + let crates = layers::from_metadata(&meta)?; println!("Dependency layering (plan/architecture.md §3)\n"); println!("{:<28} {:<14} workspace deps", "crate", "layer"); for c in &crates { @@ -219,17 +221,18 @@ fn cmd_layers() -> Result<(), String> { .collect(); println!("{:<28} {:<14} {}", c.name, layers::describe(layers::classify(&c.name)), ws.join(", ")); } - let violations = layers::check(&crates); + let mut violations: Vec = layers::check(&crates).iter().map(ToString::to_string).collect(); + violations.extend(doc_tests::check(&meta)?); println!(); if violations.is_empty() { - println!("OK: {} crates, no layering violations.", crates.len()); + println!("OK: {} crates, no layering violations, and every library's doc tests deny unsafe code.", crates.len()); Ok(()) } else { println!("{} violation(s):", violations.len()); for v in &violations { println!(" - {v}"); } - Err(format!("{} layering violation(s)", violations.len())) + Err(format!("{} violation(s)", violations.len())) } } diff --git a/xtask/src/web_fonts.rs b/xtask/src/web_fonts.rs index d30ef58c8e..391a3ee819 100644 --- a/xtask/src/web_fonts.rs +++ b/xtask/src/web_fonts.rs @@ -218,6 +218,42 @@ mod tests { assert!(at.join("LICENSE.txt").exists() && !at.join("LICENSE.html").exists()); } + /// The real hook on the real list: every `startup` and `demand` face (Gujarati included) lands + /// in the packaged site under `fonts/ui/`, byte for byte the file the craft-fonts manifest + /// hashes. Needs a craft-fonts checkout in `CRAFT_FONTS_DIR`; skips without one unless + /// `CRAFT_FONTS_REQUIRED=1`. + #[test] + fn the_packaged_site_serves_every_interface_face_as_the_manifest_hashes_it() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap(); + let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|v| !v.is_empty()).map(PathBuf::from) else { + assert!(std::env::var("CRAFT_FONTS_REQUIRED").as_deref() != Ok("1"), "CRAFT_FONTS_REQUIRED=1 but CRAFT_FONTS_DIR is unset"); + eprintln!("skipping: set CRAFT_FONTS_DIR to a craft-fonts checkout"); + return; + }; + let dir = if dir.is_absolute() { dir } else { root.join(dir) }; + let site = tempfile::tempdir().unwrap(); + run_with(root, Some(dir.clone()), Some(site.path().to_path_buf())).unwrap(); + + let list = std::fs::read_to_string(root.join("crates/text/web-fonts.txt")).unwrap(); + let manifest = std::fs::read_to_string(dir.join("fonts/manifest.txt")).unwrap(); + let mut checked = Vec::new(); + for e in list::parse_list(&list).unwrap().into_iter().filter(|e| e.startup || e.demand) { + let row = manifest + .lines() + .map(|l| l.split(" | ").map(str::trim).collect::>()) + .find(|r| r.first() == Some(&e.family) && r.get(1) == Some(&e.style)); + let Some(row) = row else { continue }; // an older craft-fonts lacks it; build.rs skips it too + let file = row[2].strip_prefix("fonts/").unwrap(); + let bytes = std::fs::read(site.path().join(SERVED_URL).join(file)).unwrap_or_else(|err| panic!("{SERVED_URL}{file}: {err}")); + assert_eq!(sha256::hex(&bytes), row[6], "{SERVED_URL}{file} differs from the manifest"); + checked.push(e.family.to_owned()); + } + // An older craft-fonts without the Gujarati face stays valid; one that has it must publish it. + if manifest.lines().any(|l| l.starts_with("Noto Sans Gujarati | Regular |")) { + assert!(checked.iter().any(|f| f == "Noto Sans Gujarati"), "the Gujarati face was not published: {checked:?}"); + } + } + #[test] fn without_craft_fonts_the_hook_does_nothing() { let (_, _, site, _) = fixture("noop", None);