From 1f148094d4ea0b8cab5f56186a0e4152c359d94b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:02:01 -0800 Subject: [PATCH 01/56] Type Tools: Create Font Sheet sets a sample text in every font, labeled Object > Plug-ins > Type Tools > Create Font Sheet... (addon.type.fontSheet) sets one line of sample text once in each family the font menus list, or in the families whose name contains a filter, or in a given list. Each entry is point type labeled with its font's name, flowed down columns on the active artboard inside a margin, and on new artboards of the same size to the right of the rightmost artboard when it fills. Every Style gives each style of a family its own entry. Fonts that do not load are left out, listed in `skipped` and named in a warning. The sheet is one selected group made in one undo step. The dialog's Preview starts off, since each preview sets the whole sheet again; addons::dialogs::open_with opens an add-on dialog with Preview off. Invalid parameters are refused with nothing changed: empty or multi-line text, sizes, columns, gaps and margins out of range or leaving no room, an unknown or repeated family, a filter that matches nothing, more than 5000 entries. Plug-ins cannot call the command, as with text.fontList. Docs: docs/mcp.md (Type Tools add-on > Create Font Sheet), docs/target-app-parity.md. --- crates/engine/src/cmd/addons/typetools.rs | 7 +- .../src/cmd/addons/typetools/font_sheet.rs | 280 ++++++++++++++++++ .../cmd/addons/typetools/font_sheet/tests.rs | 243 +++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/ui-egui/src/addons/dialogs.rs | 13 + crates/ui-egui/src/addons/dialogs/tests.rs | 22 ++ crates/ui-egui/src/addons/typetools.rs | 10 +- .../src/addons/typetools/font_sheet.rs | 84 ++++++ .../src/addons/typetools/font_sheet/tests.rs | 97 ++++++ docs/mcp.md | 49 ++- docs/target-app-parity.md | 4 + 11 files changed, 805 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/addons/typetools/font_sheet.rs create mode 100644 crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs create mode 100644 crates/ui-egui/src/addons/typetools/font_sheet.rs create mode 100644 crates/ui-egui/src/addons/typetools/font_sheet/tests.rs diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index 14a462d79f..586a716938 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -5,8 +5,10 @@ //! (). Release Type on a Path //! splits type on a path into point type holding the same text and the plain path it was set on //! (#5532). The reference app has no command for it, so it goes beyond parity and changes no -//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's. +//! parity score. Create Font Sheet ([`font_sheet`]) sets a line of sample text in every font. Its +//! submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's. +pub mod font_sheet; #[cfg(test)] mod tests; @@ -66,6 +68,9 @@ pub fn specs() -> Vec { release_path ), ] + .into_iter() + .chain(font_sheet::specs()) + .collect() } /// Release Type on a Path's command (the id in [`specs`]). diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet.rs b/crates/engine/src/cmd/addons/typetools/font_sheet.rs new file mode 100644 index 0000000000..699550c77f --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/font_sheet.rs @@ -0,0 +1,280 @@ +//! Create Font Sheet (`addon.type.fontSheet`; Object › Plug-ins › Type Tools › Create Font +//! Sheet…): a line of sample text set once in each font the font menus list (or in the fonts a +//! filter or a list names), each labeled with its font's name, flowed down columns on the active +//! artboard and on new artboards to its right when it fills, as one group made in one undo step. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind, TextObject, TextRun}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_text::FontDb; + +use super::super::super::create::{new_type_para, new_type_style}; +use super::super::super::typecmd::refresh_bounds; +use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; +use crate::{Result, Session}; + +/// The command. +pub const COMMAND: &str = "addon.type.fontSheet"; +/// The sample text when none is given. +pub const DEFAULT_TEXT: &str = "The quick brown fox jumps over the lazy dog"; +/// Most fonts one sheet sets. +pub const MAX_FONTS: usize = 5000; +/// Most characters the sample text has. +pub const MAX_CHARS: usize = 1000; +/// The largest size a label is set at; a smaller sample's label is set at the sample's size. +const LABEL_SIZE: f64 = 9.0; +/// The space between the artboards the sheet adds, as `artboard.new` leaves it. +const ARTBOARD_GAP: f64 = 20.0; +/// The page a document without artboards lays the sheet out on (US Letter). +const LETTER: Rect = Rect { x0: 0.0, y0: 0.0, x1: 612.0, y1: 792.0 }; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.type.fontSheet", + "Create Font Sheet", + ["Object", "Plug-ins", "Type Tools"], + None, + "{text?: one line of sample text, at most 1000 characters, without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, flowed down the columns of the active artboard (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer, in one undo step; the group is selected. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, is left out, listed in `skipped` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}", + has_doc, + font_sheet + )] +} + +/// `key` of `p`: `default` when omitted, else a number in `range`. +fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive) -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(default), + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && range.contains(n)) + .ok_or_else(|| bad(COMMAND, format!("`{key}` must be a number {}..{}", range.start(), range.end()))), + } +} + +/// The sample text of `p`: one line, not empty, at most [`MAX_CHARS`] characters. +fn sample_text(p: &Value) -> Result { + let text = match p.get("text") { + None | Some(Value::Null) => return Ok(DEFAULT_TEXT.into()), + Some(Value::String(t)) => t.clone(), + Some(_) => return Err(bad(COMMAND, "`text` must be a string")), + }; + if text.trim().is_empty() { + return Err(bad(COMMAND, "`text` must not be empty")); + } + // The line and paragraph separators break a line too. + if text.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')) { + return Err(bad(COMMAND, "`text` must be one line, without line breaks or other control characters")); + } + if text.chars().count() > MAX_CHARS { + return Err(bad(COMMAND, format!("`text` must be at most {MAX_CHARS} characters"))); + } + Ok(text) +} + +/// The families the sheet sets, in order: those `families` names, else those the font menus of +/// `db` list whose name contains `filter`. +fn families(p: &Value, db: &FontDb) -> Result> { + let filter = match p.get("filter") { + None | Some(Value::Null) => None, + Some(Value::String(f)) => Some(f.trim().to_lowercase()).filter(|f| !f.is_empty()), + Some(_) => return Err(bad(COMMAND, "`filter` must be a string")), + }; + let listed = match p.get("families") { + None | Some(Value::Null) => { + let menu = db.menu_family_list(); + let wanted = |f: &&String| filter.as_ref().is_none_or(|w| f.to_lowercase().contains(w.as_str())); + let found: Vec = menu.iter().filter(wanted).cloned().collect(); + if found.is_empty() { + return Err(bad(COMMAND, "no font family matches `filter`")); + } + return Ok(found); + } + Some(_) if filter.is_some() => return Err(bad(COMMAND, "give `families` or `filter`, not both")), + Some(Value::Array(a)) => a, + Some(_) => return Err(bad(COMMAND, "`families` must be a list of font family names")), + }; + if listed.is_empty() { + return Err(bad(COMMAND, "`families` must name at least one family")); + } + let composites = db.composite_font_names(); + let mut out: Vec = Vec::with_capacity(listed.len()); + for f in listed { + let f = f.as_str().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(COMMAND, "`families` must be a list of font family names"))?; + if !db.has_family(f) { + return Err(bad(COMMAND, format!("font family `{f}` is not available"))); + } + // The name as the font menus spell it. + let name = match composites.iter().find(|c| c.eq_ignore_ascii_case(f)) { + Some(c) => c.clone(), + None => db.canonical(f, "").0, + }; + if out.iter().any(|o| o.eq_ignore_ascii_case(&name)) { + return Err(bad(COMMAND, format!("`families` names `{name}` twice"))); + } + out.push(name); + } + Ok(out) +} + +/// The index of the artboard the view has active, else the one the document opened on, else the first. +fn active_artboard(st: &crate::DocState) -> usize { + let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id); + st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0) +} + +fn font_sheet(s: &mut Session, p: &Value) -> Result { + font_sheet_in(s, p, FontDb::global()) +} + +/// [`font_sheet`] over the fonts of `db`. +fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { + const C: &str = COMMAND; + let text = sample_text(p)?; + let size = number(p, "size", 12.0, 1.0..=1296.0)?; + let columns = number(p, "columns", 2.0, 1.0..=50.0)?; + if columns.fract() != 0.0 { + return Err(bad(C, "`columns` must be a whole number 1..50")); + } + let columns = columns as usize; + let gap = number(p, "gap", 12.0, 0.0..=1000.0)?; + let margin = number(p, "margin", 36.0, 0.0..=1000.0)?; + let all_styles = switch_or(p, "allStyles", false, C)?; + let labels = switch_or(p, "labels", true, C)?; + let new_artboards = switch_or(p, "newArtboards", true, C)?; + let families = families(p, db)?; + + // Each entry's font: (family, style); no style for the family's Regular or closest style. + let mut fonts: Vec<(String, Option)> = vec![]; + for f in &families { + let styles = if all_styles { db.styles(f) } else { vec![] }; + if styles.is_empty() { + fonts.push((f.clone(), None)); + } else { + fonts.extend(styles.into_iter().map(|st| (f.clone(), Some(st)))); + } + if fonts.len() > MAX_FONTS { + return Err(bad(C, format!("a sheet sets at most {MAX_FONTS} fonts: give `filter` or `families`"))); + } + } + + // Each page's layout: the label and sample sizes, an entry's height with the gap below it, and + // the rows and column width that fit inside the margin. + let label = size.min(LABEL_SIZE); + let pitch = if labels { label } else { 0.0 } + size * 1.5 + gap; + let st = s.doc()?; + let d = &st.doc; + let active = active_artboard(st); + let template = d.artboards.get(active).cloned(); + let page = template.as_ref().map_or(LETTER, |a| a.rect); + let (inner_w, inner_h) = (page.width() - 2.0 * margin, page.height() - 2.0 * margin); + let column_w = (inner_w - gap * (columns - 1) as f64) / columns as f64; + if column_w <= 0.0 || inner_h < pitch - gap { + return Err(bad(C, "the margin, gap and columns leave no room for a font on the artboard")); + } + let rows = (((inner_h + gap) / pitch).floor() as usize).max(1); + let per_page = rows * columns; + let right = d.artboards.iter().map(|a| a.rect.x1).fold(page.x1, f64::max); + // Where page `k` starts: the active artboard, then to the right of every artboard. + let page_x = |k: usize| if k == 0 { page.x0 } else { right + ARTBOARD_GAP + (k - 1) as f64 * (page.width() + ARTBOARD_GAP) }; + let system_layout = d.setup.system_layout; + let parent = st.target_parent()?; + + let label_style = { + let mut style = new_type_style(s, &json!({ "size": label }), C)?; + style.leading = Some(label * 1.2); + style + }; + let mut entries: Vec<(String, TextObject)> = Vec::with_capacity(fonts.len()); + let mut skipped: Vec = vec![]; + let composites = db.composite_font_names(); + for (family, style) in fonts { + let mut sample = new_type_style(s, &json!({ "size": size, "font": family, "style": style }), C)?; + sample.leading = Some(size * 1.2); + let name = match &style { + Some(st) => format!("{family} {st}"), + None => family.clone(), + }; + // A font that doesn't load is drawn in the fallback font, and a style that doesn't in the + // family's closest style: either is left out. + let composite = composites.iter().any(|c| c.eq_ignore_ascii_case(&family)); + let wanted = db.canonical(&family, "").0; + let loads = db + .face(&sample.font_family, &sample.font_style) + .is_some_and(|face| face.family.eq_ignore_ascii_case(&wanted) && style.as_ref().is_none_or(|st| face.style.eq_ignore_ascii_case(st))); + if !composite && !loads { + skipped.push(name); + continue; + } + let i = entries.len(); + let (k, j) = (i / per_page, i % per_page); + let (col, row) = (j / rows, j % rows); + let x = page_x(k) + margin + col as f64 * (column_w + gap); + let top = page.y0 + margin + row as f64 * pitch; + // The origin is the first baseline: one line's size below the entry's top. + let baseline = top + if labels { label } else { size }; + let mut t = TextObject::point(Point::new(x, baseline), &text, sample.clone()); + if labels { + t.runs = vec![TextRun::new(format!("{name}\n"), label_style.clone()), TextRun::new(text.clone(), sample)]; + } + t.para = new_type_para(); + t.system_layout = system_layout; + refresh_bounds(&mut t); + entries.push((name, t)); + } + if entries.is_empty() { + return Err(bad(C, "none of the fonts could be loaded")); + } + let count = entries.len(); + let pages = count.div_ceil(per_page); + let boards: Vec = (1..pages).map(|k| Rect::new(page_x(k), page.y0, page_x(k) + page.width(), page.y1)).collect(); + let template = template.filter(|_| new_artboards); + let (gid, added) = s.edit("Create Font Sheet", |d, sel| { + let mut added = vec![]; + if let Some(template) = template { + for rect in boards { + let mut a = template.clone(); + a.id = d.next_artboard_id(); + a.name = format!("Artboard {}", d.artboards.len() + 1); + a.rect = rect; + a.locked = false; + d.artboards.push(a); + added.push(d.artboards.len() - 1); + } + } + let children: Vec> = entries + .into_iter() + .map(|(name, t)| { + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.name = Some(name); + Arc::new(n) + }) + .collect(); + let gid = d.alloc_id(); + let mut g = Node::new(gid, NodeKind::Group { children, clip: false }); + g.name = Some("Font Sheet".into()); + d.insert(parent, usize::MAX, g)?; + sel.set([gid]); + Ok((gid, added)) + })?; + let mut out = json!({ "id": gid.0, "count": count, "skipped": skipped, "artboards": added }); + if let Some(warning) = skipped_warning(&skipped) { + out["warning"] = json!(warning); + } + Ok(out) +} + +/// The warning a sheet that left fonts out gives, naming the first few. +fn skipped_warning(skipped: &[String]) -> Option { + const NAMED: usize = 5; + let (first, more) = (skipped.iter().take(NAMED).cloned().collect::>(), skipped.len().saturating_sub(NAMED)); + match (first.is_empty(), more) { + (true, _) => None, + (false, 0) => Some(format!("{} font(s) could not be loaded and were left out: {}", skipped.len(), first.join(", "))), + (false, more) => Some(format!("{} font(s) could not be loaded and were left out: {} and {more} more", skipped.len(), first.join(", "))), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs new file mode 100644 index 0000000000..5a6064d530 --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs @@ -0,0 +1,243 @@ +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeId, NodeKind, TextObject}; +use vectorcraft_text::FontDb; + +use super::{COMMAND, DEFAULT_TEXT, MAX_CHARS}; +use crate::Session; + +/// The bundled families, available on every platform. +const BUNDLED: [&str; 3] = ["Inter", "Source Serif 4", "JetBrains Mono"]; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn group(s: &Session, r: &Value) -> Node { + s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().clone() +} + +/// Each entry of the sheet `g`: its name and its type. +fn entries(g: &Node) -> Vec<(String, TextObject)> { + g.children() + .unwrap() + .iter() + .map(|n| match &n.kind { + NodeKind::Text(t) => (n.name.clone().unwrap_or_default(), (**t).clone()), + _ => panic!("a font sheet holds only type"), + }) + .collect() +} + +/// Where the first baseline of `t` starts. +fn origin(t: &TextObject) -> (f64, f64) { + let [.., x, y] = t.xf.as_coeffs(); + (x, y) +} + +#[test] +fn a_sheet_sets_the_text_in_each_family_labeled_in_columns_in_one_undo_step() { + let mut s = session(); + let undo = steps(&s); + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 2, "size": 12, "gap": 10, "margin": 20, "text": "Hamburgefonstiv"})).unwrap(); + assert_eq!(r["count"], 3); + assert_eq!(r["skipped"], json!([])); + assert_eq!(r["artboards"], json!([]), "three entries fit on the artboard"); + assert_eq!(steps(&s), undo + 1, "one undo step"); + let g = group(&s, &r); + assert_eq!(g.name.as_deref(), Some("Font Sheet")); + assert_eq!(s.doc().unwrap().selection.objects, [g.id], "the sheet is selected"); + let e = entries(&g); + assert_eq!(e.iter().map(|(n, _)| n.as_str()).collect::>(), BUNDLED, "in the order given, each named after its font"); + for ((name, t), family) in e.iter().zip(BUNDLED) { + assert_eq!(t.plain_text(), format!("{name}\nHamburgefonstiv"), "a label line, then the sample"); + let [label, sample] = &t.runs[..] else { panic!("a label run and a sample run: {:?}", t.runs.len()) }; + assert_eq!(sample.style.font_family, family); + assert!((sample.style.size - 12.0).abs() < 1e-9 && (label.style.size - 9.0).abs() < 1e-9, "the label is set at 9 pt"); + assert_eq!(label.style.font_family, "Source Sans 3", "the label is in the normal type font"); + } + // Down the first column, 9 + 18 + 10 pt apart, inside the 20 pt margin, the first baseline one label below the top. + let board = s.doc().unwrap().doc.artboards[0].rect; + let (a, b) = (origin(&e[0].1), origin(&e[1].1)); + assert!((a.0 - board.x0 - 20.0).abs() < 1e-9 && (a.1 - board.y0 - 29.0).abs() < 1e-9, "{a:?}"); + assert!((b.0 - a.0).abs() < 1e-9 && (b.1 - a.1 - 37.0).abs() < 1e-9, "{b:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(g.id).is_none(), "undo removes the sheet"); +} + +#[test] +fn a_full_artboard_continues_on_new_artboards_to_the_right() { + let mut s = session(); + let undo = steps(&s); + // 400 pt tall less 2 × 100 pt of margin: 200 pt, room for two 72 pt entries (9 + 54 + 9). + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100})).unwrap(); + assert_eq!(r["count"], 3); + assert_eq!(r["artboards"], json!([1]), "the third entry goes on a new artboard"); + assert_eq!(steps(&s), undo + 1, "the new artboard is in the same undo step"); + let doc = &s.doc().unwrap().doc; + let (first, added) = (doc.artboards[0].rect, doc.artboards[1].rect); + assert!((added.x0 - first.x1 - 20.0).abs() < 1e-9 && (added.y0 - first.y0).abs() < 1e-9, "{added:?}"); + assert!((added.width() - first.width()).abs() < 1e-9 && (added.height() - first.height()).abs() < 1e-9, "the same size"); + let e = entries(&group(&s, &r)); + assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9, "inset by the margin on the new artboard"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "undo removes the artboard too"); + + // Without new artboards, the page after the first is laid out in the same place with none. + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100, "newArtboards": false})).unwrap(); + assert_eq!(r["artboards"], json!([])); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 1); + let e = entries(&group(&s, &r)); + assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9); +} + +#[test] +fn a_filter_picks_families_and_all_styles_lists_each_style() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"filter": " sOURCE s ", "labels": false})).unwrap(); + let e = entries(&group(&s, &r)); + let names: Vec<&str> = e.iter().map(|(n, _)| n.as_str()).collect(); + assert!(names.contains(&"Source Sans 3") && names.contains(&"Source Serif 4"), "{names:?}"); + assert!(names.iter().all(|n| n.to_lowercase().contains("source s")), "{names:?}"); + assert!(e.iter().all(|(_, t)| t.runs.len() == 1 && t.plain_text() == DEFAULT_TEXT), "no labels: the sample alone"); + + let r = s.execute(COMMAND, &json!({"families": ["Source Sans 3"], "allStyles": true})).unwrap(); + let e = entries(&group(&s, &r)); + let styles: Vec = vectorcraft_text::FontDb::global().styles("Source Sans 3"); + assert!(styles.len() > 1, "{styles:?}"); + assert_eq!(e.len(), styles.len(), "one entry for each style"); + for ((name, t), style) in e.iter().zip(&styles) { + assert_eq!(name, &format!("Source Sans 3 {style}")); + assert_eq!(&t.runs[1].style.font_style, style); + } +} + +/// Columns sit side by side, each `gap` apart and as wide as the room inside the margin allows. +#[test] +fn columns_share_the_room_inside_the_margin() { + let mut s = session(); + // 400 pt less 2 × 50 pt of margin leaves 300 pt: eight 39 pt entries (9 + 18 + 12) fit in a column. + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12})).unwrap(); + let board = s.doc().unwrap().doc.artboards[0].rect; + let e = entries(&group(&s, &r)); + // The first column fills before the second starts, so all three share it. + let xs: Vec = e.iter().map(|(_, t)| origin(t).0).collect(); + assert!(xs.iter().all(|x| (x - board.x0 - 50.0).abs() < 1e-9), "{xs:?}"); + // One row per column: each entry starts a column, (500 − 2 × 12) / 3 wide plus the gap apart. + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "size": 150})).unwrap(); + let e = entries(&group(&s, &r)); + let step = (500.0 - 24.0) / 3.0 + 12.0; + for (i, (_, t)) in e.iter().enumerate() { + let (x, y) = origin(t); + assert!((x - board.x0 - 50.0 - i as f64 * step).abs() < 1e-9 && (y - board.y0 - 59.0).abs() < 1e-9, "entry {i}: {x}, {y}"); + } + assert_eq!(r["artboards"], json!([])); +} + +#[test] +fn bad_params_are_refused_without_a_change() { + let mut s = session(); + let before = steps(&s); + let long = "x".repeat(MAX_CHARS + 1); + for bad in [ + json!({"text": ""}), + json!({"text": " "}), + json!({"text": "two\nlines"}), + json!({"text": "two\u{2028}lines"}), + json!({"text": "two\u{2029}paragraphs"}), + json!({"text": long}), + json!({"text": 5}), + json!({"size": 0.5}), + json!({"size": "12"}), + json!({"columns": 0}), + json!({"columns": 1.5}), + json!({"gap": -1}), + json!({"margin": 2000}), + json!({"margin": 300}), + json!({"columns": 50, "gap": 1000}), + json!({"filter": "no family is called this"}), + json!({"filter": 3}), + json!({"families": []}), + json!({"families": "Inter"}), + json!({"families": ["Inter", "inter"]}), + json!({"families": ["No Such Family Anywhere"]}), + json!({"families": [""]}), + json!({"families": ["Inter"], "filter": "Inter"}), + json!({"labels": "yes"}), + json!({"allStyles": 1}), + json!({"newArtboards": "no"}), + ] { + assert!(s.execute(COMMAND, &bad).is_err(), "{bad}"); + } + assert_eq!(steps(&s), before); + assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "nothing was drawn"); +} + +/// Fonts left out are named in the warning, the first five of them, with a count of the rest. +#[test] +fn fonts_left_out_are_named_in_a_warning() { + let names = |n: usize| (1..=n).map(|i| format!("Font {i}")).collect::>(); + assert_eq!(super::skipped_warning(&[]), None); + assert_eq!(super::skipped_warning(&names(2)).as_deref(), Some("2 font(s) could not be loaded and were left out: Font 1, Font 2")); + assert_eq!( + super::skipped_warning(&names(7)).as_deref(), + Some("7 font(s) could not be loaded and were left out: Font 1, Font 2, Font 3, Font 4, Font 5 and 2 more") + ); + let mut s = session(); + let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap(); + assert!(r.get("warning").is_none(), "nothing left out: no warning"); +} + +/// A family the font menus list whose file no longer reads as a font is left out, as is a style +/// that would be drawn in another style of its family; the rest of the sheet is made. +#[test] +fn fonts_that_do_not_load_are_left_out_and_named() { + use vectorcraft_text::test_fonts::named_copy; + let dir = vectorcraft_testkit::temp_dir("font-sheet-unreadable"); + let file = |family: &str, style: &str| dir.join(format!("{}-{style}.ttf", family.replace(' ', ""))); + for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Regular"), ("Sheet Half", "Bold")] { + let postscript = format!("{}-{style}", family.replace(' ', "")); + std::fs::write(file(family, style), named_copy(false, (family, style, "Version 1.000", &postscript)).unwrap()).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir.clone()]); + // Cataloged while every file reads; then two of them stop reading as fonts. + assert_eq!(db.styles("Sheet Half").len(), 2, "{:?}", db.styles("Sheet Half")); + assert!(db.menu_family_list().iter().any(|f| f == "Sheet Gone")); + for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Bold")] { + std::fs::write(file(family, style), b"not a font").unwrap(); + } + let mut s = session(); + let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone", "Inter"]}), &db).unwrap(); + assert_eq!(r["skipped"], json!(["Sheet Gone"]), "drawn in the fallback font, it is left out: {r}"); + assert_eq!(r["count"], 1); + assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: Sheet Gone"); + assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::>(), ["Inter"]); + let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Half"], "allStyles": true}), &db).unwrap(); + assert_eq!(r["skipped"], json!(["Sheet Half Bold"]), "drawn in its Regular, the Bold is left out: {r}"); + assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::>(), ["Sheet Half Regular"]); + // Nothing that loads: an error, with nothing changed. + let before = steps(&s); + assert!(super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone"]}), &db).is_err()); + assert_eq!(steps(&s), before); +} + +#[test] +fn it_needs_a_document() { + let mut s = Session::new(); + assert!(s.execute(COMMAND, &json!({})).is_err()); +} + +#[test] +fn a_locked_layer_takes_no_sheet() { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); + let before = steps(&s); + assert!(s.execute(COMMAND, &json!({"families": ["Inter"]})).is_err()); + assert_eq!(steps(&s), before); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 783f971487..132519d050 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -757,6 +757,7 @@ pub(super) const DENIED: &[&str] = &[ "addon.cleanup.splitText", "addon.pathtools.movePointsTogether", "addon.pen.nextSegment", + "addon.type.fontSheet", "color.contrast", "effect.refreshDeferred", "graphicStyle.setOptions", diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index e58443e259..09b8fe4efe 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -85,9 +85,21 @@ pub(crate) fn open( spec: &'static Spec, fields: DialogFields, build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static, +) -> Result { + open_with(app, spec, fields, build, true) +} + +/// [`open`], with the Preview box on at the start when `previewing`, else off. +pub(crate) fn open_with( + app: &mut VectorcraftApp, + spec: &'static Spec, + fields: DialogFields, + build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static, + previewing: bool, ) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; let dialog = HostedParamDialog::new(&ctx, spec.command, fields, build); + let dialog = if previewing { dialog } else { dialog.preview_off() }; let host = app.dialogs().ok_or("no window")?; close_open(app); let id = dialog.id(); @@ -105,6 +117,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option pathtools::bridge::open, pathtools::tangent_circle::COMMAND => pathtools::tangent_circle::open, typetools::COMMAND => typetools::open, + typetools::font_sheet::COMMAND => typetools::font_sheet::open, color::legend::COMMAND => color::legend::open, color::nearest::COMMAND => color::nearest::open, select::COMMAND => select::open, diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index 679a2e2e34..d2d21855ad 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -222,6 +222,28 @@ fn rows() -> Vec { assert!(label.contains("#123456") && label.contains("C="), "{label}"); }, }, + Row { + group: "Type Tools", + label: "Create Font Sheet…", + setup: new_app, + refused: || vec![("text", json!(" "))], + values: || vec![("text", json!("Sample")), ("filter", json!("JetBrains Mono"))], + check: |app| { + let doc = &app.session.doc().unwrap().doc; + let sheet = doc.layers[0].children().unwrap().last().unwrap(); + assert_eq!(sheet.name.as_deref(), Some("Font Sheet")); + let texts: Vec = sheet + .children() + .unwrap() + .iter() + .filter_map(|c| match &c.kind { + NodeKind::Text(t) => Some(t.plain_text()), + _ => None, + }) + .collect(); + assert!(texts.contains(&"JetBrains Mono\nSample".to_string()), "{texts:?}"); + }, + }, ] } diff --git a/crates/ui-egui/src/addons/typetools.rs b/crates/ui-egui/src/addons/typetools.rs index 3f73b835ee..790d4e661c 100644 --- a/crates/ui-egui/src/addons/typetools.rs +++ b/crates/ui-egui/src/addons/typetools.rs @@ -1,6 +1,8 @@ //! Type Tools in the interface: its submenu (Object › Plug-ins › Type Tools) and Text Tweaker's //! dialog, which picks an attribute, its start and end values and a shape, previews on the canvas -//! and runs `addon.type.textTweaker` on OK. +//! and runs `addon.type.textTweaker` on OK. Create Font Sheet's dialog is [`font_sheet`]'s. + +pub mod font_sheet; use craft::menu::Node; use craft::ui::contract::Bind; @@ -40,7 +42,11 @@ pub const RELEASE_MODES: &[(&str, &str)] = &[("Text and Path", "both"), ("Path O /// Object › Plug-ins › Type Tools. pub fn menu() -> Vec { - vec![c("Text Tweaker…", COMMAND), cp("Release Type on a Path…", RELEASE, json!({"mode": "both", "keepOriginal": false}))] + vec![ + c("Text Tweaker…", COMMAND), + cp("Release Type on a Path…", RELEASE, json!({"mode": "both", "keepOriginal": false})), + c("Create Font Sheet…", font_sheet::COMMAND), + ] } /// The attribute row of param `key` (the first, Font Size, for an unknown one). diff --git a/crates/ui-egui/src/addons/typetools/font_sheet.rs b/crates/ui-egui/src/addons/typetools/font_sheet.rs new file mode 100644 index 0000000000..3d92a96f1b --- /dev/null +++ b/crates/ui-egui/src/addons/typetools/font_sheet.rs @@ -0,0 +1,84 @@ +//! Create Font Sheet in the interface (Object › Plug-ins › Type Tools › Create Font Sheet…): a +//! dialog for the sample text, its size, a filter on the family names, whether each style gets an +//! entry and a label, and the columns, gap and margin of the pages. Its Preview box starts off; +//! switched on, it previews on the canvas. It runs `addon.type.fontSheet` on OK. + +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; +use craft::ui::runtime::env::UnitKind; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::addons::dialogs::{self, Spec}; +use crate::canvas::rulers::general_lengths; + +/// The command. +pub const COMMAND: &str = "addon.type.fontSheet"; +/// The sample text the dialog opens on. +const SAMPLE: &str = "The quick brown fox jumps over the lazy dog"; + +/// How the dialog's values reach the command. +pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; + +/// The command's parameters from the dialog's fields; an empty filter sets every family. +pub(crate) fn params(fields: &DialogFields) -> Value { + let mut p = json!({ + "text": fields.text("text").unwrap_or(SAMPLE), + "size": fields.number("size").unwrap_or(12.0), + "allStyles": fields.bool("allStyles").unwrap_or(false), + "labels": fields.bool("labels").unwrap_or(true), + "columns": fields.int("columns").unwrap_or(2), + "gap": fields.number("gap").unwrap_or(12.0), + "margin": fields.number("margin").unwrap_or(36.0), + "newArtboards": fields.bool("newArtboards").unwrap_or(true), + }); + if let Some(filter) = fields.text("filter").map(str::trim).filter(|f| !f.is_empty()) { + p["filter"] = json!(filter); + } + p +} + +/// Opens Create Font Sheet's dialog on the command's defaults, with Preview off: each preview sets +/// the whole sheet again. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + let fields = DialogFields::from_pairs([ + ("text", FieldValue::Text(SAMPLE.into())), + ("size", FieldValue::Number(12.0)), + ("filter", FieldValue::Text(String::new())), + ("allStyles", FieldValue::Bool(false)), + ("labels", FieldValue::Bool(true)), + ("columns", FieldValue::Int(2)), + ("gap", FieldValue::Number(12.0)), + ("margin", FieldValue::Number(36.0)), + ("newArtboards", FieldValue::Bool(true)), + ]); + let lengths = general_lengths(app); + dialogs::open_with( + app, + &SPEC, + fields, + move |fields| { + let written = fields.text("text").is_some_and(|t| !t.trim().is_empty()); + let rows = vec![ + Param::new("text", tl!("Sample Text:"), ParamKind::text(SAMPLE)), + Param::number("size", tl!("Size:"), 12.0, 1.0, 1).unit(UnitKind::Points).bounds(Some(1.0), Some(1296.0)), + Param::new("filter", tl!("Font Names Containing:"), ParamKind::text("")), + Param::new("allStyles", tl!("Every Style"), ParamKind::bool(false)), + Param::new("labels", tl!("Label Each Font"), ParamKind::bool(true)), + Param::new("columns", tl!("Columns:"), ParamKind::int(Some(1), Some(50), 2)), + Param::number("gap", tl!("Gap:"), 12.0, 1.0, 2).length(lengths).bounds(Some(0.0), Some(1000.0)), + Param::number("margin", tl!("Margin:"), 36.0, 1.0, 2).length(lengths).bounds(Some(0.0), Some(1000.0)), + Param::new("newArtboards", tl!("Add Artboards When Full"), ParamKind::bool(true)), + ]; + ParamDialog::new(COMMAND, tl!("Create Font Sheet"), rows) + .ok_enabled(written) + .ok_reason(tl!("Type a sample text.").into()) + .values(Bind::bound(fields)) + .previews(true) + }, + false, + ) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/typetools/font_sheet/tests.rs b/crates/ui-egui/src/addons/typetools/font_sheet/tests.rs new file mode 100644 index 0000000000..4891cea545 --- /dev/null +++ b/crates/ui-egui/src/addons/typetools/font_sheet/tests.rs @@ -0,0 +1,97 @@ +use craft::behavior::Mixed; +use craft::ui::contract::Role; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; +use serde_json::json; +use vectorcraft_doc::{NodeKind, TextObject}; + +use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; + +/// The entries of the selected font sheet. +fn sheet(app: &VectorcraftApp) -> Vec { + let state = app.session.active().unwrap(); + let group = state.doc.node(state.selection.objects[0]).unwrap(); + assert_eq!(group.name.as_deref(), Some("Font Sheet")); + group + .children() + .unwrap() + .iter() + .map(|node| match &node.kind { + NodeKind::Text(text) => (**text).clone(), + _ => panic!("a font sheet holds only type"), + }) + .collect() +} + +fn assert_typed_sheet(app: &VectorcraftApp) { + let entries = sheet(app); + assert_eq!(entries.len(), 1, "the typed filter picks one family"); + let entry = &entries[0]; + assert_eq!(entry.plain_text(), "Hamburg", "the typed text, with the label switched off"); + assert_eq!(entry.runs[0].style.font_family, "Source Serif 4"); + assert!((entry.runs[0].style.size - 20.0).abs() < 1e-9, "the typed size reaches the sample"); +} + +/// The dialog opens with Preview off. The keyboard and checkbox edits reach the preview once it is +/// switched on, and OK; Cancel restores the drawing, while OK with Preview left off applies the +/// same fields in one undo step. +#[test] +fn keyboard_and_checkbox_edits_reach_font_sheet_preview_ok_and_cancel() { + for commit in [false, true] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + assert_eq!(panel.toggled("Preview"), Some(Mixed::Same(false)), "Preview starts off"); + assert!(!panel.app().session.in_interaction(), "the opening sheet is not previewed"); + assert!(panel.app().session.active().unwrap().doc == before); + if !commit { + panel.click_role("Preview", Role::CHECK_BOX); + panel.frame(); + assert!(panel.app().session.in_interaction(), "switched on, Preview shows the sheet"); + } + for (label, input) in [("Sample Text", "Hamburg"), ("Font Names Containing", "Source Serif 4")] { + panel.click_role(label, Role::TEXT_INPUT); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(input); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + } + for (label, input) in [("Size", "20"), ("Columns", "1")] { + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(input); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + } + panel.click_role("Label Each Font", Role::CHECK_BOX); + if commit { + assert!(panel.app().session.active().unwrap().doc == before, "Preview off leaves the drawing alone"); + panel.click("OK"); + assert_typed_sheet(&panel.app()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + panel.app().run("edit.undo", json!({})).unwrap(); + } else { + assert_typed_sheet(&panel.app()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "Preview adds no undo step"); + panel.click("Cancel"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + assert!(!panel.app().session.in_interaction()); + assert!(panel.app().session.active().unwrap().doc == before, "Cancel or Undo restores the original drawing"); + assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty()); + } +} + +/// An empty filter sends none, so the sheet sets every family; a filter is sent trimmed. +#[test] +fn params_sends_a_filter_only_when_one_is_typed() { + let mut fields = DialogFields::from_pairs([("text", FieldValue::Text("Abc".into())), ("filter", FieldValue::Text(" ".into()))]); + let p = super::params(&fields); + assert!(p.get("filter").is_none(), "{p}"); + assert_eq!((&p["text"], &p["columns"], &p["labels"], &p["newArtboards"]), (&json!("Abc"), &json!(2), &json!(true), &json!(true))); + fields.set("filter", FieldValue::Text(" Inter ".into())); + assert_eq!(super::params(&fields)["filter"], json!("Inter")); +} diff --git a/docs/mcp.md b/docs/mcp.md index 7ed0eebae6..fde01f0426 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17913,8 +17913,8 @@ enabled only when a selected image has a mask. → `{changed, ids}` ## Type Tools add-on -Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker` and `addon.type.releasePath`, and -in the desktop app it lives in Object › Plug-ins › Type Tools (#4924, #5532). Text Tweaker gives one character attribute to the characters letter by letter, +Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker`, `addon.type.releasePath` and +`addon.type.fontSheet`, and in the desktop app it lives in Object › Plug-ins › Type Tools (#4924, #5532). Text Tweaker gives one character attribute to the characters letter by letter, from a start value to an end value along a shape, as one undo step; the text stays live and editable. Each value is set as `text.setRangeStyle` sets it (the Character panel), in its units and ranges ([formatting type](https://helpx.adobe.com/illustrator/using/formatting-type.html)), so on scaled type it is the size shown. @@ -17978,6 +17978,51 @@ Path Options' Preview does (#5360). {"name":"run_command","arguments":{"command":"addon.type.releasePath","params":{"mode":"path","keepOriginal":true}}} ``` +### Create Font Sheet + +`addon.type.fontSheet` makes a font specimen sheet in the active document: a line of sample text set once in each +font family the font menus list (the bundled, added and installed fonts), each entry labeled with its font's name, so +the fonts can be compared on the artboard or printed. + +- **Entries** are point type, one per family in the font menus' order (or in the order `families` gives), each named + after its font. With `labels` on, an entry starts with a line naming its font in the document's normal type font, at + the sample's size up to 9 pt, and the sample follows on the next line. With `allStyles` each style of a family gets + its own entry, labeled with the family and style; otherwise the family's Regular is used, else its closest style. +- **Layout:** the entries flow down the columns of the active artboard, inside `margin`, with `gap` between entries + and between columns. A sample wider than its column runs on past it. When the artboard is full, the sheet continues + on new artboards of the same size to the right of the rightmost artboard, 20 pt apart; with `newArtboards` off the + later pages are laid out in the same places without artboards. A document without artboards lays the sheet out on a + 612 × 792 pt page at the origin and adds no artboards. +- **Fonts that don't load:** a family whose font can't be loaded (text in it would be drawn in the fallback font), or + with `allStyles` a style that can't (it would be drawn in the family's closest style), is left out, listed in + `skipped` and named in `warning`, which the status bar shows. +- The sheet is one group named Font Sheet, in the current layer, made in one undo step and selected. Nothing changes, + and an error is returned, when no family matches, when there would be more than 5000 entries, when no font loads, + when the margin, gap and columns leave no room for one entry, or when the current layer is locked or hidden. + +| Parameter | Values (default) | +|---|---| +| `text` | one line of sample text, at most 1000 characters, without line or paragraph breaks or other control characters (`The quick brown fox jumps over the lazy dog`) | +| `size` | the sample's size, pt 1…1296 (12) | +| `filter` | only the families whose name contains this text, in any case; empty: every family | +| `families` | instead of `filter`: these family names, in this order; each must be available and named once | +| `allStyles` | false; true: one entry for each style of each family | +| `labels` | true; false: the sample alone | +| `columns` | whole number 1…50 (2) | +| `gap` | pt 0…1000, between entries and between columns (12) | +| `margin` | pt 0…1000, inside each page (36) | +| `newArtboards` | true; false: the pages after the first get no artboards | + +→ `{id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}`. Create Font Sheet… opens a dialog +(`ui.menuDialog {command}`) whose fields are the command's parameters except `families`, with Preview, which starts +off: switched on, it sets the whole sheet again after each change. OK is off while the sample text is empty. Plug-ins can't call the command, since the sheet lists the installed fonts as +`text.fontList` does. + +```json +{"name":"run_command","arguments":{"command":"addon.type.fontSheet","params":{"text":"Hamburgefonstiv","size":18,"filter":"sans"}}} +{"name":"run_command","arguments":{"command":"addon.type.fontSheet","params":{"families":["Inter","JetBrains Mono"],"allStyles":true,"columns":1}}} +``` + ## Unit Converter add-on Unit Converter is a built-in add-on that shows one length in every unit at once (#5528): its commands are diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f2d93a4568..cadb5b2c33 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3166,6 +3166,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app (it has no command for this), so no area score moves. Object › Plug-ins › Type Tools › Release Type on a Path… splits each selected type on a path into point type holding the same text and the plain path it was set on, or keeps only one of them (#5532). The path keeps its exact shape (open or closed, anchors and handles, the object's transform), layer and place in the stacking order, with no fill and no stroke since type paths carry no paint of their own. The text keeps its runs, character and paragraph attributes and becomes point type on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options don't apply to point type and are dropped. Keep Original leaves the type on a path and adds the released objects above it. Other objects are left alone and a selection with no type on a path makes no undo step; otherwise the run is one undo step, the released objects are selected, and the dialog's Preview works as Type on a Path Options' does (#5360). Tests: `cmd::addons::typetools::tests::release` in `vectorcraft-engine` (each mode, Keep Original, mixed and empty selections, closed, open, curved and flipped paths, transformed and grouped type, multi-style and unicode text with a centred paragraph, empty type, undo and redo, preview, cancel and commit, bad params refused), `release_type_on_a_path_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on › Release Type on a Path. +## Type Tools add-on: Create Font Sheet (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name, as point type flowed down columns on the active artboard and on new artboards of the same size to its right when the artboard is full. Every Style gives each style of a family its own entry; families whose font can't be loaded are left out and listed. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`). Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet. + ## Unit Converter add-on (2026-11-14) A VectorCraft addition, so no area score moves. Object › Plug-ins › Unit Converter opens a panel with one number field per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha), as proposed in #5528. A length typed in any field, with units and arithmetic as every number field reads them, updates the others as it is typed; text that does not read leaves them as they were. From Selection reads the selection's width and height as the Transform panel measures them, Width or Height picks which one the fields show, and Apply sets that side of the selection through `object.setBounds` as the Transform panel's W or H field does (its reference point, Constrain Width and Height Proportions and its Transform Object Only, Pattern Only or Both choice) as one undo step, with no step when the size is already that length. Each field's copy button copies its value, with its unit when Copy with Units is on. Agents use `addon.units.convert` and `addon.units.selectionSize`, which change nothing in the document (`docs/mcp.md`). Tests: `cmd::addons::units::tests` in `vectorcraft-engine` (every unit, number-field syntax, preview bounds and selected anchors, bad params and unknown keys refused), `addons::units::tests` in `vectorcraft-ui-egui` (typing, From Selection and a changed selection, Apply with the Transform panel's reference point, proportions, pattern choice and a symbol's registration point, copy, screen-reader names) and `command_sweep`. From db8fe499782e507fbad5ef5dcb1f89afd37b1727 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:58:14 -0800 Subject: [PATCH 02/56] Type Tools: Create Font Sheet's text parameter reads as one key CI failed `tests::params::every_description_parses`: the `text` note in `addon.type.fontSheet`'s description had commas outside parentheses, so the description parser split it and read `at most 1000 characters` as a key. The note now has no commas and keeps the same limits and default. --- crates/engine/src/cmd/addons/typetools/font_sheet.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet.rs b/crates/engine/src/cmd/addons/typetools/font_sheet.rs index 699550c77f..38073be8c9 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Create Font Sheet", ["Object", "Plug-ins", "Type Tools"], None, - "{text?: one line of sample text, at most 1000 characters, without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, flowed down the columns of the active artboard (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer, in one undo step; the group is selected. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, is left out, listed in `skipped` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}", + "{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, flowed down the columns of the active artboard (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer, in one undo step; the group is selected. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, is left out, listed in `skipped` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}", has_doc, font_sheet )] From 2198519cc73a67eb89f7a9271f336346c3715ad6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 22:18:10 -0800 Subject: [PATCH 03/56] Type Tools: Create Font Sheet keeps its opening artboard and sizes rows by ink Preview and OK now place the sheet on the artboard that was active when the dialog opened, and the view's active artboard is restored afterwards. Deleting that artboard while the dialog is open is refused; if it is gone, Preview and OK stop and ask to reopen the dialog. Other add-on dialogs keep using the current artboard. Rows are sized from each run's laid-out ink, so composite fonts whose sample uses fallback faces get rows tall enough for what they draw. The layout keeps per-run ink bounds so labeled sheets measure each glyph outline once. --- .../src/cmd/addons/typetools/font_sheet.rs | 127 +++++-- .../cmd/addons/typetools/font_sheet/tests.rs | 149 ++++++++ crates/engine/src/cmd/layer.rs | 6 + crates/engine/src/lib.rs | 7 + crates/engine/src/session/documents.rs | 1 + crates/text/src/layout/driver.rs | 12 +- crates/text/src/layout/vertical.rs | 12 +- crates/text/src/lib.rs | 36 +- crates/text/src/test_fonts.rs | 14 + crates/ui-egui/src/addons/arrange.rs | 10 +- crates/ui-egui/src/addons/color/legend.rs | 2 +- crates/ui-egui/src/addons/dialogs.rs | 71 +++- crates/ui-egui/src/addons/pathtools/bridge.rs | 2 +- crates/ui-egui/src/addons/pathtools/dashes.rs | 2 +- .../src/addons/pathtools/set_corners.rs | 2 +- .../src/addons/pathtools/tangent_circle.rs | 2 +- crates/ui-egui/src/addons/typetools.rs | 2 +- .../src/addons/typetools/font_sheet.rs | 2 +- .../src/addons/typetools/font_sheet/tests.rs | 331 ++++++++++++++++++ crates/ui-egui/src/app/commands.rs | 7 +- crates/ui-egui/src/dialogs/preview.rs | 6 +- docs/mcp.md | 12 +- docs/target-app-parity.md | 2 +- 23 files changed, 743 insertions(+), 74 deletions(-) diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet.rs b/crates/engine/src/cmd/addons/typetools/font_sheet.rs index 38073be8c9..9d71c86610 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet.rs @@ -7,8 +7,8 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Node, NodeKind, TextObject, TextRun}; -use vectorcraft_geom::{Point, Rect}; -use vectorcraft_text::FontDb; +use vectorcraft_geom::{Affine, Point, Rect, Shape}; +use vectorcraft_text::{FontDb, FontMatch}; use super::super::super::create::{new_type_para, new_type_style}; use super::super::super::typecmd::refresh_bounds; @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Create Font Sheet", ["Object", "Plug-ins", "Type Tools"], None, - "{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, flowed down the columns of the active artboard (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer, in one undo step; the group is selected. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, is left out, listed in `skipped` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}", + "{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, flowed down the columns of the active artboard (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}", has_doc, font_sheet )] @@ -159,34 +159,32 @@ fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { } } - // Each page's layout: the label and sample sizes, an entry's height with the gap below it, and - // the rows and column width that fit inside the margin. let label = size.min(LABEL_SIZE); - let pitch = if labels { label } else { 0.0 } + size * 1.5 + gap; let st = s.doc()?; let d = &st.doc; let active = active_artboard(st); let template = d.artboards.get(active).cloned(); let page = template.as_ref().map_or(LETTER, |a| a.rect); - let (inner_w, inner_h) = (page.width() - 2.0 * margin, page.height() - 2.0 * margin); - let column_w = (inner_w - gap * (columns - 1) as f64) / columns as f64; - if column_w <= 0.0 || inner_h < pitch - gap { - return Err(bad(C, "the margin, gap and columns leave no room for a font on the artboard")); - } - let rows = (((inner_h + gap) / pitch).floor() as usize).max(1); - let per_page = rows * columns; let right = d.artboards.iter().map(|a| a.rect.x1).fold(page.x1, f64::max); - // Where page `k` starts: the active artboard, then to the right of every artboard. - let page_x = |k: usize| if k == 0 { page.x0 } else { right + ARTBOARD_GAP + (k - 1) as f64 * (page.width() + ARTBOARD_GAP) }; let system_layout = d.setup.system_layout; let parent = st.target_parent()?; + // An entry's first baseline is at least one line's size below its top, and the entry at least + // this tall; the fonts are only laid out when the page has room for that. + let (least_above, least_height) = (if labels { label } else { size }, if labels { label } else { 0.0 } + size * 1.5); + let (inner_w, inner_h) = (page.width() - 2.0 * margin, page.height() - 2.0 * margin); + let column_w = (inner_w - gap * (columns - 1) as f64) / columns as f64; + let no_room = || bad(C, "the margin, gap and columns leave no room for a font on the artboard"); + if column_w <= 0.0 || inner_h < least_height { + return Err(no_room()); + } let label_style = { let mut style = new_type_style(s, &json!({ "size": label }), C)?; style.leading = Some(label * 1.2); style }; - let mut entries: Vec<(String, TextObject)> = Vec::with_capacity(fonts.len()); + // Each entry laid out at the origin, and how far its laid-out ink reaches above and below its first baseline. + let mut laid: Vec<(String, TextObject, (f64, f64))> = Vec::with_capacity(fonts.len()); let mut skipped: Vec = vec![]; let composites = db.composite_font_names(); for (family, style) in fonts { @@ -197,35 +195,54 @@ fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { None => family.clone(), }; // A font that doesn't load is drawn in the fallback font, and a style that doesn't in the - // family's closest style: either is left out. + // family's closest style: either is left out. A composite font is left out when a part + // that sets the sample names a font or style that doesn't load. let composite = composites.iter().any(|c| c.eq_ignore_ascii_case(&family)); - let wanted = db.canonical(&family, "").0; - let loads = db - .face(&sample.font_family, &sample.font_style) - .is_some_and(|face| face.family.eq_ignore_ascii_case(&wanted) && style.as_ref().is_none_or(|st| face.style.eq_ignore_ascii_case(st))); - if !composite && !loads { + let loads = if composite { + db.composite_coverage(&family, &[text.as_str()]).is_some_and(|c| c.status == FontMatch::Exact) + } else { + let wanted = db.canonical(&family, "").0; + db.face(&sample.font_family, &sample.font_style) + .is_some_and(|face| face.family.eq_ignore_ascii_case(&wanted) && style.as_ref().is_none_or(|st| face.style.eq_ignore_ascii_case(st))) + }; + if !loads { skipped.push(name); continue; } - let i = entries.len(); + let (first, more) = if labels { + (TextRun::new(format!("{name}\n"), label_style.clone()), Some(TextRun::new(text.clone(), sample))) + } else { + (TextRun::new(text.clone(), sample), None) + }; + let t = laid_out(first, more, system_layout); + let extent = ink_extent(&t); + laid.push((name, t, extent)); + } + if laid.is_empty() { + return Err(bad(C, "none of the fonts could be loaded")); + } + + // Each page's layout: each entry's first baseline as far below its top as its ink reaches above + // it, a row as tall as the tallest entry with the gap below it, and the rows that fit inside the margin. + let height = laid.iter().map(|(.., (a, b))| a.max(least_above) + b).fold(least_height, f64::max); + let pitch = height + gap; + if inner_h < height { + return Err(no_room()); + } + let rows = (((inner_h + gap) / pitch).floor() as usize).max(1); + let per_page = rows * columns; + // Where page `k` starts: the active artboard, then to the right of every artboard. + let page_x = |k: usize| if k == 0 { page.x0 } else { right + ARTBOARD_GAP + (k - 1) as f64 * (page.width() + ARTBOARD_GAP) }; + let mut entries: Vec<(String, TextObject)> = Vec::with_capacity(laid.len()); + for (i, (name, mut t, (above, _))) in laid.into_iter().enumerate() { let (k, j) = (i / per_page, i % per_page); let (col, row) = (j / rows, j % rows); let x = page_x(k) + margin + col as f64 * (column_w + gap); - let top = page.y0 + margin + row as f64 * pitch; - // The origin is the first baseline: one line's size below the entry's top. - let baseline = top + if labels { label } else { size }; - let mut t = TextObject::point(Point::new(x, baseline), &text, sample.clone()); - if labels { - t.runs = vec![TextRun::new(format!("{name}\n"), label_style.clone()), TextRun::new(text.clone(), sample)]; - } - t.para = new_type_para(); - t.system_layout = system_layout; - refresh_bounds(&mut t); + let baseline = page.y0 + margin + row as f64 * pitch + above.max(least_above); + // The layout is in text space, so moving the type keeps it. + t.xf = Affine::translate((x, baseline)); entries.push((name, t)); } - if entries.is_empty() { - return Err(bad(C, "none of the fonts could be loaded")); - } let count = entries.len(); let pages = count.div_ceil(per_page); let boards: Vec = (1..pages).map(|k| Rect::new(page_x(k), page.y0, page_x(k) + page.width(), page.y1)).collect(); @@ -265,6 +282,44 @@ fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { Ok(out) } +/// Point type set in `first` and then `more`, with its first baseline at the origin, laid out. +fn laid_out(first: TextRun, more: Option, system_layout: bool) -> TextObject { + let mut t = TextObject::point(Point::ZERO, "", first.style.clone()); + t.runs = std::iter::once(first).chain(more).collect(); + t.para = new_type_para(); + t.system_layout = system_layout; + t.normalize_paras(); + let layout = vectorcraft_text::layout(FontDb::global(), &t); + t.cached_bounds = Some(layout.bounds); + t.cached_baselines = layout.baselines(); + let mut ink = layout.run_ink_bounds.clone(); + for (run, bar) in vectorcraft_text::decorations(&layout, FontDb::global(), &t) { + if let Some(bounds) = ink.get_mut(run) { + let bar = bar.bounding_box(); + *bounds = Some(bounds.map_or(bar, |bounds| bounds.union(bar))); + } + } + t.cached_ink = Some((layout.bounds, ink.iter().copied().flatten().reduce(|a, b| a.union(b)))); + if t.runs.len() == 2 + && let (Some(label), Some(sample)) = (ink[0], ink[1]) + { + let overlap = label.y1 - sample.y0; + if overlap > 0.0 + && let Some(run) = t.runs.get_mut(1) + { + run.style.leading = Some(run.style.leading.unwrap_or(run.style.size * 1.2) + overlap); + refresh_bounds(&mut t); + } + } + t +} + +/// How far the ink of laid-out type `t` reaches above and below its first baseline, underline and +/// strikethrough bars included; none when nothing draws. +fn ink_extent(t: &TextObject) -> (f64, f64) { + t.cached_ink.and_then(|(_, ink)| ink).map_or((0.0, 0.0), |b| ((-b.y0).max(0.0), b.y1.max(0.0))) +} + /// The warning a sheet that left fonts out gives, naming the first few. fn skipped_warning(skipped: &[String]) -> Option { const NAMED: usize = 5; diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs index 5a6064d530..1095b4428c 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs @@ -226,6 +226,155 @@ fn fonts_that_do_not_load_are_left_out_and_named() { assert_eq!(steps(&s), before); } +/// Where the ink of `t` starts and ends down the page. +fn ink_rows(t: &TextObject) -> (f64, f64) { + let (_, y) = origin(t); + let b = vectorcraft_text::layout(FontDb::global(), t).ink_bounds().unwrap(); + (y + b.y0, y + b.y1) +} + +/// A composite font whose Roman part sets the sample at four times its size gets rows as tall as +/// its laid-out ink: the first entry stays inside the margin, the second starts below the first, +/// and each sample starts below its own label. +#[test] +fn rows_fit_the_laid_out_ink_of_a_composite_font() { + let mut s = session(); + let big = |name: &str| json!({"name": name, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter", "size": 400}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [big("CF Sheet Big A"), big("CF Sheet Big B")]})).unwrap(); + let p = json!({"families": ["CF Sheet Big A", "CF Sheet Big B"], "columns": 1, "size": 12, "gap": 10, "margin": 20, "text": "Hamburg"}); + let r = s.execute(COMMAND, &p).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}"); + let board = s.doc().unwrap().doc.artboards[0].rect; + let e = entries(&group(&s, &r)); + let ((top0, bottom0), (top1, _)) = (ink_rows(&e[0].1), ink_rows(&e[1].1)); + assert!(top0 >= board.y0 + 20.0 - 1e-6, "the first entry reaches into the margin: {top0}"); + assert!(top1 >= bottom0 - 1e-6, "the second entry overlaps the first: {top1} < {bottom0}"); + for (name, t) in &e { + let mut label = t.clone(); + label.runs.truncate(1); + let mut sample = t.clone(); + sample.runs.remove(0); + let (y0, y1) = (t.cached_baselines[0].0.y, t.cached_baselines[1].0.y); + let label_bottom = y0 + vectorcraft_text::layout(FontDb::global(), &label).ink_bounds().unwrap().y1; + let sample_top = y1 + vectorcraft_text::layout(FontDb::global(), &sample).ink_bounds().unwrap().y0; + assert!(sample_top >= label_bottom - 1e-6, "{name}: the sample reaches into its label: {sample_top} < {label_bottom}"); + } +} + +/// A composite font whose part setting the sample names a font that doesn't load is left out and +/// named, as a family that doesn't load is. +#[test] +fn a_composite_font_with_a_missing_part_is_left_out() { + let mut s = session(); + let font = json!({"name": "CF Sheet Gone", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "No Such Sheet Font"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Gone", "Inter"], "text": "Hamburg"})).unwrap(); + assert_eq!(r["skipped"], json!(["CF Sheet Gone"]), "{r}"); + assert_eq!(r["count"], 1); + assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::>(), ["Inter"]); +} + +#[test] +fn a_composite_font_with_an_unavailable_part_style_is_left_out() { + let mut s = session(); + let font = json!({ + "name": "CF Sheet Missing Style", + "parts": { + "kanji": {"font": "Source Sans 3"}, + "roman": {"font": "Inter", "style": "No Such Sheet Style"} + } + }); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let coverage = FontDb::global().composite_coverage("CF Sheet Missing Style", &["Hamburg"]).unwrap(); + assert_eq!(coverage.status, vectorcraft_text::FontMatch::Style); + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style", "Inter"], "text": "Hamburg"})).unwrap(); + assert_eq!(r["skipped"], json!(["CF Sheet Missing Style"])); + assert_eq!(r["count"], 1); + assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: CF Sheet Missing Style"); + assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::>(), ["Inter"]); + let before = (s.doc().unwrap().doc.clone(), steps(&s)); + assert!(s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style"], "text": "Hamburg"})).is_err()); + assert_eq!(s.doc().unwrap().doc, before.0); + assert_eq!(steps(&s), before.1); +} + +#[test] +fn labels_without_overlap_need_no_additional_layouts() { + use vectorcraft_text::test_fonts::{ink_work_on_this_thread, layouts_on_this_thread}; + + let mut counts = vec![]; + for labels in [false, true] { + let mut s = session(); + let before = layouts_on_this_thread(); + let ink_before = ink_work_on_this_thread(); + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "text": "Hamburg", "labels": labels})).unwrap(); + let ink_after = ink_work_on_this_thread(); + counts.push(layouts_on_this_thread() - before); + assert_eq!(r["count"], BUNDLED.len()); + let mut outlines = 0; + for (_, t) in entries(&group(&s, &r)) { + assert!(t.cached_ink.unwrap().1.is_some()); + assert_eq!(t.cached_baselines.len(), if labels { 2 } else { 1 }); + let layout = vectorcraft_text::layout(FontDb::global(), &t); + outlines += layout.glyphs.iter().chain(&layout.ruby).filter(|glyph| !glyph.outline.elements().is_empty()).count() as u64; + assert_eq!(t.cached_ink.unwrap().1, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t)); + } + assert_eq!(ink_after.0 - ink_before.0, outlines, "each glyph outline is measured once"); + assert_eq!(ink_after.1 - ink_before.1, BUNDLED.len() as u64, "decorations are measured once per entry"); + } + assert!(counts[0] > 0); + assert_eq!(counts[1], counts[0], "labels that fit must not cause separate label and sample layouts"); +} + +#[test] +fn reused_font_sheet_ink_includes_decorations_and_handles_blank_runs() { + use vectorcraft_doc::{CharStyle, TextRun}; + + for text in ["Hamburg", " "] { + for labels in [false, true] { + let style = CharStyle { font_family: "Inter".into(), size: 12.0, underline: true, strikethrough: true, ..Default::default() }; + let sample = TextRun::new(text, style.clone()); + let (first, more) = if labels { (TextRun::new("Font\n", style), Some(sample)) } else { (sample, None) }; + let t = super::laid_out(first, more, false); + let layout = vectorcraft_text::layout(FontDb::global(), &t); + let bars = vectorcraft_text::decorations(&layout, FontDb::global(), &t); + assert!(!bars.is_empty(), "the entry includes underline and strikethrough bars"); + let ink = t.cached_ink.unwrap().1; + assert_eq!(ink, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t)); + let ink = ink.unwrap(); + for (_, bar) in bars { + let bounds = vectorcraft_geom::Shape::bounding_box(&bar); + assert!(ink.x0 <= bounds.x0 && ink.y0 <= bounds.y0 && ink.x1 >= bounds.x1 && ink.y1 >= bounds.y1); + } + } + } +} + +#[test] +fn an_artboard_deletion_guard_checks_the_document_and_artboard_ids() { + let mut s = Session::new(); + s.execute("file.new", &json!({"artboards": 3})).unwrap(); + let state = s.doc().unwrap(); + let document = (state.uid, state.reverts); + let artboard = state.doc.artboards[1].id; + s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() }); + s.execute("artboard.delete", &json!({"index": 0})).unwrap(); + let before = (s.doc().unwrap().doc.clone(), steps(&s)); + for params in [json!({"index": 0}), json!({"indices": [1, 0]})] { + let error = s.execute("artboard.delete", ¶ms).unwrap_err(); + assert_eq!(error.to_string(), "The artboard is in use."); + assert_eq!(s.doc().unwrap().doc, before.0); + assert_eq!(steps(&s), before.1); + } + s.execute("file.new", &json!({"artboards": 2})).unwrap(); + s.execute("artboard.delete", &json!({"index": 1})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "another document is not protected"); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + s.doc_mut().unwrap().reverts += 1; + s.execute("artboard.delete", &json!({"index": 0})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "a reverted drawing is not protected"); +} + #[test] fn it_needs_a_document() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 78febf0f18..9528bb6c86 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -1155,6 +1155,12 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result { fn artboard_delete(s: &mut Session, p: &Value) -> Result { let indices = super::panelcmds::artboard_indices(&s.doc()?.doc, p, "artboard.delete")?; + if let Some(guard) = &s.artboard_deletion_guard { + let state = s.doc()?; + if (state.uid, state.reverts) == guard.document && indices.iter().any(|&index| state.doc.artboards[index].id == guard.artboard) { + return Err(EngineError::Other(guard.message.clone())); + } + } super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?; s.edit("Delete Artboard", |d, sel| remove_artboards(d, sel, &indices))?; ok() diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 48964aad0c..e1cabd484b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -50,12 +50,19 @@ pub use vectorcraft_tools as tools; pub use vectorcraft_doc::MAX_COORD; const _: () = assert!(vectorcraft_doc::MAX_DEPTH == 32, "TOO_DEEP (and its catalog rows) names the cap"); +pub struct ArtboardDeletionGuard { + pub document: (u64, u64), + pub artboard: u32, + pub message: String, +} + pub struct Session { docs: Vec, active: Option, pub prefs: Prefs, /// Whether Caps Lock is on, as the desktop host reports it; never saved with the preferences. pub caps_lock: bool, + pub artboard_deletion_guard: Option, /// Fill/stroke for new art (the toolbar proxy). pub paint: PaintDefaults, /// Which proxy is in front (true = Fill, false = Stroke) — the X key toggles. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 9c65271161..110722fa55 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -51,6 +51,7 @@ impl Session { active: None, prefs: Prefs::default(), caps_lock: false, + artboard_deletion_guard: None, paint: PaintDefaults::default(), fill_active: true, clipboard: Clipboard::default(), diff --git a/crates/text/src/layout/driver.rs b/crates/text/src/layout/driver.rs index 5813687d76..07f74f44cc 100644 --- a/crates/text/src/layout/driver.rs +++ b/crates/text/src/layout/driver.rs @@ -99,6 +99,8 @@ pub fn fit_source_lines(db: &FontDb, t: &mut TextObject, lines: usize) -> bool { /// own underline and strikeout metrics through the glyph's transform (so the size, baseline shift /// and scaling follow) → (run, bar in text space). Type on a path and vertical type have none yet. pub fn decorations(layout: &TextLayout, db: &FontDb, t: &TextObject) -> Vec<(usize, BezPath)> { + #[cfg(any(test, feature = "test-fonts"))] + crate::test_fonts::count_decorations(); let mut out = vec![]; if layout.on_path || layout.vertical { return out; @@ -449,6 +451,14 @@ fn layout_once(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout let original = |run: &mut usize| *run = from.get(*run).copied().unwrap_or(*run); l.glyphs.iter_mut().chain(l.ruby.iter_mut()).for_each(|g| original(&mut g.run)); l.inlines.iter_mut().for_each(|i| original(&mut i.run)); + let mut ink: Vec> = vec![None; t.runs.len()]; + for (mut run, bounds) in std::mem::take(&mut l.run_ink_bounds).into_iter().enumerate() { + original(&mut run); + if let (Some(ink), Some(bounds)) = (ink.get_mut(run), bounds) { + *ink = Some(ink.map_or(bounds, |ink| ink.union(bounds))); + } + } + l.run_ink_bounds = ink; l } @@ -572,6 +582,6 @@ fn layout_runs(db: &FontDb, t: &TextObject, opts: &LayoutOptions, set: Option<&T cx.out.line_xf = line_xf; } keep_lone_ligature_carets(&mut cx.out.glyphs); - finish_bounds(&mut cx.out); + finish_bounds(&mut cx.out, t.runs.len()); cx.out } diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs index 3262362fae..c8ed01552d 100644 --- a/crates/text/src/layout/vertical.rs +++ b/crates/text/src/layout/vertical.rs @@ -402,9 +402,17 @@ pub(super) fn stands_upright(g: &SGlyph) -> bool { !needs_vertical_form || g.gid != g.face.glyph_for(g.ch) } -pub(super) fn finish_bounds(out: &mut TextLayout) { +pub(super) fn finish_bounds(out: &mut TextLayout, runs: usize) { let xf = out.line_xf; - let mut b: Option = out.ink_bounds(); + let mut ink: Vec> = vec![None; runs]; + let mut b: Option = None; + out.for_each_ink(|run, bounds| { + b = Some(b.map_or(bounds, |b| b.union(bounds))); + if let Some(ink) = ink.get_mut(run) { + *ink = Some(ink.map_or(bounds, |ink| ink.union(bounds))); + } + }); + out.run_ink_bounds = ink; let mut add = |r: Rect| b = Some(b.map_or(r, |b| b.union(r))); if !out.on_path { for l in &out.lines { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 25e44392d6..27555a8e4a 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -387,6 +387,9 @@ pub struct TextLayout { pub lines: Vec, /// Ink/advance bounds in text space. pub bounds: Rect, + /// Ink bounds per text run when layout completed, excluding decorations. These bounds do + /// not update when glyph geometry changes; [`Self::ink_bounds`] measures the current geometry. + pub run_ink_bounds: Vec>, /// True if area text did not fit its frame (the red overflow "+" marker), or on-path text ran /// past the end of the path. pub overflow: bool, @@ -421,6 +424,7 @@ impl Default for TextLayout { ruby: Vec::new(), lines: Vec::new(), bounds: Rect::ZERO, + run_ink_bounds: Vec::new(), overflow: false, on_path: false, frames: Vec::new(), @@ -476,16 +480,34 @@ impl TextLayout { /// inline graphics included, without the lines' em boxes that [`Self::bounds`] also covers. /// What Align to Glyph Bounds aligns. `None` when nothing draws (only spaces, or no text). pub fn ink_bounds(&self) -> Option { - let outlined = |g: &PositionedGlyph| (!g.outline.elements().is_empty()).then(|| g.outline.bounding_box()); - let glyphs = self.glyphs.iter().flat_map(|g| { + let mut bounds: Option = None; + self.for_each_ink(|_, ink| bounds = Some(bounds.map_or(ink, |bounds| bounds.union(ink)))); + bounds + } + fn for_each_ink(&self, mut add: impl FnMut(usize, Rect)) { + let outlined = |g: &PositionedGlyph| { + (!g.outline.elements().is_empty()).then(|| { + #[cfg(any(test, feature = "test-fonts"))] + test_fonts::count_ink_outline(); + g.outline.bounding_box() + }) + }; + for g in &self.glyphs { let image = g.placed_image().map(|(image, xf)| xf.transform_rect_bbox(image.rect())); let colour = g.colour.as_ref().and_then(|c| c.geometric_bounds()).map(|b| g.xf.transform_rect_bbox(b)); - [outlined(g), image, colour] - }); + for ink in [outlined(g), image, colour].into_iter().flatten() { + add(g.run, ink); + } + } // Ruby is covered by its line's ascent, but its ink can overhang sideways past the line. - let ruby = self.ruby.iter().map(outlined); - let inlines = self.inlines.iter().map(|i| Some(i.bounds)); - glyphs.chain(ruby).chain(inlines).flatten().reduce(|a, b| a.union(b)) + for g in &self.ruby { + if let Some(ink) = outlined(g) { + add(g.run, ink); + } + } + for inline in &self.inlines { + add(inline.run, inline.bounds); + } } /// The box of [`Self::ink_bounds`]' ink with text space mapped by `m`: the glyph and ruby /// outlines are mapped point by point, so a rotated or sheared `m` gives the outlines' own diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index b07c7d63d8..800a832ae2 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -29,6 +29,20 @@ pub(crate) fn keeps_shape_plans() -> bool { std::thread_local! { /// How many layouts this thread has started ([`layouts_on_this_thread`]). static LAYOUTS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INK_OUTLINES: std::cell::Cell = const { std::cell::Cell::new(0) }; + static DECORATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +pub(crate) fn count_ink_outline() { + INK_OUTLINES.with(|n| n.set(n.get() + 1)); +} + +pub(crate) fn count_decorations() { + DECORATIONS.with(|n| n.set(n.get() + 1)); +} + +pub fn ink_work_on_this_thread() -> (u64, u64) { + (INK_OUTLINES.with(std::cell::Cell::get), DECORATIONS.with(std::cell::Cell::get)) } pub(crate) fn count_layout() { diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index a26f5f7a28..98f4061064 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -68,11 +68,11 @@ pub fn menu() -> Vec { ] } -static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None }; -static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None }; -static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None }; -static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None }; -static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None }; +static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None, pin_opening_artboard: false }; +static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None, pin_opening_artboard: false }; +static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None, pin_opening_artboard: false }; +static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None, pin_opening_artboard: false }; +static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None, pin_opening_artboard: false }; /// The dialog over `rows`, titled by the heading of `command`. fn dialog<'a>(command: &str, rows: Vec) -> ParamDialog<'a> { diff --git a/crates/ui-egui/src/addons/color/legend.rs b/crates/ui-egui/src/addons/color/legend.rs index 31fa3a5011..9badbd1a8a 100644 --- a/crates/ui-egui/src/addons/color/legend.rs +++ b/crates/ui-egui/src/addons/color/legend.rs @@ -17,7 +17,7 @@ pub const COMMAND: &str = "addon.color.swatchLegend"; pub const VALUES: [(&str, &str); 5] = [("hex", "HEX"), ("rgb", "RGB"), ("cmyk", "CMYK"), ("lab", "Lab"), ("gray", "Grayscale")]; /// How the dialog's values reach the command. -pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; +pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false }; /// The command's params from the dialog's fields. pub(crate) fn params(fields: &DialogFields) -> Value { diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 09b8fe4efe..dd6565701a 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -27,6 +27,7 @@ pub(crate) struct Spec { pub params: fn(&DialogFields) -> Value, /// Receives the answer of each preview run (or its error), to show it in the dialog. pub found: Option, + pub pin_opening_artboard: bool, } /// The add-on dialog open now and the live preview it drives; one at a time, since a preview owns the document. @@ -34,6 +35,8 @@ pub(crate) struct Spec { pub(crate) struct AddonDialogs { open: Option, preview: LivePreview, + /// Preview and OK are running with the dialog's opening artboard. + pub(crate) using_opening_artboard: bool, /// The open Tangent Circle Tool radius dialog. pub(crate) tangent_radius: Option, } @@ -44,6 +47,8 @@ struct Open { spec: &'static Spec, /// The opening document's uid and revert count: File › Revert keeps the uid but replaces the drawing. document: Option<(u64, u64)>, + /// The view's active artboard when the dialog opened. + artboard: Option, } impl Open { @@ -62,6 +67,40 @@ fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> { app.session.active().map(|state| (state.uid, state.reverts)) } +/// Runs the open dialog's command with its opening artboard, then restores the saved artboard. +pub(crate) fn with_opening_artboard(app: &mut VectorcraftApp, command: &str, run: impl FnOnce(&mut VectorcraftApp) -> T) -> T { + let saved = + app.addon_dialogs.open.filter(|open| open.spec.pin_opening_artboard && open.spec.command == command && open.on_document(app)).and_then( + |open| { + let state = app.session.active_mut()?; + let saved = (state.uid, state.active_artboard); + state.active_artboard = open.artboard; + Some(saved) + }, + ); + let using_opening_artboard = app.addon_dialogs.using_opening_artboard; + if saved.is_some() { + app.addon_dialogs.using_opening_artboard = true; + } + let answer = run(app); + app.addon_dialogs.using_opening_artboard = using_opening_artboard; + if let Some((uid, artboard)) = saved + && let Some(state) = app.session.document_mut(uid) + { + state.active_artboard = artboard; + } + answer +} + +pub(crate) fn artboard_deletion_guard(app: &VectorcraftApp) -> Option { + let open = app.addon_dialogs.open.filter(|open| open.spec.pin_opening_artboard)?; + Some(vectorcraft_engine::ArtboardDeletionGuard { + document: open.document?, + artboard: open.artboard?, + message: tl!("Close Create Font Sheet before deleting its opening artboard.").to_owned(), + }) +} + /// Closes the open add-on dialog without an answer and rolls its preview back. fn close_open(app: &mut VectorcraftApp) { let Some(open) = app.addon_dialogs.open.take() else { return }; @@ -102,9 +141,11 @@ pub(crate) fn open_with( let dialog = if previewing { dialog } else { dialog.preview_off() }; let host = app.dialogs().ok_or("no window")?; close_open(app); + crate::io::remember_active_artboard(app); + let artboard = app.session.active().and_then(|state| state.active_artboard); let id = dialog.id(); host.with(|h| h.open(dialog)); - app.addon_dialogs.open = Some(Open { id, spec, document: active_document(app) }); + app.addon_dialogs.open = Some(Open { id, spec, document: active_document(app), artboard }); Ok(json!({ "dialog": spec.command })) } @@ -142,12 +183,22 @@ fn pump_commit(app: &mut VectorcraftApp) { let Some(host) = app.dialogs() else { return }; let Open { id, spec, .. } = open; let on_document = open.on_document(app); + let missing_artboard = spec.pin_opening_artboard + && on_document + && open.artboard.is_some_and(|id| app.session.active().is_some_and(|state| !state.doc.artboards.iter().any(|artboard| artboard.id == id))); if !on_document { // Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing. app.addon_dialogs.preview = LivePreview::default(); } let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); - if on_document && let Some((previewing, params)) = &live { + if missing_artboard { + mem::take(&mut app.addon_dialogs.preview).cancel(app); + app.status(tl!("The opening artboard was deleted. Reopen this dialog to continue.")); + } + if on_document + && !missing_artboard + && let Some((previewing, params)) = &live + { let mut preview = mem::take(&mut app.addon_dialogs.preview); let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); let answer = preview.run(app, *previewing, label, spec.command, params); @@ -162,16 +213,22 @@ fn pump_commit(app: &mut VectorcraftApp) { } match host.with(|h| h.take_by_id::(id)).map(DialogResult::ok) { Some(Some(result)) => { - app.addon_dialogs.open = None; let preview = mem::take(&mut app.addon_dialogs.preview); // The dialog is closed already, so a refusal can only go to the status line. if open.reverted(app) { - app.status("The document was reverted. Reopen this dialog to continue."); + app.status(tl!("The document was reverted. Reopen this dialog to continue.")); } else if !on_document { - app.status("The add-on settings apply only to the drawing where the dialog opened."); - } else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) { - app.status(error); + app.status(tl!("The add-on settings apply only to the drawing where the dialog opened.")); + } else if missing_artboard { + preview.cancel(app); + app.status(tl!("The opening artboard was deleted. Reopen this dialog to continue.")); + } else { + let answer = preview.commit(app, spec.command, (spec.params)(&result.fields)); + if let Err(error) = answer { + app.status(error); + } } + app.addon_dialogs.open = None; } Some(None) => { app.addon_dialogs.open = None; diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs index 76b3627f76..e3da637953 100644 --- a/crates/ui-egui/src/addons/pathtools/bridge.rs +++ b/crates/ui-egui/src/addons/pathtools/bridge.rs @@ -25,7 +25,7 @@ const REACHES: std::ops::RangeInclusive = 0.0..=10000.0; const REACH: f64 = 10.0; /// How the dialog's values reach the command. -pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; +pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false }; /// The command's parameters from the dialog's fields: the radius, or with Constant Gap the gap. fn params(fields: &DialogFields) -> Value { diff --git a/crates/ui-egui/src/addons/pathtools/dashes.rs b/crates/ui-egui/src/addons/pathtools/dashes.rs index 48432a81e6..ca266f7139 100644 --- a/crates/ui-egui/src/addons/pathtools/dashes.rs +++ b/crates/ui-egui/src/addons/pathtools/dashes.rs @@ -16,7 +16,7 @@ const DASHES: std::ops::RangeInclusive = 0.01..=1e6; const GAPS: std::ops::RangeInclusive = 0.0..=1e6; /// How the dialog's values reach the command. -pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; +pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false }; /// The command's parameters from the dialog's fields. pub(crate) fn params(fields: &DialogFields) -> Value { diff --git a/crates/ui-egui/src/addons/pathtools/set_corners.rs b/crates/ui-egui/src/addons/pathtools/set_corners.rs index 50233b0908..dc631f0afe 100644 --- a/crates/ui-egui/src/addons/pathtools/set_corners.rs +++ b/crates/ui-egui/src/addons/pathtools/set_corners.rs @@ -23,7 +23,7 @@ const EVERY: [(&str, &str); 3] = [("all", "All Anchors"), ("odd", "Odd-Numbered const ANGLES: std::ops::RangeInclusive = 0.0..=180.0; /// How the dialog's values reach the command. -pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; +pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false }; /// The command's parameters from the dialog's fields. pub(crate) fn params(fields: &DialogFields) -> Value { diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle.rs index c890e063da..743672324a 100644 --- a/crates/ui-egui/src/addons/pathtools/tangent_circle.rs +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle.rs @@ -20,7 +20,7 @@ const MAX_CIRCLES: u64 = 64; const RADIUS: f64 = 36.0; /// How the dialog's values reach the command; the preview's answer says how many circles were found. -pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: Some(found) }; +pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: Some(found), pin_opening_artboard: false }; /// The circle number the choice holds (an option id): 0 is every circle, `k` the k-th, counted from 1. fn circle(fields: &DialogFields) -> u64 { diff --git a/crates/ui-egui/src/addons/typetools.rs b/crates/ui-egui/src/addons/typetools.rs index 790d4e661c..32ba39d4a2 100644 --- a/crates/ui-egui/src/addons/typetools.rs +++ b/crates/ui-egui/src/addons/typetools.rs @@ -55,7 +55,7 @@ fn attribute(key: &str) -> &'static Attribute { } /// How the dialog's values reach the command. -pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; +pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false }; /// The command's parameters from the dialog's fields; an end of the ramp not set yet is the attribute's own. pub(crate) fn params(fields: &DialogFields) -> Value { diff --git a/crates/ui-egui/src/addons/typetools/font_sheet.rs b/crates/ui-egui/src/addons/typetools/font_sheet.rs index 3d92a96f1b..987adbdc75 100644 --- a/crates/ui-egui/src/addons/typetools/font_sheet.rs +++ b/crates/ui-egui/src/addons/typetools/font_sheet.rs @@ -18,7 +18,7 @@ pub const COMMAND: &str = "addon.type.fontSheet"; const SAMPLE: &str = "The quick brown fox jumps over the lazy dog"; /// How the dialog's values reach the command. -pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; +pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: true }; /// The command's parameters from the dialog's fields; an empty filter sets every family. pub(crate) fn params(fields: &DialogFields) -> Value { diff --git a/crates/ui-egui/src/addons/typetools/font_sheet/tests.rs b/crates/ui-egui/src/addons/typetools/font_sheet/tests.rs index 4891cea545..76eaf6193b 100644 --- a/crates/ui-egui/src/addons/typetools/font_sheet/tests.rs +++ b/crates/ui-egui/src/addons/typetools/font_sheet/tests.rs @@ -85,6 +85,337 @@ fn keyboard_and_checkbox_edits_reach_font_sheet_preview_ok_and_cancel() { } } +/// Asserts that every entry of the selected font sheet starts on artboard `index`. +fn assert_on_artboard(app: &VectorcraftApp, index: usize, case: &str) { + let board = app.session.active().unwrap().doc.artboards[index].rect; + let entries = sheet(app); + assert!(!entries.is_empty(), "{case}"); + for entry in &entries { + let [.., x, _] = entry.xf.as_coeffs(); + assert!(x >= board.x0 && x <= board.x1, "{case}: entry at {x} lies outside artboard {index} {board:?}"); + } +} + +/// Preview and OK with Preview off use the artboard picked in the view before the dialog opens. +#[test] +fn font_sheet_preview_and_ok_use_the_views_current_artboard() { + for preview in [false, true] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap(); + app.sync_views(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + panel.app().view_mut().unwrap().artboard = 1; + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + panel.click_role("Font Names Containing", Role::TEXT_INPUT); + panel.type_text("Source Serif 4"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.app().view_mut().unwrap().artboard = 0; + if preview { + panel.click_role("Preview", Role::CHECK_BOX); + panel.frame(); + assert!(panel.app().session.in_interaction()); + assert_on_artboard(&panel.app(), 1, "the preview on the opening artboard"); + } + panel.click("OK"); + assert_on_artboard(&panel.app(), 1, if preview { "OK after Preview" } else { "OK with Preview off" }); + } +} + +#[test] +fn deleting_the_opening_artboard_refuses_font_sheet_preview_and_ok() { + for preview in [false, true] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap(); + app.sync_views(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + panel.app().view_mut().unwrap().artboard = 1; + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + panel.click_role("Font Names Containing", Role::TEXT_INPUT); + panel.type_text("Source Serif 4"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.app().session.execute("artboard.delete", &json!({"index": 1})).unwrap(); + let before = panel.app().session.active().unwrap().doc.clone(); + let undo = panel.app().session.active().unwrap().history.undo.len(); + if preview { + panel.click_role("Preview", Role::CHECK_BOX); + panel.frame(); + assert!(!panel.app().session.in_interaction()); + assert_eq!(panel.app().session.active().unwrap().doc, before); + assert_eq!(panel.app().ui.status, "The opening artboard was deleted. Reopen this dialog to continue."); + assert_eq!(panel.app().ui.status, tl!("The opening artboard was deleted. Reopen this dialog to continue.")); + } + panel.click("OK"); + assert_eq!(panel.app().session.active().unwrap().doc, before, "OK creates no sheet entries after the opening artboard is deleted"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + assert!(!panel.app().session.in_interaction()); + assert_eq!(panel.app().ui.status, "The opening artboard was deleted. Reopen this dialog to continue."); + assert_eq!(panel.app().ui.status, tl!("The opening artboard was deleted. Reopen this dialog to continue.")); + assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty()); + } +} + +#[test] +fn deleting_the_opening_artboard_is_refused_before_it_changes_a_font_sheet_preview() { + for preview in [false, true] { + for commit in [false, true] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400, "artboards": 3})).unwrap(); + app.sync_views(); + let original = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + panel.app().view_mut().unwrap().artboard = 1; + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + panel.click_role("Font Names Containing", Role::TEXT_INPUT); + panel.type_text("Source Serif 4"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + if preview { + panel.click_role("Preview", Role::CHECK_BOX); + } + let before = panel.app().session.active().unwrap().doc.clone(); + let selection = panel.app().session.active().unwrap().selection.clone(); + for params in [json!({"index": 1}), json!({"indices": [2, 1, 1]})] { + let (request, _) = craft::automation::ControlRequest::new("engine.execute", json!({"command": "artboard.delete", "params": params})); + let craft::automation::Reply::Done(answer) = crate::control::handle(&mut panel.app(), &egui::Context::default(), &request) else { + panic!("the deletion did not finish"); + }; + assert_eq!(answer["ok"], false, "{answer}"); + assert!(answer.to_string().contains(tl!("Close Create Font Sheet before deleting its opening artboard.")), "{answer}"); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().doc, before); + assert_eq!(panel.app().session.active().unwrap().selection, selection); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + assert_eq!(panel.app().session.in_interaction(), preview); + assert!(panel.app().session.artboard_deletion_guard.is_none()); + } + panel.click(if commit { "OK" } else { "Cancel" }); + assert!(!panel.app().session.in_interaction()); + if commit { + assert_on_artboard(&panel.app(), 1, "OK after a refused deletion"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + } + assert_eq!(panel.app().session.active().unwrap().doc, original); + panel.app().run("artboard.delete", json!({"index": 1})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc.artboards.len(), 2); + } + } +} + +#[test] +fn a_batch_cannot_delete_the_font_sheet_dialogs_opening_artboard() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400, "artboards": 3})).unwrap(); + app.sync_views(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + panel.app().view_mut().unwrap().artboard = 1; + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + let before = panel.app().session.active().unwrap().doc.clone(); + let undo = panel.app().session.active().unwrap().history.undo.len(); + let error = panel + .app() + .run( + "command.batch", + json!({"commands": [ + {"command": "artboard.delete", "params": {"index": 0}}, + {"command": "artboard.delete", "params": {"index": 0}} + ]}), + ) + .unwrap_err(); + assert!(error.contains(tl!("Close Create Font Sheet before deleting its opening artboard.")), "{error}"); + assert_eq!(panel.app().session.active().unwrap().doc, before, "the earlier deletion is rolled back"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + assert!(panel.app().session.artboard_deletion_guard.is_none()); + panel.click("Cancel"); + assert_eq!(panel.app().session.active().unwrap().doc, before); +} + +#[test] +fn font_sheet_allows_deleting_another_artboard() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400, "artboards": 3})).unwrap(); + app.sync_views(); + let opening = app.session.active().unwrap().doc.artboards[1].id; + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + panel.app().view_mut().unwrap().artboard = 1; + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + panel.app().run("artboard.delete", json!({"index": 0})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc.artboards[0].id, opening); + assert!(panel.app().run("artboard.delete", json!({"index": 0})).is_err(), "the protection follows the artboard ID"); + let before = panel.app().session.active().unwrap().doc.clone(); + panel.click("Cancel"); + assert_eq!(panel.app().session.active().unwrap().doc, before); +} + +#[test] +fn another_addon_uses_the_current_artboard_and_survives_deleting_its_opening_artboard() { + use crate::addons::dialogs::tests as host; + + for commit in [false, true] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.sync_views(); + let current = app.session.active().unwrap().doc.artboards[0].id; + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + panel.app().view_mut().unwrap().artboard = 1; + let command = "addon.arrange.randomizeOpacity"; + crate::menus::invoke(&mut panel.app(), command, json!({})); + panel.frame(); + panel.click_role("Preview", Role::CHECK_BOX); + panel.app().view_mut().unwrap().artboard = 0; + crate::io::remember_active_artboard(&mut panel.app()); + let active = crate::addons::dialogs::with_opening_artboard(&mut panel.app(), command, |app| app.session.active().unwrap().active_artboard); + assert_eq!(active, Some(current), "the other dialog does not pin the opening artboard"); + panel.app().run("artboard.delete", json!({"index": 1})).unwrap(); + let before = panel.app().session.active().unwrap().doc.clone(); + let undo = panel.app().session.active().unwrap().history.undo.len(); + let dialog = host::dialog_id(&panel.app()); + host::set(&panel.app(), dialog, "min", json!(37)); + host::set(&panel.app(), dialog, "max", json!(37)); + panel.click_role("Preview", Role::CHECK_BOX); + panel.frame(); + assert!(panel.app().session.in_interaction()); + assert!((panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().opacity - 0.37).abs() < 1e-6); + panel.click(if commit { "OK" } else { "Cancel" }); + assert!(!panel.app().session.in_interaction()); + assert_eq!(panel.app().session.active().unwrap().doc.artboards.len(), 1); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + usize::from(commit)); + if commit { + assert!((panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().opacity - 0.37).abs() < 1e-6); + } else { + assert_eq!(panel.app().session.active().unwrap().doc, before); + } + } +} + +#[test] +fn font_sheet_frames_restore_the_active_artboard_after_preview_and_commit() { + for commit in [false, true] { + for preview_at_close in [false, true] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap(); + app.sync_views(); + let current = app.session.active().unwrap().doc.artboards[0].id; + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + panel.app().view_mut().unwrap().artboard = 1; + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + panel.click_role("Font Names Containing", Role::TEXT_INPUT); + panel.type_text("Source Serif 4"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.app().view_mut().unwrap().artboard = 0; + crate::io::remember_active_artboard(&mut panel.app()); + for _ in 0..2 { + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current), "Preview off preserves the active artboard"); + } + for preview in [true, false, true, false] { + panel.click_role("Preview", Role::CHECK_BOX); + assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current), "toggling Preview preserves the active artboard"); + for _ in 0..2 { + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current), "idle frames preserve the active artboard"); + } + assert_eq!(panel.app().session.in_interaction(), preview); + if preview { + assert_on_artboard(&panel.app(), 1, "Preview uses the opening artboard"); + } + } + if preview_at_close { + panel.click_role("Preview", Role::CHECK_BOX); + assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current)); + } + panel.click(if commit { "OK" } else { "Cancel" }); + assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current), "closing the dialog preserves the active artboard"); + assert!(!panel.app().session.in_interaction()); + if commit { + assert_on_artboard(&panel.app(), 1, "OK uses the opening artboard"); + } + } + } +} + +#[test] +fn a_standalone_font_sheet_uses_the_current_artboard_with_its_dialog_open() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap(); + app.sync_views(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + panel.app().view_mut().unwrap().artboard = 1; + let (request, _) = craft::automation::ControlRequest::new( + "engine.execute", + json!({"command": super::COMMAND, "params": {"families": ["Inter"], "labels": false}}), + ); + let craft::automation::Reply::Done(answer) = crate::control::handle(&mut panel.app(), &egui::Context::default(), &request) else { + panic!("the font sheet command did not finish"); + }; + assert_eq!(answer["ok"], true, "{answer}"); + assert_on_artboard(&panel.app(), 1, "a standalone command while Preview is off"); + panel.click("Cancel"); + assert_on_artboard(&panel.app(), 1, "Cancel keeps the standalone sheet"); +} + +/// The sheet stays on its opening artboard when a preview removes the page shown in the view. +#[test] +fn going_to_a_page_the_font_sheet_preview_added_keeps_its_start() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap(); + app.sync_views(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + let original_artboards = panel.app().session.active().unwrap().doc.artboards.len(); + // Each page holds one 100 pt entry. + let edits = [("Font Names Containing", Role::TEXT_INPUT, "Source S"), ("Size", Role::SPIN_BUTTON, "100"), ("Columns", Role::SPIN_BUTTON, "1")]; + for (label, role, input) in edits { + panel.click_role(label, role); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(input); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + } + panel.click_role("Preview", Role::CHECK_BOX); + panel.frame(); + assert!(panel.app().session.active().unwrap().doc.artboards.len() > original_artboards, "the preview adds a page"); + panel.app().view_mut().unwrap().artboard = original_artboards; + panel.frame(); + let first_on_opening_artboard = |panel: &Panel| { + let app = panel.app(); + let [.., x, _] = sheet(&app)[0].xf.as_coeffs(); + let board = app.session.active().unwrap().doc.artboards[0].rect; + assert!(x >= board.x0 && x <= board.x1, "the first entry stays on the opening artboard: {x}, {board:?}"); + }; + first_on_opening_artboard(&panel); + panel.click_role("Add Artboards When Full", Role::CHECK_BOX); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().doc.artboards.len(), original_artboards); + panel.app().sync_views(); + assert_eq!(panel.app().view().unwrap().artboard, original_artboards - 1, "the view clamps to the last original artboard"); + panel.frame(); + first_on_opening_artboard(&panel); + panel.click_role("Preview", Role::CHECK_BOX); + panel.frame(); + assert!(!panel.app().session.in_interaction()); + panel.click("OK"); + first_on_opening_artboard(&panel); +} + /// An empty filter sends none, so the sheet sets every family; a filter is sent trimmed. #[test] fn params_sends_a_filter_only_when_one_is_typed() { diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index b7ff421414..e6b526f441 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -88,7 +88,10 @@ impl VectorcraftApp { let touch_workspace = self.session.prefs.touch_workspace; // A `prefs.reset` that ran straight on the session applies before this command can switch workspaces. crate::prefs_dialog::apply_prefs_resets(self); + let guard = crate::addons::dialogs::artboard_deletion_guard(self); + let previous_guard = std::mem::replace(&mut self.session.artboard_deletion_guard, guard); let result = self.run_now(id, params); + self.session.artboard_deletion_guard = previous_guard; crate::prefs_dialog::apply_prefs_resets(self); if id == "prefs.import" && result.is_ok() { crate::prefs_dialog::imported(self, touch_workspace); @@ -157,7 +160,9 @@ impl VectorcraftApp { self.wait_for_tool_edit(id); // A `.ai` file a command writes (a save, an export, a timestamped copy, a batch's save) names // the view's active artboard. - io::remember_active_artboard(self); + if !self.addon_dialogs.using_opening_artboard { + io::remember_active_artboard(self); + } let artboards = self.artboard_tool_state(); if let Some(r) = menus::run_ui_command(self, id, ¶ms) { self.ui.recording_base = None; diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index 2e029fc1c6..79654f4c92 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -76,7 +76,7 @@ impl LivePreview { app.status(e); return None; } - let answer = match app.session.preview(cmd, params) { + let answer = match crate::addons::dialogs::with_opening_artboard(app, cmd, |app| app.session.preview(cmd, params)) { Ok(v) => Ok(v), Err(e) => { app.status(e.to_string()); @@ -105,9 +105,9 @@ impl LivePreview { if app.session.in_interaction() { return Err(tl!("Finish the active edit first.").to_owned()); } - return app.run(cmd, params); + return crate::addons::dialogs::with_opening_artboard(app, cmd, |app| app.run(cmd, params)); } - let result = app.session.preview(cmd, ¶ms).and_then(|answer| { + let result = crate::addons::dialogs::with_opening_artboard(app, cmd, |app| app.session.preview(cmd, ¶ms)).and_then(|answer| { app.session.commit_interaction()?; Ok(answer) }); diff --git a/docs/mcp.md b/docs/mcp.md index fde01f0426..dee1f80313 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17995,10 +17995,14 @@ the fonts can be compared on the artboard or printed. 612 × 792 pt page at the origin and adds no artboards. - **Fonts that don't load:** a family whose font can't be loaded (text in it would be drawn in the fallback font), or with `allStyles` a style that can't (it would be drawn in the family's closest style), is left out, listed in - `skipped` and named in `warning`, which the status bar shows. -- The sheet is one group named Font Sheet, in the current layer, made in one undo step and selected. Nothing changes, - and an error is returned, when no family matches, when there would be more than 5000 entries, when no font loads, - when the margin, gap and columns leave no room for one entry, or when the current layer is locked or hidden. + `skipped` and named in `warning`, which the status bar shows. A composite font is left out the same way when a part + that sets the sample text names a font or style that can't be loaded. +- Each row is as tall as the tallest laid-out entry needs, so a composite font whose part enlarges or raises the + sample does not overlap the entry above it or reach into the margin. +- The sheet is one group named Font Sheet, made in one undo step and selected. It goes where new art goes: the current + layer, or, when that layer is locked or hidden, the topmost layer that is shown and unlocked. Nothing changes, and an + error is returned, when no family matches, when there would be more than 5000 entries, when no font loads, when the + margin, gap and columns leave no room for one entry, or when no layer is shown and unlocked. | Parameter | Values (default) | |---|---| diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cadb5b2c33..0e11ab4886 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3168,7 +3168,7 @@ A VectorCraft addition, not a feature of the reference app (it has no command fo ## Type Tools add-on: Create Font Sheet (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name, as point type flowed down columns on the active artboard and on new artboards of the same size to its right when the artboard is full. Every Style gives each style of a family its own entry; families whose font can't be loaded are left out and listed. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`). Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name, as point type flowed down columns on the active artboard and on new artboards of the same size to its right when the artboard is full. Every Style gives each style of a family its own entry; families whose font can't be loaded, and composite fonts whose part setting the sample can't, are left out and listed. Each row is as tall as the tallest laid-out entry, so a composite font that enlarges the sample does not overlap. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`); its preview and OK set the sheet on the artboard active in the view when it opens. Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, composite fonts' row heights and missing parts, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` (including the artboard active when the dialog opens) and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet. ## Unit Converter add-on (2026-11-14) From e58c1f2a07935064fe57e9cd5b29b0572a042e63 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:07:02 -0800 Subject: [PATCH 04/56] Type Tools: Create Font Sheet's artboard guard covers every artboard deletion Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards now return the guard's error, with nothing changed, when they would delete the artboard an open Create Font Sheet dialog uses, as Delete Artboard already did. `families` with any `filter`, an empty one included, is an error. docs/mcp.md says that `null` is the same as an omitted parameter for `addon.type.fontSheet`, and the progress line says labels are optional. --- crates/engine/src/cmd/addons/cleanup.rs | 9 ++++++- .../src/cmd/addons/typetools/font_sheet.rs | 4 +-- .../cmd/addons/typetools/font_sheet/tests.rs | 26 +++++++++++++++++++ crates/engine/src/cmd/layer.rs | 25 ++++++++++++------ crates/engine/src/cmd/panelcmds.rs | 3 ++- docs/mcp.md | 11 ++++++-- docs/target-app-parity.md | 2 +- 7 files changed, 65 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/addons/cleanup.rs b/crates/engine/src/cmd/addons/cleanup.rs index d5f241b4ee..9050f07479 100644 --- a/crates/engine/src/cmd/addons/cleanup.rs +++ b/crates/engine/src/cmd/addons/cleanup.rs @@ -64,7 +64,7 @@ pub fn specs() -> Vec { "Fix All Issues", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents → {scope, total, fixed: {kind: count}}", + "{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents. An error, with nothing fixed, when the fixes would delete the artboard an open Create Font Sheet dialog uses → {scope, total, fixed: {kind: count}}", has_doc, fix ), @@ -260,6 +260,13 @@ fn fix(s: &mut Session, p: &Value) -> Result { } // With nothing to fix, the document and its undo history stay as they are. if total > 0 { + if let Some(guard) = &s.artboard_deletion_guard { + let st = s.doc()?; + let protected = |doc: &Document| doc.artboards.iter().any(|a| a.id == guard.artboard); + if (st.uid, st.reverts) == guard.document && protected(&st.doc) && !protected(&d) { + return Err(EngineError::Other(guard.message.clone())); + } + } sel.prune(&d); s.edit("Fix Issues", |doc, selection| { *doc = d; diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet.rs b/crates/engine/src/cmd/addons/typetools/font_sheet.rs index 9d71c86610..14c4f46edf 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Create Font Sheet", ["Object", "Plug-ins", "Type Tools"], None, - "{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, flowed down the columns of the active artboard (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}", + "{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once; an error with any filter, an empty one included), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, flowed down the columns of the active artboard (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}", has_doc, font_sheet )] @@ -91,7 +91,7 @@ fn families(p: &Value, db: &FontDb) -> Result> { } return Ok(found); } - Some(_) if filter.is_some() => return Err(bad(COMMAND, "give `families` or `filter`, not both")), + Some(_) if p.get("filter").is_some_and(|f| !f.is_null()) => return Err(bad(COMMAND, "give `families` or `filter`, not both")), Some(Value::Array(a)) => a, Some(_) => return Err(bad(COMMAND, "`families` must be a list of font family names")), }; diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs index 1095b4428c..5119d6c339 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs @@ -168,6 +168,8 @@ fn bad_params_are_refused_without_a_change() { json!({"families": ["No Such Family Anywhere"]}), json!({"families": [""]}), json!({"families": ["Inter"], "filter": "Inter"}), + json!({"families": ["Inter"], "filter": ""}), + json!({"families": ["Inter"], "filter": " "}), json!({"labels": "yes"}), json!({"allStyles": 1}), json!({"newArtboards": "no"}), @@ -375,6 +377,30 @@ fn an_artboard_deletion_guard_checks_the_document_and_artboard_ids() { assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "a reverted drawing is not protected"); } +/// Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards keep the guarded artboard too. +#[test] +fn an_artboard_deletion_guard_covers_every_command_that_deletes_artboards() { + let mut s = Session::new(); + s.execute("file.new", &json!({"artboards": 3})).unwrap(); + let state = s.doc().unwrap(); + let document = (state.uid, state.reverts); + let artboard = state.doc.artboards[1].id; + s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() }); + let before = (s.doc().unwrap().doc.clone(), steps(&s)); + for (command, params) in [ + ("artboard.cut", json!({"index": 1})), + ("artboard.deleteEmpty", json!({})), + ("addon.cleanup.fix", json!({"kinds": ["emptyArtboards"], "scope": "document"})), + ] { + let error = s.execute(command, ¶ms).unwrap_err(); + assert_eq!(error.to_string(), "The artboard is in use.", "{command}"); + assert_eq!(s.doc().unwrap().doc, before.0, "{command}"); + assert_eq!(steps(&s), before.1, "{command}"); + } + s.execute("artboard.cut", &json!({"index": 2})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2, "another artboard is cut"); +} + #[test] fn it_needs_a_document() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 9528bb6c86..19c1358c2a 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -147,7 +147,7 @@ pub fn specs() -> Vec { "Delete Artboard", ["Window", "Artboards"], None, - "{index | indices: [index…]} delete artboards (with their guides) in one step; one is always left, and a locked one is an error", + "{index | indices: [index…]} delete artboards (with their guides) in one step; one is always left, and a locked one, or the one an open Create Font Sheet dialog uses, is an error", has_doc, artboard_delete ), @@ -156,7 +156,7 @@ pub fn specs() -> Vec { "Delete Empty Artboards", ["Window", "Artboards"], None, - "{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go) → {deleted: [index…]} (the indices before deleting)", + "{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go); an error, with nothing deleted, when one of them is the artboard an open Create Font Sheet dialog uses → {deleted: [index…]} (the indices before deleting)", has_empty_artboards, artboard_delete_empty ), @@ -1155,17 +1155,25 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result { fn artboard_delete(s: &mut Session, p: &Value) -> Result { let indices = super::panelcmds::artboard_indices(&s.doc()?.doc, p, "artboard.delete")?; - if let Some(guard) = &s.artboard_deletion_guard { - let state = s.doc()?; - if (state.uid, state.reverts) == guard.document && indices.iter().any(|&index| state.doc.artboards[index].id == guard.artboard) { - return Err(EngineError::Other(guard.message.clone())); - } - } + refuse_guarded(s, &indices)?; super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?; s.edit("Delete Artboard", |d, sel| remove_artboards(d, sel, &indices))?; ok() } +/// The session's artboard deletion guard's message when deleting artboards `indices` of the +/// active document would delete the artboard it protects. +pub(crate) fn refuse_guarded(s: &Session, indices: &[usize]) -> Result<()> { + let Some(guard) = &s.artboard_deletion_guard else { return Ok(()) }; + let state = s.doc()?; + if (state.uid, state.reverts) == guard.document + && indices.iter().any(|&index| state.doc.artboards.get(index).is_some_and(|a| a.id == guard.artboard)) + { + return Err(EngineError::Other(guard.message.clone())); + } + Ok(()) +} + /// Delete artboards `indices` (sorted, each once) of `d` with their guides; at least one must be /// left. The other artboards keep their order, no later artboard takes a deleted one's id, and /// `sel` forgets the deleted guides. One walk over the artboards and one over the ruler guides, @@ -1242,6 +1250,7 @@ fn artboard_delete_empty(s: &mut Session, _: &Value) -> Result { if indices.is_empty() { return Err(EngineError::Other("no empty artboards to delete".into())); } + refuse_guarded(s, &indices)?; s.edit("Delete Empty Artboards", |d, sel| remove_artboards(d, sel, &indices))?; Ok(json!({ "deleted": indices })) } diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 433c69202c..4ccd3529e2 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -38,7 +38,7 @@ pub fn specs() -> Vec { "Cut Artboard", [], None, - "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}", + "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, a locked one, or the one an open Create Font Sheet dialog uses; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}", has_doc, |s, p| { boards_and_art_noted(s, p, "artboard.cut")?; @@ -366,6 +366,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result Date: Mon, 30 Nov 2026 05:16:31 -0800 Subject: [PATCH 05/56] Type Tools: Create Font Sheet's artboard guard covers script slices A script run that the frames take to its end ran each slice with no artboard deletion guard, so a vc.run of artboard.delete in a later slice could delete the artboard an open Create Font Sheet dialog uses. The script poll now sets the guard around each pump and restores the previous one after it. The new test runs such a script in the frames and checks that the deletion is refused and the document is unchanged. --- .../src/addons/typetools/font_sheet/tests.rs | 29 +++++++++++++++++++ crates/ui-egui/src/script_runs.rs | 4 +++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/addons/typetools/font_sheet/tests.rs b/crates/ui-egui/src/addons/typetools/font_sheet/tests.rs index 76eaf6193b..5e998142a5 100644 --- a/crates/ui-egui/src/addons/typetools/font_sheet/tests.rs +++ b/crates/ui-egui/src/addons/typetools/font_sheet/tests.rs @@ -238,6 +238,35 @@ fn a_batch_cannot_delete_the_font_sheet_dialogs_opening_artboard() { assert_eq!(panel.app().session.active().unwrap().doc, before); } +#[test] +fn a_script_slice_cannot_delete_the_font_sheet_dialogs_opening_artboard() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap(); + app.sync_views(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + panel.app().view_mut().unwrap().artboard = 1; + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + let before = panel.app().session.active().unwrap().doc.clone(); + panel.app().session.script_frames = true; + let started = panel.app().run("script.run", json!({"source": "vc.run('artboard.delete', {index: 1});", "name": "t.js"})); + assert_eq!(started.map(|v| v["running"].clone()), Ok(json!(true)), "the run goes on in the frames"); + for _ in 0..1_000 { + if !panel.app().session.script_running() { + break; + } + crate::script_runs::poll(&mut panel.app()); + } + assert!(!panel.app().session.script_running()); + let status = panel.app().ui.status.clone(); + assert!(status.contains(tl!("Close Create Font Sheet before deleting its opening artboard.")), "{status}"); + assert_eq!(panel.app().session.active().unwrap().doc.artboards.len(), 2, "the opening artboard is kept"); + assert_eq!(panel.app().session.active().unwrap().doc, before); + assert!(panel.app().session.artboard_deletion_guard.is_none()); + panel.click("Cancel"); +} + #[test] fn font_sheet_allows_deleting_another_artboard() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index ee469adf18..e32165515c 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -28,7 +28,11 @@ pub fn poll(app: &mut VectorcraftApp) { let name = app.session.script_name().unwrap_or_default(); let startup = app.session.startup_script_running(); let shared = share_views(app); + // A slice may delete an artboard; the one an open Create Font Sheet dialog uses is refused. + let guard = crate::addons::dialogs::artboard_deletion_guard(app); + let previous_guard = std::mem::replace(&mut app.session.artboard_deletion_guard, guard); let pumped = app.session.script_pump(); + app.session.artboard_deletion_guard = previous_guard; take_views(app, &shared); let Some(result) = pumped else { // A pump that started the next queued run shows the runs before it that could not start diff --git a/docs/mcp.md b/docs/mcp.md index b54b1f1f53..29319fd62f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -18072,7 +18072,8 @@ the fonts can be compared on the artboard or printed. In `addon.type.fontSheet`, a parameter given as `null` is the same as one left out and takes its default; any other value of the wrong type or out of range is an error. While the Create Font Sheet… dialog is open, Delete Artboard, Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an error and change nothing when they -would delete the artboard the dialog opened on; close the dialog first. +would delete the artboard the dialog opened on, and so does a running script's `vc.run` of one of them (a script +that does not catch the error ends with it); close the dialog first. → `{id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}`. Create Font Sheet… opens a dialog (`ui.menuDialog {command}`) whose fields are the command's parameters except `families`, with Preview, which starts diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 029ab9d55b..08ca2761bc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3176,7 +3176,7 @@ A VectorCraft addition, not a feature of the reference app (it has no command fo ## Type Tools add-on: Create Font Sheet (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name unless labels are switched off, as point type flowed down columns on the active artboard and on new artboards of the same size to its right when the artboard is full. Every Style gives each style of a family its own entry; families whose font can't be loaded, and composite fonts whose part setting the sample can't, are left out and listed. Each row is as tall as the tallest laid-out entry, so a composite font that enlarges the sample does not overlap. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`); its preview and OK set the sheet on the artboard active in the view when it opens, and while it is open, Delete Artboard, Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an error when they would delete that artboard. Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, composite fonts' row heights and missing parts, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` (including the artboard active when the dialog opens) and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name unless labels are switched off, as point type flowed down columns on the active artboard and on new artboards of the same size to its right when the artboard is full. Every Style gives each style of a family its own entry; families whose font can't be loaded, and composite fonts whose part setting the sample can't, are left out and listed. Each row is as tall as the tallest laid-out entry, so a composite font that enlarges the sample does not overlap. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`); its preview and OK set the sheet on the artboard active in the view when it opens, and while it is open, Delete Artboard, Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an error when they would delete that artboard, also when a running script calls them through `vc.run`. Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, composite fonts' row heights and missing parts, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` (including the artboard active when the dialog opens) and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet. ## Unit Converter add-on (2026-11-14) From 3281477229c9da57d4cf4de89cde894fc62c05cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:08:53 -0800 Subject: [PATCH 06/56] Docs: Create Font Sheet adds artboards only with Add Artboards When Full on --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 08ca2761bc..d6c812d7d2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3176,7 +3176,7 @@ A VectorCraft addition, not a feature of the reference app (it has no command fo ## Type Tools add-on: Create Font Sheet (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name unless labels are switched off, as point type flowed down columns on the active artboard and on new artboards of the same size to its right when the artboard is full. Every Style gives each style of a family its own entry; families whose font can't be loaded, and composite fonts whose part setting the sample can't, are left out and listed. Each row is as tall as the tallest laid-out entry, so a composite font that enlarges the sample does not overlap. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`); its preview and OK set the sheet on the artboard active in the view when it opens, and while it is open, Delete Artboard, Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an error when they would delete that artboard, also when a running script calls them through `vc.run`. Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, composite fonts' row heights and missing parts, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` (including the artboard active when the dialog opens) and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name unless labels are switched off, as point type flowed down columns on the active artboard. When the artboard is full, Add Artboards When Full (on by default) adds new artboards of the same size to its right for the rest; with it off, the rest is laid out in the same places to the right without artboards. Every Style gives each style of a family its own entry; families whose font can't be loaded, and composite fonts whose part setting the sample can't, are left out and listed. Each row is as tall as the tallest laid-out entry, so a composite font that enlarges the sample does not overlap. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`); its preview and OK set the sheet on the artboard active in the view when it opens, and while it is open, Delete Artboard, Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an error when they would delete that artboard, also when a running script calls them through `vc.run`. Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, composite fonts' row heights and missing parts, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` (including the artboard active when the dialog opens) and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet. ## Unit Converter add-on (2026-11-14) From f80c7d33ac62a9e37956fdd675fa99af1eaf49da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:39:51 -0800 Subject: [PATCH 07/56] Type: test that a locked current layer sends Create Font Sheet to the topmost editable layer --- .../src/cmd/addons/typetools/font_sheet/tests.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs index 5119d6c339..a64d79c7a2 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs @@ -416,3 +416,17 @@ fn a_locked_layer_takes_no_sheet() { assert!(s.execute(COMMAND, &json!({"families": ["Inter"]})).is_err()); assert_eq!(steps(&s), before); } + +#[test] +fn a_locked_current_layer_sends_the_sheet_to_the_topmost_editable_layer() { + let mut s = session(); + let editable = s.doc().unwrap().doc.layers[0].id; + let locked = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap(); + let gid = NodeId(r["id"].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + let holds = |layer: NodeId| doc.children(Some(layer)).is_some_and(|c| c.iter().any(|n| n.id == gid)); + assert!(holds(editable), "the sheet goes to the layer that is shown and unlocked"); + assert!(!holds(locked)); +} From 8a808afc6fd7f84db77848972701781f019c20cc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 12:22:29 -0800 Subject: [PATCH 08/56] Type: Create Font Sheet aligns right-to-left samples left and journals its artboard Right-to-left samples used the automatic alignment, which anchors them at their right edge, so a sample started left of its column and could cross the margin or the column before it. Every line is now aligned left. The command now takes `artboard`, and when it is left out the journal records the active artboard as `activeArtboard`, so a replay lays the sheet out on the same artboard. An action leaves `activeArtboard` out. --- .../src/cmd/addons/typetools/font_sheet.rs | 21 ++++++-- .../cmd/addons/typetools/font_sheet/tests.rs | 52 +++++++++++++++++++ crates/engine/src/command_sets.rs | 3 +- docs/mcp.md | 9 ++-- docs/target-app-parity.md | 2 +- 5 files changed, 79 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet.rs b/crates/engine/src/cmd/addons/typetools/font_sheet.rs index 14c4f46edf..46ae534764 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet.rs @@ -11,6 +11,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Shape}; use vectorcraft_text::{FontDb, FontMatch}; use super::super::super::create::{new_type_para, new_type_style}; +use super::super::super::panelcmds::artboard_at; use super::super::super::typecmd::refresh_bounds; use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; use crate::{Result, Session}; @@ -36,7 +37,7 @@ pub fn specs() -> Vec { "Create Font Sheet", ["Object", "Plug-ins", "Type Tools"], None, - "{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once; an error with any filter, an empty one included), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, flowed down the columns of the active artboard (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}", + "{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once; an error with any filter, an empty one included), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards), artboard?: n (0-based; the artboard the first page is; default: the active one), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, every line aligned left (right-to-left samples too), flowed down the columns of the active artboard, or artboard `artboard` (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}", has_doc, font_sheet )] @@ -160,9 +161,22 @@ fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { } let label = size.min(LABEL_SIZE); + // The artboard named, else `activeArtboard` (a replay of the journal), else the view's active + // one, which the journal entry then records as `activeArtboard` so a replay uses the same artboard. + let named = artboard_at(&s.doc()?.doc, p, "artboard", C)?; + let active = match named.or(artboard_at(&s.doc()?.doc, p, "activeArtboard", C)?) { + Some(i) => i, + None => { + let st = s.doc()?; + let i = active_artboard(st); + if i < st.doc.artboards.len() { + s.note_journal("activeArtboard", json!(i)); + } + i + } + }; let st = s.doc()?; let d = &st.doc; - let active = active_artboard(st); let template = d.artboards.get(active).cloned(); let page = template.as_ref().map_or(LETTER, |a| a.rect); let right = d.artboards.iter().map(|a| a.rect.x1).fold(page.x1, f64::max); @@ -286,7 +300,8 @@ fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { fn laid_out(first: TextRun, more: Option, system_layout: bool) -> TextObject { let mut t = TextObject::point(Point::ZERO, "", first.style.clone()); t.runs = std::iter::once(first).chain(more).collect(); - t.para = new_type_para(); + // Every paragraph is aligned left, right-to-left ones too, so each starts at the column's edge. + t.para = vectorcraft_doc::ParaStyle { justify: vectorcraft_doc::Justify::Left, ..new_type_para() }; t.system_layout = system_layout; t.normalize_paras(); let layout = vectorcraft_text::layout(FontDb::global(), &t); diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs index a64d79c7a2..e52a1e8ce0 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs @@ -139,6 +139,58 @@ fn columns_share_the_room_inside_the_margin() { assert_eq!(r["artboards"], json!([])); } +/// The journal records the active artboard, so a replay in a new session lays the sheet out on the +/// same one; an action leaves it out, and a named artboard goes ahead of it. +#[test] +fn the_journal_records_the_artboard_the_sheet_was_laid_out_on() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap(); + let second = s.doc().unwrap().doc.artboards[1].clone(); + s.doc_mut().unwrap().active_artboard = Some(second.id); + let start = s.journal.len(); + let params = json!({"families": ["Inter"], "margin": 10}); + let r = s.execute(COMMAND, ¶ms).unwrap(); + let e = entries(&group(&s, &r)); + assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "on the active artboard"); + let (id, recorded) = s.journal.last().unwrap().clone(); + assert_eq!((id.as_str(), &recorded["activeArtboard"]), (COMMAND, &json!(1))); + assert_eq!(s.journal_for_action(start)[0].1.get("activeArtboard"), None, "an action uses the artboard active when it plays"); + + // A replay in a session whose view has no active artboard uses the recorded one. + let mut fresh = session(); + fresh.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap(); + let r = fresh.replay(COMMAND, &recorded).unwrap(); + let e = entries(&group(&fresh, &r)); + assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "the replay lays it out on the recorded artboard"); + // A named artboard goes ahead of the recorded one. + let r = fresh.execute(COMMAND, &json!({"families": ["Inter"], "margin": 10, "artboard": 0, "activeArtboard": 1})).unwrap(); + let e = entries(&group(&fresh, &r)); + let first = fresh.doc().unwrap().doc.artboards[0].rect; + assert!((origin(&e[0].1).0 - first.x0 - 10.0).abs() < 1e-9); + assert!(fresh.execute(COMMAND, &json!({"families": ["Inter"], "artboard": 5})).is_err(), "no such artboard"); +} + +/// A right-to-left sample starts at its column's left edge like any other, so it stays inside its column. +#[test] +fn a_right_to_left_sample_stays_inside_its_column() { + let mut s = session(); + let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}"; + let board = s.doc().unwrap().doc.artboards[0].rect; + // Alone, and under a left-to-right label: each line starts at the column's left edge. + for labels in [false, true] { + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "labels": labels, "text": rtl})).unwrap(); + for (name, t) in &entries(&group(&s, &r)) { + let x = origin(t).0; + assert!((x - board.x0 - 50.0).abs() < 1e-9, "{name}: {x}"); + let layout = vectorcraft_text::layout(FontDb::global(), t); + for line in &layout.lines { + let left = x + line.x0; + assert!(left > board.x0 + 50.0 - 1e-6, "{name}, labels {labels}: a line starts at {left}, left of the column's edge"); + } + } + } +} + #[test] fn bad_params_are_refused_without_a_change() { let mut s = session(); diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 228d23a0f0..9b2b0ad033 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -37,7 +37,7 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 37] = [ +const REPLAY_ONLY: [(&str, &str); 38] = [ ("edit.copy", "artboard"), ("edit.cut", "artboard"), ("file.new", "created"), @@ -67,6 +67,7 @@ const REPLAY_ONLY: [(&str, &str); 37] = [ ("artboard.distribute", "activeArtboard"), ("artboard.distributeSpacing", "selectedArtboards"), ("artboard.distributeSpacing", "activeArtboard"), + ("addon.type.fontSheet", "activeArtboard"), ("edit.copy", "selectedArtboards"), ("edit.copy", "art"), ("edit.cut", "selectedArtboards"), diff --git a/docs/mcp.md b/docs/mcp.md index a14d344869..8ccd65f7c5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -18252,8 +18252,9 @@ the fonts can be compared on the artboard or printed. after its font. With `labels` on, an entry starts with a line naming its font in the document's normal type font, at the sample's size up to 9 pt, and the sample follows on the next line. With `allStyles` each style of a family gets its own entry, labeled with the family and style; otherwise the family's Regular is used, else its closest style. -- **Layout:** the entries flow down the columns of the active artboard, inside `margin`, with `gap` between entries - and between columns. A sample wider than its column runs on past it. When the artboard is full, the sheet continues +- **Layout:** the entries flow down the columns of the active artboard (or the one `artboard` names), inside `margin`, with `gap` between entries + and between columns. Every line is aligned left, right-to-left samples too, so each starts at its column's left + edge. A sample wider than its column runs on past it. When the artboard is full, the sheet continues on new artboards of the same size to the right of the rightmost artboard, 20 pt apart; with `newArtboards` off the later pages are laid out in the same places without artboards. A document without artboards lays the sheet out on a 612 × 792 pt page at the origin and adds no artboards. @@ -18280,6 +18281,8 @@ the fonts can be compared on the artboard or printed. | `gap` | pt 0…1000, between entries and between columns (12) | | `margin` | pt 0…1000, inside each page (36) | | `newArtboards` | true; false: the pages after the first get no artboards | +| `artboard` | 0-based index of the artboard the first page is laid out on (the active artboard) | +| `activeArtboard` | the journal records the active artboard here when `artboard` is left out, so a replay uses the same artboard; `artboard` goes ahead of it, and an action leaves it out | In `addon.type.fontSheet`, a parameter given as `null` is the same as one left out and takes its default; any other value of the wrong type or out of range is an error. While the Create Font Sheet… dialog is open, Delete Artboard, Cut @@ -18288,7 +18291,7 @@ would delete the artboard the dialog opened on, and so does a running script's ` that does not catch the error ends with it); close the dialog first. → `{id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}`. Create Font Sheet… opens a dialog -(`ui.menuDialog {command}`) whose fields are the command's parameters except `families`, with Preview, which starts +(`ui.menuDialog {command}`) whose fields are the command's parameters except `families`, `artboard` and `activeArtboard` (it lays the sheet out on the artboard that was active when it opened), with Preview, which starts off: switched on, it sets the whole sheet again after each change. OK is off while the sample text is empty. Plug-ins can't call the command, since the sheet lists the installed fonts as `text.fontList` does. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef28729815..0e5b2852b3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3186,7 +3186,7 @@ A VectorCraft addition, not a feature of the reference app (it has no command fo ## Type Tools add-on: Create Font Sheet (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name unless labels are switched off, as point type flowed down columns on the active artboard. When the artboard is full, Add Artboards When Full (on by default) adds new artboards of the same size to its right for the rest; with it off, the rest is laid out in the same places to the right without artboards. Every Style gives each style of a family its own entry; families whose font can't be loaded, and composite fonts whose part setting the sample can't, are left out and listed. Each row is as tall as the tallest laid-out entry, so a composite font that enlarges the sample does not overlap. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`); its preview and OK set the sheet on the artboard active in the view when it opens, and while it is open, Delete Artboard, Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an error when they would delete that artboard, also when a running script calls them through `vc.run`. Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, composite fonts' row heights and missing parts, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` (including the artboard active when the dialog opens) and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name unless labels are switched off, as point type flowed down columns on the active artboard (or the one `artboard` names; the journal records the active one, so a replay uses the same artboard). Every line is aligned left, right-to-left samples too, so each starts at its column's left edge. When the artboard is full, Add Artboards When Full (on by default) adds new artboards of the same size to its right for the rest; with it off, the rest is laid out in the same places to the right without artboards. Every Style gives each style of a family its own entry; families whose font can't be loaded, and composite fonts whose part setting the sample can't, are left out and listed. Each row is as tall as the tallest laid-out entry, so a composite font that enlarges the sample does not overlap. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`); its preview and OK set the sheet on the artboard active in the view when it opens, and while it is open, Delete Artboard, Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an error when they would delete that artboard, also when a running script calls them through `vc.run`. Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, composite fonts' row heights and missing parts, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` (including the artboard active when the dialog opens) and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet. ## Unit Converter add-on (2026-11-14) From ebc14a9b36ff906edf11b502cf6790848b318d1b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:37:32 -0800 Subject: [PATCH 09/56] Type: Create Font Sheet names entries whose font lacks a glyph of the sample An entry whose font has no glyph for a character the sample draws (by the shaper's rules and the style's numerals) stays on the sheet, and is listed in `fallback` and named in the warning. Composite font names given in another letter case, accented letters included, are found as the font database compares names. --- .../src/cmd/addons/typetools/font_sheet.rs | 49 +++++++++++----- .../cmd/addons/typetools/font_sheet/tests.rs | 57 +++++++++++++++++++ crates/text/src/lib.rs | 2 +- crates/text/src/shape.rs | 6 +- docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 6 files changed, 100 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet.rs b/crates/engine/src/cmd/addons/typetools/font_sheet.rs index 46ae534764..bb009540e4 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet.rs @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Create Font Sheet", ["Object", "Plug-ins", "Type Tools"], None, - "{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once; an error with any filter, an empty one included), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards), artboard?: n (0-based; the artboard the first page is; default: the active one), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, every line aligned left (right-to-left samples too), flowed down the columns of the active artboard, or artboard `artboard` (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}", + "{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once; an error with any filter, an empty one included), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards), artboard?: n (0-based; the artboard the first page is; default: the active one), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, every line aligned left (right-to-left samples too), flowed down the columns of the active artboard, or artboard `artboard` (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An entry whose font lacks a glyph needed by the sample stays on the sheet, and is listed in `fallback` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], fallback: [entry name…], artboards: [index…] (the artboards added), warning?}", has_doc, font_sheet )] @@ -99,19 +99,18 @@ fn families(p: &Value, db: &FontDb) -> Result> { if listed.is_empty() { return Err(bad(COMMAND, "`families` must name at least one family")); } - let composites = db.composite_font_names(); let mut out: Vec = Vec::with_capacity(listed.len()); for f in listed { let f = f.as_str().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(COMMAND, "`families` must be a list of font family names"))?; if !db.has_family(f) { return Err(bad(COMMAND, format!("font family `{f}` is not available"))); } - // The name as the font menus spell it. - let name = match composites.iter().find(|c| c.eq_ignore_ascii_case(f)) { - Some(c) => c.clone(), + // The name as the font menus spell it, looked up as the database compares names. + let name = match db.composite_font(f) { + Some(c) => c.name.clone(), None => db.canonical(f, "").0, }; - if out.iter().any(|o| o.eq_ignore_ascii_case(&name)) { + if out.iter().any(|o| o.to_lowercase() == name.to_lowercase()) { return Err(bad(COMMAND, format!("`families` names `{name}` twice"))); } out.push(name); @@ -200,7 +199,8 @@ fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { // Each entry laid out at the origin, and how far its laid-out ink reaches above and below its first baseline. let mut laid: Vec<(String, TextObject, (f64, f64))> = Vec::with_capacity(fonts.len()); let mut skipped: Vec = vec![]; - let composites = db.composite_font_names(); + // The entries whose font lacks a glyph needed by the sample. + let mut fallback: Vec = vec![]; for (family, style) in fonts { let mut sample = new_type_style(s, &json!({ "size": size, "font": family, "style": style }), C)?; sample.leading = Some(size * 1.2); @@ -211,18 +211,25 @@ fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { // A font that doesn't load is drawn in the fallback font, and a style that doesn't in the // family's closest style: either is left out. A composite font is left out when a part // that sets the sample names a font or style that doesn't load. - let composite = composites.iter().any(|c| c.eq_ignore_ascii_case(&family)); - let loads = if composite { - db.composite_coverage(&family, &[text.as_str()]).is_some_and(|c| c.status == FontMatch::Exact) + let composite = db.composite_font(&family).is_some(); + let (loads, covers) = if composite { + (db.composite_coverage(&family, &[text.as_str()]).is_some_and(|c| c.status == FontMatch::Exact), true) } else { let wanted = db.canonical(&family, "").0; - db.face(&sample.font_family, &sample.font_style) - .is_some_and(|face| face.family.eq_ignore_ascii_case(&wanted) && style.as_ref().is_none_or(|st| face.style.eq_ignore_ascii_case(st))) + match db.face(&sample.font_family, &sample.font_style) { + Some(face) if face.family.eq_ignore_ascii_case(&wanted) && style.as_ref().is_none_or(|st| face.style.eq_ignore_ascii_case(st)) => { + (true, vectorcraft_text::drawn_chars(&text, sample.digits).all(|c| face.covers(c))) + } + _ => (false, true), + } }; if !loads { skipped.push(name); continue; } + if !covers { + fallback.push(name.clone()); + } let (first, more) = if labels { (TextRun::new(format!("{name}\n"), label_style.clone()), Some(TextRun::new(text.clone(), sample))) } else { @@ -289,13 +296,25 @@ fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { sel.set([gid]); Ok((gid, added)) })?; - let mut out = json!({ "id": gid.0, "count": count, "skipped": skipped, "artboards": added }); - if let Some(warning) = skipped_warning(&skipped) { - out["warning"] = json!(warning); + let mut out = json!({ "id": gid.0, "count": count, "skipped": skipped, "fallback": fallback, "artboards": added }); + let warnings: Vec = skipped_warning(&skipped).into_iter().chain(fallback_warning(&fallback)).collect(); + if !warnings.is_empty() { + out["warning"] = json!(warnings.join("; ")); } Ok(out) } +/// The warning a sheet with entries whose font lacks a glyph of the sample gives, naming the first few. +fn fallback_warning(fallback: &[String]) -> Option { + const NAMED: usize = 5; + let (first, more) = (fallback.iter().take(NAMED).cloned().collect::>(), fallback.len().saturating_sub(NAMED)); + match (first.is_empty(), more) { + (true, _) => None, + (false, 0) => Some(format!("{} font(s) lack glyphs for the sample: {}", fallback.len(), first.join(", "))), + (false, more) => Some(format!("{} font(s) lack glyphs for the sample: {} and {more} more", fallback.len(), first.join(", "))), + } +} + /// Point type set in `first` and then `more`, with its first baseline at the origin, laid out. fn laid_out(first: TextRun, more: Option, system_layout: bool) -> TextObject { let mut t = TextObject::point(Point::ZERO, "", first.style.clone()); diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs index e52a1e8ce0..ffa62df82b 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs @@ -179,6 +179,8 @@ fn a_right_to_left_sample_stays_inside_its_column() { // Alone, and under a left-to-right label: each line starts at the column's left edge. for labels in [false, true] { let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "labels": labels, "text": rtl})).unwrap(); + assert_eq!(r["fallback"], json!(BUNDLED), "no bundled font has Hebrew glyphs, so each entry is named"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}"); for (name, t) in &entries(&group(&s, &r)) { let x = origin(t).0; assert!((x - board.x0 - 50.0).abs() < 1e-9, "{name}: {x}"); @@ -191,6 +193,48 @@ fn a_right_to_left_sample_stays_inside_its_column() { } } +#[test] +fn a_variation_selector_does_not_require_a_separate_glyph() { + let mut s = session(); + let face = FontDb::global().face("Inter", "Regular").unwrap(); + assert!(face.covers('A')); + assert!(!face.covers('\u{fe0f}')); + let text = "A\u{fe0f}"; + let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap(); + assert_eq!(r["count"], 1); + assert_eq!(r["skipped"], json!([])); + assert_eq!(r["fallback"], json!([])); + assert!(r.get("warning").is_none(), "{r}"); + let e = entries(&group(&s, &r)); + assert_eq!(e.len(), 1); + assert_eq!(e[0].1.plain_text(), text); +} + +#[test] +fn coverage_uses_the_samples_numeral_system() { + let mut s = session(); + let face = FontDb::global().face("Inter", "Regular").unwrap(); + assert!(face.covers('1')); + assert!(!face.covers('\u{661}')); + for (digits, text, missing) in [("hindi", "1", true), ("arabic", "\u{661}", false)] { + s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": digits}})) + .unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap(); + assert_eq!(r["count"], 1); + assert_eq!(r["skipped"], json!([])); + assert_eq!(r["fallback"], if missing { json!(["Inter"]) } else { json!([]) }, "{digits}: {r}"); + if missing { + assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}"); + } else { + assert!(r.get("warning").is_none(), "{r}"); + } + let e = entries(&group(&s, &r)); + assert_eq!(e.len(), 1); + assert_eq!(e[0].1.plain_text(), text); + assert_eq!(e[0].1.runs[0].style.digits.id(), digits); + } +} + #[test] fn bad_params_are_refused_without_a_change() { let mut s = session(); @@ -315,6 +359,19 @@ fn rows_fit_the_laid_out_ink_of_a_composite_font() { } } +/// A composite font named in other letter case, accented letters included, is found by its own name. +#[test] +fn a_composite_font_named_in_other_case_is_set() { + let mut s = session(); + let font = json!({"name": "\u{c9}preuve Sheet", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["\u{e9}preuve sheet"], "text": "Hamburg"})).unwrap(); + assert_eq!((r["skipped"].clone(), r["count"].clone()), (json!([]), json!(1)), "{r}"); + assert_eq!(entries(&group(&s, &r))[0].0, "\u{c9}preuve Sheet"); + let twice = s.execute(COMMAND, &json!({"families": ["\u{c9}preuve Sheet", "\u{e9}PREUVE SHEET"]})).unwrap_err().to_string(); + assert!(twice.contains("twice"), "{twice}"); +} + /// A composite font whose part setting the sample names a font that doesn't load is left out and /// named, as a family that doesn't load is. #[test] diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 27555a8e4a..e41c8ccce7 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -59,7 +59,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader}; pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout}; use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2}; pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled}; -pub use shape::{aki_space, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale}; +pub use shape::{aki_space, drawn_chars, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale}; pub use vectorcraft_doc::TextObject; pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign}; diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 00658a1b34..004f5a5cb0 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -1382,11 +1382,11 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { && ligatures_suppressed_by(*tracking) == ligatures_suppressed_by(b.tracking) } -/// The characters of a grapheme cluster that need a glyph of their own, in the numeral system +/// The characters of the text that need a glyph of their own, in the numeral system /// `digits`: not what the layout handles itself (tab, line and paragraph breaks), joiners or /// variation selectors. -fn drawn_chars(cluster: &str, digits: Digits) -> impl Iterator + '_ { - craft::font_catalog::drawable_characters(cluster, move |c| digits.map(c)) +pub fn drawn_chars(text: &str, digits: Digits) -> impl Iterator + '_ { + craft::font_catalog::drawable_characters(text, move |c| digits.map(c)) } /// Does the face with charmap `map` have a glyph for `c` (any face does when it has no charmap)? diff --git a/docs/mcp.md b/docs/mcp.md index 8ccd65f7c5..e0e74f962e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -18262,6 +18262,8 @@ the fonts can be compared on the artboard or printed. with `allStyles` a style that can't (it would be drawn in the family's closest style), is left out, listed in `skipped` and named in `warning`, which the status bar shows. A composite font is left out the same way when a part that sets the sample text names a font or style that can't be loaded. +- **Missing glyphs:** an entry whose font lacks a glyph needed by the sample text stays on the sheet, and is listed + in `fallback` and named in `warning`. - Each row is as tall as the tallest laid-out entry needs, so a composite font whose part enlarges or raises the sample does not overlap the entry above it or reach into the margin. - The sheet is one group named Font Sheet, made in one undo step and selected. It goes where new art goes: the current @@ -18290,7 +18292,8 @@ Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an would delete the artboard the dialog opened on, and so does a running script's `vc.run` of one of them (a script that does not catch the error ends with it); close the dialog first. -→ `{id, count, skipped: [family, or family and style…], artboards: [index…] (the artboards added), warning?}`. Create Font Sheet… opens a dialog +→ `{id, count, skipped: [family, or family and style…], fallback: [entry name…], artboards: [index…] (the artboards added), warning?}`. +`fallback` lists entries kept on the sheet whose font lacks a glyph needed by the sample. Create Font Sheet… opens a dialog (`ui.menuDialog {command}`) whose fields are the command's parameters except `families`, `artboard` and `activeArtboard` (it lays the sheet out on the artboard that was active when it opened), with Preview, which starts off: switched on, it sets the whole sheet again after each change. OK is off while the sample text is empty. Plug-ins can't call the command, since the sheet lists the installed fonts as `text.fontList` does. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0e5b2852b3..342f4a1c1f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3186,7 +3186,7 @@ A VectorCraft addition, not a feature of the reference app (it has no command fo ## Type Tools add-on: Create Font Sheet (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name unless labels are switched off, as point type flowed down columns on the active artboard (or the one `artboard` names; the journal records the active one, so a replay uses the same artboard). Every line is aligned left, right-to-left samples too, so each starts at its column's left edge. When the artboard is full, Add Artboards When Full (on by default) adds new artboards of the same size to its right for the rest; with it off, the rest is laid out in the same places to the right without artboards. Every Style gives each style of a family its own entry; families whose font can't be loaded, and composite fonts whose part setting the sample can't, are left out and listed. Each row is as tall as the tallest laid-out entry, so a composite font that enlarges the sample does not overlap. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`); its preview and OK set the sheet on the artboard active in the view when it opens, and while it is open, Delete Artboard, Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an error when they would delete that artboard, also when a running script calls them through `vc.run`. Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, composite fonts' row heights and missing parts, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` (including the artboard active when the dialog opens) and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name unless labels are switched off, as point type flowed down columns on the active artboard (or the one `artboard` names; the journal records the active one, so a replay uses the same artboard). Every line is aligned left, right-to-left samples too, so each starts at its column's left edge. When the artboard is full, Add Artboards When Full (on by default) adds new artboards of the same size to its right for the rest; with it off, the rest is laid out in the same places to the right without artboards. Every Style gives each style of a family its own entry; families whose font can't be loaded, and composite fonts whose part setting the sample can't, are left out, listed in `skipped` and named in `warning`. Entries whose font lacks a glyph needed by the sample stay on the sheet, are listed in `fallback` and named in `warning`. Each row is as tall as the tallest laid-out entry, so a composite font that enlarges the sample does not overlap. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`); its preview and OK set the sheet on the artboard active in the view when it opens, and while it is open, Delete Artboard, Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an error when they would delete that artboard, also when a running script calls them through `vc.run`. Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, composite fonts' row heights and missing parts, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` (including the artboard active when the dialog opens) and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet. ## Unit Converter add-on (2026-11-14) From 417e857a892cfa18126b99a0c0f135d511c6891d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 20:44:24 -0800 Subject: [PATCH 10/56] Artboards: touching artboards cast no shadow on each other Artboards made with Spacing 0 sit edge to edge, but the canvas painted each artboard's drop shadow and then its paper in turn, so the lower artboard's shadow darkened the upper one along the join and showed a dark band between them. craft-libs#4740 paints every page shadow before any page. This moves the craft-libs pin to that pull request's head, a59264281, which is craft-libs main at 77ade517e plus the fix, and the egui pin to 861d60a6, the rev that craft-libs commit pins. The PDF dependency check reads the new rev. The new test makes two 200 x 200 artboards in a column with Spacing 0, checks that they touch, and checks that both shadows paint before both papers. It fails on the previous pin. --- Cargo.lock | 194 ++++++++++++++--------------- Cargo.toml | 98 +++++++-------- apps/vectorcraft-web/Cargo.toml | 2 +- crates/ui-egui/src/canvas/tests.rs | 27 ++++ xtask/src/pdf_deps.rs | 2 +- 5 files changed, 175 insertions(+), 148 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a398edf733..dfd56b5ca4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1231,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-automation", "craft-behavior", @@ -1272,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "crc32fast", "flate2", @@ -1283,7 +1283,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1295,7 +1295,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "rustix 1.1.6", ] @@ -1303,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-docpath", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "crc32fast", "flate2", @@ -1373,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "md-5", "rayon", @@ -1390,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-cms", @@ -1415,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1426,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1436,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1470,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "blake3", "craft-ecproj-format", @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1513,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-codepage", "encoding_rs", @@ -1525,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "serde", "serde_json", @@ -1535,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1574,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1583,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "cap-primitives", "craft-atomic", @@ -1606,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1640,7 +1640,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-dds", "craft-jpeg", @@ -1697,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1715,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "thiserror 2.0.21", ] @@ -1723,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1734,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-host", "craft-i18n", @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-i18n", @@ -1763,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-host", @@ -1781,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1793,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "encoding_rs", "image", @@ -1804,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "chrono", "craft-codepage", @@ -1814,7 +1814,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "uds_windows", "winsafe", @@ -1823,7 +1823,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-keymap", @@ -1839,7 +1839,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "flate2", "serde", @@ -1850,7 +1850,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1862,7 +1862,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "async-channel", "async-io", @@ -1895,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1904,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-host", @@ -1928,7 +1928,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1939,7 +1939,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-eps", "flate2", @@ -1953,7 +1953,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "encoding_rs", "flate2", @@ -1964,7 +1964,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "dispatch2", "egui", @@ -1977,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1996,7 +1996,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-atomic", "craft-host", @@ -2013,7 +2013,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "fax", "hayro-ccitt", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2045,7 +2045,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-keymap", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2082,7 +2082,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2097,7 +2097,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-atomic", "craft-behavior", @@ -2112,7 +2112,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "serde", "thiserror 2.0.21", @@ -2122,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "serde", "thiserror 2.0.21", @@ -2131,7 +2131,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-keymap", @@ -2146,12 +2146,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2165,7 +2165,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2182,7 +2182,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "accesskit", "craft-behavior", @@ -2220,7 +2220,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2231,7 +2231,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-host", @@ -2249,7 +2249,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-host", @@ -2270,7 +2270,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-host", @@ -2291,7 +2291,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-behavior", "craft-host", @@ -2310,7 +2310,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "base64 0.22.1", "chrono", @@ -2342,7 +2342,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "flate2", "serde", @@ -2353,7 +2353,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2363,7 +2363,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "js-sys", "serde_json", @@ -2374,7 +2374,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "winsafe", ] @@ -2382,7 +2382,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "craft-appkit", "craft-atomic", @@ -2414,7 +2414,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2759,7 +2759,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "bytemuck", "emath", @@ -2792,7 +2792,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "ahash", "bytemuck", @@ -2827,7 +2827,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "accesskit", "ahash", @@ -2846,7 +2846,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "ahash", "bytemuck", @@ -2865,7 +2865,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "accesskit_winit", "arboard", @@ -2890,7 +2890,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "ahash", "egui", @@ -2904,7 +2904,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "bytemuck", "egui", @@ -2917,7 +2917,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "dify", "eframe", @@ -2943,7 +2943,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "bytemuck", ] @@ -3024,7 +3024,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "ahash", "bytemuck", @@ -3050,7 +3050,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321" +source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -3773,7 +3773,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3782,7 +3782,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3800,7 +3800,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3818,12 +3818,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "flate2", "hayro-ccitt", @@ -4806,7 +4806,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4963,7 +4963,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" +source = "git+https://github.com/storytold/craft-libs?rev=a59264281e498d78ede8f503572b3d5502c44d51#a59264281e498d78ede8f503572b3d5502c44d51" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index fcc2a1ad8f..8562d3201b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,51 +10,51 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -194,22 +194,22 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +emath = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 824600f90a..d94dcf91cc 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "a59264281e498d78ede8f503572b3d5502c44d51", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 41d0e93837..5c8f2ca4ab 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6903,3 +6903,30 @@ fn a_wheel_pan_under_a_resting_pointer_keeps_the_tool_cursor() { } assert!(asks() > before, "once the view is still, the tool gives the cursor again"); } + +/// Artboards made with no spacing touch, and the canvas paints every artboard's drop shadow before any artboard's +/// paper, so the lower artboard's shadow does not darken the upper one along the shared edge. +#[test] +fn touching_artboards_cast_no_shadow_on_each_other() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200, "artboards": 2, "artboardLayout": {"layout": "column", "spacing": 0}})).unwrap(); + let boards: Vec<_> = app.session.active().unwrap().doc.artboards.iter().map(|ab| ab.rect).collect(); + assert_eq!(boards[0].y1, boards[1].y0, "the artboards touch"); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.canvas.worker_started = true; + let ctx = crate::testing::ui_context(); + let _ = shapes(&mut app, &ctx); + let view = app.view_mut().unwrap(); + (view.zoom, view.center) = (1.0, Point::new(100.0, 200.0)); + let all = shapes(&mut app, &ctx); + let papers: Vec = all + .iter() + .enumerate() + .filter(|(_, s)| matches!(s, Shape::Mesh(m) if m.texture_id == egui::TextureId::default() && m.vertices.first().is_some_and(|v| v.color == Color32::WHITE))) + .map(|(at, _)| at) + .collect(); + let shadows: Vec = all.iter().enumerate().filter(|(_, s)| matches!(s, Shape::Rect(r) if r.blur_width > 0.0)).map(|(at, _)| at).collect(); + assert_eq!((papers.len(), shadows.len()), (2, 2), "each artboard paints its paper and casts a shadow"); + assert!(shadows.iter().all(|s| papers.iter().all(|p| s < p)), "every shadow lies under both papers: shadows {shadows:?}, papers {papers:?}"); +} diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 337ba6325e..ab3fd17273 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "965c7beeb6076480e016e448bddddcce0a738ff6"; +const REV: &str = "a59264281e498d78ede8f503572b3d5502c44d51"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 0db6dddc60dc55fc2fb466cd3b1460fee2a02b65 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:34:37 -0800 Subject: [PATCH 11/56] Type: Font Sheet lists composite fonts lacking sample glyphs as fallbacks A composite font's entry was never named in `fallback`, even when the part that sets the sample lacked a glyph it needs. The entry now checks each grapheme's part face for the characters layout draws, in the sample's numeral system, through the new `FontDb::composite_drawn_coverage`. --- .../src/cmd/addons/typetools/font_sheet.rs | 4 +++- .../cmd/addons/typetools/font_sheet/tests.rs | 24 +++++++++++++++++++ crates/text/src/fontdb/composite.rs | 19 +++++++++++++-- 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet.rs b/crates/engine/src/cmd/addons/typetools/font_sheet.rs index bb009540e4..edc72587cc 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet.rs @@ -213,7 +213,9 @@ fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { // that sets the sample names a font or style that doesn't load. let composite = db.composite_font(&family).is_some(); let (loads, covers) = if composite { - (db.composite_coverage(&family, &[text.as_str()]).is_some_and(|c| c.status == FontMatch::Exact), true) + // Glyph coverage is checked on the characters layout draws, in the sample's numeral system. + let covers = db.composite_drawn_coverage(&family, &[text.as_str()], sample.digits).is_none_or(|c| c.lacking.is_empty()); + (db.composite_coverage(&family, &[text.as_str()]).is_some_and(|c| c.status == FontMatch::Exact), covers) } else { let wanted = db.canonical(&family, "").0; match db.face(&sample.font_family, &sample.font_style) { diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs index ffa62df82b..f1b207025b 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs @@ -409,6 +409,30 @@ fn a_composite_font_with_an_unavailable_part_style_is_left_out() { assert_eq!(steps(&s), before.1); } +/// A composite font whose parts load but lack a glyph the sample needs stays on the sheet and is +/// named in `fallback`, as a plain font is. +#[test] +fn a_composite_font_lacking_a_sample_glyph_is_named_as_a_fallback() { + let mut s = session(); + let font = json!({"name": "CF Sheet Lacking", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}"; + let coverage = FontDb::global().composite_coverage("CF Sheet Lacking", &[rtl]).unwrap(); + assert_eq!(coverage.status, vectorcraft_text::FontMatch::Exact); + assert!(!coverage.lacking.is_empty()); + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": rtl})).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(1), &json!([])), "{r}"); + assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("CF Sheet Lacking")), "{r}"); + // A variation selector needs no glyph of its own, and digits are checked in the sample's numeral system. + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "A\u{fe0f}"})).unwrap(); + assert_eq!(r["fallback"], json!([]), "{r}"); + s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": "hindi"}})) + .unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "1"})).unwrap(); + assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}"); +} + #[test] fn labels_without_overlap_need_no_additional_layouts() { use vectorcraft_text::test_fonts::{ink_work_on_this_thread, layouts_on_this_thread}; diff --git a/crates/text/src/fontdb/composite.rs b/crates/text/src/fontdb/composite.rs index 1ac538b7a0..371d8e2574 100644 --- a/crates/text/src/fontdb/composite.rs +++ b/crates/text/src/fontdb/composite.rs @@ -12,7 +12,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use unicode_segmentation::UnicodeSegmentation; use vectorcraft_doc::text::CompositeClasses; -use vectorcraft_doc::{CharClass, CompositeClass, CompositeFont, CompositePart, TextObject, TextRun}; +use vectorcraft_doc::{CharClass, CompositeClass, CompositeFont, CompositePart, Digits, TextObject, TextRun}; use super::face::FALLBACK_FAMILY; use super::{Arc, FontDb, FontFace, FontMatch}; @@ -242,6 +242,17 @@ impl FontDb { /// match, and the characters (neither whitespace nor control characters, sorted, each once) /// that their part's face lacks. `None` when `name` is no composite font. pub fn composite_coverage(&self, name: &str, texts: &[&str]) -> Option { + self.coverage_of(name, texts, None) + } + + /// [`FontDb::composite_coverage`] of the characters layout draws in numeral system `digits`: + /// each grapheme cluster's part is chosen by its own first character, and the part's face is + /// checked for the cluster's drawn characters ([`crate::drawn_chars`]). + pub fn composite_drawn_coverage(&self, name: &str, texts: &[&str], digits: Digits) -> Option { + self.coverage_of(name, texts, Some(digits)) + } + + fn coverage_of(&self, name: &str, texts: &[&str], digits: Option) -> Option { let f = self.composite_font(name)?; let rank = |m: FontMatch| match m { FontMatch::Exact => 0, @@ -272,7 +283,11 @@ impl FontDb { if worst.as_ref().is_none_or(|(w, _)| rank(m) > rank(*w)) { worst = Some((m, found.as_ref().map(|(face, _)| face.clone()))); } - lacking.extend(g.chars().filter(|c| !c.is_whitespace() && !c.is_control() && !found.as_ref().is_some_and(|(face, _)| face.covers(*c)))); + match digits { + Some(d) => lacking.extend(crate::drawn_chars(g, d).filter(|c| !found.as_ref().is_some_and(|(face, _)| face.covers(*c)))), + None => lacking + .extend(g.chars().filter(|c| !c.is_whitespace() && !c.is_control() && !found.as_ref().is_some_and(|(face, _)| face.covers(*c)))), + } } lacking.sort_unstable(); lacking.dedup(); From a94dbea4dad596064e59a806ed0b5f7064d637e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:24:38 -0800 Subject: [PATCH 12/56] Tests: the PDF 1.3 transparency check reads dictionaries only pdf_1_3_flattens_all_transparency_and_looks_the_same failed on CI at 820f3d34 and passed on rerun. The transparency check searched the whole file for `/BM`, and the file ID, written in the trailer and the XMP stream, is base64 that changes with the export time. About one export in three thousand has an ID that contains `/BM`, so the check reported a blend mode in a flat file. The check now leaves out literal strings and stream data, skipped by the stream's direct `/Length`, and fails when that length does not end at `endstream`. Every dictionary key it looked for is still checked. A new test covers an ID and an XMP packet that spell the keys, a `(` in image data, nested and escaped parentheses, `endstream` inside stream data, and wrong lengths. --- crates/engine/src/cmd/fileio/tests_pdf13.rs | 84 ++++++++++++++++++++- 1 file changed, 82 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index 7c0aa4a74b..7497b9490d 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -71,9 +71,59 @@ fn export(s: &mut Session, p: Value) -> (Vec, Vec) { (bytes, v["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect()) } -/// The transparency `pdf` has, in its dictionaries. +/// The transparency `pdf` has, in its dictionaries. Stream data and literal strings are left out: +/// the file ID, in the trailer and in the XMP stream, is base64 that changes with the export time +/// and can spell `/BM`. fn transparency(pdf: &[u8]) -> Vec<&'static str> { - let text = String::from_utf8_lossy(pdf); + let mut text = Vec::with_capacity(pdf.len()); + let mut i = 0; + while i < pdf.len() { + let rest = &pdf[i..]; + if rest.starts_with(b"endstream") { + text.extend_from_slice(b"endstream"); + i += b"endstream".len(); + } else if rest.starts_with(b"stream") { + // Stream data is the dictionary's `/Length` bytes after the end of line (else it runs to + // `endstream`); its bytes are not PDF syntax. + let start = i + b"stream".len() + if rest[b"stream".len()..].starts_with(b"\r\n") { 2 } else { 1 }; + let dict = String::from_utf8_lossy(&text[text.windows(3).rposition(|w| w == b"obj").unwrap_or(0)..]).into_owned(); + let length = dict.rfind("/Length ").and_then(|at| { + let digits = &dict[at + "/Length ".len()..]; + let (n, after) = digits.split_at(digits.find(|c: char| !c.is_ascii_digit()).unwrap_or(digits.len())); + (!after.trim_start().starts_with(|c: char| c.is_ascii_digit())).then(|| n.parse::().ok()).flatten() + }); + i = match length { + Some(n) => { + let mut end = start.checked_add(n).filter(|&end| end <= pdf.len()).expect("stream /Length is inconsistent with endstream"); + while matches!(pdf.get(end), Some(b'\r' | b'\n')) { + end += 1; + } + assert!(pdf[end..].starts_with(b"endstream"), "stream /Length is inconsistent with endstream"); + end + } + None => i + rest.windows(b"endstream".len()).position(|w| w == b"endstream").unwrap_or(rest.len()), + }; + } else if rest[0] == b'(' { + // A literal string: balanced parentheses, with `\` escaping the next byte. + let mut depth = 0usize; + while i < pdf.len() { + match pdf[i] { + b'\\' => i += 1, + b'(' => depth += 1, + b')' => depth -= 1, + _ => {} + } + i += 1; + if depth == 0 { + break; + } + } + } else { + text.push(rest[0]); + i += 1; + } + } + let text = String::from_utf8_lossy(&text); let mut found = vec![]; for (what, there) in [ ("soft masks", text.contains("/SMask") && !text.contains("/SMask/None")), @@ -193,3 +243,33 @@ fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() { s.execute("document.open", &json!({"dataBase64": vectorcraft_format::base64_encode(&pdf), "name": "old.pdf", "password": "nope"})).is_err() ); } + +/// The file ID is base64 that changes with the export time, so it can spell `/BM`; the check +/// reads the file's dictionaries only, not its strings or its XMP packet. +#[test] +fn the_transparency_check_skips_strings_and_metadata() { + let pdf = b"%PDF-1.3\n5 0 obj\n<>\nendobj\n6 0 obj\n<>\nstream\nq/BMx/S/Transparency\nendstream\nendobj\ntrailer\n<>\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + assert_eq!(transparency(b"<>>>>>"), vec!["blend modes", "opacity"]); + // A `(` in image data starts no string, and nested and escaped parentheses end where the + // string does. + let pdf = b"<>\nstream\n(\x00(\nendstream\n<>\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks", "transparency groups"]); + // Stream data is skipped by its length, even when it holds `endstream` itself. + let pdf = b"1 0 obj\n<>\nstream\nendstream (/BM\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + let pdf = b"1 0 obj\n<>\nstream\nabc\r\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + let pdf = b"1 0 obj\n<>\nstream\nabcendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + for length in [2, 20, 999, usize::MAX] { + let pdf = format!("1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n<>"); + let panic = std::panic::catch_unwind(|| transparency(pdf.as_bytes())).expect_err("an inconsistent stream /Length must panic"); + let message = panic.downcast_ref::<&str>().copied().or_else(|| panic.downcast_ref::().map(String::as_str)); + assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}"); + } +} From 9217a44f6ee064627845260459614a5a50afe64f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:05:15 -0800 Subject: [PATCH 13/56] Type: font sheet checks the capitals All Caps draws With All Caps on in [Normal Character Style], layout draws the sample in capitals, but the coverage check looked only at the text as typed, so a font with a lowercase letter and no capital was left out of the fallback warning. The check now also tests the capitals, in plain fonts and in composite fonts, where each cluster's part is still chosen by the character as typed. --- .../src/cmd/addons/typetools/font_sheet.rs | 8 +++- .../cmd/addons/typetools/font_sheet/tests.rs | 39 +++++++++++++++++++ crates/text/src/fontdb/composite.rs | 20 ++++++++-- 3 files changed, 62 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet.rs b/crates/engine/src/cmd/addons/typetools/font_sheet.rs index edc72587cc..c73fab6d2f 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet.rs @@ -212,15 +212,19 @@ fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { // family's closest style: either is left out. A composite font is left out when a part // that sets the sample names a font or style that doesn't load. let composite = db.composite_font(&family).is_some(); + // Layout picks a font for each character as typed, then draws All Caps type in capitals in + // that font, so coverage is checked on both. let (loads, covers) = if composite { // Glyph coverage is checked on the characters layout draws, in the sample's numeral system. - let covers = db.composite_drawn_coverage(&family, &[text.as_str()], sample.digits).is_none_or(|c| c.lacking.is_empty()); + let covers = db.composite_cased_coverage(&family, &[text.as_str()], sample.digits, sample.all_caps).is_none_or(|c| c.lacking.is_empty()); (db.composite_coverage(&family, &[text.as_str()]).is_some_and(|c| c.status == FontMatch::Exact), covers) } else { let wanted = db.canonical(&family, "").0; match db.face(&sample.font_family, &sample.font_style) { Some(face) if face.family.eq_ignore_ascii_case(&wanted) && style.as_ref().is_none_or(|st| face.style.eq_ignore_ascii_case(st)) => { - (true, vectorcraft_text::drawn_chars(&text, sample.digits).all(|c| face.covers(c))) + let drawn = |t: &str| vectorcraft_text::drawn_chars(t, sample.digits).all(|c| face.covers(c)); + let capitals = || text.chars().flat_map(char::to_uppercase).collect::(); + (true, drawn(&text) && (!sample.all_caps || drawn(&capitals()))) } _ => (false, true), } diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs index f1b207025b..0e8e81fc52 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs @@ -235,6 +235,45 @@ fn coverage_uses_the_samples_numeral_system() { } } +/// All Caps in the normal character style draws the sample in capitals, so a font with a lowercase +/// letter but not its capital is named in `fallback`, plain and composite fonts alike. +#[test] +fn coverage_checks_the_capitals_all_caps_draws() { + let mut s = session(); + let face = FontDb::global().face("Inter", "Regular").unwrap(); + let lower = (0x80..0x3000u32) + .filter_map(char::from_u32) + .find(|&c| { + let mut up = c.to_uppercase(); + face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u)) + }) + .unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital")); + let font = json!({"name": "CF Sheet Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let text = lower.to_string(); + let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap(); + assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}"); + s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"all_caps": true}})).unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}"); + assert_eq!(r["fallback"], json!(["Inter", "CF Sheet Caps"]), "{lower:?}: {r}"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs")), "{r}"); + let e = entries(&group(&s, &r)); + assert!(e[0].1.runs[0].style.all_caps); + assert_eq!(e[0].1.plain_text(), text, "the sample keeps its own case"); + // Layout picks the font for the character as typed, so one the font lacks still falls back + // when the font has its capitals. + let uncased = (0x80..0x3000u32) + .filter_map(char::from_u32) + .find(|&c| { + let up: String = c.to_uppercase().collect(); + !face.covers(c) && up != c.to_string() && up.chars().all(|u| face.covers(u)) + }) + .unwrap_or_else(|| panic!("Inter has every character whose capitals it has")); + let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": uncased.to_string()})).unwrap(); + assert_eq!(r["fallback"], json!(["Inter"]), "{uncased:?}: {r}"); +} + #[test] fn bad_params_are_refused_without_a_change() { let mut s = session(); diff --git a/crates/text/src/fontdb/composite.rs b/crates/text/src/fontdb/composite.rs index 371d8e2574..772b62cfb6 100644 --- a/crates/text/src/fontdb/composite.rs +++ b/crates/text/src/fontdb/composite.rs @@ -249,10 +249,17 @@ impl FontDb { /// each grapheme cluster's part is chosen by its own first character, and the part's face is /// checked for the cluster's drawn characters ([`crate::drawn_chars`]). pub fn composite_drawn_coverage(&self, name: &str, texts: &[&str], digits: Digits) -> Option { - self.coverage_of(name, texts, Some(digits)) + self.coverage_of(name, texts, Some((digits, false))) } - fn coverage_of(&self, name: &str, texts: &[&str], digits: Option) -> Option { + /// [`FontDb::composite_drawn_coverage`] of type set in All Caps when `all_caps` is on: each + /// cluster's part is still chosen by its own first character, and the part's face is also + /// checked for the capitals layout draws. + pub fn composite_cased_coverage(&self, name: &str, texts: &[&str], digits: Digits, all_caps: bool) -> Option { + self.coverage_of(name, texts, Some((digits, all_caps))) + } + + fn coverage_of(&self, name: &str, texts: &[&str], digits: Option<(Digits, bool)>) -> Option { let f = self.composite_font(name)?; let rank = |m: FontMatch| match m { FontMatch::Exact => 0, @@ -284,7 +291,14 @@ impl FontDb { worst = Some((m, found.as_ref().map(|(face, _)| face.clone()))); } match digits { - Some(d) => lacking.extend(crate::drawn_chars(g, d).filter(|c| !found.as_ref().is_some_and(|(face, _)| face.covers(*c)))), + Some((d, caps)) => { + let missing = |c: &char| !found.as_ref().is_some_and(|(face, _)| face.covers(*c)); + lacking.extend(crate::drawn_chars(g, d).filter(missing)); + if caps { + let upper: String = g.chars().flat_map(char::to_uppercase).collect(); + lacking.extend(crate::drawn_chars(&upper, d).filter(missing)); + } + } None => lacking .extend(g.chars().filter(|c| !c.is_whitespace() && !c.is_control() && !found.as_ref().is_some_and(|(face, _)| face.covers(*c)))), } From e2e89207fcc0dcc285c0714792531ba76ca8c883 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:28:50 -0800 Subject: [PATCH 14/56] Type: font sheet test checks the document keeps its layers test-lint's all-unguarded rule flagged bad_params_are_refused_without_a_change: its all() over the layers also passed on a document with no layers. The test now asserts the layer list is not empty before checking nothing was drawn. --- crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs index 0e8e81fc52..ab86b42be4 100644 --- a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs @@ -312,7 +312,9 @@ fn bad_params_are_refused_without_a_change() { assert!(s.execute(COMMAND, &bad).is_err(), "{bad}"); } assert_eq!(steps(&s), before); - assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "nothing was drawn"); + let layers = &s.doc().unwrap().doc.layers; + assert!(!layers.is_empty(), "the document keeps its layers"); + assert!(layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "nothing was drawn"); } /// Fonts left out are named in the warning, the first five of them, with a count of the rest. From 761f99fc5ab2efa7d83220f1dc1489253e4e6c9c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 06:49:26 -0800 Subject: [PATCH 15/56] Scripts: pathItems.removeAll keeps a clipping path that still holds an image The document's pathItems.removeAll() refused to delete paths from a group that is a clipping path when an image or placed document stayed inside that group, although the image's frame still clips. It now counts the frame of a visible image or placed document as clipping geometry when the frame encloses an area, as Node::clip_shapes does, and still refuses when the frame is collapsed to a line. --- crates/engine/src/script/dom/paths.rs | 13 ++++-- crates/engine/src/tests/script_dom.rs | 60 +++++++++++++++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 71 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 392e8c7700..3e1f5e1266 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -561,7 +561,7 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before /// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or /// layer that keeps other objects, or a compound path or group that clips one and would be left -/// with no visible path or visible type that lays out glyphs to clip by. +/// with no visible path, image, placed document or visible type that lays out glyphs to clip by. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if super::layers::is_scoped(a, "PathItems") { return super::layers::scoped_remove_all(h, a); @@ -617,12 +617,17 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { { going.insert(n.id); } - // A clip outline takes in visible paths and the glyphs of visible type, as - // `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no - // outline. A list marker is a glyph too, so whitespace-only type is laid out as well. + // A clip outline takes in visible paths, the frames of visible images and placed + // documents that enclose an area, and the glyphs of visible type, as `push_clip_shapes` does; type that lays + // out no glyphs (blank, or overset) gives no outline. A list marker is a glyph too, so + // whitespace-only type is laid out as well. let shape = n.visible && match &n.kind { NodeKind::Path { .. } => true, + // A frame collapsed to a line or a point encloses nothing to clip by. + NodeKind::Image(_) | NodeKind::PlacedDocument(_) => { + n.clip_shapes(None).iter().any(|(frame, _)| kurbo::Shape::area(frame).abs() > 0.0) + } NodeKind::Text(t) => { in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty() } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index a982c82575..30250055d5 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -4014,6 +4014,66 @@ fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empt assert_eq!(undo_steps(&s), steps); } +/// An image's frame clips as a clipping path does, so a clipping group whose clipping path keeps +/// an image still has an outline after its paths are deleted. +#[test] +fn document_path_items_remove_all_keeps_a_clipping_group_whose_clipping_path_keeps_an_image() { + for flat in [false, true] { + remove_all_beside_an_image(flat); + } +} + +/// A clipping group whose clipping path is a group of one path and an image, the image's frame +/// collapsed to a line when `flat`, then the document's `pathItems.removeAll()`. +fn remove_all_beside_an_image(flat: bool) { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let image = s + .edit("Place", |d, _| { + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 4, + height: 4, + xf: kurbo::Affine::scale_non_uniform(10.0, if flat { 0.0 } else { 10.0 }), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(Some(mask), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(id) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + if flat { + assert_eq!( + out[0], + json!(format!("cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", mask.0)) + ); + assert_eq!(s.active().unwrap().doc, before); + return; + } + assert_eq!(out, [json!(""), json!(0)]); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none()); + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.parent_of(image), Some(mask)); + assert!(d.node(t).is_some()); +} + #[test] fn document_path_items_remove_all_keeps_empty_groups_but_removes_empty_compounds() { for compound in [false, true] { diff --git a/docs/mcp.md b/docs/mcp.md index 85e35043df..a7b3263f44 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3249,7 +3249,7 @@ through `$`: `groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group or layer that keeps other objects. The document's `pathItems.removeAll()` still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then - clips. Text beside the clipping path in the clipping group does not count. Hidden text, text + clips. A visible image or placed document inside that group keeps it clipping by its frame too, when the frame encloses an area. Text beside the clipping path in the clipping group does not count. Hidden text, text in a hidden group, blank text without a list marker, area text too short for its first line, and text that a clipping group nested in the mask clips do not keep it clipping, so `removeAll()` then throws and deletes nothing. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 95dcc2c098..d13d090c99 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1119,7 +1119,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips, and the same holds for a visible image or placed document whose frame encloses an area; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From 07c33b9f2ae21e80eecac8d3ea7c304cec45ca0c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 09:32:28 -0800 Subject: [PATCH 16/56] Scripts: pathItems.removeAll judges a kept clipping region by its live effects The check that an image or placed-document frame still encloses an area now measures each subpath from its own first point, so a tiny frame far from the origin is not lost to roundoff and a collapsed frame is not counted through roundoff. When a live geometry effect, such as an Offset Path inset, would leave no clipping region once the paths are deleted, removeAll() now throws and deletes nothing. The preflight copies only the members that hold a path being deleted. --- crates/engine/src/script/dom/paths.rs | 50 ++++++++++++++++++++++++--- crates/engine/src/tests/script_dom.rs | 33 ++++++++++++++---- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 75 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 3e1f5e1266..50d8666389 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -625,9 +625,7 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { && match &n.kind { NodeKind::Path { .. } => true, // A frame collapsed to a line or a point encloses nothing to clip by. - NodeKind::Image(_) | NodeKind::PlacedDocument(_) => { - n.clip_shapes(None).iter().any(|(frame, _)| kurbo::Shape::area(frame).abs() > 0.0) - } + NodeKind::Image(_) | NodeKind::PlacedDocument(_) => n.clip_shapes(None).iter().any(|(frame, _)| encloses(frame)), NodeKind::Text(t) => { in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty() } @@ -639,10 +637,16 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if n.visible && ((shape && !going.contains(&n.id)) || inner) { geometry.insert(n.id); } + // The live geometry effects of what stays in the clipping path reshape the region it + // clips by, as the renderer draws it; deleting paths that lets an effect shrink the + // region to nothing leaves no outline. A region that was empty before is left as it is. + let reshaped_empty = |m: &vectorcraft_doc::Node| { + vectorcraft_render::effects::reshaped_clip_outline(m).is_some_and(|o| !o.is_some_and(|(bp, _)| encloses(&bp))) + }; if n.clips() && let Some(mask) = kids.first() && affected.contains(&mask.id) - && !geometry.contains(&mask.id) + && (!geometry.contains(&mask.id) || (reshaped_empty(&without(mask, &going, &affected)) && !reshaped_empty(mask))) && kids.iter().skip(1).any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. })) && masks.len() < 20 { @@ -671,6 +675,44 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// Whether a subpath of `outline` encloses an area. Each subpath's area is measured from its first +/// point, so its position does not change the result, and an area within roundoff of its own +/// bounding box's is counted as none. +fn encloses(outline: &kurbo::BezPath) -> bool { + let mut subpaths: Vec = Vec::new(); + for el in outline.elements() { + if matches!(el, kurbo::PathEl::MoveTo(_)) || subpaths.is_empty() { + subpaths.push(kurbo::BezPath::new()); + } + if let Some(last) = subpaths.last_mut() { + last.push(*el); + } + } + subpaths.into_iter().any(|mut sub| { + let Some(start) = sub.elements().iter().find_map(|e| e.end_point()) else { return false }; + sub.apply_affine(kurbo::Affine::translate(-start.to_vec2())); + let area = kurbo::Shape::area(&sub).abs(); + area > 0.0 && area > 64.0 * f64::EPSILON * kurbo::Shape::bounding_box(&sub).area() + }) +} + +/// `n` without the members in `going`, at every depth. Only the members in `affected` (those that +/// hold a member in `going`) are copied; the others are shared. +fn without( + n: &vectorcraft_doc::Node, + going: &std::collections::HashSet, + affected: &std::collections::HashSet, +) -> vectorcraft_doc::Node { + let mut m = n.clone(); + if let Some(kids) = m.children_mut() { + kids.retain(|k| !going.contains(&k.id)); + for k in kids.iter_mut().filter(|k| affected.contains(&k.id)) { + *k = Arc::new(without(k, going, affected)); + } + } + m +} + /// The id in the JSON result of a command that made an object, read exactly, as the text creators /// read it. fn made_id(r: &(Data, Value)) -> std::result::Result { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 30250055d5..07e7ec9dfb 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -4018,14 +4018,28 @@ fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empt /// an image still has an outline after its paths are deleted. #[test] fn document_path_items_remove_all_keeps_a_clipping_group_whose_clipping_path_keeps_an_image() { - for flat in [false, true] { - remove_all_beside_an_image(flat); + for frame in [Frame::Square, Frame::Line, Frame::Far, Frame::Inset] { + remove_all_beside_an_image(frame); } } -/// A clipping group whose clipping path is a group of one path and an image, the image's frame -/// collapsed to a line when `flat`, then the document's `pathItems.removeAll()`. -fn remove_all_beside_an_image(flat: bool) { +/// The image frame of [`remove_all_beside_an_image`]. +#[derive(Clone, Copy, PartialEq)] +enum Frame { + /// 40 pt square. + Square, + /// Collapsed to a line. + Line, + /// 1/64 pt square 3,500,000 pt from the origin. + Far, + /// 40 pt square with a live Offset Path of -30 pt, which leaves nothing. + Inset, +} + +/// A clipping group whose clipping path is a group of one path and an image with `frame`, then the +/// document's `pathItems.removeAll()`. +fn remove_all_beside_an_image(frame: Frame) { + let flat = matches!(frame, Frame::Line | Frame::Inset); let (mut s, a, b) = doc(); let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); @@ -4037,7 +4051,11 @@ fn remove_all_beside_an_image(flat: bool) { key: "pic".into(), width: 4, height: 4, - xf: kurbo::Affine::scale_non_uniform(10.0, if flat { 0.0 } else { 10.0 }), + xf: match frame { + Frame::Square | Frame::Inset => kurbo::Affine::scale(10.0), + Frame::Line => kurbo::Affine::scale_non_uniform(10.0, 0.0), + Frame::Far => kurbo::Affine::translate((3_500_000.0, 3_500_000.0)) * kurbo::Affine::scale(1.0 / 256.0), + }, link: None, placement: Default::default(), pixels: None, @@ -4046,6 +4064,9 @@ fn remove_all_beside_an_image(flat: bool) { Ok(id) }) .unwrap(); + if frame == Frame::Inset { + s.execute("effect.apply", &json!({"effect": "path.offsetPath", "params": {"offset": -30}, "ids": [image.0], "item": null})).unwrap(); + } s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap(); let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); s.edit("Clip", |d, _| { diff --git a/docs/mcp.md b/docs/mcp.md index a7b3263f44..52509fe45d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3249,7 +3249,7 @@ through `$`: `groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group or layer that keeps other objects. The document's `pathItems.removeAll()` still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then - clips. A visible image or placed document inside that group keeps it clipping by its frame too, when the frame encloses an area. Text beside the clipping path in the clipping group does not count. Hidden text, text + clips. A visible image or placed document inside that group keeps it clipping by its frame too, when the frame encloses an area. When a live geometry effect, such as an Offset Path inset, leaves no clipping region once the paths are deleted, `removeAll()` throws and deletes nothing. Text beside the clipping path in the clipping group does not count. Hidden text, text in a hidden group, blank text without a list marker, area text too short for its first line, and text that a clipping group nested in the mask clips do not keep it clipping, so `removeAll()` then throws and deletes nothing. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d13d090c99..1634645d88 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1119,7 +1119,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips, and the same holds for a visible image or placed document whose frame encloses an area; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips, and the same holds for a visible image or placed document whose frame encloses an area, unless a live geometry effect then leaves no clipping region; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From 0041956b541a8b6bd3018f7789bcbec77fbf8b03 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 11:42:08 -0800 Subject: [PATCH 17/56] Paths: Reverse Path Direction keeps the same anchors direct-selected path.reverse turned each subpath's anchor order around but left the selection's anchor and segment indices as they were, so after Object > Path > Reverse Path Direction a Direct-Selected anchor named the point at the other end of the subpath. Anchor-scoped edits such as Corner Radius, Move and Delete then acted on points the user had not picked. The command now remaps the selection with the path in the same undo step: in a reversed subpath of n anchors, anchor i becomes n - 1 - i, segment j becomes n - 2 - j, and a closed subpath's closing segment stays its closing segment. The key anchor follows its point too. Subpaths that do not turn keep their indices. --- crates/engine/src/cmd/path.rs | 107 +++++++++++++++++--------- crates/engine/src/tests/attributes.rs | 70 +++++++++++++++++ 2 files changed, 142 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index d989e0da00..f5fe3e72cc 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1073,45 +1073,82 @@ fn reverse(s: &mut Session, p: &Value) -> Result { None => path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect(), } }; - let changed = super::overprint::edit_counted(s, "Reverse Path Direction", |d| { - // A compound path's own strokes run along its members' subpaths in order, so they turn - // with them, read before any member turns. - let compounds: BTreeSet = ids.iter().map(|id| compound_or_self(d, *id)).filter(|c| ids.binary_search(c).is_err()).collect(); - for c in compounds { - let Some(NodeKind::Compound { children, .. }) = d.node(c).map(|n| &n.kind) else { continue }; - let flip: Vec = children - .iter() - .filter_map(|m| m.path_data().map(|pd| if ids.binary_search(&m.id).is_ok() { flip_of(pd) } else { vec![false; pd.subpaths.len()] })) - .flatten() - .collect(); - if flip.contains(&true) - && let Some(n) = d.node_mut(c) - { - vectorcraft_doc::blend::reverse_stroke_records(n, &flip); + let mut d = (*s.doc()?.doc).clone(); + // A compound path's own strokes run along its members' subpaths in order, so they turn + // with them, read before any member turns. + let compounds: BTreeSet = ids.iter().map(|id| compound_or_self(&d, *id)).filter(|c| ids.binary_search(c).is_err()).collect(); + for c in compounds { + let Some(NodeKind::Compound { children, .. }) = d.node(c).map(|n| &n.kind) else { continue }; + let flip: Vec = children + .iter() + .filter_map(|m| m.path_data().map(|pd| if ids.binary_search(&m.id).is_ok() { flip_of(pd) } else { vec![false; pd.subpaths.len()] })) + .flatten() + .collect(); + if flip.contains(&true) + && let Some(n) = d.node_mut(c) + { + vectorcraft_doc::blend::reverse_stroke_records(n, &flip); + } + } + let mut turned = Vec::new(); + for id in &ids { + let path = path_mut(&mut d, *id)?; + let flip = flip_of(path); + if !flip.contains(&true) { + continue; + } + // The stroke's width profile and pen recordings turn with the path, read before it turns. + if let Some(n) = d.node_mut(*id) { + vectorcraft_doc::blend::reverse_stroke_records(n, &flip); + } + let path = path_mut(&mut d, *id)?; + for (sp, f) in path.subpaths.iter_mut().zip(&flip) { + if *f { + sp.reverse(); } } - let mut changed = 0; - for id in &ids { - let path = path_mut(d, *id)?; - let flip = flip_of(path); - if !flip.contains(&true) { - continue; - } - // The stroke's width profile and pen recordings turn with the path, read before it turns. - if let Some(n) = d.node_mut(*id) { - vectorcraft_doc::blend::reverse_stroke_records(n, &flip); - } - let path = path_mut(d, *id)?; - for (sp, f) in path.subpaths.iter_mut().zip(flip) { - if f { - sp.reverse(); + turned.push((*id, flip)); + } + if !turned.is_empty() { + s.edit("Reverse Path Direction", |doc, sel| { + *doc = d; + for (id, flip) in &turned { + if let Some(path) = doc.node(*id).and_then(Node::path_data) { + reverse_selected_anchors(sel, *id, path, flip); } } - changed += 1; - } - Ok(changed) - })?; - Ok(json!({ "changed": changed })) + Ok(()) + })?; + } + Ok(json!({ "changed": turned.len() })) +} + +/// Point the selected anchors, selected segments and key anchor of `sel` on path `id` at the same +/// points after the subpaths of `path` marked in `flip` were reversed ([`SubPath::reverse`]). In a +/// reversed subpath of `n` anchors, anchor `i` becomes anchor `n - 1 - i` and segment `j` becomes +/// segment `n - 2 - j`; a closed subpath's closing segment (`n - 1`) stays its closing segment. +fn reverse_selected_anchors(sel: &mut Selection, id: NodeId, path: &PathData, flip: &[bool]) { + let reversed = |si: usize| path.subpaths.get(si).filter(|_| flip.get(si) == Some(&true)).map(|sp| (sp.anchors.len(), sp.closed)); + let anchor = |(si, ai): AnchorRef| match reversed(si) { + Some((n, _)) if ai < n => (si, n - 1 - ai), + _ => (si, ai), + }; + let segment = |(si, j): SegmentRef| match reversed(si) { + Some((n, true)) if j < n => (si, (2 * n - 2 - j) % n), + Some((n, false)) if j < n.saturating_sub(1) => (si, n - 2 - j), + _ => (si, j), + }; + if let Some(set) = sel.anchors.get_mut(&id) { + *set = set.iter().map(|r| anchor(*r)).collect(); + } + if let Some(set) = sel.segments.get_mut(&id) { + *set = set.iter().map(|r| segment(*r)).collect(); + } + if let Some((key, r)) = sel.key_anchor + && key == id + { + sel.key_anchor = Some((id, anchor(r))); + } } /// First and last anchor points of a subpath. diff --git a/crates/engine/src/tests/attributes.rs b/crates/engine/src/tests/attributes.rs index 35dda8656b..9af2662852 100644 --- a/crates/engine/src/tests/attributes.rs +++ b/crates/engine/src/tests/attributes.rs @@ -180,6 +180,76 @@ fn reverse_path_direction_on_and_off_set_the_winding() { assert!(s.execute("path.reverse", &json!({})).is_err(), "nothing to reverse"); } +/// Points of what is direct-selected on one path, rounded to whole points. +#[derive(Debug, PartialEq)] +struct Picked { + /// The selected anchors' points, sorted. + anchors: Vec<(i64, i64)>, + /// The end points of the selected segments, each pair and the list sorted. + segments: Vec<[(i64, i64); 2]>, + /// The key anchor's point, when the key anchor is on the path. + key: Option<(i64, i64)>, +} + +/// What is direct-selected on path `id`, as points. +fn picked_points(s: &Session, id: NodeId) -> Picked { + let st = s.doc().unwrap(); + let sp = &st.doc.node(id).unwrap().path_data().unwrap().subpaths; + let at = |(si, ai): (usize, usize)| { + let p = sp[si].anchors[ai].p; + (p.x.round() as i64, p.y.round() as i64) + }; + let mut anchors: Vec<_> = st.selection.anchors.get(&id).into_iter().flatten().map(|r| at(*r)).collect(); + anchors.sort_unstable(); + let mut segments: Vec<_> = st + .selection + .segments + .get(&id) + .into_iter() + .flatten() + .map(|&(si, j)| { + let mut ends = [at((si, j)), at((si, (j + 1) % sp[si].anchors.len()))]; + ends.sort_unstable(); + ends + }) + .collect(); + segments.sort_unstable(); + let key = st.selection.key_anchor.filter(|(k, _)| *k == id).map(|(_, r)| at(r)); + Picked { anchors, segments, key } +} + +#[test] +fn reverse_path_direction_keeps_the_same_anchors_and_segments_direct_selected() { + let mut s = session(); + let path = |s: &mut Session, anchors: Value, closed: bool| { + NodeId(run(s, "path.create", json!({"anchors": anchors, "closed": closed}))["id"].as_u64().unwrap()) + }; + let open = path(&mut s, json!([{"x": 0, "y": 50}, {"x": 40, "y": 50}, {"x": 100, "y": 50}]), false); + let closed = path(&mut s, json!([{"x": 10, "y": 10}, {"x": 90, "y": 10}, {"x": 90, "y": 90}, {"x": 10, "y": 90}]), true); + run(&mut s, "select.anchorsMany", json!({"items": [{"id": open.0, "anchors": [[0, 0]]}, {"id": closed.0, "anchors": [[0, 1], [0, 2]]}]})); + run(&mut s, "select.key", json!({"id": closed.0, "anchor": [0, 1]})); + let before = [picked_points(&s, open), picked_points(&s, closed)]; + assert_eq!(before[0].anchors, [(0, 50)]); + assert_eq!((before[1].anchors.clone(), before[1].key), (vec![(90, 10), (90, 90)], Some((90, 10)))); + assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 2); + let first = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[0].p; + assert_eq!((first(&s, open).x, first(&s, closed).y), (100.0, 90.0), "both paths turned"); + assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "the same points stay direct-selected after Reverse Path Direction"); + // Undo turns the paths back with the selection they had. + run(&mut s, "edit.undo", json!({})); + assert_eq!(first(&s, open).x, 0.0); + assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "undo"); + + // Selected segments, the closing segment of a closed path included, stay the same segments. + run(&mut s, "select.segments", json!({"id": closed.0, "segments": [[0, 0], [0, 3]], "mode": "set"})); + run(&mut s, "select.segments", json!({"id": open.0, "segments": [[0, 0]], "mode": "add"})); + let before = [picked_points(&s, open), picked_points(&s, closed)]; + assert_eq!(before[0].segments, [[(0, 50), (40, 50)]]); + assert_eq!(before[1].segments, [[(10, 10), (10, 90)], [(10, 10), (90, 10)]]); + assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 2); + assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "the same segments stay selected after Reverse Path Direction"); +} + #[test] fn reverse_path_direction_turns_the_width_profile_and_pen_records_with_the_path() { use vectorcraft_doc::{AngleProfile, PressureProfile, WidthProfile}; From 04ea00461d352dd99e8a2b91184ab7aeeb0f7422 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 12:57:57 -0800 Subject: [PATCH 18/56] Docs: removeAll refuses only when deleting empties an effect's clip region The refusal for a live geometry effect applies when deleting the paths turns a non-empty clipping region into an empty one. A region the effect already left empty does not count as that change. --- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 8aeb1d5dfe..c30457e1f2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3298,7 +3298,7 @@ through `$`: or layer that keeps other objects that are not ruler guides. `removeAll()` on the `pathItems` of a compound path that is such a clipping path throws the same way, since it would leave the clipping path empty. The document's `pathItems.removeAll()` still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then - clips. A visible image or placed document inside that group keeps it clipping by its frame too, when the frame encloses an area. When a live geometry effect, such as an Offset Path inset, leaves no clipping region once the paths are deleted, `removeAll()` throws and deletes nothing. Text beside the clipping path in the clipping group does not count. Hidden text, text + clips. A visible image or placed document inside that group keeps it clipping by its frame too, when the frame encloses an area. When deleting the paths makes a live geometry effect, such as an Offset Path inset, leave no clipping region where there was one before, `removeAll()` throws and deletes nothing. A region that the effect already left empty before the call does not count as such a change; the call still throws when no clipping geometry stays in the mask. Text beside the clipping path in the clipping group does not count. Hidden text, text in a hidden group, blank text without a list marker, area text too short for its first line, and text that a clipping group nested in the mask clips do not keep it clipping, so `removeAll()` then throws and deletes nothing. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a9196c2a32..5857b58b46 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1122,7 +1122,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips, and the same holds for a visible image or placed document whose frame encloses an area, unless a live geometry effect then leaves no clipping region; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips, and the same holds for a visible image or placed document whose frame encloses an area, unless deleting the paths makes a live geometry effect leave no clipping region where there was one before; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error, and so does a `groupItems.removeAll()` or `compoundPathItems.removeAll()` that would leave an image at the bottom of such a group. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From bb8e15797b0469c72fc0ae4d88a4b36f1c442401 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 15:32:09 -0800 Subject: [PATCH 19/56] Paths: Add Anchor Point keeps the key anchor on its point renumber_after_insert numbered the direct-selected anchors and segments after a new anchor one higher but left the key anchor's index as it was, so after Add Anchor Point before the key anchor the key named the point before it. The key anchor now moves with the other anchors. Also adds a test that Reverse Path Direction on one subpath leaves the other subpath's selection unchanged. --- crates/engine/src/cmd/path.rs | 13 ++++++++++-- crates/engine/src/tests/attributes.rs | 30 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index f5fe3e72cc..a805105ef0 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -2430,8 +2430,9 @@ fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f shares } -/// After an anchor is added at `(si, added)` of path `id`, number the direct-selected anchors and -/// selected segments after it on that subpath one higher, so the selection keeps the same points. +/// After an anchor is added at `(si, added)` of path `id`, number the direct-selected anchors, +/// selected segments and key anchor after it on that subpath one higher, so the selection keeps +/// the same points. /// A selected segment that the new anchor splits stays selected as its two halves, and the new /// anchor joins its ends in the anchors that move with it. fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usize) { @@ -2440,6 +2441,14 @@ fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usiz // renumbering saturates instead of overflowing. *set = set.iter().map(|&(s, a)| if s == si && a >= added { (s, a.saturating_add(1)) } else { (s, a) }).collect(); } + // The key anchor moves along with the anchors after the new one. + if let Some((key, (s, a))) = sel.key_anchor + && key == id + && s == si + && a >= added + { + sel.key_anchor = Some((id, (s, a.saturating_add(1)))); + } let split = added.checked_sub(1); if sel.segments.get(&id).is_some_and(|set| split.is_some_and(|g| set.contains(&(si, g)))) { sel.anchors.entry(id).or_default().insert((si, added)); diff --git a/crates/engine/src/tests/attributes.rs b/crates/engine/src/tests/attributes.rs index 9af2662852..80ad05cb01 100644 --- a/crates/engine/src/tests/attributes.rs +++ b/crates/engine/src/tests/attributes.rs @@ -250,6 +250,36 @@ fn reverse_path_direction_keeps_the_same_anchors_and_segments_direct_selected() assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "the same segments stay selected after Reverse Path Direction"); } +#[test] +fn reverse_path_direction_of_one_subpath_leaves_the_others_selection_as_it_is() { + let mut s = session(); + let id = NodeId(run(&mut s, "path.create", json!({"d": "M0 0 L40 0 L100 0 M0 200 L40 200 L100 200"}))["id"].as_u64().unwrap()); + run(&mut s, "select.anchorsMany", json!({"items": [{"id": id.0, "anchors": [[0, 0], [1, 0]]}]})); + run(&mut s, "select.key", json!({"id": id.0, "anchor": [0, 0]})); + let before = picked_points(&s, id); + assert_eq!((before.anchors.clone(), before.key), (vec![(0, 0), (0, 200)], Some((0, 0)))); + assert_eq!(run(&mut s, "path.reverse", json!({"subpath": 1}))["changed"], 1); + let first = |s: &Session, si: usize| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[si].anchors[0].p; + assert_eq!((first(&s, 0).x, first(&s, 1).x), (0.0, 100.0), "only the second subpath turned"); + assert_eq!(picked_points(&s, id), before, "the same points stay direct-selected on both subpaths"); +} + +#[test] +fn add_anchor_point_keeps_the_key_anchor_on_its_point() { + let mut s = session(); + let anchors = json!([{"x": 10, "y": 10}, {"x": 90, "y": 10}, {"x": 90, "y": 90}, {"x": 10, "y": 90}]); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": anchors, "closed": true}))["id"].as_u64().unwrap()); + run(&mut s, "select.anchorsMany", json!({"items": [{"id": id.0, "anchors": [[0, 1], [0, 2]]}]})); + run(&mut s, "select.key", json!({"id": id.0, "anchor": [0, 2]})); + let before = picked_points(&s, id); + assert_eq!((before.anchors.clone(), before.key), (vec![(90, 10), (90, 90)], Some((90, 90)))); + run(&mut s, "path.insertAnchor", json!({"id": id.0, "segment": 0})); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.len(), 5); + assert_eq!(picked_points(&s, id), before, "the key anchor and the selected anchors stay on their points after Add Anchor Point"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(picked_points(&s, id), before, "undo"); +} + #[test] fn reverse_path_direction_turns_the_width_profile_and_pen_records_with_the_path() { use vectorcraft_doc::{AngleProfile, PressureProfile, WidthProfile}; From 42f4dddec8683322234ae213a8f0702ce2c93246 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 16:00:39 -0800 Subject: [PATCH 20/56] File formats: JPEG files named .jpe open and place File > Open and File > Place now list and read JPEG files with the .jpe extension, like .jpg and .jpeg, in any letter case. The "All readable files", "All placeable files" and JPEG filters include .jpe, and a .jpe file dropped on the window opens as JPEG. Exports still write only .jpg and .jpeg, and the desktop packaging declares no type for .jpe. Supported formats for Open and Place list .jpg, .jpe and .jpeg for JPEG: https://helpx.adobe.com/illustrator/kb/supported-file-formats-illustrator.html Docs: docs/mcp.md, docs/file-format-parity.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/formats.rs | 26 +++++++++++--------- crates/engine/src/cmd/fileio/tests_jpeg.rs | 28 +++++++++++++++++++++- docs/file-format-parity.md | 2 +- docs/mcp.md | 2 +- docs/target-app-parity.md | 1 + 5 files changed, 45 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index f8da5b941c..e96bfadc23 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -579,6 +579,7 @@ pub const OPEN_EXTS: &[&str] = &[ "pns", "jpg", "jpeg", + "jpe", "gif", "webp", "tif", @@ -630,14 +631,15 @@ pub const OPEN_EXTS: &[&str] = &[ /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to /// raster editors, so Finder and file managers don't offer a vector app for them, and there is no -/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of -/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS -/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. +/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib`, `.rle` and `.jpe` +/// names of PNG, BMP and JPEG files (File › Open and Place still read them all). On Linux the desktop +/// entry's EPS and JPEG types (shared-mime-info's) also cover `.epsf` and `.jpe`, so file managers +/// offer VectorCraft for them. /// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft` /// documents or DWG drawings either. pub const UNASSOCIATED_EXTS: &[&str] = &[ - "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", + "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "jpe", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", + "jpc", "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -682,6 +684,7 @@ pub const PLACE_EXTS: &[&str] = &[ "pns", "jpg", "jpeg", + "jpe", "gif", "webp", "tif", @@ -735,13 +738,14 @@ pub const PLACE_EXTS: &[&str] = &[ "doc", ]; -/// The extensions File › Open and Place read PNG, BMP and Photoshop files by: the format's own, -/// then the other names its files have (`.pns`, `.dib` and `.rle`, `.pdd`). Exports write only -/// the format's own extension. -const READ_ALIASES: &[(&str, &[&str])] = &[("png", &["png", "pns"]), ("bmp", &["bmp", "dib", "rle"]), ("psd", &["psd", "pdd"])]; +/// The extensions File › Open and Place read PNG, JPEG, BMP and Photoshop files by: the format's +/// own, then the other names its files have (`.pns`, `.jpe`, `.dib` and `.rle`, `.pdd`). Exports +/// write only the format's own extensions. +const READ_ALIASES: &[(&str, &[&str])] = + &[("png", &["png", "pns"]), ("jpg", &["jpg", "jpeg", "jpe"]), ("bmp", &["bmp", "dib", "rle"]), ("psd", &["psd", "pdd"])]; -/// The extensions File › Open and Place read format `f` by: its own, and for PNG, BMP and PSD -/// those of [`READ_ALIASES`]. +/// The extensions File › Open and Place read format `f` by: its own, and for PNG, JPEG, BMP and +/// PSD those of [`READ_ALIASES`]. pub fn read_extensions(f: &Format) -> &'static [&'static str] { READ_ALIASES.iter().find(|(id, _)| *id == f.id).map_or(f.extensions, |(_, exts)| *exts) } diff --git a/crates/engine/src/cmd/fileio/tests_jpeg.rs b/crates/engine/src/cmd/fileio/tests_jpeg.rs index 2e3c0d156c..7e27c15cc6 100644 --- a/crates/engine/src/cmd/fileio/tests_jpeg.rs +++ b/crates/engine/src/cmd/fileio/tests_jpeg.rs @@ -1,4 +1,5 @@ -//! JPEG Options: colour model, coding method, scans, profile and image maps. +//! JPEG Options: colour model, coding method, scans, profile and image maps; JPEG files named +//! `.jpe` open and place. use serde_json::{Value, json}; @@ -87,3 +88,28 @@ fn image_maps_list_the_objects_with_a_url() { // One file only: Export for Screens can't add the map. assert!(s.execute("document.exportForScreens", &json!({"formats": [{"format": "jpg", "imageMap": "client"}]})).is_err()); } + +/// JPEG files named `.jpe` open and place as JPEG, in any case; the dialogs and a drop on the +/// window take them by their extension, the desktop packaging doesn't associate them, and exports +/// still write `.jpg`. +#[test] +fn jpe_files_open_and_place() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let jpg = b64(&s.execute("document.export", &json!({"format": "jpg"})).unwrap()); + let data = vectorcraft_format::base64_encode(&jpg); + for name in ["art.jpe", "ART.JPE"] { + assert_eq!(readable_format_for_name(name).map(|f| f.id), Some("jpg"), "{name}"); + let r = s.execute("document.open", &json!({"name": name, "dataBase64": data})).unwrap(); + assert_eq!((&r["format"], &r["warnings"]), (&json!("jpg"), &json!([])), "{name}: {r}"); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + let r = s.execute("file.place", &json!({"name": name, "dataBase64": data})).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("jpg"), Some(1)), "{name}: {r}"); + } + assert!(OPEN_EXTS.contains(&"jpe") && PLACE_EXTS.contains(&"jpe") && UNASSOCIATED_EXTS.contains(&"jpe")); + let jpeg = ("JPEG", &["jpg", "jpeg", "jpe"][..]); + assert!(open_filters().any(|f| f == jpeg) && place_filters().any(|f| f == jpeg)); + assert!(!export_extensions().contains(&"jpe")); + assert!(format_for_name("x.jpe").is_none() && writable_format(None, Some("x.jpe")).is_err()); + assert!(s.execute("document.export", &json!({"path": "x.jpe"})).is_err()); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 31f0da4316..0502f56e72 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -377,7 +377,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` | | PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | | PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | | -| PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | +| PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; JPEG: `.jpg`, `.jpeg` and `.jpe`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | | WebP | export (Export for Screens) | yes | yes (lossless by default; `lossless: false` writes lossy WebP at `quality` 0–100, default 90) | lossy files are `VP8 `, with an `ALPH` chunk when some pixels are not opaque; `tests_text.rs` | | JPEG XL `.jxl` | — | yes (first frame; 16-bit and floating-point samples as 8 bits, alpha kept; CMYK refused) | no | decoded with jxl-oxide; the size is checked from the header before decoding; container Exif resolution sizes opened and placed images; tests in `crates/engine/src/cmd/fileio/tests_jxlread.rs` and `crates/engine/tests/import_fuzz.rs` | | HEIC / HEIF | open, place | yes (HEVC-coded still images: single pictures and grids of tiles, 8 to 10 bits, with an alpha image; image sequences, other codings and grids of cropped tiles are refused) | no | `.heic`, `.heif`; decoded by heic-rs in the engine's default `heif` feature (a build without it refuses the files with a message); the container's rotation, mirror and crop are applied; without an `nclx` box the HEVC stream's video signal type gives the matrix and range; an RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; EXIF resolution tags size the image, or 72 ppi; bounded decoding; `tests_heifread.rs` | diff --git a/docs/mcp.md b/docs/mcp.md index 9c5f1bc38b..5d60be4279 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -870,7 +870,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). The app refuses `attributes.openUrl`, `file.export.svg.browser`, `file.saveForWeb.browser` and `file.showPackage` for every control and MCP request, since each opens another app, so the headless error for them does not suggest `--connect`. | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. | -| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | +| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG (`.jpg`/`.jpeg`/`.jpe`), GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error; versions 1 to 3 get each live star as a plain path of its outline, without its point count and ratio), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1bba3d826..c81ce30c04 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2531,6 +2531,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). + - JPEG files named `.jpe` open and place as JPEG files, in any letter case, as the [supported file formats](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html) page lists for Open and Place: the Open and Place dialogs list them with `.jpg` and `.jpeg`, and a file dropped on the window opens. Exports write only `.jpg` and `.jpeg` (`crates/engine/src/cmd/fileio/tests_jpeg.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers, nor a layer or group whose layer mask hides all of it) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings; a clip, or a merge for another layer, that one with a layer mask too large to read is part of goes on without it (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From d3d6e81975db5b13276ac56c2ab9df89f1e9d90e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 16:12:00 -0800 Subject: [PATCH 21/56] Targa export: a Color Model option writes grayscale files Targa Options gets a Color Model menu, RGB or Grayscale, and `document.export` takes it as `colorModel` (`rgb` or `gray`, as BMP does). Grayscale writes an uncompressed grayscale file (image type 3) at 8 bits per pixel, flattened on white, or 16 bits with an 8-bit alpha; omitting `depth` with `gray` gives 8 bits. `cmyk`, an unknown model and a grayscale depth of 24 or 32 bits are refused with an error. Switching the model in the dialog moves a depth the new model lacks to that model's default. The transparency rule of the dialog's background list now follows the depth: 16 and 32 bits keep transparency, 8 and 24 bits are flattened. Docs: docs/mcp.md, docs/control-protocol.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/encode.rs | 9 ++-- crates/engine/src/cmd/fileio/formats.rs | 8 ++- crates/engine/src/cmd/fileio/tests_tiffbmp.rs | 34 +++++++++++- crates/render/src/encode/tests_tga.rs | 30 +++++++++-- crates/render/src/encode/tga.rs | 54 +++++++++++++------ crates/ui-egui/src/dialogs/png_options.rs | 6 ++- .../ui-egui/src/dialogs/tests_tiff_bmp_tga.rs | 27 +++++++++- crates/ui-egui/src/dialogs/tiff_bmp_tga.rs | 36 ++++++++++--- docs/control-protocol.md | 7 +-- docs/mcp.md | 5 +- docs/target-app-parity.md | 1 + 11 files changed, 177 insertions(+), 40 deletions(-) diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 96e5d2210f..42dc278e30 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -388,7 +388,10 @@ impl RasterOptions { top_down: self.flip_rows.unwrap_or(false), gray: color_model == jpeg::ColorModel::Gray, }, - tga: tga::TgaOptions { depth: self.depth.unwrap_or(24) }, + tga: { + let gray = color_model == jpeg::ColorModel::Gray; + tga::TgaOptions { depth: self.depth.unwrap_or_else(|| tga::TgaOptions::default_depth(gray)), gray } + }, psd: psd::PsdOptions { color_model, layers: self.layers.unwrap_or(true), @@ -412,12 +415,12 @@ fn bmp_layout(s: &str) -> Option { } /// Refuse options `format` can't write together: BMP and Targa depths and layouts, and colour -/// models (BMP is RGB or grey, Targa RGB). +/// models (BMP and Targa are RGB or grey). fn check_options(format: RasterFormat, o: &RasterExportOptions) -> Result<()> { let model = o.jpeg.color_model; let r = match format { RasterFormat::Bmp if model == jpeg::ColorModel::Cmyk => Err("BMP files are RGB or grayscale: colorModel rgb or gray".to_string()), - RasterFormat::Tga if model != jpeg::ColorModel::Rgb => Err("Targa files are RGB: colorModel rgb".to_string()), + RasterFormat::Tga if model == jpeg::ColorModel::Cmyk => Err("Targa files are RGB or grayscale: colorModel rgb or gray".to_string()), RasterFormat::Psd if o.psd.preserve_text && !o.psd.layers => Err("preserveText writes type layers: it needs layers: true".to_string()), RasterFormat::Bmp => o.bmp.check(), RasterFormat::Tga => o.tga.check(), diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index f8da5b941c..feea9d5478 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -315,14 +315,18 @@ const BMP_OPTIONS: &[FormatOption] = &[ DITHER_AMOUNT, ]; +const TGA_COLOR_MODEL: FormatOption = + FormatOption { name: "colorModel", ty: "string", default: "\"rgb\"", description: "rgb (true color) or gray (grayscale)" }; + const TGA_DEPTH: FormatOption = FormatOption { name: "depth", ty: "integer", default: "24", - description: "bits per pixel: 16 (one-bit alpha), 24 (flattened on white) or 32 (keeps transparency)", + description: "bits per pixel: with rgb 16 (one-bit alpha), 24 (flattened on white) or 32 (keeps transparency); with gray 8 (the default, flattened on white) or 16 (keeps transparency)", }; -const TGA_OPTIONS: &[FormatOption] = &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, TGA_DEPTH]; +const TGA_OPTIONS: &[FormatOption] = + &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, TGA_COLOR_MODEL, TGA_DEPTH]; const PSD_LAYERS: FormatOption = FormatOption { name: "layers", diff --git a/crates/engine/src/cmd/fileio/tests_tiffbmp.rs b/crates/engine/src/cmd/fileio/tests_tiffbmp.rs index 74df5216aa..9a00ad28e0 100644 --- a/crates/engine/src/cmd/fileio/tests_tiffbmp.rs +++ b/crates/engine/src/cmd/fileio/tests_tiffbmp.rs @@ -138,8 +138,38 @@ fn targa_depth_reaches_the_file() { } let tga = export(&mut s, json!({"format": "tga"})); assert_eq!(tga[16], 24, "24 bits by default"); - for bad in [json!({"depth": 8}), json!({"colorModel": "gray"})] { - assert!(s.execute("document.export", &merge(json!({"format": "tga"}), bad.clone())).is_err(), "{bad}"); + for bad in [ + json!({"depth": 8}), + json!({"colorModel": "cmyk"}), + json!({"colorModel": "lab"}), + json!({"colorModel": "gray", "depth": 24}), + json!({"colorModel": "gray", "depth": 32}), + ] { + let e = s.execute("document.export", &merge(json!({"format": "tga"}), bad.clone())).unwrap_err(); + assert!(matches!(e, EngineError::BadParams { .. }), "{bad}: {e}"); + } +} + +#[test] +fn targa_color_model_gray_writes_grayscale() { + let mut s = session(); + let gray = export(&mut s, json!({"format": "tga", "colorModel": "gray"})); + assert_eq!((gray[2], gray[16], gray[17]), (3, 8, 0), "grayscale, 8 bits by default, no alpha"); + let img = image::load_from_memory_with_format(&gray, image::ImageFormat::Tga).unwrap().to_rgba8(); + assert_eq!(img.dimensions(), (60, 40)); + assert_eq!(img.get_pixel(5, 5).0, [255; 4], "flattened on white"); + let black = img.get_pixel(40, 20).0; + assert!(black[0] == black[1] && black[1] == black[2] && black[0] < 80, "{black:?}"); + + let alpha = export(&mut s, json!({"format": "tga", "colorModel": "gray", "depth": 16})); + assert_eq!((alpha[2], alpha[16], alpha[17]), (3, 16, 8), "grayscale with an 8-bit alpha"); + let img = image::load_from_memory_with_format(&alpha, image::ImageFormat::Tga).unwrap().to_rgba8(); + assert_eq!(img.get_pixel(5, 5).0[3], 0, "transparent where nothing is drawn"); + assert_eq!(img.get_pixel(40, 20).0[3], 255); + + for file in [gray, alpha] { + let r = s.execute("document.open", &json!({"name": "back.tga", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap(); + assert_eq!(r["format"], "tga"); } } diff --git a/crates/render/src/encode/tests_tga.rs b/crates/render/src/encode/tests_tga.rs index 2851a25873..823d53cd82 100644 --- a/crates/render/src/encode/tests_tga.rs +++ b/crates/render/src/encode/tests_tga.rs @@ -1,4 +1,4 @@ -//! Targa export: depths, alpha and the footer. +//! Targa export: depths, grayscale, alpha and the footer. use super::on_white; use super::tests_bmp::{art, decode, u16_at}; @@ -9,7 +9,7 @@ fn targa_depths_alpha_and_footer() { let (w, h) = (7, 3); let px = art(w, h); for (depth, alpha_bits) in [(16, 1), (24, 0), (32, 8)] { - let file = tga::encode(&px, w, h, &TgaOptions { depth }).unwrap(); + let file = tga::encode(&px, w, h, &TgaOptions { depth, gray: false }).unwrap(); assert_eq!((file[2], file[16], file[17]), (2, depth, alpha_bits), "true colour, the depth byte, alpha bits"); assert_eq!((u16_at(&file, 12), u16_at(&file, 14)), (7, 3)); assert_eq!(file.len(), 18 + (w * h) as usize * usize::from(depth / 8) + 26); @@ -25,6 +25,30 @@ fn targa_depths_alpha_and_footer() { _ => {} } } - assert!(tga::encode(&px, w, h, &TgaOptions { depth: 8 }).is_err()); + assert!(tga::encode(&px, w, h, &TgaOptions { depth: 8, gray: false }).is_err()); assert!(tga::encode(&px, 70_000, 1, &TgaOptions::default()).is_err(), "too wide"); } + +/// Grayscale Targa files are image type 3: 8 bits flattened on white, or 16 with an 8-bit alpha. +#[test] +fn targa_grayscale_writes_lightness() { + let (w, h) = (7, 3); + let px = art(w, h); + for (depth, alpha_bits) in [(8, 0), (16, 8)] { + let file = tga::encode(&px, w, h, &TgaOptions { depth, gray: true }).unwrap(); + assert_eq!((file[2], file[16], file[17]), (3, depth, alpha_bits), "grayscale, the depth byte, alpha bits"); + assert_eq!(file.len(), 18 + (w * h) as usize * usize::from(depth / 8) + 26); + let img = decode(&file, craft_image_codecs::Format::Tga); + assert_eq!(img.dimensions(), (w, h)); + // (0, 2) is opaque red 230, 40, 30: Rec. 601 lightness 96, the same in every channel. + let [r, g, b, a] = img.get_pixel(0, 2).0; + assert!(r == g && g == b && r.abs_diff(96) <= 1 && a == 255, "depth {depth}: {:?}", [r, g, b, a]); + match depth { + 8 => assert_eq!(img.get_pixel(0, 0).0, [255; 4], "flattened on white"), + _ => assert_eq!((img.get_pixel(0, 0).0[3], img.get_pixel(1, 0).0[3]), (0, 128), "8-bit alpha"), + } + } + for depth in [24, 32] { + assert!(tga::encode(&px, w, h, &TgaOptions { depth, gray: true }).is_err(), "{depth} bits gray"); + } +} diff --git a/crates/render/src/encode/tga.rs b/crates/render/src/encode/tga.rs index 031b5f1b61..94cee10461 100644 --- a/crates/render/src/encode/tga.rs +++ b/crates/render/src/encode/tga.rs @@ -1,33 +1,55 @@ //! Targa export: uncompressed true colour at 16 bits per pixel (5-5-5 and a one-bit alpha), 24 or -//! 32 (8-bit alpha), rows bottom-up, with the version 2 footer. +//! 32 (8-bit alpha), or uncompressed grayscale at 8 bits or 16 (8-bit alpha), rows bottom-up, with +//! the version 2 footer. use super::on_white; +use super::quantize::luma; -/// Bits per pixel a Targa export can have. +/// Bits per pixel a true-colour Targa export can have. pub const DEPTHS: [u8; 3] = [16, 24, 32]; +/// Bits per pixel a grayscale Targa export can have. +pub const GRAY_DEPTHS: [u8; 2] = [8, 16]; + /// The Targa options of a raster export. #[derive(Clone, Debug, PartialEq)] pub struct TgaOptions { - /// Bits per pixel ([`DEPTHS`]). + /// Bits per pixel ([`DEPTHS`], or [`GRAY_DEPTHS`] when `gray`). pub depth: u8, + /// Grayscale (image type 3) instead of true colour (image type 2). + pub gray: bool, } impl Default for TgaOptions { fn default() -> Self { - Self { depth: 24 } + Self { depth: Self::default_depth(false), gray: false } } } impl TgaOptions { + /// The depth a colour model starts with: 24 bits for true colour, 8 for grayscale. + pub fn default_depth(gray: bool) -> u8 { + if gray { 8 } else { 24 } + } + + /// The depths the colour model can be written at. + pub fn depths(gray: bool) -> &'static [u8] { + if gray { &GRAY_DEPTHS } else { &DEPTHS } + } + /// Why these options can't be written, if they can't. pub fn check(&self) -> Result<(), String> { - if DEPTHS.contains(&self.depth) { Ok(()) } else { Err(format!("Targa depth {}: 16, 24 or 32 bits per pixel", self.depth)) } + match (self.gray, Self::depths(self.gray).contains(&self.depth)) { + (_, true) => Ok(()), + (false, false) => Err(format!("Targa depth {}: 16, 24 or 32 bits per pixel", self.depth)), + (true, false) => Err(format!("grayscale Targa depth {}: 8 or 16 bits per pixel", self.depth)), + } } } -/// Straight-alpha RGBA pixels as a Targa file. 24 bits blend partly transparent pixels over white; -/// at 16 bits a pixel is opaque from half opacity up, else transparent. +/// Straight-alpha RGBA pixels as a Targa file. 24 bits and 8-bit grayscale blend partly +/// transparent pixels over white; at 16 bits true colour a pixel is opaque from half opacity up, +/// else transparent. pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result, String> { o.check()?; let (Ok(w16), Ok(h16)) = (u16::try_from(width), u16::try_from(height)) else { @@ -40,21 +62,23 @@ pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result().0; let mut out = Vec::with_capacity((w * h).saturating_mul(usize::from(o.depth / 8)).saturating_add(18 + 26)); - // No image id or colour map, uncompressed true colour, origin (0, 0). - out.extend([0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // No image id or colour map, uncompressed true colour (2) or grayscale (3), origin (0, 0). + out.extend([0, 0, if o.gray { 3 } else { 2 }, 0, 0, 0, 0, 0, 0, 0, 0, 0]); out.extend(w16.to_le_bytes()); out.extend(h16.to_le_bytes()); // Bits per pixel, then the alpha bits (rows bottom-up, left to right). - let alpha_bits = match o.depth { - 16 => 1, - 32 => 8, + let alpha_bits = match (o.gray, o.depth) { + (false, 16) => 1, + (true, 16) | (false, 32) => 8, _ => 0, }; out.extend([o.depth, alpha_bits]); for row in px.chunks(w).rev() { for p in row { - match o.depth { - 16 => { + match (o.gray, o.depth) { + (true, 8) => out.push(luma(on_white(p))), + (true, _) => out.extend([luma([p[0], p[1], p[2]]), p[3]]), + (false, 16) => { let v = if p[3] >= 128 { let [r, g, b] = [p[0], p[1], p[2]].map(|c| u16::from(c >> 3)); 0x8000 | r << 10 | g << 5 | b @@ -63,7 +87,7 @@ pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result { + (false, 24) => { let [r, g, b] = on_white(p); out.extend([b, g, r]); } diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 44990cf783..9a86efdb54 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -93,8 +93,10 @@ pub(crate) fn open_with(app: &mut VectorcraftApp, f: &Format, mut params: Value, let initial = fields_of(&raster_rows(id, false, size, &DialogFields::new()), &map); let dialog = HostedParamDialog::new(&ctx, key.clone(), initial, move |fields| { normalize_colors(fields); - if id == "bmp" { - tiff_bmp_tga::normalize_bmp(fields); + match id { + "bmp" => tiff_bmp_tga::normalize_bmp(fields), + "tga" => tiff_bmp_tga::normalize_tga(fields), + _ => {} } ParamDialog::new(key.clone(), heading(label), raster_rows(id, false, size, fields)).values(Bind::bound(fields)).ok_label(tl!("Export").into()) }); diff --git a/crates/ui-egui/src/dialogs/tests_tiff_bmp_tga.rs b/crates/ui-egui/src/dialogs/tests_tiff_bmp_tga.rs index 012c42705d..04e23c5d91 100644 --- a/crates/ui-egui/src/dialogs/tests_tiff_bmp_tga.rs +++ b/crates/ui-egui/src/dialogs/tests_tiff_bmp_tga.rs @@ -39,9 +39,32 @@ fn bmp_options_keep_their_choices_writable() { assert_eq!((&bmp[..2], bmp[28], bmp[30]), (&b"BM"[..], 8, 1), "8-bit RLE8"); } -/// Targa at 24 bits is flattened on white; its other depths keep transparency. +/// Targa at 24 bits, and grayscale at 8, is flattened on white; 16 and 32 bits keep transparency. #[test] -fn targa_keeps_transparency_above_24_bits() { +fn targa_keeps_transparency_at_16_and_32_bits() { assert!(!tiff_bmp_tga::keeps_alpha("tga", &DialogFields::from_pairs([("depth", "24")]))); assert!(tiff_bmp_tga::keeps_alpha("tga", &DialogFields::from_pairs([("depth", "32")]))); + assert!(!tiff_bmp_tga::keeps_alpha("tga", &DialogFields::from_pairs([("colorModel", "gray"), ("depth", "8")]))); + assert!(tiff_bmp_tga::keeps_alpha("tga", &DialogFields::from_pairs([("colorModel", "gray"), ("depth", "16")]))); +} + +/// Targa Options' Color Model writes a grayscale file, and a change of model moves the depth to +/// one that model has. +#[test] +fn targa_color_model_reaches_the_file() { + let (mut app, written) = app(1); + app.run("file.exportAs", json!({"format": "tga"})).unwrap(); + confirm(&mut app); + assert_eq!(kind(&app).as_deref(), Some("tgaOptions")); + let f = fields(&app); + assert_eq!((f.text("colorModel"), f.text("depth")), (Some("rgb"), Some("24"))); + frame(&mut app); + // Grayscale has no 24 bits: the depth moves to 8. + set(&mut app, "colorModel", json!("gray")); + frame(&mut app); + assert_eq!(fields(&app).text("depth"), Some("8")); + confirm(&mut app); + let (path, tga) = written.borrow()[0].clone(); + assert_eq!(path, "/out/Untitled-1.tga"); + assert_eq!((tga[2], tga[16]), (3, 8), "8-bit grayscale"); } diff --git a/crates/ui-egui/src/dialogs/tiff_bmp_tga.rs b/crates/ui-egui/src/dialogs/tiff_bmp_tga.rs index 9e70f59ee7..d969a2a8f6 100644 --- a/crates/ui-egui/src/dialogs/tiff_bmp_tga.rs +++ b/crates/ui-egui/src/dialogs/tiff_bmp_tga.rs @@ -1,5 +1,5 @@ //! The options of TIFF (colour model, byte order, LZW, profile), BMP (colour model, layout, depth, -//! palette, RLE, row order) and Targa (depth), after the raster export rows they share with PNG +//! palette, RLE, row order) and Targa (colour model, depth), after the raster export rows they share with PNG //! Options ([`super::png_options`]): the `tiffOptions`, `bmpOptions` and `tgaOptions` dialogs. use craft::ui::patterns::form_dialogs::{DialogFields, Param}; @@ -12,14 +12,15 @@ use vectorcraft_render::encode::tiff::{ByteOrder, TiffOptions}; use super::png_options::{check, choice}; -/// BMP colour models and layouts: param values and labels. +/// BMP and Targa colour models and BMP layouts: param values and labels. const BMP_MODELS: [&str; 2] = ["rgb", "gray"]; const BMP_MODEL_LABELS: [&str; 2] = ["RGB", "Grayscale"]; const LAYOUTS: [&str; 2] = ["windows", "os2"]; const LAYOUT_LABELS: [&str; 2] = ["Windows", "OS/2"]; -/// Labels of [`bmp::DEPTHS`] and [`tga::DEPTHS`]. +/// Labels of [`bmp::DEPTHS`], [`tga::DEPTHS`] and [`tga::GRAY_DEPTHS`]. const BMP_DEPTH_LABELS: [&str; 6] = ["1 bit", "4 bit", "8 bit", "16 bit", "24 bit", "32 bit"]; const TGA_DEPTH_LABELS: [&str; 3] = ["16 bits/pixel", "24 bits/pixel", "32 bits/pixel"]; +const TGA_GRAY_DEPTH_LABELS: [&str; 2] = ["8 bits/pixel", "16 bits/pixel"]; /// The options format `id` starts with (`cmyk`: a CMYK document exports CMYK TIFFs). pub(super) fn defaults(id: &str, cmyk: bool, o: &mut Map) { @@ -47,7 +48,8 @@ pub(super) fn defaults(id: &str, cmyk: bool, o: &mut Map) { ]); } "tga" => { - o.insert("depth".into(), json!(TgaOptions::default().depth.to_string())); + let t = TgaOptions::default(); + o.extend([("colorModel".into(), json!(BMP_MODELS[usize::from(t.gray)])), ("depth".into(), json!(t.depth.to_string()))]); } _ => {} } @@ -64,7 +66,7 @@ pub(super) fn keeps_alpha(id: &str, f: &DialogFields) -> bool { "jpg" => false, "tiff" => ColorModel::from_id(f.text("colorModel").unwrap_or_default()).unwrap_or_default() == ColorModel::Rgb, "bmp" => depth(f) == 32.0, - "tga" => depth(f) != 24.0, + "tga" => matches!(depth(f) as u8, 16 | 32), // A flat PSD is flattened; its layers keep transparency. "psd" => f.text("layers") == Some("true"), _ => true, @@ -81,11 +83,33 @@ pub(super) fn params(id: &str, fields: &DialogFields) -> Vec { check("embedIcc", tl!("Embed ICC Profile"), true), ], "bmp" => bmp_params(fields), - "tga" => vec![choice("depth", tl!("Depth:"), &tga::DEPTHS.map(|d| d.to_string()), &TGA_DEPTH_LABELS)], + "tga" => { + let depth = if tga_gray(fields) { + choice("depth", tl!("Depth:"), &tga::GRAY_DEPTHS.map(|d| d.to_string()), &TGA_GRAY_DEPTH_LABELS) + } else { + choice("depth", tl!("Depth:"), &tga::DEPTHS.map(|d| d.to_string()), &TGA_DEPTH_LABELS) + }; + vec![choice("colorModel", tl!("Color Model:"), &BMP_MODELS, &BMP_MODEL_LABELS), depth] + } _ => Vec::new(), } } +/// Does the Targa dialog hold the grayscale colour model? +fn tga_gray(f: &DialogFields) -> bool { + f.text("colorModel") == Some(BMP_MODELS[1]) +} + +/// Keep the Targa depth one the colour model has: a change of model starts the depth at that +/// model's default (24 bits for RGB, 8 for grayscale). +pub(super) fn normalize_tga(f: &mut DialogFields) { + let gray = tga_gray(f); + let bits = depth(f); + if !TgaOptions::depths(gray).iter().any(|d| f64::from(*d) == bits) { + f.set("depth", TgaOptions::default_depth(gray).to_string()); + } +} + fn bmp_params(fields: &DialogFields) -> Vec { let os2 = fields.text("fileFormat") == Some(LAYOUTS[1]); let depths = bmp::DEPTHS.map(|d| d.to_string()); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1180f20319..e70de287f0 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1005,9 +1005,10 @@ TIFF, BMP and Targa Options: Export As… with the TIFF, BMP or Targa format (`f the save dialog) opens `tiffOptions`, `bmpOptions` or `tgaOptions`: the raster rows of PNG Options (`ppi`, `background`, `antiAlias`), then TIFF's `colorModel` (`rgb`, `cmyk`, `gray`; a CMYK document starts on `cmyk`), `byteOrder` (`little`, `big`), `lzw` and `embedIcc`; BMP's `colorModel` (`rgb`, `gray`), `fileFormat` (`windows`, -`os2`), `depth` (1, 4, 8, 16, 24, 32), `reduction` and `dither` (4 and 8 bits), `rle` and `flipRows`; Targa's `depth` -(16, 24, 32). The BMP dialog keeps its choices writable together (OS/2 falls back to 24 bits and turns RLE and flipped -rows off; RLE turns flipped rows off). `ui.dialog.set` the fields and `ui.dialog.confirm` writes the file(s) with +`os2`), `depth` (1, 4, 8, 16, 24, 32), `reduction` and `dither` (4 and 8 bits), `rle` and `flipRows`; Targa's `colorModel` +(`rgb`, `gray`) and `depth` (16, 24, 32 for `rgb`; 8, 16 for `gray`). The BMP dialog keeps its choices writable together +(OS/2 falls back to 24 bits and turns RLE and flipped rows off; RLE turns flipped rows off), and the Targa dialog moves +a depth the new color model lacks to that model's default (24 bits, or 8 for `gray`). `ui.dialog.set` the fields and `ui.dialog.confirm` writes the file(s) with `document.export`. Save for Web: File → Export → Save for Web (Legacy)… (`file.saveForWeb`, Ctrl/Cmd+Alt+Shift+S) opens the `save-for-web` diff --git a/docs/mcp.md b/docs/mcp.md index 93dff42eba..77c64a5c25 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13455,8 +13455,9 @@ and `embedIcc` (sRGB, the working CMYK profile or grey). BMP takes `depth` (1 is palette chosen by `reduction` and `dither`; 16, 24, or 32, which keeps transparency), `colorModel` (`rgb` or `gray`), `fileFormat` (`windows` or `os2`: 1, 4, 8 or 24 bits only), `rle` (RLE4/RLE8 for 4- and 8-bit Windows bitmaps) and `flipRows` (rows top-down, a negative height; not with `rle` or `os2`); impossible combinations are refused. Targa -takes `depth`: 16 (a one-bit alpha), 24 (default) or 32 (with alpha). Formats and depths without alpha are flattened -on white. TIFF, BMP and Targa files open again (a 16-bit Targa file with its one-bit alpha); `document.formats` lists +takes `colorModel` (`rgb`, true color, or `gray`, grayscale) and `depth`: with `rgb` 16 (a one-bit alpha), 24 (default) +or 32 (with alpha); with `gray` 8 (default) or 16 (with alpha). Formats and depths without alpha are flattened on +white. TIFF, BMP and Targa files open again (a 16-bit Targa file with its one-bit alpha); `document.formats` lists every option. ```json diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bfccfd4a5a..aaeb9ca5bf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2531,6 +2531,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EPS export writes a linear or radial gradient of tints of one spot color (and paper white) in that ink's Separation space, at Level 2 and 3, and at Level 3 one that mixes a spot color with process or gray colors, or two spot colors, in a DeviceN space of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. At Level 2, such a mix is written in process colors with a warning. In an RGB export, a gradient that mixes a spot color with RGB or Lab colors is written without the spot ink, with a warning; a CMYK export converts those stops to CMYK first, and the gradient follows the rules above. A Perceptual gradient of spot colors, and a mix whose DeviceN space would need more than 32 inks or a spot color named Cyan, Magenta, Yellow or Black, are also written in process colors with a warning (`crates/eps/src/tests.rs`). A spot color named All or None (in a Separation space, the names of every plate and of no plate: [ISO 32000-1:2008](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf), 8.6.6.4), is written as the ink All Spot or None Spot (All Spot 2 and on when a spot swatch already has that name) in its fills, strokes, gradients and DSC comments; Registration still prints on every plate (`tests::spot_inks_named_all_or_none_are_written_under_names_of_their_own`). EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). + - Targa Options has a Color Model menu: RGB writes true color at 16, 24 or 32 bits per pixel, and Grayscale writes a grayscale file (image type 3) at 8 bits, flattened on white, or 16 bits with an 8-bit alpha. `document.export` takes it as `colorModel` (`rgb` or `gray`, as BMP does; `cmyk` is refused), and a grayscale depth of 24 or 32 bits is refused (`crates/render/src/encode/tests_tga.rs`, `crates/engine/src/cmd/fileio/tests_tiffbmp.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers, nor a layer or group whose layer mask hides all of it) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings; a clip, or a merge for another layer, that one with a layer mask too large to read is part of goes on without it (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). From caa950a772b821626e89c159a9055b1ea0326af6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 16:29:32 -0800 Subject: [PATCH 22/56] Docs: the earlier pathItems entry names the image exception to removeAll The layer and group pathItems entry described only the text exception, so it read as if removeAll threw when a clipping group kept a visible image. It now states the image and placed-document case and the live geometry effect limit, as the Document.pathItems entry does. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 21dafed596..8927addbf8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1119,7 +1119,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: `Document.rasterize` replaces page items with an embedded image and `Document.imageCapture` writes a PNG of the art or of an area of the page, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/ describe; `object.rasterize` takes `ids` and `clipBounds` for them (`docs/mcp.md`). `Document.windowCapture` is not there yet. `crates/engine/src/tests/script_raster_capture.rs`. - - Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.rs`. + - Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips, and the same holds for a visible image or placed document whose frame encloses an area, unless deleting the paths makes a live geometry effect leave no clipping region where there was one before; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.rs`. - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. From 7f47355dee46e42f122244643b3d0e4b054bd06b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 16:29:57 -0800 Subject: [PATCH 23/56] Docs: a dropped .jpe file is placed or opened as a dropped .jpg file is --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c81ce30c04..3ca1d8d720 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2531,7 +2531,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - - JPEG files named `.jpe` open and place as JPEG files, in any letter case, as the [supported file formats](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html) page lists for Open and Place: the Open and Place dialogs list them with `.jpg` and `.jpeg`, and a file dropped on the window opens. Exports write only `.jpg` and `.jpeg` (`crates/engine/src/cmd/fileio/tests_jpeg.rs`). + - JPEG files named `.jpe` open and place as JPEG files, in any letter case, as the [supported file formats](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html) page lists for Open and Place: the Open and Place dialogs list them with `.jpg` and `.jpeg`, and a dropped file is handled as a dropped `.jpg` file is: with a document open, a file dropped on the canvas, or dropped with no position, is placed in that document, and one dropped elsewhere on the window opens. Exports write only `.jpg` and `.jpeg` (`crates/engine/src/cmd/fileio/tests_jpeg.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers, nor a layer or group whose layer mask hides all of it) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings; a clip, or a merge for another layer, that one with a layer mask too large to read is part of goes on without it (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From ca20b965f2c8afb9f9da9987fa65a88ab04f432d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 16:31:32 -0800 Subject: [PATCH 24/56] DXF Import: OK refuses to place a drawing changed on disk since the preview Placing a DXF or DWG drawing by path through DXF Import Options read the file again at OK, so a file written over it while the dialog was open was placed with the options chosen for the drawing the dialog showed. OK now compares the file with the bytes the dialog previewed and keeps the dialog open with the reason when they differ. --- crates/ui-egui/src/dialogs/dxf_import.rs | 54 ++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index a01076a838..55e50c8972 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -498,6 +498,12 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R if let Some(placement) = placement { placement.check(app)?; } + // Place reads the file again: it must still be the drawing the dialog previewed. + if let (Some(path), Some(read)) = (source.path.as_deref(), app.services.read.as_ref()) + && read(path)? != source.file.bytes + { + return Err(tl!("The drawing changed on disk. Place it again to use the new version.").to_owned()); + } app.ui.dxf_import = remembered; let mut p = with_file(place, source.path.as_deref(), &source.name, &source.file); p["dxf"] = dxf; @@ -917,6 +923,54 @@ mod tests { }); } + /// A DWG drawing placed through its dialog is the drawing the dialog previewed: a file written + /// over it on disk while the dialog is open is not placed, and OK keeps the dialog open. + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + #[test] + fn ok_places_the_drawing_the_dialog_previewed() { + fn placed_size(app: &mut VectorcraftApp) -> (f64, f64) { + while !app.placing.pending.is_empty() { + crate::placing::wait(app); + crate::placing::poll(app); + } + let st = app.session.doc().unwrap(); + let mut out: Option = None; + st.doc.node(st.selection.objects[0]).unwrap().walk(&mut |c| { + if let Some(b) = c.path_data().and_then(vectorcraft_geom::PathData::bounds) { + out = Some(out.map_or(b, |o| o.union(b))); + } + }); + let r = out.unwrap(); + (r.width(), r.height()) + } + vectorcraft_engine::dwg::allow_in_process(); + let (_dir, plan) = dwg_file("dxf-import-dwg-previewed"); + let flatter = String::from_utf8(drawing()).unwrap().replace(" 21\n50\n", " 21\n10\n"); + crate::opening::tests::with_threads(|| { + let mut app = host::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + finish_conversions(&mut app); + host::confirm(&mut app, KIND).unwrap(); + let previewed = placed_size(&mut app); + crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap(); + finish_conversions(&mut app); + assert_eq!(host::fields(&app, KIND)["mode"], "place"); + std::fs::write(&plan, craft_dwg::dxf_to_dwg_as(flatter.as_bytes(), "AC1018").unwrap()).unwrap(); + let steps = app.session.doc().unwrap().history.undo.len(); + let refused = host::confirm(&mut app, KIND); + assert_eq!(refused, Err("The drawing changed on disk. Place it again to use the new version.".to_owned())); + assert!(host::is_open(&app, KIND), "the dialog stays open"); + assert!(app.placing.pending.is_empty()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "nothing is placed"); + // Written back as it was, the drawing the dialog previewed is placed. + std::fs::write(&plan, craft_dwg::dxf_to_dwg_as(&drawing(), "AC1018").unwrap()).unwrap(); + host::confirm(&mut app, KIND).unwrap(); + assert_eq!(placed_size(&mut app), previewed, "OK places the drawing the dialog opened on"); + }); + } + /// A DWG drawing converted off the UI thread and placed keeps its conversion until the place /// read off the UI thread is done. #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] From f6de56e4900da896b02c8ab6173c051520ef55e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 16:34:29 -0800 Subject: [PATCH 25/56] Scripts: pathItems.removeAll measures an effect's clip region under its fill rule When a live geometry effect reshapes what stays in a clipping path, removeAll() now measures the area that outline fills under its fill rule, with overlaps resolved, instead of the area of each subpath. An image whose Transform effect adds a copy reflected onto itself fills nothing under nonzero, so deleting the other paths now throws and deletes nothing. A frame that an effect scales to a thin strip still counts as a clipping region. --- crates/engine/src/script/dom/paths.rs | 17 ++++++++++++++++- crates/engine/src/tests/script_dom.rs | 22 +++++++++++++++++++--- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 0c7ef40971..efb3b957ea 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -655,8 +655,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { // The live geometry effects of what stays in the clipping path reshape the region it // clips by, as the renderer draws it; deleting paths that lets an effect shrink the // region to nothing leaves no outline. A region that was empty before is left as it is. + // The region is the area the outline fills under its fill rule, so outlines that run + // opposite ways over the same area under nonzero fill nothing. let reshaped_empty = |m: &vectorcraft_doc::Node| { - vectorcraft_render::effects::reshaped_clip_outline(m).is_some_and(|o| !o.is_some_and(|(bp, _)| encloses(&bp))) + vectorcraft_render::effects::reshaped_clip_outline(m).is_some_and(|o| !o.is_some_and(|(bp, rule)| fills(&bp, rule))) }; if n.clips() && let Some(mask) = kids.first() @@ -711,6 +713,19 @@ fn encloses(outline: &kurbo::BezPath) -> bool { }) } +/// Whether `outline` fills an area under `rule`: a subpath encloses an area ([`encloses`]) and the +/// outline with its overlaps resolved, thin strips included, has an area. An outline the path +/// operations refuse is judged by [`encloses`] alone. +fn fills(outline: &kurbo::BezPath, rule: vectorcraft_geom::FillRule) -> bool { + if !encloses(outline) { + return false; + } + match vectorcraft_pathops::try_area(&vectorcraft_geom::PathData::from_bezpath(outline), rule) { + Ok(area) => area > 0.0, + Err(_) => true, + } +} + /// `n` without the members in `going`, at every depth. Only the members in `affected` (those that /// hold a member in `going`) are copied; the others are shared. fn without( diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ab53076c4a..6577127b6a 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -4060,7 +4060,7 @@ fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empt /// an image still has an outline after its paths are deleted. #[test] fn document_path_items_remove_all_keeps_a_clipping_group_whose_clipping_path_keeps_an_image() { - for frame in [Frame::Square, Frame::Line, Frame::Far, Frame::Inset] { + for frame in [Frame::Square, Frame::Line, Frame::Far, Frame::Inset, Frame::Mirrored, Frame::Strip] { remove_all_beside_an_image(frame); } } @@ -4076,12 +4076,18 @@ enum Frame { Far, /// 40 pt square with a live Offset Path of -30 pt, which leaves nothing. Inset, + /// 40 pt square with a live Transform effect that adds one copy reflected about its center: + /// the two outlines run opposite ways over the same area and fill nothing under nonzero. + Mirrored, + /// 40 pt square with a live Transform effect that scales it to 0.004 pt high, which still + /// clips to a thin strip. + Strip, } /// A clipping group whose clipping path is a group of one path and an image with `frame`, then the /// document's `pathItems.removeAll()`. fn remove_all_beside_an_image(frame: Frame) { - let flat = matches!(frame, Frame::Line | Frame::Inset); + let flat = matches!(frame, Frame::Line | Frame::Inset | Frame::Mirrored); let (mut s, a, b) = doc(); let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); @@ -4094,7 +4100,7 @@ fn remove_all_beside_an_image(frame: Frame) { width: 4, height: 4, xf: match frame { - Frame::Square | Frame::Inset => kurbo::Affine::scale(10.0), + Frame::Square | Frame::Inset | Frame::Mirrored | Frame::Strip => kurbo::Affine::scale(10.0), Frame::Line => kurbo::Affine::scale_non_uniform(10.0, 0.0), Frame::Far => kurbo::Affine::translate((3_500_000.0, 3_500_000.0)) * kurbo::Affine::scale(1.0 / 256.0), }, @@ -4109,6 +4115,16 @@ fn remove_all_beside_an_image(frame: Frame) { if frame == Frame::Inset { s.execute("effect.apply", &json!({"effect": "path.offsetPath", "params": {"offset": -30}, "ids": [image.0], "item": null})).unwrap(); } + if frame == Frame::Mirrored { + s.execute( + "effect.apply", + &json!({"effect": "distort.transform", "params": {"reflectX": true, "copies": 1, "reference": 4}, "ids": [image.0], "item": null}), + ) + .unwrap(); + } + if frame == Frame::Strip { + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleV": 0.01}, "ids": [image.0], "item": null})).unwrap(); + } s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap(); let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); s.edit("Clip", |d, _| { From 8ff9964b13452ca8f43160ec3ed6cc1ecb48af16 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 16:41:41 -0800 Subject: [PATCH 26/56] 3D: Raster Settings OK sets the objects the dialog opened on Raster Settings opened with the selected objects' render settings, but OK applied the edited values to whatever was selected at OK time. An object selected while the dialog was open took settings it was never shown. OK now sets the objects selected when the dialog opened. When the document is no longer the active one, was reverted, had an Undo or Redo, or one of those objects was changed, deleted, locked or hidden, OK keeps the dialog open with the reason. --- ROADMAP.md | 2 + crates/ui-egui/src/panels/tests_three_d.rs | 113 ++++++++++++++++++++ crates/ui-egui/src/panels/three_d.rs | 62 ++++++++--- crates/ui-egui/src/panels/three_d/raster.rs | 73 ++++++++++--- docs/mcp.md | 5 + docs/three-d.md | 9 +- 6 files changed, 230 insertions(+), 34 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 616e6eea9d..3746644bb8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-12-04: Raster Settings OK edits the objects selected when the dialog opened. It keeps the dialog open with the reason if its document is not active, was reverted or had an Undo or Redo, if a target was changed, deleted, locked or hidden, if another edit is in progress, or if the change is refused. Headline numbers unchanged. + - 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips that starts again where the path turns back on itself at a cusp, a straight segment included (#10659). Headline numbers unchanged. - 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied. diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 145c210b72..9847028ef1 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -1791,6 +1791,119 @@ fn raster_settings_rendered_warning_reaches_the_status_bar() { assert_eq!(panel.app().ui.status, vectorcraft_effects::rendered::TOO_LARGE); } +/// Raster Settings OK sets the objects the dialog opened on: an object selected after it opened +/// keeps its render settings. +#[test] +fn raster_settings_ok_keeps_the_objects_it_opened_on() { + use craft::ui::dialog::dialog_id; + + use crate::tests::panel_harness::Panel; + + let (mut app, a, b) = two_renders(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + let a_before = render_of(&app, a); + let mut panel = Panel::new(app, show_with_dialogs); + panel.frame(); + panel.click("Render Settings"); + panel.click("Raster Settings…"); + panel.frame(); + let (dialog, ctx) = (dialog_id(super::raster::KIND), panel.ctx().clone()); + panel.app().run("select.set", json!({"ids": [a]})).unwrap(); + panel.app().dialogs().unwrap().with(|host| host.set_json_field(&ctx, dialog, "resolution", json!(300))).unwrap(); + panel.app().dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog)); + panel.frame(); + panel.frame(); + assert_eq!(render_of(&panel.app(), a), a_before, "the object selected after the dialog opened keeps its settings"); + assert_eq!(render_of(&panel.app(), b)["resolution"].as_f64(), Some(300.0), "OK sets the object the dialog opened on"); +} + +/// After an Undo while Raster Settings is open, OK keeps the dialog open and changes nothing: the +/// objects it opened on may no longer be the ones with their ids. +#[test] +fn raster_settings_ok_is_refused_after_undo() { + use crate::tests::panel_harness::Panel; + + let (mut app, a, b) = two_renders(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + let mut panel = Panel::new(app, show_with_dialogs); + panel.frame(); + panel.click("Render Settings"); + panel.click("Raster Settings…"); + panel.frame(); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_refused(&mut panel, a, b); +} + +/// An object locked while Raster Settings is open keeps its settings: OK keeps the dialog open. +#[test] +fn raster_settings_ok_is_refused_after_a_lock() { + use crate::tests::panel_harness::Panel; + + let (mut app, a, b) = two_renders(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + let mut panel = Panel::new(app, show_with_dialogs); + panel.frame(); + panel.click("Render Settings"); + panel.click("Raster Settings…"); + panel.frame(); + panel.app().run("object.lock", json!({})).unwrap(); + assert_refused(&mut panel, a, b); +} + +/// Raster Settings OK keeps another object's preview in progress and leaves its undo history unchanged. +#[test] +fn raster_settings_ok_is_refused_during_another_preview() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + use crate::tests::panel_harness::Panel; + + let (mut app, a, b) = two_renders(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + let mut panel = Panel::new(app, show_with_dialogs); + panel.frame(); + panel.click("Render Settings"); + panel.click("Raster Settings…"); + panel.frame(); + panel.app().run("select.set", json!({"ids": [a]})).unwrap(); + let before = panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(a)).unwrap().clone(); + panel.app().session.begin_interaction("Change fill").unwrap(); + panel.app().session.preview("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let preview = panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(a)).unwrap().clone(); + assert_ne!(preview, before, "the other object has a previewed edit"); + let history = undo_len(&panel.app()); + assert_refused(&mut panel, a, b); + let dialog = dialog_id(super::raster::KIND); + let refused = panel.app().dialogs().unwrap().with(|h| h.held_state(dialog)); + assert!(matches!(refused, Some(HeldOk::Refused(reason)) if format!("{reason:?}").contains("Finish the active edit first."))); + assert_eq!(panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(a)), Some(&preview)); + assert!(panel.app().session.in_interaction(), "the other edit stays in progress"); + assert_eq!(undo_len(&panel.app()), history); + panel.app().session.cancel_interaction().unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(a)), Some(&before)); +} + +/// Raster Settings, open, is given a resolution and OK: it stays open, and `a` and `b` keep their +/// render settings. +fn assert_refused(panel: &mut crate::tests::panel_harness::Panel, a: u64, b: u64) { + use craft::ui::dialog::{HeldOk, dialog_id}; + + use crate::tests::panel_harness::Panel; + + let (dialog, ctx) = (dialog_id(super::raster::KIND), panel.ctx().clone()); + let renders = |panel: &Panel| { + let app = panel.app(); + [render_of(&app, a), render_of(&app, b)] + }; + let before = renders(panel); + panel.app().dialogs().unwrap().with(|host| host.set_json_field(&ctx, dialog, "resolution", json!(300))).unwrap(); + panel.app().dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog)); + panel.frame(); + panel.frame(); + let refused = panel.app().dialogs().unwrap().with(|h| matches!(h.held_state(dialog), Some(HeldOk::Refused(_)))); + assert!(refused, "OK is refused and the dialog stays open"); + assert_eq!(renders(panel), before); +} + /// The panel with the window's dialogs run and their held answers applied, as in the app's frame. fn show_with_dialogs(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.ui_ctx = Some(ui.ctx().clone()); diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index fe8e629be2..bdbc686055 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -190,9 +190,16 @@ struct Plan { } fn plan(app: &VectorcraftApp) -> Plan { + let selection: Vec = app.session.active().map(|st| st.selection.objects.iter().map(|id| id.0).collect()).unwrap_or_default(); + plan_of(app, &selection) +} + +/// The plan of a change to the objects `ids` of the active document, with the current selection +/// as its selection; ids no longer in the document are left out. +fn plan_of(app: &VectorcraftApp, ids: &[u64]) -> Plan { let Some(st) = app.session.active() else { return Plan { selection: vec![], targets: vec![] } }; let selection: Vec = st.selection.objects.iter().map(|id| id.0).collect(); - let found: Vec<(u64, Target)> = st.selection.objects.iter().filter_map(|id| Some((id.0, find(st.doc.node(*id)?)?))).collect(); + let found: Vec<(u64, Target)> = ids.iter().filter_map(|id| Some((*id, find(st.doc.node(NodeId(*id))?)?))).collect(); let lights = |t: &Target| vectorcraft_effects::merged_params(&t.effect, &t.params).get("lights").cloned(); let first = found.first().map(|(_, t)| lights(t)); let targets = found @@ -205,6 +212,20 @@ fn plan(app: &VectorcraftApp) -> Plan { Plan { selection, targets } } +/// Commits the settings `changed` to the 3D effects of the objects `ids` as one undo step. +/// An active edit is left in progress and returns an error; ids no longer in the document are left out. +pub(crate) fn send_to(app: &mut VectorcraftApp, changed: Map, ids: &[u64]) -> Result<(), String> { + if app.session.in_interaction() { + return Err(tl!("Finish the active edit first.").to_owned()); + } + let steps = settings_steps(&plan_of(app, ids), &changed); + match steps.as_slice() { + [] => Ok(()), + [step] => app.run("effect.setParams", step["params"].clone()).map(|_| ()), + _ => app.run("command.batch", json!({"label": LABEL, "commands": steps})).map(|_| ()), + } +} + /// Sends the settings `changed` to the 3D effect of each selected object (only the settings its /// effect takes; objects without a 3D effect are left as they are): previews them while the /// gesture runs (`Live::Dragging`) and commits them as one undo step when it ends. Settings @@ -227,8 +248,20 @@ pub(crate) fn send(app: &mut VectorcraftApp, changed: Map, phase: let held = app.three_d.plan.take().unwrap_or_else(|| plan(app)); let mut pending = std::mem::take(&mut app.three_d.pending); pending.extend(changed); - let steps: Vec = held - .targets + let steps = settings_steps(&held, &pending); + match steps.as_slice() { + [] => {} + [step] => live_run(app, LABEL, "effect.setParams", step["params"].clone(), phase), + _ => live_run(app, LABEL, "command.batch", json!({"label": LABEL, "commands": steps}), phase), + } + if dragging { + app.three_d.pending = pending; + app.three_d.plan = Some(held); + } +} + +fn settings_steps(held: &Plan, pending: &Map) -> Vec { + held.targets .iter() .filter_map(|(id, t, same_lights)| { let takes = vectorcraft_effects::default_params(&t.effect).unwrap_or(Value::Null); @@ -262,16 +295,7 @@ pub(crate) fn send(app: &mut VectorcraftApp, changed: Map, phase: (!params.is_empty()) .then(|| json!({"command": "effect.setParams", "params": {"ids": [id], "index": t.index, "item": t.item, "params": params}})) }) - .collect(); - match steps.as_slice() { - [] => {} - [step] => live_run(app, LABEL, "effect.setParams", step["params"].clone(), phase), - _ => live_run(app, LABEL, "command.batch", json!({"label": LABEL, "commands": steps}), phase), - } - if dragging { - app.three_d.pending = pending; - app.three_d.plan = Some(held); - } + .collect() } /// Applies the edits of one pass of the panel's rows: `Begin` takes the plan and the settings as @@ -606,12 +630,16 @@ pub(crate) fn set_render(app: &mut VectorcraftApp, mode: &str, quality: Option<& /// Shows the first rendered fallback warning for selected objects whose effects take render settings. pub(crate) fn show_rendered_warning(app: &mut VectorcraftApp) { + let selection: Vec = app.session.active().map(|st| st.selection.objects.iter().map(|id| id.0).collect()).unwrap_or_default(); + show_rendered_warning_of(app, &selection); +} + +/// Shows the first rendered fallback warning for the objects `ids` whose effects take render settings. +pub(crate) fn show_rendered_warning_of(app: &mut VectorcraftApp, ids: &[u64]) { if let Some(st) = app.session.active() - && let Some(message) = st - .selection - .objects + && let Some(message) = ids .iter() - .filter_map(|id| st.doc.node(*id)) + .filter_map(|id| st.doc.node(NodeId(*id))) .filter(|n| { find(n).is_some_and(|t| vectorcraft_effects::default_params(&t.effect).is_some_and(|p| p.get(vectorcraft_effects::RENDER).is_some())) }) diff --git a/crates/ui-egui/src/panels/three_d/raster.rs b/crates/ui-egui/src/panels/three_d/raster.rs index c00dfab2b3..fb0d253b0b 100644 --- a/crates/ui-egui/src/panels/three_d/raster.rs +++ b/crates/ui-egui/src/panels/three_d/raster.rs @@ -3,14 +3,17 @@ //! //! Fields: `document` (Use Document Raster Effects Resolution), `resolution` (1 to 2400 ppi) and //! `background` (`transparent` or `white`). A field the selected objects hold differently opens -//! blank, and OK leaves it as each object has it. OK runs one `effect.setParams` over the -//! selection, one undo step, which records none when every object already holds what it sets. +//! blank, and OK leaves it as each object has it. OK runs one `effect.setParams` over the objects +//! selected when the dialog opened, one undo step, which records none when every object already +//! holds what it sets. While another document is the active one, or after the document was +//! reverted or had an Undo or Redo, OK keeps the dialog open with the reason. use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use serde_json::{Map, Value, json}; +use vectorcraft_doc::Node; -use super::{Live, finish, selected_renders, send, shared_render, show_rendered_warning}; +use super::{find, selected_renders, send_to, shared_render, show_rendered_warning_of, takes_render}; use crate::VectorcraftApp; use crate::dialogs::host::open_held; @@ -53,7 +56,22 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<(), String> { } let ctx = app.ui_ctx.clone().ok_or("no window")?; let dialog = HostedParamDialog::new(&ctx, KIND, fields, |fields| dialog().values(Bind::bound(fields))); - let opened = Opened { document, resolution: opening, background }; + let (doc, targets) = app + .session + .active() + .map(|st| { + let targets = st + .selection + .objects + .iter() + .filter_map(|id| st.doc.node(*id)) + .filter(|n| find(n).is_some_and(|t| takes_render(&t.effect))) + .cloned() + .collect(); + (Some((st.uid, st.reverts, st.history_restores)), targets) + }) + .unwrap_or_default(); + let opened = Opened { document, resolution: opening, background, doc, targets }; open_held(app, dialog, move |app, answer| ok(app, answer, &opened)).ok_or("no window")?; Ok(()) } @@ -83,6 +101,11 @@ struct Opened { document: Option, resolution: Option, background: Option, + /// The document the dialog opened on: its uid, and its revert and Undo or Redo counts then. + doc: Option<(u64, u64, u64)>, + /// The selected objects whose render settings the dialog opened on, as they were then: OK sets + /// these. + targets: Vec, } /// The render settings the answer `f` sets, given the values the dialog opened on: a field left @@ -115,17 +138,39 @@ fn edited(f: &DialogFields, opened: &Opened) -> Result, Strin Ok(render) } -/// OK: sets the edited render settings on every selected object's 3D effect, one undo step. +/// OK: sets the edited render settings on the 3D effect of every object the dialog opened on, one +/// undo step. While another document is the active one, after that document was reverted or had an +/// Undo or Redo, once one of those objects was changed, deleted, locked or hidden, or while another +/// edit is in progress, OK keeps the dialog open with the reason. fn ok(app: &mut VectorcraftApp, answer: &ParamResult, opened: &Opened) -> Result<(), String> { let render = edited(&answer.fields, opened)?; if render.is_empty() { return Ok(()); } - finish(app); + let Some((uid, reverts, restores)) = opened.doc else { return Ok(()) }; + let st = app + .session + .active() + .filter(|st| st.uid == uid) + .ok_or_else(|| tl!("Return to the original drawing to change its raster settings.").to_owned())?; + if st.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } + if st.history_restores != restores { + return Err(tl!("Reopen Raster Settings after Undo or Redo.").to_owned()); + } + let stale = { + let editable = st.doc.editable(); + opened.targets.is_empty() || opened.targets.iter().any(|t| st.doc.node(t.id) != Some(t) || !editable(t.id)) + }; + if stale { + return Err(tl!("The objects were changed, deleted or locked. Reopen Raster Settings to continue.").to_owned()); + } + let ids: Vec = opened.targets.iter().map(|t| t.id.0).collect(); let mut changed = Map::new(); changed.insert(vectorcraft_effects::RENDER.into(), Value::Object(render)); - send(app, changed, Live::Released); - show_rendered_warning(app); + send_to(app, changed, &ids)?; + show_rendered_warning_of(app, &ids); Ok(()) } @@ -157,12 +202,12 @@ mod tests { /// resolution sets nothing and a changed one sets it. #[test] fn ok_needs_a_resolution_and_keeps_blank_fields() { - let on = Opened { document: Some(true), resolution: Some(72.0), background: Some("transparent".into()) }; + let on = Opened { document: Some(true), resolution: Some(72.0), background: Some("transparent".into()), doc: None, targets: vec![] }; assert_eq!(edited(&fields(&[("document", FieldValue::Bool(false))]), &on), Err(NO_RESOLUTION.to_string())); - let own = Opened { document: Some(false), resolution: None, background: Some("transparent".into()) }; + let own = Opened { document: Some(false), resolution: None, background: Some("transparent".into()), doc: None, targets: vec![] }; let kept = edited(&fields(&[("document", FieldValue::Bool(false)), ("background", FieldValue::Text("white".into()))]), &own).unwrap(); assert_eq!(kept, Map::from_iter([("background".to_string(), json!("white"))])); - let mixed = Opened { document: None, resolution: Some(150.0), background: None }; + let mixed = Opened { document: None, resolution: Some(150.0), background: None, doc: None, targets: vec![] }; assert_eq!(edited(&fields(&[("resolution", FieldValue::Number(150.0))]), &mixed), Ok(Map::new())); let changed = edited(&fields(&[("resolution", FieldValue::Number(200.0))]), &mixed).unwrap(); assert_eq!(changed.get("resolution").and_then(Value::as_f64), Some(200.0)); @@ -174,14 +219,14 @@ mod tests { /// mixed one sets it. #[test] fn ok_on_unchanged_values_sets_nothing() { - let on = Opened { document: Some(true), resolution: Some(72.0), background: Some("transparent".into()) }; + let on = Opened { document: Some(true), resolution: Some(72.0), background: Some("transparent".into()), doc: None, targets: vec![] }; let unchanged = fields(&[ ("document", FieldValue::Bool(true)), ("resolution", FieldValue::Number(72.0)), ("background", FieldValue::Text("transparent".into())), ]); assert_eq!(edited(&unchanged, &on), Ok(Map::new())); - let own = Opened { document: Some(false), resolution: Some(150.0), background: Some("transparent".into()) }; + let own = Opened { document: Some(false), resolution: Some(150.0), background: Some("transparent".into()), doc: None, targets: vec![] }; let kept = fields(&[("document", FieldValue::Bool(false)), ("resolution", FieldValue::Number(150.0))]); assert_eq!(edited(&kept, &own), Ok(Map::new())); let raised = edited(&fields(&[("document", FieldValue::Bool(false)), ("resolution", FieldValue::Number(200.0))]), &own).unwrap(); @@ -190,7 +235,7 @@ mod tests { assert_eq!(switched, Map::from_iter([("resolution".to_string(), Value::Null)])); let white = edited(&fields(&[("background", FieldValue::Text("white".into()))]), &on).unwrap(); assert_eq!(white, Map::from_iter([("background".to_string(), json!("white"))])); - let mixed = Opened { document: Some(true), resolution: Some(72.0), background: None }; + let mixed = Opened { document: Some(true), resolution: Some(72.0), background: None, doc: None, targets: vec![] }; let picked = edited(&fields(&[("background", FieldValue::Text("transparent".into()))]), &mixed).unwrap(); assert_eq!(picked, Map::from_iter([("background".to_string(), json!("transparent"))])); } diff --git a/docs/mcp.md b/docs/mcp.md index 2fd8648262..fcf4545d49 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7387,6 +7387,11 @@ limits, so art too complex for the shaded surface does not refuse the wireframe. {"name":"run_command","arguments":{"command":"effect.setParams","params":{"index":0,"item":null,"params":{"render":{"mode":"rendered","quality":"high","background":"white"}}}}} ``` +The 3D and Materials panel's Render Settings › Raster Settings dialog sets resolution and background on the objects +selected when the dialog opened. OK applies the changes in one undo step and records nothing when nothing changes. +OK keeps the dialog open with the reason while its document is not active, after it was reverted or had an Undo +or Redo, if one of those objects was changed, deleted, locked or hidden, or while another edit is in progress. + ## 3D material Revolve, Extrude & Bevel, Inflate and Rotate take `material`, an object with `roughness` (0..1, default 1) and diff --git a/docs/three-d.md b/docs/three-d.md index d45a826edc..dff2eaacb2 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -68,9 +68,12 @@ pages describe it. off, no light casts a shadow. Low takes one sample a pixel, Medium 2 × 2 and High 3 × 3 (VectorCraft's own values), at the effect's `resolution` or, without one, at Document Raster Effects Settings › Resolution. **Render Settings › Raster Settings…** sets Use Document Raster Effects Resolution, Resolution (1 to 2400 ppi) and - Background (Transparent or White) for every selected object in one undo step, as the Render 3D vector artwork page - describes Raster Settings changing the resolution and background. A setting the selected objects hold differently - opens blank and is left as each object has it; Rendered and the qualities show unchecked for such a selection. + Background (Transparent or White). OK sets the objects selected when the dialog opened in one undo step. + OK keeps the dialog open with the reason while its document is not active, after it was reverted or had an Undo + or Redo, if one of those objects was changed, deleted, locked or hidden, or while another edit is in progress. + The Render 3D vector artwork page describes Raster Settings changing the resolution and background. A setting + the selected objects hold differently opens blank and is left as each object has it; Rendered and the qualities + show unchecked for such a selection. The selection box, Use Preview Bounds, Align, hit testing and snapping measure the shaded faces, and the image is made only when the object is drawn, then reused until an input to it changes. A quality whose samples would pass 16,777,216 pixels takes fewer; past that limit at one sample a pixel, or when the solid can't be placed in one From 830737d1f00e90f1f6771374c2631d0f5493d65a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 17:12:08 -0800 Subject: [PATCH 27/56] File formats: DWG is listed as readable only where a decoder reads it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Web builds and FreeBSD on 64-bit ARM have no DWG decoder, yet File › Open, File › Place, their "All readable files" and "All placeable files" filters, `openExtensions`, `document.formats`, the MCP open_file description and the CLI help all offered `.dwg` there, and a DWG file then failed in the missing decoder. - `vectorcraft_cad::dwg::DECODES` says whether the build decodes DWG. - `readable_format`, `open_exts()`, `place_exts()` and the per-format dialog filters leave DWG out where it is false; `document.formats` reports `dwg` as not readable there. - An installed `.dwg` importer plug-in is used for such files on those builds, by File › Open, File › Place and folder batches, and the desktop app skips its background DWG conversion there. - Without an importer, File › Place keeps the DWG-specific error, and a `.dwg` file is still not read as HP-GL. The listing functions take the decoder availability as a parameter, so the new test checks both cases on every platform. --- apps/vectorcraft-cli/src/main.rs | 4 +- crates/cad/src/dwg.rs | 3 + crates/engine/src/cmd/fileio.rs | 6 +- crates/engine/src/cmd/fileio/action_batch.rs | 2 +- crates/engine/src/cmd/fileio/formats.rs | 106 ++++++++++++++++--- crates/engine/src/cmd/fileio/importer.rs | 8 +- crates/engine/src/cmd/fileio/load.rs | 4 +- crates/engine/src/cmd/fileio/tests.rs | 12 +-- crates/engine/src/cmd/place.rs | 13 ++- crates/engine/src/tests/textimport.rs | 2 +- crates/mcp/src/tools.rs | 2 +- crates/mcp/src/tools/definitions.rs | 4 +- crates/ui-egui/src/dialogs/dxf_import.rs | 4 +- docs/mcp.md | 7 +- 14 files changed, 133 insertions(+), 44 deletions(-) diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 8855d3f9e3..1bfb6b817a 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -196,8 +196,8 @@ USAGE: /// The usage text plus the formats `document.open` reads and `document.export` writes. fn usage() -> String { - use vectorcraft_engine::cmd::fileio::{OPEN_EXTS, export_extensions}; - format!("{USAGE}\nReadable formats: .{}\nWritable formats: .{}\n", OPEN_EXTS.join(", ."), export_extensions().join(", .")) + use vectorcraft_engine::cmd::fileio::{export_extensions, open_exts}; + format!("{USAGE}\nReadable formats: .{}\nWritable formats: .{}\n", open_exts().join(", ."), export_extensions().join(", .")) } /// Does a subcommand's `args` ask for the usage? `--help` or `-h` counts where an option goes, not as diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs index b6e4b545c4..c49beecb99 100644 --- a/crates/cad/src/dwg.rs +++ b/crates/cad/src/dwg.rs @@ -13,6 +13,9 @@ use web_time::Instant; pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker}; +/// Whether this build decodes DWG drawings. Web builds and FreeBSD on 64-bit ARM have no DWG decoder. +pub const DECODES: bool = !cfg!(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))); + /// The worker argument after [`WORKER_ARG`] that gives its deadline in milliseconds since the UNIX epoch /// ([`use_own_worker_for`]). const WORKER_UNTIL_ARG: &str = "--dwg-worker-until"; diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 1a24bf623b..fc0e9008b4 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -178,14 +178,14 @@ pub(crate) use export_names::{ artboard_file_names_keeping_dots, default_name, merge, unique_file_names_keeping_dots, with_black_output, write_or_return, }; use export_names::{distinct_names_by, write_encoded}; -pub(crate) use formats::is_own_title; use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable}; pub use formats::{ DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters, export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions, - open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_filters, places_with_importer, plugin_formats, read_extensions, - readable_format, readable_format_for_name, titled_for_export, writable_format, + open_exts, open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_exts, place_filters, places_with_importer, + plugin_formats, read_extensions, readable_format, readable_format_for_name, titled_for_export, writable_format, }; +pub(crate) use formats::{is_own_title, reads}; #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 9beed7e8a2..276886d534 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -785,7 +785,7 @@ fn is_openable(path: &str) -> bool { if ext.is_empty() { return false; } - open_extensions().iter().any(|e| *e == ext) || FORMATS.iter().any(|f| f.read && f.extensions.iter().any(|e| *e == ext)) + open_extensions().iter().any(|e| *e == ext) || FORMATS.iter().any(|f| super::formats::reads(f) && f.extensions.iter().any(|e| *e == ext)) } #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index f8da5b941c..fdb5a9508c 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -749,9 +749,52 @@ pub fn read_extensions(f: &Format) -> &'static [&'static str] { /// The built-in readable format of extension `ext` (any case, leading dot allowed): [`format`]'s /// when it reads, else the one [`READ_ALIASES`] gives it (`.dib` is BMP). Importer plug-ins are /// not looked at ([`importer_formats`]). +/// DWG drawings are readable only in a build with a DWG decoder ([`vectorcraft_cad::dwg::DECODES`]). pub fn readable_format(ext: &str) -> Option<&'static Format> { + readable_format_in(ext, vectorcraft_cad::dwg::DECODES) +} + +/// The built-in format a file of extension `ext` is taken for ([`super::load::detect`]): [`readable_format`]'s, +/// with DWG also in a build without a DWG decoder. +pub(crate) fn recognized_format(ext: &str) -> Option<&'static Format> { + readable_format_in(ext, true) +} + +/// [`readable_format`] in a build that decodes DWG drawings when `dwg`. +fn readable_format_in(ext: &str, dwg: bool) -> Option<&'static Format> { let k = ext.trim_start_matches('.').to_ascii_lowercase(); - builtin(&k).filter(|f| f.read).or_else(|| READ_ALIASES.iter().find(|(_, exts)| exts.contains(&k.as_str())).and_then(|(id, _)| builtin(id))) + builtin(&k) + .filter(|f| reads_in(f, dwg)) + .or_else(|| READ_ALIASES.iter().find(|(_, exts)| exts.contains(&k.as_str())).and_then(|(id, _)| builtin(id))) +} + +/// Whether format `f` reads in this build: DWG drawings only where a DWG decoder is built in. +pub(crate) fn reads(f: &Format) -> bool { + reads_in(f, vectorcraft_cad::dwg::DECODES) +} + +/// Whether format `f` reads in a build that decodes DWG drawings when `dwg`. +fn reads_in(f: &Format, dwg: bool) -> bool { + f.read && (dwg || f.id != "dwg") +} + +/// `exts` less `.dwg` in a build without a DWG decoder (`dwg` false). +fn listed_in(exts: &[&'static str], dwg: bool) -> Vec<&'static str> { + exts.iter().copied().filter(|e| dwg || *e != "dwg").collect() +} + +/// The extensions File › Open reads as a document in this build: [`OPEN_EXTS`], less `.dwg` where +/// no DWG decoder is built in ([`vectorcraft_cad::dwg::DECODES`]). +pub fn open_exts() -> &'static [&'static str] { + static EXTS: std::sync::LazyLock> = std::sync::LazyLock::new(|| listed_in(OPEN_EXTS, vectorcraft_cad::dwg::DECODES)); + &EXTS +} + +/// The extensions File › Place reads in this build: [`PLACE_EXTS`], less `.dwg` where no DWG +/// decoder is built in ([`vectorcraft_cad::dwg::DECODES`]). +pub fn place_exts() -> &'static [&'static str] { + static EXTS: std::sync::LazyLock> = std::sync::LazyLock::new(|| listed_in(PLACE_EXTS, vectorcraft_cad::dwg::DECODES)); + &EXTS } /// The readable format a file name's extension names ([`readable_format`]). @@ -761,7 +804,12 @@ pub fn readable_format_for_name(name: &str) -> Option<&'static Format> { /// One dialog filter per readable format. fn format_filters() -> impl Iterator { - FORMATS.iter().filter(|f| f.read).map(|f| (f.label, read_extensions(f))) + format_filters_in(vectorcraft_cad::dwg::DECODES) +} + +/// [`format_filters`] in a build that decodes DWG drawings when `dwg`. +fn format_filters_in(dwg: bool) -> impl Iterator { + FORMATS.iter().filter(move |f| reads_in(f, dwg)).map(|f| (f.label, read_extensions(f))) } /// Whether a file named `name` can only be opened, by an importer plug-in: an installed importer lists @@ -770,7 +818,7 @@ fn format_filters() -> impl Iterator bool { let ext = extension(name); !ext.is_empty() - && !PLACE_EXTS.contains(&ext.as_str()) + && !place_exts().contains(&ext.as_str()) && !vectorcraft_plugins::import::for_extension(&ext).is_empty() && !places_with_importer(name) } @@ -782,7 +830,7 @@ pub fn places_with_importer(name: &str) -> bool { let ext = extension(name); !ext.is_empty() && readable_format(&ext).is_none() - && !PLACE_EXTS.contains(&ext.as_str()) + && !place_exts().contains(&ext.as_str()) && !vectorcraft_plugins::import::placing(&ext).is_empty() } @@ -828,7 +876,7 @@ fn importer_open_part() -> ImporterPart { { return part.clone(); } - let mut exts: Vec<&'static str> = OPEN_EXTS.to_vec(); + let mut exts: Vec<&'static str> = open_exts().to_vec(); let mut filters = Vec::new(); for f in importer_formats() { let own: Vec<&'static str> = f.extensions.iter().copied().filter(|e| readable_format(e).is_none() && !opens_as_other(e)).collect(); @@ -843,7 +891,7 @@ fn importer_open_part() -> ImporterPart { let own: &'static [&'static str] = if own.len() == f.extensions.len() { f.extensions } else { Box::leak(own.into_boxed_slice()) }; filters.push((f.label, own)); } - let exts: &'static [&'static str] = if exts.len() == OPEN_EXTS.len() { OPEN_EXTS } else { Box::leak(exts.into_boxed_slice()) }; + let exts: &'static [&'static str] = if exts.len() == open_exts().len() { open_exts() } else { Box::leak(exts.into_boxed_slice()) }; let part = (exts, filters); *made = Some((revision, part.clone())); part @@ -870,7 +918,7 @@ pub fn open_filters() -> impl Iterator impl Iterator { - std::iter::once(("All readable files", OPEN_EXTS)).chain(format_filters()).chain(other_open_filters()) + std::iter::once(("All readable files", open_exts())).chain(format_filters()).chain(other_open_filters()) } /// The open-dialog filters after the document formats: swatch and graphic style libraries, @@ -906,7 +954,7 @@ pub fn library_open_filters( /// File → Place dialog filters: "All placeable files", then one per placeable format, then text, /// RTF and Word (`.docx` and `.doc`). pub fn place_filters() -> impl Iterator { - std::iter::once(("All placeable files", PLACE_EXTS)) + std::iter::once(("All placeable files", place_exts())) .chain(format_filters().filter(|(_, exts)| exts.iter().all(|ext| PLACE_EXTS.contains(ext)))) .chain(std::iter::once(("Text", TEXT_EXTS))) .chain(std::iter::once(("RTF", RTF_EXTS))) @@ -928,12 +976,16 @@ fn importer_place_part() -> ImporterPart { { return part.clone(); } - let mut exts: Vec<&'static str> = PLACE_EXTS.to_vec(); + let mut exts: Vec<&'static str> = place_exts().to_vec(); let mut filters = Vec::new(); for p in import::installed().into_iter().filter(|p| p.manifest().place) { let m = p.manifest(); - let own: Vec<&'static str> = - m.extensions.iter().filter(|e| readable_format(e).is_none() && !PLACE_EXTS.contains(&e.as_str())).map(|e| registry::intern(e)).collect(); + let own: Vec<&'static str> = m + .extensions + .iter() + .filter(|e| readable_format(e).is_none() && !place_exts().contains(&e.as_str())) + .map(|e| registry::intern(e)) + .collect(); if own.is_empty() { continue; } @@ -945,7 +997,7 @@ fn importer_place_part() -> ImporterPart { let own: &'static [&'static str] = Box::leak(own.into_boxed_slice()); filters.push((registry::intern(&m.name), own)); } - let exts: &'static [&'static str] = if exts.len() == PLACE_EXTS.len() { PLACE_EXTS } else { Box::leak(exts.into_boxed_slice()) }; + let exts: &'static [&'static str] = if exts.len() == place_exts().len() { place_exts() } else { Box::leak(exts.into_boxed_slice()) }; let part = (exts, filters); *made = Some((revision, part.clone())); part @@ -1110,6 +1162,9 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result { let ids = |pick: fn(&Format) -> bool| all().filter(|f| pick(f)).map(|f| f.id).collect::>(); let listed = |f: &Format| { let mut v = f.to_json(); + if f.read && !reads(f) { + v["read"] = json!(false); + } if let Some(id) = vectorcraft_plugins::export::plugin_id(f.id) { v["plugin"] = json!(id); if vectorcraft_plugins::import::by_format(f.id).is_some_and(|p| p.manifest().place) { @@ -1120,9 +1175,34 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result { }; Ok(json!({ "formats": all().map(listed).collect::>(), - "readable": ids(|f| f.read), + "readable": ids(reads), "writable": ids(|f| f.write), "openExtensions": open_extensions(), "unsupported": UNSUPPORTED.iter().map(Unsupported::to_json).collect::>(), })) } + +#[cfg(test)] +mod dwg_listing_tests { + use super::*; + + #[test] + fn dwg_is_listed_only_in_a_build_that_decodes_it() { + assert_eq!(readable_format_in("dwg", true).map(|f| f.id), Some("dwg")); + assert_eq!(listed_in(OPEN_EXTS, true), OPEN_EXTS); + assert_eq!(listed_in(PLACE_EXTS, true), PLACE_EXTS); + assert!(format_filters_in(true).any(|(_, exts)| exts.contains(&"dwg"))); + // Without a decoder, nothing offers DWG drawings. + assert!(readable_format_in("dwg", false).is_none(), "DWG is not readable"); + assert!(readable_format_in("dxf", false).is_some(), "DXF still is"); + assert!(!listed_in(OPEN_EXTS, false).contains(&"dwg"), "File › Open does not list .dwg"); + assert!(!listed_in(PLACE_EXTS, false).contains(&"dwg"), "File › Place does not list .dwg"); + assert_eq!(listed_in(OPEN_EXTS, false).len(), OPEN_EXTS.len() - 1, "every other extension stays"); + assert!(format_filters_in(false).all(|(_, exts)| !exts.contains(&"dwg")), "no DWG filter"); + // This build lists DWG exactly when it decodes it. + let dwg = vectorcraft_cad::dwg::DECODES; + assert_eq!(open_exts().contains(&"dwg"), dwg); + assert_eq!(place_exts().contains(&"dwg"), dwg); + assert_eq!(readable_format("dwg").is_some(), dwg); + } +} diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index c578dece5d..01db94fbb2 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -61,7 +61,7 @@ pub(super) fn pick(name: &str, bytes: &[u8], p: &Value) -> Result bool { super::readable_format(ext).is_none() && match mode { Mode::Import => !import::for_extension(ext).is_empty(), - Mode::Place => !super::PLACE_EXTS.contains(&ext) && !import::placing(ext).is_empty(), + Mode::Place => !super::place_exts().contains(&ext) && !import::placing(ext).is_empty(), } } @@ -140,7 +140,7 @@ fn check_data_for(p: &Value, mode: Mode, cmd: &str) -> Result<()> { if !explicit { let start: Vec = b64.bytes().filter(|b| !b.is_ascii_whitespace()).take(SNIFF_BYTES / 3 * 4).collect(); let head = std::str::from_utf8(&start).ok().and_then(vectorcraft_format::base64_decode); - if head.is_some_and(|head| detect(name, &head).is_some()) { + if head.is_some_and(|head| detect(name, &head).is_some_and(super::formats::reads)) { return Ok(()); } } @@ -171,7 +171,7 @@ fn read_path_for(path: &str, p: &Value, mode: Mode, cmd: &str) -> Result if head.len() < SNIFF_BYTES { return Ok(head); } - if detect(path, &head).is_some() { + if detect(path, &head).is_some_and(super::formats::reads) { return super::read_file(path); } read_for_importer(path, mode) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index f152132c69..da6e2f437f 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -8,7 +8,7 @@ use vectorcraft_render::effects::pixel::LoadedTexture; use super::super::fileinfo::imported_title; use super::super::{Result, Session, bad, bool_or, clipboard, parse_range, str_param}; use super::pdfimport::LoadOptions; -use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, jxlread, psdread, read_file, readable_format_for_name}; +use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, jxlread, psdread, read_file}; use crate::cmd::links::Resolved; use crate::{EngineError, Prefs}; @@ -91,7 +91,7 @@ pub fn file_name(name: &str) -> String { /// The readable format of a file: from its content (magic bytes) when that tells, else from the /// extension of `name`. pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { - let by_name = readable_format_for_name(name); + let by_name = super::formats::recognized_format(&super::extension(name)); if vectorcraft_affinity::is_affinity(bytes) { return format("affinity"); } diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index ed0034b99e..9c86777182 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -453,14 +453,14 @@ fn open_exts_cover_every_readable_format() { assert!(OPEN_EXTS.contains(e), "OPEN_EXTS lacks .{e} ({})", f.label); } } - for e in OPEN_EXTS { - assert!(readable_format(e).is_some(), ".{e} in OPEN_EXTS is no readable format"); + for e in open_exts() { + assert!(readable_format(e).is_some(), ".{e} in open_exts() is no readable format"); } let filters: Vec<_> = open_filters().collect(); - assert_eq!(filters[0], ("All readable files", OPEN_EXTS)); + assert_eq!(filters[0], ("All readable files", open_exts())); assert_eq!( filters.len(), - 13 + FORMATS.iter().filter(|f| f.read).count(), + 13 + FORMATS.iter().filter(|f| formats::reads(f)).count(), "and swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export presets, composite \ fonts, shortcut sets, scripts, plug-ins" ); @@ -484,7 +484,7 @@ fn library_open_filters_list_library_formats_first() { let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS).collect(); assert_eq!(filters[0], ("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS)); assert!(filters[0].1.contains(&"ase")); - assert_eq!(filters[1], ("All readable files", OPEN_EXTS)); + assert_eq!(filters[1], ("All readable files", open_exts())); let styles: &'static [&'static str] = std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT); for (label, exts) in [("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS), ("Graphic Style Libraries", styles)] { let filters: Vec<_> = library_open_filters(label, exts).collect(); @@ -576,7 +576,7 @@ fn formats_query_lists_readers_writers_and_options() { assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string())); let png = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "png").unwrap(); assert_eq!(png["options"]["scale"]["default"], Value::Null); - assert_eq!(r["openExtensions"].as_array().unwrap().len(), OPEN_EXTS.len()); + assert_eq!(r["openExtensions"].as_array().unwrap().len(), open_exts().len()); } /// The format ids `command`'s params text lists for `format` (`a|b (default)|c (…)`, up to the diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 9d145853b9..06fa7de01a 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -238,11 +238,14 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o } return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None }); } - let Some(format) = fileio::detect(src.name, &src.bytes) else { - return match fileio::importer::for_place(src.name) { - Some(plugin) => plugin_art(name, src.name, &src.bytes, &plugin, p, cmd), - None => Err(bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)"))), - }; + let format = fileio::detect(src.name, &src.bytes); + if format.is_none_or(|f| !fileio::reads(f)) + && let Some(plugin) = fileio::importer::for_place(src.name) + { + return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd); + } + let Some(format) = format else { + return Err(bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)"))); }; let page = match p.get("page") { None => 1, diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index 7af09c95e8..61e98c9088 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -1160,7 +1160,7 @@ fn place_reads_what_open_reads_and_text_files() { assert_eq!(PLACE_EXTS, [OPEN_EXTS, TEXT_EXTS, RTF_EXTS, DOCX_EXTS, DOC_EXTS].concat()); let filters: Vec<_> = cmd::fileio::place_filters().collect(); let word: (&str, &[&str]) = ("Word", &["docx", "doc"]); - assert_eq!((filters.first(), filters.last()), (Some(&("All placeable files", PLACE_EXTS)), Some(&word))); + assert_eq!((filters.first(), filters.last()), (Some(&("All placeable files", cmd::fileio::place_exts())), Some(&word))); assert_eq!(filters.get(filters.len() - 3..), Some(&[("Text", TEXT_EXTS), ("RTF", RTF_EXTS), word][..])); assert!( !cmd::fileio::open_filters().any(|(_, exts)| ["txt", "rtf", "docx", "doc"].iter().any(|e| exts.contains(e))), diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 93ef5749af..f0e6e28c5d 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -2,7 +2,7 @@ //! [`Backend`]. use serde_json::{Map, Value, json}; -use vectorcraft_engine::cmd::fileio::{ARTBOARD_PARAMS, FORMATS, OPEN_EXTS, SAVE_FORMATS, format, writable_format}; +use vectorcraft_engine::cmd::fileio::{ARTBOARD_PARAMS, FORMATS, SAVE_FORMATS, format, open_exts, writable_format}; use crate::backend::Backend; diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index cc187ea408..769b82d543 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -1,6 +1,6 @@ use super::dispatch::{BRIEF, MAX_SIDE_WINDOW, MENU_FILTER, TRACE_VIEWS}; use super::handlers::MAX_DIALOG_FIELDS; -use super::{FORMATS, OPEN_EXTS, SAVE_FORMATS, Value, format, json}; +use super::{FORMATS, SAVE_FORMATS, Value, format, json, open_exts}; // ---------- schemas ---------- @@ -365,7 +365,7 @@ pub fn tool_definitions() -> Vec { "Open file", &format!( "Open a file as a new, active document: .{} (see run_command document.formats). Templates (.ait, native templates) open as a new untitled document. The reply's `warnings` say what didn't come in as it was (an EPS shown as its preview image says why its PostScript couldn't be read). A file of an extension no built-in format reads opens with the installed importer plug-in that lists it; `importer` names the importer to use (File › Open With), also for an extension a built-in format reads, and `params` gives that importer's parameters.", - OPEN_EXTS.join(", .") + open_exts().join(", .") ), obj( json!({ diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index a01076a838..09ce1f9d5d 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -351,7 +351,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, place: Option<&Value>) -> bool { - if !vectorcraft_cad::is_dwg(bytes) || fileio::detect(name, bytes).is_none_or(|f| f.id != "dwg") { + if !vectorcraft_cad::dwg::DECODES || !vectorcraft_cad::is_dwg(bytes) || fileio::detect(name, bytes).is_none_or(|f| f.id != "dwg") { return false; } crate::opening::convert_drawing(app, name, bytes.to_vec(), path, place.cloned()); @@ -365,7 +365,7 @@ pub fn convert_in_background(app: &mut VectorcraftApp, name: &str, bytes: &[u8], /// converted (true). pub fn convert_place_in_background(app: &mut VectorcraftApp, p: &Value) -> bool { let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension); - if p.get("dxf").is_some() || named.as_deref() != Some("dwg") { + if !vectorcraft_cad::dwg::DECODES || p.get("dxf").is_some() || named.as_deref() != Some("dwg") { return false; } let Some((name, bytes, path)) = place_source(app, p, |ext| ext == "dwg") else { return false }; diff --git a/docs/mcp.md b/docs/mcp.md index 9c5f1bc38b..e0495588b1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12683,7 +12683,10 @@ no linked file, and `warnings` carries "an image couldn't be decoded and is miss images. DWG drawings open and place (see DXF import) but can't be written: `document.formats` lists `dwg` as readable and -not writable, and exporting to it answers with the hint to export DXF. PICT files open and place (see PICT +not writable, and exporting to it answers with the hint to export DXF. Web builds and FreeBSD on 64-bit ARM have no +DWG decoder: there `document.formats` lists `dwg` as neither readable nor writable, File › Open, File › Place and +`openExtensions` list `.dwg` only for an installed importer plug-in that reads it, and a DWG drawing opens or places +only through such a plug-in. PICT files open and place (see PICT import) but can't be written. ```json @@ -12714,7 +12717,7 @@ transparency resolve through layers and blocks. What is left out (viewports, ima vertices are missing, unknown entities) is listed in `warnings`. ASCII and binary DXF files are read. DWG drawings (by content or the `.dwg` extension) open, place and answer `document.dxfInfo` the same way, with the -same `dxf` options: craft-dwg converts the drawing to DXF (acadrust 0.6.6, MPL-2.0) and the DXF reader reads that. +same `dxf` options, in builds with a DWG decoder (not web builds or FreeBSD on 64-bit ARM): craft-dwg converts the drawing to DXF (acadrust 0.6.6, MPL-2.0) and the DXF reader reads that. In the desktop app and `vectorcraft-cli` the conversion runs in a copy of the program started with `--dwg-worker`, so a damaged file stops that copy, not the app; it gives up after 30 minutes. Files over 512 MiB, or whose DXF would pass 1 GiB, are refused. What the conversion skips (objects of types it can't read) is listed in `warnings`. R1.x and From 632598888f77022b43e69a5b795bf7e974c0be1c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 17:29:37 -0800 Subject: [PATCH 28/56] Plug-ins: an edit made during an add-on preview survives Cancel and OK With Add Artboard Guides previewing, deleting an artboard from the Artboards panel ran inside the preview's interaction. On the next frame the dialog could no longer find its artboard, canceled the preview, and the cancel put the deleted artboard back. The same happened in every add-on dialog: any command run while its preview showed was undone by the next preview or by Cancel. An add-on dialog's preview now marks its interaction (`dialog`). A command from outside the dialog sets that interaction aside, runs on the document without the preview as an undo step of its own, and the dialog previews again from the command's result and selection, as a tool drag already does. `edit.copy` and the `file.*` commands other than `file.documentColorMode` still act on the document as the preview shows it, and Edit Points Only keeps the old behavior, since it previews a selection. A preview whose snapshot an outside command changed runs again, also after a failed run. Docs: docs/mcp.md (undo/redo row). --- crates/engine/src/interaction.rs | 4 +++ crates/engine/src/session/edit.rs | 31 +++++++++++++---- crates/ui-egui/src/addons/arrange/tests.rs | 22 ++++++++++++ crates/ui-egui/src/addons/dialogs.rs | 4 +++ crates/ui-egui/src/addons/dialogs/tests.rs | 23 +++++++++++++ crates/ui-egui/src/dialogs/preview.rs | 39 +++++++++++++++++++--- docs/mcp.md | 2 +- 7 files changed, 113 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 1ede3c2509..15630b6bbd 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -19,6 +19,10 @@ pub struct Interaction { /// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an /// interaction runs its commands inside it. pub(crate) tool: bool, + /// A dialog's live preview began it: a command from outside the dialog runs as a step of its + /// own under it, as it does under a drag, so the next preview, OK and Cancel keep its edit + /// (a `file.*` command still runs inside it). + pub dialog: bool, /// A tool began or joined this interaction through `Action::Begin`. pub(crate) tool_joined: bool, /// A replaced or canceled preview restores these new-art paints from before the interaction. diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 604ca822df..6581503054 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -343,19 +343,22 @@ impl Session { /// it updates Recent Colors and converts or remaps the new-art paints at once, as it does with /// no drag in progress. /// - /// The interaction stays as it is, and the command runs inside it, for an interaction a dialog - /// or a panel began (it builds its preview from commands), for typing in progress + /// A dialog's live preview ([`crate::Interaction::dialog`]) is set aside the same way, except + /// for a command that acts on the drawing on show ([`reads_preview`]). The + /// interaction stays as it is, and the command runs inside it, for an interaction a panel or + /// another dialog began (it builds its preview from commands), for typing in progress /// ([`Session::edit`] keeps it as a step of its own), for the Quick Pen (an edit made outside /// it ends the path it draws), and for a copy made with `object.transform` during a drag that /// copies (it copies the document as the drag's move left it). A command that settles, /// commits or cancels the interaction, or that hands the active tool actions to apply, gets it /// back first ([`Session::put_back_interaction`]), as it found it. pub(crate) fn outside_interaction(&mut self, id: &str, params: &Value, f: impl FnOnce(&mut Self) -> Result) -> Result { - if cmd::typing_in_progress(self) || self.tool_id() == vectorcraft_tools::quickpen::ID { + let dialog = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.dialog); + if cmd::typing_in_progress(self) || (!dialog && self.tool_id() == vectorcraft_tools::quickpen::ID) { return f(self); } let Some(st) = self.active_mut() else { return f(self) }; - let Some(it) = st.interaction.as_ref().filter(|it| it.tool) else { return f(self) }; + let Some(it) = st.interaction.as_ref().filter(|it| it.tool || (it.dialog && !reads_preview(id))) else { return f(self) }; // A drag that copies: its latest preview, applied or held back by Real-time Drawing off, copies. let copying = it.preview.as_ref().is_some_and(|(c, p)| c == "object.transform" && p.get("copy").and_then(Value::as_bool) == Some(true)); if copying && id == "object.transform" && params.get("copy").and_then(Value::as_bool) == Some(true) { @@ -472,8 +475,17 @@ impl Session { } let began = std::mem::replace(&mut it.doc, st.doc.clone()); // The drag acts on the objects it began with: a selection the command made (a paste, a - // duplicate, Select All) does not change what the drag moves. - it.selection = Arc::new(drag_selection(&it.selection, &st.doc)); + // duplicate, Select All) does not change what the drag moves. A dialog's preview acts on + // the selection the command left, and its dialog previews again on its next pass, from the + // values it shows then, so nothing is applied here. + if it.dialog { + if st.selection != *it.selection { + it.selection = Arc::new(st.selection.clone()); + } + it.preview = None; + } else { + it.selection = Arc::new(drag_selection(&it.selection, &st.doc)); + } // The journal holds the selection the command left. The drag's own selection is journaled // after it, so the drag and the commands after it replay on the objects they act on. let reselect = (active && st.selection != *it.selection) @@ -569,6 +581,7 @@ impl Session { revision: st.revision, preview: None, tool: false, + dialog: false, tool_joined: false, paint, used_defaults_only: false, @@ -944,6 +957,12 @@ fn take_changed_paints( } } +/// Whether command `id` acts on the drawing as a dialog's preview shows it (a copy, a save, a +/// revert), so it runs inside that preview rather than as a step of its own. +fn reads_preview(id: &str) -> bool { + id == "edit.copy" || (id.starts_with("file.") && id != "file.documentColorMode") +} + /// The selection a drag began with, without the objects that a command run during it removed, /// hid or locked in `doc`. fn drag_selection(began: &Selection, doc: &Document) -> Selection { diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 2e9beac838..1f0b3f7b3b 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -298,6 +298,28 @@ fn add_artboard_guides_does_not_replace_a_deleted_artboard_with_its_neighbor() { } } +#[test] +fn add_artboard_guides_preview_keeps_an_artboard_deleted_while_it_shows() { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + app.view_mut().unwrap().artboard = 0; + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "preview", json!(true)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app).len(), 1); + app.run("artboard.delete", json!({"index": 0})).unwrap(); + assert!(artboard_guides(&app).is_empty(), "the remaining artboard gets no guide"); + host::frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc.artboards.len(), 1); + assert!(artboard_guides(&app).is_empty()); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc.artboards.len(), 1); + assert!(artboard_guides(&app).is_empty()); + assert_eq!(app.ui.status, "The artboard no longer exists."); +} + #[test] fn artboard_guides_menu_dialog_is_available_without_a_selection() { let (mut app, _, _) = app(); diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 02f9745b5d..39d40bf740 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -164,6 +164,10 @@ fn pump_commit(app: &mut VectorcraftApp) { Some(Err(error.clone())) } }; + // Edit Points Only previews a selection, which an outside command (Clear) has to see as shown. + if spec.command != super::select::points_only::COMMAND { + preview.keep_outside_edits(app); + } app.addon_dialogs.preview = preview; if spec.command == super::select::points_only::COMMAND { match &answer { diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index dc2372552e..392900b20a 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -318,6 +318,29 @@ fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview() assert_eq!(x0(&app, 1), 100.0, "the first preview rolled back"); } +#[test] +fn an_add_on_preview_keeps_an_edit_made_outside_the_dialog() { + let mut app = two_rects(); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "previewed"); + let undo = undo_len(&app); + app.run("shape.rectangle", json!({"x": 300, "y": 300, "width": 10, "height": 10})).unwrap(); + assert_eq!(undo_len(&app), undo + 1, "the rectangle is a step of its own"); + set(&app, id, "layout", json!("column")); + frame(&mut app); + assert_eq!(count(&app), 3, "the next preview keeps the rectangle"); + cancel(&app, id); + frame(&mut app); + assert!(!app.session.in_interaction()); + assert_eq!(count(&app), 3, "Cancel keeps the rectangle"); + assert_eq!(x0(&app, 1), 100.0, "Cancel rolls the preview back"); + assert_eq!(undo_len(&app), undo + 1); +} + #[test] fn an_add_on_preview_waits_for_its_opening_drawing() { let mut app = two_drawings(); diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index f1585adc6b..11b9dc7a8f 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -4,7 +4,7 @@ use std::sync::{Arc, Weak}; use serde_json::Value; -use vectorcraft_doc::Selection; +use vectorcraft_doc::{Document, Selection}; use crate::VectorcraftApp; @@ -13,15 +13,22 @@ use crate::VectorcraftApp; #[derive(Clone, Default)] pub(crate) struct LivePreview { previewed: Option<(String, Value)>, + /// The last preview ran without an error, so its result is on show. + shown: bool, + /// The document the last preview ran on: a command from outside the dialog that changes it has the preview run + /// again, even one that failed. + snapshot: Weak, owner: Option, } /// The interaction a preview ran in: its document's `uid` and `reverts`, and the selection snapshot the interaction -/// began with, which no other interaction shares. +/// began with, which no other interaction shares. A marked interaction ([`LivePreview::keep_outside_edits`]) is +/// known by its mark instead, since a command from outside the dialog can give it a new selection. #[derive(Clone)] struct Owner { document: (u64, u64), selection: Weak, + marked: bool, } impl LivePreview { @@ -30,7 +37,9 @@ impl LivePreview { let Some(owner) = &self.owner else { return false }; app.session.active().is_some_and(|state| { (state.uid, state.reverts) == owner.document - && state.interaction.as_ref().is_some_and(|interaction| owner.selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + && state.interaction.as_ref().is_some_and(|interaction| { + owner.selection.as_ptr() == Arc::as_ptr(&interaction.selection) || (owner.marked && interaction.dialog) + }) }) } @@ -56,8 +65,14 @@ impl LivePreview { self.owner = None; return None; } + // A command from outside the dialog took a shown preview off its interaction: it runs again. + let taken_off = app + .session + .active() + .and_then(|state| state.interaction.as_ref()) + .is_some_and(|it| (self.shown && it.preview.is_none()) || self.snapshot.as_ptr() != Arc::as_ptr(&it.doc)); let same = self.previewed.as_ref().is_some_and(|(c, p)| c == cmd && p == params); - if same { + if same && !taken_off { return None; } // Another dialog's, a panel's or a tool's edit in progress gets no preview of this one. @@ -87,9 +102,11 @@ impl LivePreview { } }; self.previewed = Some((cmd.to_string(), params.clone())); + self.shown = answer.is_ok(); self.owner = app.session.active().and_then(|state| { let interaction = state.interaction.as_ref()?; - Some(Owner { document: (state.uid, state.reverts), selection: Arc::downgrade(&interaction.selection) }) + self.snapshot = Arc::downgrade(&interaction.doc); + Some(Owner { document: (state.uid, state.reverts), selection: Arc::downgrade(&interaction.selection), marked: interaction.dialog }) }); Some(answer) } @@ -131,6 +148,18 @@ impl LivePreview { Self::default().commit(app, cmd, params) } + /// Has a command from outside the dialog (a panel's Delete) run as an undo step of its own while this preview + /// shows, so that the next preview, OK and Cancel keep its edit. + pub(crate) fn keep_outside_edits(&mut self, app: &mut VectorcraftApp) { + if self.owns(app) + && let Some(interaction) = app.session.active_mut().and_then(|state| state.interaction.as_mut()) + && let Some(owner) = &mut self.owner + { + interaction.dialog = true; + owner.marked = true; + } + } + /// Cancel: rolls a shown preview back, and leaves any other edit in progress as it is. pub(crate) fn cancel(self, app: &mut VectorcraftApp) { if self.previewed.is_some() && self.owns(app) { diff --git a/docs/mcp.md b/docs/mcp.md index 93dff42eba..1322ade27b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -889,7 +889,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. The same holds for a step that is neither a number nor null, a `reflect` that is not a string, a `copy` that is not true or false, and an `origin` that is not two numbers. A null `rotate`, `scale`, `scaleX`, `scaleY`, `shear`, `reflect`, `copy` or `origin` is left out; a null `dx` or `dy` counts as 0, so it still runs the move. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. A type object in `ids` with another of them above it in its layer is the text to wrap, not a wrap object, so the objects and the type can be selected together. The reply has a `warning` when no area type lies below any of the wrap objects. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | -| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | +| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview, except during an add-on dialog's preview (Object › Plug-ins, other than Edit Points Only): there a command that changes the document records its own undo step, acts on the document without the preview, and stays after the dialog's Cancel or OK, and the dialog previews again from the command's result and selection. `edit.copy` and the `file.*` commands other than `file.documentColorMode` still run on the document as the preview shows it. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | | `agent_folders` | `{}` | Where VectorCraft opens and saves files for this session: `{read_folder, write_folder}`, each a path or `null`. In the open window, the agent folders of Preferences › AI Integrations (`Documents/ArtCraft/Agents/VectorCraft` for an empty one); in a headless session started for agents, the folders it was confined to (`read_folders` / `write_folders` list them all when a kind has several); a session started without automation roots answers `unrestricted: true`. An app reached with the deprecated `--connect` answers an error: its own `--automation-*-root` flags, if any, confine it. | For example, create editable Japanese area type with the engine's vertical writing mode: From 22b169a90547fab18aaf9914ddd5efc92e877676 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 17:29:32 -0800 Subject: [PATCH 29/56] Scripts: a group's pathItems.removeAll() walks only the group removeAll() on a layer's or group's pathItems walked every object in the document to check clipping paths, even when the collection was empty or held two paths. It now walks the container's own objects, or, when the container sits in the clipping path of a clipping group, the subtree of the highest such clipping path and the group it clips. An empty collection walks nothing. The document's own pathItems.removeAll() still checks every object. A scoped removeAll() now also throws when a path id in the list resolves to an object outside the container, which a damaged file with repeated ids can cause, instead of deleting that other object. The walk came in with #9288 ("Scripts: paths, path points and colors for scripts"). --- crates/engine/src/script/dom.rs | 2 ++ crates/engine/src/script/dom/paths.rs | 41 ++++++++++++++++++++++++++- crates/engine/src/tests/script_dom.rs | 22 ++++++++++++++ 3 files changed, 64 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 3c12eb0027..0cc25dc6fe 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -122,6 +122,8 @@ pub(super) use colors::of_color as color_data; #[cfg(test)] pub(crate) use paths::POINT_LOOKS; #[cfg(test)] +pub(crate) use paths::REMOVE_ALL_VISITS; +#[cfg(test)] pub(crate) use paths::index_builds; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index cc1cbe6a62..01dc239c1f 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -638,6 +638,12 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { } } +#[cfg(test)] +thread_local! { + /// How many objects [`items_remove_all`] walked on this thread, for the tests. + pub(crate) static REMOVE_ALL_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or /// locked path, one in a hidden or locked layer or group, or one on a locked artboard stops it /// before anything is deleted, as `PageItems.removeAll()` does. A compound path's @@ -658,9 +664,42 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let refused: Vec = ids.iter().filter(|i| !editable(d, **i)).map(|i| i.0).take(20).collect(); let locks = d.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - let mut next: Vec<_> = d.layers.iter().collect(); + // The document's list is checked against every object. A layer's or group's list is checked + // against the container's subtree, or, when the container lies in the clipping path of a + // clipping group above it, against the subtree of the highest such clipping path and the + // group it clips; no other outline holds its paths. An empty list is not walked. + let mut next: Vec<&Arc> = Vec::new(); let mut nodes = Vec::new(); + if !ids.is_empty() { + match c.and_then(|c| d.index_path(c)) { + None => next.extend(d.layers.iter()), + Some(at) => { + // A damaged file can give two objects one id; a path that the id finds outside + // the container would be deleted in place of the container's own. + if let Some(id) = ids.iter().find(|i| d.index_path(**i).is_none_or(|p| p.len() != at.len() + 1 || !p.starts_with(&at))) { + return Err(HostError::Error(format!("cannot delete PathItem {}: its id also names another object", id.0))); + } + let mut line: Vec<&Arc> = Vec::with_capacity(at.len()); + let mut kids = d.layers.as_slice(); + for &i in &at { + let Some(n) = kids.get(i) else { break }; + line.push(n); + kids = n.children().map_or(&[][..], Vec::as_slice); + } + // A clipping path is its group's first child, found by place, not by id. + let clip = (1..line.len()).find(|&k| line[k - 1].clips() && at[k] == 0); + if let Some(k) = clip { + #[cfg(test)] + REMOVE_ALL_VISITS.with(|v| v.set(v.get() + 1)); + nodes.push(line[k - 1]); + } + next.extend(line.get(clip.unwrap_or(line.len().saturating_sub(1))).copied()); + } + } + } while let Some(n) = next.pop() { + #[cfg(test)] + REMOVE_ALL_VISITS.with(|v| v.set(v.get() + 1)); nodes.push(n); next.extend(n.children().into_iter().flatten()); } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 54926e1659..6b45c5105f 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -4058,6 +4058,28 @@ const CAUGHT_PATHS_REMOVE_ALL: &str = "var p = app.activeDocument.pathItems, m = try { p.removeAll(); } catch (e) { m = e.message; }\ vc.log(m); vc.log(p.length);"; +/// A group's `pathItems.removeAll()` walks the group, not the document: emptying a group of two +/// paths beside 500 other paths looks at a handful of objects, and an empty group's looks at none. +#[test] +fn group_path_items_remove_all_walks_only_the_group() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + for i in 0..500 { + rect(&mut s, f64::from(i % 25) * 10.0, f64::from(i / 25) * 10.0, 5.0, 5.0); + } + s.execute("select.none", &json!({})).unwrap(); + let start = crate::script::dom::REMOVE_ALL_VISITS.with(|n| n.get()); + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0]; g.pathItems.removeAll(); g.pathItems.removeAll();\ + vc.log(g.pathItems.length); vc.log(app.activeDocument.pathItems.length);", + ); + let visits = crate::script::dom::REMOVE_ALL_VISITS.with(|n| n.get()) - start; + assert_eq!(out, vec![json!(0), json!(500)]); + assert!(visits <= 3, "{visits} objects walked to empty a group of two paths"); +} + /// The document's `pathItems.removeAll()` refuses to delete the path that clips a group while the /// group keeps other art, and deletes nothing, as the scoped collections do. #[test] From eacba80e0c58ef5f1479d84ffd7e2950c7fa262c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 17:41:58 -0800 Subject: [PATCH 30/56] DXF Import: OK places the drawing the dialog previewed OK in DXF Import Options, for a DXF or DWG drawing placed by path, compared the file on disk with the previewed bytes and refused to place it when they differed. The place job now takes the bytes the dialog read (PlaceJob::with_bytes), so OK places the previewed drawing even when the file was written over meanwhile, and the UI thread no longer reads the file at OK. The placed object's link and the journaled file.place params keep the path, and the read roots in force still apply to it. A DXF drawing laid out again for an artboard that changed before it was placed uses the same bytes. --- crates/engine/src/cmd/fileio/importer.rs | 24 +++++++++++++-- crates/engine/src/cmd/place.rs | 39 ++++++++++++++++-------- crates/ui-egui/src/dialogs/dxf_import.rs | 34 +++++++++++---------- crates/ui-egui/src/dialogs/import_pdf.rs | 7 +++++ crates/ui-egui/src/place.rs | 17 ++++++++++- crates/ui-egui/src/placing.rs | 17 ++++++++++- 6 files changed, 105 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index c578dece5d..2add54d017 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -202,10 +202,28 @@ fn read_path_for(path: &str, _: &Value, _: Mode, _: &str) -> Result> { /// The file `file.place`'s params `p` name, as [`super::source`] reads it for command `cmd`, except /// that a file an importer would place (one `importer` names, or an extension no built-in format /// reads that an importer which places its files lists) is read, or decoded, only when it is at -/// most [`import::MAX_INPUT_BYTES`] long. -pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result> { +/// most [`import::MAX_INPUT_BYTES`] long. `given`: the bytes of the file `path` names, read already, +/// which are used instead of reading the path again (by the same size rule). +pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str, given: Option<&[u8]>) -> Result> { match str_param(p, "path") { - Some(path) => Ok(Source { name: path, bytes: read_path_for(path, p, Mode::Place, cmd)?, path: Some(path) }), + Some(path) => { + let bytes = match given { + Some(bytes) => { + // The roots in force now still apply to the path, though it is not read again. + #[cfg(not(target_arch = "wasm32"))] + super::may_read(path)?; + let explicit = named(p, cmd)?.is_some(); + let importer = explicit || importer_reads(&extension(path), Mode::Place); + let built_in = !explicit && detect(path, bytes.get(..SNIFF_BYTES).unwrap_or(bytes)).is_some(); + if importer && !built_in && bytes.len() > import::MAX_INPUT_BYTES { + return Err(too_large(path, Mode::Place)); + } + bytes.to_vec() + } + None => read_path_for(path, p, Mode::Place, cmd)?, + }; + Ok(Source { name: path, bytes, path: Some(path) }) + } None => { check_data_for(p, Mode::Place, cmd)?; super::source(p, cmd) diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 9d145853b9..b793008142 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -183,13 +183,13 @@ pub(crate) fn pt_per_px(ppi: Option<(f64, f64)>) -> (f64, f64) { /// [`load_sliced`] without the slices. fn load(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result { - load_into(p, cmd, board, link_pdf, &mut vec![]) + load_into(p, cmd, board, link_pdf, None, &mut vec![]) } /// [`load_into`], with the slices of a PSD or PSB file that `importSlices` brings in. -fn load_sliced(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result<(Loaded, Slices)> { +fn load_sliced(p: &Value, cmd: &str, board: Option, link_pdf: bool, given: Option<&[u8]>) -> Result<(Loaded, Slices)> { let mut slices = vec![]; - let l = load_into(p, cmd, board, link_pdf, &mut slices)?; + let l = load_into(p, cmd, board, link_pdf, given, &mut slices)?; Ok((l, slices)) } @@ -197,9 +197,10 @@ fn load_sliced(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Res /// (unless the params name their own box). A PDF/.ai page or an EPS file read from a path is placed /// linked with Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB /// file's slices go to `slices`. A file an importer plug-in places (the one `importer` names, or one -/// no built-in format reads) is read by it ([`plugin_art`]). -fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_out: &mut Slices) -> Result { - let src = fileio::importer::place_source(p, cmd)?; +/// no built-in format reads) is read by it ([`plugin_art`]). `given`: the bytes of the file `p`'s +/// `path` names, read already ([`PlaceJob::with_bytes`]). +fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, given: Option<&[u8]>, slices_out: &mut Slices) -> Result { + let src = fileio::importer::place_source(p, cmd, given)?; let name = fileio::file_name(src.name); if let Some(plugin) = fileio::importer::named_for_place(src.name, p, cmd)? { return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd); @@ -760,8 +761,13 @@ pub struct PlaceJob { /// The object Replace swaps as it was when Place started. replaced: Option, target: Option, + /// The bytes of the file `path` names, read already ([`PlaceJob::with_bytes`]). + bytes: Option, } +/// The bytes of a file read already, shared with whoever read them ([`PlaceJob::with_bytes`]). +pub type GivenBytes = Arc + Send + Sync>; + /// A file [`PlaceJob::read`] read, which [`Session::place_read`] places. pub struct PlaceRead { job: PlaceJob, @@ -775,6 +781,14 @@ impl PlaceJob { str_param(&self.params, "path").or_else(|| str_param(&self.params, "name")).map(fileio::file_name).unwrap_or_else(|| "Untitled".into()) } + /// The job placing `bytes` as the file its `path` names, which [`PlaceJob::read`] then does not + /// read again: the placed object's link and the journaled params keep the path. Without a + /// `path` the bytes are not used. + pub fn with_bytes(mut self, bytes: GivenBytes) -> Self { + self.bytes = Some(bytes); + self + } + /// Read and decode the file, as `file.place` does, without the session. The pixels of a PNG, /// JPEG, GIF or WebP file are decoded here to check that they can be read (an error when they /// can't), a linked image's preview is made from that decode, and the decoded pixels are kept in @@ -782,7 +796,7 @@ impl PlaceJob { /// ([`super::links::readable_and_kept`]). pub fn read(self) -> Result { crate::cancel::check()?; - let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true)?; + let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true, self.bytes.as_deref().map(AsRef::as_ref))?; let linked = loaded.link.is_some() && bool_or(&self.params, "link", true); match &mut loaded.art { Art::Image(img, _) => { @@ -941,12 +955,12 @@ fn prepare(s: &Session, p: &Value) -> Result { (true, _) => return Err(bad(PLACE, "replace: select the one object to replace")), }; let replaced = old.and_then(|id| st.doc.node(id)).cloned(); - Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at) }) + Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at), bytes: None }) } /// Place the file `read` holds in the active document. fn apply(s: &mut Session, read: PlaceRead) -> Result { - let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded, slices: read_slices } = read; + let PlaceRead { job: PlaceJob { params, old, target: read_for, bytes, .. }, mut loaded, slices: read_slices } = read; let p = ¶ms; let template = bool_or(p, "template", false); let at = at_param(p)?; @@ -957,10 +971,11 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { None => None, }; // The artboard under `at` as it is now, as a replay of the journal finds it: a DXF drawing laid - // out on the artboard it was read for is read again when that artboard changed meanwhile. + // out on the artboard it was read for is read again when that artboard changed meanwhile, from + // the same bytes when the job was given them. let target = board_at(&st.doc, at); if loaded.board.is_some() && target != read_for { - loaded = load(p, PLACE, target, true)?; + loaded = load_into(p, PLACE, target, true, bytes.as_deref().map(AsRef::as_ref), &mut vec![])?; } // Type reflows rather than scales: its frame takes the size it is placed at. let is_text = matches!(loaded.art, Art::Text(_)); @@ -1347,7 +1362,7 @@ pub fn read_info(p: &Value) -> Result { check_switches(p, &["link"], "file.place.info")?; check_numbers(p, &["thumbnail"], "file.place.info")?; // A PDF/.ai page linked or not has the same size and art. - let (mut l, slices) = load_sliced(p, "file.place.info", None, false)?; + let (mut l, slices) = load_sliced(p, "file.place.info", None, false, None)?; let natural = l.natural; let mut out = json!({ "name": l.name, diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index 55e50c8972..c923a4ebc3 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -498,12 +498,6 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R if let Some(placement) = placement { placement.check(app)?; } - // Place reads the file again: it must still be the drawing the dialog previewed. - if let (Some(path), Some(read)) = (source.path.as_deref(), app.services.read.as_ref()) - && read(path)? != source.file.bytes - { - return Err(tl!("The drawing changed on disk. Place it again to use the new version.").to_owned()); - } app.ui.dxf_import = remembered; let mut p = with_file(place, source.path.as_deref(), &source.name, &source.file); p["dxf"] = dxf; @@ -530,8 +524,14 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R if let Some(converted) = &source.converted { app.placing.keep_next = Some(Box::new(converted.held.clone())); } + // The drawing placed is the one the dialog showed, not the file as it is on disk now; + // its link and the journal keep the path. + if let Some(path) = &source.path { + app.placing.bytes_next = Some((path.clone(), source.file.clone())); + } let r = crate::place::run_for_user(app, &p).map(|_| ()); app.placing.keep_next = None; + app.placing.bytes_next = None; if let (Some(current), Some(insertion)) = (current, restore) { current.restore_changed(&insertion, app); } @@ -924,7 +924,7 @@ mod tests { } /// A DWG drawing placed through its dialog is the drawing the dialog previewed: a file written - /// over it on disk while the dialog is open is not placed, and OK keeps the dialog open. + /// over it on disk while the dialog is open is not placed. #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn ok_places_the_drawing_the_dialog_previewed() { @@ -958,16 +958,18 @@ mod tests { finish_conversions(&mut app); assert_eq!(host::fields(&app, KIND)["mode"], "place"); std::fs::write(&plan, craft_dwg::dxf_to_dwg_as(flatter.as_bytes(), "AC1018").unwrap()).unwrap(); - let steps = app.session.doc().unwrap().history.undo.len(); - let refused = host::confirm(&mut app, KIND); - assert_eq!(refused, Err("The drawing changed on disk. Place it again to use the new version.".to_owned())); - assert!(host::is_open(&app, KIND), "the dialog stays open"); - assert!(app.placing.pending.is_empty()); - assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "nothing is placed"); - // Written back as it was, the drawing the dialog previewed is placed. - std::fs::write(&plan, craft_dwg::dxf_to_dwg_as(&drawing(), "AC1018").unwrap()).unwrap(); + let before = app.session.doc().unwrap().selection.objects.clone(); host::confirm(&mut app, KIND).unwrap(); - assert_eq!(placed_size(&mut app), previewed, "OK places the drawing the dialog opened on"); + let size = placed_size(&mut app); + assert_ne!(app.session.doc().unwrap().selection.objects, before, "OK places a new object"); + assert_eq!(size, previewed, "OK places the drawing the dialog opened on"); + assert!(app.placing.bytes_next.is_none()); + // Placed again, the file as it is on disk now is read. + let before = app.session.doc().unwrap().selection.objects.clone(); + crate::place::run_for_user(&mut app, &json!({ "path": plan, "showImportOptions": false })).unwrap(); + let size = placed_size(&mut app); + assert_ne!(app.session.doc().unwrap().selection.objects, before, "the place adds a new object"); + assert_ne!(size, previewed, "a later place reads the new file"); }); } diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index fb23157d9e..dd40e5d322 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -69,6 +69,13 @@ impl DialogFile { } } +/// The file's bytes, as a place given them reads them ([`vectorcraft_engine::cmd::place::GivenBytes`]). +impl AsRef<[u8]> for DialogFile { + fn as_ref(&self) -> &[u8] { + &self.bytes + } +} + /// Equal by token: a token names one file's bytes, so a dialog's values compare without reading them. impl PartialEq for DialogFile { fn eq(&self, other: &Self) -> bool { diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index b4d501fcd0..cec2a8b352 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -346,7 +346,22 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result engine(app, "file.place", &p), + _ => match crate::placing::given_bytes(app, &p) { + // A drawing placed through its import options places the bytes the dialog showed. + Some(bytes) => { + // The edit the tool computes on another thread comes first, as for `placing::start`. + let r = app.session.finish_tool_edit(); + crate::canvas::apply_requests(app, r); + let job = app.session.prepare_place(&p).and_then(|job| job.with_bytes(bytes).read()); + let r = job.and_then(|read| app.session.place_read(read)).map_err(|e| e.to_string()); + app.sync_views(); + if let Err(e) = &r { + app.status(e.clone()); + } + r + } + None => engine(app, "file.place", &p), + }, } } diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index a1eeb20879..91f71c5ed8 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -202,6 +202,10 @@ pub struct Placing { /// dropped: the conversion of a DWG drawing placed through its import options, which the read /// then finds without converting the drawing again. pub(crate) keep_next: Option>, + /// The path and the bytes of a drawing placed through its import options: the next place of + /// that path ([`crate::place::run_for_user`]) places these bytes, the ones the dialog showed, + /// instead of reading the file again. + pub(crate) bytes_next: Option<(String, vectorcraft_engine::cmd::place::GivenBytes)>, /// A deferred paste awaiting its own Swatch Conflict dialog. swatch_paste: Option, /// Set by unit tests whose app reads the files the user places off the UI thread. @@ -305,12 +309,23 @@ pub fn start(app: &mut VectorcraftApp, p: &Value, dropped: bool) -> Result Option { + let (path, bytes) = app.placing.bytes_next.take()?; + (p.get("path").and_then(Value::as_str) == Some(path.as_str())).then_some(bytes) +} + /// `file.place.queue` with `p` for the active document, its files read and their thumbnails made off /// the UI thread → `{background: true, status}`; the place cursor is loaded once they are ready. /// `asks`: the cursor's files ask for their import options when placed ([`crate::place::show_thumbnails`]). From e69e51dbddb19760d81a5c7edb8b710714ea7835 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 17:44:05 -0800 Subject: [PATCH 31/56] DXF import: REGION entities open as filled paths A REGION holds its outline as solid-modeler data. The import now reads it and draws each face's boundary loops as one filled path (even-odd), so holes stay open. Lines, circles, ellipses and spline edges keep their shape; coedge and edge directions and a body's transform are applied. The data is read from the text in groups 1 and 3 (DXF R13 to 2010, ciphered or not) and from the binary data in the ACDSDATA section (DXF 2013 and later, with either binary signature), so DWG drawings converted to DXF bring their regions too. Damaged data is reported instead of drawn silently: edges of other curve types come in straight, outlines that break off are closed with a straight line, and a spline edge whose endpoint lies on two parts of a self-crossing curve is trimmed at the nearer one, each with a warning. Regions that can't be read, or that go over the record or path element limits, are left out and listed. The DXF import fuzz tests now include REGION entities and mutated text and binary region data. --- crates/cad/src/import.rs | 6 +- crates/cad/src/import/acis.rs | 751 ++++++++++++++++++++++++++ crates/cad/src/import/build.rs | 4 +- crates/cad/src/import/entity.rs | 52 +- crates/cad/src/import/reader.rs | 51 +- crates/cad/src/import/tests_region.rs | 637 ++++++++++++++++++++++ crates/engine/tests/import_fuzz.rs | 132 ++++- docs/file-format-parity.md | 2 +- 8 files changed, 1625 insertions(+), 10 deletions(-) create mode 100644 crates/cad/src/import/acis.rs create mode 100644 crates/cad/src/import/tests_region.rs diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index 5a5582efe1..bed5bef361 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -6,7 +6,7 @@ //! or with the drawing's origin on the artboard's bottom-left corner. Each DXF layer holding art //! becomes a layer (hidden, frozen, locked and non-plotting layers keep that), or all art goes on //! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid -//! hatches and solids become paths; text and multiline text point type; named blocks symbols +//! hatches, solids and regions become paths; text and multiline text point type; named blocks symbols //! (anonymous ones, such as dimensions, groups of their art). Colours (indexed and true colour), //! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve //! them. What can't come in is listed in the warnings. @@ -16,8 +16,10 @@ //! - `entity`: entities to items (geometry and properties). //! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths. //! - `text`: text values to plain text. +//! - `acis`: a region's solid-modeler data as its outline. //! - `build`: items to the document. +mod acis; mod build; mod curve; mod entity; @@ -237,3 +239,5 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result { mod tests; #[cfg(test)] mod tests_dwg; +#[cfg(test)] +mod tests_region; diff --git a/crates/cad/src/import/acis.rs b/crates/cad/src/import/acis.rs new file mode 100644 index 0000000000..bb1bc92a1c --- /dev/null +++ b/crates/cad/src/import/acis.rs @@ -0,0 +1,751 @@ +//! The solid-modeler data of a REGION as a filled outline: each face's loops of edges, in world x +//! and y (drawing units). The data comes as text (DXF before 2013, ciphered or not) or binary +//! (DXF 2013 and later keep it in the ACDSDATA section). +//! +//! The model is a list of records pointing at each other: a body holds lumps, a lump shells, a +//! shell faces, a face loops, a loop a ring of coedges. Each coedge uses an edge (forward or +//! reversed), and each edge runs between two vertices along a line, an ellipse or a spline. A +//! curve of any other kind comes in as a straight line between its vertices. +//! +//! The REGION groups are in the DXF Reference +//! (); which +//! DXF versions hold text and which binary data is in . + +use std::collections::HashMap; + +use kurbo::{BezPath, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathSeg}; +use vectorcraft_geom::{Affine, Point}; + +use super::curve; + +/// The most bytes of one region's data read. +pub(crate) const MAX_BYTES: usize = 16 << 20; +/// The most records one region's outline may visit: bodies, lumps, shells, faces and coedges +/// (a loop counts as one at least). +const MAX_VISITS: usize = 1_000_000; +/// The first bytes of binary data: ACIS's, or ASM's (DXF 2018 writes either). +const BINARY_MAGIC: [&[u8]; 2] = [b"ACIS BinaryFile", b"ASM BinaryFile4"]; +/// From this version on, every record starts with its attribute, a history number and one more +/// pointer; before it, with its attribute alone. +const LONG_HEADER_VERSION: u32 = 700; + +type P3 = [f64; 3]; +/// A B-spline: degree, knots, control points, weights (none: all 1). +type Spline = (usize, Vec, Vec, Option>); + +/// One value of a record. +#[derive(Clone, Debug, PartialEq)] +enum Tok { + Ptr(i64), + Num(f64), + Word(String), + /// `forward` (false) or `reversed` (true). + Sense(bool), + Open, + Close, +} + +/// A record: its type (`body`, `plane-surface`…) and its values after the ones every record +/// starts with. +#[derive(Debug)] +struct Rec { + kind: String, + toks: Vec, +} + +impl Rec { + /// The type `base` or one derived from it (`tedge-edge` is an edge). + fn is(&self, base: &str) -> bool { + self.kind == base || self.kind.strip_suffix(base).is_some_and(|k| k.ends_with('-')) + } + + /// The `n`th pointer (-1: none). + fn ptr(&self, n: usize) -> i64 { + self.toks.iter().filter_map(|t| if let Tok::Ptr(p) = t { Some(*p) } else { None }).nth(n).unwrap_or(-1) + } + + /// The sense right after the `n`th pointer: true when reversed (old files write 1). + fn sense_after(&self, n: usize) -> Option { + let mut ptrs = 0; + for t in &self.toks { + if ptrs > n { + return match t { + Tok::Sense(r) => Some(*r), + Tok::Num(v) if v.is_finite() => Some(*v != 0.0), + _ => None, + }; + } + if matches!(t, Tok::Ptr(_)) { + ptrs += 1; + } + } + None + } + + /// The numbers, in order. + fn nums(&self) -> Vec { + self.toks.iter().filter_map(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect() + } +} + +/// The records of one body, and how pointers find them. +struct Model { + recs: Vec, + /// Record number by index, when the records carry their own. + at: HashMap, +} + +impl Model { + fn get(&self, p: i64) -> Option<&Rec> { + if p < 0 { + return None; + } + if self.at.is_empty() { self.recs.get(usize::try_from(p).ok()?) } else { self.recs.get(*self.at.get(&p)?) } + } + + /// The record `p` points at when it is of type `base`. + fn get_is(&self, p: i64, base: &str) -> Option<&Rec> { + self.get(p).filter(|r| r.is(base)) + } + + /// The records of type `base` from `first` along their `next` pointer (pointer `next`), each + /// once. Missing records, wrong types and cycles outside coedge rings set `broken`. + fn chain(&self, first: i64, base: &str, next: usize, broken: &mut bool) -> Vec<&Rec> { + let mut out = vec![]; + let mut seen = std::collections::HashSet::new(); + let mut p = first; + while p >= 0 { + if !seen.insert(p) { + *broken |= base != "coedge"; + break; + } + let Some(r) = self.get_is(p, base) else { + *broken = true; + break; + }; + out.push(r); + p = r.ptr(next); + } + out + } +} + +/// A region's outline: its faces' loops, closed; `approximated` when an edge of a curve type +/// this reader doesn't draw came in as a straight line; `broken` when a topology chain breaks +/// off or a loop's ring of coedges doesn't come back to its first; `ambiguous` when an edge's +/// endpoint lies on separate parts of its curve. +#[derive(Debug)] +pub(crate) struct Outline { + pub path: BezPath, + pub approximated: bool, + pub broken: bool, + pub ambiguous: bool, +} + +/// Text data, ciphered as DXF writes it or not. +pub(crate) fn from_text(text: &str) -> Option { + if text.len() > MAX_BYTES { + return None; + } + let plain; + let text = if text.trim_start().starts_with(|c: char| c.is_ascii_digit()) { + text + } else { + plain = decipher(text); + &plain + }; + outline(&sat_model(text)?) +} + +/// Binary data. +pub(crate) fn from_binary(bytes: &[u8]) -> Option { + if bytes.len() > MAX_BYTES { + return None; + } + outline(&sab_model(bytes)?) +} + +/// DXF's cipher of text data undone: each printable character is mapped back, and the space +/// written after a mapped `A` (a caret, which DXF reads as a control code) is dropped. +fn decipher(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + out.push(match c { + ' ' | '\n' | '\r' | '\t' => c, + '@'..='_' => char::from(159 - c as u8), + c if c.is_ascii() && !c.is_ascii_control() => char::from(c as u8 ^ 0x5F), + c => c, + }); + if c == '^' && chars.peek() == Some(&' ') { + chars.next(); + } + } + out +} + +/// How many values every record starts with in data of `version`. +fn header_len(version: u32) -> usize { + if version >= LONG_HEADER_VERSION { 3 } else { 1 } +} + +/// A text value as a value. +fn sat_tok(w: &str) -> Tok { + match w { + "{" => Tok::Open, + "}" => Tok::Close, + "forward" | "forward_v" => Tok::Sense(false), + "reversed" | "reversed_v" => Tok::Sense(true), + _ => { + if let Some(p) = w.strip_prefix('$').and_then(|p| p.parse::().ok()) { + return Tok::Ptr(p); + } + match w.parse::() { + Ok(v) if v.is_finite() => Tok::Num(v), + _ => Tok::Word(w.to_string()), + } + } + } +} + +/// Does this line start a record (`[-] $ …`)? +fn starts_record(line: &str) -> bool { + let mut words = line.split_whitespace(); + let first = words.next().unwrap_or_default(); + let (kind, next) = if first.starts_with('-') && first[1..].parse::().is_ok() { + (words.next().unwrap_or_default(), words.next().unwrap_or_default()) + } else { + (first, words.next().unwrap_or_default()) + }; + kind.starts_with(|c: char| c.is_ascii_alphabetic()) && next.starts_with('$') +} + +/// Text data's records: a version line, product and tolerance lines, then records ending in `#`. +fn sat_model(text: &str) -> Option { + let version = text.split_whitespace().next()?.parse::().ok().filter(|v| v.is_finite() && *v >= 0.0)? as u32; + let skip = header_len(version); + let mut offset = text.find('\n')? + 1; + let start = loop { + let rest = text.get(offset..)?; + let line = rest.split('\n').next().unwrap_or_default(); + if starts_record(line) { + break offset; + } + offset += line.len() + 1; + }; + let body = text.get(start..)?; + let (mut recs, mut at) = (Vec::new(), HashMap::new()); + let mut cur: Vec = vec![]; + let (mut kind, mut index): (Option, Option) = (None, None); + let mut i = 0; + let b = body.as_bytes(); + while i < b.len() { + if b[i].is_ascii_whitespace() { + i += 1; + continue; + } + let end = b[i..].iter().position(u8::is_ascii_whitespace).map_or(b.len(), |n| i + n); + let word = body.get(i..end)?; + i = end; + // A counted string: `@`, a space, then n bytes. + if let Some(n) = word.strip_prefix('@').and_then(|n| n.parse::().ok()) { + let from = (i + 1).min(b.len()); + let to = from.checked_add(n)?.min(b.len()); + cur.push(Tok::Word(body.get(from..to)?.to_string())); + i = to; + continue; + } + let (word, ends) = match word.strip_suffix('#') { + Some(w) => (w, true), + None => (word, false), + }; + if !word.is_empty() { + match &kind { + None if index.is_none() && word.starts_with('-') && word[1..].parse::().is_ok() => { + index = word[1..].parse().ok(); + } + None => { + if word.starts_with("End-of-") || word.starts_with("Begin-of-") { + break; + } + kind = Some(word.to_string()); + } + Some(_) => cur.push(sat_tok(word)), + } + } + if ends { + let toks = cur.split_off(skip.min(cur.len())); + cur.clear(); + if let Some(n) = index.take() { + at.insert(n, recs.len()); + } + recs.push(Rec { kind: kind.take().unwrap_or_default(), toks }); + } + } + Some(Model { recs, at }) +} + +/// Reads binary data's little-endian values. +struct Bytes<'b> { + b: &'b [u8], + i: usize, +} + +impl Bytes<'_> { + fn take(&mut self, n: usize) -> Option<&[u8]> { + let s = self.b.get(self.i..self.i.checked_add(n)?)?; + self.i += n; + Some(s) + } + fn u8(&mut self) -> Option { + self.take(1).map(|s| s[0]) + } + fn i16(&mut self) -> Option { + self.take(2).map(|s| f64::from(i16::from_le_bytes([s[0], s[1]]))) + } + fn u16(&mut self) -> Option { + self.take(2).map(|s| usize::from(u16::from_le_bytes([s[0], s[1]]))) + } + fn i32(&mut self) -> Option { + self.take(4).map(|s| i32::from_le_bytes([s[0], s[1], s[2], s[3]])) + } + fn u32(&mut self) -> Option { + self.take(4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])) + } + fn f64(&mut self) -> Option { + let s = self.take(8)?; + Some(f64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]])) + } + fn text(&mut self, n: usize) -> Option { + self.take(n).map(|s| String::from_utf8_lossy(s).into_owned()) + } +} + +/// Binary data's records: the magic, four numbers (version first), product and tolerance values, +/// then records of tagged values, each type name made of its parts. +fn sab_model(b: &[u8]) -> Option { + let mut r = Bytes { b: BINARY_MAGIC.iter().find_map(|m| b.strip_prefix(*m))?, i: 0 }; + let version = r.u32()?; + r.take(12)?; + let skip = header_len(version); + let mut recs = vec![]; + let (mut parts, mut kind, mut cur): (Vec, Option, Vec) = (vec![], None, vec![]); + while r.i < r.b.len() { + let tag = r.u8()?; + let tok = match tag { + 0x02 => Tok::Num(f64::from(i8::from_le_bytes([r.u8()?]))), + 0x03 => Tok::Num(r.i16()?), + 0x04 | 0x15 => Tok::Num(f64::from(r.i32()?)), + 0x05 => Tok::Num(f64::from(f32::from_le_bytes(r.take(4)?.try_into().ok()?))), + 0x06 | 0x17 => Tok::Num(r.f64()?), + 0x07 => { + let n = usize::from(r.u8()?); + Tok::Word(r.text(n)?) + } + 0x08 => { + let n = r.u16()?; + Tok::Word(r.text(n)?) + } + 0x09 | 0x12 => { + let n = usize::try_from(r.u32()?).ok()?; + Tok::Word(r.text(n)?) + } + 0x0A => Tok::Sense(true), + 0x0B => Tok::Sense(false), + 0x0C => Tok::Ptr(i64::from(r.i32()?)), + 0x0D | 0x0E => { + let n = usize::from(r.u8()?); + let name = r.text(n)?; + if kind.is_some() { + Tok::Word(name) + } else { + parts.push(name); + if tag == 0x0D { + let k = parts.join("-"); + parts.clear(); + if k.starts_with("End-of-") || k.starts_with("Begin-of-") { + break; + } + kind = Some(k); + } + continue; + } + } + 0x0F => Tok::Open, + 0x10 => Tok::Close, + 0x11 => { + if let Some(k) = kind.take() { + let toks = cur.split_off(skip.min(cur.len())); + recs.push(Rec { kind: k, toks }); + } + cur.clear(); + continue; + } + 0x13 | 0x14 => { + for _ in 0..3 { + cur.push(Tok::Num(r.f64()?)); + } + continue; + } + 0x16 => { + for _ in 0..2 { + cur.push(Tok::Num(r.f64()?)); + } + continue; + } + _ => return None, + }; + // Values before the first record are the header's. + if kind.is_some() { + cur.push(tok); + } + } + Some(Model { recs, at: HashMap::new() }) +} + +/// A body's placement: `p · m · scale + t`. +#[derive(Clone, Copy)] +struct Xf { + m: [P3; 3], + scale: f64, + t: P3, +} + +impl Xf { + const IDENTITY: Xf = Xf { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], scale: 1.0, t: [0.0; 3] }; + + /// A `transform` record's: nine matrix numbers row by row, the translation, the scale. + fn read(r: &Rec) -> Option { + let n: Vec = r.toks.iter().map_while(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect(); + if n.iter().any(|v| !v.is_finite()) { + return None; + } + let v = |i: usize| n.get(i).copied(); + let row = |i: usize| Some([v(i)?, v(i + 1)?, v(i + 2)?]); + let scale = v(12)?; + Some(Xf { m: [row(0)?, row(3)?, row(6)?], t: row(9)?, scale }) + } + + fn vector(&self, p: P3) -> P3 { + let [a, b, c] = self.m; + std::array::from_fn(|i| (p[0] * a[i] + p[1] * b[i] + p[2] * c[i]) * self.scale) + } + + fn point(&self, p: P3) -> P3 { + let v = self.vector(p); + std::array::from_fn(|i| v[i] + self.t[i]) + } +} + +/// Seen from above: x and y. +fn flat(p: P3) -> Point { + Point::new(p[0], p[1]) +} + +fn sub(a: P3, b: P3) -> P3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn dot(a: P3, b: P3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn cross(a: P3, b: P3) -> P3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn p3(n: &[f64], i: usize) -> Option { + Some([*n.get(i)?, *n.get(i + 1)?, *n.get(i + 2)?]) +} + +/// Endpoints farther apart than rounding at their coordinate size allows. +fn endpoints_apart(a: Point, b: Point) -> bool { + a.distance(b) > 1e-6 * (1.0 + a.x.hypot(a.y).max(b.x.hypot(b.y))) +} + +/// Every face's loops of every body, as one path (filled even-odd). +fn outline(m: &Model) -> Option { + let mut o = Outline { path: BezPath::new(), approximated: false, broken: false, ambiguous: false }; + // Records visited at every level together: chains shared between records are walked again + // each time. + let mut visits = 0usize; + let mut spend = |n: usize| { + visits = visits.saturating_add(n.max(1)); + (visits <= MAX_VISITS).then_some(()) + }; + for body in m.recs.iter().filter(|r| r.is("body")) { + spend(1)?; + let xf = if body.ptr(2) == -1 { Xf::IDENTITY } else { Xf::read(m.get_is(body.ptr(2), "transform")?)? }; + for lump in m.chain(body.ptr(0), "lump", 0, &mut o.broken) { + spend(1)?; + for shell in m.chain(lump.ptr(1), "shell", 0, &mut o.broken) { + spend(1)?; + for face in m.chain(shell.ptr(2), "face", 0, &mut o.broken) { + spend(1)?; + for lp in m.chain(face.ptr(1), "loop", 0, &mut o.broken) { + let ring = m.chain(lp.ptr(1), "coedge", 0, &mut o.broken); + spend(ring.len())?; + let complete = ring.last().is_some_and(|c| c.ptr(0) == lp.ptr(1)); + o.broken |= !complete; + let mut bp = BezPath::new(); + for c in ring { + let edge = m.get_is(c.ptr(3), "edge")?; + let (seg, ambiguous) = edge_path(m, edge, c.sense_after(3)?, &xf, &mut o.approximated)?; + o.ambiguous |= ambiguous; + if let (Some(end), Some(start)) = + (bp.elements().last().and_then(|e| e.end_point()), seg.elements().first().and_then(|e| e.end_point())) + { + o.broken |= endpoints_apart(end, start); + } + super::entity::append(&mut bp, &seg); + if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS { + return None; + } + } + if !bp.elements().is_empty() { + if complete + && let (Some(end), Some(start)) = + (bp.elements().last().and_then(|e| e.end_point()), bp.elements().first().and_then(|e| e.end_point())) + { + o.broken |= endpoints_apart(end, start); + } + bp.close_path(); + if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS { + return None; + } + o.path.extend(bp); + } + } + } + } + } + } + let ok = !o.path.elements().is_empty() && curve::bounds(&o.path).is_some(); + ok.then_some(o) +} + +/// A vertex's position. +fn vertex(m: &Model, p: i64) -> Option { + let v = m.get_is(p, "vertex")?; + let n = m.get_is(v.ptr(1), "point")?.nums(); + p3(&n, 0).filter(|p| p.iter().all(|c| c.is_finite())) +} + +/// The edge as a coedge runs it (`reversed`: from its end vertex to its start), from the first +/// point. +fn edge_path(m: &Model, edge: &Rec, reversed: bool, xf: &Xf, approximated: &mut bool) -> Option<(BezPath, bool)> { + let (sv, ev) = (vertex(m, edge.ptr(0))?, vertex(m, edge.ptr(1))?); + let closed = edge.ptr(0) == edge.ptr(1); + let (from, to) = if reversed { (ev, sv) } else { (sv, ev) }; + // Against the curve's own direction? + let back = edge.sense_after(3)? != reversed; + let drawn = match m.get(edge.ptr(3)) { + // Only -1 means the edge has no curve. + None => { + *approximated |= edge.ptr(3) != -1; + None + } + Some(c) if c.is("straight-curve") => None, + Some(c) => { + let bp = if c.is("ellipse-curve") { + ellipse(c, from, to, closed, back, xf).map(|bp| (bp, false)) + } else if c.is("intcurve-curve") { + spline(c, from, to, closed, back, xf) + } else { + None + }; + *approximated |= bp.is_none(); + bp + } + }; + if let Some(bp) = drawn { + return Some(bp); + } + let mut bp = BezPath::new(); + bp.move_to(flat(xf.point(from))); + bp.line_to(flat(xf.point(to))); + Some((bp, false)) +} + +/// An `ellipse-curve` (centre, normal, major axis, ratio) from `from` to `to`; the whole curve +/// when the edge starts and ends at one vertex. It runs counter-clockwise about its normal, +/// clockwise when `back`. +fn ellipse(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option { + let n = c.nums(); + let (centre, normal, major, ratio) = (p3(&n, 0)?, p3(&n, 3)?, p3(&n, 6)?, *n.get(9)?); + let len = dot(normal, normal).sqrt(); + if !(len > 1e-12 && ratio > 0.0 && ratio.is_finite() && dot(major, major) > 1e-24) { + return None; + } + let minor = cross(normal, major).map(|v| v / len * ratio); + let angle = |p: P3| { + let d = sub(p, centre); + (dot(d, minor) / dot(minor, minor)).atan2(dot(d, major) / dot(major, major)) + }; + let (a, b) = (angle(from), angle(to)); + let tau = std::f64::consts::TAU; + let sweep = match (closed, back) { + (true, false) => tau, + (true, true) => -tau, + (false, false) => (b - a).rem_euclid(tau), + (false, true) => -(a - b).rem_euclid(tau), + }; + let (o, u, v) = (flat(xf.point(centre)), flat(xf.vector(major)), flat(xf.vector(minor))); + curve::ellipse(Affine::new([u.x, u.y, v.x, v.y, o.x, o.y]), a, sweep) +} + +/// An `intcurve-curve`'s B-spline (`nubs`, or `nurbs` with weights): degree, form, the knots +/// with their multiplicities (without the end knots, or with them), the control points. +fn bspline(toks: &[Tok]) -> Option { + let at = toks.iter().position(|t| matches!(t, Tok::Word(w) if matches!(w.as_str(), "nubs" | "nurbs" | "nullbs")))?; + let rational = match &toks[at] { + Tok::Word(w) if w == "nurbs" => true, + Tok::Word(w) if w == "nubs" => false, + _ => return None, + }; + let num = |i: usize| if let Some(Tok::Num(v)) = toks.get(i) { Some(*v) } else { None }; + let degree = num(at + 1).filter(|d| (1.0..=32.0).contains(d))? as usize; + let count = num(at + 3).filter(|n| *n >= 1.0 && *n <= toks.len() as f64)? as usize; + let mut knots = vec![]; + let mut i = at + 4; + for _ in 0..count { + let (k, mult) = (num(i)?, num(i + 1)?); + if !(mult >= 1.0 && mult <= (degree + 1) as f64) { + return None; + } + knots.extend(std::iter::repeat_n(k, mult as usize)); + i += 2; + } + let stride = if rational { 4 } else { 3 }; + let values: Vec = toks[i.min(toks.len())..].iter().map_while(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect(); + let available = values.len() / stride; + // The data leaves out the first and last knots; data that keeps them has two points fewer. + let short = (knots.len() + 1).checked_sub(degree)?; + let n = if available >= short { + let (first, last) = (*knots.first()?, *knots.last()?); + knots.insert(0, first); + knots.push(last); + short + } else { + knots.len().checked_sub(degree + 1)? + }; + if n == 0 || n > available { + return None; + } + let pts = values.chunks(stride).take(n).map(|c| [c[0], c[1], c[2]]).collect(); + let weights = rational.then(|| values.chunks(stride).take(n).map(|c| c[3]).collect()); + Some((degree, knots, pts, weights)) +} + +/// The distinct parameters of a cubic's self-intersection, when both lie on the curve. +fn cubic_crossing(cubic: kurbo::CubicBez) -> Option<(f64, f64)> { + let b = (cubic.p1 - cubic.p0) * 3.0; + let c = (cubic.p2 - cubic.p1) * 3.0 - b; + let d = (cubic.p3 - cubic.p0) - b - c; + let det = c.cross(d); + if det == 0.0 { + return None; + } + // Dividing P(s) - P(t) by s - t gives b + c*u + d*(u*u - v) = 0, + // where u = s + t and v = s*t. + let u = -b.cross(d) / det; + let v = u * u - b.cross(c) / det; + let discriminant = u * u - 4.0 * v; + if !discriminant.is_finite() || discriminant <= 0.0 { + return None; + } + let root = discriminant.sqrt(); + let (s, t) = ((u - root) * 0.5, (u + root) * 0.5); + (0.0 <= s && s < t && t <= 1.0).then_some((s, t)) +} + +/// An `intcurve-curve` from `from` to `to` (the part of its spline between them), the whole +/// curve when the edge starts and ends at one vertex; also whether trimming is ambiguous. +fn spline(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option<(BezPath, bool)> { + // The curve's own sense comes before its data. + let open = c.toks.iter().position(|t| *t == Tok::Open)?; + let curve_back = c.toks[..open].contains(&Tok::Sense(true)); + let (degree, knots, pts, weights) = bspline(&c.toks[open..])?; + let ctrl: Vec = pts.into_iter().map(|p| flat(xf.point(p))).collect(); + let full = curve::nurbs(degree, &knots, &ctrl, weights.as_deref())?; + let back = back != curve_back; + let segs: Vec = full.segments().collect(); + let (first, last) = (segs.first()?.start(), segs.last()?.end()); + let mut ambiguous = false; + let part = if closed { + full + } else { + let ring = first.distance(last) <= 1e-9 * (1.0 + first.to_vec2().hypot()); + let mut lengths = vec![0.0]; + for s in &segs { + lengths.push(lengths.last()? + s.arclen(1e-9)); + } + let total = *lengths.last()?; + let at = |p: P3| { + let p = flat(xf.point(p)); + let near: Vec<_> = segs.iter().enumerate().map(|(i, s)| (s.nearest(p, 1e-9), i)).collect(); + let (n, i) = near.iter().min_by(|a, b| a.0.distance_sq.total_cmp(&b.0.distance_sq))?; + let along = |i: usize, t: f64| lengths[i] + segs[i].subsegment(0.0..t).arclen(1e-9); + let start = along(*i, n.t); + let tolerance = 1e-6 * (1.0 + p.x.hypot(p.y)); + // Nearby ends at a segment joint, or at a closed curve's seam, are one location. + let ambiguous = near.iter().any(|(other, j)| { + if endpoints_apart(p, segs[*j].eval(other.t)) { + return false; + } + let distance = (along(*j, other.t) - start).abs(); + let distance = if ring { distance.min((total - distance).abs()) } else { distance }; + distance > 4.0 * tolerance + }) || segs.iter().any(|s| match s { + PathSeg::Cubic(cubic) => cubic_crossing(*cubic).is_some_and(|(t, _)| !endpoints_apart(p, cubic.eval(t))), + _ => false, + }); + Some((*i as f64 + n.t, ambiguous)) + }; + let ((ga, a), (gb, b)) = (at(from)?, at(to)?); + ambiguous = a || b; + let (lo, hi) = if back { (gb, ga) } else { (ga, gb) }; + let pieces = if lo <= hi || !ring { + piece(&segs, lo.min(hi), hi.max(lo)) + } else { + [piece(&segs, lo, segs.len() as f64), piece(&segs, 0.0, hi)].concat() + }; + if pieces.is_empty() { + return None; + } + BezPath::from_path_segments(pieces.into_iter()) + }; + Some((if back { part.reverse_subpaths() } else { part }, ambiguous)) +} + +/// The parts of `segs` from `lo` to `hi`, counted in segments (2.5: halfway along the third). +fn piece(segs: &[PathSeg], lo: f64, hi: f64) -> Vec { + let mut out = vec![]; + for (i, s) in segs.iter().enumerate() { + let (t0, t1) = ((lo - i as f64).max(0.0), (hi - i as f64).min(1.0)); + if t1 > t0 { + out.push(s.subsegment(t0..t1)); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cubic_crossings_have_two_distinct_parameters() { + let cubic = kurbo::CubicBez::new((36.0, -18.0), (-28.0, 26.0), (-28.0, -26.0), (36.0, 18.0)); + let (s, t) = cubic_crossing(cubic).unwrap(); + assert!((s - 0.25).abs() < 1e-12 && (t - 0.75).abs() < 1e-12, "{s}, {t}"); + let plain = kurbo::CubicBez::new((0.0, 0.0), (30.0, 50.0), (70.0, -50.0), (100.0, 0.0)); + assert!(cubic_crossing(plain).is_none()); + } + + #[test] + fn deciphering_maps_each_character_back_and_drops_the_caret_space() { + // "Ab@_ 7#" ciphered: A→^ (and a space), b→=, @→_, _→@, 7→h, #→|. + assert_eq!(decipher("^ =_@ h|"), "Ab@_ 7#"); + } +} diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 4e1bed4ae1..0b3532ca87 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -27,7 +27,7 @@ const MAX_NODES: usize = 2_000_000; /// per item of the block looked at for it (art on hidden layers too). const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 }; /// The most path elements an import makes (blocks drawn as art are copied for every placement). -const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 }; +pub(crate) const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 }; /// The most dash lengths an import keeps (every dashed path holds its own copy of its pattern). const MAX_DASH_VALUES: usize = if cfg!(test) { 1_000 } else { 4_000_000 }; /// The most bytes of text, font names and symbol names an import copies into objects (a block's @@ -128,7 +128,7 @@ impl<'d, 'a> Build<'d, 'a> { Self { d, o, - conv: Converter::default(), + conv: Converter::new(d.regions.clone()), doc: Document::new(1.0, 1.0), blocks: HashMap::new(), bounds: HashMap::new(), diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index 9d147b08cf..acca831206 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -1,7 +1,8 @@ //! Entities to drawing items: their geometry in world coordinates (drawing units, y up) and the //! properties they take from their layer or block (resolved when the items become art). -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; +use std::rc::Rc; use kurbo::{BezPath, PathEl}; use vectorcraft_doc::Justify; @@ -9,6 +10,7 @@ use vectorcraft_geom::{Affine, Point, Vec2}; use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath}; +use super::acis; use super::curve::{self, Vertex}; use super::reader::{aci_paper, point}; @@ -174,6 +176,8 @@ pub(crate) struct Converter { pub warnings: Vec, /// Array insert copies made so far, against [`MAX_TOTAL_CELLS`]. cells: i64, + /// The binary solid-modeler data of regions, by handle (DXF 2013 and later). + regions: Rc>>, } const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries"; @@ -182,8 +186,16 @@ const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertic const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each"; const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all"; const FAR_AWAY: &str = "entities with coordinates out of range are left out"; +const REGION_CURVES: &str = "region edges of some curve types come in as straight lines"; +const REGION_BROKEN: &str = "regions whose outlines break off are closed with straight lines"; +const REGION_AMBIGUOUS: &str = "region edges on curves that cross themselves may come in along the wrong part of the curve"; impl Converter { + /// A converter reading regions' binary data from `regions`. + pub fn new(regions: Rc>>) -> Self { + Self { regions, ..Self::default() } + } + fn warn(&mut self, w: &str) { if !self.warnings.iter().any(|x| x == w) { self.warnings.push(w.to_string()); @@ -255,6 +267,7 @@ impl Converter { model::EntityKind::Dimension(d) => { Some(Geom::Insert(InsertItem { block: d.block.as_ref()?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] })) } + _ if e.kind == "REGION" => self.region(e), _ => None, } } @@ -378,6 +391,41 @@ impl Converter { out } + /// A region as a filled path: its solid-modeler data as text in groups 1 (a line each) and 3 + /// (the rest of a long line), or, from DXF 2013 on, binary data kept by handle. + fn region(&mut self, e: &EntityRecord<'_>) -> Option { + let g = e.groups(); + let own = g.subclass("AcDbModelerGeometry"); + let tags = if own.0.is_empty() { g.0 } else { own.0 }; + let mut text = String::new(); + for t in tags { + match t.code { + 1 => { + if !text.is_empty() { + text.push('\n'); + } + text.push_str(t.str_ref().unwrap_or_default()); + } + 3 => text.push_str(t.str_ref().unwrap_or_default()), + _ => {} + } + if text.len() > acis::MAX_BYTES { + return None; + } + } + let outline = if text.trim().is_empty() { acis::from_binary(self.regions.get(&e.record().handle()?)?) } else { acis::from_text(&text) }?; + if outline.approximated { + self.warn(REGION_CURVES); + } + if outline.broken { + self.warn(REGION_BROKEN); + } + if outline.ambiguous { + self.warn(REGION_AMBIGUOUS); + } + Some(Geom::Path { bp: outline.path, fill: true, width: 0.0 }) + } + fn hatch(&mut self, h: &model::Hatch, ocs: Affine) -> Option { let mut bp = BezPath::new(); for l in &h.loops { @@ -601,7 +649,7 @@ fn boundary(path: &HatchPath) -> Option { } /// `seg` continuing `bp`: joined by a line when it starts elsewhere. -fn append(bp: &mut BezPath, seg: &BezPath) { +pub(super) fn append(bp: &mut BezPath, seg: &BezPath) { for el in seg.elements() { match *el { PathEl::MoveTo(p) => { diff --git a/crates/cad/src/import/reader.rs b/crates/cad/src/import/reader.rs index f2ed000809..f635e3cf8c 100644 --- a/crates/cad/src/import/reader.rs +++ b/crates/cad/src/import/reader.rs @@ -1,7 +1,8 @@ //! What the import uses of a drawing, from `craft_dxf::model`: header variables; the layer, //! linetype and text style tables; the blocks; the entities; the layouts. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; +use std::rc::Rc; use craft_dxf::model::{self, EntityRecord}; use vectorcraft_geom::Point; @@ -81,6 +82,9 @@ pub(crate) struct Drawing<'a> { pub layouts: Vec, /// How many sections the file has (none: not a drawing). pub sections: usize, + /// The binary solid-modeler data of the regions, by handle (DXF 2013 and later keep it in + /// the ACDSDATA section). + pub regions: Rc>>, } /// The colour of index `i` on paper: index 7 (white on a CAD screen) is black. @@ -112,6 +116,7 @@ impl<'a> Drawing<'a> { } let block_names = doc.block_names(); d.layouts = layouts(&doc, &block_names); + d.regions = Rc::new(region_data(&doc)); for b in doc.blocks { if b.name.is_empty() { continue; @@ -148,6 +153,50 @@ impl<'a> Drawing<'a> { } } +/// The binary data of each region in the ACDSDATA section: an `ACDSRECORD` names its entity's +/// handle (320), then holds the bytes (310 chunks) after `2 ASM_Data`, their count in 94. +fn region_data(doc: &model::Document<'_>) -> HashMap> { + let records = doc.entities.iter().chain(doc.blocks.iter().flat_map(|b| &b.entities)); + let wanted: HashSet = records.filter(|e| e.kind == "REGION").filter_map(|e| e.record().handle()).collect(); + let mut out = HashMap::new(); + if wanted.is_empty() { + return out; + } + for section in doc.other_sections.iter().filter(|s| s.name.eq_ignore_ascii_case("ACDSDATA")) { + for r in model::records(section.tags).into_iter().filter(|r| r.kind == "ACDSRECORD") { + let Some(handle) = r.tags.iter().find(|t| t.code == 320).and_then(|t| model::parse_handle(&t.str())) else { continue }; + if !wanted.contains(&handle) || out.contains_key(&handle) { + continue; + } + let Some(at) = r.tags.iter().position(|t| t.code == 2 && t.str_ref().is_some_and(|s| s.trim() == "ASM_Data")) else { continue }; + let data = r.tags.get(at + 1..).unwrap_or_default(); + let size = data.iter().find(|t| t.code == 94).and_then(|t| usize::try_from(t.i64()).ok()); + let mut bytes = Vec::new(); + for t in data.iter().filter(|t| t.code == 310) { + hex_bytes(t.str_ref().unwrap_or_default(), &mut bytes); + if bytes.len() > super::acis::MAX_BYTES { + break; + } + } + if let Some(n) = size.filter(|n| *n <= bytes.len()) { + bytes.truncate(n); + } + out.insert(handle, bytes); + } + } + out +} + +/// Hex digits' bytes, two digits each, onto `out`. +fn hex_bytes(hex: &str, out: &mut Vec) { + let digit = |c: u8| (c as char).to_digit(16).and_then(|d| u8::try_from(d).ok()); + for pair in hex.as_bytes().as_chunks::<2>().0 { + if let (Some(hi), Some(lo)) = (digit(pair[0]), digit(pair[1])) { + out.push(hi << 4 | lo); + } + } +} + pub(crate) fn point(p: model::Point) -> Point { Point::new(p[0], p[1]) } diff --git a/crates/cad/src/import/tests_region.rs b/crates/cad/src/import/tests_region.rs new file mode 100644 index 0000000000..cf37e9585f --- /dev/null +++ b/crates/cad/src/import/tests_region.rs @@ -0,0 +1,637 @@ +//! Regions: solid-modeler data in text (ciphered or not, lines split over groups 1 and 3) and in +//! binary form (the ACDSDATA section) comes in as one filled path of the region's loops; lines, +//! circles, ellipses and spline edges keep their shape, coedge and edge senses are followed, a +//! body's transform is applied, and damaged data is left out without hanging. + +use kurbo::{BezPath, Shape}; +use vectorcraft_doc::{Document, Node, NodeKind, Unit}; +use vectorcraft_geom::{FillRule, Point, Rect}; + +use super::*; + +/// A curve an edge runs along. +#[derive(Clone)] +enum Curve { + Line, + /// A circle about the z axis (`-z`: clockwise) of this centre and radius. + Circle { + c: [f64; 2], + r: f64, + down: bool, + }, + /// A curve record's text after its first three values. + Raw(String), +} + +/// An edge of a loop, from `a` to `b` as the loop runs it. `flip`: the edge is stored from `b` +/// to `a` and the coedge runs it reversed; `against`: the edge also runs against its curve. +#[derive(Clone)] +struct E { + a: [f64; 2], + b: [f64; 2], + curve: Curve, + flip: bool, + against: bool, +} + +fn line(a: [f64; 2], b: [f64; 2]) -> E { + E { a, b, curve: Curve::Line, flip: false, against: false } +} + +fn circle(c: [f64; 2], r: f64, down: bool) -> E { + let p = [c[0] + r, c[1]]; + E { a: p, b: p, curve: Curve::Circle { c, r, down }, flip: false, against: false } +} + +fn square(lo: f64, hi: f64) -> Vec { + vec![line([lo, lo], [hi, lo]), line([hi, lo], [hi, hi]), line([hi, hi], [lo, hi]), line([lo, hi], [lo, lo])] +} + +/// Text data (version 700) of one face with `loops`, placed by `transform` (12 numbers and a +/// scale) when given. +fn sat(loops: &[Vec], transform: Option<&str>) -> String { + let mut recs: Vec = vec![]; + let xf = if transform.is_some() { "$5" } else { "$-1" }; + recs.push(format!("body $-1 -1 $-1 $1 $-1 {xf}")); + recs.push("lump $-1 -1 $-1 $-1 $2 $0".into()); + recs.push("shell $-1 -1 $-1 $-1 $-1 $3 $-1 $1".into()); + recs.push("face $-1 -1 $-1 $-1 $6 $2 $-1 $4 forward single".into()); + recs.push("plane-surface $-1 -1 $-1 0 0 0 0 0 1 1 0 0 forward_v I I I I".into()); + recs.push(format!("transform $-1 -1 $-1 {} no_rotate no_reflect no_shear", transform.unwrap_or("1 0 0 0 1 0 0 0 1 0 0 0 1"))); + let mut base = 6; + for (l, edges) in loops.iter().enumerate() { + let next_loop = if l + 1 < loops.len() { format!("${}", base + 1 + 7 * edges.len()) } else { "$-1".into() }; + recs.push(format!("loop $-1 -1 $-1 {next_loop} ${} $3", base + 1)); + let n = edges.len(); + for (j, e) in edges.iter().enumerate() { + let at = |k: usize| base + 1 + 7 * k; + let i = at(j); + let (coedge, edge, sv, ev, sp, ep, cv) = (i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6); + let (start, end) = if e.flip { (e.b, e.a) } else { (e.a, e.b) }; + let ev = if start == end { sv } else { ev }; + let sense = |r: bool| if r { "reversed" } else { "forward" }; + recs.push(format!("coedge $-1 -1 $-1 ${} ${} $-1 ${edge} {} ${base} $-1", at((j + 1) % n), at((j + n - 1) % n), sense(e.flip))); + recs.push(format!("edge $-1 -1 $-1 ${sv} 0 ${ev} 1 ${coedge} ${cv} {} @7 unknown", sense(e.against))); + recs.push(format!("vertex $-1 -1 $-1 ${edge} ${sp}")); + recs.push(format!("vertex $-1 -1 $-1 ${edge} ${ep}")); + recs.push(format!("point $-1 -1 $-1 {} {} 0", start[0], start[1])); + recs.push(format!("point $-1 -1 $-1 {} {} 0", end[0], end[1])); + recs.push(match &e.curve { + Curve::Line => format!("straight-curve $-1 -1 $-1 {} {} 0 {} {} 0 I I", start[0], start[1], end[0] - start[0], end[1] - start[1]), + Curve::Circle { c, r, down } => { + format!("ellipse-curve $-1 -1 $-1 {} {} 0 0 0 {} {r} 0 0 1 I I", c[0], c[1], if *down { -1 } else { 1 }) + } + Curve::Raw(s) => s.clone(), + }); + } + base += 1 + 7 * n; + } + let mut s = String::from("700 0 1 0\n9 Synthetic 3 ASM 4 none\n1 9.9999999999999995e-07 1e-10\n"); + for r in recs { + s.push_str(&r); + s.push_str(" #\n"); + } + s.push_str("End-of-ACIS-data\n"); + s +} + +/// DXF's cipher of text data: each printable character mapped, a space after each caret. +fn encipher(s: &str) -> String { + let mut out = String::new(); + for c in s.chars() { + let m = match c { + ' ' | '\n' => c, + '@'..='_' => char::from(159 - c as u8), + c => char::from(c as u8 ^ 0x5F), + }; + out.push(m); + if m == '^' { + out.push(' '); + } + } + out +} + +/// A drawing of `version` with `entities` and, when given, an ACDSDATA section. +fn drawing(version: &str, entities: &[(i32, String)], acds: &[(i32, String)]) -> Vec { + let mut s = format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\n{version}\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n"); + let put = |pairs: &[(i32, String)], s: &mut String| { + for (c, v) in pairs { + s.push_str(&format!("{c:>3}\n{v}\n")); + } + }; + put(entities, &mut s); + s.push_str(" 0\nENDSEC\n"); + if !acds.is_empty() { + s.push_str(" 0\nSECTION\n 2\nACDSDATA\n"); + put(acds, &mut s); + s.push_str(" 0\nENDSEC\n"); + } + s.push_str(" 0\nEOF\n"); + s.into_bytes() +} + +/// A REGION entity holding `lines` of text data (`split`: each line over 40 characters goes on +/// in group 3 from inside a word). +fn region_text(lines: &str, split: bool) -> Vec<(i32, String)> { + let mut e = vec![ + (0, "REGION".to_string()), + (5, "2A".into()), + (8, "0".into()), + (100, "AcDbEntity".into()), + (100, "AcDbModelerGeometry".into()), + (70, "1".into()), + ]; + for l in lines.lines() { + let b = l.as_bytes(); + let cut = (40..b.len()).find(|&i| !b[i - 1].is_ascii_whitespace() && !b[i].is_ascii_whitespace()); + if let Some(at) = cut.filter(|_| split) { + e.push((1, l[..at].to_string())); + e.push((3, l[at..].to_string())); + } else { + e.push((1, l.to_string())); + } + } + e +} + +fn points() -> ImportOptions { + ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() } +} + +/// Every leaf path of the document as one path, in document coordinates. +fn outline(doc: &Document) -> BezPath { + let mut bp = BezPath::new(); + doc.walk(|n: &Node| { + if let NodeKind::Path { path, .. } = &n.kind { + bp.extend(path.to_bezpath()); + } + }); + bp +} + +/// Inside the path by the even-odd rule. +fn filled(bp: &BezPath, p: Point) -> bool { + bp.winding(p) % 2 != 0 +} + +/// The region (drawing `x, y`) is filled at `inside` and not at `outside`. +fn check(doc: &Document, inside: &[[f64; 2]], outside: &[[f64; 2]]) { + let h = doc.artboards[0].rect.height(); + let (bp, at) = (outline(doc), |p: &[f64; 2]| Point::new(p[0], h - p[1])); + for p in inside { + assert!(filled(&bp, at(p)), "{p:?} should be filled"); + } + for p in outside { + assert!(!filled(&bp, at(p)), "{p:?} should be empty"); + } +} + +/// The only top-level object: filled, without a stroke. +fn filled_object(doc: &Document) -> Node { + let [n] = &doc.layers[0].children().unwrap()[..] else { panic!("{:?}", doc.layers[0].children()) }; + assert!(n.appearance.fill().is_some_and(|f| !f.paint.is_none()), "regions are filled"); + assert!(n.appearance.stroke().is_none_or(|s| s.paint.is_none()), "regions have no stroke"); + n.as_ref().clone() +} + +fn square_with_hole() -> Vec> { + vec![square(0.0, 100.0), vec![circle([50.0, 50.0], 20.0, true)]] +} + +#[test] +fn ciphered_text_data_comes_in_as_a_filled_path_with_its_hole() { + let text = encipher(&sat(&square_with_hole(), None)); + let r = import(&drawing("AC1015", ®ion_text(&text, false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let n = filled_object(&r.document); + let NodeKind::Compound { rule, .. } = &n.kind else { panic!("{:?}", n.kind) }; + assert_eq!(*rule, FillRule::EvenOdd); + assert!((n.geometric_bounds().unwrap().area() - 10_000.0).abs() < 1e-6); + check(&r.document, &[[10.0, 10.0], [50.0, 75.0], [90.0, 50.0]], &[[50.0, 50.0], [60.0, 55.0], [110.0, 50.0]]); + // The hole is a circle. + let h = r.document.artboards[0].rect.height(); + let bp = outline(&r.document); + let centre = Point::new(50.0, h - 50.0); + let on_hole: Vec = bp.segments().map(|s| kurbo::ParamCurve::eval(&s, 0.5).distance(centre)).filter(|d| *d < 30.0).collect(); + assert!(!on_hole.is_empty() && on_hole.iter().all(|d| (d - 20.0).abs() < 1e-3), "{on_hole:?}"); +} + +#[test] +fn plain_text_split_over_groups_one_and_three_reads_alike() { + let text = sat(&square_with_hole(), None); + let r = import(&drawing("AC1021", ®ion_text(&text, true), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + filled_object(&r.document); + check(&r.document, &[[10.0, 10.0]], &[[50.0, 50.0]]); + // Before version 700 a record starts with its attribute alone. + let old: String = text.replacen("700 0 1 0", "400 0 1 0", 1).lines().map(|l| format!("{}\n", l.replacen(" $-1 -1 $-1 ", " $-1 ", 1))).collect(); + assert!(old.contains("body $-1 $1 $-1 $-1 #"), "{old}"); + let r = import(&drawing("AC1012", ®ion_text(&old, false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + check(&r.document, &[[10.0, 10.0]], &[[50.0, 50.0]]); +} + +/// Binary data of the same records: tagged values, type names in parts. +fn sab(text: &str) -> Vec { + let mut b = b"ACIS BinaryFile".to_vec(); + for v in [700u32, 0, 1, 0] { + b.extend(v.to_le_bytes()); + } + let string = |b: &mut Vec, tag: u8, s: &str| { + b.push(tag); + b.push(u8::try_from(s.len()).unwrap()); + b.extend(s.as_bytes()); + }; + string(&mut b, 0x07, "Synthetic"); + b.push(0x06); + b.extend(1.0f64.to_le_bytes()); + for line in text.lines().skip(3) { + if line.starts_with("End-of") { + break; + } + let mut words = line.split_whitespace().peekable(); + let kind = words.next().unwrap(); + let parts: Vec<&str> = kind.split('-').collect(); + for (i, p) in parts.iter().enumerate() { + string(&mut b, if i + 1 == parts.len() { 0x0D } else { 0x0E }, p); + } + while let Some(w) = words.next() { + match w { + "#" => {} + "forward" | "forward_v" => b.push(0x0B), + "reversed" | "reversed_v" => b.push(0x0A), + "{" => b.push(0x0F), + "}" => b.push(0x10), + w if w.starts_with('$') => { + b.push(0x0C); + b.extend(w[1..].parse::().unwrap().to_le_bytes()); + } + w if w.starts_with('@') => { + let s = words.next().unwrap(); + string(&mut b, 0x07, s); + } + w => match w.parse::() { + Ok(v) => { + b.push(0x06); + b.extend(v.to_le_bytes()); + } + Err(_) => string(&mut b, 0x07, w), + }, + } + } + b.push(0x11); + } + for p in ["End", "of", "ASM"] { + string(&mut b, 0x0E, p); + } + string(&mut b, 0x0D, "data"); + b +} + +/// An ACDSDATA record holding `bytes` for the entity with handle 2A, in 50-byte chunks. +fn acds(bytes: &[u8]) -> Vec<(i32, String)> { + let mut a = vec![ + (0, "ACDSRECORD".to_string()), + (90, "1".into()), + (2, "AcDbDs::ID".into()), + (280, "10".into()), + (320, "2A".into()), + (2, "ASM_Data".into()), + (280, "15".into()), + (94, bytes.len().to_string()), + ]; + for c in bytes.chunks(50) { + a.push((310, c.iter().map(|b| format!("{b:02X}")).collect())); + } + a +} + +#[test] +fn binary_data_in_the_acdsdata_section_reads_alike() { + let bytes = sab(&sat(&square_with_hole(), None)); + let e = vec![(0, "REGION".to_string()), (5, "2A".into()), (8, "0".into()), (100, "AcDbModelerGeometry".into()), (290, "0".into())]; + // ASM's signature in place of ACIS's, as DXF 2018 may write it. + let asm = [b"ASM BinaryFile4".as_slice(), &bytes[b"ACIS BinaryFile".len()..]].concat(); + for data in [&bytes, &asm] { + let r = import(&drawing("AC1032", &e, &acds(data)), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + filled_object(&r.document); + check(&r.document, &[[10.0, 10.0], [50.0, 75.0]], &[[50.0, 50.0]]); + } + // Without its data the region is left out and listed. + let r = import(&drawing("AC1027", &e, &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings); +} + +/// A drawing the export writes (R2000, millimetres) with a region added to its entities. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +fn exported_with_region() -> Vec { + let d = Document::new(200.0, 200.0); + let o = + crate::DxfOptions { version: crate::DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..crate::DxfOptions::default() }; + let dxf = String::from_utf8(crate::export(&d, &o).unwrap().bytes).unwrap(); + let mut region = String::new(); + for (c, v) in region_text(&encipher(&sat(&square_with_hole(), None)), false) { + let v = if c == 5 { "FFF0".to_string() } else { v }; + region.push_str(&format!("{c:>3}\n{v}\n")); + } + let at = dxf.find("ENTITIES\n").unwrap() + "ENTITIES\n".len(); + format!("{}{region}{}", &dxf[..at], &dxf[at..]).into_bytes() +} + +/// The converter writes a region's data as text in a 2004 drawing and as binary data in the +/// ACDSDATA section of a 2013 one; both come in as the DXF does. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn regions_in_dwg_drawings_come_in_from_text_and_binary_data() { + crate::dwg::allow_in_process(); + let dxf = exported_with_region(); + let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), center: false, ..ImportOptions::default() }; + let want = import(&dxf, &o).unwrap(); + assert!(want.warnings.is_empty(), "{:?}", want.warnings); + let want = filled_object(&want.document).geometric_bounds().unwrap(); + for version in ["AC1018", "AC1027"] { + let dwg = craft_dwg::dxf_to_dwg_as(&dxf, version).unwrap(); + let back = craft_dwg::dwg_to_dxf(&dwg).unwrap(); + let binary = String::from_utf8_lossy(&back).contains("ACDSDATA"); + assert_eq!(binary, version == "AC1027", "{version}: the data's form"); + let r = import(&dwg, &o).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("REGION")), "{version}: {:?}", r.warnings); + let got = filled_object(&r.document).geometric_bounds().unwrap(); + assert!((got.area() - want.area()).abs() < 1e-6 && got.origin().distance(want.origin()) < 1e-6, "{version}: {got:?} {want:?}"); + let mm = 72.0 / 25.4; + check_at(&r.document, mm, &[[10.0, 10.0], [50.0, 75.0]], &[[50.0, 50.0]]); + } +} + +/// [`check`] for art at `k` points per drawing unit. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +fn check_at(doc: &Document, k: f64, inside: &[[f64; 2]], outside: &[[f64; 2]]) { + let scale = |ps: &[[f64; 2]]| ps.iter().map(|p| [p[0] * k, p[1] * k]).collect::>(); + check(doc, &scale(inside), &scale(outside)); +} + +#[test] +fn reversed_coedges_and_edges_run_their_curves_backwards() { + // A quarter of a circle from (100, 0) to (0, 100): on a counter-clockwise circle run along + // it, or on a clockwise one run against it, with the edge stored either way round. + for (down, flip, against) in [(false, true, true), (true, false, true), (true, true, false), (false, false, false)] { + let quarter = E { a: [100.0, 0.0], b: [0.0, 100.0], curve: Curve::Circle { c: [0.0, 0.0], r: 100.0, down }, flip, against }; + let flipped_line = E { flip: true, against: true, ..line([0.0, 100.0], [0.0, 0.0]) }; + let quadrant = vec![line([0.0, 0.0], [100.0, 0.0]), quarter, flipped_line]; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[quadrant], None), false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + // A quarter disc, not the three quarters the other way round. + check(&r.document, &[[20.0, 20.0], [10.0, 50.0], [65.0, 65.0]], &[[80.0, 80.0], [-50.0, 50.0], [50.0, -50.0]]); + let b = filled_object(&r.document).geometric_bounds().unwrap(); + assert!((b.width() - 100.0).abs() < 1e-6 && (b.height() - 100.0).abs() < 1e-6, "{down} {flip} {against}: {b:?}"); + } +} + +#[test] +fn a_spline_edge_keeps_only_its_part_of_the_curve() { + // A parabola from (0, 0) through (100, -50) to (200, 0); the edge runs its first half, + // stored from its end and run reversed. + let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 2 open 2 0 2 1 2 0 0 0 100 -100 0 200 0 0 0 } I I".to_string(); + let half = E { a: [0.0, 0.0], b: [100.0, -50.0], curve: Curve::Raw(curve), flip: true, against: true }; + let shape = vec![half, line([100.0, -50.0], [100.0, 50.0]), line([100.0, 50.0], [0.0, 0.0])]; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[shape], None), false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let b = filled_object(&r.document).geometric_bounds().unwrap(); + assert!((b.width() - 100.0).abs() < 1e-6, "only the first half of the curve: {b:?}"); + assert!((b.height() - 100.0).abs() < 1e-6, "down to the curve's midpoint: {b:?}"); + // Below the chord from (0, 0) to (100, -50), above the curve. + check(&r.document, &[[50.0, -30.0], [90.0, 0.0]], &[[50.0, -45.0], [150.0, 0.0]]); +} + +#[test] +fn a_spline_edge_warns_when_an_endpoint_lies_on_separate_parts_of_its_curve() { + // The first and last spans both pass through (0, 0), away from their ends. + let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 open 4 0 2 1 1 2 1 3 2 -100 -100 0 100 100 0 -100 100 0 100 -100 0 } I I"; + for back in [false, true] { + let (a, b) = if back { ([100.0, 100.0], [0.0, 0.0]) } else { ([0.0, 0.0], [100.0, 100.0]) }; + let edge = E { a, b, curve: Curve::Raw(curve.into()), flip: false, against: back }; + let shape = vec![edge, line(b, [100.0, 0.0]), line([100.0, 0.0], a)]; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[shape], None), false), &[]), &points()).unwrap(); + assert_eq!(r.warnings, ["region edges on curves that cross themselves may come in along the wrong part of the curve"]); + assert!(!outline(&r.document).elements().is_empty()); + } +} + +#[test] +fn a_spline_edge_warns_when_an_endpoint_is_at_one_cubic_spans_crossing() { + let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 3 open 2 0 3 1 3 36 -18 0 -28 26 0 -28 -26 0 36 18 0 } I I"; + let edge = E { a: [0.0, 0.0], b: [36.0, 18.0], curve: Curve::Raw(curve.into()), flip: false, against: false }; + let shape = vec![edge, line([36.0, 18.0], [36.0, 0.0]), line([36.0, 0.0], [0.0, 0.0])]; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[shape], None), false), &[]), &points()).unwrap(); + assert_eq!(r.warnings, ["region edges on curves that cross themselves may come in along the wrong part of the curve"]); + assert!(!outline(&r.document).elements().is_empty()); +} + +#[test] +fn spline_joints_and_a_closed_curves_seam_do_not_warn() { + for (curve, a) in [ + ("intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 open 3 0 2 1 1 2 2 0 0 0 100 0 0 100 100 0 } I I", [100.0, 0.0]), + ( + "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 closed 5 0 2 1 1 2 1 3 1 4 2 0 0 0 100 0 0 100 100 0 0 100 0 0 0 0 } I I", + [0.0, 0.0], + ), + ] { + let edge = E { a, b: [100.0, 100.0], curve: Curve::Raw(curve.into()), flip: false, against: false }; + let shape = vec![edge, line([100.0, 100.0], [0.0, 100.0]), line([0.0, 100.0], a)]; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[shape], None), false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(!outline(&r.document).elements().is_empty()); + } +} + +#[test] +fn a_transform_places_the_body() { + // Twice the size, moved 1000 along x. + let text = sat(&[square(0.0, 10.0)], Some("1 0 0 0 1 0 0 0 1 1000 0 0 2")); + let r = import(&drawing("AC1015", ®ion_text(&text, false), &[]), &points()).unwrap(); + let b = filled_object(&r.document).geometric_bounds().unwrap(); + assert!((b.width() - 20.0).abs() < 1e-9 && (b.height() - 20.0).abs() < 1e-9, "{b:?}"); + let h = r.document.artboards[0].rect.height(); + assert!(Rect::new(b.x0, h - b.y1, b.x1, h - b.y0).contains(Point::new(1010.0, 10.0)), "{b:?}"); +} + +#[test] +fn missing_or_unreadable_body_transforms_leave_the_region_out() { + let text = sat(&[square(0.0, 10.0)], Some("1 0 0 0 1 0 0 0 1 1000 0 0 2")); + for damaged in [ + text.replacen("body $-1 -1 $-1 $1 $-1 $5", "body $-1 -1 $-1 $1 $-1 $99999", 1), + text.replacen("body $-1 -1 $-1 $1 $-1 $5", "body $-1 -1 $-1 $1 $-1 $4", 1), + text.replacen("1 0 0 0 1 0 0 0 1 1000 0 0 2 no_rotate", "1 0 0 0 1 0 0 0 1 1000 0 no_rotate", 1), + text.replacen("1000 0 0 2 no_rotate", "1000 0 0 no_rotate", 1), + text.replacen("1000 0 0 2 no_rotate", "1000 0 0 unreadable no_rotate", 1), + text.replacen("1 0 0 0 1 0 0 0 1 1000", "1 unreadable 0 0 0 1 0 0 0 1 1000", 1), + ] { + assert_ne!(damaged, text); + let r = import(&drawing("AC1015", ®ion_text(&damaged, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings); + assert!(outline(&r.document).elements().is_empty()); + } +} + +#[test] +fn missing_or_unreadable_edge_and_coedge_senses_leave_the_region_out() { + let text = sat(&[square(0.0, 10.0)], None); + for before in ["$8 forward $6", "$13 forward @7 unknown"] { + assert!(text.contains(before), "{text}"); + for sense in ["", "unreadable"] { + let damaged = text.replacen(before, &before.replace("forward", sense), 1); + let r = import(&drawing("AC1015", ®ion_text(&damaged, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{before} {sense}: {:?}", r.warnings); + assert!(outline(&r.document).elements().is_empty()); + } + } +} + +#[test] +fn missing_curve_records_warn_when_edges_come_in_straight() { + let text = sat(&square_with_hole(), None); + let before = "$42 forward @7 unknown"; + assert!(text.contains(before), "{text}"); + let damaged = text.replacen(before, "$99999 forward @7 unknown", 1); + let r = import(&drawing("AC1015", ®ion_text(&damaged, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("straight lines")), "{:?}", r.warnings); + check(&r.document, &[[10.0, 10.0], [50.0, 50.0]], &[[110.0, 50.0]]); +} + +#[test] +fn disconnected_edges_warn_even_when_the_coedge_ring_is_complete() { + let mut edges = square(0.0, 100.0); + edges[1].a[0] += 5.0; + edges[1].b[0] += 5.0; + let mut closing = square(0.0, 100.0); + closing[3].b[0] += 5.0; + for edges in [edges, closing] { + let r = import(&drawing("AC1015", ®ion_text(&sat(&[edges], None), false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("break off")), "{:?}", r.warnings); + check(&r.document, &[[50.0, 50.0]], &[[110.0, 50.0]]); + } +} + +#[test] +fn unknown_curves_come_in_straight_and_damaged_data_is_left_out() { + let mut edges = square(0.0, 100.0); + edges[0].curve = Curve::Raw("helix-curve $-1 -1 $-1 0 0 0".into()); + let r = import(&drawing("AC1015", ®ion_text(&sat(&[edges], None), false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("straight lines")), "{:?}", r.warnings); + check(&r.document, &[[50.0, 50.0]], &[]); + // A ring of coedges whose second points at itself ends there; a body pointing out of range + // and text that isn't data are listed as left out. + let ring = sat(&[square(0.0, 10.0)], None); + assert!(ring.contains("coedge $-1 -1 $-1 $21 $7 $-1")); + let ring = ring.replace("coedge $-1 -1 $-1 $21 $7 $-1", "coedge $-1 -1 $-1 $14 $7 $-1"); + let wild = sat(&[square(0.0, 10.0)], None).replace("body $-1 -1 $-1 $1", "body $-1 -1 $-1 $99999"); + let mut e = region_text(&ring, false); + for text in [wild.as_str(), "not data", "700 0 1 0\n"] { + e.extend(region_text(text, false)); + } + let r = import(&drawing("AC1015", &e, &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("3 REGION")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("break off")), "{:?}", r.warnings); + // The ring's two edges and the line that closes them. + check(&r.document, &[[8.0, 2.0]], &[[2.0, 8.0]]); + // A hole whose ring of coedges is missing is listed, not dropped quietly. + let holed = sat(&[square(0.0, 100.0), square(40.0, 60.0)], None); + assert!(holed.contains("loop $-1 -1 $-1 $-1 $36 $3"), "{holed}"); + let holed = holed.replace("loop $-1 -1 $-1 $-1 $36 $3", "loop $-1 -1 $-1 $-1 $99999 $3"); + let r = import(&drawing("AC1015", ®ion_text(&holed, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("break off")), "{:?}", r.warnings); +} + +#[test] +fn shared_topology_chains_are_walked_within_a_limit() { + // 100 lumps share one chain of 100 shells, each shell one chain of 100 faces: the first face + // a square, the others without loops. That is 1,000,000 faces visited, over the limit of + // records visited, though only 40,000 coedges. + let one = sat(&[square(0.0, 10.0)], None); + let mut recs: Vec = one.lines().skip(3).take_while(|l| !l.starts_with("End-of")).map(str::to_string).collect(); + let (lumps, shells, faces) = (recs.len(), recs.len() + 100, recs.len() + 200); + recs[0] = format!("body $-1 -1 $-1 ${lumps} $-1 $-1 #"); + let next = |i: usize, n: usize, at: usize| if i + 1 < n { format!("${}", at + i + 1) } else { "$-1".into() }; + for i in 0..100 { + recs.push(format!("lump $-1 -1 $-1 {} ${shells} $0 #", next(i, 100, lumps))); + } + for i in 0..100 { + recs.push(format!("shell $-1 -1 $-1 {} $-1 ${faces} $-1 ${lumps} #", next(i, 100, shells))); + } + for i in 0..100 { + let lp = if i == 0 { "$6" } else { "$-1" }; + recs.push(format!("face $-1 -1 $-1 {} {lp} ${shells} $-1 $4 forward single #", next(i, 100, faces))); + } + let text = format!("{}\n{}\nEnd-of-ACIS-data\n", one.lines().take(3).collect::>().join("\n"), recs.join("\n")); + let r = import(&drawing("AC1015", ®ion_text(&text, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings); + // One lump, shell and face of the same records come in. + let small = text.replacen(&format!("lump $-1 -1 $-1 ${} ", lumps + 1), "lump $-1 -1 $-1 $-1 ", 1); + let small = small.replacen(&format!("shell $-1 -1 $-1 ${} ", shells + 1), "shell $-1 -1 $-1 $-1 ", 1); + let small = small.replacen(&format!("face $-1 -1 $-1 ${} ", faces + 1), "face $-1 -1 $-1 $-1 ", 1); + let r = import(&drawing("AC1015", ®ion_text(&small, false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + check(&r.document, &[[5.0, 5.0]], &[[15.0, 5.0]]); +} + +#[test] +fn broken_topology_chains_warn_when_the_next_record_is_missing_or_the_wrong_type() { + let text = sat(&[square(0.0, 100.0), square(40.0, 60.0)], None); + for (before, prefix) in [ + ("lump $-1 -1 $-1 $-1", "lump $-1 -1 $-1"), + ("shell $-1 -1 $-1 $-1", "shell $-1 -1 $-1"), + ("face $-1 -1 $-1 $-1", "face $-1 -1 $-1"), + ("loop $-1 -1 $-1 $35", "loop $-1 -1 $-1"), + ] { + for next in ["$99999", "$4"] { + assert!(text.contains(before), "{before}"); + let broken = text.replacen(before, &format!("{prefix} {next}"), 1); + let r = import(&drawing("AC1015", ®ion_text(&broken, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("break off")), "{before} {next}: {:?}", r.warnings); + check(&r.document, &[[10.0, 10.0]], &[[110.0, 10.0]]); + } + } +} + +#[test] +fn shared_spline_loops_are_left_out_when_their_generated_outline_is_too_large() { + // Many faces share one loop. Its degree-one spline follows a square with many knot spans, + // so generated elements reach their limit well before topology visits do. + let spans = 1024; + let mut curve = format!("intcurve-curve $-1 -1 $-1 forward {{ exactcur 0 nubs 1 closed {} 0 2", spans + 1); + for i in 1..spans { + curve.push_str(&format!(" {i} 1")); + } + curve.push_str(&format!(" {spans} 2")); + for i in 0..=spans { + let t = (i % (spans / 4)) as f64 / (spans / 4) as f64; + let (x, y) = match i / (spans / 4) { + 0 => (t, 0.0), + 1 => (1.0, t), + 2 => (1.0 - t, 1.0), + _ => (0.0, 1.0 - t), + }; + let (x, y) = if i == spans { (0.0, 0.0) } else { (x, y) }; + curve.push_str(&format!(" {x} {y} 0")); + } + curve.push_str(" } I I"); + let edge = E { a: [0.0, 0.0], b: [0.0, 0.0], curve: Curve::Raw(curve), flip: false, against: false }; + let one = sat(&[vec![edge]], None); + let r = import(&drawing("AC1015", ®ion_text(&one, false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + check(&r.document, &[[0.5, 0.5]], &[[1.5, 0.5]]); + let mut recs: Vec = one.lines().skip(3).take_while(|l| !l.starts_with("End-of")).map(str::to_string).collect(); + let faces = recs.len(); + let count = super::build::MAX_ELEMENTS / (spans + 2) + 1; + recs[2] = format!("shell $-1 -1 $-1 $-1 $-1 ${faces} $-1 $1 #"); + for i in 0..count { + let next = if i + 1 < count { format!("${}", faces + i + 1) } else { "$-1".into() }; + recs.push(format!("face $-1 -1 $-1 {next} $6 $2 $-1 $4 forward single #")); + } + let text = format!("{}\n{}\nEnd-of-ACIS-data\n", one.lines().take(3).collect::>().join("\n"), recs.join("\n")); + let r = import(&drawing("AC1015", ®ion_text(&text, false), &[]), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings); + assert!(outline(&r.document).elements().is_empty()); +} diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index c6f02b9240..98bbefed40 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3711,12 +3711,20 @@ fn arb_dxf_entity() -> impl Strategy> { "ATTRIB", "DIMENSION", "VIEWPORT", + "REGION", ]); let code = prop::sample::select(vec![ - 2, 6, 7, 8, 10, 11, 12, 13, 20, 21, 22, 23, 40, 41, 42, 43, 44, 45, 48, 50, 51, 60, 62, 66, 67, 70, 71, 72, 73, 74, 75, 76, 90, 91, 92, 93, - 94, 95, 96, 97, 210, 220, 230, 370, 420, 440, 450, + 1, 2, 3, 6, 7, 8, 10, 11, 12, 13, 20, 21, 22, 23, 40, 41, 42, 43, 44, 45, 48, 50, 51, 60, 62, 66, 67, 70, 71, 72, 73, 74, 75, 76, 90, 91, 92, + 93, 94, 95, 96, 97, 210, 220, 230, 370, 420, 440, 450, ]); - let value = prop_oneof![arb_num(), Just("B".to_string()), Just("*U1".to_string()), Just(r"{\fA;x}\P%%c^".to_string())]; + let value = prop_oneof![ + arb_num(), + Just("B".to_string()), + Just("*U1".to_string()), + Just(r"{\fA;x}\P%%c^".to_string()), + Just("700 0 1 0".to_string()), + Just("body $-1 -1 $-1 $0 $-1 $-1 #".to_string()), + ]; (kind, prop::collection::vec((code, value), 0..24)).prop_map(|(k, g)| std::iter::once((0, k.to_string())).chain(g).collect()) } @@ -3730,6 +3738,107 @@ fn hostile_dxf(block: &[Vec<(i32, String)>], body: &[Vec<(i32, String)>]) -> Vec dxf_text(&all).into_bytes() } +/// A region's solid-modeler text data: one face whose loop is two lines and a quarter circle, +/// (0, 0) to (100, 0), round to (0, 100) and back. +const REGION_SAT: &str = "700 0 1 0 +4 Fuzz 3 ASM 4 none +1 9.9999999999999995e-07 1e-10 +body $-1 -1 $-1 $1 $-1 $-1 # +lump $-1 -1 $-1 $-1 $2 $0 # +shell $-1 -1 $-1 $-1 $-1 $3 $-1 $1 # +face $-1 -1 $-1 $-1 $4 $2 $-1 $-1 forward single # +loop $-1 -1 $-1 $-1 $5 $3 # +coedge $-1 -1 $-1 $6 $7 $-1 $8 forward $4 $-1 # +coedge $-1 -1 $-1 $7 $5 $-1 $9 forward $4 $-1 # +coedge $-1 -1 $-1 $5 $6 $-1 $10 forward $4 $-1 # +edge $-1 -1 $-1 $11 0 $12 1 $5 $-1 forward @7 unknown # +edge $-1 -1 $-1 $12 0 $13 1 $6 $17 forward @7 unknown # +edge $-1 -1 $-1 $13 0 $11 1 $7 $-1 forward @7 unknown # +vertex $-1 -1 $-1 $8 $14 # +vertex $-1 -1 $-1 $9 $15 # +vertex $-1 -1 $-1 $10 $16 # +point $-1 -1 $-1 0 0 0 # +point $-1 -1 $-1 100 0 0 # +point $-1 -1 $-1 0 100 0 # +ellipse-curve $-1 -1 $-1 0 0 0 0 0 1 100 0 0 1 I I # +End-of-ACIS-data +"; + +/// [`REGION_SAT`]'s records as binary data: tagged values, type names in parts. +fn region_sab() -> Vec { + let mut b = b"ACIS BinaryFile".to_vec(); + for v in [700u32, 0, 1, 0] { + b.extend(v.to_le_bytes()); + } + let string = |b: &mut Vec, tag: u8, s: &str| { + b.push(tag); + b.push(u8::try_from(s.len()).unwrap_or(0)); + b.extend(s.as_bytes()); + }; + for line in REGION_SAT.lines().skip(3).take_while(|l| !l.starts_with("End-of")) { + let mut words = line.split_whitespace(); + let parts: Vec<&str> = words.next().unwrap_or_default().split('-').collect(); + for (i, p) in parts.iter().enumerate() { + string(&mut b, if i + 1 == parts.len() { 0x0D } else { 0x0E }, p); + } + while let Some(w) = words.next() { + match w { + "#" => {} + "forward" => b.push(0x0B), + "reversed" => b.push(0x0A), + w if w.starts_with('$') => { + b.push(0x0C); + b.extend(w[1..].parse::().unwrap_or(-1).to_le_bytes()); + } + w if w.starts_with('@') => string(&mut b, 0x07, words.next().unwrap_or_default()), + w => match w.parse::() { + Ok(v) => { + b.push(0x06); + b.extend(v.to_le_bytes()); + } + Err(_) => string(&mut b, 0x07, w), + }, + } + } + b.push(0x11); + } + b +} + +/// A drawing with one REGION: `text` as its data in groups 1 (DXF 2000), or `binary` in the +/// ACDSDATA section (DXF 2013). +fn region_dxf(text: &str, binary: Option<&[u8]>) -> Vec { + let version = if binary.is_some() { "AC1027" } else { "AC1015" }; + let mut p: Vec<(i32, String)> = + [(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, version), (0, "ENDSEC"), (0, "SECTION"), (2, "ENTITIES"), (0, "REGION"), (5, "2A")] + .iter() + .map(|(c, v)| (*c, v.to_string())) + .collect(); + p.extend([(8, "0".to_string()), (100, "AcDbEntity".into()), (100, "AcDbModelerGeometry".into()), (70, "1".into())]); + p.extend(text.lines().map(|l| (1, l.to_string()))); + p.push((0, "ENDSEC".into())); + if let Some(bytes) = binary { + p.extend([(0, "SECTION"), (2, "ACDSDATA"), (0, "ACDSRECORD"), (320, "2A"), (2, "ASM_Data")].iter().map(|(c, v)| (*c, v.to_string()))); + p.push((94, bytes.len().to_string())); + p.extend(bytes.chunks(127).map(|c| (310, c.iter().map(|b| format!("{b:02X}")).collect()))); + p.push((0, "ENDSEC".into())); + } + p.push((0, "EOF".into())); + dxf_text(&p).into_bytes() +} + +#[test] +fn region_seeds_open_as_a_filled_path() { + let o = vectorcraft_cad::ImportOptions::default(); + for bytes in [region_dxf(REGION_SAT, None), region_dxf("", Some(®ion_sab()))] { + let r = vectorcraft_cad::import(&bytes, &o).expect("opens"); + assert!(!r.warnings.iter().any(|w| w.contains("REGION")), "{:?}", r.warnings); + let mut paths = 0; + r.document.walk(|n: &vectorcraft_doc::Node| paths += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }))); + assert_eq!(paths, 1); + } +} + /// Import with every option at once, and place it; whatever comes back must render and export. fn survive_dxf(what: &str, bytes: &[u8], fit: bool) -> Result<(), TestCaseError> { let o = vectorcraft_cad::ImportOptions { fit, center: !fit, merge_layers: fit, ..Default::default() }; @@ -3783,6 +3892,23 @@ proptest! { bytes.truncate(cut.max(8)); survive_dxf("mutated dxf", &bytes, cut % 2 == 0)?; } + + #[test] + fn dxf_mutated_regions_never_panic( + binary in any::(), + cut in 0usize..2_000, + edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec![b'0', b'1', b'9', b'-', b'.', b'e', b'$', b'#', b' ', b'@', 0xFF, 0x0C])), 0..12), + ) { + let mut data = if binary { region_sab() } else { REGION_SAT.as_bytes().to_vec() }; + for &(at, b) in &edits { + let n = data.len(); + // Text stays ASCII, as group values are. + data[at % n] = if binary || (b' '..0x80).contains(&b) { b } else { b' ' }; + } + data.truncate(cut.max(8)); + let bytes = if binary { region_dxf("", Some(&data)) } else { region_dxf(&String::from_utf8_lossy(&data), None) }; + survive_dxf("mutated region", &bytes, cut % 2 == 0)?; + } } // ---------- Windows metafiles: opened, placed and pasted ---------- diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 31f0da4316..d2290b4fa6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -371,7 +371,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`); SVG Options › Units writes `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, the `viewBox` staying in points, for software that reads physical size such as LaserGRBL (#4462, `crates/svg/tests/it/roundtrip.rs`) | -| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open | +| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open. REGION entities open as filled paths of their faces' boundary loops (lines, circles, ellipses and spline edges), read from the text data of DXF R13 to 2010 and the binary data in the ACDSDATA section of DXF 2013 and later, DWG included; edges of other curve types come in straight, an outline that breaks off is closed with a straight line, and a spline edge whose endpoint lies on two parts of a self-crossing curve is trimmed at the nearer one, each with a warning ([REGION group codes](https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-644BF0F0-FD79-4C5E-AD5A-0053FCC5A5A4), `crates/cad/src/import/tests_region.rs`) | | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines; Export As opens HP-GL Options) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | yes (open and place: craft-dwg converts the drawing to DXF, in a child process on desktop, and the DXF reader reads it with the DXF import options) | no (export DXF instead) | `crates/cad/src/import/tests_dwg.rs`, `crates/engine/src/cmd/fileio/tests_dwgimport.rs` (drawings written as DXF and converted to DWG by craft-dwg's writer); not in the web build | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` | From dc65d0320083d3dba03ba22b7ad11dc91961ff1c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 17:52:09 -0800 Subject: [PATCH 32/56] Plug-ins: an outside command acts on the selection an add-on preview shows During an add-on dialog's preview, a command from outside the dialog now uses the selection on show, without the objects the preview made, instead of the selection from before the preview, so Clear no longer deletes art that was not shown selected. A failed preview runs again when an outside command changes only the selection, and the new-art paints a selection command loads stay with the selection it made. --- crates/engine/src/session/edit.rs | 25 ++++--- crates/ui-egui/src/addons/dialogs/tests.rs | 76 ++++++++++++++++++++++ crates/ui-egui/src/dialogs/preview.rs | 19 +++--- docs/mcp.md | 2 +- 4 files changed, 103 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 6581503054..5b5f3df44f 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -344,8 +344,10 @@ impl Session { /// no drag in progress. /// /// A dialog's live preview ([`crate::Interaction::dialog`]) is set aside the same way, except - /// for a command that acts on the drawing on show ([`reads_preview`]). The - /// interaction stays as it is, and the command runs inside it, for an interaction a panel or + /// for a command that acts on the drawing on show ([`reads_preview`]). Outside commands use + /// the shown selection with objects absent from the base document removed. A selection of + /// only preview objects becomes empty. The interaction stays as it is, and the command runs + /// inside it, for an interaction a panel or /// another dialog began (it builds its preview from commands), for typing in progress /// ([`Session::edit`] keeps it as a step of its own), for the Quick Pen (an edit made outside /// it ends the path it draws), and for a copy made with `object.transform` during a drag that @@ -370,7 +372,11 @@ impl Session { let shown = previewed.then(|| (st.doc.clone(), st.selection.clone())); if previewed { st.doc = interaction.doc.clone(); - st.selection.clone_from(&interaction.selection); + if interaction.dialog { + st.selection.prune(&st.doc); + } else { + st.selection.clone_from(&interaction.selection); + } st.revision += 1; cmd::globaledit::follow_history(st); } @@ -387,19 +393,20 @@ impl Session { /// Put back the interaction [`Session::outside_interaction`] set aside. When the command left /// the document and the selection as it found them, the preview on show before it is on show - /// again. Otherwise the interaction starts from the document the command left and from its - /// own selection, without the objects the command removed, hid or locked, and the preview that Real-time - /// Drawing showed is applied to it again. The warning or the error of that preview goes to + /// again. Otherwise a tool drag starts from the document the command left and from its own + /// selection, without the objects the command removed, hid or locked. The preview that + /// Real-time Drawing showed is applied to it again. The warning or the error of that preview goes to /// the command's result ([`Session::note_settled_warning`]); a preview that fails leaves the /// interaction with nothing to commit. An interaction whose document the command closed ends, /// and so does one with anchors or segments selected on a path the command changed in more - /// than a move. A document - /// the command left an interaction of its own on keeps that one. + /// than a move. A document the command left an interaction of its own on keeps that one. + /// A dialog adopts the command's selection and paints and reruns its preview on its next pass. pub(crate) fn put_back_interaction(&mut self) { let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint }) = self.held_interaction.take() else { return }; // A selection command loaded the paints of the selection it made into the fill and stroke // proxies. The drag goes on with its own selection, so they show its paints again. - if self.paint != paint + if !it.dialog + && self.paint != paint && let Some(st) = self.active_mut().filter(|d| d.uid == uid && d.interaction.is_none()) { let own = drag_selection(&it.selection, &st.doc); diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index 392900b20a..bd2ae77899 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -318,6 +318,82 @@ fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview() assert_eq!(x0(&app, 1), 100.0, "the first preview rolled back"); } +#[test] +fn clearing_a_dialog_preview_uses_only_the_shown_base_objects() { + for include_base_object in [false, true] { + let mut app = two_rects_filled(); + let original = app.session.active().unwrap().doc.clone(); + let selected = app.session.active().unwrap().selection.objects.clone(); + let undo = undo_len(&app); + let mut preview = crate::dialogs::preview::LivePreview::default(); + let params = json!({}); + assert!(preview.run(&mut app, true, "Flood Fill Artboards", "addon.document.floodFillArtboards", ¶ms).unwrap().is_ok()); + preview.keep_outside_edits(&mut app); + assert!(app.session.active().unwrap().selection.objects.iter().all(|id| original.node(*id).is_none())); + if include_base_object { + app.session.active_mut().unwrap().selection.add(selected[0]); + } + + let result = app.run("edit.clear", json!({})); + if include_base_object { + result.unwrap(); + } + preview.cancel(&mut app); + let state = app.session.active().unwrap(); + assert!(state.doc.node(selected[1]).is_some(), "Clear must keep hidden selected artwork"); + if include_base_object { + assert!(state.doc.node(selected[0]).is_none(), "Clear deletes a shown object present in the base document"); + assert_eq!(undo_len(&app), undo + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, original); + } else { + assert_eq!(state.doc, original, "Cancel keeps all artwork when only preview objects were selected"); + assert_eq!(undo_len(&app), undo); + } + } +} + +#[test] +fn a_failed_dialog_preview_retries_after_an_outside_selection_change() { + let mut app = two_rects(); + app.run("select.none", json!({})).unwrap(); + let mut preview = crate::dialogs::preview::LivePreview::default(); + let params = json!({"offset": 5}); + assert!(preview.run(&mut app, true, "Contour", "addon.contour.set", ¶ms).unwrap().is_err()); + preview.keep_outside_edits(&mut app); + assert!(preview.run(&mut app, true, "Contour", "addon.contour.set", ¶ms).is_none()); + let document = app.session.active().unwrap().doc.clone(); + app.run("select.all", json!({})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &document)); + assert!(preview.run(&mut app, true, "Contour", "addon.contour.set", ¶ms).unwrap().is_ok()); + assert!(count(&app) > 2); + preview.cancel(&mut app); + assert_eq!(app.session.active().unwrap().doc, document); +} + +#[test] +fn an_outside_dialog_selection_keeps_its_paints_after_cancel() { + let mut app = two_rects(); + let ids = app.session.active().unwrap().selection.objects.clone(); + app.run("select.set", json!({"ids": [ids[0].0]})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [ids[1].0]})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + let expected = app.session.paint.clone(); + app.run("select.set", json!({"ids": [ids[0].0]})).unwrap(); + assert_ne!(app.session.paint, expected); + + let mut preview = crate::dialogs::preview::LivePreview::default(); + assert!(preview.run(&mut app, true, "Move", "object.move", &json!({"dx": 10, "dy": 0})).unwrap().is_ok()); + preview.keep_outside_edits(&mut app); + app.run("select.set", json!({"ids": [ids[1].0]})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects, vec![ids[1]]); + assert_eq!(app.session.paint, expected); + preview.cancel(&mut app); + assert_eq!(app.session.active().unwrap().selection.objects, vec![ids[1]]); + assert_eq!(app.session.paint, expected); +} + #[test] fn an_add_on_preview_keeps_an_edit_made_outside_the_dialog() { let mut app = two_rects(); diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index 11b9dc7a8f..882da76991 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -15,8 +15,8 @@ pub(crate) struct LivePreview { previewed: Option<(String, Value)>, /// The last preview ran without an error, so its result is on show. shown: bool, - /// The document the last preview ran on: a command from outside the dialog that changes it has the preview run - /// again, even one that failed. + /// The document the last preview ran on. A change to it or the owner's selection snapshot + /// reruns the preview, including one that failed. snapshot: Weak<Document>, owner: Option<Owner>, } @@ -52,8 +52,9 @@ impl LivePreview { } /// While `on`, runs `cmd` with `params` on the interaction's snapshot whenever they differ from the last preview - /// or its interaction has ended; `label` names the undo step. Returns the command's answer when this call ran a - /// preview, and `None` when nothing ran: the same values again (a pass reruns nothing), a preview that could not + /// or its interaction has ended or changed its document or selection snapshot; `label` names the undo step. + /// Returns the command's answer when this call ran a preview, and `None` when nothing ran: + /// the same values and snapshots again, a preview that could not /// begin, another edit in progress, or `on` off, which rolls a shown preview back. Typing in progress is kept as /// its own step first. A refusal's text is written for the user, without the command's id. pub(crate) fn run(&mut self, app: &mut VectorcraftApp, on: bool, label: &str, cmd: &str, params: &Value) -> Option<Result<Value, String>> { @@ -66,11 +67,11 @@ impl LivePreview { return None; } // A command from outside the dialog took a shown preview off its interaction: it runs again. - let taken_off = app - .session - .active() - .and_then(|state| state.interaction.as_ref()) - .is_some_and(|it| (self.shown && it.preview.is_none()) || self.snapshot.as_ptr() != Arc::as_ptr(&it.doc)); + let taken_off = app.session.active().and_then(|state| state.interaction.as_ref()).is_some_and(|it| { + (self.shown && it.preview.is_none()) + || self.snapshot.as_ptr() != Arc::as_ptr(&it.doc) + || self.owner.as_ref().is_some_and(|owner| owner.selection.as_ptr() != Arc::as_ptr(&it.selection)) + }); let same = self.previewed.as_ref().is_some_and(|(c, p)| c == cmd && p == params); if same && !taken_off { return None; diff --git a/docs/mcp.md b/docs/mcp.md index 1322ade27b..57640fb9c7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -889,7 +889,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. The same holds for a step that is neither a number nor null, a `reflect` that is not a string, a `copy` that is not true or false, and an `origin` that is not two numbers. A null `rotate`, `scale`, `scaleX`, `scaleY`, `shear`, `reflect`, `copy` or `origin` is left out; a null `dx` or `dy` counts as 0, so it still runs the move. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. A type object in `ids` with another of them above it in its layer is the text to wrap, not a wrap object, so the objects and the type can be selected together. The reply has a `warning` when no area type lies below any of the wrap objects. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | -| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview, except during an add-on dialog's preview (Object › Plug-ins, other than Edit Points Only): there a command that changes the document records its own undo step, acts on the document without the preview, and stays after the dialog's Cancel or OK, and the dialog previews again from the command's result and selection. `edit.copy` and the `file.*` commands other than `file.documentColorMode` still run on the document as the preview shows it. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | +| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview, except during an add-on dialog's preview (Object › Plug-ins, other than Edit Points Only): there a command that changes the document records its own undo step, acts on the document without the preview using the shown selection restricted to objects present in that document, and stays after the dialog's Cancel or OK. A shown selection containing only preview objects becomes empty for the command. The dialog previews again from the command's result and selection, including after a failed preview when only the selection changed. An outside selection command's selection and paint defaults stay together after Cancel or OK. `edit.copy` and the `file.*` commands other than `file.documentColorMode` still run on the document as the preview shows it. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | | `agent_folders` | `{}` | Where VectorCraft opens and saves files for this session: `{read_folder, write_folder}`, each a path or `null`. In the open window, the agent folders of Preferences › AI Integrations (`Documents/ArtCraft/Agents/VectorCraft` for an empty one); in a headless session started for agents, the folders it was confined to (`read_folders` / `write_folders` list them all when a kind has several); a session started without automation roots answers `unrestricted: true`. An app reached with the deprecated `--connect` answers an error: its own `--automation-*-root` flags, if any, confine it. | For example, create editable Japanese area type with the engine's vertical writing mode: From 68dea71151827b6cc238b79202e9acf725d31b7e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 17:52:27 -0800 Subject: [PATCH 33/56] Docs: Targa's 16-bit gray files carry an 8-bit alpha The MCP export notes said a 16-bit Targa file opens with its one-bit alpha. That holds for 16-bit RGB files only; a 16-bit gray file stores an 8-bit alpha. --- docs/mcp.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 77c64a5c25..c196454366 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13456,8 +13456,9 @@ palette chosen by `reduction` and `dither`; 16, 24, or 32, which keeps transpare `fileFormat` (`windows` or `os2`: 1, 4, 8 or 24 bits only), `rle` (RLE4/RLE8 for 4- and 8-bit Windows bitmaps) and `flipRows` (rows top-down, a negative height; not with `rle` or `os2`); impossible combinations are refused. Targa takes `colorModel` (`rgb`, true color, or `gray`, grayscale) and `depth`: with `rgb` 16 (a one-bit alpha), 24 (default) -or 32 (with alpha); with `gray` 8 (default) or 16 (with alpha). Formats and depths without alpha are flattened on -white. TIFF, BMP and Targa files open again (a 16-bit Targa file with its one-bit alpha); `document.formats` lists +or 32 (with alpha); with `gray` 8 (default) or 16 (an 8-bit alpha). Formats and depths without alpha are flattened on +white. TIFF, BMP and Targa files open again (a 16-bit RGB Targa file with its one-bit alpha, a 16-bit gray one with its +8-bit alpha); `document.formats` lists every option. ```json From 4e6018cece34ecfad2adfc4d594a582899f699c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 17:55:42 -0800 Subject: [PATCH 34/56] Save: ask again for a name the Flatpak file chooser did not grant In the Flatpak build the save panel answers with a path in the document portal (/run/user/<uid>/doc/<id>/<name>), and the portal puts only that name into the folder picked. When the app changed the answer before writing, for example `poster` to `poster.pdf` or `Untitled-1.vectorcraft` to `Untitled-1.pdf` with PDF picked, the write succeeded inside the portal, the status bar said the file was saved, and no file appeared in the folder. Export, Save As, Save a Copy and the read-only Save retry now open the save panel again with the changed name suggested, and the status bar says why. The answer to that panel is written. A read-only retry that changes format still asks for the new format's options. Fixes #10868 --- crates/ui-egui/src/io/save.rs | 75 ++++++++++++++++++- crates/ui-egui/src/io/tests_read_only_save.rs | 25 +++++++ crates/ui-egui/src/tests/saveext.rs | 52 +++++++++++++ 3 files changed, 150 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 1990d57e06..2d2e73354e 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -235,9 +235,47 @@ fn write_step(app: &mut VectorcraftApp, uid: u64, path: &str, target: SaveTarget let path = with_picked_type(&answered, &suggested, picked_ext.as_deref(), first.format, mode); // The flow ends here: the questions and options dialogs that follow run on the path alone. app.saves.release(uid); + if portal_renamed(&answered, &path) { + let name = confirm_portal_name(app, &answered, &path); + return ask_again(app, mode, ¶ms, ask, target, retrying, name); + } replaces_unasked(app, &answered, &path, move |app, path| finish_picked(app, mode, ¶ms, ask, &path, retrying)) } +#[cfg(not(target_arch = "wasm32"))] +/// The save panel again for the active document's save (`mode`, `params`), suggesting `name` in the +/// format its extension names, as a new flow with the same options question (`ask_options`) and +/// `target`. A read-only retry (`retrying`) that changes format drops the options it carries and +/// asks for the new format's, as [`finish_picked`] does. +fn ask_again( + app: &mut VectorcraftApp, + mode: SaveMode, + params: &Value, + mut ask_options: bool, + target: SaveTarget, + retrying: bool, + name: String, +) -> Result<Value, String> { + let original = plan(app, mode, &acknowledged(params))?.format.id; + let mut q = if params.is_object() { params.clone() } else { json!({}) }; + if let Some(f) = fileio::format_for_name(&name) { + if retrying && f.id != original { + if let Some(o) = q.as_object_mut() { + o.remove("options"); + } + ask_options = true; + } + q["format"] = json!(f.id); + } + let first = plan(app, mode, &acknowledged(&q))?; + let directory = if mode == SaveMode::Template { + fileio::templates_dialog_folder(&app.session.prefs).map(PathBuf::from) + } else { + first.folder.clone().map(PathBuf::from) + }; + start_flow(app, &first, Start { mode, params: &q, ask_options, target, retry: None, name, directory, retrying }) +} + #[cfg(not(target_arch = "wasm32"))] /// What [`start_flow`] needs besides the plan. struct Start<'a> { @@ -456,18 +494,51 @@ fn ask_path( return then(app, with_written_extension(&name, &ext, &keeps)); } let mut request = PickRequest::save("export").file_name(name); - request.filters = filters; - if let Some(folder) = folder { + request.filters = filters.clone(); + if let Some(folder) = folder.clone() { request = request.directory(folder); } Ok(file_asks::ask(app, request, Owner::Document, move |app, picked| { let Picked::Saved { path: picked, .. } = picked else { return Err("cancelled".into()) }; let picked = picked.to_string_lossy().into_owned(); let path = with_written_extension(&picked, &ext, &keeps); + if portal_renamed(&picked, &path) { + let name = confirm_portal_name(app, &picked, &path); + return ask_path(app, None, name, folder, filters, ext, keeps, then); + } replaces_unasked(app, &picked, &path, then) })) } +/// Whether `path` is a file in a folder of the document portal (`/run/user/<uid>/doc/<id>/` or +/// `/run/flatpak/doc/<id>/`), where the save panel's answers point in a Flatpak sandbox. The portal +/// puts only the name the panel answered into the folder picked in it: a file written there under +/// another name is written without an error, and the folder gets no file. +fn in_document_portal(path: &str) -> bool { + let rest = path.strip_prefix("/run/flatpak/doc/").or_else(|| { + let (uid, rest) = path.strip_prefix("/run/user/")?.split_once('/')?; + if uid.is_empty() || !uid.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + rest.strip_prefix("doc/") + }); + rest.and_then(|r| r.split_once('/')).is_some_and(|(id, name)| !id.is_empty() && !name.is_empty() && !name.contains('/')) +} + +/// Whether the save panel's answer `picked` was made into another name, `path`, in a folder of the +/// document portal ([`in_document_portal`]). +fn portal_renamed(picked: &str, path: &str) -> bool { + path != picked && in_document_portal(picked) +} + +/// The file name of `path`, for the save panel to ask with again in place of the answer `picked`; +/// the status bar says why the panel opens again. +fn confirm_portal_name(app: &mut VectorcraftApp, picked: &str, path: &str) -> String { + let name = fileio::file_name(path); + app.status(format!("The file chooser can only save “{}”: confirm “{name}” to save it", fileio::file_name(picked))); + name +} + /// `path` as typed in a save panel for a file with extension `ext`: kept when its extension is /// `ext` in any letter case, or names the format `ext` names (`photo.jpeg` for a `.jpg` file) or /// a format `keeps` takes. An extension that names another format (`card.svg` for a `.png` file) diff --git a/crates/ui-egui/src/io/tests_read_only_save.rs b/crates/ui-egui/src/io/tests_read_only_save.rs index 19725e4b4d..ae42d1c4d6 100644 --- a/crates/ui-egui/src/io/tests_read_only_save.rs +++ b/crates/ui-egui/src/io/tests_read_only_save.rs @@ -310,6 +310,31 @@ fn readonly_changed_format_asks_for_its_options_before_writing() { assert_eq!(files.lock().unwrap().attempts, ["/locked/Poster.svg"]); } +/// The retry's save panel in the document portal, with PDF picked and `Poster.svg` kept: the panel +/// opens again for `Poster.pdf`, and its answer asks for the PDF options before writing. +#[test] +fn readonly_changed_format_in_the_document_portal_asks_for_its_options_before_writing() { + let portal = "/run/user/1000/doc/a1b2c3d4"; + let (mut app, files) = app("svg", ErrorKind::PermissionDenied); + let before = state(&app); + let picker = scripted(&mut app); + assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "fileDialog"); + let pdf = picker.requests()[0].filters.iter().position(|f| f.extensions.iter().any(|e| e == "pdf")); + assert!(pdf.is_some(), "the retry's save panel offers PDF"); + picker.answer_saved(&format!("{portal}/Poster.svg"), pdf); + poll(&mut app); + assert!(fields_of(&app, "pdf-export").is_none(), "no options before the name is granted"); + assert_eq!(picker.requests().len(), 2, "the save panel opens again"); + assert_eq!(picker.requests()[1].file_name.as_deref(), Some("Poster.pdf")); + picker.answer_saved(&format!("{portal}/Poster.pdf"), None); + poll(&mut app); + assert!(fields_of(&app, "pdf-export").is_some(), "the picked format's Save dialog"); + let job = app.save_pdf.as_ref().and_then(|open| open.job.as_ref()); + assert_eq!(job.and_then(|job| job.path.clone()), Some(format!("{portal}/Poster.pdf"))); + assert_eq!(state(&app), before); + assert_eq!(files.lock().unwrap().attempts, ["/locked/Poster.svg"]); +} + /// Typed saves keep the sidecar preflight both before the refused write and at the retry's /// destination. Confirming the ordinary Save still permits its one read-only fallback. #[test] diff --git a/crates/ui-egui/src/tests/saveext.rs b/crates/ui-egui/src/tests/saveext.rs index b8b456abd9..a34a3c55eb 100644 --- a/crates/ui-egui/src/tests/saveext.rs +++ b/crates/ui-egui/src/tests/saveext.rs @@ -552,3 +552,55 @@ fn an_export_keeps_a_typed_extension_of_the_format_it_writes() { answer_top(&mut app, &[], true); assert_eq!(last(&w), "/tmp/sel.pdf", "Export Selection takes its format from the typed name"); } + +/// The file name the last save panel suggested. +fn suggested_name(picker: &Picker) -> Option<String> { + picker.requests().last()?.file_name.clone() +} + +/// In a Flatpak sandbox the save panel answers with a path in the document portal, which puts only +/// that name into the folder picked. A name the export has to change (`poster` for a PDF) is not +/// written: the save panel opens again suggesting `poster.pdf`, and its answer is written. A +/// look-alike path outside the portal gets the extension at once. +#[test] +fn an_export_asks_again_for_a_name_the_document_portal_did_not_grant() { + for portal in ["/run/user/1000/doc/a1b2c3d4", "/run/flatpak/doc/a1b2c3d4"] { + let (mut app, picker, w) = saving_app(); + save_via(&mut app, &picker, |a| io::export_pdf(a, json!({})), (&format!("{portal}/poster"), None)); + assert!(w.borrow().is_empty(), "nothing is written under a name the portal did not grant: {:?}", w.borrow()); + assert_eq!(picker.requests().len(), 2, "the save panel opens again"); + assert_eq!(suggested_name(&picker).as_deref(), Some("poster.pdf")); + assert!(app.ui.status.contains("poster.pdf"), "{}", app.ui.status); + picker.answer_saved(&format!("{portal}/poster.pdf"), None); + poll(&mut app); + assert_eq!(w.borrow().as_slice(), [format!("{portal}/poster.pdf")]); + assert_eq!(picker.requests().len(), 2, "a granted name is written without asking again"); + } + let (mut app, picker, w) = saving_app(); + save_via(&mut app, &picker, |a| io::export_pdf(a, json!({})), ("/home/me/run/user/1000/doc/a1b2/poster", None)); + assert_eq!(w.borrow().as_slice(), ["/home/me/run/user/1000/doc/a1b2/poster.pdf"]); + assert_eq!(picker.requests().len(), 1); +} + +/// Save As in the document portal with PDF picked and the suggested `Untitled-1.vectorcraft` kept: +/// the save panel opens again suggesting `Untitled-1.pdf` with PDF as the file type, and the PDF +/// options and the write follow its answer. +#[test] +fn save_as_asks_again_for_a_name_the_document_portal_did_not_grant() { + let portal = "/run/user/1000/doc/a1b2c3d4"; + let (mut app, picker, w) = saving_app(); + let _ = app.run("file.saveAs", json!({})); + let pdf = type_index(&picker, "pdf").expect("Save As offers PDF"); + picker.answer_saved(&format!("{portal}/Untitled-1.vectorcraft"), Some(pdf)); + poll(&mut app); + assert!(w.borrow().is_empty(), "{:?}", w.borrow()); + assert!(dialog_path(&app).is_none(), "no PDF options before the name is granted"); + assert_eq!(picker.requests().len(), 2, "the save panel opens again"); + assert_eq!(suggested_name(&picker).as_deref(), Some("Untitled-1.pdf")); + assert_eq!(type_index(&picker, "pdf"), Some(0), "PDF is the first file type offered"); + picker.answer_saved(&format!("{portal}/Untitled-1.pdf"), Some(0)); + poll(&mut app); + assert_eq!(dialog_path(&app), Some(format!("{portal}/Untitled-1.pdf"))); + answer_top(&mut app, &[], true); + assert_eq!(last(&w), format!("{portal}/Untitled-1.pdf")); +} From 8eacad4a694eed179948f7e2e4cc2c1917081e2b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 18:00:55 -0800 Subject: [PATCH 35/56] Tests: check the shown selection is not empty before checking its members --- crates/ui-egui/src/addons/dialogs/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index bd2ae77899..d3e3b3d9f0 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -329,6 +329,7 @@ fn clearing_a_dialog_preview_uses_only_the_shown_base_objects() { let params = json!({}); assert!(preview.run(&mut app, true, "Flood Fill Artboards", "addon.document.floodFillArtboards", ¶ms).unwrap().is_ok()); preview.keep_outside_edits(&mut app); + assert!(!app.session.active().unwrap().selection.objects.is_empty()); assert!(app.session.active().unwrap().selection.objects.iter().all(|id| original.node(*id).is_none())); if include_base_object { app.session.active_mut().unwrap().selection.add(selected[0]); From fcc8f717dc85c3f32799d9e15b5c6d0fbbbeef88 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 18:15:21 -0800 Subject: [PATCH 36/56] Scripts: test that a group's pathItems.removeAll() refuses an id found outside it Adds a test that builds a document where a path outside a group has the same id as a path in the group, and checks that the group's pathItems.removeAll() throws and deletes nothing. --- crates/engine/src/tests/script_dom.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 6b45c5105f..1bab9b1e4b 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -4080,6 +4080,33 @@ fn group_path_items_remove_all_walks_only_the_group() { assert!(visits <= 3, "{visits} objects walked to empty a group of two paths"); } +/// In a damaged document where a path outside a group has the same id as a path in it, the +/// group's `pathItems.removeAll()` throws and deletes nothing, instead of deleting the outside path. +#[test] +fn group_path_items_remove_all_refuses_an_id_found_outside_the_group() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + s.execute("object.arrange.sendToBack", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + d.node_mut(c).unwrap().id = a; + d.drop_lookup_cache(); + // The first object in tree order with the id is the one outside the group. + assert_eq!(d.index_path(a).map(|p| p.len()), Some(2)); + let n = d.layers[0].children().map_or(0, Vec::len); + let out = log( + &mut s, + "var d = app.activeDocument, m = ''; try { d.groupItems[0].pathItems.removeAll(); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(d.groupItems[0].pathItems.length);", + ); + assert_eq!(out, vec![json!(format!("cannot delete PathItem {}: its id also names another object", a.0)), json!(2)]); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers[0].children().map_or(0, Vec::len), n, "the path outside the group is kept"); +} + /// The document's `pathItems.removeAll()` refuses to delete the path that clips a group while the /// group keeps other art, and deletes nothing, as the scoped collections do. #[test] From 06f65d1870a510e3d57b2280606a5eb113ff973a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 18:15:22 -0800 Subject: [PATCH 37/56] DXF import: a region edge that loops on an open spline keeps only its loop An edge that starts and ends at one vertex took its whole spline. When the spline is open, the edge is the loop between the two places where the curve passes through that vertex, and the import now trims it there; with any other count of such places it keeps the whole curve and warns. A loop made of a single curve that ends where it starts is split in two, so it keeps two anchors and doesn't collapse to a point. --- crates/cad/src/import/acis.rs | 76 ++++++++++++++++++--------- crates/cad/src/import/tests_region.rs | 12 +++++ 2 files changed, 63 insertions(+), 25 deletions(-) diff --git a/crates/cad/src/import/acis.rs b/crates/cad/src/import/acis.rs index bb1bc92a1c..af12f517be 100644 --- a/crates/cad/src/import/acis.rs +++ b/crates/cad/src/import/acis.rs @@ -509,6 +509,14 @@ fn outline(m: &Model) -> Option<Outline> { { o.broken |= endpoints_apart(end, start); } + // A loop of one curve ending where it starts is split in two: as one + // segment, its start and end would become one anchor. + if let [seg] = bp.segments().collect::<Vec<_>>()[..] + && !matches!(seg, PathSeg::Line(_)) + { + let (a, b) = seg.subdivide(); + bp = BezPath::from_path_segments([a, b].into_iter()); + } bp.close_path(); if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS { return None; @@ -660,7 +668,7 @@ fn cubic_crossing(cubic: kurbo::CubicBez) -> Option<(f64, f64)> { } /// An `intcurve-curve` from `from` to `to` (the part of its spline between them), the whole -/// curve when the edge starts and ends at one vertex; also whether trimming is ambiguous. +/// ring when the edge starts and ends at one vertex; also whether trimming is ambiguous. fn spline(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option<(BezPath, bool)> { // The curve's own sense comes before its data. let open = c.toks.iter().position(|t| *t == Tok::Open)?; @@ -671,11 +679,11 @@ fn spline(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Optio let back = back != curve_back; let segs: Vec<PathSeg> = full.segments().collect(); let (first, last) = (segs.first()?.start(), segs.last()?.end()); + let ring = first.distance(last) <= 1e-9 * (1.0 + first.to_vec2().hypot()); let mut ambiguous = false; - let part = if closed { + let part = if closed && ring { full } else { - let ring = first.distance(last) <= 1e-9 * (1.0 + first.to_vec2().hypot()); let mut lengths = vec![0.0]; for s in &segs { lengths.push(lengths.last()? + s.arclen(1e-9)); @@ -686,34 +694,52 @@ fn spline(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Optio let near: Vec<_> = segs.iter().enumerate().map(|(i, s)| (s.nearest(p, 1e-9), i)).collect(); let (n, i) = near.iter().min_by(|a, b| a.0.distance_sq.total_cmp(&b.0.distance_sq))?; let along = |i: usize, t: f64| lengths[i] + segs[i].subsegment(0.0..t).arclen(1e-9); - let start = along(*i, n.t); let tolerance = 1e-6 * (1.0 + p.x.hypot(p.y)); - // Nearby ends at a segment joint, or at a closed curve's seam, are one location. - let ambiguous = near.iter().any(|(other, j)| { - if endpoints_apart(p, segs[*j].eval(other.t)) { - return false; + let mut locations: Vec<_> = + near.iter().filter(|(n, i)| !endpoints_apart(p, segs[*i].eval(n.t))).map(|(n, i)| (*i as f64 + n.t, along(*i, n.t))).collect(); + for (i, s) in segs.iter().enumerate() { + if let PathSeg::Cubic(cubic) = s + && let Some((a, b)) = cubic_crossing(*cubic) + && !endpoints_apart(p, cubic.eval(a)) + { + locations.extend([a, b].map(|t| (i as f64 + t, along(i, t)))); } - let distance = (along(*j, other.t) - start).abs(); - let distance = if ring { distance.min((total - distance).abs()) } else { distance }; - distance > 4.0 * tolerance - }) || segs.iter().any(|s| match s { - PathSeg::Cubic(cubic) => cubic_crossing(*cubic).is_some_and(|(t, _)| !endpoints_apart(p, cubic.eval(t))), - _ => false, - }); - Some((*i as f64 + n.t, ambiguous)) + } + // Nearby ends at a segment joint, or at a closed curve's seam, are one location. + locations.sort_by(|a, b| a.0.total_cmp(&b.0)); + locations.dedup_by(|a, b| (a.1 - b.1).abs() <= 4.0 * tolerance); + if ring && locations.len() > 1 && (total - (locations.last()?.1 - locations.first()?.1)).abs() <= 4.0 * tolerance { + locations.pop(); + } + Some((*i as f64 + n.t, locations)) }; - let ((ga, a), (gb, b)) = (at(from)?, at(to)?); - ambiguous = a || b; - let (lo, hi) = if back { (gb, ga) } else { (ga, gb) }; - let pieces = if lo <= hi || !ring { - piece(&segs, lo.min(hi), hi.max(lo)) + let bounds = if closed { + let (_, locations) = at(from)?; + if let [a, b] = locations.as_slice() { + Some((a.0, b.0)) + } else { + ambiguous = true; + None + } } else { - [piece(&segs, lo, segs.len() as f64), piece(&segs, 0.0, hi)].concat() + let ((ga, a), (gb, b)) = (at(from)?, at(to)?); + ambiguous = a.len() > 1 || b.len() > 1; + Some((ga, gb)) }; - if pieces.is_empty() { - return None; + if let Some((ga, gb)) = bounds { + let (lo, hi) = if back { (gb, ga) } else { (ga, gb) }; + let pieces = if lo <= hi || !ring { + piece(&segs, lo.min(hi), hi.max(lo)) + } else { + [piece(&segs, lo, segs.len() as f64), piece(&segs, 0.0, hi)].concat() + }; + if pieces.is_empty() { + return None; + } + BezPath::from_path_segments(pieces.into_iter()) + } else { + full } - BezPath::from_path_segments(pieces.into_iter()) }; Some((if back { part.reverse_subpaths() } else { part }, ambiguous)) } diff --git a/crates/cad/src/import/tests_region.rs b/crates/cad/src/import/tests_region.rs index cf37e9585f..0925729add 100644 --- a/crates/cad/src/import/tests_region.rs +++ b/crates/cad/src/import/tests_region.rs @@ -429,6 +429,18 @@ fn a_spline_edge_warns_when_an_endpoint_is_at_one_cubic_spans_crossing() { assert!(!outline(&r.document).elements().is_empty()); } +#[test] +fn a_closed_spline_edge_keeps_the_loop_at_one_cubic_spans_crossing() { + // The curve crosses (0, 0) at 0.25 and 0.75; the loop reaches (-12, 0) at 0.5. + let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 3 open 2 0 3 1 3 36 -18 0 -28 26 0 -28 -26 0 36 18 0 } I I"; + for back in [false, true] { + let edge = E { a: [0.0, 0.0], b: [0.0, 0.0], curve: Curve::Raw(curve.into()), flip: false, against: back }; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[vec![edge]], None), false), &[]), &points()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + check(&r.document, &[[-6.0, 0.0]], &[[30.0, 0.0]]); + } +} + #[test] fn spline_joints_and_a_closed_curves_seam_do_not_warn() { for (curve, a) in [ From 0648ab54b960c5cab32811ecb79fa77da3f37b23 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 18:22:50 -0800 Subject: [PATCH 38/56] DXF import: warn when a closed spline edge starts at the curve's crossing An edge whose vertex lies where a closed spline crosses itself may bound only one lobe of the curve. The import still draws the whole curve, now with the warning for edges on self-crossing curves. --- crates/cad/src/import/acis.rs | 60 ++++++++++++++------------- crates/cad/src/import/tests_region.rs | 18 ++++++++ 2 files changed, 49 insertions(+), 29 deletions(-) diff --git a/crates/cad/src/import/acis.rs b/crates/cad/src/import/acis.rs index af12f517be..581e168625 100644 --- a/crates/cad/src/import/acis.rs +++ b/crates/cad/src/import/acis.rs @@ -680,39 +680,41 @@ fn spline(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Optio let segs: Vec<PathSeg> = full.segments().collect(); let (first, last) = (segs.first()?.start(), segs.last()?.end()); let ring = first.distance(last) <= 1e-9 * (1.0 + first.to_vec2().hypot()); + let mut lengths = vec![0.0]; + for s in &segs { + lengths.push(lengths.last()? + s.arclen(1e-9)); + } + let total = *lengths.last()?; + let at = |p: P3| { + let p = flat(xf.point(p)); + let near: Vec<_> = segs.iter().enumerate().map(|(i, s)| (s.nearest(p, 1e-9), i)).collect(); + let (n, i) = near.iter().min_by(|a, b| a.0.distance_sq.total_cmp(&b.0.distance_sq))?; + let along = |i: usize, t: f64| lengths[i] + segs[i].subsegment(0.0..t).arclen(1e-9); + let tolerance = 1e-6 * (1.0 + p.x.hypot(p.y)); + let mut locations: Vec<_> = + near.iter().filter(|(n, i)| !endpoints_apart(p, segs[*i].eval(n.t))).map(|(n, i)| (*i as f64 + n.t, along(*i, n.t))).collect(); + for (i, s) in segs.iter().enumerate() { + if let PathSeg::Cubic(cubic) = s + && let Some((a, b)) = cubic_crossing(*cubic) + && !endpoints_apart(p, cubic.eval(a)) + { + locations.extend([a, b].map(|t| (i as f64 + t, along(i, t)))); + } + } + // Nearby ends at a segment joint, or at a closed curve's seam, are one location. + locations.sort_by(|a, b| a.0.total_cmp(&b.0)); + locations.dedup_by(|a, b| (a.1 - b.1).abs() <= 4.0 * tolerance); + if ring && locations.len() > 1 && (total - (locations.last()?.1 - locations.first()?.1)).abs() <= 4.0 * tolerance { + locations.pop(); + } + Some((*i as f64 + n.t, locations)) + }; let mut ambiguous = false; let part = if closed && ring { + let (_, locations) = at(from)?; + ambiguous = locations.len() > 1; full } else { - let mut lengths = vec![0.0]; - for s in &segs { - lengths.push(lengths.last()? + s.arclen(1e-9)); - } - let total = *lengths.last()?; - let at = |p: P3| { - let p = flat(xf.point(p)); - let near: Vec<_> = segs.iter().enumerate().map(|(i, s)| (s.nearest(p, 1e-9), i)).collect(); - let (n, i) = near.iter().min_by(|a, b| a.0.distance_sq.total_cmp(&b.0.distance_sq))?; - let along = |i: usize, t: f64| lengths[i] + segs[i].subsegment(0.0..t).arclen(1e-9); - let tolerance = 1e-6 * (1.0 + p.x.hypot(p.y)); - let mut locations: Vec<_> = - near.iter().filter(|(n, i)| !endpoints_apart(p, segs[*i].eval(n.t))).map(|(n, i)| (*i as f64 + n.t, along(*i, n.t))).collect(); - for (i, s) in segs.iter().enumerate() { - if let PathSeg::Cubic(cubic) = s - && let Some((a, b)) = cubic_crossing(*cubic) - && !endpoints_apart(p, cubic.eval(a)) - { - locations.extend([a, b].map(|t| (i as f64 + t, along(i, t)))); - } - } - // Nearby ends at a segment joint, or at a closed curve's seam, are one location. - locations.sort_by(|a, b| a.0.total_cmp(&b.0)); - locations.dedup_by(|a, b| (a.1 - b.1).abs() <= 4.0 * tolerance); - if ring && locations.len() > 1 && (total - (locations.last()?.1 - locations.first()?.1)).abs() <= 4.0 * tolerance { - locations.pop(); - } - Some((*i as f64 + n.t, locations)) - }; let bounds = if closed { let (_, locations) = at(from)?; if let [a, b] = locations.as_slice() { diff --git a/crates/cad/src/import/tests_region.rs b/crates/cad/src/import/tests_region.rs index 0925729add..18167d1fe9 100644 --- a/crates/cad/src/import/tests_region.rs +++ b/crates/cad/src/import/tests_region.rs @@ -441,6 +441,24 @@ fn a_closed_spline_edge_keeps_the_loop_at_one_cubic_spans_crossing() { } } +#[test] +fn a_closed_spline_ring_warns_only_when_its_vertex_is_at_the_crossing() { + // The first and third spans cross (0, 0) halfway along each; the seam is (-100, -100). + let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 closed 5 0 2 1 1 2 1 3 1 4 2 -100 -100 0 100 100 0 -100 100 0 100 -100 0 -100 -100 0 } I I"; + for a in [[0.0, 0.0], [-100.0, -100.0]] { + for back in [false, true] { + let edge = E { a, b: a, curve: Curve::Raw(curve.into()), flip: false, against: back }; + let r = import(&drawing("AC1015", ®ion_text(&sat(&[vec![edge]], None), false), &[]), &points()).unwrap(); + if a == [0.0, 0.0] { + assert_eq!(r.warnings, ["region edges on curves that cross themselves may come in along the wrong part of the curve"]); + } else { + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + } + check(&r.document, &[[0.0, 50.0], [0.0, -50.0]], &[[75.0, 0.0], [-75.0, 0.0]]); + } + } +} + #[test] fn spline_joints_and_a_closed_curves_seam_do_not_warn() { for (curve, a) in [ From c9837cf096f1417f3cf865767c42847beda6523f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 18:23:22 -0800 Subject: [PATCH 39/56] DXF Import: Place borrows the previewed bytes instead of copying them The place job given the dialog's bytes reads them in place, so a large drawing is not held twice in memory while it is decoded. --- crates/engine/src/cmd/fileio/importer.rs | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index 2add54d017..322f671ede 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -17,6 +17,7 @@ //! layers and artboards (its manifest's `outputKinds`): the artboards it returns replace the one //! around the art of a new document, and File › Place leaves them out. +use std::borrow::Cow; use std::sync::Arc; use serde_json::Value; @@ -203,11 +204,11 @@ fn read_path_for(path: &str, _: &Value, _: Mode, _: &str) -> Result<Vec<u8>> { /// that a file an importer would place (one `importer` names, or an extension no built-in format /// reads that an importer which places its files lists) is read, or decoded, only when it is at /// most [`import::MAX_INPUT_BYTES`] long. `given`: the bytes of the file `path` names, read already, -/// which are used instead of reading the path again (by the same size rule). -pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str, given: Option<&[u8]>) -> Result<Source<'a>> { +/// which are borrowed instead of reading the path again (by the same size rule). +pub(crate) fn place_source<'a, 'b>(p: &'a Value, cmd: &str, given: Option<&'b [u8]>) -> Result<PlaceSource<'a, 'b>> { match str_param(p, "path") { Some(path) => { - let bytes = match given { + let bytes: Cow<'b, [u8]> = match given { Some(bytes) => { // The roots in force now still apply to the path, though it is not read again. #[cfg(not(target_arch = "wasm32"))] @@ -218,19 +219,27 @@ pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str, given: Option<&[u8]>) -> if importer && !built_in && bytes.len() > import::MAX_INPUT_BYTES { return Err(too_large(path, Mode::Place)); } - bytes.to_vec() + Cow::Borrowed(bytes) } - None => read_path_for(path, p, Mode::Place, cmd)?, + None => Cow::Owned(read_path_for(path, p, Mode::Place, cmd)?), }; - Ok(Source { name: path, bytes, path: Some(path) }) + Ok(PlaceSource { name: path, bytes, path: Some(path) }) } None => { check_data_for(p, Mode::Place, cmd)?; - super::source(p, cmd) + let Source { name, bytes, path } = super::source(p, cmd)?; + Ok(PlaceSource { name, bytes: Cow::Owned(bytes), path }) } } } +/// The file [`place_source`] gives: as [`Source`], its bytes borrowed when they were given. +pub(crate) struct PlaceSource<'a, 'b> { + pub name: &'a str, + pub bytes: Cow<'b, [u8]>, + pub path: Option<&'a str>, +} + /// What [`read`] gives: the importer's format, the new document, its objects' ids, the artboards /// the importer returned and its warnings. type Read = (&'static Format, Document, Vec<NodeId>, Vec<import::OutArtboard>, Vec<String>); From 02c4ac0f74922f55039f317f2494bdc6350e4de7 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 18:38:31 -0800 Subject: [PATCH 40/56] Scripts: a Color Picker pick converts through the script document's profiles app.showColorPicker answers the run between slices, when the active color settings hold the profiles of the document the window shows. A pick in the run's own document, made or assigned other profiles by the script, was converted to that document's RGB space and separated to CMYK through the window's profiles instead. The dialog now carries the RGB and CMYK profiles assigned to the run's active document when the picker opens. On OK a display-sRGB pick (hex, sample, HSB) is taken into that document's RGB space, RGB values typed into the picker convert from the shown RGB profile to the document's, and an RGB pick in a CMYK document separates through the document's CMYK profile. --- crates/engine/src/script/dialogs.rs | 16 ++++- crates/engine/src/script/dom/preferences.rs | 1 + crates/engine/src/tests/script_dialogs.rs | 1 + crates/engine/src/tests/script_dom_prefs.rs | 1 + crates/ui-egui/src/dialogs/color_picker.rs | 40 +++++++++-- crates/ui-egui/src/dialogs/script_run.rs | 1 + crates/ui-egui/src/script_runs.rs | 2 +- crates/ui-egui/src/tests/script_dialogs.rs | 73 +++++++++++++++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 10 files changed, 128 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index 7264290717..cae33925aa 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -98,6 +98,10 @@ pub struct ScriptDialog { /// `showColorPicker`: the run's active document is in CMYK when the picker opens, so the app /// gives an RGB pick back as CMYK. False for the other dialogs. pub cmyk_document: bool, + /// `showColorPicker`: the RGB and CMYK profiles the run's active document is assigned (`None`: + /// none) when the picker opens, which the app converts the pick through. `(None, None)` for the + /// other dialogs. + pub profiles: (Option<String>, Option<String>), } /// The answer to a [`ScriptDialog`]. @@ -705,7 +709,10 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError> if preset.len() > MAX_PROMPT_BYTES { return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB"))); } - wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false }) + wait_or_answer( + host, + ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false, profiles: (None, None) }, + ) } /// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK, @@ -713,7 +720,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError> pub(super) fn show_color_picker(host: &Host, color: Color) -> Result<Data, HostError> { // During a slice the session holds the run's working copy, whose active document may be one // the script made; between slices the app sees the documents as they were before the run. - let cmyk_document = host.session.borrow().active().is_some_and(|s| s.doc.color_mode == crate::doc::ColorMode::Cmyk); + let (cmyk_document, profiles) = host + .session + .borrow() + .active() + .map_or((false, (None, None)), |s| (s.doc.color_mode == crate::doc::ColorMode::Cmyk, crate::cmd::colormgmt::doc_profiles(&s.doc))); let dialog = ScriptDialog { kind: DialogKind::ColorPicker, message: String::new(), @@ -723,6 +734,7 @@ pub(super) fn show_color_picker(host: &Host, color: Color) -> Result<Data, HostE preset: String::new(), color: Some(color), cmyk_document, + profiles, }; wait_or_answer(host, dialog) } diff --git a/crates/engine/src/script/dom/preferences.rs b/crates/engine/src/script/dom/preferences.rs index cec96feeec..a2b04db9ff 100644 --- a/crates/engine/src/script/dom/preferences.rs +++ b/crates/engine/src/script/dom/preferences.rs @@ -281,6 +281,7 @@ fn set_warning(h: &Host, on: bool) -> Answer { preset: String::new(), color: None, cmyk_document: false, + profiles: (None, None), }; if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) { return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into())); diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index 3bd15e3fa8..e9931c11ab 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -179,6 +179,7 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() { preset: String::new(), color: None, cmyk_document: false, + profiles: (None, None), }; assert_eq!(s.script_dialog(), Some(want)); assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 1eaff02d45..99d555b603 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -106,6 +106,7 @@ fn yes_to_the_confirm_turns_the_warning_off() { preset: String::new(), color: None, cmyk_document: false, + profiles: (None, None), }; assert_eq!(s.script_dialog(), Some(want)); assert!(s.script_dialog_turns_warning_off()); diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 44684cac2a..938237f5fc 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -51,8 +51,9 @@ pub(crate) enum Target { /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, /// The answer to a running script's `app.showColorPicker`, which opened it on `color`; `cmyk`: - /// the run's active document is in CMYK. - Script { color: Color, cmyk: bool }, + /// the run's active document is in CMYK; `profiles`: the RGB and CMYK profiles that document is + /// assigned, which the pick converts through. + Script { color: Color, cmyk: bool, profiles: (Option<String>, Option<String>) }, } impl Target { @@ -242,6 +243,28 @@ fn working_cmyk() -> Option<CmykConverter> { CmykConverter::new(Arc::new(Profile::parse(&bytes).ok()?)).ok() } +/// The color a script's picker gives for `picked` in the script's document assigned `profiles` +/// (`cmyk`: a CMYK document), which separates through that document's CMYK profile. A pick in +/// display sRGB (a hex value, a sample, HSB) is that sRGB color in the document's RGB space; RGB +/// values typed into the picker are in the active RGB space, and convert from it to the document's +/// RGB space when the two differ. CMYK, gray and Lab values stay as they are. +fn script_pick(picked: &PickedColor, cmyk: bool, profiles: &(Option<String>, Option<String>)) -> Color { + let shown = cms::active(); + let own = cms::for_document(profiles.0.as_deref(), profiles.1.as_deref()); + let c = match picked.model.as_ref().map(|v| v.model) { + None | Some("hsb") => screen_color::sampled(&own, [picked.color.r, picked.color.g, picked.color.b]), + Some(_) => { + let c = color_of(picked); + if matches!(c, Color::Rgb { .. }) && shown.settings().rgb != own.settings().rgb { + shown.convert_into(&own, &c, own.settings().intent) + } else { + c + } + } + }; + cms::with_active(own, || in_model(cmyk, c)) +} + /// `ui.colorPicker {stroke?, artboard?, color?}`: open the picker for the fill (or stroke) proxy, /// or for artboard `artboard`'s background color, starting from `color`, else the proxy's color /// or the artboard's color (white when it has none). @@ -322,16 +345,17 @@ fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool) -> ColorPi } /// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`; `cmyk`: -/// the run's own active document is in CMYK, which the session does not show between slices. It +/// the run's own active document is in CMYK, which the session does not show between slices; +/// `profiles`: the RGB and CMYK profiles that document is assigned, which OK converts the pick through. It /// previews nothing; its OK and Cancel answer the run ([`finish`]). -pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool) { +pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool, profiles: (Option<String>, Option<String>)) { let Some(dialogs) = app.dialogs() else { return }; // The given colour's own values, so that OK can tell an untouched pick from another model's. // The Only Web Colors setting of earlier pickers is not recalled, so the colour opens as given. let dialog = picker(app, SCRIPT_KEY, &color, cmyk).kept(model_values(&color)).web_colors_remembered(false); let id = dialogs.with(|h| h.open(dialog)); app.color_dialogs.pickers.retain(|o| o.id != id); - let target = Target::Script { color, cmyk }; + let target = Target::Script { color, cmyk, profiles }; app.color_dialogs.pickers.push(Open { id, target, @@ -503,9 +527,11 @@ fn finish( } } // OK on the colour it opened with, in the model it opened with, gives that colour back. - (Some(DialogResult::Ok(r)), Target::Script { color: given, cmyk }) => { + // Between slices the window's front document sets the active profiles; the pick converts + // through the profiles of the script's document instead. + (Some(DialogResult::Ok(r)), Target::Script { color: given, cmyk, profiles }) => { let untouched = r.picked.color == open.start && r.picked.model == Some(model_values(given)); - let picked = if untouched { *given } else { in_model(*cmyk, color_of(&r.picked)) }; + let picked = if untouched { *given } else { script_pick(&r.picked, *cmyk, profiles) }; app.session.script_answer(DialogAnswer::ColorPicker(Some(picked))); } (_, Target::Script { .. }) => { diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 69dc0c9b58..3a16914ee7 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -1222,6 +1222,7 @@ mod tests { preset: String::new(), color: None, cmyk_document: false, + profiles: (None, None), }; let ctx = egui::Context::default(); // A script's own confirm with the same text takes Yes. diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 9f75b2cc80..93b64eb68b 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -247,7 +247,7 @@ fn ask(app: &mut VectorcraftApp) -> bool { && !script_run::busy(app) && let Some(color) = dialog.color { - color_picker::open_for_script(app, color, dialog.cmyk_document); + color_picker::open_for_script(app, color, dialog.cmyk_document, dialog.profiles.clone()); } } else if script_run::can_ask(app) { script_run::open_notice(app, &dialog); diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index 9d2c95bffd..ec7fbd0579 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -510,6 +510,79 @@ fn a_pick_takes_the_model_of_the_document_the_script_made() { } } +/// An RGB pick in the CMYK document a script made and assigned its own profiles separates through +/// those profiles, not through the profiles of the document the window shows: a hex pick, and RGB +/// values typed into the picker, which show the green they show in the window's RGB space. +#[test] +fn a_pick_separates_through_the_profiles_of_the_scripts_document() { + const CHILD: &str = "VECTORCRAFT_TEST_SCRIPT_PICK_DOC_PROFILE"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: assign the profiles in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "tests::script_dialogs::a_pick_separates_through_the_profiles_of_the_scripts_document", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated document profile test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use craft::theme::{ModelValues, Srgba}; + use vectorcraft_color::Color; + use vectorcraft_color::cms; + let srgb = [128.0 / 255.0, 160.0 / 255.0, 96.0 / 255.0]; + // The green in a context's RGB space: the display color (a hex pick), or the window's RGB values + // converted from the window's RGB profile (typed values). + let inks = |ctx: std::sync::Arc<cms::Cms>, native: bool| { + let c = if native { + let window = cms::for_document(None, None); + let [r, g, b] = window.srgb_to_rgb(srgb); + window.convert_into(&ctx, &Color::rgb(r, g, b), ctx.settings().intent) + } else { + crate::screen_color::sampled(&ctx, srgb) + }; + cms::with_active(ctx, || c.to_cmyk_managed(cms::active().settings().intent)) + }; + let nums = |s: &str| s.split(',').skip(1).map(|v| v.parse::<f64>().unwrap()).collect::<Vec<_>>(); + for native in [false, true] { + let own = inks(cms::for_document(Some(cms::WIDE_GAMUT_RGB), Some(cms::FOGRA51_CMYK)), native); + let shown = inks(cms::for_document(None, None), native); + assert_ne!(own, shown, "the two profiles separate green differently"); + let [c, m, y, k] = own; + let want = format!("CMYKColor,{},{},{},{}", c * 100.0, m * 100.0, y * 100.0, k * 100.0); + let mut app = app(); + start( + &mut app, + &format!( + "app.documents.add(DocumentColorSpace.CMYK, 50, 60, 1); vc.run('edit.assignProfile', {{rgb: '{}', cmyk: '{}'}}); \ + var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); \ + vc.log([p.typename, p.cyan, p.magenta, p.yellow, p.black].join());", + cms::WIDE_GAMUT_RGB, + cms::FOGRA51_CMYK + ), + ); + assert!(until_picker(&mut app)); + if native { + let id = color_picker::script_picker(&app).unwrap(); + let green = PickedColor::in_model(Srgba::rgb(srgb[0], srgb[1], srgb[2]), ModelValues::new("rgb", &[128.0, 160.0, 96.0])); + script_run::with_host(&app, |host, _| host.get_mut_by_id::<ColorPickerDialog>(id).map(|d| d.set_color(green))).unwrap(); + } else { + set(&app, color_picker::SCRIPT_KEY, "color", json!("#80a060")).unwrap(); + } + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + let got = log(&app)[0].as_str().unwrap().to_string(); + assert_eq!(got.split(',').next(), Some("CMYKColor")); + for (g, w) in nums(&got).iter().zip(nums(&want)) { + assert!((g - w).abs() < 0.01, "typed RGB {native}: picked {got}, the script's document separates green as {want}"); + } + } +} + /// Only the person at the keyboard turns off the external script warning: Yes from automation, set /// as the answer or given in a pass automation drives, is refused, the warning stays on and the /// question opens again; No is taken from automation. diff --git a/docs/mcp.md b/docs/mcp.md index 183f042d80..6f51e40677 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4529,7 +4529,8 @@ https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a `RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in the app, when the run's active document (a document the script made included) is in CMYK, an RGB pick is returned as CMYK, so -the color's `typename` can differ from the picker's model and from the color given. An answer taken from `answers` +the color's `typename` can differ from the picker's model and from the color given. The pick is converted through the +RGB and CMYK profiles assigned to the run's active document, not those of the document the window shows. An answer taken from `answers` keeps the color model it was given. The picker opens on the color as given, whatever Only Web Colors was left at in another picker. OK with both the color and its model unchanged, and Cancel, return a new object of the color the script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bfccfd4a5a..296e084f9f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1138,7 +1138,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel, and OK with both the color and its model unchanged, return a new object based on the color given, in its own model. Stopping the run closes the picker and ends a screen color sample the picker started. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, converted through the profiles assigned to that document, while Cancel, and OK with both the color and its model unchanged, return a new object based on the color given, in its own model. Stopping the run closes the picker and ends a screen color sample the picker started. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`. From 9a06335957672158f46e871e5f2f92544fd1ff54 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 18:41:21 -0800 Subject: [PATCH 41/56] DXF Import: a failed tool edit stops the synchronous Place Where files are placed on the UI thread, OK finished the pending tool edit before preparing the place and went on when that edit failed, so Place could use the selection the failed edit left. It now stops with the edit's error, as file.place run as a command does. --- crates/ui-egui/src/place.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index cec2a8b352..2317750d81 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -349,9 +349,14 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Valu _ => match crate::placing::given_bytes(app, &p) { // A drawing placed through its import options places the bytes the dialog showed. Some(bytes) => { - // The edit the tool computes on another thread comes first, as for `placing::start`. + // The edit the tool computes on another thread comes first; when it fails, nothing + // is placed, as `file.place` run as a command does. let r = app.session.finish_tool_edit(); + let failed = r.as_ref().err().map(ToString::to_string); crate::canvas::apply_requests(app, r); + if let Some(e) = failed { + return Err(e); + } let job = app.session.prepare_place(&p).and_then(|job| job.with_bytes(bytes).read()); let r = job.and_then(|read| app.session.place_read(read)).map_err(|e| e.to_string()); app.sync_views(); From 7753e19da0ccb0ae8184e433276a86816c4c7ae0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 18:43:16 -0800 Subject: [PATCH 42/56] Save: open the second save panel in the folder of the first answer When the save panel opens again for a name the Flatpak file chooser did not grant, it starts in the folder of the path it answered, not in the document's own folder, so confirming the suggested name saves where the person first chose. --- crates/ui-egui/src/io/save.rs | 22 ++++++++++------------ crates/ui-egui/src/tests/saveext.rs | 7 +++++++ 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 2d2e73354e..1bf2183d28 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -237,16 +237,17 @@ fn write_step(app: &mut VectorcraftApp, uid: u64, path: &str, target: SaveTarget app.saves.release(uid); if portal_renamed(&answered, &path) { let name = confirm_portal_name(app, &answered, &path); - return ask_again(app, mode, ¶ms, ask, target, retrying, name); + let folder = Path::new(&answered).parent().map(Path::to_path_buf); + return ask_again(app, mode, ¶ms, ask, target, retrying, (name, folder)); } replaces_unasked(app, &answered, &path, move |app, path| finish_picked(app, mode, ¶ms, ask, &path, retrying)) } #[cfg(not(target_arch = "wasm32"))] -/// The save panel again for the active document's save (`mode`, `params`), suggesting `name` in the -/// format its extension names, as a new flow with the same options question (`ask_options`) and -/// `target`. A read-only retry (`retrying`) that changes format drops the options it carries and -/// asks for the new format's, as [`finish_picked`] does. +/// The save panel again for the active document's save (`mode`, `params`), in the folder the last +/// answer was in and suggesting `name` in the format its extension names, as a new flow with the +/// same options question (`ask_options`) and `target`. A read-only retry (`retrying`) that changes +/// format drops the options it carries and asks for the new format's, as [`finish_picked`] does. fn ask_again( app: &mut VectorcraftApp, mode: SaveMode, @@ -254,7 +255,7 @@ fn ask_again( mut ask_options: bool, target: SaveTarget, retrying: bool, - name: String, + (name, directory): (String, Option<PathBuf>), ) -> Result<Value, String> { let original = plan(app, mode, &acknowledged(params))?.format.id; let mut q = if params.is_object() { params.clone() } else { json!({}) }; @@ -268,11 +269,6 @@ fn ask_again( q["format"] = json!(f.id); } let first = plan(app, mode, &acknowledged(&q))?; - let directory = if mode == SaveMode::Template { - fileio::templates_dialog_folder(&app.session.prefs).map(PathBuf::from) - } else { - first.folder.clone().map(PathBuf::from) - }; start_flow(app, &first, Start { mode, params: &q, ask_options, target, retry: None, name, directory, retrying }) } @@ -495,7 +491,7 @@ fn ask_path( } let mut request = PickRequest::save("export").file_name(name); request.filters = filters.clone(); - if let Some(folder) = folder.clone() { + if let Some(folder) = folder { request = request.directory(folder); } Ok(file_asks::ask(app, request, Owner::Document, move |app, picked| { @@ -504,6 +500,8 @@ fn ask_path( let path = with_written_extension(&picked, &ext, &keeps); if portal_renamed(&picked, &path) { let name = confirm_portal_name(app, &picked, &path); + // The panel opens again in the folder of its last answer. + let folder = std::path::Path::new(&picked).parent().map(|p| p.to_string_lossy().into_owned()); return ask_path(app, None, name, folder, filters, ext, keeps, then); } replaces_unasked(app, &picked, &path, then) diff --git a/crates/ui-egui/src/tests/saveext.rs b/crates/ui-egui/src/tests/saveext.rs index a34a3c55eb..807cbdfe48 100644 --- a/crates/ui-egui/src/tests/saveext.rs +++ b/crates/ui-egui/src/tests/saveext.rs @@ -558,6 +558,11 @@ fn suggested_name(picker: &Picker) -> Option<String> { picker.requests().last()?.file_name.clone() } +/// The folder the last save panel opened in. +fn panel_folder(picker: &Picker) -> Option<PathBuf> { + picker.requests().last()?.directory.clone() +} + /// In a Flatpak sandbox the save panel answers with a path in the document portal, which puts only /// that name into the folder picked. A name the export has to change (`poster` for a PDF) is not /// written: the save panel opens again suggesting `poster.pdf`, and its answer is written. A @@ -570,6 +575,7 @@ fn an_export_asks_again_for_a_name_the_document_portal_did_not_grant() { assert!(w.borrow().is_empty(), "nothing is written under a name the portal did not grant: {:?}", w.borrow()); assert_eq!(picker.requests().len(), 2, "the save panel opens again"); assert_eq!(suggested_name(&picker).as_deref(), Some("poster.pdf")); + assert_eq!(panel_folder(&picker).as_deref(), Some(Path::new(portal)), "the folder of the last answer"); assert!(app.ui.status.contains("poster.pdf"), "{}", app.ui.status); picker.answer_saved(&format!("{portal}/poster.pdf"), None); poll(&mut app); @@ -597,6 +603,7 @@ fn save_as_asks_again_for_a_name_the_document_portal_did_not_grant() { assert!(dialog_path(&app).is_none(), "no PDF options before the name is granted"); assert_eq!(picker.requests().len(), 2, "the save panel opens again"); assert_eq!(suggested_name(&picker).as_deref(), Some("Untitled-1.pdf")); + assert_eq!(panel_folder(&picker).as_deref(), Some(Path::new(portal)), "the folder of the last answer"); assert_eq!(type_index(&picker, "pdf"), Some(0), "PDF is the first file type offered"); picker.answer_saved(&format!("{portal}/Untitled-1.pdf"), Some(0)); poll(&mut app); From eb1e5b6b141e73c02c4ca20bda05beeb1129d2a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 19:04:33 -0800 Subject: [PATCH 43/56] 3D: Raster Settings OK refuses after a canceled edit or during a tool edit A canceled undo group, or a canceled undo scope that put back an earlier snapshot, now advances the document's history restore count, as Undo and Redo do. The same steps can make an equal object with the same id again after such a cancel, so Raster Settings, Placement Options and Create Object Mosaic ask to be reopened. A scope canceled without an edit puts back the same snapshot and does not count. Raster Settings OK also refuses while a tool edit computed on another thread is pending, since running the command would apply that edit first, after the targets were checked. When the objects the dialog opened on render again, OK clears their earlier fallback warning from the status bar while it still shows it, unless a selected object still gives that warning; the selection's first other warning takes its place. --- crates/engine/src/doc_state.rs | 2 +- crates/engine/src/session/undo.rs | 4 + crates/engine/src/tests/history_mem.rs | 26 ++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/object_mosaic.rs | 2 +- .../ui-egui/src/dialogs/placement_options.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/tests_three_d.rs | 124 ++++++++++++++++++ crates/ui-egui/src/panels/three_d.rs | 27 ++-- crates/ui-egui/src/panels/three_d/raster.rs | 36 ++++- docs/mcp.md | 6 +- docs/three-d.md | 4 +- 12 files changed, 212 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 501cb6cd53..51ac31def1 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -118,7 +118,7 @@ pub struct DocState { /// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not /// change it, and a batch that fails puts it back with the document. pub reverts: u64, - /// Advances when Undo or Redo restores an older document snapshot. The same node ID can name different objects + /// Advances when Undo, Redo or a canceled undo group restores an older document snapshot. The same node ID can name different objects /// across that boundary. pub history_restores: u64, /// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared, diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index bf7b0bf6f7..910fbda9f9 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -123,6 +123,7 @@ impl Session { st.sync_new_art(); cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); + st.history_restores += 1; st.revision += 1; // The journal drops only the canceled groups' own entries and keeps the ones made in other documents meanwhile. journal.extend(g.journal); @@ -280,6 +281,9 @@ impl Session { st.drop_stale_variables_highlight(); deselect_hidden(&menu, &st.doc, &mut st.selection); st.history.recost_last(&st.doc); + if !Arc::ptr_eq(&undone, &st.doc) { + st.history_restores += 1; + } st.revision += 1; if colors_changed { self.paint = scope.paint; diff --git a/crates/engine/src/tests/history_mem.rs b/crates/engine/src/tests/history_mem.rs index 56580097f2..dcc6eee159 100644 --- a/crates/engine/src/tests/history_mem.rs +++ b/crates/engine/src/tests/history_mem.rs @@ -175,6 +175,32 @@ fn an_undo_group_lets_no_other_documents_steps_go_until_it_ends() { assert!(history_bytes(&s) <= s.history_budget); } +/// A canceled undo group, and a canceled undo scope that joined one, put back an older snapshot: +/// both advance the document's history restores, as Undo does, and a kept one does not. +#[test] +fn canceled_undo_groups_and_scopes_count_as_history_restores() { + let mut s = session_with_rects(2); + let restores = |s: &Session| s.docs[0].history_restores; + s.begin_undo_group(); + moves(&mut s, 2); + s.end_undo_group(false); + assert_eq!(restores(&s), 0, "a kept group restores nothing"); + s.begin_undo_group(); + moves(&mut s, 2); + s.end_undo_group(true); + assert_eq!(restores(&s), 1, "a canceled group"); + s.begin_undo_group(); + moves(&mut s, 1); + let scope = s.begin_undo_scope().unwrap(); + moves(&mut s, 2); + s.end_undo_scope(scope, true); + assert_eq!(restores(&s), 2, "a canceled scope that joined the open group"); + let scope = s.begin_undo_scope().unwrap(); + s.end_undo_scope(scope, true); + assert_eq!(restores(&s), 2, "a canceled scope that made no edit puts back the same snapshot"); + s.end_undo_group(false); +} + #[test] fn steps_kept_outside_a_command_keep_to_the_shared_budget() { let mut s = session_with_rects(50); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 62d9ac97f8..f613f78c8e 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1780,7 +1780,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.placementOptionsDialog", "Placement Options…", "", - "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo or Redo there (reopen the dialog)", + "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo, a Redo or a canceled edit that put back an earlier state there (reopen the dialog)", ), ( "ui.relinkDialog", diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index 9bb66b6696..96c0b40fa6 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -148,7 +148,7 @@ impl MosaicSource { return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } if st.history_restores != self.history_restores { - return Err(tl!("Reopen Create Object Mosaic after Undo or Redo.").to_owned()); + return Err(tl!("Reopen Create Object Mosaic after Undo, Redo or a canceled edit.").to_owned()); } match selected_image(app) { Some((source, size)) if source == self => Ok(size), diff --git a/crates/ui-egui/src/dialogs/placement_options.rs b/crates/ui-egui/src/dialogs/placement_options.rs index 3dc00a9bfb..a88334b508 100644 --- a/crates/ui-egui/src/dialogs/placement_options.rs +++ b/crates/ui-egui/src/dialogs/placement_options.rs @@ -75,7 +75,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } if Some(active.history_restores) != opening["historyRestores"].as_u64() { - return Err(tl!("Reopen Placement Options after Undo or Redo.").to_owned()); + return Err(tl!("Reopen Placement Options after Undo, Redo or a canceled edit.").to_owned()); } let align = f.int("align").and_then(|i| usize::try_from(i).ok()).and_then(|i| ALIGN.get(i).copied()).unwrap_or(ALIGN[CENTRE]); let params = json!({ "ids": opening["ids"], "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) }); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ebdb694870..41e06d0893 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1781,7 +1781,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.placementOptionsDialog", "Placement Options…", "", - "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo or Redo there (reopen the dialog)", + "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo, a Redo or a canceled edit that put back an earlier state there (reopen the dialog)", ), ( "ui.relinkDialog", diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 9847028ef1..dbb058c0c7 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -1789,6 +1789,130 @@ fn raster_settings_rendered_warning_reaches_the_status_bar() { panel.frame(); assert_eq!(render_of(&panel.app(), id)["resolution"].as_f64(), Some(2400.0)); assert_eq!(panel.app().ui.status, vectorcraft_effects::rendered::TOO_LARGE); + panel.click("Render Settings"); + panel.click("Raster Settings…"); + panel.frame(); + panel.app().dialogs().unwrap().with(|host| host.set_json_field(&ctx, dialog, "resolution", json!(1))).unwrap(); + panel.app().dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog)); + panel.frame(); + panel.frame(); + assert_eq!(render_of(&panel.app(), id)["resolution"].as_f64(), Some(1.0)); + assert_eq!(panel.app().ui.status, "", "a resolution that renders again clears the warning"); +} + +/// Raster Settings OK keeps a rendered warning that a selected object outside the dialog still +/// gives after the objects the dialog opened on render again. +#[test] +fn raster_settings_keeps_the_warning_of_another_selected_object() { + use craft::ui::dialog::dialog_id; + + use crate::tests::panel_harness::Panel; + + let mut app = app(); + let render = json!({"render": {"mode": "rendered", "quality": "low", "resolution": 2400}}); + let mut big = || { + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 3000, "height": 3000})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": render})).unwrap(); + id + }; + let (p, q) = (big(), big()); + // An object with a gradient fill, selected first, gives another warning. + let o = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]}); + app.run("paint.setFill", json!({"gradient": gradient})).unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"render": {"mode": "rendered", "quality": "low"}}})).unwrap(); + app.run("select.set", json!({"ids": [o]})).unwrap(); + assert_eq!(super::rendered_warning_of(&app, &[o]).as_deref(), Some(vectorcraft_effects::rendered::OPAQUE_ONLY)); + app.run("select.set", json!({"ids": [q]})).unwrap(); + app.ui.status = vectorcraft_effects::rendered::TOO_LARGE.to_owned(); + let mut panel = Panel::new(app, show_with_dialogs); + panel.frame(); + panel.click("Render Settings"); + panel.click("Raster Settings…"); + panel.frame(); + let (dialog, ctx) = (dialog_id(super::raster::KIND), panel.ctx().clone()); + panel.app().run("select.set", json!({"ids": [o, p, q]})).unwrap(); + panel.app().dialogs().unwrap().with(|host| host.set_json_field(&ctx, dialog, "resolution", json!(1))).unwrap(); + panel.app().dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog)); + panel.frame(); + panel.frame(); + assert_eq!(render_of(&panel.app(), q)["resolution"].as_f64(), Some(1.0)); + assert_eq!(render_of(&panel.app(), p)["resolution"].as_f64(), Some(2400.0)); + assert_eq!(panel.app().ui.status, vectorcraft_effects::rendered::TOO_LARGE, "the other selected object still falls back"); +} + +/// After an undo group that created the object Raster Settings opened on is canceled, OK keeps the +/// dialog open even when the same steps make an equal object with the same id again. +#[test] +fn raster_settings_ok_is_refused_after_a_canceled_undo_group() { + use crate::tests::panel_harness::Panel; + + let (mut app, a, _) = two_renders(); + let make = |app: &mut VectorcraftApp| { + let c = app.run("shape.rectangle", json!({"x": 500, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + let render = json!({"mode": "rendered", "resolution": 150}); + app.run("effect.setParams", json!({"index": 0, "item": null, "params": {"render": render}})).unwrap(); + c + }; + app.session.begin_undo_group(); + let c = make(&mut app); + let mut panel = Panel::new(app, show_with_dialogs); + panel.frame(); + panel.click("Render Settings"); + panel.click("Raster Settings…"); + panel.frame(); + panel.app().session.end_undo_group(true); + assert!(panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(c)).is_none()); + assert_eq!(make(&mut panel.app()), c, "the same steps make an object with the same id"); + assert_refused(&mut panel, a, c); +} + +/// While a Shape Builder merge is computed on another thread, Raster Settings OK keeps the dialog +/// open and the merge pending, and leaves the render settings as they are. +#[test] +fn raster_settings_ok_is_refused_while_a_tool_edit_is_pending() { + use craft::ui::dialog::{HeldOk, dialog_id}; + use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + + use crate::tests::panel_harness::Panel; + + let (mut app, a, b) = two_renders(); + let rects: Vec<u64> = (0..40) + .map(|k| app.run("shape.rectangle", json!({"x": 1000 + k * 10, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()) + .collect(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + let mut panel = Panel::new(app, show_with_dialogs); + panel.frame(); + panel.click("Render Settings"); + panel.click("Raster Settings…"); + panel.frame(); + { + let mut app = panel.app(); + app.run("select.set", json!({"ids": rects})).unwrap(); + app.run("tool.select", json!({"tool": "shapeBuilder"})).unwrap(); + let view = app.view_info(); + let at = |kind| PointerEvent { + kind, + pos: vectorcraft_geom::Point::new(1015.0, 10.0), + mods: Mods::default(), + pressure: 1.0, + backquote: false, + pen: None, + }; + crate::canvas::dispatch(&mut app, &at(PointerKind::Move), view); + app.session.tool_poll(view, true).unwrap(); + crate::canvas::dispatch(&mut app, &at(PointerKind::Down), view); + crate::canvas::dispatch(&mut app, &at(PointerKind::Up), view); + assert!(app.session.tool_editing(), "the merge is being computed"); + } + let history = undo_len(&panel.app()); + assert_refused(&mut panel, a, b); + let dialog = dialog_id(super::raster::KIND); + let refused = panel.app().dialogs().unwrap().with(|h| h.held_state(dialog)); + assert!(matches!(refused, Some(HeldOk::Refused(reason)) if format!("{reason:?}").contains("Finish the active edit first."))); + assert!(panel.app().session.tool_editing(), "the merge stays pending"); + assert_eq!(undo_len(&panel.app()), history); } /// Raster Settings OK sets the objects the dialog opened on: an object selected after it opened diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index bdbc686055..51a26d533c 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -636,19 +636,28 @@ pub(crate) fn show_rendered_warning(app: &mut VectorcraftApp) { /// Shows the first rendered fallback warning for the objects `ids` whose effects take render settings. pub(crate) fn show_rendered_warning_of(app: &mut VectorcraftApp, ids: &[u64]) { - if let Some(st) = app.session.active() - && let Some(message) = ids - .iter() - .filter_map(|id| st.doc.node(NodeId(*id))) - .filter(|n| { - find(n).is_some_and(|t| vectorcraft_effects::default_params(&t.effect).is_some_and(|p| p.get(vectorcraft_effects::RENDER).is_some())) - }) - .find_map(|n| vectorcraft_effects::rendered_warning(&st.doc, n)) - { + if let Some(message) = rendered_warning_of(app, ids) { app.ui.status = message; } } +/// The first rendered fallback warning for the objects `ids` whose effects take render settings. +pub(crate) fn rendered_warning_of(app: &VectorcraftApp, ids: &[u64]) -> Option<String> { + rendered_warnings(app, ids).next() +} + +/// The rendered fallback warnings for the objects `ids` whose effects take render settings, in +/// their order, each checked only when it is asked for. +pub(crate) fn rendered_warnings<'a>(app: &'a VectorcraftApp, ids: &'a [u64]) -> impl Iterator<Item = String> + 'a { + let st = app.session.active(); + ids.iter() + .filter_map(move |id| Some((st?, st?.doc.node(NodeId(*id))?))) + .filter(|(_, n)| { + find(n).is_some_and(|t| vectorcraft_effects::default_params(&t.effect).is_some_and(|p| p.get(vectorcraft_effects::RENDER).is_some())) + }) + .filter_map(|(st, n)| vectorcraft_effects::rendered_warning(&st.doc, n)) +} + /// Runs what a click in the Materials page's Graphics asked for: maps the graphic onto the selected /// objects, its row then selected, or keeps art as a new graphic. An error goes to the status bar. fn run_action(app: &mut VectorcraftApp, action: materials::Action) { diff --git a/crates/ui-egui/src/panels/three_d/raster.rs b/crates/ui-egui/src/panels/three_d/raster.rs index fb0d253b0b..1e0ef2e86c 100644 --- a/crates/ui-egui/src/panels/three_d/raster.rs +++ b/crates/ui-egui/src/panels/three_d/raster.rs @@ -6,14 +6,14 @@ //! blank, and OK leaves it as each object has it. OK runs one `effect.setParams` over the objects //! selected when the dialog opened, one undo step, which records none when every object already //! holds what it sets. While another document is the active one, or after the document was -//! reverted or had an Undo or Redo, OK keeps the dialog open with the reason. +//! reverted or had an Undo, Redo or canceled edit, OK keeps the dialog open with the reason. use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use serde_json::{Map, Value, json}; use vectorcraft_doc::Node; -use super::{find, selected_renders, send_to, shared_render, show_rendered_warning_of, takes_render}; +use super::{find, rendered_warning_of, rendered_warnings, selected_renders, send_to, shared_render, takes_render}; use crate::VectorcraftApp; use crate::dialogs::host::open_held; @@ -101,7 +101,7 @@ struct Opened { document: Option<bool>, resolution: Option<f64>, background: Option<String>, - /// The document the dialog opened on: its uid, and its revert and Undo or Redo counts then. + /// The document the dialog opened on: its uid, and its revert count and history restore count (Undo, Redo or a canceled edit) then. doc: Option<(u64, u64, u64)>, /// The selected objects whose render settings the dialog opened on, as they were then: OK sets /// these. @@ -140,7 +140,7 @@ fn edited(f: &DialogFields, opened: &Opened) -> Result<Map<String, Value>, Strin /// OK: sets the edited render settings on the 3D effect of every object the dialog opened on, one /// undo step. While another document is the active one, after that document was reverted or had an -/// Undo or Redo, once one of those objects was changed, deleted, locked or hidden, or while another +/// Undo, Redo or canceled edit, once one of those objects was changed, deleted, locked or hidden, or while another /// edit is in progress, OK keeps the dialog open with the reason. fn ok(app: &mut VectorcraftApp, answer: &ParamResult, opened: &Opened) -> Result<(), String> { let render = edited(&answer.fields, opened)?; @@ -157,7 +157,7 @@ fn ok(app: &mut VectorcraftApp, answer: &ParamResult, opened: &Opened) -> Result return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } if st.history_restores != restores { - return Err(tl!("Reopen Raster Settings after Undo or Redo.").to_owned()); + return Err(tl!("Reopen Raster Settings after Undo, Redo or a canceled edit.").to_owned()); } let stale = { let editable = st.doc.editable(); @@ -166,11 +166,35 @@ fn ok(app: &mut VectorcraftApp, answer: &ParamResult, opened: &Opened) -> Result if stale { return Err(tl!("The objects were changed, deleted or locked. Reopen Raster Settings to continue.").to_owned()); } + // A pending tool edit would be applied before the change, after these checks. + if app.session.tool_editing() { + return Err(tl!("Finish the active edit first.").to_owned()); + } let ids: Vec<u64> = opened.targets.iter().map(|t| t.id.0).collect(); + let status = app.ui.status.clone(); + let shown = (!status.is_empty() && rendered_warnings(app, &ids).any(|w| w == status)).then_some(status); let mut changed = Map::new(); changed.insert(vectorcraft_effects::RENDER.into(), Value::Object(render)); send_to(app, changed, &ids)?; - show_rendered_warning_of(app, &ids); + match rendered_warning_of(app, &ids) { + Some(message) => app.ui.status = message, + // The objects' earlier warning goes once they render, while the status line still shows it: + // a selected object that still gives it keeps it, and otherwise the selection's first + // warning, if any, takes its place. + None if shown.is_some_and(|w| w == app.ui.status) => { + let selection: Vec<u64> = app.session.active().map(|st| st.selection.objects.iter().map(|id| id.0).collect()).unwrap_or_default(); + let mut first = None; + let kept = rendered_warnings(app, &selection).any(|w| { + let same = w == app.ui.status; + first.get_or_insert(w); + same + }); + if !kept { + app.ui.status = first.unwrap_or_default(); + } + } + None => {} + } Ok(()) } diff --git a/docs/mcp.md b/docs/mcp.md index fcf4545d49..71cc234dab 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7389,8 +7389,8 @@ limits, so art too complex for the shaded surface does not refuse the wireframe. The 3D and Materials panel's Render Settings › Raster Settings dialog sets resolution and background on the objects selected when the dialog opened. OK applies the changes in one undo step and records nothing when nothing changes. -OK keeps the dialog open with the reason while its document is not active, after it was reverted or had an Undo -or Redo, if one of those objects was changed, deleted, locked or hidden, or while another edit is in progress. +OK keeps the dialog open with the reason while its document is not active, after it was reverted or had an Undo, +a Redo or a canceled edit that put back an earlier state, if one of those objects was changed, deleted, locked or hidden, or while another edit is in progress. ## 3D material @@ -12775,7 +12775,7 @@ downloads each image instead and links none). clip?}` decides how a relinked or updated file takes an image's place (default `bounds`: stretched into the old bounds; `clip` puts it in a clip group of the old bounds when it is larger). MCP clients must reopen the Placement Options dialog (`ui.placementOptionsDialog`) before confirming again after -Undo, Redo, or a revert in the document where it opened. +Undo, Redo, a canceled edit that put back an earlier state, or a revert in the document where it opened. The UI commands `links.editOriginal` and `links.reveal` open the linked file in its app or show it in its folder (desktop). Edit Original runs only from the app's window, except for a placed document, which opens in a tab. With the preference `editOriginalSystemDefaults` (Preferences › diff --git a/docs/three-d.md b/docs/three-d.md index dff2eaacb2..49b8c45a46 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -69,8 +69,8 @@ pages describe it. values), at the effect's `resolution` or, without one, at Document Raster Effects Settings › Resolution. **Render Settings › Raster Settings…** sets Use Document Raster Effects Resolution, Resolution (1 to 2400 ppi) and Background (Transparent or White). OK sets the objects selected when the dialog opened in one undo step. - OK keeps the dialog open with the reason while its document is not active, after it was reverted or had an Undo - or Redo, if one of those objects was changed, deleted, locked or hidden, or while another edit is in progress. + OK keeps the dialog open with the reason while its document is not active, after it was reverted or had an Undo, + a Redo or a canceled edit that put back an earlier state, if one of those objects was changed, deleted, locked or hidden, or while another edit is in progress. The Render 3D vector artwork page describes Raster Settings changing the resolution and background. A setting the selected objects hold differently opens blank and is left as each object has it; Rendered and the qualities show unchecked for such a selection. From 51522b906920112fd5bfe91204f4f01fa29cd58b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 19:09:38 -0800 Subject: [PATCH 44/56] DXF import: a region whose binary data is shorter than its declared size is left out The ACDSDATA reader kept a buffer with fewer bytes than group 94 declares, and a buffer cut at a record boundary read as a partial outline. Such a region is now left out and listed. A 310 chunk with an odd number of digits or a character that is not a hex digit also leaves the region out. --- crates/cad/src/import/reader.rs | 32 ++++++++++++++++++--------- crates/cad/src/import/tests_region.rs | 12 ++++++++++ 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/crates/cad/src/import/reader.rs b/crates/cad/src/import/reader.rs index f635e3cf8c..167c07cc70 100644 --- a/crates/cad/src/import/reader.rs +++ b/crates/cad/src/import/reader.rs @@ -172,14 +172,21 @@ fn region_data(doc: &model::Document<'_>) -> HashMap<u64, Vec<u8>> { let data = r.tags.get(at + 1..).unwrap_or_default(); let size = data.iter().find(|t| t.code == 94).and_then(|t| usize::try_from(t.i64()).ok()); let mut bytes = Vec::new(); + let mut whole = true; for t in data.iter().filter(|t| t.code == 310) { - hex_bytes(t.str_ref().unwrap_or_default(), &mut bytes); - if bytes.len() > super::acis::MAX_BYTES { + whole = hex_bytes(t.str_ref().unwrap_or_default().trim(), &mut bytes); + if !whole || bytes.len() > super::acis::MAX_BYTES { break; } } - if let Some(n) = size.filter(|n| *n <= bytes.len()) { - bytes.truncate(n); + if !whole { + continue; + } + // Fewer bytes than the record declares means the data was cut short or damaged. + match size { + Some(n) if n <= bytes.len() => bytes.truncate(n), + Some(_) => continue, + None => {} } out.insert(handle, bytes); } @@ -187,14 +194,19 @@ fn region_data(doc: &model::Document<'_>) -> HashMap<u64, Vec<u8>> { out } -/// Hex digits' bytes, two digits each, onto `out`. -fn hex_bytes(hex: &str, out: &mut Vec<u8>) { +/// Hex digits' bytes, two digits each, onto `out`. False when `hex` has a character that is not +/// a hex digit or an odd number of digits. +pub(super) fn hex_bytes(hex: &str, out: &mut Vec<u8>) -> bool { let digit = |c: u8| (c as char).to_digit(16).and_then(|d| u8::try_from(d).ok()); - for pair in hex.as_bytes().as_chunks::<2>().0 { - if let (Some(hi), Some(lo)) = (digit(pair[0]), digit(pair[1])) { - out.push(hi << 4 | lo); - } + let (pairs, rest) = hex.as_bytes().as_chunks::<2>(); + if !rest.is_empty() { + return false; } + for pair in pairs { + let (Some(hi), Some(lo)) = (digit(pair[0]), digit(pair[1])) else { return false }; + out.push(hi << 4 | lo); + } + true } pub(crate) fn point(p: model::Point) -> Point { diff --git a/crates/cad/src/import/tests_region.rs b/crates/cad/src/import/tests_region.rs index 18167d1fe9..b6b538887c 100644 --- a/crates/cad/src/import/tests_region.rs +++ b/crates/cad/src/import/tests_region.rs @@ -322,6 +322,18 @@ fn binary_data_in_the_acdsdata_section_reads_alike() { // Without its data the region is left out and listed. let r = import(&drawing("AC1027", &e, &[]), &points()).unwrap(); assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings); + // Data shorter than its declared size is left out and listed too. + let mut short = acds(&bytes); + short[7].1 = (bytes.len() + 1).to_string(); + let r = import(&drawing("AC1032", &e, &short), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings); + // A chunk with an odd number of digits or a character that is not a hex digit fails to read. + let mut out = Vec::new(); + assert!(super::reader::hex_bytes("0aFf", &mut out)); + assert_eq!(out, [0x0A, 0xFF]); + for hex in ["0aF", "0aZZ", "0 aF"] { + assert!(!super::reader::hex_bytes(hex, &mut Vec::new()), "{hex}"); + } } /// A drawing the export writes (R2000, millimetres) with a region added to its entities. From e76423a1e24eab5f60478515b5869fd287869967 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 19:10:05 -0800 Subject: [PATCH 45/56] Tests: check each Targa color channel on its own test-lint rejects assert!(...all(...)) without a length check, which failed the gate. The test now compares the three channels one at a time with the same tolerance. --- crates/render/src/encode/tests_tga.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/render/src/encode/tests_tga.rs b/crates/render/src/encode/tests_tga.rs index 823d53cd82..21281286b5 100644 --- a/crates/render/src/encode/tests_tga.rs +++ b/crates/render/src/encode/tests_tga.rs @@ -18,7 +18,9 @@ fn targa_depths_alpha_and_footer() { assert_eq!(img.dimensions(), (w, h)); let want = on_white(px[(2 * w as usize + 3) * 4..][..4].try_into().unwrap()); let got = img.get_pixel(3, 2).0; - assert!(got[..3].iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 8), "depth {depth}: {got:?} vs {want:?}"); + for c in 0..3 { + assert!(got[c].abs_diff(want[c]) <= 8, "depth {depth}, channel {c}: {got:?} vs {want:?}"); + } match depth { 32 => assert_eq!((img.get_pixel(0, 0).0[3], img.get_pixel(1, 0).0[3]), (0, 128), "8-bit alpha"), 24 => assert_eq!(img.get_pixel(0, 0).0, [255; 4], "flattened on white"), From d556e768f703ba987e66f6be3b3c28d4a0cebe15 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 19:31:49 -0800 Subject: [PATCH 46/56] Docs: name the source profile of each script color pick Typed RGB values convert from the RGB profile of the document the window shows (or the working RGB profile) to the script document's RGB profile, and separate through its CMYK profile only in a CMYK document. Hex, screen-sample, HSB and web-snapped picks start in display sRGB. --- docs/mcp.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 6f51e40677..981da2b14b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4529,8 +4529,11 @@ https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a `RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in the app, when the run's active document (a document the script made included) is in CMYK, an RGB pick is returned as CMYK, so -the color's `typename` can differ from the picker's model and from the color given. The pick is converted through the -RGB and CMYK profiles assigned to the run's active document, not those of the document the window shows. An answer taken from `answers` +the color's `typename` can differ from the picker's model and from the color given. RGB values typed into the +picker convert from the RGB profile of the document the window shows (the working RGB profile when it shows none) to the RGB profile of the run's active +document, and in a CMYK document they then separate through that document's CMYK profile. Hex, screen-sample and HSB +picks, and typed values that Only Web Colors snaps, start in display sRGB and convert only through the active +document's profiles. An answer taken from `answers` keeps the color model it was given. The picker opens on the color as given, whatever Only Web Colors was left at in another picker. OK with both the color and its model unchanged, and Cancel, return a new object of the color the script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting From 4e438a452596010c8755850f152070180c53d9c4 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 19:36:44 -0800 Subject: [PATCH 47/56] Properties: the reversal test follows the reversed anchor selection The corner radius test from #10864 expected Reverse Path Direction to leave the Direct-Selected anchor index unchanged, so that the same index named a different corner. Reverse Path Direction now moves the selection with its points, so the picked anchor is the same corner at its reversed index, with its sides swapped. The test now checks both cases for each of its six paths: the picked anchor follows its point and the unfinished radius is dropped, and picking the old index again after the reversal names a different corner and drops the radius. corner_radii reads every anchor, so an open path's end reads 0. --- crates/ui-egui/src/panels/properties/tests.rs | 57 ++++++++++++++----- 1 file changed, 42 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 3076231e18..f24696da3c 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1616,11 +1616,13 @@ fn two_corner_radii(panel: &Panel, a: u64, b: u64) -> (Vec<f64>, Vec<f64>) { (corner_radii(&app, a), corner_radii(&app, b)) } -/// The radius of each corner of live-cornered path `id`, in document lengths. +/// The radius at each anchor of live-cornered path `id`, by anchor index counted across subpaths, +/// in document lengths. An anchor that is not a corner, such as an open subpath's end, reads 0. fn corner_radii(app: &VectorcraftApp, id: u64) -> Vec<f64> { let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap(); - (0..lc.all().len()).map(|k| crate::panels::corner_length(&lc, k)).collect() + let anchors = lc.base.subpaths.iter().map(|sp| sp.anchors.len()).sum(); + (0..anchors).map(|k| if lc.corner(k).is_some() { crate::panels::corner_length(&lc, k) } else { 0.0 }).collect() } /// A corner radius typed and not yet entered is dropped when the selection moves to other corners @@ -1729,11 +1731,12 @@ fn rounding_a_direct_selected_corner_keeps_the_corner_fields_target() { assert_eq!(target(&app), before, "the same corner is the target"); } -/// Reversing a path drops an unfinished radius when the picked index names a different corner: -/// an expanded rectangle, a path whose first corner and last corner have sides of the same -/// lengths and turn the same way, a crossing path whose corners share a position, a path whose -/// reversed corner has sides in the same directions, a path with two corners at the same point -/// whose sides lean the same ways, and a small subpath beside a very large one. +/// Reversing a path drops an unfinished radius, both while the picked anchor follows its point to +/// its new index and when the old index is picked again and names a different corner: an expanded +/// rectangle, a path whose first corner and last corner have sides of the same lengths and turn +/// the same way, a crossing path whose corners share a position, a path whose reversed corner has +/// sides in the same directions, a path with two corners at the same point whose sides lean the +/// same ways, and a small subpath beside a very large one. #[test] fn an_unfinished_corner_radius_is_dropped_when_the_path_is_reversed() { let mut app = new_app(); @@ -1757,24 +1760,48 @@ fn an_unfinished_corner_radius_is_dropped_when_the_path_is_reversed() { ("coincident corners", coincident, 1), ("small subpath", small, 1), ] { - // Where the corner at `index` is and the directions its sides leave it in. - let corner = |app: &VectorcraftApp| { + // Where corner `k` is and the directions its sides leave it in. + let corner = |app: &VectorcraftApp, k: usize| { let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap(); - let c = *vectorcraft_doc::LiveCorners::of(node).unwrap().corner(index).unwrap(); + let c = *vectorcraft_doc::LiveCorners::of(node).unwrap().corner(k).unwrap(); (c.at, c.u, c.v) }; + // The anchors of the first subpath, where `index` is. + let first_subpath = |app: &VectorcraftApp| { + app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().path_data().unwrap().subpaths[0].anchors.len() + }; + + // The picked anchor follows its point to its new index, and the draft is dropped. panel.app().run("select.anchors", json!({"id": id, "anchors": [[0, index]], "mode": "set"})).unwrap(); panel.frame(); - let before = corner(&panel.app()); + let before = corner(&panel.app(), index); + let reversed = first_subpath(&panel.app()) - 1 - index; finish_after_change(&mut panel, case, "Corner Radius", "0 pt", |app| { app.run("path.reverse", json!({"ids": [id]})).unwrap(); }); - let app = panel.app(); - assert_ne!(corner(&app), before, "{case}: index {index} names a different corner"); + let mut app = panel.app(); let picked = picked_corner(&app); - assert_eq!(picked, index, "{case}: the picked corner index stays the same"); + assert_eq!(picked, reversed, "{case}: the picked anchor follows its point"); + assert_eq!(corner(&app, picked), (before.0, before.2, before.1), "{case}: the same corner, its sides swapped"); let radii = corner_radii(&app, id); - assert_eq!(radii[picked], 1.0, "{case}: the corner now picked takes 1 pt"); + assert_eq!(radii[picked], 1.0, "{case}: the picked corner takes 1 pt"); + assert!(radii.iter().all(|&radius| radius != 4.0), "{case}: no corner takes the unfinished 3+1 draft"); + app.run("edit.undo", json!({})).unwrap(); + drop(app); + + // Picking `index` again after the reversal names a different corner and drops the draft. + panel.app().run("select.anchors", json!({"id": id, "anchors": [[0, index]], "mode": "set"})).unwrap(); + panel.frame(); + let before = corner(&panel.app(), index); + finish_after_change(&mut panel, case, "Corner Radius", "0 pt", |app| { + app.run("path.reverse", json!({"ids": [id]})).unwrap(); + app.run("select.anchors", json!({"id": id, "anchors": [[0, index]], "mode": "set"})).unwrap(); + }); + let app = panel.app(); + assert_ne!(corner(&app, index), before, "{case}: index {index} names a different corner"); + assert_eq!(picked_corner(&app), index, "{case}: index {index} is picked"); + let radii = corner_radii(&app, id); + assert_eq!(radii[index], 1.0, "{case}: the corner now picked takes 1 pt"); assert!(radii.iter().all(|&radius| radius != 4.0), "{case}: no corner takes the unfinished 3+1 draft"); } } From 6ab79bce2e7677b187a190fd9a53dc1a792cc515 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 19:37:30 -0800 Subject: [PATCH 48/56] Docs: the JPEG filter lists only the lowercase .jpe Open and Place read .jpe files in any letter case, but the dialogs' JPEG filter adds only the lowercase extension, and GTK matches filter patterns case-sensitively. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 56b106564d..9960c7302b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2534,7 +2534,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - - JPEG files named `.jpe` open and place as JPEG files, in any letter case, as the [supported file formats](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html) page lists for Open and Place: the Open and Place dialogs list them with `.jpg` and `.jpeg`, and a dropped file is handled as a dropped `.jpg` file is: with a document open, a file dropped on the canvas, or dropped with no position, is placed in that document, and one dropped elsewhere on the window opens. Exports write only `.jpg` and `.jpeg` (`crates/engine/src/cmd/fileio/tests_jpeg.rs`). + - JPEG files named `.jpe` open and place as JPEG files, in any letter case, as the [supported file formats](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html) page lists for Open and Place: the JPEG filter of the Open and Place dialogs adds the lowercase `.jpe` to `.jpg` and `.jpeg`, and a dropped file is handled as a dropped `.jpg` file is: with a document open, a file dropped on the canvas, or dropped with no position, is placed in that document, and one dropped elsewhere on the window opens. Exports write only `.jpg` and `.jpeg` (`crates/engine/src/cmd/fileio/tests_jpeg.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers, nor a layer or group whose layer mask hides all of it) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings; a clip, or a merge for another layer, that one with a layer mask too large to read is part of goes on without it (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From f8cdebe86d7102aac82cd99705a3b4daf8cd2d25 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 20:25:49 -0800 Subject: [PATCH 49/56] Save: Export Text, Unembed and metadata templates ask again in the Flatpak file chooser In the Flatpak build the save panel answers with a path in the document portal, which puts only that exact name into the folder picked. Three more save panels changed the answer before writing, so the write succeeded inside the portal and no file appeared: - Keyboard Shortcuts > Export Text added or replaced the extension of the format picked (list became list.pdf). - Save Metadata Template added .xmp to a name typed without it. - Unembed added the stored image format's extension to a name typed without one (links.unembed does this in the engine). Each now opens the save panel again in the answer's folder, suggesting the completed name, and the status bar says why. Its answer is written. Paths outside the portal are unchanged. The check reuses the helper the main Save and Export flows use, now shared as io::save::portal_ask_again, and the engine exposes links::unembed_path so the panel knows the name Unembed writes. --- crates/engine/src/cmd/links.rs | 18 +++++++- crates/ui-egui/src/dialogs/file_info.rs | 50 +++++++++++++++++++-- crates/ui-egui/src/io/save.rs | 17 +++++-- crates/ui-egui/src/panels/links.rs | 17 ++++++- crates/ui-egui/src/panels/tests_links.rs | 27 ++++++++++++ crates/ui-egui/src/shortcut_editor.rs | 56 ++++++++++++++++-------- crates/ui-egui/src/tests/picks.rs | 31 +++++++++++++ 7 files changed, 189 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 3851aeefac..92171a0b71 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -3061,6 +3061,22 @@ fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::R if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) } } +/// `path` with `.ext` added when it has no extension: the file Unembed writes for a `path` given. +fn with_unembed_extension(path: &str, ext: &str) -> String { + if fileio::extension(path).is_empty() { format!("{path}.{ext}") } else { path.to_string() } +} + +/// The file `links.unembed {id, path}` writes embedded image `id` of the active document to: `path` +/// with the extension of the format the image is stored in added when `path` has none. `None` when +/// `id` is not an embedded image there. +pub fn unembed_path(s: &Session, id: u64, path: &str) -> Option<String> { + let st = s.doc().ok()?; + let doc = with_brush_art(&st.doc); + let im = image_of(&doc, NodeId(id)).filter(|im| im.link.is_none())?; + let blob = st.doc.images.get(&im.key)?; + Some(with_unembed_extension(path, stored_extension(blob))) +} + fn unembed(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "links.unembed"; let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); @@ -3097,7 +3113,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> { let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned()); return Ok(json!({ "name": format!("{stem}.{ext}"), "dataBase64": vectorcraft_format::base64_encode(&bytes) })); }; - let path = absolute_path(&if fileio::extension(path).is_empty() { format!("{path}.{ext}") } else { path.to_string() }); + let path = absolute_path(&with_unembed_extension(path, &ext)); // Read before writing: pixels that can't be read leave no file behind. let img = linked_image(&bytes, Some(&path))?; write_file(&path, &bytes)?; diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index 24fb32b996..493c5a1b34 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -556,10 +556,24 @@ fn list_templates(app: &mut VectorcraftApp) -> (Vec<(String, String)>, Option<St /// Save Metadata Template…: the fields as they are in the dialog, at the path a save pick answered. A name /// typed without `.xmp` takes it, so the templates list shows the file; a file already there under the -/// completed name is replaced only after a question. +/// completed name is replaced only after a question. In the document portal, which takes only the name +/// answered, the save pick opens again with the completed name in the answer's folder. fn save_template(app: &mut VectorcraftApp, picked: PathBuf, fields: Info) -> Result<(), String> { let picked = picked.to_string_lossy().into_owned(); let path = if picked.to_ascii_lowercase().ends_with(&format!(".{XMP_EXT}")) { picked.clone() } else { format!("{picked}.{XMP_EXT}") }; + if let Some((name, folder)) = crate::io::save::portal_ask_again(app, &picked, &path) { + let mut request = template_request(name); + if let Some(folder) = folder { + request = request.directory(folder); + } + file_asks::ask(app, request, file_asks::Owner::Free, move |app, picked| { + if let Some(path) = picked.first_path() { + save_template(app, path, fields)?; + } + Ok(Value::Null) + }); + return Ok(()); + } // The save pick does not ask about the completed name. app.session.execute("file.info.templates", &json!({ "create": true })).map_err(|e| e.to_string())?; let save = { @@ -573,6 +587,11 @@ fn save_template(app: &mut VectorcraftApp, picked: PathBuf, fields: Info) -> Res save(app).map(|_| ()) } +/// A save pick for a metadata template, suggesting `name`. +fn template_request(name: String) -> PickRequest { + PickRequest::save(PURPOSE).file_name(name).suggested_extension(XMP_EXT).filter(tl!("XMP metadata templates"), &[XMP_EXT]) +} + /// Save the draft through the browser's file service. Serializing it changes neither drawing nor draft. fn download_template(app: &mut VectorcraftApp, fields: Info) -> Result<(), String> { let title = text_of(&fields, "title"); @@ -580,8 +599,7 @@ fn download_template(app: &mut VectorcraftApp, fields: Info) -> Result<(), Strin let name = format!("{stem}.{XMP_EXT}"); let result = app.run("file.info.saveTemplate", json!({"fields": fields}))?; let data = result["data"].as_str().ok_or("the metadata template contains no data")?.as_bytes().to_vec(); - let request = PickRequest::save(PURPOSE).file_name(name).suggested_extension(XMP_EXT).filter(tl!("XMP metadata templates"), &[XMP_EXT]); - file_asks::save(app, request, data, file_asks::Owner::Free, |app, picked| { + file_asks::save(app, template_request(name), data, file_asks::Owner::Free, |app, picked| { match picked { Picked::Downloaded(name) => app.status(format!("Saved {name}")), Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())), @@ -884,6 +902,32 @@ mod tests { assert!(app.session.active().unwrap().history.undo.is_empty()); } + /// In the document portal, which takes only the name the save pick answered, Save Metadata + /// Template… writes nothing under the completed name (`Card` for `Card.xmp`): the save pick opens + /// again in the answer's folder suggesting `Card.xmp`, and its answer is written. + #[test] + fn a_template_save_asks_again_for_a_name_the_document_portal_did_not_grant() { + let dir = vectorcraft_testkit::TempDir::new("ui-file-info-portal"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let picker = crate::tests::picks::scripted(&mut app); + app.session.attach_metadata_templates_dir(dir.join("Metadata Templates")); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let portal = "/run/user/1000/doc/a1b2c3d4"; + let fields = json!({"author": "Ada"}).as_object().cloned().unwrap_or_default(); + super::save_template(&mut app, format!("{portal}/Card").into(), fields).unwrap(); + let requests = picker.requests(); + let [again] = requests.as_slice() else { panic!("the save pick opens again: {requests:?}") }; + assert_eq!(again.file_name.as_deref(), Some("Card.xmp")); + assert_eq!(again.directory.as_deref(), Some(std::path::Path::new(portal))); + assert!(app.ui.status.contains("Card.xmp"), "{}", app.ui.status); + let granted = dir.join("Card.xmp"); + picker.answer_saved(&granted.to_string_lossy(), None); + let ctx = app.ui_ctx.clone().unwrap_or_default(); + crate::tests::picks::poll(&mut app, &ctx); + assert!(std::fs::read_to_string(&granted).is_ok_and(|xmp| xmp.contains("Ada")), "the granted name is written"); + assert_eq!(picker.requests().len(), 1, "a granted name is written without asking again"); + } + #[test] fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() { let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template"); diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 1bf2183d28..fc42da3c77 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -498,10 +498,8 @@ fn ask_path( let Picked::Saved { path: picked, .. } = picked else { return Err("cancelled".into()) }; let picked = picked.to_string_lossy().into_owned(); let path = with_written_extension(&picked, &ext, &keeps); - if portal_renamed(&picked, &path) { - let name = confirm_portal_name(app, &picked, &path); - // The panel opens again in the folder of its last answer. - let folder = std::path::Path::new(&picked).parent().map(|p| p.to_string_lossy().into_owned()); + if let Some((name, folder)) = portal_ask_again(app, &picked, &path) { + let folder = folder.map(|p| p.to_string_lossy().into_owned()); return ask_path(app, None, name, folder, filters, ext, keeps, then); } replaces_unasked(app, &picked, &path, then) @@ -537,6 +535,17 @@ fn confirm_portal_name(app: &mut VectorcraftApp, picked: &str, path: &str) -> St name } +/// When `path`, the file the save panel's answer `picked` was made into, is another name in a +/// folder of the document portal ([`portal_renamed`]): the name for the save panel to ask with +/// again and the folder of the answer, for it to open in. The status bar says why. +pub(crate) fn portal_ask_again(app: &mut VectorcraftApp, picked: &str, path: &str) -> Option<(String, Option<PathBuf>)> { + if !portal_renamed(picked, path) { + return None; + } + let name = confirm_portal_name(app, picked, path); + Some((name, std::path::Path::new(picked).parent().map(std::path::Path::to_path_buf))) +} + /// `path` as typed in a save panel for a file with extension `ext`: kept when its extension is /// `ext` in any letter case, or names the format `ext` names (`photo.jpeg` for a `.jpg` file) or /// a format `keeps` takes. An extension that names another format (`card.svg` for a `.png` file) diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index e2c4441815..f976842163 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -428,7 +428,22 @@ pub(crate) fn unembed(app: &mut VectorcraftApp, id: u64, name: &str) { } return; } - ask(app, PickRequest::save("links").file_name(name), move |app, path| { + ask_unembed(app, id, PickRequest::save("links").file_name(name)); +} + +/// Asks `request`'s save panel where to write embedded image `id`, and unembeds it there. In the +/// document portal, which takes only the name answered, a name without an extension opens the panel +/// again with the stored format's extension added, in the answer's folder. +fn ask_unembed(app: &mut VectorcraftApp, id: u64, request: PickRequest) { + ask(app, request, move |app, path| { + let written = vectorcraft_engine::cmd::links::unembed_path(&app.session, id, &path); + if let Some((name, folder)) = written.and_then(|written| crate::io::save::portal_ask_again(app, &path, &written)) { + let mut request = PickRequest::save("links").file_name(name); + if let Some(folder) = folder { + request = request.directory(folder); + } + return ask_unembed(app, id, request); + } let r = app.run("links.unembed", json!({ "id": id, "path": path })); report(app, r, |v| format!("Unembedded to {}", v["path"].as_str().unwrap_or_default())); }); diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 71c9033b8d..48ceb17ea6 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -1037,6 +1037,33 @@ fn unembed_writes_several_images_to_one_picked_folder() { assert_eq!(app.ui.status, format!("Unembedded 2 images to {picked}")); } +/// In the document portal, which takes only the name its save panel answered, Unembed… writes +/// nothing under a name it had to complete (`photo` for a PNG): the panel opens again in the answer's +/// folder suggesting `photo.png`, and its answer is written and linked. +#[test] +fn unembed_asks_again_for_a_name_the_document_portal_did_not_grant() { + use crate::tests::picks::{poll, scripted}; + let dir = Folder::new("unembed-portal"); + let (mut app, _, embedded) = app(&dir); + let picker = scripted(&mut app); + let ctx = crate::testing::ui_context(); + let portal = "/run/user/1000/doc/a1b2c3d4"; + super::links::unembed(&mut app, embedded, "embedded.png"); + picker.answer_saved(&format!("{portal}/photo"), None); + poll(&mut app, &ctx); + assert_eq!(app.run("links.info", json!({"id": embedded})).unwrap()["status"], "embedded", "nothing is written or linked"); + let requests = picker.requests(); + let [_, again] = requests.as_slice() else { panic!("the save panel opens again: {requests:?}") }; + assert_eq!(again.file_name.as_deref(), Some("photo.png")); + assert_eq!(again.directory.as_deref(), Some(std::path::Path::new(portal))); + assert!(app.ui.status.contains("photo.png"), "{}", app.ui.status); + let granted = dir.0.join("photo.png").to_string_lossy().into_owned(); + picker.answer_saved(&granted, None); + poll(&mut app, &ctx); + assert_eq!(app.run("links.info", json!({"id": embedded})).unwrap()["path"], granted.as_str()); + assert_eq!(picker.requests().len(), 2, "a granted name is written without asking again"); +} + #[test] fn switching_documents_dismisses_a_links_row_menu() { let dir = Folder::new("context-switched-document"); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index d32575ef9c..c93eef486f 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1703,24 +1703,7 @@ fn export_text(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { } let shown = format.unwrap_or(TextFormat::Text); if !crate::io::is_web(app) { - let offered: Vec<TextFormat> = format.map_or_else(|| TextFormat::ALL.to_vec(), |f| vec![f]); - let request = offered.iter().fold(PickRequest::save(SHORTCUT_SETS).file_name(shown.file_name()), |r, f| f.filter(r)); - let (km, set) = (keymap.clone(), name.clone()); - let asked = file_asks::ask(app, request, Owner::Free, move |app, picked| { - let Picked::Saved { path, file_type } = picked else { return Err("cancelled".into()) }; - let answer = path.to_string_lossy().into_owned(); - let typed = file_type.and_then(|i| offered.get(i)).copied(); - let picked = format.unwrap_or_else(|| TextFormat::picked(&answer, typed.map(TextFormat::extension))); - // The format that `format` names, or that the dialog reports as the type picked, gives - // the name its extension. A file already at a path changed that way, which the dialog - // did not check, is replaced only after asking. - let path = if format.is_some() || typed.is_some() { TextFormat::with_extension(&answer, picked) } else { answer.clone() }; - if path != answer && std::path::Path::new(&path).exists() { - let to = path.clone(); - return Ok(file_asks::ask_replace(app, &path, &answer, move |app| write_text_file(app, &km, &set, picked, page, Some(to)))); - } - write_text_file(app, &km, &set, picked, page, Some(path)) - }); + let asked = ask_text_file(app, format, (shown.file_name(), None), keymap.clone(), name.clone(), page); if !asked.is_null() { return Ok(asked); } @@ -1728,6 +1711,43 @@ fn export_text(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { write_text_file(app, &keymap, &name, shown, page, None) } +/// Export Text's save panel, suggesting `file` in `folder` (the last folder used when `None`) and +/// offering the file type `format` names, or every one. The answer is written as [`export_text`] +/// says; an answer in the document portal that would be written under another name opens the panel +/// again with that name in the answer's folder, for the picked format. +fn ask_text_file( + app: &mut VectorcraftApp, + format: Option<TextFormat>, + (file, folder): (String, Option<std::path::PathBuf>), + km: Keymap, + set: String, + page: PageSize, +) -> Value { + let offered: Vec<TextFormat> = format.map_or_else(|| TextFormat::ALL.to_vec(), |f| vec![f]); + let mut request = offered.iter().fold(PickRequest::save(SHORTCUT_SETS).file_name(file), |r, f| f.filter(r)); + if let Some(folder) = folder { + request = request.directory(folder); + } + file_asks::ask(app, request, Owner::Free, move |app, picked| { + let Picked::Saved { path, file_type } = picked else { return Err("cancelled".into()) }; + let answer = path.to_string_lossy().into_owned(); + let typed = file_type.and_then(|i| offered.get(i)).copied(); + let picked = format.unwrap_or_else(|| TextFormat::picked(&answer, typed.map(TextFormat::extension))); + // The format that `format` names, or that the dialog reports as the type picked, gives + // the name its extension. A file already at a path changed that way, which the dialog + // did not check, is replaced only after asking. + let path = if format.is_some() || typed.is_some() { TextFormat::with_extension(&answer, picked) } else { answer.clone() }; + if let Some(again) = crate::io::save::portal_ask_again(app, &answer, &path) { + return Ok(ask_text_file(app, Some(picked), again, km, set, page)); + } + if path != answer && std::path::Path::new(&path).exists() { + let to = path.clone(); + return Ok(file_asks::ask_replace(app, &path, &answer, move |app| write_text_file(app, &km, &set, picked, page, Some(to)))); + } + write_text_file(app, &km, &set, picked, page, Some(path)) + }) +} + /// Writes Export Text's file to `path`; with none, downloads it, or returns it. fn write_text_file( app: &mut VectorcraftApp, diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index 50f14a1ee8..1fe7e2fb57 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -597,6 +597,37 @@ fn keyboard_shortcuts_export_text_writes_the_format_picked_in_its_save_dialog() } } +/// In the document portal, which takes only the name its save panel answered, Export Text writes +/// nothing under a name it had to change (`list` with the sheet picked): the panel opens again in the +/// answer's folder, suggesting `list.pdf` and offering only the sheet, and its answer is written. +#[test] +fn keyboard_shortcuts_export_text_asks_again_for_a_name_the_document_portal_did_not_grant() { + let portal = "/run/user/1000/doc/a1b2c3d4"; + let mut app = app(); + let picker = scripted(&mut app); + let files: Rc<RefCell<Vec<String>>> = Default::default(); + let f = files.clone(); + app.services.write = Some(Box::new(move |path: &str, _: &[u8]| { + f.borrow_mut().push(path.to_string()); + Ok(()) + })); + app_frame(&app.ui_ctx.clone().unwrap(), &mut app, false); + let _ = app.run("shortcuts.exportText", json!({})); + picker.answer_saved(&format!("{portal}/list"), Some(1)); + settle(&mut app); + assert!(files.borrow().is_empty(), "nothing is written under a name the portal did not grant: {:?}", files.borrow()); + let requests = picker.requests(); + let [_, again] = requests.as_slice() else { panic!("the save panel opens again: {requests:?}") }; + assert_eq!(again.file_name.as_deref(), Some("list.pdf")); + assert_eq!(again.directory.as_deref(), Some(std::path::Path::new(portal))); + assert_eq!(again.filters.iter().map(|f| f.extensions.join(",")).collect::<Vec<_>>(), ["pdf"]); + assert!(app.ui.status.contains("list.pdf"), "{}", app.ui.status); + picker.answer_saved(&format!("{portal}/list.pdf"), Some(0)); + settle(&mut app); + assert_eq!(files.borrow().as_slice(), [format!("{portal}/list.pdf")]); + assert_eq!(picker.requests().len(), 2, "a granted name is written without asking again"); +} + /// Keyboard Shortcuts' Import opens a shortcut set another app saved as text (`.kys`) in a review /// over the dialog when its file dialog answers; Cancel shows Keyboard Shortcuts again. #[test] From 039234712f7d967bc28c69e6d9a5127a1753313e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 21:00:20 -0800 Subject: [PATCH 50/56] DXF import: region data longer than the size limit is not kept When a region's decoded data went past the size limit and its record had no group 94, or a group 94 at or above the decoded length, the reader kept the whole oversized buffer in the drawing until the import ended. The region was still left out later, but its data stayed in memory. The reader now checks the stored length after the declared-size cut and drops the record when it is still over the limit. A declared size within the limit still cuts the data and loads it. --- crates/cad/src/import/reader.rs | 19 +++++++++++++------ crates/cad/src/import/tests_region.rs | 7 +++++++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/crates/cad/src/import/reader.rs b/crates/cad/src/import/reader.rs index 167c07cc70..bfa1293b8d 100644 --- a/crates/cad/src/import/reader.rs +++ b/crates/cad/src/import/reader.rs @@ -182,18 +182,25 @@ fn region_data(doc: &model::Document<'_>) -> HashMap<u64, Vec<u8>> { if !whole { continue; } - // Fewer bytes than the record declares means the data was cut short or damaged. - match size { - Some(n) if n <= bytes.len() => bytes.truncate(n), - Some(_) => continue, - None => {} + if let Some(bytes) = sized_region(bytes, size, super::acis::MAX_BYTES) { + out.insert(handle, bytes); } - out.insert(handle, bytes); } } out } +/// A region's `bytes` cut to its declared `size`, or `None` when the record declares more bytes +/// than it holds (the data was cut short or damaged) or the data is longer than `limit`. +pub(super) fn sized_region(mut bytes: Vec<u8>, size: Option<usize>, limit: usize) -> Option<Vec<u8>> { + match size { + Some(n) if n <= bytes.len() => bytes.truncate(n), + Some(_) => return None, + None => {} + } + (bytes.len() <= limit).then_some(bytes) +} + /// Hex digits' bytes, two digits each, onto `out`. False when `hex` has a character that is not /// a hex digit or an odd number of digits. pub(super) fn hex_bytes(hex: &str, out: &mut Vec<u8>) -> bool { diff --git a/crates/cad/src/import/tests_region.rs b/crates/cad/src/import/tests_region.rs index b6b538887c..a44e02c84d 100644 --- a/crates/cad/src/import/tests_region.rs +++ b/crates/cad/src/import/tests_region.rs @@ -334,6 +334,13 @@ fn binary_data_in_the_acdsdata_section_reads_alike() { for hex in ["0aF", "0aZZ", "0 aF"] { assert!(!super::reader::hex_bytes(hex, &mut Vec::new()), "{hex}"); } + // Data longer than the limit is left out, unless its declared size cuts it within the limit. + let sized = |len: usize, size: Option<usize>| super::reader::sized_region(vec![7; len], size, 8).map(|b| b.len()); + assert_eq!(sized(10, None), None); + assert_eq!(sized(10, Some(9)), None); + assert_eq!(sized(10, Some(11)), None); + assert_eq!(sized(10, Some(5)), Some(5)); + assert_eq!(sized(8, None), Some(8)); } /// A drawing the export writes (R2000, millimetres) with a region added to its entities. From 168d6c9cce12dad51c7eaae159671af77d4d2a58 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 21:17:55 -0800 Subject: [PATCH 51/56] Plug-ins: an outside command leaves recut paths and a refused step alone During an add-on dialog's preview, a command from outside the dialog no longer acts on a path whose selected anchors the preview renumbered (Set Corners recut it), so Clear does not delete other points of the base path. A refused outside command leaves the dialog's own selection as it was, while a command that ran, such as Deselect, still sets it. The journal records the selection the command acts on before it, so an action replays it on the same objects. --- crates/engine/src/interaction.rs | 4 ++ crates/engine/src/session/edit.rs | 78 ++++++++++++++++++++-- crates/ui-egui/src/addons/dialogs/tests.rs | 48 +++++++++++++ docs/mcp.md | 2 +- 4 files changed, 124 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 15630b6bbd..825fd4c986 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -104,6 +104,10 @@ pub(crate) struct HeldInteraction { /// The new-art paints when the command began: a change the command makes to them stays when /// the interaction's next preview or a cancel puts back the paints it began with. pub(crate) paint: vectorcraft_tools::PaintDefaults, + /// The command's own selection steps went into the journal before it ran. + pub(crate) journaled: bool, + /// The command returned an error. + pub(crate) refused: bool, } /// The per-document state an interaction puts back when it is canceled, besides the document and diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 5b5f3df44f..21ba56347c 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -345,8 +345,10 @@ impl Session { /// /// A dialog's live preview ([`crate::Interaction::dialog`]) is set aside the same way, except /// for a command that acts on the drawing on show ([`reads_preview`]). Outside commands use - /// the shown selection with objects absent from the base document removed. A selection of - /// only preview objects becomes empty. The interaction stays as it is, and the command runs + /// the shown selection with objects absent from the base document removed, and without a path + /// whose selected anchors the preview renumbered. A selection of only preview objects becomes + /// empty. The journal records that selection before the command, and records the dialog's + /// own selection again when the command is refused. The interaction stays as it is, and the command runs /// inside it, for an interaction a panel or /// another dialog began (it builds its preview from commands), for typing in progress /// ([`Session::edit`] keeps it as a step of its own), for the Quick Pen (an edit made outside @@ -372,21 +374,35 @@ impl Session { let shown = previewed.then(|| (st.doc.clone(), st.selection.clone())); if previewed { st.doc = interaction.doc.clone(); - if interaction.dialog { - st.selection.prune(&st.doc); + if let Some((shown_doc, _)) = shown.as_ref().filter(|_| interaction.dialog) { + shown_base_selection(&mut st.selection, shown_doc, &st.doc); } else { st.selection.clone_from(&interaction.selection); } st.revision += 1; cmd::globaledit::follow_history(st); } + // The journal holds the dialog's base selection, so the command replays on the one it acts on. + let reselect = (interaction.dialog && st.selection != *interaction.selection) + .then(|| selection_steps(&st.selection, &interaction.selection, &st.doc, st.active_layer, &st.highlighted_rows())); let (uid, state) = (st.uid, crate::interaction::ViewState::of(st)); let paint = self.paint.clone(); - self.held_interaction = Some(crate::HeldInteraction { uid, interaction, shown, state, paint }); + let journaled = reselect.is_some(); + if let Some(steps) = reselect { + let (from, grouped) = (self.journal.len(), self.undo_group_docs()); + for step in steps { + self.journal.push(step); + } + self.journal_in_undo_groups(Some(uid), &grouped, from); + } + self.held_interaction = Some(crate::HeldInteraction { uid, interaction, shown, state, paint, journaled, refused: false }); if previewed { self.sync_front_profiles(); } let r = f(self); + if let Some(held) = self.held_interaction.as_mut().filter(|_| r.is_err()) { + held.refused = true; + } self.put_back_interaction(); r } @@ -402,7 +418,9 @@ impl Session { /// than a move. A document the command left an interaction of its own on keeps that one. /// A dialog adopts the command's selection and paints and reruns its preview on its next pass. pub(crate) fn put_back_interaction(&mut self) { - let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint }) = self.held_interaction.take() else { return }; + let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint, journaled, refused }) = self.held_interaction.take() else { + return; + }; // A selection command loaded the paints of the selection it made into the fill and stroke // proxies. The drag goes on with its own selection, so they show its paints again. if !it.dialog @@ -460,7 +478,19 @@ impl Session { // isolation stays when the interaction is canceled. state.rebase(crate::interaction::ViewState::of(st), &mut it); let previewed = shown.is_some(); - if Arc::ptr_eq(&st.doc, &it.doc) && st.selection == *it.selection { + // A refused command leaves the selection it was given: a dialog's is the one on show without + // preview objects. A command that ran (Deselect) and left that selection keeps it. + let given = match shown.as_ref().filter(|_| it.dialog && refused) { + Some((shown_doc, selection)) => { + let mut given = selection.clone(); + shown_base_selection(&mut given, shown_doc, &it.doc); + given + } + None => (*it.selection).clone(), + }; + if Arc::ptr_eq(&st.doc, &it.doc) && st.selection == given { + // The journal goes back to the dialog's base selection, as the preview on show again holds it. + let back = (journaled && active).then(|| selection_steps(&it.selection, &given, &st.doc, st.active_layer, &st.highlighted_rows())); if let Some((doc, selection)) = shown { st.doc = doc; st.selection = selection; @@ -468,6 +498,13 @@ impl Session { cmd::globaledit::follow_history(st); } st.interaction = Some(it); + if let Some(steps) = back { + let (from, grouped) = (self.journal.len(), self.undo_group_docs()); + for step in steps { + self.journal.push(step); + } + self.journal_in_undo_groups(Some(uid), &grouped, from); + } if previewed { self.sync_front_profiles(); } @@ -970,6 +1007,33 @@ fn reads_preview(id: &str) -> bool { id == "edit.copy" || (id.starts_with("file.") && id != "file.documentColorMode") } +/// The selection on show in a dialog's preview `shown`, as a command from outside the dialog acts +/// on it in the base document `base`: without the objects the preview made, and without a path +/// whose selected anchors or segments are numbered in a shape the preview changed in more than a +/// move (Set Corners recut it), since those numbers can name other points in `base`. +fn shown_base_selection(selection: &mut Selection, shown: &Document, base: &Document) { + selection.prune(base); + let recut: Vec<_> = selection + .anchors + .keys() + .chain(selection.segments.keys()) + .copied() + .filter(|&id| { + let path = |d: &Document| d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.clone()); + match (path(shown), path(base)) { + (Some(now), Some(was)) => !moved_whole(&was, &now), + (now, was) => now.is_some() != was.is_some(), + } + }) + .collect(); + for id in recut { + selection.objects.retain(|o| *o != id); + selection.anchors.remove(&id); + selection.segments.remove(&id); + } + selection.prune(base); +} + /// The selection a drag began with, without the objects that a command run during it removed, /// hid or locked in `doc`. fn drag_selection(began: &Selection, doc: &Document) -> Selection { diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index d3e3b3d9f0..7349b1765a 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -354,6 +354,54 @@ fn clearing_a_dialog_preview_uses_only_the_shown_base_objects() { } } +#[test] +fn clearing_anchors_of_a_path_the_preview_recut_keeps_the_base_path() { + let mut app = two_rects_filled(); + let original = app.session.active().unwrap().doc.clone(); + let ids = app.session.active().unwrap().selection.objects.clone(); + app.run("select.anchors", json!({"id": ids[0].0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + let mut preview = crate::dialogs::preview::LivePreview::default(); + assert!(preview.run(&mut app, true, "Set Corners", "addon.pathtools.cornerSet", &json!({"radius": 2, "kind": "chamfer"})).unwrap().is_ok()); + preview.keep_outside_edits(&mut app); + assert!(!app.session.active().unwrap().selection.anchors.is_empty(), "anchors on the recut path are on show"); + let _refused = app.run("edit.clear", json!({})); + preview.cancel(&mut app); + assert_eq!(app.session.active().unwrap().doc, original, "Clear deletes no anchor of the base path"); +} + +#[test] +fn a_refused_outside_command_keeps_the_dialog_selection() { + let mut app = two_rects_filled(); + let selected = app.session.active().unwrap().selection.objects.clone(); + let mut preview = crate::dialogs::preview::LivePreview::default(); + assert!(preview.run(&mut app, true, "Flood Fill Artboards", "addon.document.floodFillArtboards", &json!({})).unwrap().is_ok()); + preview.keep_outside_edits(&mut app); + let shown = app.session.active().unwrap().selection.clone(); + assert!(app.run("edit.clear", json!({})).is_err(), "only preview objects are selected"); + let state = app.session.active().unwrap(); + assert_eq!(state.interaction.as_ref().unwrap().selection.objects, selected, "the dialog keeps its own selection"); + assert_eq!(state.selection, shown, "the preview's selection is on show again"); + app.run("select.none", json!({})).unwrap(); + assert!(app.session.active().unwrap().interaction.as_ref().unwrap().selection.objects.is_empty(), "Deselect still deselects"); + preview.cancel(&mut app); +} + +#[test] +fn an_outside_command_journals_the_selection_it_acts_on() { + let mut app = two_rects_filled(); + let selected = app.session.active().unwrap().selection.objects.clone(); + let mut preview = crate::dialogs::preview::LivePreview::default(); + assert!(preview.run(&mut app, true, "Flood Fill Artboards", "addon.document.floodFillArtboards", &json!({})).unwrap().is_ok()); + preview.keep_outside_edits(&mut app); + app.session.active_mut().unwrap().selection.add(selected[0]); + let start = app.session.journal_for_action(0).len(); + app.run("edit.clear", json!({})).unwrap(); + let action = app.session.journal_for_action(start); + let clear = action.iter().position(|(id, _)| id == "edit.clear").unwrap(); + assert!(action[..clear].iter().any(|(id, _)| id.starts_with("select.")), "Clear replays on the shown selection: {action:?}"); + preview.cancel(&mut app); +} + #[test] fn a_failed_dialog_preview_retries_after_an_outside_selection_change() { let mut app = two_rects(); diff --git a/docs/mcp.md b/docs/mcp.md index 57640fb9c7..22ee99a898 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -889,7 +889,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. The same holds for a step that is neither a number nor null, a `reflect` that is not a string, a `copy` that is not true or false, and an `origin` that is not two numbers. A null `rotate`, `scale`, `scaleX`, `scaleY`, `shear`, `reflect`, `copy` or `origin` is left out; a null `dx` or `dy` counts as 0, so it still runs the move. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. A type object in `ids` with another of them above it in its layer is the text to wrap, not a wrap object, so the objects and the type can be selected together. The reply has a `warning` when no area type lies below any of the wrap objects. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | -| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview, except during an add-on dialog's preview (Object › Plug-ins, other than Edit Points Only): there a command that changes the document records its own undo step, acts on the document without the preview using the shown selection restricted to objects present in that document, and stays after the dialog's Cancel or OK. A shown selection containing only preview objects becomes empty for the command. The dialog previews again from the command's result and selection, including after a failed preview when only the selection changed. An outside selection command's selection and paint defaults stay together after Cancel or OK. `edit.copy` and the `file.*` commands other than `file.documentColorMode` still run on the document as the preview shows it. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | +| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview, except during an add-on dialog's preview (Object › Plug-ins, other than Edit Points Only): there a command that changes the document records its own undo step, acts on the document without the preview using the shown selection restricted to objects present in that document, and stays after the dialog's Cancel or OK. A shown selection containing only preview objects becomes empty for the command. A path whose selected anchors or segments the preview renumbered (Set Corners recut it) is left out of that selection, so Clear does not delete its points. A command that is refused leaves the dialog's selection as it was. The dialog previews again from the command's result and selection, including after a failed preview when only the selection changed. An outside selection command's selection and paint defaults stay together after Cancel or OK. `edit.copy` and the `file.*` commands other than `file.documentColorMode` still run on the document as the preview shows it. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | | `agent_folders` | `{}` | Where VectorCraft opens and saves files for this session: `{read_folder, write_folder}`, each a path or `null`. In the open window, the agent folders of Preferences › AI Integrations (`Documents/ArtCraft/Agents/VectorCraft` for an empty one); in a headless session started for agents, the folders it was confined to (`read_folders` / `write_folders` list them all when a kind has several); a session started without automation roots answers `unrestricted: true`. An app reached with the deprecated `--connect` answers an error: its own `--automation-*-root` flags, if any, confine it. | For example, create editable Japanese area type with the engine's vertical writing mode: From 028ff072e29bab45c38c42d4834e39d08e009d09 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 21:26:00 -0800 Subject: [PATCH 52/56] Docs: Raster Settings OK refuses only when there are changes to apply With unchanged settings OK closes the dialog before the document, history and object checks run (crates/ui-egui/src/panels/three_d/raster.rs:147), so docs/mcp.md and docs/three-d.md now say the refusals apply when there are changes. --- docs/mcp.md | 2 +- docs/three-d.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 2f8eb98a5b..4b286682f3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7544,7 +7544,7 @@ limits, so art too complex for the shaded surface does not refuse the wireframe. The 3D and Materials panel's Render Settings › Raster Settings dialog sets resolution and background on the objects selected when the dialog opened. OK applies the changes in one undo step and records nothing when nothing changes. -OK keeps the dialog open with the reason while its document is not active, after it was reverted or had an Undo, +When there are changes to apply, OK keeps the dialog open with the reason while its document is not active, after it was reverted or had an Undo, a Redo or a canceled edit that put back an earlier state, if one of those objects was changed, deleted, locked or hidden, or while another edit is in progress. ## 3D material diff --git a/docs/three-d.md b/docs/three-d.md index 49b8c45a46..e40f21c168 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -69,7 +69,8 @@ pages describe it. values), at the effect's `resolution` or, without one, at Document Raster Effects Settings › Resolution. **Render Settings › Raster Settings…** sets Use Document Raster Effects Resolution, Resolution (1 to 2400 ppi) and Background (Transparent or White). OK sets the objects selected when the dialog opened in one undo step. - OK keeps the dialog open with the reason while its document is not active, after it was reverted or had an Undo, + When nothing changed, OK closes the dialog and records nothing. When there are changes to apply, OK keeps the + dialog open with the reason while its document is not active, after it was reverted or had an Undo, a Redo or a canceled edit that put back an earlier state, if one of those objects was changed, deleted, locked or hidden, or while another edit is in progress. The Render 3D vector artwork page describes Raster Settings changing the resolution and background. A setting the selected objects hold differently opens blank and is left as each object has it; Rendered and the qualities From 6996cc7878c60fe7ded1c59ad61a03036f4ed5cb Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 01:13:30 -0800 Subject: [PATCH 53/56] Windows: floating panels and dialogs draw where the pointer is on OpenGL Part of #10797. On the OpenGL backend, Preferences and floating panels drew their content offset down and right by a title bar and border, while clicks landed at the unshifted positions. These windows draw their own title bar, so winit makes them undecorated, but it still gives them the WS_CAPTION and WS_BORDER styles, and on these systems the frame stays reserved for the window surface. The guard added for #1758 removes the two styles from the main window only. A viewport hook now records every undecorated window other than the main one as eframe creates it, and runs the same guard on it at creation and before each of its frames, so the styles stay off when winit puts them back. Windows with the system title bar are left alone, and a window's record is dropped with the window. --- apps/vectorcraft/src/main.rs | 4 + apps/vectorcraft/src/window_frame.rs | 145 ++++++++++++++++++++++++++- 2 files changed, 148 insertions(+), 1 deletion(-) diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index d772397ce3..63135d00e5 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -799,6 +799,10 @@ fn main() -> std::process::ExitCode { // window, so eframe's windows are recorded as it makes and drops them (`quit_windows`). #[cfg(target_os = "linux")] let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(quit_windows::Hooks)), ..options }; + // Floating panels and dialogs that draw their own title bar stay borderless on Windows, as the + // main window does (`window_frame`, #10797). + #[cfg(all(windows, feature = "wgpu"))] + let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(window_frame::Hooks)), ..options }; #[cfg(feature = "wgpu")] let options = { let mut options = options; diff --git a/apps/vectorcraft/src/window_frame.rs b/apps/vectorcraft/src/window_frame.rs index e69806ac29..ba5d3d298d 100644 --- a/apps/vectorcraft/src/window_frame.rs +++ b/apps/vectorcraft/src/window_frame.rs @@ -22,10 +22,20 @@ //! monitor. In PhotoCraft the taskbar then did not show when the pointer reached its edge //! (storytold/photocraft#4845). On each edge with an auto-hidden taskbar the guard stops the window //! one pixel short of the monitor instead, as PhotoCraft does (storytold/photocraft#6878). +//! +//! Floating panels and dialogs that draw their own title bar (Preferences, a floating Color panel) +//! are undecorated winit windows as well, and on the same systems their content was drawn offset +//! by the caption and border too (#10797). `Hooks` records those windows as eframe makes them and +//! runs the same guard on each one in each of its frames. + +use std::collections::HashMap; +use std::sync::{Mutex, MutexGuard, PoisonError}; /// Run once per frame; a no-op once the window is borderless. pub type WindowFrameFn = Box<dyn FnMut()>; +#[cfg(all(windows, feature = "wgpu"))] +pub use platform::Hooks; pub use platform::service; #[cfg(all(windows, feature = "wgpu"))] @@ -49,6 +59,33 @@ mod platform { Some(Box::new(move || reapply(&hwnd))) } + /// The undecorated windows of floating panels and dialogs, which [`Hooks`] records. + static SECONDARY: std::sync::LazyLock<super::Viewports<HWND>> = std::sync::LazyLock::new(super::Viewports::default); + + /// Keeps the undecorated windows of floating panels and dialogs borderless, as [`service`] + /// keeps the main window: the guard runs when eframe makes such a window and before each of its + /// frames. Set as [`eframe::NativeOptions::viewport_hooks`]. + pub struct Hooks; + + impl eframe::ViewportHooks for Hooks { + fn window_created(&self, viewport: egui::ViewportId, window: &winit::window::Window) { + let hwnd = match window.window_handle().map(|h| h.as_raw()) { + Ok(RawWindowHandle::Win32(h)) => find_window(h.hwnd.get()), + _ => None, + }; + SECONDARY.created(viewport, window.is_decorated(), hwnd); + SECONDARY.with(viewport, reapply); + } + + fn window_destroyed(&self, viewport: egui::ViewportId) { + SECONDARY.destroyed(viewport); + } + + fn raw_input(&self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) { + SECONDARY.with(raw_input.viewport_id, reapply); + } + } + /// One pass of the per-frame guard: the styles winit put back come off again, and a parked /// maximize stays clear of the taskbar. fn reapply(hwnd: &HWND) { @@ -152,6 +189,55 @@ mod platform { } } +/// The windows of the undecorated floating panels and dialogs, by viewport, while eframe holds +/// them. A record holds `None` while [`Viewports::with`] has its window out. Platform-neutral so +/// it is tested everywhere. +#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] +struct Viewports<H>(Mutex<HashMap<egui::ViewportId, Option<H>>>); + +impl<H> Default for Viewports<H> { + fn default() -> Self { + Self(Mutex::new(HashMap::new())) + } +} + +#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] +impl<H> Viewports<H> { + /// eframe made `viewport`'s window, with `handle`. It is recorded when it is an undecorated + /// window other than the main one, which [`service`] keeps; otherwise any earlier record of the + /// viewport is removed, so a window made again with the system title bar is left alone. + fn created(&self, viewport: egui::ViewportId, decorated: bool, handle: Option<H>) { + let mut windows = self.lock(); + match handle { + Some(handle) if viewport != egui::ViewportId::ROOT && !decorated => windows.insert(viewport, Some(handle)), + _ => windows.remove(&viewport), + }; + } + + /// eframe dropped `viewport`'s window. + fn destroyed(&self, viewport: egui::ViewportId) { + self.lock().remove(&viewport); + } + + /// Runs `f` on `viewport`'s recorded window, if any. The window is taken out of its record + /// while `f` runs, so window messages that `f` sends and that reach the hooks again do not wait + /// on the lock. It goes back only if the record is still there and empty: a window dropped or + /// made again for the viewport in the meantime wins. + fn with(&self, viewport: egui::ViewportId, f: impl FnOnce(&H)) { + let Some(handle) = self.lock().get_mut(&viewport).and_then(Option::take) else { + return; + }; + f(&handle); + if let Some(slot @ None) = self.lock().get_mut(&viewport) { + *slot = Some(handle); + } + } + + fn lock(&self) -> MutexGuard<'_, HashMap<egui::ViewportId, Option<H>>> { + self.0.lock().unwrap_or_else(PoisonError::into_inner) + } +} + /// How far a parked maximize reaches past a monitor or work-area edge: the resize border (about /// 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but being /// dragged or snapped, and is left alone. @@ -260,7 +346,64 @@ fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: & #[cfg(test)] mod tests { - use super::{Edge, clamped_rect, short_of_autohide_taskbars, taskbar_edge}; + use super::{Edge, Viewports, clamped_rect, short_of_autohide_taskbars, taskbar_edge}; + + fn viewport(name: &str) -> egui::ViewportId { + egui::ViewportId::from_hash_of(name) + } + + /// The windows `with` reaches for each viewport, in order. + fn reached(windows: &Viewports<u32>, viewports: &[egui::ViewportId]) -> Vec<Option<u32>> { + viewports + .iter() + .map(|&id| { + let mut seen = None; + windows.with(id, |&h| seen = Some(h)); + seen + }) + .collect() + } + + /// Floating panels and dialogs with their own title bar are kept borderless (#10797); the main + /// window, which `service` keeps, and windows with the system title bar are not recorded. + #[test] + fn undecorated_floating_windows_are_recorded_until_dropped() { + let windows = Viewports::default(); + let (prefs, color, hang) = (viewport("Preferences"), viewport("Color"), viewport("Not responding")); + windows.created(egui::ViewportId::ROOT, false, Some(1)); + windows.created(prefs, false, Some(7)); + windows.created(color, false, Some(9)); + windows.created(hang, true, Some(11)); + assert_eq!(reached(&windows, &[egui::ViewportId::ROOT, prefs, color, hang]), [None, Some(7), Some(9), None]); + // Each frame reaches the window again. + assert_eq!(reached(&windows, &[prefs]), [Some(7)]); + windows.destroyed(prefs); + assert_eq!(reached(&windows, &[prefs, color]), [None, Some(9)]); + // A window made again with the system title bar, or without a handle, is left alone. + windows.created(color, true, Some(13)); + assert_eq!(reached(&windows, &[color]), [None]); + windows.created(color, false, Some(15)); + windows.created(color, false, None); + assert_eq!(reached(&windows, &[color]), [None]); + } + + /// A window dropped or made again while the guard runs on the old one is not brought back. + #[test] + fn a_window_dropped_or_made_again_during_the_guard_wins() { + let windows = Viewports::default(); + let prefs = viewport("Preferences"); + windows.created(prefs, false, Some(7)); + windows.with(prefs, |_| windows.destroyed(prefs)); + assert_eq!(reached(&windows, &[prefs]), [None]); + windows.created(prefs, false, Some(7)); + windows.with(prefs, |_| windows.created(prefs, false, Some(8))); + assert_eq!(reached(&windows, &[prefs]), [Some(8)]); + // The guard can reach the hooks again for the same viewport without waiting on itself. + let mut inner = None; + windows.with(prefs, |_| windows.with(prefs, |&h| inner = Some(h))); + assert_eq!(inner, None); + assert_eq!(reached(&windows, &[prefs]), [Some(8)]); + } #[test] fn a_maximize_covering_the_taskbar_is_trimmed_to_the_work_area() { From 5ee0ebc7be6a54ce57e82b4614e99364eb8ace0c Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 5 Dec 2026 11:09:44 +0100 Subject: [PATCH 54/56] Panels: a floating window revealed with a flyout open shows (#10934) Palette windows hide while the main window shows a popup, and an open flyout is one. A built-in workspace now opens its panel's flyout when it is switched to, so a panel floated by a command in Essentials Classic (Color's flyout) and the other workspaces that open one opened its window hidden, and a_panel_floated_in_any_built_in_workspace_opens_a_shown_window failed on main. The command that reveals a floating window now closes the open flyout. Co-authored-by: FredApps <FredApps@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/ui-egui/src/panel_docking.rs | 6 ++++++ crates/ui-egui/src/panel_docking/native_tests.rs | 15 +++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 37090a916d..e5b0110b77 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1076,6 +1076,12 @@ fn run(app: &mut VectorcraftApp, actions: Vec<Action<String>>, reveal: Option<St if layout_of(&app.ui).opens_in_flyout(&panel) { app.ui.open_panel = Some(panel); } else { + // An open flyout is a popup layer of the main window, and palette windows stay hidden while one shows: a + // floating window revealed with a flyout open (a built-in workspace opens its panel's flyout) would open + // hidden, so the flyout closes. + if floating_window(layout_of(&app.ui), &panel).is_some() { + app.ui.open_panel = None; + } app.dock_rt.raise = Some(panel); } } diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 5f2cbf8648..2c03c5b989 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -601,6 +601,21 @@ fn a_panel_floated_in_any_built_in_workspace_opens_a_shown_window() { } } +/// Palette windows hide while the main window shows a popup, which an open flyout is: a built-in workspace opens its +/// panel's flyout, and a panel floated then closes it, so its window shows. +#[test] +fn floating_a_panel_closes_the_open_flyout_that_would_hide_its_window() { + let mut h = Harness::new(); + h.app.run("window.workspace", json!({"name": "Essentials Classic"})).unwrap(); + h.frames(3); + assert_eq!(h.app.ui.open_panel.as_deref(), Some("color"), "Essentials Classic opens its Color flyout"); + h.app.run("window.panel.float", json!({"panel": "tools", "x": 200, "y": 200})).unwrap(); + h.frames(6); + assert_eq!(h.app.ui.open_panel, None, "the flyout closed"); + let viewport = h.viewport("tools"); + assert!(h.host.borrow().windows[&viewport].visible, "the tools window shows"); +} + /// A panel opened from the Window menu floats in an OS window that keeps showing while the art on /// the canvas is selected and moved, and the Selection tool's move ends where it is released. #[test] From f990e669854ea61025abf3e6ee768883e2752a56 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 5 Dec 2026 11:39:51 +0100 Subject: [PATCH 55/56] Port release fixes to main: v0252b Crop Box, Divide test and regional fixtures (#10907) * Use regional decimals in remaining UI fixtures (cherry picked from commit d689f09e465e5fb83f0468ce4f0c5eacdb63b7ab) * Test Divide preserves artwork at complexity limit (cherry picked from commit cc54974df6af51e318fe27de3226dba437c7715b) * Honor an explicit Crop Box when opening editable PDFs Backport the PDF option handling from 82d4ec4336. Apply it to editable and linked opens while preserving the original file when an alternate box was requested. (cherry picked from commit 73bbd005f3575c3f6c1df2c2fc1d821f92938146) --------- Co-authored-by: Codex <codex@users.noreply.github.com> --- crates/engine/src/cmd/fileio/load.rs | 14 +++++---- crates/engine/src/cmd/fileio/pdfimport.rs | 8 ++++- .../engine/src/cmd/fileio/tests_aiimport.rs | 10 +++++-- crates/engine/src/tests/pathops.rs | 29 ++++++++++++++++++- crates/ui-egui/src/addons/pathtools/corner.rs | 2 +- crates/ui-egui/src/addons/shapes.rs | 2 +- crates/ui-egui/src/canvas/rulers/tests.rs | 2 +- .../ui-egui/src/dialogs/artboard_options.rs | 4 +-- .../ui-egui/src/dialogs/tests_import_pdf.rs | 25 +++++++++++++--- crates/ui-egui/src/dialogs/variation.rs | 4 +-- crates/ui-egui/src/panels/appearance/tests.rs | 2 +- crates/ui-egui/src/panels/tests_units.rs | 1 + crates/ui-egui/src/panels/transform/tests.rs | 2 +- crates/ui-egui/src/tests.rs | 7 +++++ crates/ui-egui/src/tests/taskbar.rs | 2 +- 15 files changed, 90 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index bd21723558..d434dcf6ec 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -308,10 +308,12 @@ fn reads_editing_copy(opts: &LoadOptions) -> bool { /// May a file opened with `opts` open from the editor's own copy of its art without its PDF part /// being imported ([`vectorcraft_eps::ai_layers_alone`]): it reads the editor's copy, on the pages' -/// trim boxes (the crop box asked for, as a file with the editor's copy opens on them), with its -/// type as text? +/// trim boxes by default, with its type as text? fn reads_layers_alone(opts: &LoadOptions) -> bool { - reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines + reads_editing_copy(opts) + && !opts.explicit_crop_box + && opts.crop == vectorcraft_pdf::CropTo::Crop + && opts.text_as != vectorcraft_pdf::TextAs::Outlines } /// The editor's own copy of its art that `opened` carries, decoded ([`decoded_copy`]), when `opts` @@ -475,8 +477,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded> // The file is read and checked once, for the document it carries, its pages, the // editor's copy and its File Info. let opened = vectorcraft_pdf::open_pdf(bytes, opts.password.as_deref()); - // Saved with Preserve Editing: the document it carries, unless some pages are picked. - let editing = (opts.pages.is_none() && opts.native) + // Restore the preserved document when opening all pages at their original size. + let editing = (opts.pages.is_none() && opts.native && !opts.explicit_crop_box) .then(|| opened.as_ref().ok().and_then(|o| o.editing())) .flatten() .map(|e| (e.intact, move || Some(e.data))); @@ -524,7 +526,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded> } None => None, }; - let alone = (r.only_text || empty) + let alone = (!opts.explicit_crop_box && (r.only_text || empty)) .then(copy_alone) .flatten() .and_then(|read| read.ok()) diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 005cc4a557..2dd408acdc 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -173,7 +173,13 @@ impl LoadOptions { /// box, a password, without its hidden layers, without the VectorCraft document it carries, its /// pages linked)? Writing it back would lose the rest, so Save doesn't (it asks for a name). pub fn is_partial(&self) -> bool { - self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages + self.pages.is_some() + || self.crop != CropTo::default() + || self.explicit_crop_box + || self.password.is_some() + || !self.layers + || !self.native + || self.link_pages } /// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 6e63170f88..3c6343ebea 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -1395,8 +1395,7 @@ fn link_pages_refuses_an_ai_file_saved_without_its_pdf_part() { let _ = std::fs::remove_dir_all(&d); } -/// `document.open` with `linkPages` opens a PDF-compatible `.ai` asked for its crop box on its trim -/// box, as it opens as art, showing its bleed box round the artboard, which is the document's bleed. +/// Linked pages default to the trim box with the bleed and honor an explicit Crop Box. #[test] fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() { let d = std::env::temp_dir().join(format!("vc-ailinkpagestrim-{}", std::process::id())); @@ -1416,6 +1415,13 @@ fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() { let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) }; assert_eq!((p.width, p.height, p.page_box), (192.0, 96.0, vectorcraft_doc::PageBox::Bleed)); assert_eq!(p.xf.translation(), vectorcraft_geom::Vec2::new(-6.0, -8.0), "the trim box on the artboard"); + + s.execute("document.open", &json!({"path": path, "linkPages": true, "cropTo": "crop"})).unwrap(); + let cropped = &s.doc().unwrap().doc; + assert!(cropped.artboards[0].rect.width() > board.width()); + let placed = &cropped.layers[0].children().unwrap()[0]; + let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) }; + assert_eq!(p.page_box, vectorcraft_doc::PageBox::Crop); let _ = std::fs::remove_dir_all(&d); } diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index d1b5197012..dd37818799 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, NodeKind}; -use vectorcraft_geom::{FillRule, PathData, Rect}; +use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath}; use crate::*; @@ -211,6 +211,33 @@ fn exclude_makes_compound() { assert!((area_of(&s, r[0]) - 15000.0).abs() < 1.0); } +#[test] +fn divide_over_work_budget_preserves_art_and_selection() { + let mut s = session(); + let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let line = s.execute("shape.line", &json!({"x1": -10, "y1": -10, "x2": 110, "y2": 110})).unwrap(); + let cutter = NodeId(line["id"].as_u64().unwrap()); + // The existing pathops work-budget fixture uses 1,500 overlapping lines. + // Put them in one open path so the setup only makes two document objects. + let line = SubPath::polyline(&[Point::new(-10.0, -10.0), Point::new(110.0, 110.0)], false); + s.edit("complex cutter", |d, _| { + let NodeKind::Path { path, .. } = &mut d.node_mut(cutter).unwrap().kind else { panic!("expected a path") }; + *path = PathData::new(vec![line; 1_500]); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [square.0, cutter.0]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let selection = s.doc().unwrap().selection.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let error = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string(); + assert!(error.contains("too many segments or pieces"), "{error}"); + let state = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&state.doc, &before), "the original document must be restored"); + assert_eq!(state.selection, selection); + assert_eq!(state.history.undo.len(), undo); +} + #[test] fn divide_produces_group_of_faces() { let mut s = session(); diff --git a/crates/ui-egui/src/addons/pathtools/corner.rs b/crates/ui-egui/src/addons/pathtools/corner.rs index f24542b81d..6c2d9f2b11 100644 --- a/crates/ui-egui/src/addons/pathtools/corner.rs +++ b/crates/ui-egui/src/addons/pathtools/corner.rs @@ -134,7 +134,7 @@ mod tests { let undo = panel.app().session.active().unwrap().history.undo.len(); panel.click_role(label, Role::SPIN_BUTTON); panel.key(Key::A, Modifiers::COMMAND); - panel.type_text(typed); + panel.type_text(&crate::tests::regional_text(typed)); panel.frame(); let proposed = panel.app().session.tool_options_of(tool); assert_ne!(proposed[key], before[key], "{label} changes while typing"); diff --git a/crates/ui-egui/src/addons/shapes.rs b/crates/ui-egui/src/addons/shapes.rs index 5e25b913c9..d922864054 100644 --- a/crates/ui-egui/src/addons/shapes.rs +++ b/crates/ui-egui/src/addons/shapes.rs @@ -663,7 +663,7 @@ mod cancel_tests { panel.frame(); panel.click_role("TL", Role::SPIN_BUTTON); panel.key(Key::A, Modifiers::COMMAND); - panel.type_text("4.125"); + panel.type_text(&crate::tests::regional_text("4.125")); panel.frame(); let proposed = panel.app().session.tool_options(); assert_ne!(proposed["cornerRadii"], before["cornerRadii"]); diff --git a/crates/ui-egui/src/canvas/rulers/tests.rs b/crates/ui-egui/src/canvas/rulers/tests.rs index 4e0c3342b3..a523eab866 100644 --- a/crates/ui-egui/src/canvas/rulers/tests.rs +++ b/crates/ui-egui/src/canvas/rulers/tests.rs @@ -257,6 +257,6 @@ fn ruler_labels_carry_the_sign_and_the_steps_decimals() { (1.0, 0.0625, "1"), (1.1875, 0.0625, "1.1875"), ] { - assert_eq!(x.tick_label(&units, value, step), want, "the tick at {value} of a {step} step"); + assert_eq!(x.tick_label(&units, value, step), crate::tests::regional_text(want), "the tick at {value} of a {step} step"); } } diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index 4ca5f2fc23..6c1599a5ab 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -825,7 +825,7 @@ mod tests { assert_eq!(pending.size_choice, Some(ArtboardSizeChoice::Orientation(true))); panel.click_role(label, Role::SPIN_BUTTON); panel.key(Key::A, Modifiers::COMMAND); - panel.type_text(typed); + panel.type_text(&crate::tests::regional_text(typed)); assert_eq!(actual_value(&panel), pending, "typing must not discard the pending orientation or reference-point policy"); panel.key(Key::Escape, Modifiers::NONE); assert!(!is_open(&panel.app()), "Escape discards the modal for {label}"); @@ -875,7 +875,7 @@ mod tests { panel.frame(); panel.click_role(label, Role::SPIN_BUTTON); panel.key(Key::A, Modifiers::COMMAND); - panel.type_text(typed); + panel.type_text(&crate::tests::regional_text(typed)); if blur { panel.key(Key::Tab, Modifiers::NONE); } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index ab2bd34908..2fc635abd9 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -381,16 +381,22 @@ fn two_pages(editing_data: bool, password: Option<&str>) -> Vec<u8> { /// Two 100 pt pages and, on the first, editing data with two artboards to match and a layer of its /// own, which draws the square the first page draws. -fn two_pages_with_a_layer_in_the_editing_data(layer: &str) -> Vec<u8> { +fn two_pages_with_a_layer_in_the_editing_data(layer: &str, with_trim_box: bool) -> Vec<u8> { let point = |x: i32, y: i32, n: u8| format!("%_{x} {y} /RealPointRelToROrigin\n%_ (PositionPoint{n}) ,\n"); let board = |top: i32| format!("%_/Dictionary :\n{}{}%_; ,\n", point(0, top, 1), point(100, top - 100, 2)); let boards = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n", board(100), board(-50)); let art = format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 10.0, 30.0, 30.0)); let data = ai::editing_data(100.0, 100.0, &format!("{boards}{}", ai::layer(layer, &art))); - let mut first = PdfPage::new(100.0, 100.0, "0 0 0 1 k 10 10 20 20 re f"); + let page = |content| { + let edge = if with_trim_box { 120.0 } else { 100.0 }; + let mut page = PdfPage::new(edge, edge, content); + page.trim = with_trim_box.then_some([10.0, 10.0, 110.0, 110.0]); + page + }; + let mut first = page("0 0 0 1 k 10 10 20 20 re f"); first.entries = format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(2)); let stream = format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len()); - pdf_with(&[first, PdfPage::new(100.0, 100.0, "")], &[&stream], None) + pdf_with(&[first, page("")], &[&stream], None) } /// #6135: the editing data of a `.ai` holds every artboard, so opening one asks nothing, opens @@ -398,7 +404,7 @@ fn two_pages_with_a_layer_in_the_editing_data(layer: &str) -> Vec<u8> { #[test] fn opening_an_ai_with_editing_data_reads_it_without_asking() { let mut app = app(); - let bytes = two_pages_with_a_layer_in_the_editing_data("Only in the editing data"); + let bytes = two_pages_with_a_layer_in_the_editing_data("Only in the editing data", false); io::open_bytes(&mut app, "two.ai", &bytes, Some("/tmp/two.ai".into())).unwrap(); assert!(!is_open(&app), "no Import PDF dialog"); assert_eq!(app.session.documents().len(), 2); @@ -435,6 +441,17 @@ fn opening_a_pdf_with_editing_data_keeps_its_trim_boxes_unless_a_box_is_picked() confirm(&mut app).unwrap(); assert_eq!(artboard_widths(&app), [100.0, 200.0], "an explicit crop box"); + let bytes = two_pages_with_a_layer_in_the_editing_data("An editable layer", true); + let mut app = self::app(); + assert!(import_pdf::offer(&mut app, "readable.pdf", &bytes, None, None)); + confirm(&mut app).unwrap(); + assert_eq!(artboard_widths(&app), [100.0, 100.0], "the trim boxes match the artboards in the editing data"); + let mut app = self::app(); + assert!(import_pdf::offer(&mut app, "readable.pdf", &bytes, None, None)); + set(&mut app, "cropTo", json!("crop")); + confirm(&mut app).unwrap(); + assert_eq!(artboard_widths(&app), [120.0, 120.0], "the crop boxes override the artboards in the editing data"); + let mut app = self::app(); assert!(import_pdf::offer(&mut app, "locked.pdf", &trimmed(Some("pw")), None, None)); set(&mut app, "password", json!("pw")); diff --git a/crates/ui-egui/src/dialogs/variation.rs b/crates/ui-egui/src/dialogs/variation.rs index 9ce39bc031..9b97e2d2e0 100644 --- a/crates/ui-egui/src/dialogs/variation.rs +++ b/crates/ui-egui/src/dialogs/variation.rs @@ -131,7 +131,7 @@ mod tests { for (label, text) in [("Value", typed), ("Variation:", variation)] { panel.click_role(label, Role::SPIN_BUTTON); panel.key(Key::A, Modifiers::COMMAND); - panel.type_text(text); + panel.type_text(&crate::tests::regional_text(text)); panel.key(Key::Escape, Modifiers::NONE); assert!(!panel.app().dialogs().unwrap().with(|host| host.is_open::<HostedParamDialog>())); assert_eq!(panel.app().session.tool_options_of(tool), original, "the canceled {label} leaves the tool unchanged"); @@ -143,7 +143,7 @@ mod tests { for (label, text) in [("Value", typed), ("Variation:", variation)] { panel.click_role(label, Role::SPIN_BUTTON); panel.key(Key::A, Modifiers::COMMAND); - panel.type_text(text); + panel.type_text(&crate::tests::regional_text(text)); panel.key(Key::Tab, Modifiers::NONE); } panel.click_role("Mode", Role::COMBO_BOX); diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index becf9ecc3c..0a6cd7b88c 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -227,7 +227,7 @@ fn a_plug_in_effect_s_editor_follows_its_manifest() { } assert!(!panel.shows("spacing") && !panel.shows("width"), "the labels replace the names"); let spacing = panel.value_role("Spacing", craft::ui::contract::Role::SPIN_BUTTON); - assert!(spacing.as_deref().is_some_and(|v| v.contains("1.5") && v.contains("mm")), "{spacing:?}"); + assert!(spacing.as_deref().is_some_and(|v| v.contains(&crate::tests::regional_text("1.5")) && v.contains("mm")), "{spacing:?}"); assert!(panel.value("Angles").is_some_and(|v| v.contains("45, 135")), "{:?}", panel.value("Angles")); // Without the outline, its width isn't shown. panel.app().run("effect.setParams", json!({"item": null, "index": 0, "params": {"outline": false}})).unwrap(); diff --git a/crates/ui-egui/src/panels/tests_units.rs b/crates/ui-egui/src/panels/tests_units.rs index d5837ffed5..46e400e693 100644 --- a/crates/ui-egui/src/panels/tests_units.rs +++ b/crates/ui-egui/src/panels/tests_units.rs @@ -58,6 +58,7 @@ fn bar(app: &mut VectorcraftApp, ui: &mut Ui) { pub(crate) fn reads(value: Option<String>, unit: Unit, pt: f64) -> bool { value.is_some_and(|v| { let Some(number) = v.strip_suffix(unit.suffix()).map(str::trim_end) else { return false }; + let number = vectorcraft_doc::decimal_point(number); let decimals = number.split_once('.').map_or(0, |(_, d)| d.len()); number.parse::<f64>().is_ok_and(|shown| (shown - unit.from_pt(pt)).abs() <= 0.5 * 10f64.powi(-(decimals as i32)) + 1e-9) }) diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index 15414aba1b..0c89dd27c2 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -20,7 +20,7 @@ fn pt(v: f64) -> String { /// A shown angle, in degrees. fn degrees(p: &Panel, name: &str) -> Option<f64> { - p.value(name)?.trim_end_matches('°').trim_end().parse().ok() + vectorcraft_doc::parse_number(&vectorcraft_doc::decimal_point(p.value(name)?.trim_end_matches('°').trim_end())) } /// The state of panel-menu row `id`, as the panel menus' states give it. diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 93063d4c0e..139e7a94f0 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -70,3 +70,10 @@ mod trace_runs; /// test also installs, or that check how plug-ins sharing a name are told apart, hold this lock /// while their plug-ins are installed, so each sees only its own plug-ins under that name. pub(super) static SHARED_PLUGIN_NAMES: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Formats a decimal fixture with the system region used by the UI. +pub(crate) fn regional_text(text: &str) -> String { + let decimal = craft::i18n::Format::new(&craft::i18n::Region::system(), craft::i18n::Digits::Latin).number_ungrouped(0.1, 1); + let mark = decimal.strip_prefix('0').unwrap().strip_suffix('1').unwrap(); + text.replace('.', mark) +} diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index f98a9bdd96..07f42b9c6c 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1624,7 +1624,7 @@ fn the_smooth_tools_fidelity_label_is_one_line_beside_its_field() { let labels = tree.with_role(craft::ui::contract::Role::LABEL); assert!(labels.iter().any(|key| tree.name_of(*key) == Some("Fidelity:")), "the label is in the access tree"); let run = |text: &str| fx.texts().iter().find(|t| t.text == text).cloned().unwrap_or_else(|| panic!("no `{text}` painted")); - let (label, value) = (run("Fidelity:"), run("2.50 px")); + let (label, value) = (run("Fidelity:"), run(&crate::tests::regional_text("2.50 px"))); assert!(label.rect.height() < 2.0 * value.rect.height(), "the label is one line: {:?}", label.rect); assert!((label.baseline - value.baseline).abs() <= 1.0, "the label sits on the field's baseline: {label:?} {value:?}"); }); From 7e58b453aacef86f9560a76b36a386e7568835c1 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 5 Dec 2026 11:39:58 +0100 Subject: [PATCH 56/56] Port release fixes to main: v0252a (wheel zoom easing, test fixtures) (#10908) * Locate both color wells by their reported radio values The shared swatch pair exposes unnamed radio parts. Drive real clicks on the exposed area of Stroke and Fill and keep the original paint and modifier assertions. (cherry picked from commit 5b990d637c03132cccdf9927bed1db4ae1855254) * Use regional decimal marks in UI fixtures (cherry picked from commit 4208649d63ac95a83dca57a71ce3be3e6e6b69a4) * Use ordinary canonical paths in script fixtures (cherry picked from commit f37b5811ad458b730adac37b78d664afb9234aeb) * Restore Animated Zoom for mouse-wheel notches Restore the glide when Zoom with Scroll Wheel and Animated Zoom are both on, as in 0.24.1. The canvas keeps precision point input and pinches immediate. Tracks #10418. (cherry picked from commit 1dde4db0f344c2c79f59a11392772ba93874e0b2) --------- Co-authored-by: Codex <codex@users.noreply.github.com> --- crates/engine/src/tests/script_io.rs | 2 +- crates/engine/src/tests/script_xmp.rs | 2 +- crates/ui-egui/src/app/view.rs | 3 ++- crates/ui-egui/src/panels/color/tests.rs | 9 ++++++--- crates/ui-egui/src/panels/navigator.rs | 4 +++- crates/ui-egui/src/tests/panel_harness.rs | 11 +++++++++++ .../ui-egui/tests/dimension_extension_properties.rs | 9 +++++---- 7 files changed, 29 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index b5d7fe7ded..527408f06e 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -19,7 +19,7 @@ fn folder(name: &str) -> PathBuf { let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); std::fs::create_dir_all(base.join("main")).unwrap(); - std::fs::canonicalize(&base).unwrap() + crate::cmd::findfiles::plain(std::fs::canonicalize(&base).unwrap()) } fn write(path: &Path, bytes: &[u8]) { diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index 687df5cd0e..82a0de2a6c 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -57,7 +57,7 @@ impl AsRef<Path> for Folder { /// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path. fn folder(name: &str) -> Folder { let guard = vectorcraft_testkit::TempDir::new(&format!("script-xmp-{name}")); - let base = std::fs::canonicalize(&*guard).unwrap(); + let base = crate::cmd::findfiles::plain(std::fs::canonicalize(&*guard).unwrap()); std::fs::create_dir_all(base.join("main")).unwrap(); Folder { _guard: guard, path: base } } diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index a1ab70c788..cf8983e17f 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -11,7 +11,8 @@ pub(crate) fn navigation(p: &Prefs) -> NavigationOptions { let mut options = NavigationOptions::default(); options.wheel = if p.zoom_with_mouse_wheel { WheelScheme::Zoom } else { WheelScheme::Scroll }; options.animated_zoom = crate::canvas::animated_zoom(p); - options.scrubby_zoom = crate::canvas::animated_zoom(p); + options.eased_wheel_zoom = p.zoom_with_mouse_wheel && options.animated_zoom; + options.scrubby_zoom = options.animated_zoom; options.trackpad_rotate = p.trackpad_rotate_view; options.touch_gestures = p.touch_gestures; options.overscroll = true; diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index 63d7b21f9b..0088e3037e 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -463,6 +463,7 @@ fn an_open_color_or_gradient_pop_out_runs_one_pass_a_frame() { #[test] fn the_color_panel_edits_the_selected_stroke_well_without_changing_fill() { use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; let mut app = app(); app.run("paint.setFill", json!({"color": "#224466"})).unwrap(); @@ -470,8 +471,8 @@ fn the_color_panel_edits_the_selected_stroke_well_without_changing_fill() { 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 fill_well = panel.rect_role_with_value(Role::RADIO_BUTTON, &fill); + let stroke_well = panel.rect_role_with_value(Role::RADIO_BUTTON, &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); @@ -487,7 +488,9 @@ fn the_color_panel_edits_the_selected_stroke_well_without_changing_fill() { panel.click("None"); assert_eq!(paints_hex(&panel.app()), ("#ffffff".into(), String::new())); - panel.click("Fill"); + let fill_hit = egui::pos2(fill_well.center().x, (fill_well.top() + stroke_well.top()) / 2.0); + assert!(fill_well.contains(fill_hit) && !stroke_well.contains(fill_hit), "click the exposed part of Fill"); + panel.click_at(fill_hit); 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/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index c1f6bcc537..a6c08c8db7 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -312,7 +312,9 @@ mod tests { app.run("view.setZoom", json!({"zoom": 100})).unwrap(); let mut panel = crate::tests::panel_harness::Panel::new(app, draw); panel.app().ui.status.clear(); - panel.type_into("Zoom", "80..2"); + let decimal = craft::i18n::Format::new(&craft::i18n::Region::system(), craft::i18n::Digits::Latin).number_ungrouped(0.2, 1); + let mark = decimal.strip_prefix('0').unwrap().strip_suffix('2').unwrap(); + panel.type_into("Zoom", &format!("80{mark}{mark}2")); { let app = panel.app(); assert!((app.view().unwrap().zoom - 0.8).abs() < 1e-9, "applies the valid prefix"); diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 41e03245ee..7d347119d3 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -464,6 +464,17 @@ impl Panel { part_rect_of_node(self.ctx(), self.look_role(name, role).node.into(), part.into()) } + /// Where the control of `role` reporting `value` is, for an unnamed part such as a color well. + pub(crate) fn rect_role_with_value(&self, role: Role, value: &str) -> Rect { + let tree = self.fixture.tree(); + self.fixture + .by_role(role) + .into_iter() + .find(|target| tree.value_of(target.node) == Some(value)) + .unwrap_or_else(|| panic!("no {role:?} with value {value:?}")) + .rect + } + /// The value text of the control named `name`. pub(crate) fn value(&self, name: &str) -> Option<String> { self.fixture.tree().value_of(self.look(name).node).map(str::to_owned) diff --git a/crates/ui-egui/tests/dimension_extension_properties.rs b/crates/ui-egui/tests/dimension_extension_properties.rs index 127f3e2dd0..65c8944ea4 100644 --- a/crates/ui-egui/tests/dimension_extension_properties.rs +++ b/crates/ui-egui/tests/dimension_extension_properties.rs @@ -1,6 +1,7 @@ //! Selected Dimension extension-line controls through the real Properties panel. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use craft::i18n::{Digits, Format, Region}; use craft::ui::dialog::DialogId; use craft::ui::runtime::env::WindowKey; use craft::ui::shell::WindowDialogs; @@ -236,7 +237,7 @@ fn properties_edits_both_extensions_preserves_main_text_and_roundtrips_editable_ let original = recipe(&d.app.borrow(), id); let selection = d.app.borrow().session.active().unwrap().selection.clone(); let paint = d.app.borrow().session.paint.clone(); - d.type_number("Extension Line Weight", "0.35"); + d.type_number("Extension Line Weight", &Format::new(&Region::system(), Digits::Locale).number_ungrouped(0.35, 2)); let weighted = recipe(&d.app.borrow(), id); assert_eq!(weighted.options.extension_weight, 0.35); assert_eq!(geometry(&weighted), geometry(&original)); @@ -266,7 +267,7 @@ fn properties_edits_both_extensions_preserves_main_text_and_roundtrips_editable_ d.run("document.open", json!({"name": "dimension.vectorcraft", "dataBase64": data})); assert_eq!(recipe(&d.app.borrow(), id), edited); select_properties(&mut d, id); - d.type_number("Extension Line Weight", "0.6"); + d.type_number("Extension Line Weight", &Format::new(&Region::system(), Digits::Locale).number_ungrouped(0.6, 1)); assert_eq!(recipe(&d.app.borrow(), id).options.extension_weight, 0.6, "the native recipe remains editable through Properties"); assert_eq!(geometry(&recipe(&d.app.borrow(), id)), geometry(&edited)); generated_styles(&d.app.borrow(), id, [128, 128, 128], 0.6); @@ -298,7 +299,7 @@ fn properties_apply_all_copies_full_style_to_editable_dimensions_and_undoes_as_o let other_original = recipe(&d.app.borrow(), other); let locked_original = recipe(&d.app.borrow(), locked); select_properties(&mut d, id); - d.type_number("Extension Line Weight", "0.35"); + d.type_number("Extension Line Weight", &Format::new(&Region::system(), Digits::Locale).number_ungrouped(0.35, 2)); d.pick_color("Extension Line Color", "extensionColor", "#808080"); assert_eq!(recipe(&d.app.borrow(), other), other_original, "selected edits do not change an unselected dimension"); assert_eq!(recipe(&d.app.borrow(), locked), locked_original); @@ -327,7 +328,7 @@ fn properties_set_default_is_inherited_by_an_options_free_new_dimension() { NodeId(d.run("dimension.create", json!({"a": [200,150], "b": [241.13,150], "options": {"extensionWeight": 0.8}}))["id"].as_u64().unwrap()); let other_original = recipe(&d.app.borrow(), other); select_properties(&mut d, id); - d.type_number("Extension Line Weight", "0.35"); + d.type_number("Extension Line Weight", &Format::new(&Region::system(), Digits::Locale).number_ungrouped(0.35, 2)); d.pick_color("Extension Line Color", "extensionColor", "#808080"); let selected = recipe(&d.app.borrow(), id); let document = d.app.borrow().session.active().unwrap().doc.clone();