diff --git a/Cargo.lock b/Cargo.lock index 783e02a9bc..4f74f10fc4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6841,6 +6841,7 @@ dependencies = [ "vectorcraft-svg", "vectorcraft-testkit", "vectorcraft-text", + "vectorcraft-three-d", "vectorcraft-tools", "vectorcraft-trace", "wat", @@ -7154,6 +7155,7 @@ dependencies = [ name = "vectorcraft-three-d" version = "0.24.1" dependencies = [ + "proptest", "vectorcraft-geom 0.24.1", "vectorcraft-pathops 0.24.1", ] diff --git a/ROADMAP.md b/ROADMAP.md index 6471505555..f658cccb58 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 2213190df6..36fe29a8f2 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -575,6 +575,9 @@ pub const DEFAULT_FILLED_LINE_WIDTH: f64 = 3.0; pub const MIN_FILLED_LINE_WIDTH: f64 = 0.01; pub const MAX_FILLED_LINE_WIDTH: f64 = 1000.0; +/// The weight of the black outline Draw Filled Lines draws around each band, in points. +pub const FILLED_LINE_OUTLINE_WIDTH: f64 = 0.25; + impl GraphSpec { /// How wide Draw Filled Lines draws a line, in points: [`Self::line_width`], else [`DEFAULT_FILLED_LINE_WIDTH`]. A /// width a file gives outside [`MIN_FILLED_LINE_WIDTH`] to [`MAX_FILLED_LINE_WIDTH`], or not finite, draws the diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index f590a46497..11711b3f1d 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -97,8 +97,9 @@ pub use compound_shape::ShapeMode; pub use corners::LiveCorners; pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ - ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_FILLED_LINE_WIDTH, - MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide, + ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, + LabelStyles, MAX_FILLED_LINE_WIDTH, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength, + ValueAxisSide, }; pub use hit::{Hit, HitKind}; pub use links::{LinkInfo, PlacementOptions}; diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index cd423658d7..1d6b3e4f11 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -1,5 +1,5 @@ -//! Placed documents: another VectorCraft file, or a page of a PDF or `.ai` file, placed linked -//! ([`PlacedDocument`]). +//! Placed documents: another VectorCraft file, a page of a PDF or `.ai` file, or an EPS file, +//! placed linked ([`PlacedDocument`]). //! //! The object keeps the link to the file and the file's bytes, stored like image data in //! [`Document::images`] (with a small preview a save writes instead, as for linked images), so the @@ -7,9 +7,9 @@ //! joins the object tree, so editing can't reach it: it is locked by design. Drawing and exporting //! expand it like a live object ([`crate::live::expanded`]). //! -//! The file is read by the engine's loader (native documents, PDF and `.ai` pages), which lives -//! above this crate and registers itself ([`set_loader`]); the art read is kept in a small cache -//! by content. Before exporting, +//! The file is read by the engine's loader (native documents, PDF and `.ai` pages, EPS files), +//! which lives above this crate and registers itself ([`set_loader`]); the art read is kept in a +//! small cache by content. Before exporting, //! every exporter calls [`Document::with_placed_art`], which adds the resources the art uses //! (images, symbols, patterns) under names of their own ([`RESOURCE_PREFIX`]) to a temporary copy //! of the document, so they never meet the user's or show in panels. Placed documents inside a @@ -27,8 +27,8 @@ use vectorcraft_color::Paint; use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol}; -/// A placed document: an artboard of another VectorCraft file, or a page of a PDF or `.ai` file, -/// shown as one locked object. +/// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or +/// an EPS file's art, shown as one locked object. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PlacedDocument { /// The file (its `page` is the artboard or page shown, 1-based). diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index cd91a0bfbb..f972cbb7b3 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -29,6 +29,8 @@ vectorcraft-tools = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-render = { workspace = true } vectorcraft-pathops = { workspace = true } +# The panels and hinges of a packaging blank (Packaging Tools' Check Fold Lines). +vectorcraft-three-d = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-trace = { workspace = true } vectorcraft-svg = { workspace = true } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index e2bc50cdc5..c4a86dd3a5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -893,6 +893,10 @@ pub use buildcmds::live_paint_gaps; /// Control bar enable it when it changes one). pub use brushsym::reset_transformation_changes; +/// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every +/// frame without running the command). +pub use brushsym::current_symbol; + /// The byte order of UTF-16 text without a byte-order mark, by Import Data Sets' rule (the Graph /// Data window reads files by it too). pub use variablecmds::utf16_order_without_mark; diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 7e262c3869..6099386b98 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -1,9 +1,11 @@ //! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other //! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line //! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each -//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu +//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold +//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu //! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. +mod check; mod roles; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; @@ -11,7 +13,9 @@ pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; use super::super::CommandSpec; pub fn specs() -> Vec { - roles::specs() + let mut v = roles::specs(); + v.extend(check::specs()); + v } #[cfg(test)] diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs new file mode 100644 index 0000000000..da8f7f25dd --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -0,0 +1,179 @@ +//! Check Fold Lines (`addon.packaging.check`): the blanks the fold lines make, their panels and +//! hinges, and what is wrong with the lines, found by [`vectorcraft_three_d::fold::blanks`]. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::PathData; +use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks}; + +use super::super::super::pathops::length_given; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; +use super::roles::{Role, RoleTable, can_carry, role_targets}; +use crate::{Result, Session}; + +const CHECK: &str = "addon.packaging.check"; + +/// How far apart the ends of two lines may be and still be joined, in points. +const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); + +pub fn specs() -> Vec { + vec![cmd!( + "addon.packaging.check", + "Check Fold Lines", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{ids?: [id…] (default: the selection), select?: bool (false), tolerance?: pt 0.01..10 (0.1)} check the fold lines (addon.packaging.roles) among the objects (through groups and clip groups), or, while nothing is selected and ids is left out, every fold line of the document; hidden lines are left out, also in a selected group. Cut lines bound the blanks: each connected piece of them that encloses material is one blank, its outline is its largest closed cut line, and a closed cut line inside it is a hole, so a slot drawn as a rectangle across the outline leaves the same material as a notch drawn in it; open cut lines that meet end to end count as one closed cut line. Crease, Partial Cut and Perforation lines divide a blank into panels; the pieces of them between two panels are that pair's hinge. A cut line end that comes within tolerance of another cut line is joined to it. Issues, in this order: noCut, open, looseEnd (errors), gap (a warning: the gap is closed), tooComplex (an error: more than 65,536 segments or 256 panels in a blank), cutOverCrease (an error), duplicate (two cut lines, or two lines that fold of any role), danglingCrease, noSplit, outside (wholly, or in part for tolerance or more), notStraight (a hinge's pieces are not on one straight line), sliver, ambiguous, loosePanel (joined to the largest panel by no chain of hinges), nonPrinting (warnings). With select, the objects the issues name become the selection, unless no issue names one. Changes nothing in the document → {ok (no error), blanks, panels, hinges, holes, issues: [{severity: error|warning, code, message (English), ids, at?: [x, y]}], scope: ids|selection|document}", + has_doc, + check + )] +} + +/// The English message for an issue (the Fold Lines panel shows it in the interface language). +fn message(code: IssueCode, scope: &str) -> &'static str { + match code { + IssueCode::NoCut if scope == "document" => "No cut lines are in the document.", + IssueCode::NoCut if scope == "ids" => "No cut lines are among the given objects.", + IssueCode::NoCut => "No cut lines are in the selection.", + IssueCode::Open => "The cut lines do not enclose an area.", + IssueCode::LooseEnd => "A cut line ends without meeting another cut line.", + IssueCode::Gap => "A gap between cut lines was closed.", + IssueCode::TooComplex => "The fold lines are too complex to check.", + IssueCode::CutOverCrease => "A cut line and a crease lie on top of each other.", + IssueCode::Duplicate => "Two fold lines lie on top of each other.", + IssueCode::DanglingCrease => "A crease ends inside a panel.", + IssueCode::NoSplit => "A crease does not divide two panels.", + IssueCode::Outside => "A crease lies outside the cut outline, wholly or in part.", + IssueCode::NotStraight => "The pieces of a hinge are not on one straight line.", + IssueCode::Sliver => "A gap between cut lines is too narrow to tell apart.", + IssueCode::Ambiguous => "A cut-out area holds other fold lines or another blank.", + IssueCode::LoosePanel => "A panel is not joined to the rest by a crease.", + IssueCode::NonPrinting => "A fold line is on a non-printing layer.", + } +} + +/// Every object of the document that can carry a role and is shown: on a shown layer, in shown +/// groups, and shown itself. +fn shown_targets(d: &Document) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + if !n.visible { + return; + } + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ if can_carry(n) => out.push(n.id), + _ => {} + } + } + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &mut out)); + out +} + +/// The path of object `n` in document coordinates: a path's own, or a compound path's members'. +fn path_of(n: &Node) -> Option { + match &n.kind { + NodeKind::Path { path, .. } => Some(path.clone()), + NodeKind::Compound { children, .. } => Some(PathData::new( + children + .iter() + .filter_map(|c| match &c.kind { + NodeKind::Path { path, .. } => Some(path.subpaths.iter().cloned()), + _ => None, + }) + .flatten() + .collect(), + )), + _ => None, + } +} + +/// Whether object `id` is on a layer, or a sublayer, that does not print. +fn on_non_printing_layer(d: &Document, id: NodeId) -> bool { + d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. })) +} + +fn kind(role: Role) -> LineKind { + match role { + Role::Cut => LineKind::Cut, + Role::Crease => LineKind::Crease, + Role::PartialCut => LineKind::PartialCut, + Role::Perforation => LineKind::Perforation, + } +} + +fn check(s: &mut Session, p: &Value) -> Result { + let select = switch_or(p, "select", false, CHECK)?; + let tolerance = match length_given(p, "tolerance", CHECK)? { + None => TOLERANCE.1, + Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t, + Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), + }; + let given = p.get("ids").is_some_and(|v| !v.is_null()); + let roots = checked_ids_or_selection(s, p, CHECK)?; + let d = &s.doc()?.doc; + // Hidden lines are left out in every scope, members of a selected group included. + let shown = |ids: Vec| ids.into_iter().filter(|id| d.is_visible(*id)).collect::>(); + let (scope, targets) = match (given, roots.is_empty()) { + (true, _) => ("ids", shown(role_targets(d, &roots, false).0)), + (false, false) => ("selection", shown(role_targets(d, &roots, false).0)), + (false, true) => ("document", shown_targets(d)), + }; + let table = RoleTable::of(d); + let mut lines = vec![]; + let mut non_printing = vec![]; + let mut segments = 0usize; + for id in targets { + // Once the lines have more segments than the check takes, it reports them as too complex: + // the rest are not copied. + if segments > MAX_SEGMENTS { + break; + } + let Some(n) = d.node(id) else { continue }; + let (Some(role), Some(path)) = (table.role_of(n), path_of(n)) else { continue }; + if on_non_printing_layer(d, id) { + non_printing.push(id.0); + } + segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); + lines.push(FoldLine { path, kind: kind(role), key: id.0 }); + } + let (found, mut issues) = blanks(&lines, tolerance); + if !non_printing.is_empty() { + issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None }); + } + let ok = !issues.iter().any(|i| i.code.is_error()); + let rows: Vec = issues + .iter() + .map(|i| { + let mut row = json!({ + "severity": if i.code.is_error() { "error" } else { "warning" }, + "code": i.code.id(), + "message": message(i.code, scope), + "ids": i.keys, + }); + if let (Some(at), Some(o)) = (i.at, row.as_object_mut()) { + o.insert("at".into(), json!([at.x, at.y])); + } + row + }) + .collect(); + if select { + let mut ids: Vec = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect(); + ids.sort_unstable_by_key(|id| id.0); + ids.dedup(); + if !ids.is_empty() { + s.select(|_, sel| sel.set(ids.iter().copied()))?; + } + } + Ok(json!({ + "ok": ok, + "blanks": found.len(), + "panels": found.iter().map(|b| b.panels.len()).sum::(), + "hinges": found.iter().map(|b| b.hinges.len()).sum::(), + "holes": found.iter().map(|b| b.holes.len()).sum::(), + "issues": rows, + "scope": scope, + })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/check/tests.rs b/crates/engine/src/cmd/addons/packaging/check/tests.rs new file mode 100644 index 0000000000..9940761dea --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/check/tests.rs @@ -0,0 +1,180 @@ +//! Tests for Check Fold Lines: the blanks, panels, hinges and issues of fold lines drawn in a +//! document. + +use serde_json::{Value, json}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn check(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.check", &p).unwrap() +} + +fn codes(r: &Value) -> Vec<&str> { + r["issues"].as_array().unwrap().iter().map(|i| i["code"].as_str().unwrap()).collect() +} + +/// A tray blank: a 100 pt base with a 40 pt wall on each side, its outline a cut line and the +/// base's four sides creases → (outline, creases). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +#[test] +fn a_tray_checks_clean_with_five_panels_and_four_hinges() { + let mut s = session(); + tray(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + let r = check(&mut s, json!({})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!((r["blanks"].as_u64(), r["panels"].as_u64(), r["hinges"].as_u64(), r["holes"].as_u64()), (Some(1), Some(5), Some(4), Some(0)), "{r}"); + assert!(codes(&r).is_empty(), "{r}"); + assert_eq!(r["scope"], "document"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a check records no undo step"); +} + +#[test] +fn the_selection_or_ids_limit_the_check_to_their_lines() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + s.execute("select.set", &json!({ "ids": [creases[0]] })).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!((r["scope"].as_str(), r["ok"].as_bool()), (Some("selection"), Some(false))); + assert_eq!(codes(&r), ["noCut"]); + assert_eq!(r["issues"][0]["message"], "No cut lines are in the selection."); + let r = check(&mut s, json!({ "ids": [outline] })); + assert_eq!((r["scope"].as_str(), r["ok"].as_bool(), r["panels"].as_u64()), (Some("ids"), Some(true), Some(1)), "{r}"); + let r = check(&mut s, json!({ "ids": [creases[1]] })); + assert_eq!((r["scope"].as_str(), codes(&r)), (Some("ids"), vec!["noCut"])); + assert_eq!(r["issues"][0]["message"], "No cut lines are among the given objects."); + // No fold lines at all in the document. + let mut s = session(); + let r = check(&mut s, json!({})); + assert_eq!(codes(&r), ["noCut"]); + assert_eq!(r["issues"][0]["message"], "No cut lines are in the document."); +} + +#[test] +fn issues_name_their_lines_and_select_selects_them() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // A slit from the outline that stops in the middle of the base. + let slit = path(&mut s, "M190 100 L190 190"); + role(&mut s, "cut", &[slit]); + s.execute("select.none", &json!({})).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!(r["ok"], false); + let loose = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "looseEnd").cloned().unwrap(); + assert_eq!((loose["severity"].as_str(), loose["ids"].clone()), (Some("error"), json!([slit])), "{r}"); + assert_eq!(loose["at"], json!([190.0, 190.0])); + assert!(s.doc().unwrap().selection.objects.is_empty(), "without select, the selection stays"); + let r = check(&mut s, json!({ "select": true })); + let named: std::collections::BTreeSet = + r["issues"].as_array().unwrap().iter().flat_map(|i| i["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap())).collect(); + let selected: std::collections::BTreeSet = s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + assert!(selected.contains(&slit) && selected == named, "{selected:?} {named:?}"); + assert!(!selected.contains(&creases[1])); +} + +#[test] +fn a_clean_check_with_select_leaves_the_selection_alone() { + let mut s = session(); + let (outline, _) = tray(&mut s); + s.execute("select.set", &json!({ "ids": [outline] })).unwrap(); + let r = check(&mut s, json!({ "ids": [outline], "select": true })); + assert!(codes(&r).is_empty(), "{r}"); + assert_eq!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::>(), [outline]); +} + +#[test] +fn tolerance_is_checked_and_joins_gaps_up_to_it() { + let mut s = session(); + tray(&mut s); + for bad in [json!(0.005), json!(10.5), json!("x"), json!(true)] { + let e = s.execute("addon.packaging.check", &json!({ "tolerance": bad })).unwrap_err().to_string(); + assert!(e.contains("tolerance"), "{e}"); + } + let e = s.execute("addon.packaging.check", &json!({ "select": 1 })).unwrap_err().to_string(); + assert!(e.contains("select"), "{e}"); + for edge in [json!(0.01), json!(10), json!("2 mm")] { + assert_eq!(check(&mut s, json!({ "tolerance": edge }))["ok"], true); + } + // A slit that stops 0.5 pt short of a crease: a gap at a tolerance of 1 pt, a loose end at 0.1 pt. + let mut s = session(); + tray(&mut s); + let slit = path(&mut s, "M190 100 L190 139.5"); + role(&mut s, "cut", &[slit]); + s.execute("select.none", &json!({})).unwrap(); + assert!(codes(&check(&mut s, json!({ "tolerance": 0.1 }))).contains(&"looseEnd")); + let near = check(&mut s, json!({ "tolerance": 1 })); + assert!(!codes(&near).contains(&"looseEnd"), "{near}"); +} + +#[test] +fn hidden_lines_are_left_out_and_lines_on_a_non_printing_layer_are_noted() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // A hidden crease is not checked while nothing is selected: the tray has three hinges and a + // panel joined by none. + s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}"); + // The same in a selected group, and with the group named by `ids`: the hidden member is left + // out too. + let mut s = session(); + let (outline, creases) = tray(&mut s); + s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3]] })).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap(); + s.execute("select.set", &json!({ "ids": [group] })).unwrap(); + for p in [json!({}), json!({ "ids": [group] })] { + let r = check(&mut s, p); + assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}"); + } + // A cut line on a layer that does not print. + let mut s = session(); + s.execute("layer.new", &json!({ "printable": false })).unwrap(); + let (outline, _) = tray(&mut s); + let r = check(&mut s, json!({})); + assert_eq!(r["ok"], true, "a warning only"); + let note = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "nonPrinting").cloned().unwrap(); + assert_eq!(note["severity"], "warning"); + assert!(note["ids"].as_array().unwrap().contains(&json!(outline)), "{note}"); + assert_eq!(note["message"], "A fold line is on a non-printing layer."); +} + +#[test] +fn a_compound_path_and_a_grouped_line_are_checked() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + // A window: a closed cut line in the base, made a compound path with nothing else. + let window = path(&mut s, "M170 170 L210 170 L210 210 L170 210 Z"); + s.execute("select.set", &json!({ "ids": [window] })).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64(); + let window = compound.unwrap_or(window); + role(&mut s, "cut", &[window]); + s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3], window] })).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!(r["scope"], "selection"); + assert_eq!((r["ok"].as_bool(), r["panels"].as_u64(), r["holes"].as_u64()), (Some(true), Some(5), Some(1)), "{r}"); +} diff --git a/crates/engine/src/cmd/addons/packaging/roles.rs b/crates/engine/src/cmd/addons/packaging/roles.rs index 010384c6c2..2b3c7696f3 100644 --- a/crates/engine/src/cmd/addons/packaging/roles.rs +++ b/crates/engine/src/cmd/addons/packaging/roles.rs @@ -186,7 +186,7 @@ fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String { /// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a /// guide, or a compound path. -fn can_carry(n: &Node) -> bool { +pub(super) fn can_carry(n: &Node) -> bool { match &n.kind { NodeKind::Path { clipping, guide, .. } => !clipping && !guide, NodeKind::Compound { .. } => true, @@ -199,7 +199,7 @@ fn can_carry(n: &Node) -> bool { /// how many of `roots` and their members can't (text, images, symbol instances and other objects). /// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or /// are on a locked artboard are left out and counted as skipped. -fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec, usize) { +pub(super) fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec, usize) { fn walk(n: &Node, out: &mut Vec, skipped: &mut usize) { match &n.kind { NodeKind::Group { children, .. } => { diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index 4376cbe791..8102777687 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -96,7 +96,8 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { }; return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() })); } - let center = (centerline && (a.center() - b.center()).hypot() > 1e-9).then(|| (a.center(), b.center())); + // Centers closer than a billionth of the larger path's size count as one point: no line. + let center = (centerline && (a.center() - b.center()).hypot() > 1e-9 * a.size().max(b.size())).then(|| (a.center(), b.center())); let fill = Paint::None; let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() }; let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1)); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index 5ed6e2b0d6..aef694bbdd 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -162,6 +162,19 @@ fn a_convex_bezier_path_and_the_centerline() { } } +#[test] +fn tiny_paths_close_together_still_get_the_centerline() { + // Two circles a ten-billionth of a point wide, half a billionth apart: separate, with all four + // tangents, and centers apart by far more than their sizes' rounding. + let mut s = session(); + let a = circle(&mut s, 1.0, 1.0, 1e-10); + let b = circle(&mut s, 1.0 + 5e-10, 1.0, 1e-10); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + assert_eq!(r["ids"].as_array().map(Vec::len), Some(5), "{r}"); + assert_eq!(r["centerline"], r["ids"][4]); +} + #[test] fn the_lines_take_the_current_stroke_and_no_fill() { let mut s = session(); diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 1f9490f24e..c4f35dfc3f 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -27,6 +27,9 @@ use crate::EngineError; /// Whether Reset Transformation changes a symbol instance. pub use symbols::reset_transformation_changes; +/// The Symbols panel's current symbol, as `symbol.list` answers it. +pub use symbols::current_symbol; + mod brushes; mod dynamic; mod symbols; diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 9b718c61b4..cecd314858 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -162,7 +162,7 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result { if d.symbols.is_sorted_by_key(key) { return ok(); } - let current = current_symbol(d).or_else(|| symbol_names(d).into_iter().next()); + let current = current_symbol(d); s.edit("Sort by Name", |d, _| { if let Some(name) = current { d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); @@ -173,12 +173,15 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result { ok() } -fn symbol_names(d: &Document) -> Vec { - d.symbols.iter().map(|s| s.name.clone()).collect() -} - -fn current_symbol(d: &Document) -> Option { - d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string) +/// The Symbols panel's current symbol, as `symbol.list` answers it: the stored current symbol +/// while `d` has a symbol of that name, else the first symbol; `None` when `d` has no symbols. +pub fn current_symbol(d: &Document) -> Option { + d.unknown + .get(CURRENT_SYMBOL) + .and_then(Value::as_str) + .filter(|n| d.symbols.iter().any(|s| s.name == *n)) + .or_else(|| d.symbols.first().map(|s| s.name.as_str())) + .map(str::to_string) } pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result { @@ -200,7 +203,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result { }) }) .collect(); - Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) })) + Ok(json!({ "symbols": list, "current": current_symbol(d) })) } /// Store `art` ([`normalize`]d, of natural size `size`) as symbol `name`, which becomes the @@ -398,9 +401,7 @@ fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result { match str_param(p, "name") { Some(n) if d.symbols.iter().any(|s| s.name == n) => Ok(n.to_string()), Some(n) => Err(bad(cmd, format!("no symbol named `{n}`"))), - None => { - current_symbol(d).or_else(|| symbol_names(d).into_iter().next()).ok_or_else(|| EngineError::Other("the document has no symbols".into())) - } + None => current_symbol(d).ok_or_else(|| EngineError::Other("the document has no symbols".into())), } } diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 98aa9ae490..39dc0db8a2 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Live Paint Bucket (Stroke)", [], None, - "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}", + "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; also paints every edge of the group, hidden edges skipped, that the polyline crosses or comes within 0.0001 pt of), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}", has_doc, lp_stroke_edge ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index a030f5bd8f..7938c07879 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -409,43 +409,61 @@ fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result