Merge main into fix/issue-8090

This commit is contained in:
dotCooCoo
2026-11-16 11:40:23 -08:00
179 changed files with 15181 additions and 874 deletions
Generated
+2
View File
@@ -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",
]
+1
View File
@@ -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.
+3
View File
@@ -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
+3 -2
View File
@@ -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};
+7 -7
View File
@@ -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).
+2
View File
@@ -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 }
+4
View File
@@ -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;
+6 -2
View File
@@ -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<CommandSpec> {
roles::specs()
let mut v = roles::specs();
v.extend(check::specs());
v
}
#[cfg(test)]
@@ -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<CommandSpec> {
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<NodeId> {
fn walk(n: &Node, out: &mut Vec<NodeId>) {
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<PathData> {
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<Value> {
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<NodeId>| ids.into_iter().filter(|id| d.is_visible(*id)).collect::<Vec<_>>();
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<Value> = 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<NodeId> = 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::<usize>(),
"hinges": found.iter().map(|b| b.hinges.len()).sum::<usize>(),
"holes": found.iter().map(|b| b.holes.len()).sum::<usize>(),
"issues": rows,
"scope": scope,
}))
}
#[cfg(test)]
mod tests;
@@ -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<u64>) {
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<u64> =
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<u64> = 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::<Vec<_>>(), [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}");
}
@@ -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<NodeId>, usize) {
pub(super) fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
fn walk(n: &Node, out: &mut Vec<NodeId>, skipped: &mut usize) {
match &n.kind {
NodeKind::Group { children, .. } => {
@@ -96,7 +96,8 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
};
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));
@@ -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();
+3
View File
@@ -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;
+12 -11
View File
@@ -162,7 +162,7 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result<Value> {
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<Value> {
ok()
}
fn symbol_names(d: &Document) -> Vec<String> {
d.symbols.iter().map(|s| s.name.clone()).collect()
}
fn current_symbol(d: &Document) -> Option<String> {
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<String> {
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<Value> {
@@ -200,7 +203,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
})
})
.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<String> {
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())),
}
}
+1 -1
View File
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
+49 -22
View File
@@ -409,43 +409,61 @@ fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result<Option
serde_json::from_value::<super::Paint>(v.clone()).map(Some).map_err(|_| bad(c, "match must be a paint as the document stores it"))
}
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "livePaint.fill";
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
/// The drag path of `livePaint.fill` or `livePaint.strokeEdge` (command `c`) pressed at `start`:
/// `points` followed by each chunk of `continuation`, where every chunk holds 1 to
/// [`b::LP_FILL_CHUNK_POINTS`] finite canvas points and starts at the last point of the chunk
/// before it (`points` at `start`). None when `points` is left out. With a `scope` other than
/// `one`, `points` is an error.
fn path_param(p: &Value, c: &str, start: Point, scope: LpScope) -> Result<Option<Vec<Vec<Point>>>> {
if scope != LpScope::One && p.get("points").is_some() {
return Err(bad(C, "scope applies to a click: leave out points"));
return Err(bad(c, "scope applies to a click: leave out points"));
}
let parse_chunk = |input: &Value, start: Point| -> Result<Vec<Point>> {
let values = input
.as_array()
.filter(|points| !points.is_empty() && points.len() <= b::LP_FILL_CHUNK_POINTS)
.ok_or_else(|| bad(C, "each path chunk must contain 1 to 4096 points"))?;
.ok_or_else(|| bad(c, "each path chunk must contain 1 to 4096 points"))?;
let points: Vec<_> = values
.iter()
.map(|point| {
let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(C, "points must be [x,y] pairs"))?;
let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(C, "point x must be a number"))?;
let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(C, "point y must be a number"))?;
let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(c, "points must be [x,y] pairs"))?;
let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(c, "point x must be a number"))?;
let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(c, "point y must be a number"))?;
let point = Point::new(x, y);
if !finite(point) {
return Err(bad(C, "points must be finite canvas points"));
return Err(bad(c, "points must be finite canvas points"));
}
Ok(point)
})
.collect::<Result<_>>()?;
if points.first() != Some(&start) {
return Err(bad(C, "path chunks must share their boundary point"));
return Err(bad(c, "path chunks must share their boundary point"));
}
Ok(points)
};
let points = p.get("points");
let Some(points) = p.get("points") else {
return if p.get("continuation").is_some() { Err(bad(c, "continuation requires points")) } else { Ok(None) };
};
let continuation = match p.get("continuation") {
None => &[][..],
Some(input) if points.is_some() => input.as_array().ok_or_else(|| bad(C, "continuation must be an array of path chunks"))?.as_slice(),
Some(_) => return Err(bad(C, "continuation requires points")),
Some(input) => input.as_array().ok_or_else(|| bad(c, "continuation must be an array of path chunks"))?.as_slice(),
};
let mut chunks: Vec<Vec<Point>> = Vec::with_capacity(continuation.len() + 1);
let mut last = start;
for input in std::iter::once(points).chain(continuation) {
let chunk = parse_chunk(input, last)?;
last = chunk.last().copied().unwrap_or(last);
chunks.push(chunk);
}
Ok(Some(chunks))
}
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "livePaint.fill";
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
let path = path_param(p, C, pt, scope)?;
crate::cmd::paint::check_keep_model(p, C)?;
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
let group = object_param(p, "group", C)?;
@@ -472,7 +490,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
targets.extend(b::faces(n).into_iter().filter(|f| f.visible && f.appearance.fill_paint() == like).map(|f| f.id));
}
}
if let Some(points) = points {
if let Some(chunks) = &path {
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
// Use the existing region-crossing probes, so even a face narrower than the distance
// between pointer events is filled. Reversing matches visible_face_at's front first.
@@ -488,11 +506,8 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let map = b::BuilderMap { regions, ..Default::default() };
let mut last = pt;
for input in std::iter::once(points).chain(continuation) {
let chunk = parse_chunk(input, last)?;
last = chunk.last().copied().unwrap_or(last);
targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
for chunk in chunks {
targets.extend(map.hits_along(chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
}
}
Ok((fid, targets))
@@ -567,6 +582,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
let path = path_param(p, C, pt, scope)?;
let through: Vec<NodeId> = match p.get("through") {
None => vec![],
Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")),
@@ -590,7 +606,18 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let eid = start.id;
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
let targets = match scope {
LpScope::One => vec![eid],
// A drag also reaches every edge of the group that is not hidden and that its path
// crosses or touches.
LpScope::One => std::iter::once(eid)
.chain(
path.as_deref()
.map(|chunks| b::visible_edges_along(n, chunks))
.unwrap_or_default()
.into_iter()
.map(|e| e.id)
.filter(|id| *id != eid),
)
.collect(),
LpScope::Connected => b::connected_edges_through(n, eid, &like, &through),
LpScope::SamePaint => std::iter::once(eid)
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
+51 -19
View File
@@ -64,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Arc",
[],
None,
"{x1, y1, x2, y2, closed?, slope?} or {x, y, lengthX, lengthY, reference?, baseAlong?: x|y, slope?, closed?, fillArc?} → {id}",
"{x1, y1, x2, y2, closed?, slope?: −100…100 (default 100), rotation?: deg clockwise about (x1, y1)} or {x, y, lengthX, lengthY, reference?: 0–8 (default 0), baseAlong?: x|y (either case; default x), slope?: −100…100 (default 50), closed?, fillArc?, rotation?: deg clockwise about the reference point (x, y)} (0: upright); a reference or baseAlong given as anything else (null included) or a slope outside its range is an error and draws nothing → {id}",
has_doc,
arc
),
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rectangular Grid",
[],
None,
"{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
"{x, y, width, height, rows=5, columns=5 (whole numbers; at most 999), rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
rect_grid
),
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Polar Grid",
[],
None,
"{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
"{x, y, width, height, concentric=5, radial=5 (whole numbers; at most 999), concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
polar_grid
),
@@ -299,7 +299,8 @@ fn path_kind(path: PathData, live: Option<LiveShape>) -> NodeKind {
/// (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>):
/// a box (rectangle, ellipse, grid) runs along the turned axes from `pivot`, the point the dialog
/// placed at the click (its top-left corner `x`, `y`, or a grid's reference point), which stays
/// put; a polygon or star turns its base orientation about its centre. The params as they are at
/// put; an arc sized by its lengths turns about its reference point `x`, `y`, which the dialog
/// placed at the click; a polygon or star turns its base orientation about its centre. The params as they are at
/// 0° or a whole turn, for other commands and when they already carry a `rotation`.
pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) -> Value {
let base = s.prefs.constrain_angle;
@@ -318,6 +319,9 @@ pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point)
"shape.polygon" | "shape.star" => {
o.insert("rotation".into(), json!(rotation));
}
"shape.arc" if o.contains_key("lengthX") || o.contains_key("lengthY") => {
o.insert("rotation".into(), json!(rotation));
}
_ => {}
}
params
@@ -590,26 +594,56 @@ fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
}
fn arc(s: &mut Session, p: &Value) -> Result<Value> {
let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "shape.arc")? } else { 0.0 };
if !rotation.is_finite() {
return Err(bad("shape.arc", "rotation must be finite"));
}
let closed = switch_or(p, "closed", false, "shape.arc")?;
let fill_arc = switch_or(p, "fillArc", false, "shape.arc")?;
let base_x = !matches!(p.get("baseAlong").and_then(Value::as_str), Some("y" | "Y"));
let path = if p.get("lengthX").is_some() || p.get("lengthY").is_some() {
// Given values are checked in both forms, null included; only a left-out key takes its default.
let base_x = match p.get("baseAlong") {
None => true,
Some(Value::String(v)) if v.eq_ignore_ascii_case("x") || v.eq_ignore_ascii_case("y") => v.eq_ignore_ascii_case("x"),
Some(_) => return Err(bad("shape.arc", "`baseAlong` must be one of x, y")),
};
let reference = match p.get("reference") {
None => 0,
Some(v) => match (v.as_u64(), v.as_f64()) {
(Some(n), _) if n <= 8 => n as usize,
(None, Some(x)) if (0.0..=8.0).contains(&x) && x.fract() == 0.0 => x as usize,
_ => return Err(bad("shape.arc", "`reference` must be a whole number from 0 to 8")),
},
};
let slope = |default: f64| {
let (key, lo, hi) = ("slope", -100.0, 100.0);
let v = number_or(p, key, default, "shape.arc")?;
if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad("shape.arc", format!("`{key}` must be from {lo} to {hi}, not {v}"))) }
};
// The upright path, and the point `rotation` turns it about.
let (path, pivot) = if p.get("lengthX").is_some() || p.get("lengthY").is_some() {
let anchor = Point::new(f64_req(p, "x", "shape.arc")?, f64_req(p, "y", "shape.arc")?);
let reference = p.get("reference").and_then(Value::as_u64).unwrap_or(0) as usize;
shapes::arc_segment(
let path = shapes::arc_segment(
anchor,
reference,
number_or(p, "lengthX", 100.0, "shape.arc")?,
number_or(p, "lengthY", 100.0, "shape.arc")?,
base_x,
number_or(p, "slope", 50.0, "shape.arc")?,
slope(50.0)?,
closed,
)
);
(path, anchor)
} else {
let a = Point::new(f64_req(p, "x1", "shape.arc")?, f64_req(p, "y1", "shape.arc")?);
let b = Point::new(f64_req(p, "x2", "shape.arc")?, f64_req(p, "y2", "shape.arc")?);
let slope = number_or(p, "slope", 100.0, "shape.arc")?;
shapes::arc(a, b, slope, closed, base_x)
(shapes::arc(a, b, slope(100.0)?, closed, base_x), a)
};
// 0 and whole turns leave the path as it is; quarter turns are exact.
let bbox_angle = bbox_turn(rotation);
let path = if bbox_angle == 0.0 {
path
} else {
let c = pivot.to_vec2();
path.transformed(Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c))
};
let fill = if fill_arc { s.paint.fill.clone() } else { vectorcraft_color::Paint::None };
let look = s.new_art_look(
@@ -617,7 +651,7 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
s.paint.stroke_width.max(0.1),
);
add_look(s, "Arc", path_kind(path, None), look, None)
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle)
}
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
@@ -655,13 +689,11 @@ fn grid_group(s: &mut Session, label: &str, (paths, bbox_angle): (Vec<PathData>,
Ok(json!({ "id": id.0 }))
}
/// A grid's divider count `count` (an error unless it is a number or null; 5 unless it is a JSON
/// whole number of 0 or more, so 4.0 gives 4 and 2.5 gives 5; at most 999) with its skew `key` in percent (0 when
/// absent, clamped to ±[`shapes::GRID_SKEW_MAX`]).
/// A grid's divider count `count` (5 when absent or null; a whole number of 0 or more, so 4.0 gives
/// 4, and anything else, such as 2.5, -1 or `"3"`, is an error; at most 999) with its skew `key` in
/// percent (0 when absent, clamped to ±[`shapes::GRID_SKEW_MAX`]).
fn dividers(p: &Value, count: &str, key: &str, cmd: &str) -> Result<(u32, f64)> {
check_numbers(p, &[count], cmd)?;
let whole = |v: &Value| v.as_u64().or_else(|| v.as_f64().filter(|f| f.is_finite() && *f >= 0.0 && f.fract() == 0.0).map(|f| f as u64));
let n = p.get(count).and_then(whole).unwrap_or(5).min(999) as u32;
let n = count_or(p, count, 5, cmd)?.min(999) as u32;
let skew = match p.get(key) {
None | Some(Value::Null) => 0.0,
Some(v) => v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?,
+1 -1
View File
@@ -31,6 +31,6 @@ mod freehand;
mod smooth;
pub use commands::specs;
pub(super) use common::{ids_json, replace_with_pieces, usize_opt};
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt};
pub(super) use cut::{components, erase_outline};
pub(super) use freehand::freehand_brushed;
+1 -1
View File
@@ -74,7 +74,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Split Path",
[],
None,
"{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}. A t outside 0–1 is refused with an error, and nothing changes",
"{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected; the paths keep the source's fill and stroke settings except that every stroke's alignment becomes Center (in a path of several subpaths, the other subpaths' strokes too) → {ids}. A t outside 0–1 is refused with an error, and nothing changes",
has_doc,
split
),
+20
View File
@@ -406,6 +406,26 @@ pub(super) fn sibling_with(d: &mut Document, id: NodeId, pd: PathData) -> Result
Ok(n)
}
/// Set every stroke of node `id`, and every stroke of the compound path it is a member of (whose
/// strokes its members show), to Center alignment. Every other stroke and fill setting stays as it
/// is, and an appearance whose strokes are all centered stays shared with its other copies.
pub(in super::super) fn center_strokes(d: &mut Document, id: NodeId) {
use vectorcraft_doc::{AppearanceItem, StrokeAlign};
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
for n in [Some(id), parent].into_iter().flatten() {
let Some(n) = d.node_mut(n) else { continue };
let off = |it: &AppearanceItem| matches!(it, AppearanceItem::Stroke(st) if st.align != StrokeAlign::Center);
if !n.appearance.items.iter().any(off) {
continue;
}
for it in &mut n.appearance.items {
if let AppearanceItem::Stroke(st) = it {
st.align = StrokeAlign::Center;
}
}
}
}
/// Replace path or compound path `id` with `pieces` (first keeps the id, the rest go right above
/// it; none removes it). `cut` removes the path or puts the other pieces above it. Returns ids.
pub(in super::super) fn replace_with_pieces(d: &mut Document, cut: &mut Beside, id: NodeId, pieces: Vec<PathData>) -> Result<Vec<NodeId>> {
+6 -2
View File
@@ -1,6 +1,6 @@
use super::common::{
PenRecord, SIZE_VARIATIONS, SIZES, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds,
pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param,
poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
};
use super::{
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
@@ -225,14 +225,17 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
sel.add(id);
sel.anchors.entry(id).or_default().insert((si, 0));
};
// The paths a cut makes keep the source's appearance with every stroke centered.
if sp.closed {
path.subpaths[si] = pieces.pop().ok_or_else(|| EngineError::Other("no such anchor".into()))?;
center_strokes(d, id);
pick(sel, id, si);
return Ok(vec![id]);
}
let [left, right] = <[SubPath; 2]>::try_from(pieces).map_err(|_| EngineError::Other("cannot split an open path at its end point".into()))?;
if path.subpaths.len() == 1 {
path.subpaths[0] = left;
center_strokes(d, id);
let node = sibling_with(d, id, PathData::single(right))?;
let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
let nid = d.insert(parent, idx + 1, node)?;
@@ -241,6 +244,7 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
} else {
path.subpaths[si] = left;
path.subpaths.insert(si + 1, right);
center_strokes(d, id);
pick(sel, id, si + 1);
Ok(vec![id])
}
+1 -1
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export for Screens",
["File", "Export"],
None,
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
has_doc,
screens::export_for_screens
),
+9 -3
View File
@@ -350,8 +350,8 @@ struct ScreenParams {
/// Where files go: `none` (all in the folder), `rows` (the rows' sub-folders, as
/// `subfolders`), `format` (a folder per extension), `item`, or `itemFormat`.
folders: Option<String>,
/// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file) or
/// `multiple` (a file per artboard, the default).
/// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file; refused
/// with assets, layers or `selection: "each"`) or `multiple` (a file per artboard, the default).
pdfs: Option<String>,
}
@@ -399,12 +399,18 @@ impl ScreenParams {
if p.is_object() { Self::deserialize(p).map_err(|e| bad(C, e.to_string())) } else { Ok(Self::default()) }
}
/// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given.
/// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given,
/// and when `pdfs: "single"` is given with `assets`, `layers` or `selection: "each"`, whose
/// files each hold the art of one item.
fn one_source(&self) -> Result<()> {
let sources = [self.full_document, self.assets.is_some(), self.layers.is_some(), self.selection.is_some()].iter().filter(|b| **b).count();
if sources > 1 {
return Err(bad(C, "give one of assets, layers, selection or fullDocument"));
}
let per_piece = self.assets.is_some() || self.layers.is_some() || self.selection.as_deref() == Some("each");
if per_piece && self.pdfs.as_deref() == Some("single") {
return Err(bad(C, "pdfs `single` writes artboards as the pages of one PDF: assets, layers and selection `each` write a PDF each"));
}
Ok(())
}
@@ -1245,6 +1245,41 @@ fn single_file_pdfs_hold_every_chosen_artboard() {
assert!(s.execute("document.exportForScreens", &json!({"pdfs": "both", "formats": [{"format": "pdf"}]})).is_err());
}
/// Export PDFs As › Single file holds artboards: with assets, layers or a file per selected object,
/// whose files each hold one item's art, it is refused (the Example line too) instead of writing
/// the first item alone under the document's name; Multiple files writes a PDF of each item. The
/// selection as one file is one PDF either way.
#[test]
fn single_file_pdfs_are_refused_for_assets_layers_and_each_object() {
let mut s = session(1);
s.execute("layer.new", &json!({"name": "Second"})).unwrap();
s.execute("shape.ellipse", &json!({"x": 30, "y": 5, "width": 8, "height": 8})).unwrap();
let doc = s.doc().unwrap().doc.clone();
let layers: Vec<u64> = doc.layers.iter().map(|l| l.id.0).collect();
let art: Vec<u64> = doc.layers.iter().filter_map(|l| l.children()).flatten().map(|c| c.id.0).collect();
assert_eq!((layers.len(), art.len()), (2, 2));
let a = s.execute("assets.add", &json!({"ids": [art[0]], "name": "Square"})).unwrap()["assets"][0].as_u64().unwrap();
let b = s.execute("assets.add", &json!({"ids": [art[1]], "name": "Dot"})).unwrap()["assets"][0].as_u64().unwrap();
s.execute("select.all", &json!({})).unwrap();
let pdf = json!([{"format": "pdf"}]);
for source in [json!({"assets": [a, b]}), json!({"layers": layers}), json!({"selection": "each"})] {
let mut p = source.clone();
p["formats"] = pdf.clone();
p["pdfs"] = json!("multiple");
let r = export(&mut s, p.clone());
assert_eq!(names(&r).len(), 2, "a PDF each: {:?} ({source})", names(&r));
for (name, bytes) in files(&r) {
assert_eq!(vectorcraft_pdf::import(&bytes).unwrap().artboards.len(), 1, "{name}");
}
p["pdfs"] = json!("single");
let e = s.execute("document.exportForScreens", &p).unwrap_err().to_string();
assert!(e.contains("pdfs `single`"), "{e} ({source})");
assert!(super::screens::first_file(&s, &p).is_err(), "{source}");
}
let r = export(&mut s, json!({"selection": "one", "pdfs": "single", "formats": pdf}));
assert_eq!(names(&r), ["Selection.pdf"]);
}
/// The warnings of reply `r` that name an option the file doesn't read.
fn unused(r: &Value) -> Vec<String> {
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
+1 -1
View File
@@ -58,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Show Similar Fonts",
[],
None,
"{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000",
"{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind; a family that shares none of these numbers with it comes after those that share one); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000",
always,
similar_fonts
),
+1 -1
View File
@@ -244,7 +244,7 @@ impl Gen<'_> {
let slot = g.series_paints.get(s);
let fill =
slot.and_then(|p| p.fill.clone().or_else(|| p.stroke.clone().filter(|st| !st.is_none()))).unwrap_or_else(|| default_series_paint(s));
return self.path(band, fill, Paint::solid(Color::BLACK), 0.25);
return self.path(band, fill, Paint::solid(Color::BLACK), vectorcraft_doc::FILLED_LINE_OUTLINE_WIDTH);
}
let (fill, stroke, w) = series_marks(g, s, false, default_series_paint(s), 1.0);
self.path(pd, fill, stroke, w)
+52
View File
@@ -9505,6 +9505,58 @@ fn a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns() {
}
}
/// A line graph the graph tools draw with Draw Filled Lines, saved as `.ai` in either form, opens again as the same graph
/// with its filled lines and Line Width, the default 3 pt included, and without a warning about graphs. A Line Width past
/// the records' 100 pt is saved as the graph's art, with the warning.
#[test]
fn a_drawn_graph_with_filled_lines_saved_as_ai_opens_with_them() {
let dir = vectorcraft_testkit::temp_dir("graph-ai-filled");
for (width, live) in [(None, true), (Some(8.0), true), (Some(150.0), false)] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6";
let id = s.execute("graph.create", &json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap();
let mut options = json!({"id": id, "filledLines": true});
if let Some(w) = width {
options["lineWidth"] = json!(w);
}
s.execute("graph.setType", &options).unwrap();
let written = spec(&s, NodeId(id));
assert_eq!((written.filled_lines, written.line_width), (true, width));
for (name, version) in [("v7.ai", Some("7")), ("pdf.ai", None)] {
let path = dir.join(format!("{width:?}-{name}"));
let mut p = json!({"path": path, "format": "ai"});
if let Some(v) = version {
p["aiVersion"] = json!(v);
}
let r = s.execute("file.saveAs", &p).unwrap();
let notes = r["warnings"].as_array().cloned().unwrap_or_default();
let warned = notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art")));
assert_eq!(warned, !live, "{width:?} {name}: {r}");
let mut again = Session::new();
again.execute("document.open", &json!({"path": path})).unwrap();
let mut graphs = vec![];
again.doc().unwrap().doc.walk(|n| graphs.extend(n.extras().graph.as_deref().map(|g| (n.id, g.clone()))));
assert_eq!(graphs.len(), usize::from(live), "{width:?} {name}");
if let Some((gid, g)) = graphs.first() {
assert_eq!((g.kind, g.cells(), g.filled_lines, g.line_width), (written.kind, written.cells(), true, width), "{width:?} {name}");
assert_eq!(g.filled_line_width(), written.filled_line_width(), "{width:?} {name}");
// With Draw Filled Lines turned off, each series draws its thin 1 pt line again.
again.execute("select.set", &json!({"ids": [gid.0]})).unwrap();
again.execute("graph.setType", &json!({"id": gid.0, "filledLines": false})).unwrap();
for series in 0..2 {
let line = series_parts(&again, *gid, series)
.into_iter()
.any(|p| p.appearance.fill_paint().is_none() && !p.appearance.stroke_paint().is_none() && p.appearance.stroke_width() == 1.0);
assert!(line, "{width:?} {name}: series {series} draws no thin line");
}
}
}
}
}
/// A default legend swatch has the stroke paint and weight of its series' marks, beside the plot or across the top: the
/// thin white line of stacked columns and bars, areas and pie wedges, and none on columns and bars. A stroke color kept
/// on the series, with or without a weight of its own, is on the swatch too.
+1 -10
View File
@@ -6,6 +6,7 @@ use vectorcraft_doc::text::INLINE_MAX_SCALE;
use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun};
use vectorcraft_text::edit;
use super::brushsym::current_symbol;
use super::typecmd::refresh_bounds;
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, id_param, str_param};
@@ -97,13 +98,3 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(json!({"id": id.0, "caret": caret}))
}
/// The Symbols panel's current symbol, else the first one.
fn current_symbol(d: &Document) -> Option<String> {
d.unknown
.get("currentSymbol")
.and_then(Value::as_str)
.filter(|n| d.symbols.iter().any(|s| s.name == *n))
.map(str::to_string)
.or_else(|| d.symbols.first().map(|s| s.name.clone()))
}
+26 -9
View File
@@ -509,7 +509,16 @@ pub(crate) fn linked_files(d: &Document, base: LinkBase) -> Vec<LinkedFile> {
.filter(|g| seen.insert(g.link.path.clone()))
.map(|g| {
let named = fileio::format_for_name(g.link.name()).or_else(|| fileio::readable_format_for_name(g.link.name()));
let own = |b: &&ImageBlob| !b.is_proxy() && named.is_some_and(|f| f.mime == b.mime);
// A placed document's PostScript bytes are its file's own only when its name is one that
// PostScript is read from (`.eps`, `.epsf`, `.ps`, a PostScript `.ai` or `.ait`).
let postscript_name = matches!(fileio::extension(g.link.name()).as_str(), "eps" | "epsf" | "ps" | "ai" | "ait");
let postscript = |b: &ImageBlob| {
g.document.is_some()
&& postscript_name
&& b.mime == super::place::document::POSTSCRIPT
&& super::place::document::is_postscript(&b.bytes)
};
let own = |b: &&ImageBlob| !b.is_proxy() && (named.is_some_and(|f| f.mime == b.mime) || postscript(b));
let found = locate(&g.link, base);
let found_path = found.as_ref().map(|f| f.path.clone());
let bytes = found.and_then(|mut f| f.read().ok()).or_else(|| d.images.get(&g.key).filter(own).map(|b| b.bytes.to_vec()));
@@ -2361,12 +2370,20 @@ fn format_label(d: &Document, im: &ImageObject) -> &'static str {
.map_or("Image", |f| f.label)
}
/// A placed document's `links.list` fields: `format` (`VectorCraft`, or the PDF or `.ai` file's
/// format), `document: true` and its artboard's or page's size (`pageWidth`, `pageHeight`, pt)
/// instead of pixels.
fn document_row(p: &PlacedDocument) -> Value {
let pdf = fileio::format_for_name(p.link.name()).filter(|f| matches!(f.id, "pdf" | "ai" | "ait"));
json!({ "format": pdf.map_or("VectorCraft", |f| f.label), "document": true, "pageWidth": p.width, "pageHeight": p.height })
/// A placed document's `links.list` fields (of `d`): `format` (`VectorCraft`, the PDF or `.ai`
/// file's format, or for an EPS or PostScript file `EPS` or `PostScript`), `document: true` and its
/// artboard's or page's size (`pageWidth`, `pageHeight`, pt) instead of pixels. A PostScript `.ai`
/// is told by its stored bytes or, when a save kept only its preview, by its key.
fn document_row(d: &Document, p: &PlacedDocument) -> Value {
use super::place::document::{POSTSCRIPT, is_postscript_ai_key};
let postscript = d.images.get(&p.key).is_some_and(|b| b.mime == POSTSCRIPT) || is_postscript_ai_key(&p.key);
let format = match fileio::format_for_name(p.link.name()) {
Some(f) if matches!(f.id, "eps" | "ps") => f.label,
_ if postscript => "PostScript",
Some(f) if matches!(f.id, "pdf" | "ai" | "ait") => f.label,
_ => "VectorCraft",
};
json!({ "format": format, "document": true, "pageWidth": p.width, "pageHeight": p.height })
}
/// The size in bytes of the file that link `l` (of `st`) names, as Link Info shows it: the file's
@@ -2488,7 +2505,7 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
}
(im.link.as_ref(), row)
}
NodeKind::PlacedDocument(p) => (Some(&p.link), document_row(p)),
NodeKind::PlacedDocument(p) => (Some(&p.link), document_row(&doc, p)),
_ => continue,
};
let name = link.map_or_else(|| n.display_name(), |l| l.name().to_string());
@@ -2766,7 +2783,7 @@ fn placed_info(st: &crate::DocState, doc: &Document, id: NodeId) -> Result<Value
let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) };
let size = n.geometric_bounds().unwrap_or_default();
let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0));
let mut out = document_row(pl);
let mut out = document_row(doc, pl);
let fields = [
("id", json!(id.0)),
("name", json!(n.display_name())),
+3 -1
View File
@@ -149,7 +149,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Cut Path at Selected Anchor Points",
[],
None,
"{} cut the paths at their direct-selected anchors (one undo step): a closed path opens there, an open one becomes one path per piece; one of each cut's two coincident anchors stays selected → {ids}",
"{} cut the paths at their direct-selected anchors (one undo step): a closed path opens there, an open one becomes one path per piece; one of each cut's two coincident anchors stays selected; the paths keep the source's fill and stroke settings except that every stroke's alignment becomes Center (in a path of several subpaths, the other subpaths' strokes too) → {ids}",
has_anchors,
cut_at_anchors
),
@@ -1858,6 +1858,8 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
let (mut all, mut picked) = (vec![], vec![]);
let mut cut = Beside::replacing(d, &cuts.iter().map(|(id, ..)| *id).collect::<Vec<_>>());
for (id, subs, starts) in cuts {
// The paths a cut makes keep the source's appearance with every stroke centered.
super::draw2::center_strokes(d, id);
// A path of one subpath becomes one path per piece (the first keeps the id); the
// pieces of a compound shape stay subpaths of it.
if d.node(id).and_then(|n| n.path_data()).is_some_and(|pd| pd.subpaths.len() == 1) {
+162 -38
View File
@@ -9,7 +9,7 @@ use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer};
use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject};
use vectorcraft_geom::{FillRule, PathData};
use vectorcraft_geom::{FillRule, PathData, SubPath};
use vectorcraft_pathops as po;
use vectorcraft_pathops::{BoolOp, PathfinderOp};
@@ -352,6 +352,94 @@ pub(crate) fn pf_leaves(d: &Document, n: &Node, out: &mut Vec<Node>) {
}
}
/// The region a clip group's members show through: its clipping path's outline
/// ([`vectorcraft_render::effects::clip_outline`]), cut by the clip groups around it.
struct Clip {
path: PathData,
rule: FillRule,
}
/// Does `path` have an anchor or handle that isn't a finite number?
fn has_invalid_coordinates(path: &PathData) -> bool {
path.subpaths.iter().flat_map(|sp| &sp.anchors).any(|a| [a.p, a.h_in, a.h_out].iter().any(|q| !(q.x.is_finite() && q.y.is_finite())))
}
/// A Pathfinder operation's leaf shape ([`pf_leaves`]) with the region its clip groups show it
/// through, `None` outside any clip group.
type ClippedLeaf = (Node, Option<Arc<Clip>>);
/// [`pf_leaves`], each with the region the clip groups it is in show it through (#8093). A clip
/// group's clipping path is not a leaf, and the members of one whose clipping path clips by nothing
/// are hidden, as on the canvas: their region is empty.
fn clipped_pf_leaves(d: &Document, n: &Node, clip: Option<&Arc<Clip>>, precision: f64, out: &mut Vec<ClippedLeaf>) -> Result<()> {
let (NodeKind::Group { children, clip: clips } | NodeKind::Layer { children, clip: clips, .. }) = &n.kind else {
let mut lv = vec![];
leaves(n, &mut lv);
out.extend(lv.into_iter().map(|l| (l, clip.cloned())));
return Ok(());
};
let hook = |c: &Node| vectorcraft_render::effects::outline_object(Some(d), c);
if let Some(art) = vectorcraft_render::effects::compound_shape_art(Some(d), n, Some(&hook)) {
out.push((art, clip.cloned()));
return Ok(());
}
if !*clips {
return children.iter().try_for_each(|c| clipped_pf_leaves(d, c, clip, precision, out));
}
let Some((first, rest)) = children.split_first() else { return Ok(()) };
let mut region = match vectorcraft_render::effects::clip_outline(first) {
Some((outline, rule)) => Clip { path: PathData::from_bezpath(&outline), rule },
None => Clip { path: PathData::default(), rule: FillRule::NonZero },
};
if has_invalid_coordinates(&region.path) {
return Err(EngineError::Other("paths contain invalid coordinates".into()));
}
if let Some(outer) = clip.filter(|_| !region.path.is_empty()) {
let path = po::try_boolean(&region.path, region.rule, &outer.path, outer.rule, BoolOp::Intersect, precision)
.map_err(|e| EngineError::Other(e.to_string()))?;
region = Clip { path, rule: FillRule::NonZero };
}
let region = Arc::new(region);
rest.iter().try_for_each(|c| clipped_pf_leaves(d, c, Some(&region), precision, out))
}
/// `path`, filled by `rule`, where `clip` shows it: its area intersected with the region, filled
/// non-zero, and with `lines` (Divide, whose open contours cut) its open contours' parts inside the
/// region, so their hidden parts cut nothing.
fn clipped(path: PathData, rule: FillRule, clip: &Clip, lines: bool, precision: f64) -> Result<(PathData, FillRule)> {
if has_invalid_coordinates(&path) {
// Left as it is for the operation to refuse ("paths contain invalid coordinates").
return Ok((path, rule));
}
let (Some(within), Some(bounds)) = (clip.path.control_bounds(), path.control_bounds()) else { return Ok((PathData::default(), rule)) };
if within.intersect(bounds).is_zero_area() && !bounds.is_zero_area() {
// Wholly outside the region (a line's bounds may be flat, so only an area's are trusted).
return Ok((PathData::default(), rule));
}
let (open, closed): (Vec<SubPath>, Vec<SubPath>) =
if lines { path.subpaths.into_iter().partition(|sp| !sp.closed) } else { (vec![], path.subpaths) };
let mut subs = vec![];
if !closed.is_empty() {
let area = po::try_boolean(&PathData::new(closed), rule, &clip.path, clip.rule, BoolOp::Intersect, precision)
.map_err(|e| EngineError::Other(e.to_string()))?;
subs.extend(area.subpaths);
}
if !open.is_empty() {
let open = PathData::new(open);
// Each segment is sampled at least every 1/16 of the region's shorter side (and 24 times),
// and the crossings found are refined: a part of the region narrower than that, which a
// line crosses between two samples, can be missed.
let step = (within.width().min(within.height()) / 16.0).max(precision);
let outline = clip.path.to_bezpath();
let outside = |q| !vectorcraft_geom::hit::fill_contains(&outline, clip.rule, q);
match super::draw2::erase_outline(&open, step, &outside) {
Some(pieces) => subs.extend(pieces.into_iter().flat_map(|p| p.subpaths)),
None => subs.extend(open.subpaths),
}
}
Ok((PathData::new(subs), FillRule::NonZero))
}
/// How many shapes a Pathfinder operation takes from `n` selected alone: its leaf shapes, however
/// deep its groups nest (an expanded stroke is a group inside the group, #1635). Inside a compound
/// shape, a blend, an envelope or another live object and a symbol instance count as one shape
@@ -591,6 +679,10 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
}
let shape_mode =
matches!(op, PathfinderOp::Unite | PathfinderOp::MinusFront | PathfinderOp::Intersect | PathfinderOp::Exclude | PathfinderOp::MinusBack);
// An operand its clipping masks hide altogether is an empty shape for the operations whose
// result it changes (Intersect gives nothing, Minus Front loses its back object, Minus Back its
// front one, Crop its cropping shape); the others leave it out, which gives the same art.
let keeps_hidden = matches!(op, PathfinderOp::Intersect | PathfinderOp::MinusFront | PathfinderOp::MinusBack | PathfinderOp::Crop);
let label = pf_label(op);
let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?;
let ids = s.edit(label, |d, sel| {
@@ -598,63 +690,95 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
let mut styles: Vec<Style> = vec![];
let mut shapes: Vec<po::Shape> = vec![];
let mut names: Vec<Option<String>> = vec![];
let mut push = |mut path: PathData, rule: FillRule, mut st: Style, name: Option<String>| {
if path.is_empty() {
return;
}
// Trim, Merge and Crop remove any strokes (and Merge then merges by fill alone), as the
// public Pathfinder documentation describes.
if matches!(op, PathfinderOp::Trim | PathfinderOp::Merge | PathfinderOp::Crop) {
st.appearance.items.retain(|i| !matches!(i, AppearanceItem::Stroke(_)));
}
if op == PathfinderOp::Divide && st.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if !f.paint.is_none())) {
// Filled open contours keep their implicit closing edge. A zero-area line
// stays a cutter; normalised area also catches zero-signed-area self crossings.
for sub in path.subpaths.iter_mut().filter(|sp| !sp.closed) {
sub.closed = po::encloses_area(sub) || po::area(&PathData::single(sub.clone()), rule) > 0.0;
// `hidden`: the masks hide the operand altogether, and its empty path stands for it.
let mut push =
|mut path: PathData, mut rule: FillRule, mut st: Style, name: Option<String>, clip: Option<&Clip>, hidden: bool| -> Result<()> {
if path.is_empty() && !(hidden && keeps_hidden) {
return Ok(());
}
}
let key = match styles.iter().position(|x| *x == st) {
Some(k) => k,
None => {
styles.push(st);
styles.len() - 1
// Trim, Merge and Crop remove any strokes (and Merge then merges by fill alone), as the
// public Pathfinder documentation describes.
if matches!(op, PathfinderOp::Trim | PathfinderOp::Merge | PathfinderOp::Crop) {
st.appearance.items.retain(|i| !matches!(i, AppearanceItem::Stroke(_)));
}
if op == PathfinderOp::Divide && st.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if !f.paint.is_none())) {
// Filled open contours keep their implicit closing edge. A zero-area line
// stays a cutter; normalised area also catches zero-signed-area self crossings.
for sub in path.subpaths.iter_mut().filter(|sp| !sp.closed) {
sub.closed = po::encloses_area(sub) || po::area(&PathData::single(sub.clone()), rule) > 0.0;
}
}
if let Some(clip) = clip {
(path, rule) = clipped(path, rule, clip, op == PathfinderOp::Divide, options.precision)?;
if path.is_empty() && !keeps_hidden {
return Ok(());
}
}
let key = match styles.iter().position(|x| *x == st) {
Some(k) => k,
None => {
styles.push(st);
styles.len() - 1
}
};
shapes.push(po::Shape::new(path, rule, key as u64));
names.push(name);
Ok(())
};
shapes.push(po::Shape::new(path, rule, key as u64));
names.push(name);
};
// Whether a clip group was among the selection, for the error when its mask hides it all.
let mut masked = false;
for id in &roots {
let n = d.node(*id).ok_or(EngineError::NoNode(*id))?;
let mut lv = vec![];
pf_leaves(d, n, &mut lv);
clipped_pf_leaves(d, n, None, options.precision, &mut lv)?;
masked |= lv.iter().any(|(_, clip)| clip.is_some());
if lv.is_empty() {
continue;
}
if shape_mode
&& roots.len() > 1
&& lv.len() > 1
&& let Some(top) = lv.last()
{
// Among other objects, a group acts as one shape (the union of its leaves) with
// its top leaf's style. Selected alone, its members are the shapes (#1450).
let parts: Vec<(PathData, FillRule)> = lv.iter().filter_map(node_path).collect();
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
let name = n.name.clone().or_else(|| lv.iter().find_map(|l| l.name.clone()));
if shape_mode && roots.len() > 1 && lv.len() > 1 {
// Among other objects, a group acts as one shape (the union of its leaves, each
// where its clip groups show it) with the style of its top leaf that shows.
// Selected alone, its members are the shapes (#1450).
let mut parts: Vec<(&Node, PathData, FillRule)> = vec![];
for (l, clip) in &lv {
let Some((p, r)) = node_path(l) else { continue };
let (p, r) = match clip {
Some(clip) => clipped(p, r, clip, false, options.precision)?,
None => (p, r),
};
if !p.is_empty() {
parts.push((l, p, r));
}
}
let name = n.name.clone().or_else(|| parts.iter().find_map(|(l, ..)| l.name.clone()));
let Some((top, ..)) = parts.last() else {
// The masks hide the whole group.
if let Some((top, _)) = lv.last() {
push(PathData::default(), FillRule::NonZero, style_of(top), name, None, true)?;
}
continue;
};
let top = *top;
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, p, r)| (p, *r)).collect();
push(
po::try_unite_all_with(&refs, options.precision).map_err(|e| EngineError::Other(e.to_string()))?,
FillRule::NonZero,
style_of(top),
name,
);
None,
false,
)?;
} else {
for l in &lv {
for (l, clip) in &lv {
if let Some((p, r)) = node_path(l) {
push(p, r, style_of(l), n.name.clone().or_else(|| l.name.clone()));
push(p, r, style_of(l), n.name.clone().or_else(|| l.name.clone()), clip.as_deref(), clip.is_some())?;
}
}
}
}
if shapes.is_empty() && masked {
return Err(EngineError::Other(format!("{label}: the clipping masks hide the selected art")));
}
if shapes.is_empty() {
return Err(EngineError::Other(format!("{label}: select paths, compound paths, groups or text")));
}
File diff suppressed because one or more lines are too long
+34 -7
View File
@@ -1,6 +1,6 @@
//! Placed documents (`file.place` of a VectorCraft document, a PDF or a `.ai` file from a file,
//! with `link`): one locked object showing an artboard of the document or a page of the PDF, a
//! [`PlacedDocument`].
//! Placed documents (`file.place` of a VectorCraft document, a PDF, a `.ai` file or an EPS file
//! from a file, with `link`): one locked object showing an artboard of the document, a page of the
//! PDF or the EPS file's art, a [`PlacedDocument`].
//!
//! The object keeps the file's bytes (in the document's images, like image data) and the link; the
//! art it shows is read from them the way placing the file without Link reads it
@@ -33,6 +33,16 @@ pub(crate) const MAX_FILE: usize = 256 << 20;
const NATIVE: [&str; 2] = ["vectorcraft", "template"];
/// The type a placed VectorCraft document's bytes are stored with (a PDF's: its format's).
const MIME: &str = "application/json";
/// The type a placed EPS or PostScript file's bytes are stored with.
pub(crate) const POSTSCRIPT: &str = "application/postscript";
/// What follows the hash in the key of a placed PostScript `.ai` file ([`key_for`]).
const AI_MARK: &str = "-ai";
/// Is `key` (of a placed document) a PostScript `.ai` file's ([`AI_MARK`])? Hashes are hex, so
/// only the mark puts `-ai-` in a key.
pub(crate) fn is_postscript_ai_key(key: &str) -> bool {
key.contains(&format!("{AI_MARK}-"))
}
/// Is `name` with `bytes` a VectorCraft document?
pub(crate) fn is_native(name: &str, bytes: &[u8]) -> bool {
@@ -44,6 +54,12 @@ pub(crate) fn is_pdf(name: &str, bytes: &[u8]) -> bool {
fileio::detect(name, bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait")) && !vectorcraft_pdf::is_postscript(bytes)
}
/// Is `bytes` an EPS file, a PostScript file or a PostScript `.ai` or `.ait` file, read by the EPS
/// importer (not a DCS file, which is placed as a linked image)?
pub(crate) fn is_postscript(bytes: &[u8]) -> bool {
vectorcraft_pdf::is_postscript(bytes) && !super::dcs::is_dcs(bytes)
}
/// The editing data of the `.ai` file `name` (`bytes`) when its PDF part is only a placeholder, or
/// can't be read:
/// the document its pages are read from ([`super::pdf_art`]), with the files it links. `None` for
@@ -60,9 +76,12 @@ pub(crate) fn editing_data(name: &str, bytes: &[u8]) -> Option<Document> {
}
}
/// The type the bytes of placed file `name` (`bytes`) are stored with: a PDF's format's, else
/// [`MIME`].
/// The type the bytes of placed file `name` (`bytes`) are stored with: a PDF's format's,
/// [`POSTSCRIPT`] for an EPS or PostScript file, else [`MIME`].
fn mime(name: &str, bytes: &[u8]) -> &'static str {
if is_postscript(bytes) {
return POSTSCRIPT;
}
fileio::detect(name, bytes).filter(|_| is_pdf(name, bytes)).map_or(MIME, |f| f.mime)
}
@@ -108,7 +127,9 @@ pub(crate) struct DocumentArt {
/// Artboard `page` (1-based) of the VectorCraft document `name` (`bytes`, read from `path` when
/// there is one, so its linked images are found), clipped to the artboard unless `bounding`; or
/// page `page` of the PDF or `.ai` file `name`, clipped to its box `page_box` unless `bounding`
/// ([`super::pdf_art`]).
/// ([`super::pdf_art`]); or the art of the EPS or PostScript file `name` ([`is_postscript`]) on
/// its page `page`, clipped to its bounding box unless `bounding`, as placing it without Link reads
/// it.
pub(crate) fn document_art(
name: &str,
bytes: &[u8],
@@ -135,7 +156,7 @@ fn opened_document_art(
) -> Result<DocumentArt> {
let file = fileio::file_name(name);
let pdf = is_pdf(name, bytes);
if !pdf && !is_native(name, bytes) {
if !pdf && !is_native(name, bytes) && !is_postscript(bytes) {
return Err(bad(cmd, format!("`{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file")));
}
if bytes.len() > MAX_FILE {
@@ -145,6 +166,8 @@ fn opened_document_art(
let o = fileio::LoadOptions { crop: crop_to(page_box), ..Default::default() };
return super::pdf_art(name, (bytes, opened), path, page as usize, o, bounding, cmd);
}
// A VectorCraft document, or an EPS or PostScript file: the document our EPS files carry, else
// what its PostScript draws.
let mut l = fileio::load(name, bytes)?;
// Its linked images show their files; its placed documents stay as they are, unless their
// stored bytes are lost, when resolving reads their files, which can place this one again.
@@ -292,6 +315,10 @@ fn read_source(
let hash = shared.map_or_else(|| hash_bytes(bytes), |f| f.hash.to_string());
let opened = shared.map(|f| f.opened);
let shared = shared.map(|f| f.bytes);
// A PostScript `.ai` is read with the artboard its header gives, an EPS file on its page: the
// same bytes under the two names show different art, so they have keys of their own.
let ai = is_postscript(bytes) && fileio::detect(name, bytes).is_some_and(|f| matches!(f.id, "ai" | "ait"));
let hash = if ai { format!("{hash}{AI_MARK}") } else { hash };
// The same document placed the same way is read once (placing it again is free).
let key = key_for(&hash, page, bounding, page_box);
// Resolving its links depends on where the file is and on what the caller may read, so a hit
@@ -40,6 +40,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.image.colorMask",
"addon.image.removeBackground",
"addon.image.removeColorMask",
"addon.packaging.check",
"addon.packaging.roles",
"addon.packaging.setRole",
"addon.packaging.setRoleSwatch",
+222 -31
View File
@@ -5,13 +5,14 @@
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{ColorMode, Document, Node, NodeId, NodeKind};
use super::select::selectable_ids;
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, object_param, str_param};
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, has_doc, object_param, str_param, switch_or};
/// Magic Wand panel settings. Tolerances: colours as 0–255 RGB distance, stroke weight in
/// points, opacity in percent.
/// Magic Wand panel settings. Tolerances: colors as a Euclidean distance, 0–255 between RGB
/// values in an RGB document and 0–100 between CMYK percentages in a CMYK document; stroke
/// weight in points; opacity in percent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct WandSettings {
@@ -58,33 +59,68 @@ pub fn specs() -> Vec<CommandSpec> {
"Magic Wand Options",
["Window", "Magic Wand"],
None,
"{fillColor?, fillTolerance?: 0-255, strokeColor?, strokeTolerance?: 0-255, strokeWeight?, weightTolerance?: pt, opacity?, opacityTolerance?: %, blendingMode?, reset?: bool} → the settings",
"{fillColor?, fillTolerance?: 0-255 in an RGB document or 0-100 in a CMYK one, strokeColor?, strokeTolerance?: as fillTolerance, strokeWeight?, weightTolerance?: 0-1000 pt, opacity?, opacityTolerance?: 0-100 %, blendingMode?, reset?: bool} → the settings; a value out of range is an error and changes nothing, and an omitted one keeps its setting",
always,
set
),
cmd!(query "magicWand.options", "Magic Wand Settings", [], None, "{} → the Magic Wand settings", always, |s, _| Ok(json!(s.menu.wand))),
cmd!(
query "magicWand.options",
"Magic Wand Settings",
[],
None,
"{} → the Magic Wand settings (color tolerances at most 100 in a CMYK document)",
always,
|s, _| Ok(json!(s.menu.wand.effective(active_mode(s))))
),
]
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
if bool_or(p, "reset", false) {
s.menu.wand = WandSettings::default();
/// The active document's color mode, RGB with no document open.
fn active_mode(s: &Session) -> ColorMode {
s.doc().map(|st| st.doc.color_mode).unwrap_or_default()
}
/// The largest Fill Color and Stroke Color tolerance in a document of `mode`.
pub fn color_tolerance_max(mode: ColorMode) -> f64 {
match mode {
ColorMode::Rgb => 255.0,
ColorMode::Cmyk => 100.0,
}
let mut v = serde_json::to_value(&s.menu.wand).map_err(|e| EngineError::Other(e.to_string()))?;
if let (Some(o), Some(src)) = (v.as_object_mut(), p.as_object()) {
for (k, val) in src {
if o.contains_key(k) {
o.insert(k.clone(), val.clone());
}
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "magicWand.set";
let mode = active_mode(s);
let color_max = color_tolerance_max(mode);
let mut w = if switch_or(p, "reset", false, CMD)? { WandSettings::default() } else { s.menu.wand.clone() };
for (key, flag) in [
("fillColor", &mut w.fill_color),
("strokeColor", &mut w.stroke_color),
("strokeWeight", &mut w.stroke_weight),
("opacity", &mut w.opacity),
("blendingMode", &mut w.blending_mode),
] {
// Only a missing key keeps the setting; null, like any other value that isn't true or
// false, is an error.
if let Some(v) = p.get(key) {
*flag = v.as_bool().ok_or_else(|| bad(CMD, format!("`{key}` must be true or false")))?;
}
}
let mut w: WandSettings = serde_json::from_value(v).map_err(|e| bad("magicWand.set", e.to_string()))?;
w.fill_tolerance = w.fill_tolerance.clamp(0.0, 255.0);
w.stroke_tolerance = w.stroke_tolerance.clamp(0.0, 255.0);
w.weight_tolerance = w.weight_tolerance.clamp(0.0, 1000.0);
w.opacity_tolerance = w.opacity_tolerance.clamp(0.0, 100.0);
for (key, value, max) in [
("fillTolerance", &mut w.fill_tolerance, color_max),
("strokeTolerance", &mut w.stroke_tolerance, color_max),
("weightTolerance", &mut w.weight_tolerance, 1000.0),
("opacityTolerance", &mut w.opacity_tolerance, 100.0),
] {
let Some(v) = p.get(key) else { continue };
let n = v.as_f64().ok_or_else(|| bad(CMD, format!("`{key}` must be a number, not {v}")))?;
if !(n.is_finite() && (0.0..=max).contains(&n)) {
return Err(bad(CMD, format!("`{key}` must be from 0 to {max}, not {n}")));
}
*value = n;
}
s.menu.wand = w;
Ok(json!(s.menu.wand))
Ok(json!(s.menu.wand.effective(mode)))
}
/// The fill an object shows: type's comes from its characters (the first run speaks for all; type
@@ -104,25 +140,48 @@ pub(crate) fn stroke_of(n: &Node) -> (Paint, f64) {
}
}
/// Are two paints within `tol` (0–255 Euclidean RGB distance)? Non-solid paints must match exactly.
pub fn similar_paint(a: &Paint, b: &Paint, tol: f64) -> bool {
/// Are two paints within `tol`? In an RGB document `tol` is a 0–255 Euclidean distance between
/// the display RGB values; in a CMYK document it is a 0–100 Euclidean distance between the CMYK
/// percentages (a CMYK color's own values, any other color converted to CMYK). Non-solid paints
/// must match exactly.
pub fn similar_paint(a: &Paint, b: &Paint, tol: f64, mode: ColorMode) -> bool {
match (a.color(), b.color()) {
(Some(x), Some(y)) => {
let (x, y) = (x.to_rgb(), y.to_rgb());
let d: f64 = (0..3).map(|i| ((x[i] - y[i]) as f64 * 255.0).powi(2)).sum::<f64>().sqrt();
d <= tol + 1e-6
let (d, margin) = match mode {
ColorMode::Rgb => {
let (x, y) = (x.to_rgb(), y.to_rgb());
((0..3).map(|i| ((x[i] - y[i]) as f64 * 255.0).powi(2)).sum::<f64>().sqrt(), 1e-6)
}
// CMYK components are f32 fractions, so a distance of exactly `tol` points can come
// out a few millionths over.
ColorMode::Cmyk => {
let (x, y) = (x.to_cmyk(), y.to_cmyk());
((0..4).map(|i| ((x[i] - y[i]) as f64 * 100.0).powi(2)).sum::<f64>().sqrt(), 1e-4)
}
};
d <= tol + margin
}
_ => a == b,
}
}
impl WandSettings {
/// Does `n` match `reference` on every enabled attribute?
pub fn matches(&self, reference: &Node, n: &Node) -> bool {
/// The settings in effect in a document of `mode`: the color tolerances are capped at that
/// mode's maximum, so a larger value set in an RGB document applies as 100 in a CMYK one and
/// comes back in an RGB one.
pub fn effective(&self, mode: ColorMode) -> WandSettings {
let max = color_tolerance_max(mode);
WandSettings { fill_tolerance: self.fill_tolerance.min(max), stroke_tolerance: self.stroke_tolerance.min(max), ..self.clone() }
}
/// Does `n` match `reference` on every enabled attribute, comparing colors as in a document of
/// `mode`?
pub fn matches(&self, reference: &Node, n: &Node, mode: ColorMode) -> bool {
let w = self.effective(mode);
let (rs, rw) = stroke_of(reference);
let (ns, nw) = stroke_of(n);
(!self.fill_color || similar_paint(&fill_of(reference), &fill_of(n), self.fill_tolerance))
&& (!self.stroke_color || similar_paint(&rs, &ns, self.stroke_tolerance))
(!w.fill_color || similar_paint(&fill_of(reference), &fill_of(n), w.fill_tolerance, mode))
&& (!w.stroke_color || similar_paint(&rs, &ns, w.stroke_tolerance, mode))
&& (!self.stroke_weight || (rw - nw).abs() <= self.weight_tolerance + 1e-9)
&& (!self.opacity || ((reference.opacity - n.opacity).abs() as f64 * 100.0) <= self.opacity_tolerance + 1e-6)
&& (!self.blending_mode || reference.blend == n.blend)
@@ -156,12 +215,13 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let reference = st.doc.node(id).ok_or(EngineError::NoNode(id))?.clone();
let w = s.menu.wand.clone();
let mode = st.doc.color_mode;
// In isolation mode only the isolated group's contents can be picked, as for Select Same.
let inside = st.isolation.map(|iso| selectable_ids(&st.doc, Some(iso)));
let hits: Vec<NodeId> = paintable(&st.doc)
.into_iter()
.filter(|i| inside.as_ref().is_none_or(|set| set.contains(i)))
.filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n)))
.filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n, mode)))
.collect();
let ids: Vec<NodeId> = match str_param(p, "mode").unwrap_or("set") {
"add" => st.selection.objects.iter().copied().chain(hits.iter().copied().filter(|h| !st.selection.objects.contains(h))).collect(),
@@ -232,6 +292,137 @@ mod tests {
assert_eq!(selected(&s), [b]);
}
/// A 10 × 10 rectangle at `x` filled and stroked with the given colors (JSON color values).
fn painted(s: &mut Session, x: f64, fill: Value, stroke: Value) -> u64 {
let id = s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({ "color": fill })).unwrap();
s.execute("paint.setStroke", &json!({ "color": stroke })).unwrap();
id
}
fn cmyk(c: f64, m: f64, y: f64, k: f64) -> Value {
json!({"model": "cmyk", "c": c, "m": m, "y": y, "k": k})
}
#[test]
fn cmyk_document_compares_fill_and_stroke_colors_in_cmyk() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
let white = cmyk(0.0, 0.0, 0.0, 0.0);
let a = painted(&mut s, 0.0, cmyk(0.1, 0.0, 0.0, 0.0), white.clone());
let b = painted(&mut s, 20.0, cmyk(0.0, 0.0, 0.0, 0.0), white.clone());
let c = painted(&mut s, 40.0, cmyk(0.0, 0.1, 0.0, 0.0), white.clone());
// a to b is 10 points of cyan; a to c is 10 points of cyan and 10 of magenta (14.1).
s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
s.execute("magicWand.set", &json!({"fillTolerance": 9.9})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a]);
s.execute("magicWand.set", &json!({"fillTolerance": 14.2})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b, c]);
// Stroke Color alone, the same rule: d's stroke is 5 points of black from a's.
let d = painted(&mut s, 60.0, cmyk(1.0, 1.0, 1.0, 1.0), cmyk(0.0, 0.0, 0.0, 0.05));
s.execute("magicWand.set", &json!({"fillColor": false, "strokeColor": true, "strokeTolerance": 5})).unwrap();
s.execute("select.magicWand", &json!({"id": d})).unwrap();
assert_eq!(selected(&s), [a, b, c, d]);
s.execute("magicWand.set", &json!({"strokeTolerance": 4.9})).unwrap();
s.execute("select.magicWand", &json!({"id": d})).unwrap();
assert_eq!(selected(&s), [d]);
}
#[test]
fn cmyk_document_compares_gray_as_black_ink() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
let none = cmyk(0.0, 0.0, 0.0, 0.0);
let a = painted(&mut s, 0.0, json!({"gray": 0.5}), none.clone());
let b = painted(&mut s, 20.0, cmyk(0.0, 0.0, 0.0, 0.5), none.clone());
let c = painted(&mut s, 40.0, cmyk(0.0, 0.0, 0.0, 0.6), none);
s.execute("magicWand.set", &json!({"fillTolerance": 0})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b, c]);
}
#[test]
fn rgb_document_keeps_the_rgb_distance() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
let a = rect(&mut s, 0.0, "#000000", 1.0);
let b = rect(&mut s, 20.0, "#0a0000", 1.0);
s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
s.execute("magicWand.set", &json!({"fillTolerance": 9.9})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a]);
assert_eq!(s.execute("magicWand.set", &json!({"fillTolerance": 255})).unwrap()["fillTolerance"], 255.0);
}
#[test]
fn set_rejects_tolerances_out_of_range_and_changes_nothing() {
let mut s = Session::new();
// With no document the color range is the RGB one.
assert!(s.execute("magicWand.set", &json!({"fillTolerance": 256})).is_err());
s.execute("magicWand.set", &json!({"fillTolerance": 200})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
s.execute("magicWand.set", &json!({"fillTolerance": 40, "strokeTolerance": 50})).unwrap();
let before = s.execute("magicWand.options", &json!({})).unwrap();
for bad_value in [
json!({"fillTolerance": 101}),
json!({"strokeTolerance": 100.5}),
json!({"fillTolerance": -1}),
json!({"fillTolerance": "40"}),
json!({"weightTolerance": 1001}),
json!({"opacityTolerance": -0.5}),
json!({"fillColor": "yes"}),
json!({"fillTolerance": null}),
json!({"strokeColor": null}),
json!({"reset": "yes", "fillColor": false}),
json!({"reset": true, "fillTolerance": 101}),
json!({"fillColor": false, "strokeTolerance": 101}),
] {
let e = s.execute("magicWand.set", &bad_value).unwrap_err().to_string();
assert!(e.contains("magicWand.set"), "{bad_value}: {e}");
assert_eq!(s.execute("magicWand.options", &json!({})).unwrap(), before, "{bad_value} changed the settings");
}
assert!(s.execute("magicWand.set", &json!({"fillTolerance": 101})).unwrap_err().to_string().contains("from 0 to 100"));
assert_eq!(s.execute("magicWand.set", &json!({"fillTolerance": 100})).unwrap()["fillTolerance"], 100.0);
// An omitted value keeps its setting.
assert_eq!(s.execute("magicWand.set", &json!({"strokeColor": true})).unwrap()["strokeTolerance"], 50.0);
}
#[test]
fn a_larger_rgb_tolerance_applies_as_100_in_a_cmyk_document_and_comes_back() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
s.execute("magicWand.set", &json!({"fillTolerance": 200, "strokeTolerance": 60})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
let o = s.execute("magicWand.options", &json!({})).unwrap();
assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(100.0), Some(60.0)));
// Setting another field does not overwrite the stored fill tolerance.
assert_eq!(s.execute("magicWand.set", &json!({"opacity": true})).unwrap()["fillTolerance"], 100.0);
// 100 applies: two colors 100 points apart in one channel match, 100 apart in two do not.
let none = cmyk(0.0, 0.0, 0.0, 0.0);
let a = painted(&mut s, 0.0, cmyk(0.0, 0.0, 0.0, 0.0), none.clone());
let b = painted(&mut s, 20.0, cmyk(1.0, 0.0, 0.0, 0.0), none.clone());
let c = painted(&mut s, 40.0, cmyk(1.0, 1.0, 0.0, 0.0), none);
s.execute("magicWand.set", &json!({"opacity": false})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
assert!(!selected(&s).contains(&c));
s.execute("document.activate", &json!({"index": 0})).unwrap();
assert_eq!(s.execute("magicWand.options", &json!({})).unwrap()["fillTolerance"], 200.0);
// Reset gives 32 in either mode.
s.execute("document.activate", &json!({"index": 1})).unwrap();
let o = s.execute("magicWand.set", &json!({"reset": true})).unwrap();
assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(32.0), Some(32.0)));
}
#[test]
fn isolation_mode_limits_the_wand_to_the_isolated_group() {
let mut s = Session::new();
+1
View File
@@ -122,6 +122,7 @@ mod panelcmds;
mod paragraphs;
mod params;
mod path_menu_enabled;
mod pathfinder_clip;
mod pathops;
mod pathtype;
mod pattern;
+47
View File
@@ -2599,3 +2599,50 @@ fn symbol_sort_by_name_orders_the_symbols_in_one_undo_step() {
s.execute("symbol.sortByName", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), before);
}
/// `cmd::current_symbol` answers what `symbol.list` answers as `current`, and what `rule` (the
/// stored name while a symbol has it, else the first of all the names) answers:
/// with no symbols, with no stored name, with a stored name that is not first, after the current
/// symbol is deleted, with a stored name no symbol has and with a stored value that is not text.
#[test]
fn current_symbol_is_the_current_symbol_list_answers() {
fn rule(d: &Document) -> Option<String> {
let names: Vec<String> = d.symbols.iter().map(|s| s.name.clone()).collect();
let stored = d.unknown.get("currentSymbol").and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string);
stored.or_else(|| names.into_iter().next())
}
fn check(s: &mut Session, want: Option<&str>, case: &str) {
let listed = s.execute("symbol.list", &json!({})).unwrap()["current"].clone();
let d = &s.doc().unwrap().doc;
let helper = crate::cmd::current_symbol(d);
assert_eq!(helper.as_deref(), want, "{case}");
assert_eq!(json!(helper), listed, "{case}: symbol.list");
assert_eq!(helper, rule(d), "{case}: the rule");
}
fn store(s: &mut Session, v: Value) {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.insert("currentSymbol".into(), v);
}
let mut s = session();
check(&mut s, None, "no symbols");
store(&mut s, json!("Gone"));
check(&mut s, None, "no symbols and a stored name");
for (i, name) in ["A", "B", "C"].into_iter().enumerate() {
rect(&mut s, 20.0 * i as f64, 0.0, 10.0, 10.0);
s.execute("symbol.new", &json!({"name": name})).unwrap();
}
check(&mut s, Some("C"), "the newest symbol is current");
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.remove("currentSymbol");
check(&mut s, Some("A"), "no stored name");
s.execute("symbol.setCurrent", &json!({"name": "B"})).unwrap();
check(&mut s, Some("B"), "a stored name that is not first");
s.execute("symbol.delete", &json!({"name": "B"})).unwrap();
check(&mut s, Some("A"), "the current symbol deleted");
store(&mut s, json!("Renamed"));
check(&mut s, Some("A"), "a stored name no symbol has");
store(&mut s, json!(3));
check(&mut s, Some("A"), "a stored number");
store(&mut s, json!(["C"]));
check(&mut s, Some("A"), "a stored list");
store(&mut s, json!("C"));
check(&mut s, Some("C"), "a stored name that is last");
}
+131
View File
@@ -5198,6 +5198,137 @@ fn live_paint_bucket_drag_rejects_invalid_points_atomically() {
}
}
/// The edge of `g` through (`x`, 25), halfway up the squares of [`live_squares`].
fn vertical_edge(s: &Session, g: NodeId, x: f64) -> NodeId {
vectorcraft_tools::builder::edge_near(&node(s, g), Point::new(x, 25.0), 0.5).map(|e| e.id).unwrap_or_else(|| panic!("an edge at x {x}"))
}
/// A Shift-drag from an edge strokes every visible edge of that group the drag crosses, between
/// pointer events and on the release too, as one undo step that Escape cancels; hidden edges and
/// another group's edges keep their strokes.
#[test]
fn live_paint_bucket_drag_strokes_crossed_edges_as_one_undo() {
for cancel in [false, true] {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0, 200.0]);
let other = live_squares(&mut s, &[300.0]);
let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all: Vec<NodeId> = [g, other].iter().flat_map(|g| edges_in(&s, *g, Rect::new(-1.0, -1.0, 351.0, 51.0))).collect();
paint_parts(&mut s, &all, &black, &[]);
let hidden = vertical_edge(&s, g, 100.0);
s.edit("t", |d, _| {
d.node_mut(hidden).unwrap().visible = false;
Ok(())
})
.unwrap();
let before = s.doc().unwrap().doc.clone();
let depth = s.doc().unwrap().history.undo.len();
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.stroke = green.clone();
s.paint.stroke_width = 3.0;
let shift = Mods { shift: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 25.0).with_mods(shift), v).unwrap();
// Past the hidden edge and the edge at 150, then back across it, between pointer events.
s.pointer(&PointerEvent::new(PointerKind::Drag, 160.0, 25.0).with_mods(shift), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 140.0, 30.0).with_mods(shift), v).unwrap();
if cancel {
assert!(s.tool_busy());
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
assert!(!s.tool_busy());
}
// The release crosses the edges at 200 and 250 and goes on into the other group.
s.pointer(&PointerEvent::new(PointerKind::Up, 325.0, 25.0).with_mods(shift), v).unwrap();
if cancel {
assert!(s.doc().unwrap().doc == before, "Escape cancels the whole drag");
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
continue;
}
let stroke = |s: &Session, id: NodeId| {
let n = node(s, id);
(n.appearance.stroke_paint(), n.appearance.stroke().map(|st| st.width))
};
for x in [50.0, 150.0, 200.0, 250.0] {
assert_eq!(stroke(&s, vertical_edge(&s, g, x)), (green.clone(), Some(3.0)), "edge at {x}");
}
for (group, x) in [(g, 0.0), (g, 100.0), (other, 300.0), (other, 350.0)] {
assert_eq!(stroke(&s, vertical_edge(&s, group, x)), (black.clone(), Some(1.0)), "edge at {x}");
}
for e in edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 1.0)) {
assert_eq!(stroke(&s, e).0, black, "a top edge is not crossed");
}
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == before, "one Undo restores every edge");
}
}
/// A stroke drag over edges that already have the stroke records no undo step and keeps the redo
/// steps.
#[test]
fn live_paint_bucket_stroke_drag_no_op_keeps_history() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0]);
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0));
paint_parts(&mut s, &all, &green, &[]);
paint_parts(&mut s, &all, &green, &[]);
s.execute("edit.undo", &json!({})).unwrap();
let before = s.doc().unwrap().doc.clone();
let (undo, redo) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len());
assert_eq!(redo, 1);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.stroke = green;
s.paint.stroke_width = 1.0;
let shift = Mods { shift: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 0.0, 25.0).with_mods(shift), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 60.0, 25.0).with_mods(shift), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 110.0, 25.0).with_mods(shift), v).unwrap();
assert!(s.doc().unwrap().doc == before);
assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len()), (undo, redo));
}
/// `livePaint.strokeEdge` with `points` paints the crossed edges, counting the edge at the point;
/// a malformed path or a scope other than "one" with `points` is an error that changes nothing.
#[test]
fn live_paint_stroke_drag_rejects_invalid_points_atomically() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0]);
let before = s.doc().unwrap().doc.clone();
let stroke = |s: &mut Session, extra: Value| {
let mut p = json!({"group": g.0, "point": [50.0, 25.0], "color": "#00ff00"});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
s.execute("livePaint.strokeEdge", &p)
};
for points in
[json!([]), json!([[51.0, 25.0]]), json!([[50.0, 25.0], [null, 0]]), json!([[50.0, 25.0], [1e30, 0]]), json!(vec![[50.0, 25.0]; 4097])]
{
assert!(stroke(&mut s, json!({ "points": points })).is_err(), "{points}");
assert_eq!(s.doc().unwrap().doc, before);
}
for continuation in [json!(null), json!([[[51.0, 25.0], [125.0, 25.0]]]), json!([vec![[50.0, 25.0]; 4097]])] {
assert!(stroke(&mut s, json!({ "points": [[50.0, 25.0]], "continuation": continuation })).is_err(), "{continuation}");
assert_eq!(s.doc().unwrap().doc, before);
}
assert!(stroke(&mut s, json!({ "continuation": [[[50.0, 25.0]]] })).is_err());
for scope in ["connected", "samePaint"] {
assert!(stroke(&mut s, json!({ "points": [[50.0, 25.0], [125.0, 25.0]], "scope": scope })).is_err(), "{scope}");
}
assert_eq!(s.doc().unwrap().doc, before);
// A path in two chunks reaches the edges at 50, 100 and 150, not the one at 0.
let r = stroke(&mut s, json!({ "points": [[50.0, 25.0], [90.0, 25.0]], "continuation": [[[90.0, 25.0], [160.0, 25.0]]] })).unwrap();
assert_eq!(r["count"], 3);
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
for x in [50.0, 100.0, 150.0] {
assert_eq!(node(&s, vertical_edge(&s, g, x)).appearance.stroke_paint(), green, "edge at {x}");
}
assert_ne!(node(&s, vertical_edge(&s, g, 0.0)).appearance.stroke_paint(), green);
}
#[test]
fn live_paint_bucket_tool_fills_face() {
let mut s = session();
+94
View File
@@ -412,3 +412,97 @@ fn constrain_angle_turns_a_click_made_grid_about_its_reference_point() {
let b = bounds(&s, id);
assert_eq!((b.x0, b.y0, b.x1, b.y1), (175.0, 150.0, 225.0, 250.0), "turned about the click: {b:?}");
}
/// The anchor points of the path `id`.
fn path_points(s: &Session, id: NodeId) -> Vec<Point> {
match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Path { path, .. } => path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect(),
other => panic!("a path: {other:?}"),
}
}
/// The direction (degrees, counter-clockwise on the page) of the arc `id`'s first handle.
fn first_handle_angle(s: &Session, id: NodeId) -> f64 {
let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("a path") };
let a = &path.subpaths[0].anchors[0];
let v = a.h_out - a.p;
(-v.y).atan2(v.x).to_degrees()
}
fn near(p: Point, x: f64, y: f64) -> bool {
close(p.x, x) && close(p.y, y)
}
/// An arc dragged out runs along the turned axes: at 30° it still runs from the drag's start to
/// its end, its base leaves the start along the turned x axis and its bounding box turns 30°; at
/// 0° it is as before.
#[test]
fn constrain_angle_draws_a_dragged_arc_along_the_turned_axes() {
let mut s = new_doc();
for (deg, handle) in [(0.0, 0.0), (30.0, 30.0)] {
set_angle(&mut s, deg);
s.select_tool("arc", ViewInfo::default()).unwrap();
gesture(&mut s, Mods::default(), &[(Down, 100.0, 100.0), (Drag, 130.0, 110.0), (Drag, 160.0, 120.0), (Up, 160.0, 120.0)]);
let id = last_id(&s);
let pts = path_points(&s, id);
assert!(near(pts[0], 100.0, 100.0) && near(pts[1], 160.0, 120.0), "{deg}°: {pts:?}");
assert!(close(first_handle_angle(&s, id), handle), "{deg}°: {}", first_handle_angle(&s, id));
if deg == 0.0 {
assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits());
} else {
assert!(close(bbox_angle(&s, id), 30.0), "{}", bbox_angle(&s, id));
}
}
}
/// An arc placed by the click dialog keeps its reference point at the click and runs its lengths
/// along the turned axes: at 30° from the top-left reference point, and at 90° about the center
/// one; at 0° the dialog's params are unchanged.
#[test]
fn constrain_angle_turns_a_click_made_arc_about_its_reference_point() {
let mut s = new_doc();
let params = |reference: u64, x: f64, y: f64| json!({"x": x, "y": y, "lengthX": 100, "lengthY": 50, "reference": reference, "baseAlong": "x", "slope": 50, "closed": false, "fillArc": false});
let click = Point::new(200.0, 200.0);
let p = params(0, 200.0, 200.0);
assert_eq!(constrain_click(&s, "shape.arc", p.clone(), click), p, "0°");
set_angle(&mut s, 30.0);
let turned = constrain_click(&s, "shape.arc", p, click);
assert_eq!(turned["rotation"], json!(-30.0));
let id = NodeId(s.execute("shape.arc", &turned).unwrap()["id"].as_u64().unwrap());
let pts = path_points(&s, id);
let r = 30f64.to_radians();
let end = (200.0 + 100.0 * r.cos() + 50.0 * r.sin(), 200.0 - 100.0 * r.sin() + 50.0 * r.cos());
assert!(near(pts[0], 200.0, 200.0) && near(pts[1], end.0, end.1), "{pts:?} vs {end:?}");
assert!(close(bbox_angle(&s, id), 30.0));
set_angle(&mut s, 90.0);
let p = constrain_click(&s, "shape.arc", params(4, 200.0, 200.0), click);
let id = NodeId(s.execute("shape.arc", &p).unwrap()["id"].as_u64().unwrap());
// The ends at opposite corners of the 100 × 50 box centered on the click, turned exactly.
assert_eq!(path_points(&s, id), vec![Point::new(175.0, 250.0), Point::new(225.0, 150.0)]);
let b = bounds(&s, id);
assert!(close(b.x0, 175.0) && close(b.y0, 150.0) && close(b.x1, 225.0) && close(b.y1, 250.0), "turned about the click: {b:?}");
assert_eq!(bbox_angle(&s, id), 90.0);
}
/// `shape.arc` turns by an explicit `rotation` (clockwise) about `x1`, `y1` or about its reference
/// point; a `rotation` that is not a number is refused and adds nothing.
#[test]
fn arc_rotation_turns_it_and_must_be_a_number() {
let mut s = new_doc();
let id = NodeId(s.execute("shape.arc", &json!({"x1": 0, "y1": 0, "x2": 10, "y2": 20, "rotation": 90})).unwrap()["id"].as_u64().unwrap());
let pts = path_points(&s, id);
assert!(near(pts[0], 0.0, 0.0) && near(pts[1], -20.0, 10.0), "{pts:?}");
assert_eq!(bbox_angle(&s, id), -90.0, "a quarter turn clockwise");
let id =
NodeId(s.execute("shape.arc", &json!({"x": 50, "y": 50, "lengthX": 10, "lengthY": 20, "rotation": 360})).unwrap()["id"].as_u64().unwrap());
assert_eq!(path_points(&s, id), vec![Point::new(50.0, 50.0), Point::new(60.0, 70.0)], "a whole turn leaves it upright");
assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits());
for bad in [json!("x"), Value::Null] {
for p in
[json!({"x1": 0, "y1": 0, "x2": 10, "y2": 20, "rotation": bad}), json!({"x": 0, "y": 0, "lengthX": 10, "lengthY": 20, "rotation": bad})]
{
assert!(s.execute("shape.arc", &p).is_err(), "{p}");
assert_eq!(last_id(&s), id, "nothing added for {p}");
}
}
}
+215 -3
View File
@@ -2658,6 +2658,66 @@ fn shape_arc_closed_along_y_closes_through_the_top_left_corner() {
assert!((area - std::f64::consts::FRAC_PI_4).abs() < 0.01, "{area}");
}
/// A `reference` that is not a whole number from 0 to 8, a `baseAlong` other than x or y, and a
/// `slope` outside -100 to 100 are errors naming the key in both forms of `shape.arc`, null
/// included, and nothing is drawn and no undo step is added.
#[test]
fn shape_arc_rejects_an_invalid_reference_base_along_or_slope() {
let mut s = session();
let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let (before, steps) = (objects(&s), undo(&s));
let sized = json!({"x": 100, "y": 50, "lengthX": 80, "lengthY": 40});
let ends = json!({"x1": 0, "y1": 0, "x2": 50, "y2": 50});
let mut cases = vec![];
for v in [json!("4"), json!(-1), json!(4.5), json!(9), json!(9.0), json!(true), json!(null), json!([0])] {
cases.push(("reference", "`reference` must be a whole number from 0 to 8".to_string(), v));
}
for v in [json!("z"), json!("yes"), json!(""), json!(1), json!(false), json!(null), json!({"axis": "y"})] {
cases.push(("baseAlong", "`baseAlong` must be one of x, y".to_string(), v));
}
for (v, shown) in [(json!(150), "150"), (json!(-100.5), "-100.5")] {
cases.push(("slope", format!("`slope` must be from -100 to 100, not {shown}"), v));
}
for form in [&sized, &ends] {
for (key, want, v) in &cases {
let mut p = form.clone();
p[*key] = v.clone();
let r = s.execute("shape.arc", &p);
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}");
assert_eq!((objects(&s), undo(&s)), (before, steps), "{p}");
}
}
}
/// `shape.arc` takes each of the nine reference points (`4.0` as 4) and x or y in either case for
/// `baseAlong`; a left-out `reference` is 0 and a left-out `baseAlong` is x.
#[test]
fn shape_arc_takes_every_reference_point_and_either_base_axis() {
let mut s = session();
let arc = |s: &mut Session, extra: serde_json::Value| {
let mut p = json!({"x": 100, "y": 50, "lengthX": 80, "lengthY": 40});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
let id = NodeId(s.execute("shape.arc", &p).unwrap()["id"].as_u64().unwrap());
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
};
let start = |path: &PathData| path.subpaths[0].anchors[0].p;
for r in 0..=8u64 {
let p = start(&arc(&mut s, json!({ "reference": r })));
let (col, row) = ((r % 3) as f64, (r / 3) as f64);
assert_eq!(p, Point::new(100.0 - 40.0 * col, 50.0 - 20.0 * row), "reference {r}");
}
assert_eq!(arc(&mut s, json!({"reference": 4.0})), arc(&mut s, json!({"reference": 4})));
assert_eq!(arc(&mut s, json!({})), arc(&mut s, json!({"reference": 0, "baseAlong": "x"})));
assert_eq!(arc(&mut s, json!({"baseAlong": "X"})), arc(&mut s, json!({"baseAlong": "x"})));
assert_eq!(arc(&mut s, json!({"baseAlong": "Y"})), arc(&mut s, json!({"baseAlong": "y"})));
assert_ne!(arc(&mut s, json!({"baseAlong": "y"})), arc(&mut s, json!({"baseAlong": "x"})));
let ends = json!({"x1": 0, "y1": 0, "x2": 50, "y2": 50, "slope": -100});
assert!(s.execute("shape.arc", &ends).is_ok());
}
/// A spiral dragged out with Alt pressed part way gets four more segments per wind as its outer end
/// moves out. Ctrl/Cmd pressed part way fits the decay so the inner end keeps its distance from the
/// center. The Spiral tool keeps both values for the next spiral.
@@ -2822,7 +2882,7 @@ fn polar_grid_options_compound_fill_and_skew() {
assert!(tips(&inward)[1..].iter().all(|t| t.x < 50.0), "counterclockwise of the top: {:?}", tips(&inward));
}
/// A divider count written as a whole float (`3.0`) is the same as `3`; a fraction gives the default 5.
/// A divider count written as a whole float (`3.0`) is the same as `3`.
#[test]
fn grid_divider_counts_accept_whole_floats() {
let mut s = session();
@@ -2834,8 +2894,30 @@ fn grid_divider_counts_accept_whole_floats() {
let float = grid(&mut s, "shape.polarGrid", with(&size, json!({"concentric": 2.0, "radial": 3.0})));
let int = grid(&mut s, "shape.polarGrid", with(&size, json!({"concentric": 2, "radial": 3})));
assert_eq!(float.len(), int.len());
let frac = grid(&mut s, "shape.rectangularGrid", with(&size, json!({"rows": 2.5, "columns": 2.5})));
assert_eq!(frac.len(), 11);
}
/// A divider count that is not a whole number of 0 or more (a fraction, a negative) is an error
/// naming the key, and no grid is made; a left-out or null count is 5.
#[test]
fn grid_divider_counts_reject_fractions_and_negatives() {
let mut s = session();
let size = json!({"x": 0, "y": 0, "width": 100, "height": 100});
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let before = undo(&s);
for (cmd, key, value, shown) in [
("shape.rectangularGrid", "rows", json!(2.5), "2.5"),
("shape.rectangularGrid", "columns", json!(-1), "-1"),
("shape.polarGrid", "concentric", json!(0.5), "0.5"),
("shape.polarGrid", "radial", json!(-3.0), "-3"),
] {
let r = s.execute(cmd, &with(&size, json!({ key: value })));
let want = format!("`{key}` must be a whole number of at least 0, not {shown}");
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == want), "{cmd} {key}={value}: {r:?}");
assert_eq!(undo(&s), before, "{cmd} {key}={value}");
}
let omitted = grid(&mut s, "shape.rectangularGrid", size.clone());
let null = grid(&mut s, "shape.rectangularGrid", with(&size, json!({"rows": null, "columns": null})));
assert_eq!((omitted.len(), null.len()), (11, 11));
}
/// The grid options are checked: a divider count or a skew is a number and a switch true or false,
@@ -3219,6 +3301,88 @@ fn split_refuses_a_subpath_anchor_or_segment_that_is_not_a_whole_number() {
}
}
/// Give `id` a 4 pt round-capped Inside stroke and, above it, a hidden red copy aligned Outside.
/// Returns the appearance it now has.
fn side_strokes(s: &mut Session, id: NodeId) -> vectorcraft_doc::Appearance {
use vectorcraft_doc::{AppearanceItem, LineCap, StrokeAlign};
s.edit("Side Strokes", |d, _| {
let ap = &mut d.node_mut(id).unwrap().appearance;
let st = ap.stroke_mut().unwrap();
(st.width, st.cap, st.align) = (4.0, LineCap::Round, StrokeAlign::Inside);
let mut top = st.clone();
(top.align, top.visible, top.paint) =
(StrokeAlign::Outside, false, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)));
ap.items.push(AppearanceItem::Stroke(top));
Ok(())
})
.unwrap();
appearance(s, id)
}
fn appearance(s: &Session, id: NodeId) -> vectorcraft_doc::Appearance {
(*s.doc().unwrap().doc.node(id).unwrap().appearance).clone()
}
/// `ap` with every stroke aligned Center and nothing else changed.
fn centered(ap: &vectorcraft_doc::Appearance) -> vectorcraft_doc::Appearance {
let mut ap = ap.clone();
for it in &mut ap.items {
if let vectorcraft_doc::AppearanceItem::Stroke(st) = it {
st.align = vectorcraft_doc::StrokeAlign::Center;
}
}
ap
}
#[test]
fn scissors_cut_paths_have_their_strokes_centered() {
// The paths a Scissors cut makes keep the source's fill and strokes, every stroke centered,
// in the cut's one undo step; redo centers them again.
let mut s = session();
let r = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
let before = side_strokes(&mut s, r);
assert_ne!(before, centered(&before));
let undo = undo_steps(&s);
s.execute("path.split", &json!({"id": r.0, "anchor": 2})).unwrap();
assert_eq!(undo_steps(&s), undo + 1);
assert!(!path(&s, r).subpaths[0].closed);
assert_eq!(appearance(&s, r), centered(&before), "closed path");
s.execute("edit.undo", &json!({})).unwrap();
assert!(path(&s, r).subpaths[0].closed);
assert_eq!(appearance(&s, r), before, "undo");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(appearance(&s, r), centered(&before), "redo");
// An open path becomes two, at an anchor or inside a segment, both centered.
let anchors = json!([{"x": 100, "y": 300}, {"x": 200, "y": 300}, {"x": 300, "y": 300}]);
for at in [json!({"anchor": 1}), json!({"segment": 0, "t": 0.5})] {
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
let before = side_strokes(&mut s, id);
let made = s.execute("path.split", &with(&at, json!({"id": id.0}))).unwrap();
let ids: Vec<NodeId> = made["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
assert_eq!(ids.len(), 2, "{at}");
for i in ids {
assert_eq!(appearance(&s, i), centered(&before), "{at}: {i:?}");
}
}
// A path of several subpaths keeps one node: its other subpath's strokes are centered too.
let id = two_subpaths(&mut s);
let before = side_strokes(&mut s, id);
s.execute("path.split", &json!({"id": id.0, "anchor": 1})).unwrap();
assert_eq!(path(&s, id).subpaths.len(), 3);
assert_eq!(appearance(&s, id), centered(&before), "several subpaths");
// A cut that fails, at an open path's end point, changes neither the strokes nor the history.
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
let before = side_strokes(&mut s, id);
let undo = undo_steps(&s);
assert!(s.execute("path.split", &json!({"id": id.0, "anchor": 0})).is_err());
assert_eq!((undo_steps(&s), appearance(&s, id)), (undo, before));
// Strokes already centered stay shared with the undo history's copy.
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
let shared = s.doc().unwrap().doc.node(id).unwrap().appearance.clone();
s.execute("path.split", &json!({"id": id.0, "anchor": 1})).unwrap();
assert!(vectorcraft_doc::Shared::ptr_eq(&s.doc().unwrap().doc.node(id).unwrap().appearance, &shared));
}
/// A subpath, anchor or segment of 2^32 + k fails, where k names one that exists, and the document
/// and the undo history stay as they were. A 32-bit build read the number as k.
#[test]
@@ -3938,6 +4102,54 @@ fn cut_at_anchors_splits_paths_and_leaves_one_end_selected() {
assert_eq!(undo_steps(&s), undo);
}
#[test]
fn cut_at_anchors_paths_have_their_strokes_centered() {
// Every path the cut makes keeps the source's fill and strokes, every stroke centered, in one
// undo step; a path whose anchors were not selected keeps its strokes.
let mut s = session();
let anchors = json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}]);
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
let open = side_strokes(&mut s, id);
let r = rect(&mut s, 500.0, 100.0, 100.0, 100.0);
let closed = side_strokes(&mut s, r);
let other = rect(&mut s, 100.0, 300.0, 100.0, 100.0);
let untouched = side_strokes(&mut s, other);
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, 2]]})).unwrap();
s.execute("select.anchors", &json!({"id": r.0, "anchors": [[0, 2]], "mode": "add"})).unwrap();
assert_eq!(s.doc().unwrap().selection.anchors.len(), 2);
let undo = undo_steps(&s);
let made = s.execute("path.cutAtAnchors", &json!({})).unwrap();
let ids: Vec<NodeId> = made["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
assert_eq!(undo_steps(&s), undo + 1);
assert_eq!(ids.len(), 4, "three pieces and the opened rectangle");
for i in &ids {
let want = if *i == r { centered(&closed) } else { centered(&open) };
assert_eq!(appearance(&s, *i), want, "{i:?}");
}
assert_eq!(appearance(&s, other), untouched);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((appearance(&s, id), appearance(&s, r)), (open.clone(), closed.clone()), "undo");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!((appearance(&s, id), appearance(&s, r)), (centered(&open), centered(&closed)), "redo");
// A cut member of a compound path: the compound path's strokes, which it shows, are centered.
let a = rect(&mut s, 100.0, 450.0, 100.0, 100.0);
let b = rect(&mut s, 125.0, 475.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let compound = s.doc().unwrap().selection.objects[0];
let before = side_strokes(&mut s, compound);
let members: Vec<NodeId> = match &s.doc().unwrap().doc.node(compound).unwrap().kind {
NodeKind::Compound { children, .. } => children.iter().map(|c| c.id).collect(),
k => panic!("not a compound path: {k:?}"),
};
let held = path(&s, members[1]);
s.execute("select.anchors", &json!({"id": members[0].0, "anchors": [[0, 2]]})).unwrap();
s.execute("path.cutAtAnchors", &json!({})).unwrap();
assert!(!path(&s, members[0]).subpaths[0].closed);
assert_eq!(path(&s, members[1]), held, "the other member keeps its shape");
assert_eq!(appearance(&s, compound), centered(&before), "compound path");
}
#[test]
fn direct_segment_delete_keeps_the_other_rectangle_edges_and_one_undo() {
for initially_selected in [false, true] {
+81
View File
@@ -746,6 +746,87 @@ fn package_copies_a_linked_pdf_page_as_it_is() {
assert!(s.doc().unwrap().doc.has_placed());
}
#[test]
fn package_copies_a_linked_eps_file_as_it_is() {
let dir = Folder::new("package-placed-eps");
let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n1 0 0 setrgbcolor\nnewpath 0 0 moveto 100 0 lineto 100 50 lineto 0 50 lineto closepath fill\nshowpage\n%%EOF\n";
let src = dir.file("art/seal.eps");
write(&src, eps);
let mut s = session();
let placed = run(&mut s, "file.place", json!({"path": src}));
assert_eq!(placed["linked"], true, "{placed}");
save(&mut s, &dir.file("poster.vectorcraft"));
let r = run(&mut s, "file.package", json!({"folder": dir.file("out")}));
assert_eq!((r["links"].as_u64(), r["missingLinks"].clone(), r["warnings"].clone()), (Some(1), json!([]), json!([])), "{r}");
let root = dir.0.join("out/poster Folder");
assert_eq!(std::fs::read(root.join("Links/seal.eps")).unwrap(), eps, "copied as it is");
// The packaged document shows the copy.
std::fs::remove_dir_all(dir.0.join("art")).unwrap();
let opened = open(&mut s, &root.join("poster.vectorcraft").to_string_lossy());
assert_eq!(opened["missingLinks"], json!([]), "{opened}");
assert!(s.doc().unwrap().doc.has_placed());
}
#[test]
fn package_copies_a_linked_postscript_ai_file_the_document_holds_after_it_is_gone() {
let dir = Folder::new("package-placed-ps-ai");
let ai = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n0 0 1 setrgbcolor\nnewpath 0 0 moveto 100 0 lineto 100 50 lineto 0 50 lineto closepath fill\nshowpage\n%%EOF\n";
let src = dir.file("art/badge.ai");
write(&src, ai);
let mut s = session();
let placed = run(&mut s, "file.place", json!({"path": src}));
assert_eq!(placed["linked"], true, "{placed}");
save(&mut s, &dir.file("poster.vectorcraft"));
std::fs::remove_dir_all(dir.0.join("art")).unwrap();
let r = run(&mut s, "file.package", json!({"folder": dir.file("out")}));
assert_eq!((r["links"].as_u64(), r["missingLinks"].clone()), (Some(1), json!([])), "{r}");
let root = dir.0.join("out/poster Folder");
assert_eq!(std::fs::read(root.join("Links/badge.ai")).unwrap(), ai, "the bytes the document holds");
}
/// The PostScript bytes a document holds are copied for a placed document whose file name is one
/// PostScript is read from, and not under any other name or for a linked image.
#[test]
fn package_copies_held_postscript_only_for_a_placed_document_with_a_postscript_name() {
let dir = Folder::new("package-placed-ps-names");
let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n1 0 0 setrgbcolor\nnewpath 0 0 moveto 100 0 lineto 100 50 lineto 0 50 lineto closepath fill\nshowpage\n%%EOF\n";
let ai = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n0 0 1 setrgbcolor\nnewpath 0 0 moveto 100 0 lineto 100 50 lineto 0 50 lineto closepath fill\nshowpage\n%%EOF\n";
write(&dir.file("art/seal.eps"), eps);
write(&dir.file("art/badge.ai"), ai);
write(&dir.file("art/logo.png"), &png(8, 8, RED));
let mut s = session();
let seal = run(&mut s, "file.place", json!({"path": dir.file("art/seal.eps")}));
assert_eq!(seal["linked"], true, "{seal}");
let seal = vectorcraft_doc::NodeId(seal["ids"][0].as_u64().unwrap());
run(&mut s, "file.place", json!({"path": dir.file("art/badge.ai")}));
let logo = place(&mut s, &dir.file("art/logo.png"));
let (tool, logo_ai) = (dir.file("art/tool.exe"), dir.file("art/logo.ai"));
s.edit("names", |d, _| {
let vectorcraft_doc::NodeKind::PlacedDocument(p) = &mut d.node_mut(seal).unwrap().kind else { panic!("not a placed document") };
p.link.path = tool.clone();
p.link.relative = None;
let vectorcraft_doc::NodeKind::Image(im) = &mut d.node_mut(logo).unwrap().kind else { panic!("not an image") };
im.link.as_mut().unwrap().path = logo_ai.clone();
im.link.as_mut().unwrap().relative = None;
let key = im.key.clone();
d.images
.insert(key, vectorcraft_doc::ImageBlob { mime: "application/postscript".into(), bytes: std::sync::Arc::new(eps.to_vec()), proxy: None });
Ok(())
})
.unwrap();
save(&mut s, &dir.file("poster.vectorcraft"));
std::fs::remove_dir_all(dir.0.join("art")).unwrap();
let r = run(&mut s, "file.package", json!({"folder": dir.file("out")}));
assert_eq!(r["links"].as_u64(), Some(1), "{r}");
let mut missing: Vec<&str> = r["missingLinks"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
missing.sort_unstable();
assert_eq!(missing, ["logo.ai", "tool.exe"], "{r}");
let links = dir.0.join("out/poster Folder/Links");
assert_eq!(std::fs::read(links.join("badge.ai")).unwrap(), ai, "a PostScript .ai under its own name");
assert!(!links.join("tool.exe").exists(), "PostScript under a name it isn't read from");
assert!(!links.join("logo.ai").exists(), "PostScript held for a linked image");
}
#[test]
fn package_copies_the_fonts_of_the_type_on_a_linked_pdf_page() {
let dir = Folder::new("package-placed-pdf-type");
+311
View File
@@ -0,0 +1,311 @@
//! Pathfinder on clip groups (#8093): a clip group's members take part only where its clipping
//! path shows them, so Divide and the other operations leave out the hidden art.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::NodeKind;
use vectorcraft_geom::{FillRule, PathData, Rect};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn id(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}")))
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64, fill: Color) -> NodeId {
let r = id(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap());
s.edit("fill", |d, _| {
d.node_mut(r).unwrap().appearance.set_fill(Paint::solid(fill));
Ok(())
})
.unwrap();
r
}
fn clip(s: &mut Session, ids: &[NodeId]) -> NodeId {
id(&s.execute("object.clippingMask.make", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap())
}
fn red() -> Color {
Color::rgb(1.0, 0.0, 0.0)
}
fn blue() -> Color {
Color::rgb(0.0, 0.0, 1.0)
}
fn green() -> Color {
Color::rgb(0.0, 1.0, 0.0)
}
/// A red square at (0, 0) and a blue one at (50, 50), both 100 pt, clipped by a 100 pt square
/// mask at (25, 25): the clip group. The mask shows 8750 pt² of them.
fn clipped_pair(s: &mut Session) -> NodeId {
let a = rect(s, 0.0, 0.0, 100.0, 100.0, red());
let b = rect(s, 50.0, 50.0, 100.0, 100.0, blue());
let mask = rect(s, 25.0, 25.0, 100.0, 100.0, green());
clip(s, &[a, b, mask])
}
/// The shapes `op` makes of the selection, the members of the group it makes or the one shape:
/// (fill, path, rule) each.
fn pieces(s: &mut Session, op: &str) -> Vec<(Paint, PathData, FillRule)> {
let r = s.execute(op, &json!({})).unwrap();
let g = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).cloned().unwrap();
let shape = |n: &vectorcraft_doc::Node| match &n.kind {
NodeKind::Path { path, rule, .. } => (n.appearance.fill_paint(), path.clone(), *rule),
NodeKind::Compound { children, rule } => {
let subs = children.iter().flat_map(|c| c.path_data().unwrap().subpaths.clone()).collect();
(n.appearance.fill_paint(), PathData::new(subs), *rule)
}
k => panic!("not a path: {k:?}"),
};
match &g.kind {
NodeKind::Group { children, .. } => children.iter().map(|c| shape(c)).collect(),
_ => vec![shape(&g)],
}
}
fn area(p: &(Paint, PathData, FillRule)) -> f64 {
vectorcraft_pathops::area(&p.1, p.2)
}
fn bounds(ps: &[(Paint, PathData, FillRule)]) -> Rect {
ps.iter().filter_map(|p| p.1.bounds()).reduce(|a, b| a.union(b)).unwrap()
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn assert_inside(r: Rect, within: Rect) {
assert!(within.inflate(1e-6, 1e-6).contains_rect(r), "{r:?} reaches out of {within:?}");
}
/// The issue's case: Divide on a clip group gives the pieces the mask shows, cut along it, and the
/// hidden art goes.
#[test]
fn divide_on_a_clip_group_keeps_only_what_the_mask_shows() {
let mut s = session();
let g = clipped_pair(&mut s);
select(&mut s, &[g]);
let ps = pieces(&mut s, "object.pathfinder.divide");
assert_eq!(ps.len(), 3, "red alone, the overlap and blue alone: {ps:?}");
let total: f64 = ps.iter().map(area).sum();
assert!((total - 8750.0).abs() < 1.0, "the visible area, not the whole art: {total}");
assert_inside(bounds(&ps), Rect::new(25.0, 25.0, 125.0, 125.0));
let blue: f64 = ps.iter().filter(|p| p.0 == Paint::solid(blue())).map(area).sum();
assert!((blue - 5625.0).abs() < 1.0, "the overlap takes the front (blue) fill: {blue}");
assert!(ps.iter().all(|p| p.0 != Paint::solid(green())), "the clipping path adds no piece: {ps:?}");
}
/// An irregular mask: a square clipped by a circle divides into a disc.
#[test]
fn divide_cuts_along_a_curved_clipping_path() {
let mut s = session();
let square = rect(&mut s, 100.0, 100.0, 300.0, 300.0, red());
let circle = id(&s.execute("shape.ellipse", &json!({"x": 150, "y": 150, "width": 200, "height": 200})).unwrap());
let g = clip(&mut s, &[square, circle]);
select(&mut s, &[g]);
let ps = pieces(&mut s, "object.pathfinder.divide");
assert_eq!(ps.len(), 1, "{ps:?}");
let disc = std::f64::consts::PI * 100.0 * 100.0;
assert!((area(&ps[0]) - disc).abs() < disc * 1e-3, "{} vs {disc}", area(&ps[0]));
assert_inside(bounds(&ps), Rect::new(150.0, 150.0, 350.0, 350.0));
}
/// A clip group inside a clip group: its members show only where both masks do.
#[test]
fn nested_clip_groups_cut_by_both_masks() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 200.0, 200.0, red());
let inner_mask = rect(&mut s, 0.0, 0.0, 100.0, 200.0, green());
let inner = clip(&mut s, &[a, inner_mask]);
let outer_mask = rect(&mut s, 0.0, 50.0, 200.0, 100.0, green());
let outer = clip(&mut s, &[inner, outer_mask]);
select(&mut s, &[outer]);
let ps = pieces(&mut s, "object.pathfinder.divide");
assert_eq!(ps.len(), 1, "{ps:?}");
assert!((area(&ps[0]) - 10000.0).abs() < 1.0, "100 × 100 shows: {}", area(&ps[0]));
assert_inside(bounds(&ps), Rect::new(0.0, 50.0, 100.0, 150.0));
}
/// A member the mask hides altogether gives no piece.
#[test]
fn a_member_the_mask_hides_gives_no_piece() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0, red());
let b = rect(&mut s, 300.0, 300.0, 100.0, 100.0, blue());
let mask = rect(&mut s, 0.0, 0.0, 150.0, 150.0, green());
let g = clip(&mut s, &[a, b, mask]);
select(&mut s, &[g]);
let ps = pieces(&mut s, "object.pathfinder.divide");
assert_eq!(ps.len(), 1, "only the red square shows: {ps:?}");
assert_eq!(ps[0].0, Paint::solid(red()));
}
/// A cutting line in a clip group cuts only where the mask shows it: its hidden part leaves the
/// other selected art alone.
#[test]
fn a_clipped_cutting_line_cuts_only_where_it_shows() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0, red());
let line = id(&s.execute("shape.line", &json!({"x1": 50, "y1": -50, "x2": 50, "y2": 400})).unwrap());
let mask = rect(&mut s, 0.0, 0.0, 100.0, 100.0, green());
let g = clip(&mut s, &[a, line, mask]);
let other = rect(&mut s, 0.0, 200.0, 100.0, 100.0, blue());
select(&mut s, &[g, other]);
let ps = pieces(&mut s, "object.pathfinder.divide");
let red = ps.iter().filter(|p| p.0 == Paint::solid(red())).count();
let blue = ps.iter().filter(|p| p.0 == Paint::solid(blue())).count();
assert_eq!((red, blue), (2, 1), "the line halves the red square, not the blue one: {ps:?}");
}
/// Every Shape Mode and Pathfinder button takes the members as the mask shows them (#3367 asks
/// this of Merge). The mask, 100 × 60 pt at (25, 25), cuts through the squares' overlap: it shows
/// 4500 pt² of red, 2625 pt² of blue and 1750 pt² of their overlap.
#[test]
fn every_operation_takes_only_what_the_mask_shows() {
for (op, want) in [
("unite", Some(5375.0)),
("minusFront", Some(2750.0)),
("minusBack", Some(875.0)),
("intersect", Some(1750.0)),
("exclude", Some(3625.0)),
("trim", Some(5375.0)),
("merge", Some(5375.0)),
("crop", Some(1750.0)),
("outline", None),
] {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0, red());
let b = rect(&mut s, 50.0, 50.0, 100.0, 100.0, blue());
let mask = rect(&mut s, 25.0, 25.0, 100.0, 60.0, green());
let g = clip(&mut s, &[a, b, mask]);
select(&mut s, &[g]);
let ps = pieces(&mut s, &format!("object.pathfinder.{op}"));
assert_inside(bounds(&ps), Rect::new(25.0, 25.0, 125.0, 85.0));
if let Some(want) = want {
let total: f64 = ps.iter().map(area).sum();
assert!((total - want).abs() < 1.0, "{op}: {total}, want {want}");
}
}
}
/// Among other objects a clip group acts as one shape: the union of what its mask shows.
#[test]
fn a_clip_group_among_other_objects_is_the_area_its_mask_shows() {
let mut s = session();
let g = clipped_pair(&mut s);
let other = rect(&mut s, 300.0, 0.0, 50.0, 50.0, blue());
select(&mut s, &[g, other]);
let ps = pieces(&mut s, "object.pathfinder.unite");
let total: f64 = ps.iter().map(area).sum();
assert!((total - (8750.0 + 2500.0)).abs() < 1.0, "{total}");
}
/// Among other objects a clip group takes the style of its top member that shows: a member the
/// mask hides paints nothing.
#[test]
fn a_hidden_top_member_gives_no_style() {
let mut s = session();
// Below the clip group, so the result takes the group's style.
let other = rect(&mut s, 50.0, 50.0, 100.0, 100.0, green());
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0, red());
let b = rect(&mut s, 300.0, 300.0, 100.0, 100.0, blue());
let mask = rect(&mut s, 0.0, 0.0, 150.0, 150.0, green());
let g = clip(&mut s, &[a, b, mask]);
select(&mut s, &[other, g]);
let ps = pieces(&mut s, "object.pathfinder.unite");
assert_eq!(ps.len(), 1, "{ps:?}");
assert_eq!(ps[0].0, Paint::solid(red()), "not the hidden blue member's fill");
assert!((area(&ps[0]) - 17500.0).abs() < 1.0, "{}", area(&ps[0]));
}
/// A selection the masks hide altogether says so.
#[test]
fn art_the_masks_hide_altogether_is_refused_with_a_reason() {
let mut s = session();
let a = rect(&mut s, 300.0, 300.0, 100.0, 100.0, red());
let mask = rect(&mut s, 0.0, 0.0, 100.0, 100.0, green());
let g = clip(&mut s, &[a, mask]);
select(&mut s, &[g]);
let undo = s.doc().unwrap().history.undo.len();
let e = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
assert!(e.contains("clipping masks hide"), "{e}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changes");
}
/// A clip group its mask hides altogether, selected with a red square at (0, 0) and a blue one at
/// (50, 50), each 100 pt, at `position` in the stacking order (0: at the back).
fn with_a_hidden_clip_group(s: &mut Session, position: usize) {
let mut ids = vec![];
for i in 0..3 {
if i == position {
// Two members, so among other objects the group is one shape: their union.
let a = rect(s, 300.0, 300.0, 100.0, 100.0, green());
let b = rect(s, 450.0, 300.0, 100.0, 100.0, green());
let mask = rect(s, 0.0, 0.0, 100.0, 100.0, green());
ids.push(clip(s, &[a, b, mask]));
} else {
let at = if ids.len() == usize::from(position == 0) { 0.0 } else { 50.0 };
ids.push(rect(s, at, at, 100.0, 100.0, if at == 0.0 { red() } else { blue() }));
}
}
select(s, &ids);
}
/// A selected object its masks hide altogether is an empty operand: Intersect, Minus Front with
/// it at the back, Minus Back with it in front and Crop with it on top give nothing, and the other
/// operations make what they make without it.
#[test]
fn a_hidden_operand_is_an_empty_shape_where_it_changes_the_result() {
for (op, position) in [("intersect", 1), ("minusFront", 0), ("minusBack", 2), ("crop", 2)] {
let mut s = session();
with_a_hidden_clip_group(&mut s, position);
let undo = s.doc().unwrap().history.undo.len();
let e = s.execute(&format!("object.pathfinder.{op}"), &json!({})).unwrap_err().to_string();
assert!(e.contains("empty result"), "{op}: {e}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{op}: nothing changes");
}
for (op, position, want) in [("unite", 2, 17500.0), ("exclude", 2, 15000.0), ("minusFront", 2, 7500.0), ("minusBack", 0, 7500.0)] {
let mut s = session();
with_a_hidden_clip_group(&mut s, position);
let ps = pieces(&mut s, &format!("object.pathfinder.{op}"));
let total: f64 = ps.iter().map(area).sum();
assert!((total - want).abs() < 1.0, "{op}: {total}, want {want}");
assert!(ps.iter().all(|p| p.0 != Paint::solid(green())), "{op}: the hidden group's style: {ps:?}");
}
}
/// A clip group whose clipping path clips by nothing (here an empty group) hides its members, as on
/// the canvas: they are a hidden operand too, not left out of the selection.
#[test]
fn a_clipping_path_that_clips_by_nothing_hides_the_members() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0, red());
let b = rect(&mut s, 50.0, 50.0, 100.0, 100.0, blue());
let m1 = rect(&mut s, 300.0, 300.0, 100.0, 100.0, green());
let m2 = rect(&mut s, 450.0, 300.0, 100.0, 100.0, green());
let mask = rect(&mut s, 300.0, 300.0, 300.0, 100.0, green());
let g = clip(&mut s, &[m1, m2, mask]);
s.edit("empty clipping path", |d, _| {
let empty = vectorcraft_doc::Node::group(d.alloc_id(), vec![]);
let NodeKind::Group { children, .. } = &mut d.node_mut(g).unwrap().kind else { panic!("not a group") };
children[0] = std::sync::Arc::new(empty);
Ok(())
})
.unwrap();
select(&mut s, &[a, b, g]);
let e = s.execute("object.pathfinder.intersect", &json!({})).unwrap_err().to_string();
assert!(e.contains("empty result"), "not the squares' overlap: {e}");
select(&mut s, &[g]);
let e = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
assert!(e.contains("clipping masks hide"), "{e}");
}
+184
View File
@@ -926,6 +926,190 @@ fn a_pdf_compatible_ai_file_places_linked_like_a_pdf() {
assert_eq!(images, 0);
}
/// An EPS file written by hand at `path`: a 100×50 bounding box holding a 40×20 rectangle of `rgb`
/// from (20, 10), and `extra` comment lines (which change the file's size).
fn eps_source(path: &str, rgb: [u8; 3], extra: usize) {
let [r, g, b] = rgb.map(|c| c as f64 / 255.0);
let mut ps = format!(
"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n{r} {g} {b} setrgbcolor\nnewpath 20 10 moveto 60 10 lineto 60 30 lineto 20 30 lineto closepath fill\n"
);
for i in 0..extra {
ps.push_str(&format!("% line {i}\n"));
}
ps.push_str("showpage\n%%EOF\n");
write(path, ps.as_bytes());
}
/// An EPS file at `path` written by VectorCraft's EPS export: a 100×50 artboard filled with `rgb`
/// (`extra` more rectangles change the file's size).
fn exported_eps(path: &str, rgb: [u8; 3], extra: usize) {
let mut d = Document::new(100.0, 50.0);
let layer = d.layers[0].id;
for _ in 0..=extra {
let id = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), look(rgb))).unwrap();
}
write(path, &cmd::fileio::encode_all(&d, "eps", &json!({})).unwrap().files[0].1);
}
/// The kinds of `n` and everything inside it, in order.
fn kinds(n: &Node) -> Vec<&'static str> {
let mut k = vec![];
n.walk(&mut |c| k.push(c.kind_label()));
k
}
#[test]
fn with_link_an_eps_file_places_linked_framed_as_without_link() {
let dir = Folder::new("placed-eps-linked");
let src = dir.file("badge.eps");
eps_source(&src, RED, 0);
let mut s = session();
let embedded = |s: &mut Session, crop: &str| {
let r = s.execute("file.place", &json!({"path": src, "link": false, "crop": crop, "at": [200, 150]})).unwrap();
assert_eq!(r["linked"], false, "{r}");
let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone();
s.execute("edit.undo", &json!({})).unwrap();
n
};
let copy = embedded(&mut s, "crop");
let id = place(&mut s, &src);
let p = placed(&s, id);
assert_eq!((p.link.path.as_str(), p.link.page, p.bounding), (src.as_str(), Some(1), false), "{p:?}");
assert!((p.width - 100.0).abs() < 1e-6 && (p.height - 50.0).abs() < 1e-6, "{p:?}");
assert_eq!(Some(bounds(&s, id)), copy.geometric_bounds(), "the bounding box, as without Link");
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
let row = &s.execute("links.list", &json!({})).unwrap()["links"][0];
assert_eq!((row["format"].as_str(), row["document"].as_bool(), row["status"].as_str()), (Some("EPS"), Some(true), Some("ok")), "{row}");
assert_eq!(s.doc().unwrap().doc.images[&p.key].mime, "application/postscript");
// Break Link gives the group placing it without Link gives.
let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
assert_eq!(r["embedded"], json!([id.0]), "{r}");
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
assert_eq!((kinds(&n), n.geometric_bounds()), (kinds(&copy), copy.geometric_bounds()));
assert!(!s.doc().unwrap().doc.has_placed() && near(centre_colour(&s.doc().unwrap().doc), RED));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
// Bounding Box: the art's bounds, as without Link.
let copy = embedded(&mut s, "bounding");
let r = s.execute("file.place", &json!({"path": src, "crop": "bounding", "at": [200, 150]})).unwrap();
assert_eq!(r["linked"], true, "{r}");
let id = NodeId(r["ids"][0].as_u64().unwrap());
let p = placed(&s, id);
assert!(p.bounding && (p.width - 40.0).abs() < 1e-6 && (p.height - 20.0).abs() < 1e-6, "{p:?}");
assert_eq!(Some(bounds(&s, id)), copy.geometric_bounds());
// Object › Expand gives it too (the placed object is selected).
let r = s.execute("object.expand", &json!({})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
assert_eq!((kinds(&n), n.geometric_bounds()), (kinds(&copy), copy.geometric_bounds()), "{r}");
// Placed from its bytes, it is embedded.
let data = vectorcraft_format::base64_encode(&std::fs::read(&src).unwrap());
let r = s.execute("file.place", &json!({"name": "badge.eps", "dataBase64": data})).unwrap();
assert_eq!(r["linked"], false, "{r}");
}
#[test]
fn a_changed_eps_file_is_modified_and_update_links_reads_it_again() {
let dir = Folder::new("placed-eps-update");
let src = dir.file("flyer.eps");
exported_eps(&src, RED, 0);
let mut s = session();
let id = place(&mut s, &src);
exported_eps(&src, BLUE, 1);
assert_eq!(s.execute("links.check", &json!({})).unwrap()["links"][0]["status"], "modified");
assert!(near(centre_colour(&s.doc().unwrap().doc), RED), "shows the file as it read it");
let u = s.execute("links.update", &json!({})).unwrap();
assert_eq!(u["updated"], json!([id.0]), "{u}");
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 0);
// Relinked to another EPS file, it shows that file's art.
let other = dir.file("other.eps");
eps_source(&other, RED, 0);
let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other})).unwrap();
assert_eq!(r["relinked"], json!([id.0]), "{r}");
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
// A file it can't show is refused.
let notes = dir.file("notes.txt");
write(&notes, b"not a page");
let e = s.execute("links.relink", &json!({"ids": [id.0], "path": notes})).unwrap_err().to_string();
assert!(e.contains("isn't a VectorCraft document"), "{e}");
assert_eq!(placed(&s, id).link.path, other);
// Its file replaced by one that isn't PostScript: updating keeps the art it shows.
write(&other, b"not a page");
let _ = s.execute("links.update", &json!({}));
assert_eq!(placed(&s, id).link.path, other);
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
#[test]
fn a_linked_eps_file_outputs_as_vectors_and_shows_its_preview_without_its_file() {
let dir = Folder::new("placed-eps-outputs");
let src = dir.file("seal.eps");
// Content of its own: files read are cached by content, and this one is removed.
eps_source(&src, RED, 3);
let bytes = std::fs::read(&src).unwrap();
let mut s = session();
let id = place(&mut s, &src);
let doc_path = dir.file("poster.vectorcraft");
save(&mut s, &doc_path);
// Without its file: missing, shown and output as its preview, and not embedded.
std::fs::remove_file(&src).unwrap();
open(&mut s, &doc_path);
let key = placed(&s, id).key;
assert!(s.doc().unwrap().doc.images[&key].is_proxy(), "opened with the preview only");
let row = &s.execute("links.list", &json!({})).unwrap()["links"][0];
assert_eq!((row["format"].as_str(), row["status"].as_str()), (Some("EPS"), Some("missing")), "{row}");
assert!(near(centre_colour(&s.doc().unwrap().doc), RED), "the preview");
let pdf = s.execute("document.serialize", &json!({"format": "pdf"})).unwrap();
assert!(pdf["warnings"].to_string().contains("1 placed document output as its preview"), "{}", pdf["warnings"]);
let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
assert_eq!((r["embedded"].clone(), r["missing"].clone()), (json!([]), json!([id.0])), "{r}");
assert!(s.doc().unwrap().doc.has_placed());
// The file back: output reads it again, its paths and not the preview.
write(&src, &bytes);
assert_eq!(s.execute("links.check", &json!({})).unwrap()["links"][0]["status"], "ok");
let pdf = s.execute("document.serialize", &json!({"format": "pdf"})).unwrap();
assert_eq!(pdf["warnings"], json!([]), "{}", pdf["warnings"]);
let (images, paths) = pdf_contents(&decode(&pdf));
assert_eq!(images, 0, "no image in the PDF");
assert!(paths > 0);
// Include Linked Files keeps the EPS file itself.
let full = file_json(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft", "includeLinked": true})).unwrap()));
assert_eq!((full["images"][&key]["proxy"].clone(), full["images"][&key]["mime"].as_str()), (Value::Null, Some("application/postscript")));
}
#[test]
fn a_postscript_ai_file_places_linked_like_an_eps_file() {
let dir = Folder::new("placed-ps-ai-linked");
let src = dir.file("badge.ai");
eps_source(&src, RED, 0);
let mut s = session();
let id = place(&mut s, &src);
assert_eq!(placed(&s, id).link.path, src);
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
let row = &s.execute("links.list", &json!({})).unwrap()["links"][0];
assert_eq!(row["format"], "PostScript", "{row}");
eps_source(&src, BLUE, 5);
let u = s.execute("links.update", &json!({})).unwrap();
assert_eq!(u["updated"], json!([id.0]), "{u}");
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
// Saved with its preview only and reopened without its file, it is still listed as PostScript.
let bytes = std::fs::read(&src).unwrap();
let doc_path = dir.file("poster.vectorcraft");
save(&mut s, &doc_path);
std::fs::remove_file(&src).unwrap();
open(&mut s, &doc_path);
assert!(s.doc().unwrap().doc.images[&placed(&s, id).key].is_proxy(), "opened with the preview only");
let row = &s.execute("links.list", &json!({})).unwrap()["links"][0];
assert_eq!((row["format"].as_str(), row["status"].as_str()), (Some("PostScript"), Some("missing")), "{row}");
write(&src, &bytes);
// The same bytes named .eps are read as an EPS file: a file of their own, not the .ai's art.
let eps = dir.file("badge.eps");
write(&eps, &std::fs::read(&src).unwrap());
let other = place(&mut s, &eps);
assert_ne!(placed(&s, other).key, placed(&s, id).key);
}
#[test]
fn a_placed_document_inside_a_placed_document_outputs_from_its_own_file() {
let dir = Folder::new("placed-nested");
+66
View File
@@ -149,6 +149,72 @@ fn a_shape_tool_turns_the_shape_from_just_outside_a_corner() {
assert_eq!(angle(&s, id), 0.0, "rounding does not turn it");
}
/// How many objects the first layer holds.
fn objects(s: &Session) -> usize {
s.doc().unwrap().doc.layers[0].children().map(|c| c.len()).unwrap_or_default()
}
/// Feed the pointer events `(kind, x, y, backtick held)` to the active tool, with no modifier.
fn quote_gesture(s: &mut Session, events: &[(PointerKind, f64, f64, bool)]) {
for (k, x, y, held) in events {
s.pointer(&PointerEvent { backquote: *held, ..PointerEvent::new(*k, *x, *y) }, view()).unwrap();
}
}
/// A Rectangle tool drag from (50, 50) with Backtick held from (100, 100) to (140, 100), let go
/// before (160, 120), all moved by `o` along both axes: two copies, 70 × 50 and 90 × 50 pt, and
/// the 110 × 70 pt rectangle it ends with. With `release`, the drag is let go; without, it is
/// still in progress.
fn trail(s: &mut Session, o: f64, release: bool) {
use PointerKind::{Down, Drag, Up};
quote_gesture(
s,
&[
(Down, 50.0 + o, 50.0 + o, false),
(Drag, 100.0 + o, 100.0 + o, true),
(Drag, 120.0 + o, 100.0 + o, true),
(Drag, 140.0 + o, 100.0 + o, true),
],
);
quote_gesture(s, &[(Drag, 160.0 + o, 120.0 + o, false)]);
if release {
quote_gesture(s, &[(Up, 160.0 + o, 120.0 + o, false)]);
}
}
/// The sizes of the first layer's objects, back to front.
fn sizes(s: &Session) -> Vec<(f64, f64)> {
let ids: Vec<NodeId> = s.doc().unwrap().doc.layers[0].children().map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default();
ids.into_iter().map(|id| bounds(s, id)).map(|r| (r.width(), r.height())).collect()
}
/// Backtick held while a rectangle is dragged out leaves copies of it along the drag: each its own
/// object, and the release keeps them with the last rectangle as one undo step, with Real-time
/// Drawing and Editing on or off. Escape takes the copies back with the shape being drawn.
#[test]
fn a_backtick_drag_leaves_copies_of_the_shape_as_one_undo_step() {
for real_time in [true, false] {
let mut s = new_doc();
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time})).unwrap();
s.select_tool("rectangle", view()).unwrap();
let steps = undo_steps(&s);
trail(&mut s, 0.0, true);
assert_eq!(sizes(&s), vec![(70.0, 50.0), (90.0, 50.0), (110.0, 70.0)], "real time {real_time}");
assert_eq!(undo_steps(&s), steps + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(objects(&s), 0, "Undo takes all three back");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(objects(&s), 3, "Redo puts all three back");
// Escape takes back the copies and the shape being drawn, away from the selection.
let steps = undo_steps(&s);
trail(&mut s, 200.0, false);
s.tool_key(ToolKey::Escape, NONE, view()).unwrap();
quote_gesture(&mut s, &[(PointerKind::Up, 360.0, 320.0, false)]);
assert_eq!(objects(&s), 3, "real time {real_time}: nothing new");
assert_eq!(undo_steps(&s), steps, "no step");
}
}
/// The Selection tool takes the centre point of an unfilled shape too: a drag there moves it
/// instead of starting a marquee.
#[test]
+3
View File
@@ -1011,6 +1011,9 @@ fn structured_junk() {
("addon.packaging.roles", json!({"ids": [-1, 1e300]})),
("addon.packaging.setRoleSwatch", json!({"role": "perforation", "swatch": "[Registration]"})),
("addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": 5})),
("addon.packaging.check", json!({"ids": [u64::MAX, -1], "select": "yes", "tolerance": 1e308})),
("addon.packaging.check", json!({"tolerance": "-5 mm", "select": true})),
("addon.packaging.check", json!({"ids": [], "tolerance": null})),
// Smart Pen add-on.
("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})),
("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})),
+27 -1
View File
@@ -2888,6 +2888,32 @@ proptest! {
paste_from_elsewhere("clipboard.importEps", json!({"dataBase64": vectorcraft_format::base64_encode(ps.as_bytes())}))?;
}
/// Any bytes read by `readhexstring` or `readline` into strings of any length, from the
/// program's own file, through a filter decoded when first read, or from a file being run:
/// read as data, or as an error.
#[test]
fn eps_readhexstring_and_readline_data_never_panic(
data in prop::collection::vec(prop::sample::select(vec![b'0', b'9', b'a', b'F', b'g', b' ', b'\t', b'\r', b'\n', b'>', b'%', b'(', 0u8, 0xff]), 0..300),
len in 0usize..40,
line in any::<bool>(),
source in 0usize..3,
) {
let op = if line { "readline" } else { "readhexstring" };
let file = if source == 1 { "currentfile /ASCIIHexDecode filter" } else { "currentfile" };
let reads = format!("/s {len} string def /f {file} def 30 {{ f s {op} pop pop }} repeat");
let mut bytes = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec();
if source == 2 {
bytes.extend_from_slice(format!("currentfile 0 (endstream) /SubFileDecode filter cvx exec\n{reads}\n").as_bytes());
bytes.extend_from_slice(&data);
bytes.extend_from_slice(b"\nendstream\nshowpage\n");
} else {
bytes.extend_from_slice(format!("{reads}\n").as_bytes());
bytes.extend_from_slice(&data);
bytes.extend_from_slice(b"\nshowpage\n");
}
survive("readhexstring and readline data", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?;
}
/// Damaged or hostile CMYK images (a CMYK JPEG, an image with a key color): read as images,
/// or as an error.
#[test]
@@ -3133,7 +3159,7 @@ fn arb_ps_token() -> impl Strategy<Value = String> {
"gsave", "grestore", "save", "restore", "concat", "translate", "scale", "rotate", "setlinewidth", "setdash", "setgray",
"setrgbcolor", "setcmykcolor", "sethsbcolor", "setcolorspace", "setcolor", "setpattern", "makepattern", "shfill", "arc", "arcn",
"arct", "arcto", "rectfill", "rectclip", "rectstroke", "image", "imagemask", "colorimage", "currentfile", "filter",
"readhexstring", "readstring", "show", "stringwidth", "charpath", "findfont", "scalefont", "makefont", "setfont", "selectfont",
"readhexstring", "readstring", "readline", "show", "stringwidth", "charpath", "findfont", "scalefont", "makefont", "setfont", "selectfont",
"def", "bind", "load", "dup", "exch", "pop", "roll", "index", "copy", "for", "repeat", "loop", "exit", "if", "ifelse", "exec",
"stopped", "begin", "end", "dict", "array", "string", "get", "put", "getinterval", "putinterval", "aload", "astore", "forall",
"[", "]", "<<", ">>", "{", "}", "matrix", "currentmatrix", "setmatrix", "transform", "itransform", "invertmatrix", "pathbbox",
+147 -25
View File
@@ -17,8 +17,8 @@ use std::fmt::Write;
use kurbo::{PathSeg, Point};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{
Appearance, AppearanceItem, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, Node, NodeId, NodeKind, PiePosition,
PieSort, TickLength, ValueAxisSide,
Appearance, AppearanceItem, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES,
MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, Node, NodeId, NodeKind, PiePosition, PieSort, TickLength, ValueAxisSide,
};
use vectorcraft_effects::stroke;
use vectorcraft_geom::{Affine, Rect};
@@ -46,6 +46,9 @@ const EDGE: f64 = 0.01;
/// Most values one `Gc` takes.
const CELLS_PER_RECORD: usize = 15;
/// Widest `lineShapeWidth` the records give, in points (appendix A, `Gy`).
const MAX_LINE_WIDTH: f64 = 100.0;
/// A graph's records: what goes before its group (`%_Gs` to `%_GC`), and the `Go` line that follows
/// each series' group, by the group's id. `%_GS` follows the group.
pub(crate) struct Records {
@@ -89,7 +92,8 @@ pub(crate) fn records(n: &Node, to_art: Affine) -> Option<Records> {
(r.is_finite() && r.width() > 0.0 && r.height() > 0.0).then_some(())?;
let plot = to_art.transform_rect_bbox(r);
(plot.is_finite() && plot.width() > 0.0 && plot.height() > 0.0).then_some(())?;
let tags = series_groups(children, width, first_col, g.kind == GraphKind::Line)?;
let line = g.kind == GraphKind::Line;
let tags = series_groups(children, width, first_col, line, line && g.filled_lines)?;
draws_axes(n, r).then_some(())?;
let placed = n.geometric_bounds()?;
(r.x0 >= placed.x0 - EDGE && r.y0 >= placed.y0 - EDGE && r.x1 <= placed.x1 + EDGE && r.y1 <= placed.y1 + EDGE).then_some(())?;
@@ -97,14 +101,17 @@ pub(crate) fn records(n: &Node, to_art: Affine) -> Option<Records> {
let mut head = String::from("%_Gs\n");
let _ = writeln!(head, "%_{} {} {} {} Gb", real(plot.x0), real(plot.y1), real(plot.x1), real(plot.y0));
let flag = |b: bool| u8::from(b);
// `lineShapeWidth`: the width filled lines are drawn at, the graph's default included.
let _ = writeln!(
head,
"%_{ty} {} {} 14 {} {} 0 {} 6 44 Gy",
"%_{ty} {} {} 14 {} {} {} {} {} 44 Gy",
flag(g.drop_shadow),
flag(g.first_row_in_front),
flag(g.mark_points),
flag(g.connect_points),
flag(g.legend_across_top)
flag(g.filled_lines),
flag(g.legend_across_top),
real(g.line_width.unwrap_or(DEFAULT_FILLED_LINE_WIDTH))
);
let _ =
writeln!(head, "%_10 2 {} 0 {} {} {} Gd", flag(g.first_column_in_front), real(g.column_width), real(g.cluster_width), flag(g.edge_to_edge));
@@ -233,10 +240,11 @@ fn tick(t: TickLength) -> u8 {
}
/// Whether `g`'s settings are ones the records give and the reader keeps: a legend beside or across
/// the top, every series of the graph's type, one value axis on the left, lines not filled and no
/// Line Width of their own, no graph
/// designs, label formatting or pie settings, column and cluster widths of 1% to 1000%, and at most
/// [`MAX_TICK_MARKS`] tick marks a division.
/// the top, every series of the graph's type, one value axis on the left, lines filled only where
/// they connect the points (the records ignore the setting otherwise), a Line Width of 0.01 to
/// [`MAX_LINE_WIDTH`] points, with filled lines no series stroked as the bands' outline
/// ([`band_outline`]), which the reader reads as bands, no graph designs, label formatting or pie settings, column and
/// cluster widths of 1% to 1000%, and at most [`MAX_TICK_MARKS`] tick marks a division.
fn settings_kept(g: &GraphSpec) -> bool {
let percent = |p: f64| (1.0..=1000.0).contains(&p);
g.legend
@@ -244,8 +252,9 @@ fn settings_kept(g: &GraphSpec) -> bool {
&& g.value_axis == ValueAxisSide::Left
&& !g.separate_scales
&& g.right_series.is_empty()
&& !g.filled_lines
&& g.line_width.is_none()
&& (g.connect_points || !g.filled_lines)
&& g.line_width.is_none_or(|w| (MIN_FILLED_LINE_WIDTH..=MAX_LINE_WIDTH).contains(&w))
&& !(g.kind == GraphKind::Line && g.filled_lines && g.series_paints.iter().any(|p| band_outline(&p.stroke.clone().zip(p.stroke_width))))
&& g.series_markers.iter().all(Option::is_none)
&& g.series_columns.iter().all(Option::is_none)
&& g.label_styles == LabelStyles::default()
@@ -320,10 +329,13 @@ fn plain_paint(p: &Node) -> Option<(Option<Paint>, Option<(Paint, f64)>)> {
/// The `Go` line of each series' group among `children`: a group whose series index is one of the
/// `series` the table has, each once, of paths [`as_drawn`] with one fill and one line alike
/// ([`plain_paint`]), every path filled unless the graph draws lines (`line`). Its column is the
/// ([`plain_paint`]), every path filled unless the graph draws lines (`line`). With filled lines
/// (`bands`), a filled path outlined as [`band_outline`] says is a band, any other filled path is a
/// [`square`] marker or swatch, and the line of the paths that are not bands is the series' line,
/// as the reader reads it. Its column is the
/// table's: after the label column when there is one (`first_col`). `None` when a series has no
/// such group.
fn series_groups(children: &[std::sync::Arc<Node>], series: usize, first_col: usize, line: bool) -> Option<HashMap<NodeId, String>> {
fn series_groups(children: &[std::sync::Arc<Node>], series: usize, first_col: usize, line: bool, bands: bool) -> Option<HashMap<NodeId, String>> {
let mut tags = HashMap::new();
let mut seen = vec![false; series];
for c in children {
@@ -334,21 +346,63 @@ fn series_groups(children: &[std::sync::Arc<Node>], series: usize, first_col: us
*slot = true;
let NodeKind::Group { children: paths, clip: false } = &c.kind else { return None };
(as_drawn(c) && *c.appearance == Appearance::default() && !paths.is_empty()).then_some(())?;
let mut paints = vec![];
let (mut paints, mut strokes) = (vec![], vec![]);
for p in paths {
as_drawn(p).then_some(())?;
paints.push(plain_paint(p)?);
let (fill, outline) = plain_paint(p)?;
if bands && fill.is_some() && band_outline(&outline) {
// A band, or a mark outlined as one, which the reader reads as a band.
} else if bands && fill.is_some() && !square(p) {
return None;
} else {
strokes.push(outline);
}
paints.push(fill);
}
let fill = paints.iter().find_map(|(f, _)| f.clone());
paints.iter().all(|(f, _)| f.is_none() || *f == fill).then_some(())?;
(line || paints.iter().all(|(f, _)| f.is_some())).then_some(())?;
let stroke = paints.first().and_then(|(_, s)| s.clone());
paints.iter().all(|(_, s)| *s == stroke).then_some(())?;
let fill = paints.iter().find_map(Clone::clone);
paints.iter().all(|f| f.is_none() || *f == fill).then_some(())?;
(line || paints.iter().all(Option::is_some)).then_some(())?;
let stroke = strokes.first().cloned().flatten();
strokes.iter().all(|s| *s == stroke).then_some(())?;
tags.insert(c.id, format!("%_2 {} 0 0 Go", s + first_col));
}
seen.iter().all(|s| *s).then_some(tags)
}
/// Whether `stroke`, a path's line and its weight, is the thin black outline Draw Filled Lines
/// draws around a band, whatever the series' own line.
pub(crate) fn band_outline(stroke: &Option<(Paint, f64)>) -> bool {
stroke
.as_ref()
.is_some_and(|(paint, width)| *width == FILLED_LINE_OUTLINE_WIDTH && paint.color().is_some_and(|c| c.to_rgb_uncalibrated() == [0.0; 3]))
}
/// Whether path `p` is a square with sides along the page's axes, as a data point's default
/// marker and a legend swatch are: four straight sides, closed, as wide as it is tall. In a series
/// with filled lines, every other filled path is a band.
pub(crate) fn square(p: &Node) -> bool {
let NodeKind::Path { path, .. } = &p.kind else { return false };
if path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count() != 1 {
return false;
}
let near = |a: f64, b: f64| (a - b).abs() <= EDGE;
let mut sides = vec![];
for s in path.to_bezpath().segments() {
let PathSeg::Line(l) = s else { return false };
if !(near(l.p0.x, l.p1.x) && near(l.p0.y, l.p1.y)) {
sides.push(l);
}
}
let [first, _, _, last] = sides.as_slice() else { return false };
let (x0, x1) = sides.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), l| (lo.min(l.p0.x), hi.max(l.p0.x)));
let (y0, y1) = sides.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), l| (lo.min(l.p0.y), hi.max(l.p0.y)));
near(last.p1.x, first.p0.x)
&& near(last.p1.y, first.p0.y)
&& sides.iter().all(|l| near(l.p0.x, l.p1.x) || near(l.p0.y, l.p1.y))
&& x1 - x0 > EDGE
&& near(x1 - x0, y1 - y0)
}
/// Whether `art` draws plot `plot`'s left edge and its bottom edge (the document's y runs down) as
/// straight lines, each a shown path of one subpath with a plain line ([`plain_paint`]) in a shown
/// group, as the reader finds the axes.
@@ -409,7 +463,8 @@ pub(crate) mod sample {
}
/// Graph `g` drawn as a group: a group of each series' marks (a line graph's series as an unfilled
/// line, the others' as filled columns), its axes on the plot's left and bottom edges, and a
/// line, or with filled lines as an outlined band and its markers, the others' as filled
/// columns), its axes on the plot's left and bottom edges, and a
/// legend of a swatch for each series; its series groups named after the series.
pub(crate) fn graph(doc: &mut Document, g: GraphSpec) -> Node {
let r = g.rect;
@@ -430,7 +485,27 @@ pub(crate) mod sample {
row.get(s).copied().flatten().map(|v| Point::new(r.x0 + 20.0 + 60.0 * c as f64 + 15.0 * s as f64, r.y1 - v * 10.0))
})
.collect();
let marks: Vec<Arc<Node>> = if g.kind == GraphKind::Line {
let marks: Vec<Arc<Node>> = if g.kind == GraphKind::Line && g.filled_lines {
// A band around the line, as wide as the Line Width, with the thin black outline, and a
// marker on each point.
let half = g.filled_line_width() / 2.0;
let mut bp = kurbo::BezPath::new();
for (i, p) in points.iter().enumerate() {
if i == 0 { bp.move_to((p.x, p.y - half)) } else { bp.line_to((p.x, p.y - half)) }
}
for p in points.iter().rev() {
bp.line_to((p.x, p.y + half));
}
bp.close_path();
let band = Node::path(
doc.alloc_id(),
PathData::from_bezpath(&bp),
Appearance::basic(gray.clone(), Paint::solid(Color::BLACK), super::FILLED_LINE_OUTLINE_WIDTH),
);
let mut marks = vec![Arc::new(band)];
marks.extend(points.iter().map(|p| path(doc, shapes::rectangle(Rect::from_center_size(*p, (5.0, 5.0))), gray.clone(), Paint::None)));
marks
} else if g.kind == GraphKind::Line {
let mut bp = kurbo::BezPath::new();
for (i, p) in points.iter().enumerate() {
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
@@ -472,7 +547,7 @@ pub(crate) mod sample {
/// Graphs whose records read back whole: each type the records give, every setting they keep
/// changed, labels with parentheses, backslashes and non-ASCII characters, a label of 255 bytes,
/// and a table without labels.
/// a table without labels, and line graphs with filled lines and Line Widths the records give.
pub(crate) fn kept() -> Vec<(&'static str, Document)> {
let mut cases = vec![
("column", document(spec(GraphKind::Column))),
@@ -497,6 +572,18 @@ pub(crate) mod sample {
let mut g = spec(GraphKind::Column);
(g.series, g.categories) = (vec![], vec![]);
cases.push(("no labels", document(g)));
let line = |f: &dyn Fn(&mut GraphSpec)| {
let mut g = spec(GraphKind::Line);
f(&mut g);
document(g)
};
cases.extend([
("filled lines", line(&|g| g.filled_lines = true)),
("filled lines 8 pt wide", line(&|g| (g.filled_lines, g.line_width) = (true, Some(8.0)))),
("filled lines 100 pt wide", line(&|g| (g.filled_lines, g.line_width) = (true, Some(100.0)))),
("filled lines 0.01 pt wide", line(&|g| (g.filled_lines, g.line_width) = (true, Some(0.01)))),
("a Line Width without filled lines", line(&|g| g.line_width = Some(8.0))),
]);
cases
}
@@ -515,8 +602,20 @@ pub(crate) mod sample {
.collect();
cases.extend([
("no legend", with(&|g| g.legend = false)),
("filled lines", with(&|g| (g.kind, g.filled_lines) = (GraphKind::Line, true))),
("a filled line width", with(&|g| (g.kind, g.line_width) = (GraphKind::Line, Some(8.0)))),
("a Line Width past 100 pt", with(&|g| (g.kind, g.filled_lines, g.line_width) = (GraphKind::Line, true, Some(150.0)))),
("a Line Width under 0.01 pt", with(&|g| (g.kind, g.filled_lines, g.line_width) = (GraphKind::Line, true, Some(0.001)))),
("filled lines without connected points", with(&|g| (g.kind, g.filled_lines, g.connect_points) = (GraphKind::Line, true, false))),
(
"filled lines with series stroked as their outline",
with(&|g| {
(g.kind, g.filled_lines) = (GraphKind::Line, true);
g.series_paints = vec![vectorcraft_doc::SeriesPaint {
stroke: Some(Paint::solid(Color::BLACK)),
stroke_width: Some(super::FILLED_LINE_OUTLINE_WIDTH),
..Default::default()
}];
}),
),
("a series of another type", with(&|g| g.series_kinds = vec![None, Some(GraphKind::Line)])),
("a marker design", with(&|g| g.series_markers = vec![Some("Star".into())])),
("a column design", with(&|g| g.series_columns = vec![Some(Default::default())])),
@@ -645,6 +744,29 @@ mod tests {
assert_eq!(marks, ["1", "1", "1"], "{head}");
}
/// A marker or swatch is a square along the page's axes; a band, a rotated square, a rectangle
/// of other proportions and an open path are not.
#[test]
fn markers_are_squares_and_bands_are_not() {
use vectorcraft_geom::shapes;
let node = |p: vectorcraft_geom::PathData| Node::path(NodeId(1), p, Appearance::default());
assert!(square(&node(shapes::rectangle(Rect::new(10.0, 10.0, 15.0, 15.0)))), "a 5 pt marker");
assert!(!square(&node(shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 13.0)))), "a band along a level line");
let mut diamond = kurbo::BezPath::new();
diamond.move_to((0.0, 5.0));
diamond.line_to((5.0, 0.0));
diamond.line_to((10.0, 5.0));
diamond.line_to((5.0, 10.0));
diamond.close_path();
assert!(!square(&node(vectorcraft_geom::PathData::from_bezpath(&diamond))), "a rotated square");
let mut open = kurbo::BezPath::new();
open.move_to((0.0, 0.0));
for p in [(5.0, 0.0), (5.0, 5.0), (0.0, 5.0), (0.0, 1.0)] {
open.line_to(p);
}
assert!(!square(&node(vectorcraft_geom::PathData::from_bezpath(&open))), "an open path");
}
/// A table's cells go fifteen to a record, with one string at most in each.
#[test]
fn cells_go_fifteen_to_a_record_with_one_string_each() {
+2
View File
@@ -68,6 +68,8 @@ mod tests_images;
#[cfg(test)]
mod tests_native;
#[cfg(test)]
mod tests_reads;
#[cfg(test)]
mod tests_type1;
#[cfg(test)]
mod tests_type42;
+98 -17
View File
@@ -14,10 +14,14 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use kurbo::{PathSeg, Point};
use vectorcraft_doc::{Appearance, GraphKind, GraphSpec, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, SeriesPaint, TickLength};
use vectorcraft_doc::{
Appearance, DEFAULT_FILLED_LINE_WIDTH, GraphKind, GraphSpec, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, SeriesPaint,
TickLength,
};
use super::types::{GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, Kind};
use super::{Affine, AppearanceItem, BlendMode, Node, NodeId, NodeKind, Paint, Reader, Rect, V, obj};
use crate::ai_graph::{band_outline, square};
/// Most cells of a graph's table, its label row and column included.
const MAX_CELLS: usize = 2_600_000;
@@ -293,11 +297,20 @@ impl Records {
self.spec.legend = true;
self.spec.mark_points = flag(marks)?;
self.spec.connect_points = flag(lines)?;
// Lines drawn as shapes have a width the model doesn't keep.
(!flag(shapes)?).then_some(())?;
self.spec.filled_lines = false;
// Lines drawn as shapes (Draw Filled Lines); without connected points the flag is ignored.
self.spec.filled_lines = flag(shapes)? && self.spec.connect_points;
self.spec.legend_across_top = flag(across)?;
finite(width).filter(|w| (0.0..=100.0).contains(w))?;
// `lineShapeWidth`, in points from 0 to 100. The model holds widths from 0.01 points, 3 points
// being its default; a smaller width is left out while the lines aren't filled, and keeps
// filled lines plain.
let width = finite(width).filter(|w| (0.0..=100.0).contains(w))?;
self.spec.line_width = if width == DEFAULT_FILLED_LINE_WIDTH {
None
} else if width >= MIN_FILLED_LINE_WIDTH {
Some(width)
} else {
(!self.spec.filled_lines).then_some(None)?
};
// 44: the series are measured against the left axis; 45 (right) isn't kept per series.
(int(axis)? == 44).then_some(())?;
if let Some([percentage, digits]) = pie {
@@ -471,20 +484,36 @@ fn as_drawn(n: &Node) -> bool {
/// Each series' fill and stroke, read from its group (`tags`), which holds paths only, one at
/// least: the paths with a fill share it, and every path has the same stroke or none. Only a line
/// graph (`line`) has paths without a fill: its lines. `None` when they differ, or the group, its
/// own appearance or a path is drawn otherwise than [`as_drawn`].
fn series_paints(art: &Node, tags: &HashMap<NodeId, u32>, line: bool) -> Option<Vec<SeriesPaint>> {
/// graph (`line`) has paths without a fill: its lines. With filled lines (`bands`), a filled path
/// outlined as [`band_outline`] says is a band or a mark drawn like one and gives no stroke; any
/// other filled path but a [`square`] marker or legend swatch is a band outlined otherwise. The
/// other paths give the series' stroke, and without them the series has none. A series with a band
/// and no stroke on its other paths keeps no stroke at all, so with filled lines turned off its thin
/// line is drawn in the series color at 1 pt, as for a graph drawn here. `None` when they
/// differ, a band has another outline, or the group, its own appearance or a path is drawn
/// otherwise than [`as_drawn`].
fn series_paints(art: &Node, tags: &HashMap<NodeId, u32>, line: bool, bands: bool) -> Option<Vec<SeriesPaint>> {
let mut paints = vec![SeriesPaint::default(); tags.len()];
for group in art.children().into_iter().flatten() {
let Some(slot) = tags.get(&group.id).and_then(|i| paints.get_mut(usize::try_from(*i).ok()?)) else { continue };
(as_drawn(group) && *group.appearance == Appearance::default()).then_some(())?;
let paths: Vec<&Arc<Node>> = group.children().into_iter().flatten().collect();
(!paths.is_empty() && paths.iter().all(|p| matches!(p.kind, NodeKind::Path { .. }))).then_some(())?;
let (mut fills, mut strokes) = (vec![], vec![]);
let (mut fills, mut strokes, mut banded) = (vec![], vec![], false);
for p in &paths {
as_drawn(p).then_some(())?;
fills.extend(shown(p, true).ok()?);
strokes.push(shown(p, false).ok()?);
let filled = shown(p, true).ok()?;
let outline = shown(p, false).ok()?;
if bands && filled.is_some() && band_outline(&outline) {
// A band, or a mark outlined as one: the graph keeps no stroke for a series that draws bands.
banded = true;
} else if bands && filled.is_some() && !square(p) {
// A band outlined otherwise: the graph draws it again with the thin black outline only.
return None;
} else {
strokes.push(outline);
}
fills.extend(filled);
}
let fill = fills.first().map(|(paint, _)| paint.clone());
fills.iter().all(|(paint, _)| Some(paint) == fill.as_ref()).then_some(())?;
@@ -494,6 +523,7 @@ fn series_paints(art: &Node, tags: &HashMap<NodeId, u32>, line: bool) -> Option<
slot.fill = fill;
(slot.stroke, slot.stroke_width) = match stroke {
Some((paint, width)) => (Some(paint), Some(width)),
None if banded => (None, None),
None => (Some(Paint::None), None),
};
}
@@ -628,7 +658,8 @@ impl<'a> Reader<'a> {
if r.x0 < placed.x0 - EDGE || r.y0 < placed.y0 - EDGE || r.x1 > placed.x1 + EDGE || r.y1 > placed.y1 + EDGE {
return false;
}
let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false };
let line = spec.kind == GraphKind::Line;
let Some(paints) = series_paints(art, &tags, line, line && spec.filled_lines) else { return false };
spec.series_paints = paints;
spec.placed = Some(placed);
spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::graph_art_without_type(c));
@@ -646,6 +677,7 @@ impl<'a> Reader<'a> {
mod tests {
use super::*;
use vectorcraft_color::Color;
use vectorcraft_doc::FILLED_LINE_OUTLINE_WIDTH;
use vectorcraft_geom::shapes;
/// A graph's art: one series group (id 2) holding one mark painted `ap`, the group changed by
@@ -665,9 +697,58 @@ mod tests {
let mut two = one.clone();
two.items.extend(one.items.iter().find(|i| i.is_fill()).cloned());
let tags = HashMap::from([(NodeId(2), 0)]);
let kept = series_paints(&art(one, |_| {}), &tags, false).expect("one fill");
let kept = series_paints(&art(one, |_| {}), &tags, false, false).expect("one fill");
assert_eq!((kept[0].fill.as_ref(), kept[0].stroke.as_ref()), (Some(&red), Some(&Paint::None)));
assert!(series_paints(&art(two, |_| {}), &tags, false).is_none());
assert!(series_paints(&art(two, |_| {}), &tags, false, false).is_none());
}
/// With filled lines, a band's thin black outline is not the series' stroke: its markers' stroke
/// is, and with unstroked markers or none the series keeps no stroke. A band outlined otherwise
/// than its markers has no one stroke.
#[test]
fn a_filled_line_bands_outline_is_not_its_series_stroke() {
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let series = |band: Appearance, marker: Appearance| {
let band = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 3.0)), band));
let marker = Arc::new(Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), marker));
Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(2), vec![band, marker]))])
};
let tags = HashMap::from([(NodeId(2), 0)]);
let outlined = Appearance::basic(red.clone(), Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), FILLED_LINE_OUTLINE_WIDTH);
let marker = Appearance::basic(red.clone(), Paint::None, 0.0);
let kept = series_paints(&series(outlined.clone(), marker.clone()), &tags, true, true).expect("a band and a marker");
assert_eq!((kept[0].fill.as_ref(), kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&red), None, None));
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
let stroked = Appearance::basic(red.clone(), blue.clone(), 2.0);
let kept = series_paints(&series(outlined.clone(), stroked), &tags, true, true).expect("a band and a stroked marker");
assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&blue), Some(2.0)));
let bands_only = Node::group(
NodeId(1),
vec![Arc::new(Node::group(
NodeId(2),
vec![Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 3.0)), outlined.clone()))],
))],
);
let kept = series_paints(&bands_only, &tags, true, true).expect("a band alone");
assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (None, None), "a band alone");
// A band as long as it is wide is a square, and still a band: its outline is not the series' stroke.
let square_band = |marker: Appearance| {
let band = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 3.0, 3.0)), outlined.clone()));
let marker = Arc::new(Node::path(NodeId(4), shapes::rectangle(Rect::new(10.0, 0.0, 15.0, 5.0)), marker));
Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(2), vec![band, marker]))])
};
let kept = series_paints(&square_band(marker.clone()), &tags, true, true).expect("a square band and a marker");
assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (None, None), "a square band");
assert!(series_paints(&series(outlined, marker.clone()), &tags, true, false).is_none(), "lines not filled");
let thick = Appearance::basic(red.clone(), Paint::solid(Color::BLACK), 1.0);
assert!(series_paints(&series(thick, marker), &tags, true, true).is_none(), "a 1 pt outline");
// A band outlined as its markers are stroked is drawn again with the thin black outline.
assert!(series_paints(&series(stroked_like(&blue), stroked_like(&blue)), &tags, true, true).is_none(), "a band outlined in blue");
}
/// A red mark stroked 2 pt in `paint`.
fn stroked_like(paint: &Paint) -> Appearance {
Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), paint.clone(), 2.0)
}
/// A series group that is hidden, see-through or in another blending mode is not drawn again so.
@@ -675,8 +756,8 @@ mod tests {
fn a_series_group_drawn_otherwise_has_no_series_paint() {
let ap = || Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
let tags = HashMap::from([(NodeId(2), 0)]);
assert!(series_paints(&art(ap(), |g| g.visible = false), &tags, false).is_none(), "hidden");
assert!(series_paints(&art(ap(), |g| g.opacity = 0.5), &tags, false).is_none(), "50% opaque");
assert!(series_paints(&art(ap(), |g| g.blend = BlendMode::Multiply), &tags, false).is_none(), "Multiply");
assert!(series_paints(&art(ap(), |g| g.visible = false), &tags, false, false).is_none(), "hidden");
assert!(series_paints(&art(ap(), |g| g.opacity = 0.5), &tags, false, false).is_none(), "50% opaque");
assert!(series_paints(&art(ap(), |g| g.blend = BlendMode::Multiply), &tags, false, false).is_none(), "Multiply");
}
}
+63 -1
View File
@@ -11418,6 +11418,68 @@ fn a_graphs_type_and_settings_come_from_its_records() {
assert!(art(&r.doc)[0].extras().graph.is_some());
}
/// A series of a line graph drawn with filled lines at `x`: a band filled with the series' color and
/// outlined in a thin black line, and a marker filled alike with no outline.
fn band_series(x: f64) -> String {
format!("0.5 0 0 0 k\n0 0 0 1 K\n0.25 w\n{}B\n1 w\n{}f\n", rect_path(x, 120.0, x + 40.0, 128.0), rect_path(x + 18.0, 122.0, x + 23.0, 127.0))
}
/// [`live_graph`] as a line graph with style record `style`, each series drawn by [`band_series`].
fn band_graph(style: &str) -> String {
live_graph().replace(LIVE_STYLE, style).replace(&series_bar(110.0), &band_series(110.0)).replace(&series_bar(140.0), &band_series(140.0))
}
/// A line graph whose lines are drawn as shapes (`drawLinesAsShapes` 1 with `drawLines` 1) keeps
/// Draw Filled Lines and its Line Width (`lineShapeWidth`, in points): 3 points is the graph's
/// default. Its series keep their bands' fill, and the bands' thin black outline is not taken as the
/// series' stroke. With `drawLines` 0 the flag is ignored, and the width is kept for later.
#[test]
fn a_line_graph_drawn_with_filled_lines_keeps_them_and_their_width() {
let live = |text: String| {
let r = read(stream7(&layer7("Graph", &text)).as_bytes()).unwrap();
assert!(r.warnings.is_empty(), "{text}: {:?}", r.warnings);
let a = art(&r.doc);
let g = a[0].extras().graph.clone().unwrap_or_else(|| panic!("{text}: a live graph"));
(g, live_graphs(&r.doc).1)
};
let (g, tagged) = live(band_graph("%_7 0 0 14 1 1 1 0 8 44 Gy\n"));
assert_eq!((g.kind, g.filled_lines, g.line_width, tagged), (GraphKind::Line, true, Some(8.0), 2));
let fill = Some(Paint::solid(Color::cmyk(0.5, 0.0, 0.0, 0.0)));
assert!(g.series_paints.iter().all(|p| p.fill == fill && p.stroke.is_none() && p.stroke_width.is_none()), "{:?}", g.series_paints);
assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 3 44 Gy\n")).0.line_width, None, "3 pt");
assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 6 44 Gy\n")).0.line_width, Some(6.0), "6 pt");
assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 100 44 Gy\n")).0.line_width, Some(100.0), "100 pt");
assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 0.01 44 Gy\n")).0.line_width, Some(0.01), "0.01 pt");
// Without filled lines, the series are drawn as the graph's columns are.
let (g, _) = live(live_graph().replace(LIVE_STYLE, "%_7 0 0 14 1 0 1 0 8 44 Gy\n"));
assert_eq!((g.connect_points, g.filled_lines, g.line_width), (false, false, Some(8.0)), "points not connected");
let (g, _) = live(live_graph().replace(LIVE_STYLE, "%_7 0 0 14 1 1 0 0 0 44 Gy\n"));
assert_eq!((g.filled_lines, g.line_width), (false, None), "lines not filled, 0 pt");
}
/// A graph with filled lines whose Line Width the model doesn't hold (0, under 0.01 points, or out of
/// the records' 0 to 100), or with a lines-as-shapes value other than 0 and 1, keeps its drawn art
/// as plain objects, with one note.
#[test]
fn filled_lines_of_a_width_the_model_cant_hold_stay_plain_art() {
for style in [
"%_7 0 0 14 1 1 1 0 0 44 Gy\n",
"%_7 0 0 14 1 1 1 0 0.001 44 Gy\n",
"%_7 0 0 14 1 1 1 0 101 44 Gy\n",
"%_7 0 0 14 1 1 1 0 -2 44 Gy\n",
"%_7 0 0 14 1 1 1 0 1e999 44 Gy\n",
"%_7 0 0 14 1 1 0 0 101 44 Gy\n",
"%_7 0 0 14 1 1 2 0 8 44 Gy\n",
] {
let r = read(stream7(&layer7("Graph", &band_graph(style))).as_bytes()).unwrap_or_else(|e| panic!("{style}: {e}"));
assert_eq!(r.warnings, [GRAPH_PLAIN], "{style}");
assert_eq!(live_graphs(&r.doc), (vec![], 0), "{style}");
let mut kept = false;
r.doc.walk(|n| kept |= n.children().is_some_and(|c| c.len() == 3));
assert!(kept, "{style}: the drawn art is kept");
}
}
/// A graph keeps its drawn art and stays plain, with one note, when a record has a shape or value
/// appendix A doesn't give, sets what the model doesn't keep, or the table, the series tags or the
/// art don't fit the graph.
@@ -11433,7 +11495,7 @@ fn graphs_the_model_cant_keep_stay_plain_art() {
("type 11", live_graph().replace("%_5 0 0 14", "%_11 0 0 14")),
("legends in wedges", live_graph().replace("%_5 0 0 14", "%_5 0 0 15")),
("the right axis", live_graph().replace("6 44 Gy", "6 45 Gy")),
("lines as shapes", live_graph().replace("%_5 0 0 14 0 1 0", "%_5 0 0 14 0 1 1")),
("lines as shapes 0 pt wide", live_graph().replace("%_5 0 0 14 0 1 0 0 6", "%_5 0 0 14 0 1 1 0 0")),
("both axes alike", live_graph().replace(LIVE_DIALOG, "%_10 2 0 1 90 80 0 Gd\n")),
("a subscription", live_graph().replace(LIVE_DIALOG, &format!("{LIVE_DIALOG}%_0 0 1 1 1 Gj\n"))),
("a customization", live_graph().replace("GC\n", "GC\n%_2 Gt\n%_(Bars) GD\n%_GT\n")),
+60 -42
View File
@@ -31,6 +31,7 @@ pub(super) enum Source {
}
impl Interp<'_> {
#[allow(clippy::cognitive_complexity)] // One arm for each file operator, most of them a few lines.
pub fn data_op(&mut self, op: Op) -> Res {
use Op::*;
match op {
@@ -50,23 +51,7 @@ impl Interp<'_> {
ReadLine => {
let s = self.pop_str()?;
let Obj::File { stream: f, .. } = self.pop()? else { return ps_err("typecheck", "") };
let n = s.len();
let mut line = vec![];
let mut ended = false;
while line.len() < n {
match self.read(&f, 1)?.first() {
Some(b'\n') | None => {
ended = true;
break;
}
Some(b'\r') => {
self.skip_lf(&f);
ended = true;
break;
}
Some(b) => line.push(*b),
}
}
let (line, ended) = self.read_line(&f, s.len())?;
self.fill(s, &line)?;
self.push(Obj::Bool(ended))?;
}
@@ -219,38 +204,71 @@ impl Interp<'_> {
})
}
/// After `readline` consumes CR, consume only an immediately following LF. PostScript
/// treats CR/LF as one line ending (PLRM §3.8); raw reads must keep every other byte.
/// The preceding `read` has already materialized any pending filter.
fn skip_lf(&mut self, f: &Rc<RefCell<Stream>>) {
match &mut *f.borrow_mut() {
/// Run `scan` over the bytes left in file `f`, in one slice, and consume as many of them as
/// it says it used. A file still pending after `materialize` has no bytes left.
fn scan<T>(&mut self, f: &Rc<RefCell<Stream>>, scan: impl FnOnce(&[u8]) -> (T, usize)) -> Res<T> {
self.materialize(f)?;
Ok(match &mut *f.borrow_mut() {
Stream::Current => {
if self.lex.rest().first() == Some(&b'\n') {
self.lex.advance(1);
}
let (found, used) = scan(self.lex.data());
self.lex.advance(used);
found
}
Stream::Buf { data, pos, .. } => {
if data.get(*pos) == Some(&b'\n') {
*pos += 1;
}
let start = (*pos).min(data.len());
let (found, used) = scan(data.get(start..).unwrap_or_default());
*pos = start.saturating_add(used).min(data.len());
found
}
Stream::Pending { .. } => {}
}
Stream::Pending { .. } => scan(&[]).0,
})
}
/// Up to `n` bytes read as hexadecimal digits from `f` (other characters skipped).
pub(in super::super) fn read_hex(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> {
let mut out = Vec::with_capacity(n);
let mut high: Option<u8> = None;
while out.len() < n {
let Some(&b) = self.read(f, 1)?.first() else { break };
let Some(v) = char::from(b).to_digit(16) else { continue };
match high.take() {
Some(h) => out.push(h << 4 | v as u8),
None => high = Some(v as u8),
}
/// `readline` from `f` into a string of `n` bytes: the line, and whether it ended at a line
/// ending or at the end of the data. The line ending is consumed and left out of the line.
/// CR LF is one line ending (PLRM §3.8), and a lone CR leaves the byte after it unread. A
/// line that fills the string leaves the bytes after it unread, a line ending included.
pub(in super::super) fn read_line(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<(Vec<u8>, bool)> {
if n == 0 {
return Ok((vec![], false));
}
Ok(out)
self.scan(f, |data| {
let room = data.get(..n).unwrap_or(data);
match room.iter().position(|b| matches!(b, b'\n' | b'\r')) {
Some(i) => {
let crlf = room.get(i) == Some(&b'\r') && data.get(i + 1) == Some(&b'\n');
((room.get(..i).unwrap_or_default().to_vec(), true), i + 1 + usize::from(crlf))
}
None if room.len() == n => ((room.to_vec(), false), n),
None => ((room.to_vec(), true), room.len()),
}
})
}
/// Up to `n` bytes read as hexadecimal digits from `f` (other characters skipped). The read
/// stops at the digit that completes the `n`th byte and leaves what follows unread. A lone
/// digit at the end of the data gives no byte.
pub(in super::super) fn read_hex(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> {
if n == 0 {
return Ok(vec![]);
}
self.scan(f, |data| {
let mut out = Vec::with_capacity(n.min(data.len() / 2));
let mut high: Option<u8> = None;
let mut used = 0;
for &b in data {
if out.len() == n {
break;
}
used += 1;
let Some(v) = char::from(b).to_digit(16) else { continue };
match high.take() {
Some(h) => out.push(h << 4 | v as u8),
None => high = Some(v as u8),
}
}
(out, used)
})
}
/// Skip the whitespace and the `>` that end hexadecimal data in `f`, if a `>` is next: the
+34 -15
View File
@@ -257,22 +257,12 @@ pub(crate) fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
/// Hexadecimal digits (whitespace ignored, an odd last digit padded with 0); `None` on others.
pub(crate) fn hex_decode(body: &[u8]) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(body.len() / 2);
let mut high: Option<u8> = None;
for &b in body {
if is_space(b) {
continue;
}
let v = char::from(b).to_digit(16)? as u8;
match high.take() {
Some(h) => out.push(h << 4 | v),
None => high = Some(v),
}
// Callers pass an already-delimited body. Do not let the filter decoder's EOD
// handling silently accept a stray terminator or discard bytes after it.
if body.contains(&b'>') {
return None;
}
if let Some(h) = high {
out.push(h << 4);
}
Some(out)
craft_stream_codecs::asciihex::decode(body, body.len().div_ceil(2)).ok()
}
/// A number token (`12`, `-3.5`, `.5`, `1e-3`, `16#ff`), or `None`.
@@ -310,4 +300,33 @@ mod tests {
assert!(number("16#-ff").is_none());
assert!(matches!(number("16#ff"), Some(Obj::Int(255))));
}
#[test]
fn shared_hex_decode_keeps_body_boundaries_and_odd_nibbles() {
assert_eq!(hex_decode(b" 4\t1\n4\r2\x0c4\0"), Some(vec![0x41, 0x42, 0x40]));
assert_eq!(hex_decode(b""), Some(vec![]));
for invalid in [b"41>42".as_slice(), b">", b"4g", b"4\x0b1", b"\xff"] {
assert_eq!(hex_decode(invalid), None);
}
// Every byte pairs with each possible nibble, including all whitespace
// and invalid-byte combinations; this is the former body-only contract.
for first in 0..=255u8 {
for second in 0..=255u8 {
let input = [first, second];
let mut digits = Vec::new();
let mut valid = true;
for b in input {
if is_space(b) {
continue;
}
match char::from(b).to_digit(16) {
Some(d) => digits.push(d as u8),
None => valid = false,
}
}
let expected =
if !valid { None } else { Some(digits.chunks(2).map(|pair| (pair[0] << 4) | pair.get(1).copied().unwrap_or(0)).collect()) };
assert_eq!(hex_decode(&input), expected, "{input:?}");
}
}
}
}
+17
View File
@@ -106,6 +106,23 @@ fn image_data_comes_from_the_file_being_run() {
);
}
/// An image whose procedure reads its rows with `readhexstring` comes out with the same pixels as
/// the same samples given as one hexadecimal string, with the digits broken by CR LF, LF, tabs,
/// spaces and characters that are not digits, read from the program's own file and from a file
/// being run.
#[test]
fn hex_rows_read_by_a_procedure_match_a_hexadecimal_string() {
let rgb: Vec<u8> = (0..36u32).map(|i| (i * 37 % 256) as u8).collect();
let digits = hex(&rgb);
let breaks = ["\r\n", "\n", "\t", " z", "%"];
let broken: String = digits.as_bytes().chunks(5).zip(breaks.iter().cycle()).map(|(d, b)| format!("{}{b}", String::from_utf8_lossy(d))).collect();
let want = pixels(&read(&format!("10 10 scale 4 3 8 [4 0 0 -3 0 3] <{digits}> false 3 colorimage")), 4, 3);
assert_eq!(want, rgb.chunks(3).map(|p| [p[0], p[1], p[2], 255]).collect::<Vec<_>>());
let image = "10 10 scale 4 3 8 [4 0 0 -3 0 3] {currentfile 12 string readhexstring pop} false 3 colorimage";
assert_eq!(pixels(&read(&format!("{image}\r\n{broken}\n")), 4, 3), want);
assert_eq!(pixels(&read(&format!("currentfile 0 (endstream) /SubFileDecode filter cvx exec\n{image}\n{broken}\nendstream\n")), 4, 3), want);
}
/// A filter waits until it is first read, then reads the file it was made over, wherever the
/// program runs by then: one over the program's own file, read in a file being run, and one over
/// a file being run, read in a file that one runs.
+359
View File
@@ -0,0 +1,359 @@
//! `readhexstring` and `readline` (PLRM 3rd ed., §8.2) read the data left in a file in one pass.
//! The tests run the one-pass readers next to reference readers that take one byte per call, on the
//! same data in the same interpreter state: the program's own file after the whitespace that ends
//! the last token, a decoded buffer read from its start or part way in, and a filter decoded when it
//! is first read. The bytes, the result or error, and every byte left unread must agree.
use std::cell::RefCell;
use std::fmt::Debug;
use std::rc::Rc;
use std::time::{Duration, Instant};
use vectorcraft_doc::Document;
use vectorcraft_geom::{Affine, Rect};
use super::data::Stream;
use super::graphics::{GState, Out};
use super::interp::Interp;
use super::obj::{Obj, Res};
type File = Rc<RefCell<Stream>>;
/// Bytes as hexadecimal digits.
fn hex(data: &[u8]) -> String {
data.iter().map(|b| format!("{b:02x}")).collect()
}
/// An interpreter that has run `src` up to its `quit`, and the file object the program left on the
/// operand stack. What follows `quit` in `src` is still unread.
fn file_after(src: &[u8]) -> (Interp<'_>, File) {
let mut doc = Document::new(100.0, 100.0);
doc.layers.clear();
let page = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]);
let mut it = Interp::new(src, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0)));
assert_eq!(it.run(), Ok(()), "{}", String::from_utf8_lossy(src));
let Ok(Obj::File { stream, .. }) = it.pop() else { panic!("no file on the stack: {}", String::from_utf8_lossy(src)) };
(it, stream)
}
/// The reference `readline`: one byte per call, a CR followed by an LF ending the line once.
fn line_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<(Vec<u8>, bool)> {
let mut line = vec![];
let mut ended = false;
while line.len() < n {
match it.read(f, 1)?.first() {
Some(b'\n') | None => {
ended = true;
break;
}
Some(b'\r') => {
match &mut *f.borrow_mut() {
Stream::Current => {
if it.lex.rest().first() == Some(&b'\n') {
it.lex.advance(1);
}
}
Stream::Buf { data, pos, .. } => {
if data.get(*pos) == Some(&b'\n') {
*pos += 1;
}
}
Stream::Pending { .. } => {}
}
ended = true;
break;
}
Some(b) => line.push(*b),
}
}
Ok((line, ended))
}
/// The reference `readhexstring`: one byte per call, characters that are not hexadecimal digits
/// skipped.
fn hex_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> {
let mut out = Vec::with_capacity(n);
let mut high: Option<u8> = None;
while out.len() < n {
let Some(&b) = it.read(f, 1)?.first() else { break };
let Some(v) = char::from(b).to_digit(16) else { continue };
match high.take() {
Some(h) => out.push(h << 4 | v as u8),
None => high = Some(v as u8),
}
}
Ok(out)
}
fn line_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<(Vec<u8>, bool)> {
it.read_line(f, n)
}
fn hex_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> {
it.read_hex(f, n)
}
/// Hexadecimal data as CID `StartData` reads it: the digits, then a closing `>` if one is next.
fn hex_and_end_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> {
let d = it.read_hex(f, n)?;
it.skip_hex_end(f)?;
Ok(d)
}
fn hex_and_end_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> {
let d = hex_by_bytes(it, f, n)?;
it.skip_hex_end(f)?;
Ok(d)
}
/// How the program reaches the data.
#[derive(Clone, Copy, Debug)]
enum Form {
/// `currentfile`, with this whitespace after the token before the data.
Current(&'static [u8]),
/// A buffer decoded at once, with this many bytes of it read before the data.
Buf(usize),
/// An `ASCIIHexDecode` filter over `currentfile`, decoded when it is first read, with this
/// whitespace after the token before the digits.
Pending(&'static [u8]),
}
const FORMS: [Form; 13] = [
Form::Current(b" "),
Form::Current(b"\n"),
Form::Current(b"\r"),
Form::Current(b"\r\n"),
Form::Current(b"\r\r\n"),
Form::Current(b"\n\r"),
Form::Current(b"\t\t"),
Form::Buf(0),
Form::Buf(2),
Form::Buf(3),
Form::Pending(b"\n"),
Form::Pending(b"\r\n"),
Form::Pending(b" "),
];
/// A program that leaves a file over `data` on the operand stack, in form `form`.
fn program(form: Form, data: &[u8]) -> Vec<u8> {
match form {
Form::Current(lead) => [b"currentfile quit".as_slice(), lead, data].concat(),
Form::Buf(0) => format!("<{}> /ReusableStreamDecode filter quit", hex(data)).into_bytes(),
Form::Buf(skip) => {
let before = b"\r\n\r".get(..skip).unwrap_or(b"\r\n\r".as_slice());
format!("<{}{}> /ReusableStreamDecode filter dup {skip} string readstring pop pop quit", hex(before), hex(data)).into_bytes()
}
Form::Pending(lead) => [b"currentfile /ASCIIHexDecode filter quit".as_slice(), lead, hex(data).as_bytes(), b"> tail"].concat(),
}
}
type Reader<T> = fn(&mut Interp, &File, usize) -> Res<T>;
/// Read `data` in `form` with `one_pass` and with `by_bytes` in two interpreters in the same state,
/// and check that they agree on the result and on everything left to read.
fn agree<T: PartialEq + Debug>(form: Form, data: &[u8], n: usize, one_pass: Reader<T>, by_bytes: Reader<T>) {
let src = program(form, data);
let (mut a, fa) = file_after(&src);
let (mut b, fb) = file_after(&src);
let at = || format!("{form:?}, {:?}, n = {n}", String::from_utf8_lossy(data));
assert_eq!(one_pass(&mut a, &fa, n), by_bytes(&mut b, &fb, n), "result: {}", at());
assert_eq!(a.lex.rest(), b.lex.rest(), "program left unread: {}", at());
assert_eq!(a.read(&fa, usize::MAX), b.read(&fb, usize::MAX), "file left unread: {}", at());
assert_eq!(a.lex.rest(), b.lex.rest(), "program left after the file: {}", at());
a.release();
b.release();
}
/// A fixed sequence of pseudo-random numbers (xorshift), so a failure repeats.
struct Rng(u64);
impl Rng {
fn below(&mut self, n: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % n.max(1) as u64) as usize
}
}
/// `chosen`, then `count` strings of up to 24 bytes from `alphabet`.
fn samples(chosen: &[&[u8]], alphabet: &[u8], count: usize, rng: &mut Rng) -> Vec<Vec<u8>> {
let random = (0..count).map(|_| {
let len = rng.below(25);
(0..len).filter_map(|_| alphabet.get(rng.below(alphabet.len())).copied()).collect()
});
chosen.iter().map(|s| s.to_vec()).chain(random).collect()
}
/// String lengths to read `data` with: none, one, past its end, exactly its length and one more,
/// and one at random.
fn lengths(data: &[u8], rng: &mut Rng) -> [usize; 6] {
[0, 1, 3, data.len(), data.len() + 1, rng.below(data.len() + 3)]
}
#[test]
fn readline_reads_in_one_pass_as_byte_by_byte() {
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
let chosen: [&[u8]; 16] = [
b"",
b"\n",
b"\r",
b"\r\n",
b"\n\r",
b"\r\r\n",
b"abc",
b"abc\n",
b"abc\r",
b"abc\rX",
b"abc\r\nX",
b"abc\n\nX",
b"abcdefgh\r\nX",
b"abcdefgh\nX",
b"a\0b\xff\rX",
b"abc\r\n",
];
for data in samples(&chosen, b"ab\r\n\r\n x\0\xff", 40, &mut rng) {
for form in FORMS {
for n in lengths(&data, &mut rng) {
agree(form, &data, n, line_one_pass, line_by_bytes);
}
}
}
}
#[test]
fn readhexstring_reads_in_one_pass_as_byte_by_byte() {
let mut rng = Rng(0x2545_f491_4f6c_dd1d);
let chosen: [&[u8]; 14] = [
b"",
b"0",
b"a",
b"0a",
b"0a1",
b"0 a\r\n1b>X",
b"zz0g1",
b"ff\r\n00\nAA",
b"0a1b2c3d",
b"0a1b\r\n2c>",
b"\r\n0a",
b"a b c d e",
b"0a>",
b"0a \r\n >X",
];
for data in samples(&chosen, b"0123456789abcdefABCDEFg \r\n\t>z%", 40, &mut rng) {
for form in FORMS {
for n in lengths(&data, &mut rng) {
agree(form, &data, n, hex_one_pass, hex_by_bytes);
agree(form, &data, n, hex_and_end_one_pass, hex_and_end_by_bytes);
}
}
}
}
/// `readline` of `data` into `n` bytes, after `currentfile` and a CR LF, gives `line` and `ended`
/// and leaves `left` unread.
fn line_case(data: &[u8], n: usize, line: &[u8], ended: bool, left: &[u8]) {
let src = program(Form::Current(b"\r\n"), data);
let (mut it, f) = file_after(&src);
assert_eq!(it.read_line(&f, n), Ok((line.to_vec(), ended)), "{:?}", String::from_utf8_lossy(data));
assert_eq!(it.read(&f, usize::MAX), Ok(left.to_vec()), "{:?}", String::from_utf8_lossy(data));
it.release();
}
/// `readhexstring` of `data` into `n` bytes, after `currentfile` and a CR LF, gives `bytes` and
/// leaves `left` unread in the program.
fn hex_case(data: &[u8], n: usize, bytes: &[u8], left: &[u8]) {
let src = program(Form::Current(b"\r\n"), data);
let (mut it, f) = file_after(&src);
assert_eq!(it.read_hex(&f, n), Ok(bytes.to_vec()), "{:?}", String::from_utf8_lossy(data));
assert_eq!(it.lex.rest(), left, "{:?}", String::from_utf8_lossy(data));
it.release();
}
/// The results the one-pass readers give at the edges of the data, stated directly.
#[test]
fn one_pass_reads_stop_where_their_data_ends() {
// A CR LF ends one line; a lone CR leaves the next byte unread.
line_case(b"ab\r\nX", 8, b"ab", true, b"X");
line_case(b"ab\rX", 8, b"ab", true, b"X");
line_case(b"ab\nX", 8, b"ab", true, b"X");
// A line that fills the string leaves its line ending unread.
line_case(b"abcd\nX", 4, b"abcd", false, b"\nX");
line_case(b"abc\r\nX", 3, b"abc", false, b"\r\nX");
// The end of the data ends the line.
line_case(b"ab", 8, b"ab", true, b"");
line_case(b"", 8, b"", true, b"");
// The read stops on the digit that completes the last byte.
hex_case(b"0a\r\n1b>X", 2, &[0x0a, 0x1b], b">X");
// Characters that are not digits are skipped.
hex_case(b"z0 g\ta%", 1, &[0x0a], b"%");
// A lone digit at the end of the data gives no byte.
hex_case(b"0a1", 2, &[0x0a], b"");
hex_case(b"\r\n", 2, &[], b"");
// No byte to read takes nothing, not even the whitespace after the token.
hex_case(b"0a", 0, &[], b"\r\n0a");
}
/// The median of `runs`.
fn median(runs: &[Duration]) -> Duration {
let mut sorted = runs.to_vec();
sorted.sort();
sorted.get(sorted.len() / 2).copied().unwrap_or_default()
}
/// Read all of `src`'s data with `reader` in strings of `n` bytes, `calls` times, and how long it
/// took. The interpreter is made before the clock starts.
fn timed<T>(src: &[u8], reader: Reader<T>, n: usize, calls: usize) -> (Vec<T>, Duration) {
let (mut it, f) = file_after(src);
let start = Instant::now();
let got: Vec<T> = (0..calls).map(|_| reader(&mut it, &f, n).unwrap_or_else(|e| panic!("{e:?}"))).collect();
let took = start.elapsed();
it.release();
(got, took)
}
/// Time both readers on `src` in 7 runs, alternating which goes first, check that they read the
/// same, and print every run and the medians.
fn compare<T: PartialEq>(what: &str, src: &[u8], one_pass: Reader<T>, by_bytes: Reader<T>, n: usize, calls: usize) {
let (mut old, mut new) = (vec![], vec![]);
for run in 0..7 {
let order: [bool; 2] = if run % 2 == 0 { [false, true] } else { [true, false] };
let mut got = vec![];
for one in order {
let (read, took) = timed(src, if one { one_pass } else { by_bytes }, n, calls);
if one {
new.push(took)
} else {
old.push(took)
}
got.push(read);
}
assert!(got.first() == got.get(1), "{what}: the readers differ");
}
let ms = |d: &Duration| format!("{:.1}", d.as_secs_f64() * 1000.0);
println!("{what}: {} bytes of data, {calls} calls of {n} bytes", src.len());
println!(" byte by byte, ms: {}", old.iter().map(ms).collect::<Vec<_>>().join(" "));
println!(" one pass, ms: {}", new.iter().map(ms).collect::<Vec<_>>().join(" "));
let (o, w) = (median(&old), median(&new));
println!(" median: byte by byte {} ms, one pass {} ms, {:.1}x", ms(&o), ms(&w), o.as_secs_f64() / w.as_secs_f64().max(1e-9));
}
/// Times the one-pass readers against the byte-at-a-time reference readers on the same data in one
/// process: the hexadecimal samples of a 1000 × 1000 RGB image in lines of 64 digits, read a row
/// of 3,000 bytes at a time, and 200,000 lines of 40 bytes read by `readline` into an 80-byte
/// string. Run it in release:
/// `cargo test --release -p vectorcraft-eps --lib tests_reads::one_pass_reads_timed -- --ignored --nocapture`.
#[test]
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
fn one_pass_reads_timed() {
let rgb: Vec<u8> = (0..3_000_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8).collect();
let digits = hex(&rgb);
let mut data = Vec::with_capacity(digits.len() + digits.len() / 64 + 1);
for line in digits.as_bytes().chunks(64) {
data.extend_from_slice(line);
data.push(b'\n');
}
compare("readhexstring", &program(Form::Current(b"\n"), &data), hex_one_pass, hex_by_bytes, 3_000, 1_000);
let lines: Vec<u8> = (0..200_000).flat_map(|i| format!("{:<39}\n", format!("line {i}")).into_bytes()).collect();
compare("readline", &program(Form::Current(b"\n"), &lines), line_one_pass, line_by_bytes, 80, 200_000);
}
+2 -2
View File
@@ -209,7 +209,7 @@ pub fn tool_definitions() -> Vec<Value> {
"x": num("Document x (pt)"),
"y": num("Document y (pt)"),
"mods": mods_schema(),
"backquote": {"type": "boolean", "description": "Backquote held for this event: Selection and transform tool drags transform only pattern paint"},
"backquote": {"type": "boolean", "description": "Backquote held for this event: Selection and transform tool drags transform only pattern paint; Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment drags leave copies of the shape being drawn"},
"pressure": num("Pen pressure 0..1 (default 1): the Liquify tools' intensity with Use Pressure Pen on, and the pressure the Paintbrush records"),
"tiltX": num("Pen tilt in degrees −90..90, positive leaning right (document axes); with tiltY, the tilt the Paintbrush records for Tilt and Bearing brushes. One without the other is 0"),
"tiltY": num("Pen tilt in degrees −90..90, positive leaning down the page"),
@@ -218,7 +218,7 @@ pub fn tool_definitions() -> Vec<Value> {
}), &["kind", "x", "y"]),
},
"mods": mods_schema(),
"backquote": {"type": "boolean", "description": "Default backquote held state for events: Selection and transform tool drags transform only pattern paint"},
"backquote": {"type": "boolean", "description": "Default backquote held state for events: Selection and transform tool drags transform only pattern paint; Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment drags leave copies of the shape being drawn"},
}),
&["events"],
),
+6
View File
@@ -1647,6 +1647,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{set?: index, action?: index} copy the Actions panel's action at action in set (0 is the top set) to right after it in the same set; without action, copy set with all its actions to right after it (default: the current set). The copy is named after the original with \" copy\" added, a copied set gets an id of its own, and the copy is selected. The panel menu's Duplicate runs this for the selected action, else the current set. An index past the last set or action, or a copy that would give its set more than 1,000 actions or an action set file larger than 8 MiB, is an error and copies nothing → {set, action?}",
),
(
"ui.actionSet.reset",
"Reset Actions",
"",
"{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}",
),
("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"),
(
"docInfo.save",
+8
View File
@@ -61,6 +61,14 @@ Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` t
`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas.
```rust
pub struct Adjacency { pub faces: Vec<MapFace>, pub edges: Vec<MapEdge>, pub slivers: Vec<PathData>, pub outlines: Vec<MapOutline> }
pub struct MapEdge { pub path: PathData, pub sources: Vec<usize>, pub left: Option<usize>, pub right: Option<usize>, pub piece: usize }
pub fn adjacency(shapes: &[Shape], precision: f64) -> Option<Adjacency>;
```
`adjacency` maps the paths as `live_paint` does and also reports, for each edge, every input it lies on and the faces on its left and right as it runs along its path (document coordinates, y down). A line drawn on top of another keeps both inputs on the edge, whatever the input order. A piece of line that ends inside a face has that face on both sides. Faces narrower than `precision` are listed as slivers, and `outlines` holds the outer boundary of each connected piece of the paths. It returns `None` for more than `SHAPE_BUILDER_MAX_SEGMENTS` segments, non-finite input or a `precision` that is not a positive number.
## Offset / stroke
```rust
+146 -22
View File
@@ -77,7 +77,10 @@ impl Outline {
pub fn ellipse(unit: Affine) -> Result<Self, OutlineError> {
let [a, b, c, d, e, f] = unit.as_coeffs();
let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs());
if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= 1e-12 * norm * norm {
// The determinant is rounded by about `f64::EPSILON * norm²`; one no larger than that may
// belong to a map with no area. An ellipse whose determinant is larger is measured
// exactly.
if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= f64::EPSILON * norm * norm {
return Err(OutlineError::Empty);
}
Ok(Outline::Ellipse { center: Point::new(e, f), m: [a, b, c, d] })
@@ -153,6 +156,16 @@ impl Outline {
if segments.iter().any(|s| bends_against(s, sign)) {
return Err(OutlineError::NotConvex);
}
// A corner can also turn inward between two of the points: each join is checked by the
// directions the segments leave and reach it in. Segments of no length are passed over.
let nonzero = |vs: [Vec2; 3]| vs.into_iter().find(|v| v.hypot() > 1e-9 * size).map(|v| v / v.hypot());
let ends: Vec<(Vec2, Vec2)> = segments
.iter()
.filter_map(|s| nonzero([s.p1 - s.p0, s.p2 - s.p0, s.p3 - s.p0]).zip(nonzero([s.p3 - s.p2, s.p3 - s.p1, s.p3 - s.p0])))
.collect();
if ends.iter().enumerate().any(|(i, (_, end))| ends[(i + 1) % ends.len()].0.cross(*end) * sign > 1e-9) {
return Err(OutlineError::NotConvex);
}
let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point();
if !center.x.is_finite() || !center.y.is_finite() {
return Err(OutlineError::Empty);
@@ -246,7 +259,7 @@ impl Outline {
}
/// The diagonal of the bounds (an ellipse's: of the box its axes span).
fn size(&self) -> f64 {
pub fn size(&self) -> f64 {
match self {
Outline::Ellipse { m, .. } => {
let [a, b, c, d] = *m;
@@ -270,11 +283,13 @@ impl Outline {
}
}
/// The points of the outline on the line `p · n = h`, its support value: the point where
/// `p · n` is largest, and the ends of any straight side along the line. Another point counts
/// when it lies within `tol` of the line plus `slope` times its distance from that largest
/// point, where `slope` is how far off the normal's angle may be.
fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64) -> Vec<Point> {
/// The points of the outline on the line `p · n = h`, its support value, which is reached on
/// segment `at`: the point where `p · n` is largest, and the ends of any straight side along
/// the line. Another point counts when it lies within `tol` of the line plus `slope` times its
/// distance from that largest point, where `slope` is how far off the normal's angle may be.
/// On a convex outline the points that count form one run around the largest one, so the
/// segments are measured from `at` outward both ways until a segment's end does not count.
fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64, at: usize) -> Vec<Point> {
match self {
Outline::Ellipse { center, m: [a, b, c, d] } => {
let w = Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y);
@@ -282,9 +297,25 @@ impl Outline {
vec![*center + Vec2::new(a * w.x + c * w.y, b * w.x + d * w.y)]
}
Outline::Convex { segments, .. } => {
let len = segments.len();
let mut all = vec![];
for s in segments {
each_extreme(s, n, |p, v| all.push((p, v)));
let Some(first) = segments.get(at % len.max(1)) else { return vec![] };
each_extreme(first, n, |p, v| all.push((p, v)));
let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] };
let counts = |p: Point| h - p.to_vec2().dot(n) <= tol + slope * (p - peak).hypot();
let mut ahead = 0;
for j in 1..len {
match segments.get((at + j) % len) {
Some(s) if counts(s.p0) => each_extreme(s, n, |p, v| all.push((p, v))),
_ => break,
}
ahead = j;
}
for j in 1..len - ahead {
match segments.get((at + len - j) % len) {
Some(s) if counts(s.p3) => each_extreme(s, n, |p, v| all.push((p, v))),
_ => break,
}
}
let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] };
all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect()
@@ -293,8 +324,6 @@ impl Outline {
}
}
/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where
/// the curve runs square to `n`) and the value there.
/// Whether cubic `s` bends against `sign` (the way its outline turns) anywhere. The cross product
/// of its first and second derivatives is a quadratic in t; its lowest value on [0, 1] is compared
/// with the segment's control polygon length squared.
@@ -321,7 +350,17 @@ fn bends_against(s: &CubicBez, sign: f64) -> bool {
low < -1e-9 * scale
}
#[cfg(test)]
thread_local! {
/// How many times [`each_extreme`] has measured a segment on this thread, for the tests.
static EXTREMES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where
/// the curve runs square to `n`) and the value there.
fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) {
#[cfg(test)]
EXTREMES.with(|n| n.set(n.get() + 1));
let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n));
f(s.p0, v0);
f(s.p3, v3);
@@ -396,10 +435,11 @@ pub fn common_tangents(a: &Outline, b: &Outline) -> Result<Vec<Tangent>, Coincid
let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0);
let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?;
let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?;
let (a, b) = (Hinted { o: a, at: &at, hints: &ha }, Hinted { o: b, at: &at, hints: &hb });
let mut out = Vec::with_capacity(external.len() + internal.len());
for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] {
for root in list {
let t = tangent_at(a, b, kind, dir(root.angle), root.double, size);
let t = tangent_at(&a, &b, kind, root.angle, root.double, size);
out.push(Tangent { from: t.from + origin, to: t.to + origin, ..t });
}
}
@@ -414,21 +454,47 @@ struct Root {
double: bool,
}
/// The tangent of `kind` whose normal is `n`: `a` lies where `p · n` is at most the line's value,
/// and `b` on the same side (external) or the other side (internal). `double` when the outlines
/// touch there.
fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool, size: f64) -> Tangent {
/// An outline with the segment it is touched on at each sampled normal angle.
struct Hinted<'a> {
o: &'a Outline,
at: &'a [f64],
hints: &'a [usize],
}
impl Hinted<'_> {
/// The support value at the normal angle `angle` and the segment it is reached on, walking on
/// from the segment of the sample at or before `angle`.
fn support(&self, angle: f64) -> (f64, usize) {
let angle = angle.rem_euclid(TAU);
// Before the first sample, the last one (taken 2π back) comes before `angle`.
let k = self.at.partition_point(|t| *t <= angle).checked_sub(1).unwrap_or(self.at.len().saturating_sub(1));
self.o.support_from(dir(angle), self.hints.get(k).copied().unwrap_or(0))
}
}
/// The tangent of `kind` whose normal is at `angle`: `a` lies where `p · n` is at most the line's
/// value, and `b` on the same side (external) or the other side (internal). `double` when the
/// outlines touch there.
fn tangent_at(a: &Hinted, b: &Hinted, kind: TangentKind, angle: f64, double: bool, size: f64) -> Tangent {
let n = dir(angle);
// The rounding allowed in `p · n` grows with each outline's own size and its distance from the
// origin.
let rounding = |o: &Outline| 1e-12 * o.size() + 1e-14 * (o.center().to_vec2().hypot() + o.size());
let (tol_a, tol_b) = (rounding(a), rounding(b));
let (tol_a, tol_b) = (rounding(a.o), rounding(b.o));
// Bisection finds a simple root's angle to about the rounding of the support values; the
// golden-section search finds a double root's to about 1e-8 radians.
let slope = if double { 1e-7 } else { 1e-10 };
let ha = a.support(n);
let (on_a, on_b) = match kind {
TangentKind::External => (a.touching(n, ha, tol_a, slope), b.touching(n, b.support(n), tol_b, slope)),
TangentKind::Internal => (a.touching(n, ha, tol_a, slope), b.touching(-n, b.support(-n), tol_b, slope)),
let (ha, sa) = a.support(angle);
let on_a = a.o.touching(n, ha, tol_a, slope, sa);
let on_b = match kind {
TangentKind::External => {
let (hb, sb) = b.support(angle);
b.o.touching(n, hb, tol_b, slope, sb)
}
TangentKind::Internal => {
let (hb, sb) = b.support(angle + TAU / 2.0);
b.o.touching(-n, hb, tol_b, slope, sb)
}
};
// Positions along the line, which runs square to `n` through `n * ha`.
let t = Vec2::new(-n.y, n.x);
@@ -441,7 +507,7 @@ fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool
// stand a little apart.
let (from, to) = if double && hi - lo <= 1e-6 * size {
// Touching at one point: the narrower outline's width along the line, centered there.
let width = [a, b].map(|o| o.support(t) + o.support(-t)).into_iter().fold(f64::MAX, f64::min);
let width = [a, b].map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0).into_iter().fold(f64::MAX, f64::min);
let mid = (lo + hi) / 2.0;
(mid - width / 2.0, mid + width / 2.0)
} else if mean(&on_a) <= mean(&on_b) {
@@ -575,6 +641,8 @@ fn golden(g: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> (f64, f64) {
#[cfg(test)]
mod tests {
use std::cell::Cell;
use kurbo::Rect;
use vectorcraft_geom::shapes;
@@ -850,6 +918,53 @@ mod tests {
assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 200.0 * (TAU / 1600.0).sin()).abs() < 1e-6), "{:?}", all.first());
}
#[test]
fn each_tangent_measures_only_the_segments_near_where_it_touches() {
// Two regular 2,000-gons about one center, one turned half a step: 4,000 external
// tangents. Measuring every segment of both outlines for every tangent takes about 8,000
// measurements per tangent.
let sides = 2_000;
let gon = |turn: f64| {
let pts: Vec<Point> = (0..sides).map(|k| (dir(turn + TAU * k as f64 / sides as f64) * 100.0).to_point()).collect();
SubPath::polyline(&pts, true)
};
let (a, b) = (Outline::convex(&gon(0.0)).unwrap(), Outline::convex(&gon(TAU / (2 * sides) as f64)).unwrap());
EXTREMES.with(|c| c.set(0));
let all = common_tangents(&a, &b).unwrap();
let calls = EXTREMES.with(Cell::get);
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2 * sides);
assert!(calls < 1_000 * all.len(), "{calls} measurements for {} tangents", all.len());
let r = 100.0 * (TAU / (4 * sides) as f64).sin();
assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 2.0 * r).abs() < 1e-6), "{:?}", all.first());
}
#[test]
fn a_very_thin_ellipse_is_measured_exactly() {
// Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle, then the whole figure turned
// 30 degrees: the tangents run from the ellipse's tips to the circle.
for deg in [0.0, 30.0] {
let turn = Affine::rotate(f64::to_radians(deg));
let thin = turn * Affine::scale_non_uniform(1e6, 1e-7);
let round = turn * Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]);
let all = common_tangents(&Outline::ellipse(thin).unwrap(), &Outline::ellipse(round).unwrap()).unwrap();
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}");
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}");
let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(round, 5_000));
for t in &all {
check_against_samples(t, &sa, &sb, 1e-3);
// The end on the ellipse, taken back to the unturned figure.
let (from, to) = (turn.inverse() * t.from, turn.inverse() * t.to);
let tip = if (from.x.abs() - 1e6).abs() < 1e-3 { from } else { to };
assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{deg} {t:?}");
}
}
// A determinant a few times its rounding is taken; one lost in the rounding of the map's
// entries is still refused.
assert!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, 4.0 * f64::EPSILON, 0.0, 0.0])).is_ok());
assert_eq!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty));
assert_eq!(Outline::ellipse(Affine::new([1.0, 1.0, 1.0, 1.0 + f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty));
}
#[test]
fn a_curve_peaking_inside_a_segment_is_measured_at_its_peak() {
// p(t) · n has the control values 0, 0.25, 0.5, -0.25: its derivative's linear term is
@@ -877,6 +992,15 @@ mod tests {
bp.close_path();
let bend = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone();
assert_eq!(Outline::convex(&bend).err(), Some(OutlineError::NotConvex));
// A triangle whose first side is a cubic that leaves its start a little the wrong way: the
// corner there turns inward, though the checked points and the curve itself turn one way.
let mut bp = vectorcraft_geom::BezPath::new();
bp.move_to((0.0, 0.0));
bp.curve_to((-1.0, -1.0), (66.0, -2.0), (100.0, 0.0));
bp.line_to((50.0, 100.0));
bp.close_path();
let notch = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone();
assert_eq!(Outline::convex(&notch).err(), Some(OutlineError::NotConvex));
// A square traced twice around winds around twice.
let twice: Vec<Point> = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect();
assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex));
+2 -2
View File
@@ -30,8 +30,8 @@ pub use fit::{fit_cubics, fit_cubics_through};
pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path};
pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_within};
pub use planar::{
BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, find_gaps, has_open_path, interior_point,
live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap,
Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out,
encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap,
};
pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band};
+2
View File
@@ -26,12 +26,14 @@ use vectorcraft_geom::{FillRule, PathData, SubPath};
use crate::boolean::{DEFAULT_PRECISION, Seg, Tidy, eps_for, is_sliver, segs_to_subpath, snap_horizontals, tidy_segments, to_seg};
use crate::pathfinder::{Region, Shape};
mod adjacency;
mod graph;
mod index;
mod live_paint;
mod map;
mod shape_builder;
pub use adjacency::{Adjacency, MapEdge, MapFace, MapOutline, adjacency};
pub(crate) use graph::pin_ends;
#[cfg(test)]
use index::{Crossings, RectIndex, reference_budget, segment_footprint, work_done};
+169
View File
@@ -0,0 +1,169 @@
//! Which faces of a planar map each edge separates, and every input each edge lies on.
//!
//! [`live_paint`](super::live_paint) gives each edge under its front-most input only, and says
//! nothing about the faces on its sides. [`adjacency`] reads both from the same planar map, so a
//! caller can tell which faces a line divides and which lines lie on top of each other.
use super::graph::{find, half_segs, twin, unshear};
use super::index::RectIndex;
use super::map::{Map, map_with};
use super::*;
/// A planar map of some paths with each edge's sides and inputs ([`adjacency`]).
#[derive(Clone, Debug, Default)]
pub struct Adjacency {
pub faces: Vec<MapFace>,
pub edges: Vec<MapEdge>,
/// Bounded areas left out as slivers: narrower than the precision on average, such as a thin
/// gap between two lines.
pub slivers: Vec<PathData>,
/// The outer boundary of each connected piece of the paths.
pub outlines: Vec<MapOutline>,
}
/// A bounded face: its outline, then the outer boundaries of the pieces inside it (as holes), and
/// its area without them.
#[derive(Clone, Debug)]
pub struct MapFace {
pub path: PathData,
pub area: f64,
/// The connected piece of the paths whose edges bound it.
pub piece: usize,
}
/// An edge: a piece of one or more inputs between two places where paths meet.
#[derive(Clone, Debug)]
pub struct MapEdge {
pub path: PathData,
/// Every input it lies on (indices into the inputs, ascending).
pub sources: Vec<usize>,
/// The faces on each side of it as it runs along `path`, seen on the page (document
/// coordinates, y down): `left` on the left. `None` outside every bounded face, or in a sliver.
/// A piece of line that ends loose inside a face has that face on both sides.
pub left: Option<usize>,
pub right: Option<usize>,
pub piece: usize,
}
/// The outer boundary of a connected piece of the paths.
#[derive(Clone, Debug)]
pub struct MapOutline {
pub path: PathData,
pub piece: usize,
}
/// The planar map of `shapes`, every path an edge as in [`live_paint`](super::live_paint), with
/// faces refit to `precision` and slivers narrower than it left out. `None` when the paths can't be
/// swept (non-finite, too degenerate, or more than [`SHAPE_BUILDER_MAX_SEGMENTS`] segments), when
/// `precision` is not a positive number, and when no path has two anchors.
pub fn adjacency(shapes: &[Shape], precision: f64) -> Option<Adjacency> {
if !(precision.is_finite() && precision > 0.0) {
return None;
}
let segments: usize = shapes.iter().flat_map(|s| &s.path.subpaths).map(SubPath::segment_count).sum();
if segments > SHAPE_BUILDER_MAX_SEGMENTS {
return None;
}
let m = map_with(shapes, false, precision)?;
Some(read(&m))
}
fn read(m: &Map) -> Adjacency {
let path = |cycle: &[usize], closed: bool| {
let segs: Vec<Seg> = cycle.iter().flat_map(|&h| half_segs(&m.edges, h)).collect();
segs_to_subpath(&tidy_segments(segs, closed, &m.tidy), closed)
};
let unsheared = |subpaths: Vec<SubPath>| unshear(PathData::new(subpaths), &m.anchors, m.snap);
// Connected pieces, by the vertices the edges join, numbered in the order they are first met.
let vertices = m.edges.iter().flat_map(|e| e.ends).max().map_or(0, |v| v + 1);
let mut parent: Vec<usize> = (0..vertices).collect();
for e in &m.edges {
let (a, b) = (find(&mut parent, e.ends[0]), find(&mut parent, e.ends[1]));
if let Some(p) = parent.get_mut(a) {
*p = b;
}
}
let mut number: Vec<Option<usize>> = vec![None; vertices];
let mut pieces = 0;
let mut piece_of_vertex = |v: usize| {
let root = find(&mut parent, v);
match number.get_mut(root) {
Some(Some(n)) => *n,
Some(slot) => {
*slot = Some(pieces);
pieces += 1;
pieces - 1
}
None => 0,
}
};
let edge_pieces: Vec<usize> = m.edges.iter().map(|e| piece_of_vertex(e.ends[0])).collect();
let piece_of = |cycle: &[usize]| cycle.first().and_then(|&h| edge_pieces.get(h / 2)).copied().unwrap_or(0);
// The face on each half-edge's side: a face's own cycle, and the outer boundaries of the
// pieces inside it, bound it.
let mut face_of: Vec<Option<usize>> = vec![None; 2 * m.edges.len()];
let mut faces = Vec::with_capacity(m.faces.len());
for (i, (cycle, _, area)) in m.faces.iter().enumerate() {
let holes: Vec<&(Vec<usize>, BezPath)> = m.face_holes.get(i).into_iter().flatten().filter_map(|&k| m.holes.get(k)).collect();
for &h in cycle.iter().chain(holes.iter().flat_map(|(c, _)| c)) {
if let Some(f) = face_of.get_mut(h) {
*f = Some(i);
}
}
let mut subpaths: Vec<SubPath> = path(cycle, true).into_iter().collect();
subpaths.extend(holes.iter().filter_map(|(c, _)| path(c, true)));
// A hole's outer boundary winds the other way: its area is negative.
let area = area + holes.iter().map(|(_, bp)| bp.area()).sum::<f64>();
faces.push(MapFace { path: unsheared(subpaths), area, piece: piece_of(cycle) });
}
// A face walk leaves out the edges that end loose (spurs): such an edge lies inside the face
// around its middle, on both sides.
let mut on_cycle = vec![false; 2 * m.edges.len()];
let cycles = m.faces.iter().map(|f| &f.0).chain(m.holes.iter().map(|h| &h.0)).chain(m.slivers.iter().map(|s| &s.0));
for &h in cycles.flatten() {
if let Some(c) = on_cycle.get_mut(h) {
*c = true;
}
}
let spur = |e: usize| !on_cycle.get(2 * e).copied().unwrap_or(true) && !on_cycle.get(twin(2 * e)).copied().unwrap_or(true);
// The faces by their bounds, so that each spur tests only the faces whose bounds hold it;
// built only when there is a spur.
let bezpaths: Vec<BezPath> = if (0..m.edges.len()).any(spur) { faces.iter().map(|f| f.path.to_bezpath()).collect() } else { vec![] };
let face_index = RectIndex::new(bezpaths.iter().enumerate().map(|(i, bp)| (bp.bounding_box(), i)).collect());
let face_around = |p: Point| {
face_index
.at(p, 0.0)
.copied()
.filter(|&i| bezpaths.get(i).is_some_and(|bp| bp.winding(p) != 0))
.min_by(|&a, &b| faces.get(a).map_or(f64::INFINITY, |f| f.area).total_cmp(&faces.get(b).map_or(f64::INFINITY, |f| f.area)))
};
// A face cycle winds so its face is on the side where the cross product of the half-edge's
// direction and the way to the face is positive: on the page, with y down, that is the right.
let edges = m
.edges
.iter()
.enumerate()
.filter_map(|(e, edge)| {
let sp = path(&[2 * e], false)?;
let path = unsheared(vec![sp]);
let (left, right) = if spur(e) {
let around = path.to_bezpath().segments().next().map(|s| s.eval(0.5)).and_then(face_around);
(around, around)
} else {
(face_of.get(twin(2 * e)).copied().flatten(), face_of.get(2 * e).copied().flatten())
};
Some(MapEdge { path, sources: edge.sources.clone(), left, right, piece: edge_pieces.get(e).copied().unwrap_or(0) })
})
.collect();
let slivers = m.slivers.iter().filter_map(|(cycle, _)| path(cycle, true)).map(|sp| unsheared(vec![sp])).collect();
let outlines =
m.holes.iter().filter_map(|(cycle, _)| Some(MapOutline { path: unsheared(vec![path(cycle, true)?]), piece: piece_of(cycle) })).collect();
Adjacency { faces, edges, slivers, outlines }
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,200 @@
use super::*;
use kurbo::{ParamCurveNearest, Vec2};
use proptest::prelude::*;
use vectorcraft_geom::{FillRule, Rect, shapes};
fn line(a: (f64, f64), b: (f64, f64)) -> Shape {
Shape::new(PathData::single(SubPath::polyline(&[Point::new(a.0, a.1), Point::new(b.0, b.1)], false)), FillRule::NonZero, 0)
}
fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Shape {
Shape::new(shapes::rectangle(Rect::new(x0, y0, x1, y1)), FillRule::NonZero, 0)
}
fn inside(f: &MapFace, p: Point) -> bool {
f.path.to_bezpath().winding(p) != 0
}
/// The edges whose middle lies within 0.01 of `p`.
fn edges_at(a: &Adjacency, p: Point) -> Vec<&MapEdge> {
a.edges
.iter()
.filter(|e| {
let bp = e.path.to_bezpath();
bp.segments().any(|s| {
let n = s.nearest(p, 1e-6);
n.distance_sq < 1e-4
})
})
.collect()
}
#[test]
fn a_line_across_a_rectangle_divides_two_faces_it_lies_between() {
let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), line((40.0, -10.0), (40.0, 60.0))], DEFAULT_PRECISION).unwrap();
assert_eq!(a.faces.len(), 2, "{:?}", a.faces);
let left_face = a.faces.iter().position(|f| inside(f, Point::new(20.0, 25.0))).unwrap();
let right_face = a.faces.iter().position(|f| inside(f, Point::new(70.0, 25.0))).unwrap();
assert_ne!(left_face, right_face);
assert!((a.faces[left_face].area - 2000.0).abs() < 1e-6 && (a.faces[right_face].area - 3000.0).abs() < 1e-6);
let shared = edges_at(&a, Point::new(40.0, 25.0));
assert_eq!(shared.len(), 1, "{shared:?}");
let e = shared[0];
assert_eq!(e.sources, vec![1]);
let mut sides = [e.left.unwrap(), e.right.unwrap()];
sides.sort_unstable();
let mut want = [left_face, right_face];
want.sort_unstable();
assert_eq!(sides, want);
// The rectangle's own sides have a face on one side only; the line's ends stick out into no face.
let side = edges_at(&a, Point::new(70.0, 0.0));
assert_eq!(side.len(), 1);
assert_eq!([side[0].left, side[0].right].iter().flatten().count(), 1);
let stub = edges_at(&a, Point::new(40.0, -5.0));
assert_eq!((stub[0].left, stub[0].right), (None, None));
assert!(a.faces.iter().all(|f| f.piece == 0) && a.edges.iter().all(|e| e.piece == 0));
}
#[test]
fn a_line_that_ends_inside_a_face_has_that_face_on_both_sides() {
let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), line((50.0, 0.0), (50.0, 30.0)), line((20.0, 10.0), (30.0, 20.0))], DEFAULT_PRECISION).unwrap();
assert_eq!(a.faces.len(), 1);
for at in [Point::new(50.0, 15.0), Point::new(25.0, 15.0)] {
let e = edges_at(&a, at);
assert_eq!(e.len(), 1, "{at:?}");
assert_eq!((e[0].left, e[0].right), (Some(0), Some(0)), "{at:?}");
}
}
#[test]
fn loose_lines_in_many_faces_look_only_at_the_faces_near_them() {
// A 40 × 40 grid of separate squares, then the same with a loose line in each.
let squares: Vec<Shape> =
(0..1600).map(|k| (f64::from(k % 40) * 20.0, f64::from(k / 40) * 20.0)).map(|(x, y)| rect(x, y, x + 10.0, y + 10.0)).collect();
let started = super::super::index::work_done();
assert_eq!(adjacency(&squares, DEFAULT_PRECISION).unwrap().faces.len(), 1600);
let plain = super::super::index::work_done() - started;
let mut all = squares.clone();
all.extend((0..1600).map(|k| (f64::from(k % 40) * 20.0, f64::from(k / 40) * 20.0)).map(|(x, y)| line((x + 5.0, y), (x + 5.0, y + 5.0))));
let started = super::super::index::work_done();
let a = adjacency(&all, DEFAULT_PRECISION).unwrap();
let work = super::super::index::work_done() - started - plain;
let loose: Vec<&MapEdge> = a.edges.iter().filter(|e| e.sources.len() == 1 && e.sources[0] >= 1600).collect();
assert_eq!(loose.len(), 1600);
for e in loose {
let mid = e.path.to_bezpath().segments().next().unwrap().eval(0.5);
let face = a.faces.iter().position(|f| inside(f, mid));
assert_eq!((e.left, e.right), (face, face));
assert!(face.is_some());
}
// Testing every face for each loose line would read 1,600 faces per line.
assert!(work <= 64 * 1600, "{work} reads");
}
#[test]
fn a_line_on_a_rectangle_side_keeps_both_inputs_in_either_order() {
for flip in [false, true] {
let (r, l) = (rect(0.0, 0.0, 100.0, 50.0), line((-10.0, 50.0), (110.0, 50.0)));
let shapes = if flip { vec![l, r] } else { vec![r, l] };
let a = adjacency(&shapes, DEFAULT_PRECISION).unwrap();
let on = edges_at(&a, Point::new(30.0, 50.0));
assert_eq!(on.len(), 1, "flip {flip}: {on:?}");
assert_eq!(on[0].sources, vec![0, 1], "flip {flip}");
}
}
#[test]
fn each_side_names_the_face_seen_on_that_side_of_the_edge() {
// A tray-like outline with a crease grid, edges drawn in every direction.
let a = adjacency(
&[
rect(0.0, 0.0, 90.0, 60.0),
line((30.0, 0.0), (30.0, 60.0)),
line((60.0, 60.0), (60.0, 0.0)),
line((90.0, 20.0), (0.0, 20.0)),
line((0.0, 40.0), (90.0, 40.0)),
],
DEFAULT_PRECISION,
)
.unwrap();
assert_eq!(a.faces.len(), 9);
let mut checked = 0;
for e in &a.edges {
let bp = e.path.to_bezpath();
let Some(seg) = bp.segments().next() else { continue };
let (p, d) = (seg.eval(0.5), seg.end() - seg.start());
let n = d.normalize();
// On the page (y down), the left of a direction (dx, dy) is (dy, -dx).
let (left_at, right_at) = (p + Vec2::new(n.y, -n.x) * 0.5, p + Vec2::new(-n.y, n.x) * 0.5);
for (side, at) in [(e.left, left_at), (e.right, right_at)] {
match side {
Some(f) => assert!(inside(&a.faces[f], at), "{e:?}"),
None => assert!(a.faces.iter().all(|f| !inside(f, at)), "{e:?}"),
}
checked += 1;
}
}
assert!(checked >= 24, "{checked}");
}
#[test]
fn a_slot_narrower_than_the_precision_is_a_sliver() {
let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), rect(50.0, 10.0, 50.004, 40.0)], DEFAULT_PRECISION).unwrap();
assert_eq!(a.slivers.len(), 1, "{:?}", a.slivers);
assert_eq!(a.faces.len(), 1);
let b = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), rect(50.0, 10.0, 51.0, 40.0)], DEFAULT_PRECISION).unwrap();
assert!(b.slivers.is_empty());
assert_eq!(b.faces.len(), 2, "the slot is a face of its own");
}
#[test]
fn a_ring_is_a_face_with_a_hole_and_two_pieces() {
let a = adjacency(&[rect(0.0, 0.0, 100.0, 100.0), rect(30.0, 30.0, 70.0, 70.0)], DEFAULT_PRECISION).unwrap();
assert_eq!(a.faces.len(), 2);
let ring = a.faces.iter().find(|f| inside(f, Point::new(10.0, 10.0))).unwrap();
assert!(!inside(ring, Point::new(50.0, 50.0)), "the inner square is a hole in the ring");
assert!((ring.area - 8400.0).abs() < 1e-6, "{}", ring.area);
assert_eq!(a.outlines.len(), 2);
assert_ne!(a.outlines[0].piece, a.outlines[1].piece);
let inner = a.faces.iter().find(|f| inside(f, Point::new(50.0, 50.0))).unwrap();
assert_ne!(inner.piece, ring.piece);
let inner_side = edges_at(&a, Point::new(50.0, 30.0));
let mut sides = [inner_side[0].left, inner_side[0].right];
sides.sort_unstable();
assert!(sides.iter().all(Option::is_some), "a ring face on one side, the inner square on the other: {sides:?}");
}
#[test]
fn bad_input_gives_no_map() {
assert!(adjacency(&[], DEFAULT_PRECISION).is_none());
assert!(adjacency(&[line((0.0, 0.0), (f64::NAN, 1.0))], DEFAULT_PRECISION).is_none());
assert!(adjacency(&[rect(0.0, 0.0, 10.0, 10.0)], 0.0).is_none());
assert!(adjacency(&[rect(0.0, 0.0, 10.0, 10.0)], f64::INFINITY).is_none());
let mut points: Vec<Point> = (0..=SHAPE_BUILDER_MAX_SEGMENTS + 1).map(|i| Point::new(i as f64, (i % 2) as f64)).collect();
let open = Shape::new(PathData::single(SubPath::polyline(&points, false)), FillRule::NonZero, 0);
assert!(adjacency(&[open], DEFAULT_PRECISION).is_none(), "over the segment limit");
points.truncate(64);
let open = Shape::new(PathData::single(SubPath::polyline(&points, false)), FillRule::NonZero, 0);
assert!(adjacency(&[open], DEFAULT_PRECISION).is_some());
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(64))]
/// Random lines and boxes never panic, and every side an edge names is a face.
#[test]
fn random_lines_give_a_consistent_map(
segs in proptest::collection::vec((-50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..12),
boxed in any::<bool>(),
) {
let mut shapes: Vec<Shape> = segs.iter().map(|&(a, b, c, d)| line((a, b), (c, d))).collect();
if boxed {
shapes.push(rect(-40.0, -40.0, 40.0, 40.0));
}
if let Some(a) = adjacency(&shapes, DEFAULT_PRECISION) {
for e in &a.edges {
prop_assert!(e.left.is_none_or(|f| f < a.faces.len()) && e.right.is_none_or(|f| f < a.faces.len()));
prop_assert!(e.sources.iter().all(|&s| s < shapes.len()));
}
}
}
}
+8 -8
View File
@@ -15,23 +15,23 @@ pub(crate) struct Rest {
/// The planar graph of `shapes` (in the sweep's frame) with its faces walked: what [`build`] makes
/// Live Paint faces and edges from, and what [`Map::merge`] merges faces in.
pub(crate) struct Map {
edges: Vec<Edge>,
pub(super) edges: Vec<Edge>,
around: Vec<Vec<usize>>,
slot_of: Vec<usize>,
/// Bounded faces: their cycle of half-edges, path and area; and, by their bounds, which can
/// hold a point, so finding the face around one tests only those.
faces: Vec<(Vec<usize>, BezPath, f64)>,
pub(super) faces: Vec<(Vec<usize>, BezPath, f64)>,
face_index: RectIndex<usize>,
/// Bounded faces left out as slivers ([`is_sliver`]): their cycle of half-edges and the inputs
/// whose fill covers them (none for a gap, such as a thin cutout).
pub(super) slivers: Vec<(Vec<usize>, Vec<usize>)>,
/// Outer boundaries of connected pieces, and the face each one is a hole in.
holes: Vec<(Vec<usize>, BezPath)>,
face_holes: Vec<Vec<usize>>,
tidy: Tidy,
pub(super) holes: Vec<(Vec<usize>, BezPath)>,
pub(super) face_holes: Vec<Vec<usize>>,
pub(super) tidy: Tidy,
/// The inputs' anchors (sorted by x) and how close results snap back onto them.
anchors: Vec<Point>,
snap: f64,
pub(super) anchors: Vec<Point>,
pub(super) snap: f64,
}
/// With `cover`, also finds which inputs cover each sliver, which only [`Map::merge`] reads;
@@ -41,7 +41,7 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option<Map> {
}
/// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped.
fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> {
pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> {
let mut inputs: Vec<(BezPath, usize)> = Vec::new();
for (i, s) in shapes.iter().enumerate() {
let mut bp = BezPath::new();
+1
View File
@@ -81,6 +81,7 @@ pub(super) fn make_face(bytes: FontBytes, index: u32, spec: FaceStyle, path: Opt
svg_glyphs,
gsub: std::sync::OnceLock::new(),
unencoded: std::sync::OnceLock::new(),
char_list: std::sync::OnceLock::new(),
named_chars: std::sync::OnceLock::new(),
})
}
+16 -5
View File
@@ -206,6 +206,8 @@ pub struct FontFace {
pub(super) gsub: std::sync::OnceLock<super::gsub::GsubIndex>,
/// [`Self::unencoded_glyphs`], read once.
pub(super) unencoded: std::sync::OnceLock<std::sync::Arc<[u32]>>,
/// [`Self::mapped_chars`], read once.
pub(super) char_list: std::sync::OnceLock<Arc<[(char, u32)]>>,
/// [`Self::name_owner`]'s glyph names to characters, read once.
pub(super) named_chars: std::sync::OnceLock<std::collections::HashMap<String, char>>,
}
@@ -368,11 +370,20 @@ impl FontFace {
}
/// Every mapped character and its glyph id, sorted by code point (the Glyphs panel).
pub fn chars(&self) -> Vec<(char, u32)> {
let Some(f) = self.skrifa() else { return vec![] };
let mut v: Vec<(char, u32)> = f.charmap().mappings().filter_map(|(cp, g)| char::from_u32(cp).map(|c| (c, g.to_u32()))).collect();
v.sort_unstable_by_key(|x| x.0);
v.dedup_by_key(|x| x.0);
v
self.mapped_chars().to_vec()
}
/// [`Self::chars`], read from the font once for the face and shared by every caller. Empty when
/// the font cannot be read or maps no character.
pub fn mapped_chars(&self) -> Arc<[(char, u32)]> {
self.char_list
.get_or_init(|| {
let Some(f) = self.skrifa() else { return Arc::from([]) };
let mut v: Vec<(char, u32)> = f.charmap().mappings().filter_map(|(cp, g)| char::from_u32(cp).map(|c| (c, g.to_u32()))).collect();
v.sort_unstable_by_key(|x| x.0);
v.dedup_by_key(|x| x.0);
v.into()
})
.clone()
}
/// Advance width of glyph `gid` in font units.
pub fn advance(&self, gid: u32) -> f64 {
+3 -1
View File
@@ -153,7 +153,9 @@ impl FontDb {
/// neither, as [`FontTraits`] tells), then the others, each group nearest first by
/// [`FontLikeness::distance`](super::FontLikeness::distance) of their
/// [`family_traits`](Self::family_traits), a family of another kind ([`FontTraits::class`])
/// counting 2 further. Families equally far keep their order in `families`. Reads no font
/// counting 2 further. A family that shares none of those numbers with `family` comes after
/// every family that shares one in its group. Families equally far keep their order in
/// `families`. Reads no font
/// file, as `family_traits` does not.
pub fn similar_families(&self, family: &str, families: &[String]) -> Vec<String> {
let base = self.family_traits(family);
+10 -2
View File
@@ -174,11 +174,15 @@ impl FontLikeness {
/// How unlike two faces look: 0 for faces whose numbers are all the same, more the further
/// apart they are. A number one of the faces does not give is left out. PANOSE digits are
/// compared only between faces of the same PANOSE family kind; faces of different kinds count
/// 3 apart. The weights and scales are VectorCraft's own.
/// 3 apart. Faces that share no number to compare (neither a PANOSE family kind, a weight, a
/// width, a height, an average width nor an italic angle) are `f32::INFINITY` apart, further
/// than any faces that share one. The weights and scales are VectorCraft's own.
pub fn distance(&self, other: &Self) -> f32 {
let mut d = 0.0;
let mut compared = false;
let (kind, other_kind) = (self.panose[0], other.panose[0]);
if kind > 1 && other_kind > 1 {
compared = true;
if kind == other_kind {
for (a, b) in self.panose.iter().zip(&other.panose).skip(1) {
if *a > 1 && *b > 1 {
@@ -190,21 +194,25 @@ impl FontLikeness {
}
}
if self.weight != 0 && other.weight != 0 {
compared = true;
d += f32::from(self.weight.abs_diff(other.weight)) / 200.0;
}
if self.width != 0 && other.width != 0 {
compared = true;
d += f32::from(self.width.abs_diff(other.width)) * 0.5;
}
for (a, b, scale) in [(self.x_height, other.x_height, 10.0), (self.cap_height, other.cap_height, 5.0), (self.avg_width, other.avg_width, 8.0)]
{
if a != 0 && b != 0 {
compared = true;
d += f32::from(a.abs_diff(b)) / 1000.0 * scale;
}
}
if let (Some(a), Some(b)) = (self.italic_angle, other.italic_angle) {
compared = true;
d += f32::from(a.abs_diff(b)) / 50.0;
}
d
if compared { d } else { f32::INFINITY }
}
}
+70
View File
@@ -365,6 +365,30 @@ pub fn height_outside_font() -> Option<Vec<u8>> {
heights_font(HEIGHT_OUTSIDE_FAMILY, Some((HEIGHT_OUTSIDE_X, HEIGHT_OUTSIDE_CAP)), false)
}
/// The family of [`numberless_font`].
pub const NUMBERLESS_FAMILY: &str = "Numberlesstest Sans";
/// The bundled Source Sans 3 Regular as family [`NUMBERLESS_FAMILY`], without its OS/2 and `post`
/// tables, so it gives none of the numbers Show Similar Fonts compares faces by. `None` when it
/// can't be built.
pub fn numberless_font() -> Option<Vec<u8>> {
const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
let font = skrifa::FontRef::new(BASE).ok()?;
let full = format!("{NUMBERLESS_FAMILY} Regular");
let postscript = format!("{}-Regular", NUMBERLESS_FAMILY.replace(' ', ""));
let name = name_table(&[(1, NUMBERLESS_FAMILY), (2, "Regular"), (4, &full), (6, &postscript)])?;
let mut builder = FontBuilder::new();
builder.add_raw(Tag::new(b"name"), name);
for r in font.table_directory.table_records() {
let tag = Tag::new(&r.tag().to_be_bytes());
if builder.contains(tag) || tag == Tag::new(b"OS/2") || tag == Tag::new(b"post") {
continue;
}
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes().to_vec());
}
Some(builder.build())
}
/// The bundled Source Sans 3 Regular as `family`: with the x height and cap height `heights` in
/// its OS/2 table, else a version 1 OS/2 table, which holds neither; with `base`, the `BASE`
/// table of [`height_font`].
@@ -1481,6 +1505,52 @@ fn remapped_source_sans(family: &str, postscript: &str, mapping: &[(char, char)]
Some(builder.build())
}
/// The family of [`large_cmap_font`].
pub const LARGE_CMAP_FAMILY: &str = "Largecmap Sans";
/// The family of [`cmapless_font`].
pub const CMAPLESS_FAMILY: &str = "Cmapless Sans";
/// The bundled Source Sans 3 Regular with a `cmap` of `count` characters from U+20000 up, about as
/// many as a large CJK font maps when `count` is 50,000. Each character maps to the font's next
/// glyph in turn after `.notdef`, so most glyphs have several characters.
pub fn large_cmap_font(count: u32) -> Option<Vec<u8>> {
use write_fonts::tables::cmap::Cmap;
const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
let font = skrifa::FontRef::new(BASE).ok()?;
let glyphs = u32::from(font.maxp().ok()?.num_glyphs()).checked_sub(1).filter(|n| *n > 0)?;
let mappings = (0..count).map(|i| Some((char::from_u32(0x2_0000_u32.checked_add(i)?)?, write_fonts::types::GlyphId::new(1 + i % glyphs))));
let cmap = Cmap::from_mappings(mappings.collect::<Option<Vec<_>>>()?).ok()?;
source_sans_with_cmap(LARGE_CMAP_FAMILY, "LargecmapSans-Regular", Some(&cmap))
}
/// The bundled Source Sans 3 Regular without a `cmap` table: it maps no character.
pub fn cmapless_font() -> Option<Vec<u8>> {
source_sans_with_cmap(CMAPLESS_FAMILY, "CmaplessSans-Regular", None)
}
/// The bundled Source Sans 3 Regular named `family`, with `cmap` in place of its own (none when
/// `cmap` is `None`), and its other tables kept.
fn source_sans_with_cmap(family: &str, postscript: &str, cmap: Option<&write_fonts::tables::cmap::Cmap>) -> Option<Vec<u8>> {
const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
let font = skrifa::FontRef::new(BASE).ok()?;
let full = format!("{family} Regular");
let name = name_table(&[(1, family), (2, "Regular"), (4, full.as_str()), (6, postscript)])?;
let mut builder = FontBuilder::new();
if let Some(cmap) = cmap {
builder.add_table(cmap).ok()?;
}
builder.add_raw(Tag::new(b"name"), name);
for r in font.table_directory.table_records() {
let tag = Tag::new(&r.tag().to_be_bytes());
if tag != Tag::new(b"cmap") && !builder.contains(tag) {
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes());
}
}
Some(builder.build())
}
/// The family of [`tall_ideograph_font`].
pub const TALL_IDEOGRAPH_FAMILY: &str = "Tall Ideograph Sans";
+1
View File
@@ -8,6 +8,7 @@ mod alternates;
mod axes;
mod bidi;
mod bitmaps;
mod char_list;
mod colr;
mod combos;
mod composers;
+115
View File
@@ -0,0 +1,115 @@
//! A face's list of mapped characters (the Glyphs panel's grid): read from the font once for the
//! face, and the same list, in the same order, as a fresh read of the font's `cmap`.
use std::collections::BTreeMap;
use std::sync::Arc;
use skrifa::MetadataProvider;
use crate::test_fonts::{CMAPLESS_FAMILY, LARGE_CMAP_FAMILY, VARIABLE_FAMILY, cmapless_font, large_cmap_font, variable_font};
use crate::*;
/// The characters `face` maps, read from its `cmap` each time: every mapping with a valid code point,
/// sorted by code point, one per character.
fn read_chars(face: &FontFace) -> Vec<(char, u32)> {
let Some(f) = face.skrifa() else { return vec![] };
let mut v: Vec<(char, u32)> = f.charmap().mappings().filter_map(|(cp, g)| char::from_u32(cp).map(|c| (c, g.to_u32()))).collect();
v.sort_unstable_by_key(|x| x.0);
v.dedup_by_key(|x| x.0);
v
}
/// A database of the bundled fonts, the test variable font, a font with a large `cmap` and one with
/// no `cmap`.
fn db() -> FontDb {
let db = FontDb::with_font_dirs(vec![]);
assert!(db.add_font(variable_font().expect("the variable test font builds")) > 1, "its named instances are faces");
assert_eq!(db.add_font(large_cmap_font(50_000).expect("the large test font builds")), 1);
assert_eq!(db.add_font(cmapless_font().expect("the cmapless test font builds")), 1);
db
}
/// Faces of every kind the panel browses: static faces, a variable font's named instance and an
/// instance at other axis settings, a large `cmap`, and no `cmap`.
fn faces(db: &FontDb) -> Vec<Arc<FontFace>> {
let mut faces: Vec<Arc<FontFace>> = [
(FALLBACK_FAMILY, "Regular"),
(FALLBACK_FAMILY, "Bold"),
("Inter", "Regular"),
("JetBrains Mono", "Regular"),
(VARIABLE_FAMILY, "Regular"),
(VARIABLE_FAMILY, "Bold"),
(LARGE_CMAP_FAMILY, "Regular"),
(CMAPLESS_FAMILY, "Regular"),
]
.into_iter()
.map(|(family, style)| db.face(family, style).unwrap_or_else(|| panic!("{family} {style} is loaded")))
.collect();
let regular = db.face(VARIABLE_FAMILY, "Regular").expect("the variable face");
let axes: BTreeMap<String, f64> = [("wght".to_string(), 620.0)].into_iter().collect();
let instance = db.instance(&regular, &axes);
assert_ne!(instance.id(), regular.id(), "a new instance");
faces.push(instance);
faces
}
#[test]
fn the_character_list_is_the_fonts_cmap_read_once() {
let db = db();
let faces = faces(&db);
for face in &faces {
let list = face.mapped_chars();
assert_eq!(&list[..], read_chars(face).as_slice(), "{face:?}");
assert_eq!(face.chars(), read_chars(face), "{face:?}");
assert!(Arc::ptr_eq(&list, &face.mapped_chars()), "{face:?}: read once");
}
let large = db.face(LARGE_CMAP_FAMILY, "Regular").expect("the large face");
assert_eq!(large.mapped_chars().len(), 50_000);
let none = db.face(CMAPLESS_FAMILY, "Regular").expect("the cmapless face");
assert!(none.mapped_chars().is_empty(), "a font with no cmap maps no character");
// Each face keeps its own list: an instance of a variable font shares its characters, not the
// list read for another face.
for (i, a) in faces.iter().enumerate() {
for b in &faces[i + 1..] {
assert!(a.mapped_chars().is_empty() || !Arc::ptr_eq(&a.mapped_chars(), &b.mapped_chars()), "{a:?} and {b:?}");
}
}
}
/// Times one face's character list read from the font each time against the list read once, for the
/// bundled Source Sans 3 Regular and a font mapping 50,000 characters. Run with
/// `cargo test --release -p vectorcraft-text --lib character_list_timing -- --ignored --nocapture`.
#[test]
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
fn character_list_timing() {
const CALLS: usize = 100;
let db = db();
for (family, style) in [(FALLBACK_FAMILY, "Regular"), (LARGE_CMAP_FAMILY, "Regular")] {
let face = db.face(family, style).expect("the face");
let mut read = vec![];
let mut kept = vec![];
for _ in 0..7 {
let start = std::time::Instant::now();
let mut n = 0;
for _ in 0..CALLS {
n += std::hint::black_box(read_chars(&face)).len();
}
read.push(start.elapsed().as_secs_f64() * 1000.0 / CALLS as f64);
let start = std::time::Instant::now();
let mut m = 0;
for _ in 0..CALLS {
m += std::hint::black_box(face.mapped_chars()).len();
}
kept.push(start.elapsed().as_secs_f64() * 1000.0 / CALLS as f64);
assert_eq!(n, m);
}
read.sort_by(f64::total_cmp);
kept.sort_by(f64::total_cmp);
println!(
"{family} {style}, {} characters: read each time median {:.4} ms, read once median {:.6} ms per call; samples {read:.4?} and {kept:.6?}",
face.mapped_chars().len(),
read[3],
kept[3]
);
}
}
+30 -2
View File
@@ -3,7 +3,9 @@
use skrifa::raw::TableProvider;
use crate::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, VARIABLE_FAMILY, height_font, variable_font};
use crate::test_fonts::{
HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, NUMBERLESS_FAMILY, VARIABLE_FAMILY, height_font, numberless_font, variable_font,
};
use crate::*;
/// A database of the bundled fonts and the two copies of Source Sans 3 Regular with and without
@@ -88,8 +90,14 @@ fn likeness_is_a_distance() {
assert_eq!(sans.distance(&serif), serif.distance(&sans), "symmetric");
assert!(sans.distance(&serif) > 0.0 && sans.distance(&mono) > 0.0);
// A number a face does not give is left out, not counted as 0.
assert_eq!(sans.distance(&FontLikeness { x_height: 0, cap_height: 0, ..sans }), 0.0);
// Faces that share no number are further apart than any faces that share one, not alike.
let unknown = FontLikeness::default();
assert_eq!(sans.distance(&unknown), 0.0);
assert_eq!(sans.distance(&unknown), f32::INFINITY);
assert_eq!(unknown.distance(&sans), f32::INFINITY, "symmetric");
assert_eq!(unknown.distance(&unknown), f32::INFINITY);
let weight_only = FontLikeness { weight: 400, ..unknown };
assert_eq!(sans.distance(&weight_only), 0.0, "the weight alone is compared");
let lighter = FontLikeness { weight: 300, ..sans };
assert!((sans.distance(&lighter) - 0.5).abs() < 1e-6, "100 weight units apart");
}
@@ -117,3 +125,23 @@ fn families_are_ordered_by_likeness() {
assert_eq!(without[0], HEIGHTLESS_FAMILY);
assert!(db.similar_families("Source Sans 3", &[]).is_empty());
}
/// A family that gives none of the numbers comes after every family that shares one with the
/// family asked about, instead of first as though it looked the same.
#[test]
fn a_family_without_numbers_comes_after_the_measured_ones() {
let db = db();
assert_eq!(db.add_font(numberless_font().expect("the test font builds")), 1);
assert_eq!(db.family_traits(NUMBERLESS_FAMILY).likeness, FontLikeness::default());
let families = names(&[NUMBERLESS_FAMILY, "JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3"]);
let order = db.similar_families("Source Sans 3", &families);
assert_eq!(order[..2], names(&["Source Sans 3", HEIGHTLESS_FAMILY]), "{order:?}");
assert_eq!(order.last().map(String::as_str), Some(NUMBERLESS_FAMILY), "{order:?}");
// The measured families keep the order they have without it.
let measured: Vec<String> = order.iter().filter(|f| *f != NUMBERLESS_FAMILY).cloned().collect();
assert_eq!(measured, db.similar_families("Source Sans 3", &families[1..]));
// Asked about itself, it comes first even from the end of the list, and the families it shares
// no number with keep their order in the list.
let last = names(&["JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3", NUMBERLESS_FAMILY]);
assert_eq!(db.similar_families(NUMBERLESS_FAMILY, &last), families);
}
+3
View File
@@ -11,3 +11,6 @@ workspace = true
[dependencies]
vectorcraft-geom = { workspace = true }
vectorcraft-pathops = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
File diff suppressed because it is too large Load Diff
+916
View File
@@ -0,0 +1,916 @@
use super::*;
use proptest::prelude::*;
use vectorcraft_geom::Rect;
const TOL: f64 = 0.1;
fn p(x: f64, y: f64) -> Point {
Point::new(x, y)
}
fn poly(points: &[(f64, f64)], closed: bool) -> PathData {
PathData::single(SubPath::polyline(&points.iter().map(|&(x, y)| p(x, y)).collect::<Vec<_>>(), closed))
}
fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine {
FoldLine { path: poly(points, closed), kind, key }
}
fn cut(points: &[(f64, f64)], key: u64) -> FoldLine {
line(LineKind::Cut, points, true, key)
}
fn crease(a: (f64, f64), b: (f64, f64), key: u64) -> FoldLine {
line(LineKind::Crease, &[a, b], false, key)
}
fn codes(issues: &[Issue]) -> Vec<&'static str> {
issues.iter().map(|i| i.code.id()).collect()
}
fn areas(b: &Blank) -> Vec<i64> {
let mut a: Vec<i64> = b.panels.iter().map(|p| (p.area * 1000.0).round() as i64).collect();
a.sort_unstable();
a
}
/// A tray: a 100 × 60 base with a 30 pt wall on each side, drawn as one closed cross, and the four
/// creases round the base (keys 10 to 13).
fn tray() -> Vec<FoldLine> {
vec![
cut(
&[
(30.0, 0.0),
(130.0, 0.0),
(130.0, 30.0),
(160.0, 30.0),
(160.0, 90.0),
(130.0, 90.0),
(130.0, 120.0),
(30.0, 120.0),
(30.0, 90.0),
(0.0, 90.0),
(0.0, 30.0),
(30.0, 30.0),
],
1,
),
crease((30.0, 30.0), (130.0, 30.0), 10),
crease((130.0, 30.0), (130.0, 90.0), 11),
crease((130.0, 90.0), (30.0, 90.0), 12),
crease((30.0, 90.0), (30.0, 30.0), 13),
]
}
/// The outline of a slotted box in the style of FEFCO 0201 (glue flap, four body panels 100, 60,
/// 100 and 60 wide and 80 high, 30 pt flaps top and bottom) with its 4 pt slots drawn as notches.
const NOTCHED: [(f64, f64); 30] = [
(20.0, 0.0),
(118.0, 0.0),
(118.0, 30.0),
(122.0, 30.0),
(122.0, 0.0),
(178.0, 0.0),
(178.0, 30.0),
(182.0, 30.0),
(182.0, 0.0),
(278.0, 0.0),
(278.0, 30.0),
(282.0, 30.0),
(282.0, 0.0),
(340.0, 0.0),
(340.0, 140.0),
(282.0, 140.0),
(282.0, 110.0),
(278.0, 110.0),
(278.0, 140.0),
(182.0, 140.0),
(182.0, 110.0),
(178.0, 110.0),
(178.0, 140.0),
(122.0, 140.0),
(122.0, 110.0),
(118.0, 110.0),
(118.0, 140.0),
(20.0, 140.0),
(20.0, 110.0),
(0.0, 110.0),
];
/// The slotted box's creases: the glue flap's and the body panels' (vertical), and the flaps'
/// (horizontal, from slot to slot).
fn box_creases() -> Vec<FoldLine> {
let mut out = vec![];
for (k, x) in [20.0, 120.0, 180.0, 280.0].into_iter().enumerate() {
out.push(crease((x, 30.0), (x, 110.0), 100 + k as u64));
}
for (k, (x0, x1)) in [(20.0, 118.0), (122.0, 178.0), (182.0, 278.0), (282.0, 340.0)].into_iter().enumerate() {
out.push(crease((x0, 30.0), (x1, 30.0), 110 + k as u64));
out.push(crease((x0, 110.0), (x1, 110.0), 120 + k as u64));
}
out
}
fn notched_box() -> Vec<FoldLine> {
let mut outline: Vec<(f64, f64)> = NOTCHED.to_vec();
outline.extend([(0.0, 30.0), (20.0, 30.0)]);
let mut lines = vec![cut(&outline, 1)];
lines.extend(box_creases());
lines
}
fn check(lines: &[FoldLine]) -> (Vec<Blank>, Vec<Issue>) {
blanks(lines, TOL)
}
#[test]
fn a_tray_has_a_base_four_walls_and_four_hinges() {
let (b, issues) = check(&tray());
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b.len(), 1);
assert_eq!(areas(&b[0]), vec![1_800_000, 1_800_000, 3_000_000, 3_000_000, 6_000_000]);
assert_eq!(b[0].hinges.len(), 4);
for h in &b[0].hinges {
assert!(h.straight && h.keys.len() == 1, "{h:?}");
assert!((h.from.distance(h.to) - if h.keys[0] % 2 == 0 { 100.0 } else { 60.0 }).abs() < 1e-6, "{h:?}");
}
assert_eq!(base_panel(&b[0].panels).map(|i| (b[0].panels[i].area).round()), Some(6000.0));
}
#[test]
fn a_slotted_box_gives_the_same_panels_however_its_slots_and_outline_are_drawn() {
let (notched, issues) = check(&notched_box());
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(notched.len(), 1);
assert_eq!(notched[0].panels.len(), 13, "glue flap, four body panels, eight flaps");
assert_eq!(notched[0].hinges.len(), 12);
assert!(notched[0].holes.is_empty());
// The slots as rectangles across a plain outline.
let mut across =
vec![cut(&[(20.0, 0.0), (340.0, 0.0), (340.0, 140.0), (20.0, 140.0), (20.0, 110.0), (0.0, 110.0), (0.0, 30.0), (20.0, 30.0)], 1)];
for (k, x) in [120.0, 180.0, 280.0].into_iter().enumerate() {
across.push(cut(&[(x - 2.0, -5.0), (x + 2.0, -5.0), (x + 2.0, 30.0), (x - 2.0, 30.0)], 2 + k as u64));
across.push(cut(&[(x - 2.0, 110.0), (x + 2.0, 110.0), (x + 2.0, 145.0), (x - 2.0, 145.0)], 5 + k as u64));
}
across.extend(box_creases());
let (b, issues) = check(&across);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b.len(), 1);
assert_eq!(areas(&b[0]), areas(&notched[0]));
assert_eq!(b[0].hinges.len(), 12);
// The notched outline as four open paths, end to end.
let mut outline: Vec<(f64, f64)> = NOTCHED.to_vec();
outline.extend([(0.0, 30.0), (20.0, 30.0), (20.0, 0.0)]);
let mut open: Vec<FoldLine> =
[0..9, 8..17, 16..25, 24..33].into_iter().enumerate().map(|(k, r)| line(LineKind::Cut, &outline[r], false, 1 + k as u64)).collect();
open.extend(box_creases());
let (b, issues) = check(&open);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(areas(&b[0]), areas(&notched[0]));
assert_eq!(b[0].hinges.len(), 12);
// Input order does not change the result.
let mut reversed = notched_box();
reversed.reverse();
let (b, _) = check(&reversed);
assert_eq!(areas(&b[0]), areas(&notched[0]));
}
#[test]
fn a_round_tuck_flap_folds_like_any_panel() {
let mut bp = BezPath::new();
bp.move_to(p(0.0, 40.0));
bp.line_to(p(0.0, 140.0));
bp.line_to(p(100.0, 140.0));
bp.line_to(p(100.0, 40.0));
bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0));
bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0));
bp.close_path();
let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)];
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].panels.len(), 2);
assert_eq!(b[0].hinges.len(), 1);
}
#[test]
fn a_window_is_a_hole_in_its_panel() {
let mut lines = tray();
lines.push(cut(&[(60.0, 45.0), (100.0, 45.0), (100.0, 75.0), (60.0, 75.0)], 2));
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].holes.len(), 1);
assert_eq!(areas(&b[0]), vec![1_800_000, 1_800_000, 3_000_000, 3_000_000, 4_800_000]);
}
/// The tray's outline as one open path whose end stops `short` before its start.
fn tray_with_gap(short: f64) -> Vec<FoldLine> {
let mut lines = tray();
lines[0] = line(
LineKind::Cut,
&[
(30.0 + short, 0.0),
(130.0, 0.0),
(130.0, 30.0),
(160.0, 30.0),
(160.0, 90.0),
(130.0, 90.0),
(130.0, 120.0),
(30.0, 120.0),
(30.0, 90.0),
(0.0, 90.0),
(0.0, 30.0),
(30.0, 30.0),
(30.0, 0.0),
],
false,
1,
);
lines
}
#[test]
fn a_gap_within_the_tolerance_is_closed_and_one_past_it_is_a_loose_end() {
let (closed, _) = check(&tray());
let (b, issues) = check(&tray_with_gap(0.05));
assert_eq!(codes(&issues), vec!["gap"], "{issues:?}");
assert_eq!(issues[0].keys, vec![1]);
assert_eq!(areas(&b[0]), areas(&closed[0]));
assert_eq!(b[0].hinges.len(), 4);
// The tolerance boundary.
let (_, issues) = blanks(&tray_with_gap(0.05), 0.06);
assert_eq!(codes(&issues), vec!["gap"]);
let (b, issues) = blanks(&tray_with_gap(0.05), 0.04);
assert!(codes(&issues).starts_with(&["open", "looseEnd", "looseEnd"]) || codes(&issues).starts_with(&["looseEnd"]), "{issues:?}");
assert!(issues.iter().any(|i| i.code == IssueCode::LooseEnd && i.at.is_some_and(|a| a.distance(p(30.05, 0.0)) < 1e-9)), "{issues:?}");
assert!(b.iter().all(|b| b.panels.len() < 5), "the outline does not close");
}
#[test]
fn no_cut_lines_or_no_enclosed_area_build_nothing() {
let (b, issues) = check(&[crease((0.0, 0.0), (10.0, 0.0), 1)]);
assert!(b.is_empty());
assert_eq!(codes(&issues), vec!["noCut"]);
let (b, issues) = check(&[]);
assert!(b.is_empty());
assert_eq!(codes(&issues), vec!["noCut"]);
let (b, issues) = check(&[line(LineKind::Cut, &[(0.0, 0.0), (50.0, 0.0), (50.0, 50.0)], false, 1)]);
assert!(b.is_empty());
assert!(codes(&issues).contains(&"open") && codes(&issues).contains(&"looseEnd"), "{issues:?}");
// A non-finite line is left out.
let mut lines = tray();
lines.push(line(LineKind::Crease, &[(0.0, 0.0), (f64::NAN, 1.0)], false, 9));
let (b, issues) = check(&lines);
assert!(issues.is_empty() && b[0].panels.len() == 5, "{issues:?}");
}
#[test]
fn a_cut_end_inside_the_blank_is_a_loose_end() {
let mut lines = tray();
lines.push(line(LineKind::Cut, &[(80.0, 0.0), (80.0, 20.0)], false, 2));
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["looseEnd"], "{issues:?}");
assert_eq!((issues[0].keys.clone(), issues[0].at), (vec![2], Some(p(80.0, 20.0))));
assert_eq!(b[0].panels.len(), 5, "a cut into a wall does not divide it");
// A slit that ends on a crease is not loose: it cuts the wall in two.
let mut lines = tray();
lines.push(line(LineKind::Cut, &[(80.0, 0.0), (80.0, 30.0)], false, 2));
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!((b[0].panels.len(), b[0].hinges.len()), (6, 5));
}
#[test]
fn a_cut_line_that_comes_back_through_its_own_end_meets_it() {
// From (80, 10) out to (90, 20), then back through (80, 10) to the outline at (70, 0): the
// start lies on the line's own second segment, so it is not loose.
let mut lines = tray();
lines.push(line(LineKind::Cut, &[(80.0, 10.0), (90.0, 20.0), (70.0, 0.0)], false, 2));
let (_, issues) = check(&lines);
assert!(!codes(&issues).contains(&"looseEnd"), "{issues:?}");
// A first segment shorter than the tolerance does not make the second one meet the end.
let mut lines = tray();
lines.push(line(LineKind::Cut, &[(90.0, 25.0), (90.05, 25.0), (80.0, 20.0), (80.0, 0.0)], false, 2));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["looseEnd"], "{issues:?}");
assert_eq!(issues[0].at, Some(p(90.0, 25.0)));
}
#[test]
fn two_outlines_joined_by_a_cut_line_are_both_material() {
let lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1),
cut(&[(150.0, 0.0), (180.0, 0.0), (180.0, 30.0), (150.0, 30.0)], 2),
line(LineKind::Cut, &[(100.0, 10.0), (150.0, 10.0)], false, 3),
];
let (b, issues) = check(&lines);
assert_eq!(b.len(), 1, "one connected piece");
assert_eq!(areas(&b[0]), vec![900_000, 10_000_000], "{issues:?}");
assert!(b[0].holes.is_empty());
// A slot drawn across the outline is still cut out, not made material where it sticks out.
let lines =
vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), cut(&[(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)], 2)];
let (b, _) = check(&lines);
assert_eq!(b.len(), 1);
assert_eq!(areas(&b[0]), vec![10_000_000 - 80_000]);
// The same slot drawn as four open lines end to end, one of them backwards.
let slot = [(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)];
let mut lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1)];
lines.push(line(LineKind::Cut, &[slot[0], slot[1]], false, 2));
lines.push(line(LineKind::Cut, &[slot[2], slot[1]], false, 3));
lines.push(line(LineKind::Cut, &[slot[2], slot[3]], false, 4));
lines.push(line(LineKind::Cut, &[slot[3], slot[0]], false, 5));
let (b, issues) = check(&lines);
assert_eq!(b.len(), 1, "{issues:?}");
assert_eq!(areas(&b[0]), vec![10_000_000 - 80_000]);
// And with a gap within the tolerance at one corner.
lines[4] = line(LineKind::Cut, &[slot[3], (48.0, -9.95)], false, 5);
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["gap"], "{issues:?}");
assert_eq!(b.len(), 1);
assert_eq!(areas(&b[0]), vec![10_000_000 - 80_000]);
// A slot right across the blank, with no corner inside the outline and no outline corner
// inside the slot, cuts it in two.
let lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1),
cut(&[(10.0, -210.0), (20.0, -210.0), (20.0, 110.0), (10.0, 110.0)], 2),
];
let (b, _) = check(&lines);
assert_eq!(b.len(), 1);
assert_eq!(areas(&b[0]), vec![1_000_000, 8_000_000]);
}
#[test]
fn an_outline_drawn_twice_keeps_its_material() {
let square = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
let (b, issues) = check(&[cut(&square, 1), cut(&square, 2)]);
assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}");
assert_eq!(issues[0].keys, vec![1, 2]);
assert_eq!(b.len(), 1);
assert_eq!(areas(&b[0]), vec![10_000_000]);
// The same two squares as the subpaths of one compound path.
let mut twice = poly(&square, true);
twice.subpaths.extend(poly(&square, true).subpaths);
let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1 }]);
assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}");
assert_eq!(issues[0].keys, vec![1]);
assert_eq!(areas(&b[0]), vec![10_000_000]);
}
#[test]
fn a_large_tolerance_still_closes_nearly_touching_ends_and_short_outlines() {
// Ends 0.0005 apart, closer than 1/10,000 of the tolerance.
let nearly = line(LineKind::Cut, &[(0.0005, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0), (0.0, 0.0)], false, 1);
let (b, issues) = blanks(&[nearly], 10.0);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(areas(&b[0]), vec![10_000_000]);
// An outline shorter than the tolerance, 0.05 pt open: a gap, and no loose end.
let short = line(LineKind::Cut, &[(0.05, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)], false, 1);
let (b, issues) = blanks(&[short], 10.0);
assert_eq!(codes(&issues), vec!["gap"], "{issues:?}");
assert_eq!(areas(&b[0]), vec![1000]);
}
#[test]
fn a_lookup_wider_than_the_occupied_cells_reads_only_those_cells() {
// Two points 1e-9 apart make cells about 2.4e-13 wide: a lookup 1e-6 around one spans some
// 10^14 cells, and finds both points by reading the two cells that hold them.
let cells = Cells::new(vec![(Rect::from_points(p(0.0, 0.0), p(0.0, 0.0)), 1), (Rect::from_points(p(1e-9, 0.0), p(1e-9, 0.0)), 2)], 0.0, 4096.0);
assert_eq!(cells.near(p(0.0, 0.0), 1e-6), vec![1, 2]);
assert_eq!(cells.near(p(5.0, 5.0), 1e-6), Vec::<i32>::new());
// A square open by 0.0000011 pt at a 10 pt tolerance.
let square = line(LineKind::Cut, &[(0.0000011, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)], false, 1);
let (b, issues) = blanks(&[square], 10.0);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b.len(), 1);
}
#[test]
fn a_window_of_open_lines_with_a_slit_to_its_corner_is_still_a_hole() {
let outline = cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1);
let window = [(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)];
let slit = line(LineKind::Cut, &[(40.0, 0.0), (40.0, 40.0)], false, 2);
let (closed, issues) = check(&[outline.clone(), slit.clone(), cut(&window, 3)]);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!((closed[0].holes.len(), areas(&closed[0])), (1, vec![10_000_000 - 400_000]));
let mut lines = vec![outline, slit];
for k in 0..4 {
lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64));
}
let (open, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!((open[0].holes.len(), areas(&open[0])), (1, areas(&closed[0])));
// The outline as four open lines too, the slit from its corner to the window's.
let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
let mut lines: Vec<FoldLine> = (0..4).map(|k| line(LineKind::Cut, &[corners[k], corners[(k + 1) % 4]], false, 10 + k as u64)).collect();
lines.push(line(LineKind::Cut, &[(0.0, 0.0), (40.0, 40.0)], false, 2));
for k in 0..4 {
lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64));
}
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!((b[0].holes.len(), areas(&b[0])), (1, areas(&closed[0])));
// A cut across the window of open lines, so that three lines meet at two of its corners.
let mut lines = vec![cut(&corners, 1), line(LineKind::Cut, &[(40.0, 0.0), (40.0, 40.0)], false, 2)];
for k in 0..4 {
lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64));
}
lines.push(line(LineKind::Cut, &[(40.0, 40.0), (60.0, 60.0)], false, 20));
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!((b[0].holes.len(), areas(&b[0])), (1, areas(&closed[0])));
// The outline and the window both as open lines, joined by two slits: the same as when both are
// closed.
let slits = [line(LineKind::Cut, &[(0.0, 0.0), (40.0, 40.0)], false, 30), line(LineKind::Cut, &[(100.0, 100.0), (60.0, 60.0)], false, 31)];
let (want, want_issues) = check(&[cut(&corners, 1), cut(&window, 3), slits[0].clone(), slits[1].clone()]);
let mut lines: Vec<FoldLine> = (0..4).map(|k| line(LineKind::Cut, &[corners[k], corners[(k + 1) % 4]], false, 10 + k as u64)).collect();
for k in 0..4 {
lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64));
}
lines.extend(slits);
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), codes(&want_issues), "{issues:?}");
assert_eq!((b[0].holes.len(), areas(&b[0])), (want[0].holes.len(), areas(&want[0])));
assert_eq!(want[0].holes.len(), 1);
}
#[test]
fn a_slot_drawn_across_the_outline_is_a_notch_not_a_hole() {
let outline = || cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1);
let (b, issues) = check(&[outline(), cut(&[(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)], 2)]);
assert!(issues.is_empty(), "{issues:?}");
assert!(b[0].holes.is_empty(), "{:?}", b[0].holes);
let notched = cut(&[(0.0, 0.0), (48.0, 0.0), (48.0, 20.0), (52.0, 20.0), (52.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1);
assert_eq!(areas(&b[0]), areas(&check(std::slice::from_ref(&notched)).0[0]));
// A crease in the notch lies outside the blank, and one that runs on into it from a panel too.
let slot = || cut(&[(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)], 2);
let (_, issues) = check(&[outline(), slot(), crease((49.0, 5.0), (51.0, 5.0), 3)]);
assert_eq!(codes(&issues), vec!["outside"], "{issues:?}");
let (_, issues) = check(&[outline(), slot(), crease((50.0, 5.0), (50.0, 100.0), 3)]);
let (_, want) = check(&[notched, crease((50.0, 5.0), (50.0, 100.0), 3)]);
assert_eq!(codes(&issues), codes(&want), "{issues:?}");
assert!(codes(&issues).contains(&"outside"), "{issues:?}");
// A cutout whose top side lies on the outline opens onto the outside directly.
let flush = || cut(&[(48.0, 0.0), (52.0, 0.0), (52.0, 20.0), (48.0, 20.0)], 2);
let (b, issues) = check(&[outline(), flush()]);
assert!(b[0].holes.is_empty() && !codes(&issues).contains(&"ambiguous"), "{:?} {issues:?}", b[0].holes);
let (_, issues) = check(&[outline(), flush(), crease((49.0, 5.0), (51.0, 5.0), 3)]);
assert!(codes(&issues).contains(&"outside") && !codes(&issues).contains(&"ambiguous"), "{issues:?}");
// A window joined to the outline by a slit stays a hole when a cut across it leaves a sliver.
let window = || cut(&[(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)], 4);
let slit = || line(LineKind::Cut, &[(40.0, 0.0), (40.0, 40.0)], false, 5);
let (b, _) = check(&[outline(), window(), slit(), line(LineKind::Cut, &[(40.0, 40.004), (60.0, 40.004)], false, 6)]);
assert_eq!(b[0].holes.len(), 1, "{:?}", b[0].holes);
// And a window 0.004 pt below the outline, joined to it at both corners, leaving a sliver.
let near = cut(&[(40.0, 0.004), (60.0, 0.004), (60.0, 20.0), (40.0, 20.0)], 4);
let joins = [line(LineKind::Cut, &[(40.0, 0.0), (40.0, 0.004)], false, 5), line(LineKind::Cut, &[(60.0, 0.0), (60.0, 0.004)], false, 6)];
let (b, _) = check(&[outline(), near, joins[0].clone(), joins[1].clone()]);
assert_eq!(b[0].holes.len(), 1, "{:?}", b[0].holes);
}
#[test]
fn many_small_outlines_of_open_lines_fit_the_gap_search() {
// 784 unit squares 3 pt apart, each four open lines, at a tolerance of 0.5 pt.
let mut lines = vec![];
for i in 0..28u64 {
for j in 0..28u64 {
let (x, y) = (3.0 * i as f64, 3.0 * j as f64);
let c = [(x, y), (x + 1.0, y), (x + 1.0, y + 1.0), (x, y + 1.0)];
for k in 0..4 {
lines.push(line(LineKind::Cut, &[c[k], c[(k + 1) % 4]], false, 4 * (28 * i + j) + k as u64));
}
}
}
let (b, issues) = blanks(&lines, 0.5);
assert!(!codes(&issues).contains(&"tooComplex"), "{issues:?}");
assert_eq!(b.len(), 784);
}
#[test]
fn thousands_of_cut_lines_on_top_of_each_other_are_too_complex_before_the_gap_search() {
let lines: Vec<FoldLine> = (0..3000u64).map(|k| line(LineKind::Cut, &[(0.0, 0.0), (100.0, 0.0)], false, k)).collect();
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["tooComplex"], "{issues:?}");
assert!(b.is_empty());
}
#[test]
fn cut_lines_that_cross_an_outline_of_open_lines_leave_every_cell_material() {
// A 90 pt square whose sides are open lines ending every 30 pt, and four cut lines right across
// it: nine pieces of material, as with a closed outline.
let mut lines = vec![];
for k in 0..3 {
let (a, b) = (30.0 * k as f64, 30.0 * (k + 1) as f64);
for (i, seg) in [[(a, 0.0), (b, 0.0)], [(90.0, a), (90.0, b)], [(b, 90.0), (a, 90.0)], [(0.0, b), (0.0, a)]].iter().enumerate() {
lines.push(line(LineKind::Cut, seg, false, 10 + 4 * k as u64 + i as u64));
}
}
let across = [[(30.0, 0.0), (30.0, 90.0)], [(60.0, 0.0), (60.0, 90.0)], [(0.0, 30.0), (90.0, 30.0)], [(0.0, 60.0), (90.0, 60.0)]];
for (i, seg) in across.iter().enumerate() {
lines.push(line(LineKind::Cut, seg, false, 30 + i as u64));
}
let mut closed = vec![cut(&[(0.0, 0.0), (90.0, 0.0), (90.0, 90.0), (0.0, 90.0)], 1)];
closed.extend(lines.iter().skip(12).cloned());
let (want, want_issues) = check(&closed);
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), codes(&want_issues), "{issues:?}");
let pieces = |b: &[Blank]| b.iter().map(|x| (x.panels.len(), x.holes.len())).collect::<Vec<_>>();
assert_eq!(pieces(&b), pieces(&want));
assert_eq!(b.iter().map(|x| x.panels.len()).sum::<usize>(), 9);
// With the crossing lines drawn in 30 pt pieces, the four pieces round the middle cell meet end
// to end and count as one closed cut line, whether the outline is closed or drawn in pieces.
let mut split = vec![];
for (i, seg) in across.iter().enumerate() {
let (a, b) = (seg[0], seg[1]);
for k in 0..3 {
let at = |t: f64| (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
split.push(line(LineKind::Cut, &[at(k as f64 / 3.0), at((k + 1) as f64 / 3.0)], false, 40 + 3 * i as u64 + k as u64));
}
}
let mut closed = vec![cut(&[(0.0, 0.0), (90.0, 0.0), (90.0, 90.0), (0.0, 90.0)], 1)];
closed.extend(split.iter().cloned());
let (want, want_issues) = check(&closed);
let mut open: Vec<FoldLine> = lines.iter().take(12).cloned().collect();
open.extend(split);
let (b, issues) = check(&open);
assert_eq!(codes(&issues), codes(&want_issues), "{issues:?}");
assert_eq!(pieces(&b), pieces(&want));
}
#[test]
fn a_curved_crease_is_measured_at_its_farthest_point_from_its_line() {
// A crease from corner to corner of a square: its curve strays about 10.1 pt from the diagonal,
// where samples at quarters of it see 9.8 pt.
let off = 35.0 / 2f64.sqrt();
let mut bp = BezPath::new();
bp.move_to(p(0.0, 0.0));
bp.curve_to(p(10000.0 / 3.0 - off, 10000.0 / 3.0 + off), p(20000.0 / 3.0 + off, 20000.0 / 3.0 - off), p(10000.0, 10000.0));
let lines = vec![
cut(&[(0.0, 0.0), (10000.0, 0.0), (10000.0, 10000.0), (0.0, 10000.0)], 1),
FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2 },
];
let (b, issues) = blanks(&lines, 10.0);
assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}");
assert_eq!(b[0].hinges.len(), 1);
let (_, issues) = blanks(&lines, 10.5);
assert!(issues.is_empty(), "{issues:?}");
}
#[test]
fn a_grid_of_many_touching_outlines_is_classified_without_comparing_every_pair() {
// 100 × 100 touching squares, each its own closed outline: one piece of 10,000 panels.
let mut lines = vec![];
for i in 0..100u64 {
for j in 0..100u64 {
let (x, y) = (10.0 * i as f64, 10.0 * j as f64);
lines.push(cut(&[(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)], 100 * i + j));
}
}
let (b, issues) = check(&lines);
assert!(b.is_empty());
assert!(codes(&issues).contains(&"tooComplex"), "{issues:?}");
}
#[test]
fn open_cut_lines_far_from_the_origin_are_checked_without_overflow() {
let lines = [
line(LineKind::Cut, &[(1e13, 0.0), (1e13 + 4096.0, 0.0), (1e13 + 4096.0, 4096.0)], false, 1),
line(LineKind::Cut, &[(1e13 + 4096.0, 4096.0), (1e13, 4096.0), (1e13, 0.0)], false, 2),
];
let (b, issues) = check(&lines);
assert!(b.len() <= 1, "{issues:?}");
}
#[test]
fn a_blank_in_the_hole_of_a_narrow_ring_is_a_blank_of_its_own() {
// The ring's own area (1,900) is less than the hole's (8,100), but the square lies in the hole.
let lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1),
cut(&[(5.0, 5.0), (95.0, 5.0), (95.0, 95.0), (5.0, 95.0)], 2),
cut(&[(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)], 3),
];
let (b, issues) = check(&lines);
assert_eq!(b.len(), 2, "{issues:?}");
assert_eq!(codes(&issues), vec!["ambiguous"], "{issues:?}");
assert_eq!(issues[0].keys, vec![3]);
}
#[test]
fn too_many_segments_are_refused_before_the_lines_are_copied() {
// Many lines that together pass the limit by one segment.
let each: Vec<(f64, f64)> = (0..=64).map(|i| (i as f64, 0.0)).collect();
let lines: Vec<FoldLine> = (0..=(MAX_SEGMENTS / 64) as u64).map(|k| line(LineKind::Cut, &each, false, k)).collect();
assert!(lines.len() * 64 > MAX_SEGMENTS);
let (b, issues) = check(&lines);
assert!(b.is_empty());
assert_eq!(codes(&issues), vec!["tooComplex"]);
}
#[test]
fn many_separate_blanks_each_with_a_window_are_told_apart() {
// A 50 × 40 grid of 10 pt squares 5 pt apart, each with a 4 pt window and a crease beside it.
let mut lines = vec![];
for i in 0..50u64 {
for j in 0..40u64 {
let (x, y) = (15.0 * i as f64, 15.0 * j as f64);
let k = 10 * (40 * i + j);
lines.push(cut(&[(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)], k));
lines.push(cut(&[(x + 1.0, y + 1.0), (x + 5.0, y + 1.0), (x + 5.0, y + 5.0), (x + 1.0, y + 5.0)], k + 1));
lines.push(crease((x + 7.0, y), (x + 7.0, y + 10.0), k + 2));
}
}
let (blanks, issues) = check(&lines);
assert!(issues.is_empty(), "{:?}", issues.first());
assert_eq!(blanks.len(), 2000);
assert!(blanks.iter().all(|b| b.panels.len() == 2 && b.hinges.len() == 1 && b.holes.len() == 1));
}
#[test]
fn many_separate_cut_lines_are_checked_by_the_cells_near_each_end() {
// 2,000 short slits from the top edge of a long blank, each ending loose inside it.
let mut lines = vec![cut(&[(0.0, 0.0), (4000.0, 0.0), (4000.0, 100.0), (0.0, 100.0)], 1)];
for i in 0..2000u64 {
let x = 1.0 + 2.0 * i as f64;
lines.push(line(LineKind::Cut, &[(x, 0.0), (x, 50.0)], false, 10 + i));
}
let (_, issues) = check(&lines);
let loose: Vec<&Issue> = issues.iter().filter(|i| i.code == IssueCode::LooseEnd).collect();
assert_eq!(loose.len(), 2000);
assert!(loose.iter().all(|i| i.at.is_some_and(|at| (at.y - 50.0).abs() < 1e-9)));
}
#[test]
fn too_many_segments_or_panels_are_too_complex() {
// One point more than segments.
let mut zigzag: Vec<(f64, f64)> = (0..=MAX_SEGMENTS + 1).map(|i| (i as f64 * 0.5, (i % 2) as f64)).collect();
let (b, issues) = check(&[line(LineKind::Cut, &zigzag, false, 1)]);
assert!(b.is_empty());
assert_eq!(codes(&issues), vec!["tooComplex"]);
zigzag.truncate(MAX_SEGMENTS + 1);
let (_, issues) = check(&[line(LineKind::Cut, &zigzag, false, 1)]);
assert!(!codes(&issues).contains(&"tooComplex"), "at the limit");
// A grid of 16 × 16 panels is at the panel limit; 17 × 16 is past it.
let grid = |cols: usize| {
let mut lines = vec![cut(&[(0.0, 0.0), (cols as f64 * 10.0, 0.0), (cols as f64 * 10.0, 160.0), (0.0, 160.0)], 1)];
for i in 1..cols {
lines.push(crease((i as f64 * 10.0, 0.0), (i as f64 * 10.0, 160.0), 100 + i as u64));
}
for j in 1..16 {
lines.push(crease((0.0, j as f64 * 10.0), (cols as f64 * 10.0, j as f64 * 10.0), 200 + j as u64));
}
lines
};
let (b, issues) = check(&grid(16));
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].panels.len(), MAX_PANELS);
let (b, issues) = check(&grid(17));
assert!(b.is_empty());
assert_eq!(codes(&issues), vec!["tooComplex"]);
}
#[test]
fn lines_on_top_of_each_other_are_reported() {
let mut lines = tray();
lines.push(crease((40.0, 0.0), (120.0, 0.0), 20));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["cutOverCrease"], "{issues:?}");
assert_eq!(issues[0].keys, vec![1, 20]);
let mut lines = tray();
lines.push(crease((130.0, 30.0), (30.0, 30.0), 20));
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}");
assert_eq!(issues[0].keys, vec![10, 20]);
assert_eq!(b[0].hinges.len(), 4);
assert_eq!(b[0].hinges.iter().find(|h| h.keys.contains(&20)).map(|h| h.keys.clone()), Some(vec![10, 20]));
// A perforation over a crease, lines of two kinds that fold.
let mut lines = tray();
lines.push(line(LineKind::Perforation, &[(130.0, 30.0), (30.0, 30.0)], false, 20));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}");
assert_eq!(issues[0].keys, vec![10, 20]);
// A crease drawn twice outside the blank is reported where it lies as well.
let mut lines = tray();
lines.push(crease((200.0, 0.0), (250.0, 0.0), 20));
lines.push(crease((250.0, 0.0), (200.0, 0.0), 21));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["duplicate", "outside", "outside"], "{issues:?}");
assert_eq!((issues[1].keys.clone(), issues[2].keys.clone()), (vec![20], vec![21]));
}
#[test]
fn a_crease_that_runs_past_the_outline_is_reported() {
let outline = || cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], 1);
// 5 pt past the outline at each end: the hinge is built, and the line is reported.
let (b, issues) = check(&[outline(), crease((50.0, -5.0), (50.0, 55.0), 2)]);
assert_eq!(codes(&issues), vec!["outside"], "{issues:?}");
assert_eq!(issues[0].keys, vec![2]);
assert_eq!(b[0].hinges.len(), 1);
// Past it by less than the tolerance: no issue.
let (b, issues) = check(&[outline(), crease((50.0, -0.05), (50.0, 50.0), 2)]);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].hinges.len(), 1);
// A crease drawn round a sliver inside the blank does not run outside it.
let (_, issues) = check(&[outline(), line(LineKind::Crease, &[(50.0, 10.0), (50.004, 10.0), (50.004, 40.0), (50.0, 40.0)], true, 2)]);
assert!(!codes(&issues).contains(&"outside"), "{issues:?}");
}
#[test]
fn a_crease_that_ends_inside_a_panel_is_dangling() {
let mut lines = tray();
lines.push(crease((80.0, 30.0), (80.0, 60.0), 20));
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}");
assert_eq!(issues[0].keys, vec![20]);
assert_eq!(b[0].panels.len(), 5);
}
#[test]
fn a_hinge_shorter_than_the_tolerance_divides_nothing_and_leaves_a_loose_panel() {
let lines = vec![
cut(&[(0.0, 0.0), (50.0, 0.0), (50.0, 49.95), (100.0, 49.95), (100.0, 99.95), (50.0, 99.95), (50.0, 50.0), (0.0, 50.0)], 1),
crease((50.0, 49.95), (50.0, 50.0), 2),
];
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["noSplit", "loosePanel"], "{issues:?}");
assert_eq!(issues[0].keys, vec![2]);
assert!(b[0].hinges.is_empty());
// The same with a hinge as long as the panels: no issue.
let lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], 1), crease((50.0, 0.0), (50.0, 50.0), 2)];
let (_, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
}
#[test]
fn hinge_pieces_far_apart_are_measured_by_their_own_length() {
// A window leaves two 0.02 pt strips joining the halves, each crossed by a crease: 0.04 pt of
// hinge, though its pieces span 100 pt.
let lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1),
cut(&[(40.0, 0.02), (60.0, 0.02), (60.0, 99.98), (40.0, 99.98)], 2),
crease((50.0, 0.0), (50.0, 0.02), 3),
crease((50.0, 99.98), (50.0, 100.0), 4),
];
let (b, issues) = check(&lines);
assert!(codes(&issues).contains(&"noSplit"), "{issues:?}");
assert!(b[0].hinges.is_empty());
}
#[test]
fn a_window_split_by_a_cut_line_is_one_hole() {
let mut lines =
vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), cut(&[(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)], 2)];
lines.push(line(LineKind::Cut, &[(40.0, 50.0), (60.0, 50.0)], false, 3));
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].holes.len(), 1);
let area = vectorcraft_pathops::area(&b[0].holes[0], FillRule::NonZero);
assert!((area - 400.0).abs() < 1e-3, "{area}");
}
#[test]
fn a_hinge_drawn_as_short_pieces_is_measured_whole() {
// Ten 5 pt pieces make a 50 pt hinge, longer than a 10 pt tolerance though each piece is not.
let mut lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], 1)];
for k in 0..10u64 {
let y = 5.0 * k as f64;
lines.push(crease((50.0, y), (50.0, y + 5.0), 10 + k));
}
let (b, issues) = blanks(&lines, 10.0);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].hinges.len(), 1);
let h = &b[0].hinges[0];
assert!((h.from.distance(h.to) - 50.0).abs() < 1e-6 && h.keys.len() == 10, "{h:?}");
}
#[test]
fn a_crease_outside_the_blank_is_reported() {
let mut lines = tray();
lines.push(crease((200.0, 0.0), (250.0, 0.0), 20));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["outside"], "{issues:?}");
assert_eq!(issues[0].keys, vec![20]);
}
#[test]
fn a_bent_crease_folds_along_its_longest_piece() {
let mut lines = tray();
lines[1] = line(LineKind::Crease, &[(30.0, 30.0), (90.0, 30.0), (130.0, 32.0)], false, 10);
lines[0] = cut(
&[
(30.0, 0.0),
(130.0, 0.0),
(130.0, 32.0),
(160.0, 32.0),
(160.0, 90.0),
(130.0, 90.0),
(130.0, 120.0),
(30.0, 120.0),
(30.0, 90.0),
(0.0, 90.0),
(0.0, 30.0),
(30.0, 30.0),
],
1,
);
lines[2] = crease((130.0, 32.0), (130.0, 90.0), 11);
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}");
let h = b[0].hinges.iter().find(|h| h.keys == vec![10]).unwrap();
assert!(!h.straight);
assert!((h.from.y - 30.0).abs() < 1e-9 && (h.to.y - 30.0).abs() < 1e-9, "along the 60 pt piece: {h:?}");
// Within the tolerance, a crease is straight.
let mut lines = tray();
lines[1] = line(LineKind::Crease, &[(30.0, 30.0), (90.0, 30.05), (130.0, 30.0)], false, 10);
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert!(b[0].hinges.iter().all(|h| h.straight));
}
#[test]
fn a_slot_too_narrow_to_map_is_a_sliver() {
let mut lines = tray();
lines.push(cut(&[(60.0, 45.0), (60.004, 45.0), (60.004, 75.0), (60.0, 75.0)], 2));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["sliver"], "{issues:?}");
assert!(issues[0].at.is_some_and(|a| Rect::new(59.9, 44.0, 60.1, 76.0).contains(a)));
}
#[test]
fn lines_in_a_hole_are_ambiguous() {
let mut window = tray();
window.push(cut(&[(60.0, 45.0), (100.0, 45.0), (100.0, 75.0), (60.0, 75.0)], 2));
let mut lines = window.clone();
lines.push(crease((70.0, 45.0), (70.0, 75.0), 20));
let (_, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["ambiguous"], "{issues:?}");
assert_eq!(issues[0].keys, vec![20]);
let mut lines = window;
lines.push(cut(&[(70.0, 50.0), (90.0, 50.0), (90.0, 70.0), (70.0, 70.0)], 3));
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["ambiguous"], "{issues:?}");
assert_eq!(issues[0].keys, vec![3]);
assert_eq!(b.len(), 2, "the square in the window is a blank of its own");
}
#[test]
fn partial_cuts_and_perforations_make_hinges_as_creases_do() {
let mut lines = tray();
lines[1].kind = LineKind::PartialCut;
lines[3].kind = LineKind::Perforation;
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
let mut keys: Vec<Vec<u64>> = b[0].hinges.iter().map(|h| h.keys.clone()).collect();
keys.sort_unstable();
assert_eq!(keys, vec![vec![10], vec![11], vec![12], vec![13]]);
}
#[test]
fn every_code_has_an_id_and_a_severity() {
let ids: Vec<&str> = IssueCode::ALL.iter().map(|c| c.id()).collect();
assert_eq!(ids.len(), 15);
let mut unique = ids.clone();
unique.sort_unstable();
unique.dedup();
assert_eq!(unique.len(), 15);
let errors: Vec<&str> = IssueCode::ALL.iter().filter(|c| c.is_error()).map(|c| c.id()).collect();
assert_eq!(errors, vec!["noCut", "open", "looseEnd", "tooComplex", "cutOverCrease"]);
let mut sorted = IssueCode::ALL;
sorted.sort();
assert_eq!(sorted, IssueCode::ALL, "listed in issue order");
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(48))]
/// Random fold lines never panic, and the panels and hinges they give are consistent.
#[test]
fn random_fold_lines_give_consistent_blanks(
segs in proptest::collection::vec((0u8..4, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..10),
boxed in any::<bool>(),
) {
let kinds = [LineKind::Cut, LineKind::Crease, LineKind::PartialCut, LineKind::Perforation];
let mut lines: Vec<FoldLine> = segs
.iter()
.enumerate()
.map(|(i, &(k, a, b, c, d))| line(kinds[usize::from(k)], &[(a, b), (c, d)], false, i as u64))
.collect();
if boxed {
lines.push(cut(&[(-40.0, -40.0), (40.0, -40.0), (40.0, 40.0), (-40.0, 40.0)], 99));
}
let (blanks, issues) = blanks(&lines, TOL);
for b in &blanks {
prop_assert!(!b.panels.is_empty() && b.panels.len() <= MAX_PANELS);
for h in &b.hinges {
prop_assert!(h.a < h.b && h.b < b.panels.len());
prop_assert!(h.from.is_finite() && h.to.is_finite());
}
}
let mut sorted = issues.clone();
sorted.sort_by_key(|i| i.code);
prop_assert_eq!(sorted, issues);
}
}
+3
View File
@@ -4,8 +4,11 @@
//! Open profiles optionally close their circular ends with caps, and a partial sweep its cut sides. Faces are projected and sorted back to front,
//! then flat or smoothly shaded with vector gradients. This preview uses a painter's algorithm, not a depth buffer:
//! intersecting profiles can have ambiguous visibility and are not solid modelling inputs.
//!
//! [`fold`] finds the panels and hinges of a flat packaging blank from its fold lines.
#![forbid(unsafe_code)]
pub mod fold;
mod solid;
mod visibility;
pub use solid::{
+1 -1
View File
@@ -44,7 +44,7 @@ pub use lookup::{
EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, LP_JOIN_TOL, SOURCES_NAME, builder_members, connected_edges,
connected_edges_through, drawn_outlines, edge_near, edges, face_at, faces, flood_faces, is_live_paint, leaf_shapes, live_paint_at,
live_paint_takes, lp_stroke_paint, node_outline, outline_snap, path_contains, shape_builder_shapes, shapes_for, sources, visible_edge_near,
visible_face_at,
visible_edges_along, visible_face_at,
};
pub use map::{
BuilderMap, HATCH, HIGHLIGHT_RED, Hit, MergeGeometry, MergeInput, PreparedMerge, Rest, Touched, hatch, maps_built, merge_geometry, merge_inputs,
+48 -40
View File
@@ -1,7 +1,7 @@
use super::cache::RegionCache;
use super::lookup::{
connected_edges, connected_edges_through, edges, face_at, faces, flood_faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_at_where,
lp_stroke_paint, node_outline, visible_edge_near, visible_face_at,
lp_stroke_paint, node_outline, visible_edge_near, visible_edges_along, visible_face_at,
};
use super::map::{BuilderMap, HIGHLIGHT_RED, sorted_roots};
use super::{
@@ -173,9 +173,12 @@ enum LpPaint {
/// With Paint Strokes alone on, a click paints the edge nearest the pointer and
/// Shift-click fills the face. With both on, a click paints the edge nearest the pointer when one
/// is within 4 pixels, else it fills the face, and Shift-click fills the face. With both off, a
/// click paints nothing. With Highlight off, the face or edge under the pointer is not
/// highlighted. The cursor is a filled bucket where a click fills a face, a brush where it paints
/// an edge and an empty bucket where it paints nothing; with Alt it is the Eyedropper.
/// click paints nothing. A drag from where a click paints an edge paints that edge and every edge
/// of the same group that the drag crosses or touches with the current stroke, as one undo step
/// (Escape cancels); a drag from where a click fills a face fills only faces. With Highlight off,
/// the face or edge under the pointer is not highlighted. The cursor is a filled bucket where a
/// click fills a face, a brush where it paints an edge and an empty bucket where it paints nothing;
/// with Alt it is the Eyedropper.
///
/// A double-click on a face fills it and the faces reached from it across edges that draw no
/// stroke (`scope: "connected"`); on an edge it paints the edges joined to it that have its stroke.
@@ -195,16 +198,17 @@ enum LpPaint {
/// Swatches panel, wrapping around; from a color that is no swatch, Right picks the first swatch
/// and Left the last. The selected art keeps its paint. With `cursorSwatchPreview` (on), the
/// active paint shows as a chip above the pointer between the swatches before and after it,
/// except during a fill drag or with Alt held; a solid color that is no swatch shows alone, and a
/// except during a fill or stroke drag or with Alt held; a solid color that is no swatch shows alone, and a
/// paint that is not a solid color shows no chip.
pub struct LivePaintBucketTool {
pub(super) cache: RegionCache,
pub(super) hover: LpHover,
/// Where the pointer last moved, and the modifiers held there.
at: Option<(Point, Mods)>,
/// The fill command and polyline previewed from the press's snapshot.
fill_drag: Option<(Value, Vec<Vec<Point>>)>,
/// What a fill drag paints, as it was at its press.
/// The command (`livePaint.fill` or `livePaint.strokeEdge`), its params and the polyline of a
/// drag, previewed from the press's snapshot.
fill_drag: Option<(&'static str, Value, Vec<Vec<Point>>)>,
/// What a drag paints, as it was at its press.
drag_from: LpDragFrom,
/// The last [`LP_PRESSES`] presses, oldest first: the face or edge each one painted, with its
/// paint before that press, or None for a press that painted no face or edge.
@@ -234,15 +238,15 @@ struct LpPress {
/// The other faces or edges the double-click that followed the press reached, each with its
/// fill or drawn stroke paint before the double-click.
also: Vec<(NodeId, Paint)>,
/// The other faces the press's drag crossed, its release included, each with its fill before
/// the press.
/// The other faces or edges the press's drag crossed, its release included, each with its fill
/// or drawn stroke paint before the press.
dragged: Vec<(NodeId, Paint)>,
/// For a press that makes the Live Paint group: what the group is made from, with the path
/// chunks of the press's drag, its release included.
dragged_made: Option<Arc<(LpMade, Vec<Vec<Point>>)>>,
}
/// What a Live Paint Bucket fill drag paints, as it was at the press.
/// What a Live Paint Bucket fill or stroke drag paints, as it was at the press.
#[derive(Default)]
enum LpDragFrom {
#[default]
@@ -251,6 +255,8 @@ enum LpDragFrom {
Faces(Vec<Arc<Node>>),
/// What the group is made from, for a drag that makes the group.
Made(LpMade),
/// The Live Paint group whose edges a stroke drag paints.
Edges(Arc<Node>),
}
/// The faces among `faces` (a Live Paint group's faces, back to front) that a drag along the path
@@ -404,13 +410,15 @@ impl LivePaintBucketTool {
usize::from(!cx.fill_active)
}
fn begin_fill(&mut self, params: Value, p: Point) -> Vec<Action> {
self.fill_drag = Some((params.clone(), vec![vec![p]]));
vec![Action::Begin("Live Paint Bucket".into()), Action::Preview("livePaint.fill".into(), params)]
/// Start a drag pressed at `p` that previews `cmd` with `params` and the drag's path.
fn begin_fill(&mut self, cmd: &'static str, params: Value, p: Point) -> Vec<Action> {
self.fill_drag = Some((cmd, params.clone(), vec![vec![p]]));
vec![Action::Begin("Live Paint Bucket".into()), Action::Preview(cmd.into(), params)]
}
fn drag_fill(&mut self, p: Point) -> Vec<Action> {
let Some((params, chunks)) = &mut self.fill_drag else { return vec![] };
let Some((cmd, params, chunks)) = &mut self.fill_drag else { return vec![] };
let cmd = *cmd;
let Some(points) = chunks.last_mut() else { return vec![] };
let Some(&last) = points.last() else { return vec![] };
if last == p {
@@ -431,7 +439,7 @@ impl LivePaintBucketTool {
if !continuation.is_empty() {
params["continuation"] = Value::Array(continuation);
}
vec![Action::Preview("livePaint.fill".into(), params)]
vec![Action::Preview(cmd.into(), params)]
}
/// What a click paints, Shift held or not. Shift switches Paint Fills alone to Paint Strokes
@@ -459,13 +467,13 @@ impl LivePaintBucketTool {
self.note_press(Some(LpPress { part: Some(n.id), at, before, also: vec![], dragged: vec![], dragged_made: None }));
}
/// End the fill drag, noting on the last press the other faces its drag crossed, with their
/// fills before the press (for a press that makes the group, what the group is made from and
/// the drag, for [`Self::before`] to look the faces up in the group made). → whether a fill
/// drag was on.
/// End the drag, noting on the last press the other faces or edges its drag crossed, with their
/// fills or drawn stroke paints before the press (for a press that makes the group, what the
/// group is made from and the drag, for [`Self::before`] to look the faces up in the group
/// made). → whether a drag was on.
fn end_fill(&mut self) -> bool {
let from = std::mem::take(&mut self.drag_from);
let Some((_, chunks)) = self.fill_drag.take() else { return false };
let Some((_, _, chunks)) = self.fill_drag.take() else { return false };
let Some(Some(last)) = self.presses.last_mut() else { return true };
match from {
LpDragFrom::None => {}
@@ -474,6 +482,11 @@ impl LivePaintBucketTool {
last.dragged = crossed_faces(&faces, &chunks).into_iter().filter(|(id, _)| part != Some(*id)).collect();
}
LpDragFrom::Made(made) => last.dragged_made = Some(Arc::new((made, chunks))),
LpDragFrom::Edges(group) => {
let part = last.part;
last.dragged =
visible_edges_along(&group, &chunks).into_iter().filter(|e| part != Some(e.id)).map(|e| (e.id, lp_stroke_paint(e))).collect();
}
}
true
}
@@ -549,22 +562,16 @@ impl LivePaintBucketTool {
if clicks == 2
&& let Some(group) = cx.doc.node(g)
{
// The other edge of this group either click painted joins as the stroke paint it
// had before. A face either click filled is not an edge and does not join.
// The other edges of this group either click painted, by its press or its drag, join
// as the stroke paint they had before. A face either click filled is not an edge and
// does not join. `livePaint.strokeEdge` takes at most 4096 of them.
let group_edges: std::collections::HashSet<NodeId> = edges(group).iter().map(|x| x.id).collect();
let mut seen = std::collections::HashSet::from([e.id]);
let mut through: Vec<NodeId> = vec![];
for id in self
.presses
.len()
.checked_sub(2)
.and_then(|i| self.presses.get(i..))
.into_iter()
.flatten()
.flatten()
.filter(|q| q.before == like)
.filter_map(|q| q.part)
{
if id != e.id && group_edges.contains(&id) && !through.contains(&id) {
for id in self.presses.len().checked_sub(2).and_then(|i| self.presses.get(i..)).into_iter().flatten().flatten().flat_map(|q| {
q.part.filter(|_| q.before == like).into_iter().chain(q.dragged.iter().filter(|(_, before)| *before == like).map(|(id, _)| *id))
}) {
if through.len() < 4096 && group_edges.contains(&id) && seen.insert(id) {
through.push(id);
}
}
@@ -718,7 +725,8 @@ impl Tool for LivePaintBucketTool {
&& let Some((g, Some(e))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id))
{
self.note_part(e, true, p);
return vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0) }))];
self.drag_from = cx.doc.node(g).map_or(LpDragFrom::None, |n| LpDragFrom::Edges(Arc::new(n.clone())));
return self.begin_fill("livePaint.strokeEdge", json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0) }), p);
}
if !matches!(paint, LpPaint::Fills | LpPaint::Both) {
self.note_press(None);
@@ -730,7 +738,7 @@ impl Tool for LivePaintBucketTool {
None => self.note_press(None),
}
self.drag_from = LpDragFrom::Faces(cx.doc.node(g).map(|n| faces(n).into_iter().cloned().collect()).unwrap_or_default());
return self.begin_fill(json!({ "group": g.0, "point": point }), p);
return self.begin_fill("livePaint.fill", json!({ "group": g.0, "point": point }), p);
}
if self.cache.at(cx, p).is_some() {
let roots = sorted_roots(cx.doc, &cx.selection.objects);
@@ -738,7 +746,7 @@ impl Tool for LivePaintBucketTool {
let before = made_face_fill(&made, p);
self.note_press(Some(LpPress { part: None, at: p, before, also: vec![], dragged: vec![], dragged_made: None }));
self.drag_from = LpDragFrom::Made(made);
return self.begin_fill(json!({ "ids": json_ids(&roots), "point": point }), p);
return self.begin_fill("livePaint.fill", json!({ "ids": json_ids(&roots), "point": point }), p);
}
self.note_press(None);
vec![]
@@ -762,7 +770,7 @@ impl Tool for LivePaintBucketTool {
self.presses.clear();
}
/// Escape during a fill drag cancels it. Left and Right pick the color swatch before or after
/// Escape during a fill or stroke drag cancels it. Left and Right pick the color swatch before or after
/// the active paint, while no drag is on.
fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec<Action> {
if key == ToolKey::Escape {
@@ -819,7 +827,7 @@ impl Tool for LivePaintBucketTool {
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut out = lp_overlays(&self.hover, &self.cache, self.color, self.width as f32, (self.width * LP_BUCKET_EDGE_FRACTION) as f32);
// No chips during a fill drag, or while Alt makes the tool sample with the eyedropper.
// No chips during a fill or stroke drag, or while Alt makes the tool sample with the eyedropper.
if self.preview
&& !self.busy()
&& let Some((at, mods)) = self.at
+59
View File
@@ -90,6 +90,65 @@ pub fn visible_edge_near(group: &Node, p: Point, tol: f64) -> Option<&Arc<Node>>
nearest_edge(edges(group).into_iter().filter(|e| e.visible), p, tol)
}
/// The edges of `group` that are not hidden and that the polyline through the points of each chunk
/// of `chunks` crosses or comes within [`LP_JOIN_TOL`] of, each once, in the group's order. Each
/// stretch of the polyline tests only the edge segments whose bounds lie near it.
pub fn visible_edges_along<'a>(group: &'a Node, chunks: &[Vec<Point>]) -> Vec<&'a Arc<Node>> {
use kurbo::ParamCurveNearest as _;
let shown: Vec<&Arc<Node>> = edges(group).into_iter().filter(|e| e.visible).collect();
// Each edge segment, with the index in `shown` of its edge.
let mut owner: Vec<usize> = vec![];
let mut segs: Vec<(kurbo::CubicBez, bool)> = vec![];
for (i, e) in shown.iter().enumerate() {
for s in e.path_data().map(lp_segments).unwrap_or_default() {
owner.push(i);
segs.push((s, true));
}
}
if segs.is_empty() {
return vec![];
}
let grid = LpEdgeGrid::new(&segs);
let close = LP_JOIN_TOL * LP_JOIN_TOL;
let mut hit = vec![false; shown.len()];
for chunk in chunks {
for pair in chunk.windows(2) {
let &[a, b] = pair else { continue };
let line = kurbo::Line::new(a, b);
let on_line = |p: Point| line.nearest(p, 1e-9).distance_sq <= close;
for k in grid.near_box(Rect::from_points(a, b).inflate(LP_JOIN_TOL, LP_JOIN_TOL)) {
let (Some((c, _)), Some(&i)) = (segs.get(k), owner.get(k)) else { continue };
let Some(h) = hit.get_mut(i) else { continue };
if *h {
continue;
}
let on_seg = |p: Point| c.nearest(p, 1e-9).distance_sq <= close;
// An end of either one on the other covers a touch and a stretch that runs along
// the edge, where no single crossing point exists. Where neither crosses the other,
// their closest points are ends or a point of the edge where it runs parallel to
// the drag. A crossing kurbo finds just before or after an end of the edge counts
// only through the checks on that end.
*h = on_seg(a)
|| on_seg(b)
|| on_line(c.p0)
|| on_line(c.p3)
|| (a != b
&& (kurbo::PathSeg::Cubic(*c).intersect_line(line).iter().any(|x| (0.0..=1.0).contains(&x.segment_t))
|| lp_parallel_at(c, b - a).into_iter().any(|t| on_line(kurbo::ParamCurve::eval(c, t)))));
}
}
}
shown.into_iter().zip(hit).filter_map(|(e, h)| h.then_some(e)).collect()
}
/// The parameters strictly between 0 and 1 where cubic `c` runs parallel to direction `d`: the
/// roots of the cross product of its derivative with `d`.
fn lp_parallel_at(c: &kurbo::CubicBez, d: kurbo::Vec2) -> Vec<f64> {
let [a, b, e] = [c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2].map(|v| v.cross(d));
// a(1-t)² + 2b·t(1-t) + e·t², expanded in powers of t.
kurbo::common::solve_quadratic(a, 2.0 * (b - a), a - 2.0 * b + e).into_iter().filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0).collect()
}
/// The edge of `edges` nearest to `p` within `tol`.
fn nearest_edge<'a>(edges: impl IntoIterator<Item = &'a Arc<Node>>, p: Point, tol: f64) -> Option<&'a Arc<Node>> {
let mut best: Option<(f64, &Arc<Node>)> = None;
+183 -6
View File
@@ -1120,8 +1120,170 @@ fn bucket_click_fills_face_and_shift_click_strokes_edge() {
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 25.0)), vec![Action::Commit]);
let shift = Mods { shift: true, ..Default::default() };
let acts = t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(shift));
let Action::Exec(id, _) = &acts[0] else { panic!() };
let [Action::Begin(_), Action::Preview(id, _)] = acts.as_slice() else { panic!("{acts:?}") };
assert_eq!(id, "livePaint.strokeEdge");
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 51.0, 25.0).with_mods(shift)), vec![Action::Commit]);
}
/// A drag reaches the visible edges its path crosses or passes within 0.0001 pt of, including the
/// middle of a curved edge it runs past without crossing; a hidden edge and an edge farther away are
/// not reached.
#[test]
fn visible_edges_along_finds_crossed_and_near_edges() {
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let mut arc = BezPath::new();
arc.move_to((100.0, 0.0));
// Farthest right at (130, 50), where it runs straight down.
arc.curve_to((140.0, 0.0), (140.0, 100.0), (100.0, 100.0));
let mut kids = vec![empty_sources(&mut d)];
let mut ids = vec![];
for (path, visible) in [
(shapes::line(Point::new(0.0, 0.0), Point::new(0.0, 100.0)), true),
(shapes::line(Point::new(50.0, 0.0), Point::new(50.0, 100.0)), false),
(vectorcraft_geom::PathData::from_bezpath(&arc), true),
(shapes::line(Point::new(0.0, 200.0), Point::new(100.0, 200.0)), true),
] {
let id = d.alloc_id();
let mut edge = Node::path(id, path, Appearance::default());
edge.name = Some(EDGE_NAME.into());
edge.visible = visible;
kids.push(Arc::new(edge));
ids.push(id);
}
let gid = d.alloc_id();
let mut g = Node::group(gid, kids);
g.name = Some(LIVE_PAINT_NAME.into());
d.insert(Some(l), 0, g).unwrap();
let group = d.node(gid).unwrap();
let reached = |x: f64| {
let chunks = vec![
vec![Point::new(-10.0, 50.0), Point::new(60.0, 50.0), Point::new(60.0, -20.0)],
vec![Point::new(60.0, -20.0), Point::new(x, -20.0), Point::new(x, 60.0)],
];
visible_edges_along(group, &chunks).iter().map(|e| e.id).collect::<Vec<_>>()
};
assert_eq!(reached(130.00005), vec![ids[0], ids[2]]);
assert_eq!(reached(130.001), vec![ids[0]]);
}
/// A drag that passes 0.0002 pt before the start of a long curved edge does not reach it, although
/// the curve extended a tiny step past its start meets the drag.
#[test]
fn visible_edges_along_skips_an_edge_the_drag_meets_only_past_its_end() {
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let mut curve = BezPath::new();
curve.move_to((0.0, 0.0));
curve.curve_to((100000.0, 0.0), (200000.0, 100.0), (300000.0, 100.0));
let id = d.alloc_id();
let mut edge = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&curve), Appearance::default());
edge.name = Some(EDGE_NAME.into());
let gid = d.alloc_id();
let mut g = Node::group(gid, vec![empty_sources(&mut d), Arc::new(edge)]);
g.name = Some(LIVE_PAINT_NAME.into());
d.insert(Some(l), 0, g).unwrap();
let group = d.node(gid).unwrap();
let reached = |x: f64| visible_edges_along(group, &[vec![Point::new(x, -1.0), Point::new(x, 1.0)]]).iter().map(|e| e.id).collect::<Vec<_>>();
assert_eq!(reached(-0.0002), Vec::<NodeId>::new());
assert_eq!(reached(-0.00005), vec![id]);
assert_eq!(reached(0.0002), vec![id]);
}
/// A double-click on an edge after a press whose drag stroked another edge of the line joins
/// through that edge as the stroke paint it had before the drag.
#[test]
fn bucket_edge_double_click_joins_through_an_edge_the_first_drag_stroked() {
let black = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 0.0));
let green = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 1.0, 0.0));
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let mut kids = vec![empty_sources(&mut d)];
let mut ids = vec![];
for (x0, x1) in [(0.0, 30.0), (30.0, 70.0), (70.0, 100.0)] {
let id = d.alloc_id();
let mut a = Appearance::default();
a.set_stroke(black.clone());
let mut edge = Node::path(id, shapes::line(Point::new(x0, 100.0), Point::new(x1, 100.0)), a);
edge.name = Some(EDGE_NAME.into());
kids.push(Arc::new(edge));
ids.push(id);
}
let gid = d.alloc_id();
let mut g = Node::group(gid, kids);
g.name = Some(LIVE_PAINT_NAME.into());
d.insert(Some(l), 0, g).unwrap();
let mut later = d.clone();
for id in &ids[1..] {
later.node_mut(*id).unwrap().appearance.set_stroke(green.clone());
}
let s = Selection::default();
let p = paint();
let (cx, later) = (cx(&d, &s, &p), cx(&later, &s, &p));
let shift = Mods { shift: true, ..Default::default() };
let mut t = LivePaintBucketTool::default();
// The first press strokes the right edge and its drag crosses the middle one.
for (k, x, y) in
[(PointerKind::Down, 85.0, 100.0), (PointerKind::Drag, 85.0, 110.0), (PointerKind::Drag, 50.0, 110.0), (PointerKind::Up, 50.0, 90.0)]
{
t.pointer(&cx, &ev(k, x, y).with_mods(shift));
}
t.pointer(&later, &ev(PointerKind::Down, 85.0, 100.0).with_mods(shift));
t.pointer(&later, &ev(PointerKind::Up, 85.0, 100.0).with_mods(shift));
let like = serde_json::to_value(&black).unwrap();
assert_eq!(
t.pointer(&later, &ev(PointerKind::DoubleClick, 85.0, 100.0).with_mods(shift)),
vec![Action::Exec(
"livePaint.strokeEdge".into(),
json!({ "group": gid.0, "point": [85.0, 100.0], "tolerance": 4.0, "scope": "connected", "through": [ids[1].0], "match": like })
)]
);
}
/// A drag from an edge previews `livePaint.strokeEdge` with the drag's path as it goes and commits
/// once on the release; Escape cancels it, and what the drag paints is fixed at the press.
#[test]
fn bucket_edge_drag_previews_points_and_commits_once() {
let (d, gid, ..) = live_group_doc();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let shift = Mods { shift: true, ..Default::default() };
let stroke = |points: Value| {
let mut v = json!({ "group": gid.0, "point": [51.0, 25.0], "tolerance": 4.0 });
if !points.is_null() {
v["points"] = points;
}
Action::Preview("livePaint.strokeEdge".into(), v)
};
let mut t = LivePaintBucketTool::default();
assert_eq!(
t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(shift)),
vec![Action::Begin("Live Paint Bucket".into()), stroke(Value::Null)]
);
assert!(t.busy());
// Shift let go during the drag: the drag still paints edges.
assert_eq!(t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 25.0)), vec![stroke(json!([[51.0, 25.0], [75.0, 25.0]]))]);
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 120.0, 25.0)), vec![stroke(json!([[51.0, 25.0], [75.0, 25.0], [120.0, 25.0]])), Action::Commit]);
assert!(!t.busy());
// Escape before the release cancels the drag, and the release then commits nothing.
assert_eq!(
t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(shift)),
vec![Action::Begin("Live Paint Bucket".into()), stroke(Value::Null)]
);
t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 25.0).with_mods(shift));
assert!(t.claims_key(&cx, ToolKey::Escape));
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
assert!(t.pointer(&cx, &ev(PointerKind::Up, 120.0, 25.0).with_mods(shift)).is_empty());
// With both options on, a drag from a face fills faces, even across an edge.
t.set_option("paintStrokes", &json!(true));
let acts = t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0));
let [Action::Begin(_), Action::Preview(id, _)] = acts.as_slice() else { panic!("{acts:?}") };
assert_eq!(id, "livePaint.fill");
let acts = t.pointer(&cx, &ev(PointerKind::Drag, 51.0, 25.0));
let [Action::Preview(id, _)] = acts.as_slice() else { panic!("{acts:?}") };
assert_eq!(id, "livePaint.fill");
t.pointer(&cx, &ev(PointerKind::Up, 51.0, 25.0));
}
/// A double-click runs a click's command with `scope: "connected"` and a triple-click with
@@ -1484,7 +1646,12 @@ fn bucket_options_choose_what_a_click_paints() {
let fill = |x: f64| {
vec![Action::Begin("Live Paint Bucket".into()), Action::Preview("livePaint.fill".into(), json!({ "group": gid.0, "point": [x, 25.0] }))]
};
let stroke = |x: f64| vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": gid.0, "point": [x, 25.0], "tolerance": 4.0 }))];
let stroke = |x: f64| {
vec![
Action::Begin("Live Paint Bucket".into()),
Action::Preview("livePaint.strokeEdge".into(), json!({ "group": gid.0, "point": [x, 25.0], "tolerance": 4.0 })),
]
};
let click = |t: &mut LivePaintBucketTool, x: f64, m: Mods| {
let acts = t.pointer(&cx, &ev(PointerKind::Down, x, 25.0).with_mods(m));
t.pointer(&cx, &ev(PointerKind::Up, x, 25.0).with_mods(m));
@@ -3095,8 +3262,13 @@ fn live_paint_edges_outside_the_faces_come_from_the_nearest_visible_group() {
bucket.set_option("cursorSwatchPreview", &json!(false));
bucket.pointer(&cx, &ev(PointerKind::Move, x, y).with_mods(shift));
assert_eq!(edge_x(&bucket.overlays(&cx)), want.map(|w| w.2));
let stroked = want.map(|(g, ..)| Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": [x, y], "tolerance": 4.0 })));
assert_eq!(bucket.pointer(&cx, &ev(PointerKind::Down, x, y).with_mods(shift)), stroked.into_iter().collect::<Vec<_>>());
let stroked = want.map(|(g, ..)| {
vec![
Action::Begin("Live Paint Bucket".into()),
Action::Preview("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": [x, y], "tolerance": 4.0 })),
]
});
assert_eq!(bucket.pointer(&cx, &ev(PointerKind::Down, x, y).with_mods(shift)), stroked.unwrap_or_default());
};
check(&d, Some((back, back_right, 100.0)));
// A hidden group's edges are not highlighted or picked.
@@ -3139,8 +3311,13 @@ fn live_paint_tools_skip_hidden_edges() {
bucket.set_option("cursorSwatchPreview", &json!(false));
bucket.pointer(&cx, &ev(PointerKind::Move, x, 50.0).with_mods(shift));
assert_eq!(edge_x(&bucket.overlays(&cx)), want.map(|w| w.2), "x {x}");
let stroked = want.map(|(g, ..)| Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": [x, 50.0], "tolerance": 4.0 })));
assert_eq!(bucket.pointer(&cx, &ev(PointerKind::Down, x, 50.0).with_mods(shift)), stroked.into_iter().collect::<Vec<_>>(), "x {x}");
let stroked = want.map(|(g, ..)| {
vec![
Action::Begin("Live Paint Bucket".into()),
Action::Preview("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": [x, 50.0], "tolerance": 4.0 })),
]
});
assert_eq!(bucket.pointer(&cx, &ev(PointerKind::Down, x, 50.0).with_mods(shift)), stroked.unwrap_or_default(), "x {x}");
}
}
+80 -27
View File
@@ -18,7 +18,7 @@ use serde_json::{Value, json};
use vectorcraft_geom::Point;
use crate::guides::{DrawSnap, Leave};
use crate::shape::{box_params, drag_rect, turned_box};
use crate::shape::{box_params, turned_box};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
/// How much ↑ or ↓ changes the arc's slope while it is dragged out.
@@ -155,17 +155,13 @@ impl FamilyTool {
}
/// How the dragged point keeps to the start: a spiral's radius goes anywhere, the arc's and
/// the grids' corner keeps to a diagonal with Shift (a grid's square is taken along the
/// Constrain Angle's axes instead when it turns them, [`Self::command_at`]).
/// the grids' corner keeps to a diagonal with Shift (an arc's or a grid's square is taken along
/// the Constrain Angle's axes instead when it turns them, [`Self::command_at`]).
fn leave(&self, cx: &ToolContext, start: Point, m: Mods) -> Option<Leave> {
let turned = self.is_grid() && vectorcraft_geom::constrain_axes(cx.constrain_angle).is_some();
let turned = vectorcraft_geom::constrain_axes(cx.constrain_angle).is_some();
(self.id != "spiral").then(|| Leave::diagonal(start, m.shift && !turned))
}
fn is_grid(&self) -> bool {
matches!(self.id, "rectangularGrid" | "polarGrid")
}
/// The natural logarithm of the radius of the inner end of a spiral of outer radius `r` drawn
/// with the tool's decay and segments (a logarithm, so that a low decay with many segments does
/// not round to 0). The decay ratio is clamped to 0.05…0.9999 as `shapes::spiral` clamps it.
@@ -245,7 +241,7 @@ impl FamilyTool {
}
/// [`Self::command`] with General › Constrain Angle `base` (degrees, counter-clockwise): the
/// grids are drawn along the x and y axes turned by it, as the rectangle is.
/// arc and the grids are drawn along the x and y axes turned by it, as the rectangle is.
pub fn command_at(&self, start: Point, p: Point, m: Mods, base: f64) -> (String, Value) {
match self.id {
"spiral" => {
@@ -263,25 +259,30 @@ impl FamilyTool {
}
(format!("shape.{}", self.id), params)
}
// The arc: its box along the Constrain Angle's axes, with the reference point taken in
// that box and turned out onto the page; the arc turns about it.
_ => {
let r = drag_rect(start, p, m).abs();
let (r, axes) = turned_box(start, p, m, base);
let r = r.abs();
let (w, h) = (r.width().max(1e-9), r.height().max(1e-9));
let rp = vectorcraft_geom::reference_point(vectorcraft_geom::Rect::new(0.0, 0.0, w, h), self.reference.min(8));
let anchor = Point::new(r.x0 + rp.x, r.y0 + rp.y);
(
"shape.arc".into(),
json!({
"x": anchor.x,
"y": anchor.y,
"lengthX": w,
"lengthY": h,
"reference": self.reference,
"baseAlong": self.base_along,
"slope": self.slope,
"closed": self.closed,
"fillArc": self.fill_arc,
}),
)
let local = Point::new(r.x0 + rp.x, r.y0 + rp.y);
let anchor = axes.map_or(local, |a| a * local);
let mut params = json!({
"x": anchor.x,
"y": anchor.y,
"lengthX": w,
"lengthY": h,
"reference": self.reference,
"baseAlong": self.base_along,
"slope": self.slope,
"closed": self.closed,
"fillArc": self.fill_arc,
});
if let Some(rotation) = axes.and_then(|_| vectorcraft_geom::constrain_rotation(base)) {
params["rotation"] = json!(rotation);
}
("shape.arc".into(), params)
}
}
}
@@ -433,8 +434,8 @@ impl Tool for FamilyTool {
let mut o = self.snap.guides().to_vec();
if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) {
// The size as drawn (from the centre with Alt, square with Shift).
// A grid's along the Constrain Angle's axes, as it is drawn.
let r = if self.is_grid() { turned_box(s, self.last, self.mods, cx.constrain_angle).0 } else { drag_rect(s, self.last, self.mods) };
// An arc's or a grid's along the Constrain Angle's axes, as it is drawn.
let r = turned_box(s, self.last, self.mods, cx.constrain_angle).0;
let (w, h) = if self.id == "spiral" { ((self.last - s).x.abs(), (self.last - s).y.abs()) } else { (r.width(), r.height()) };
o.push(Overlay::Measure { p: self.last, text: cx.size_label(w, h) });
}
@@ -1080,6 +1081,58 @@ mod tests {
assert_eq!(v["rotation"], json!(-30.0));
}
/// General › Constrain Angle: an arc is drawn along the turned axes, its reference point taken
/// in the turned box and the arc turned about it; Shift's equal lengths are taken along the
/// turned axes, and F, C and ↑ keep the turn and the reference point; at 0° and whole turns
/// the arc is as before.
#[test]
fn arcs_follow_the_constrain_angle() {
let t = FamilyTool::new("arc");
let (a, b) = (Point::new(100.0, 100.0), Point::new(160.0, 120.0));
let flat = t.command(a, b, Mods::default());
assert!(flat.1.get("rotation").is_none(), "{flat:?}");
assert_eq!(t.command_at(a, b, Mods::default(), 0.0), flat);
assert_eq!(t.command_at(a, b, Mods::default(), 360.0), flat);
// At 90° the drag runs 20 along the turned x axis and 60 along the turned y axis; the
// top-left reference point of that box is at (100, 120) on the page.
let (c, v) = t.command_at(a, b, Mods::default(), 90.0);
assert_eq!(c, "shape.arc");
assert_eq!(
v,
json!({"x": 100.0, "y": 120.0, "lengthX": 20.0, "lengthY": 60.0, "reference": 0, "baseAlong": "x", "slope": 50.0, "closed": false, "fillArc": false, "rotation": -90.0})
);
let shift = Mods { shift: true, ..Mods::default() };
let (_, v) = t.command_at(a, b, shift, 30.0);
assert!((v["lengthX"].as_f64().unwrap() - v["lengthY"].as_f64().unwrap()).abs() < 1e-9, "equal along the turned axes: {v}");
assert_eq!(v["rotation"], json!(-30.0));
// A Shift drag at 30°: the pointer is not held to the page's diagonal.
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let mut cx = cx(&d, &s, &p);
cx.smart_guides = false;
cx.constrain_angle = 30.0;
let mut t = FamilyTool::new("arc");
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 70.0, 30.0).with_mods(shift));
let expected = t.command_at(Point::new(10.0, 10.0), Point::new(70.0, 30.0), shift, 30.0);
assert_eq!(out, vec![Action::Begin("Arc".into()), Action::Preview(expected.0, expected.1.clone())]);
let preview = |a: Vec<Action>| match &a[..] {
[Action::Preview(c, v)] if c == "shape.arc" => v.clone(),
_ => panic!("{a:?}"),
};
let v = preview(t.key(&cx, ToolKey::Letter('f'), Mods::default()));
assert_eq!(v["baseAlong"], json!("y"));
let v = preview(t.key(&cx, ToolKey::Letter('c'), Mods::default()));
assert_eq!(v["closed"], json!(true));
let v = preview(t.key(&cx, ToolKey::Up, Mods::default()));
assert_eq!(v["slope"], json!(60.0));
for k in ["x", "y", "lengthX", "lengthY", "rotation"] {
assert_eq!(v[k], expected.1[k], "{k} stays");
}
}
/// The start and the dragged corner snap to Smart Guides (#506), Shift sliding the corner of
/// a square grid along its diagonal into line.
#[test]
+1
View File
@@ -34,6 +34,7 @@ pub mod pie;
pub mod place;
pub mod printtiling;
pub mod repeat_grid;
pub mod repeat_radial;
pub mod rulerguide;
pub mod select;
pub mod settings;
+684
View File
@@ -0,0 +1,684 @@
//! Radial Repeat's on-canvas handles: a handle below the repeat adds or removes instances, a
//! handle on the circle the instances sit on sets its radius, and a splitter on the circle hides
//! instances at the end of the ring while the others keep their places, as the public "Create
//! radial repeats" page describes. Drawing and hit testing share the document-space geometry of
//! [`RadialHandles::of`]; a drag previews the existing Repeat Options command and commits as one
//! undo step.
//!
//! A split ring is kept in the repeat's existing options: `instances` counts the instances shown,
//! and `endAngle` places them a full ring's step apart from `startAngle` (one step past it for a
//! single instance). The full ring's slot count is read back from that step, so dragging the
//! splitter forward shows the hidden instances again.
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, OrientedBox, RepeatKind, Selection};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use crate::bbox::Handle;
use crate::{Action, Cursor, Mods, ToolContext};
/// The radius of the instances, radius and splitter handles (screen points).
pub const HANDLE_RADIUS: f32 = 5.0;
/// How far (screen points) the instances handle sits below the bounding box, clear of its own
/// handles and rotate zones.
pub const HANDLE_GAP: f64 = 22.0;
/// How far (screen points) the instances handle is dragged for each instance it adds or removes.
pub const INSTANCE_STEP: f64 = 16.0;
/// How near (screen points) a press must come to a handle to take it.
const REACH: f64 = 8.0;
/// The most instances a radial repeat has (as `object.repeat.options` accepts them).
const MAX_INSTANCES: f64 = 1000.0;
/// A control of [`RadialHandles`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RadialPart {
/// Below the repeat: drag down for more instances, up for fewer.
Instances,
/// On the circle, between the first two instances: drag outward for a larger radius, inward
/// for a smaller one.
Radius,
/// On the circle, half a step past the last instance shown: drag it back around the circle to
/// hide the instances it passes, forward to show them again.
Splitter,
}
/// The full ring a radial repeat's instances sit on.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Ring {
/// The instances a full turn holds at the repeat's step.
slots: u32,
/// Degrees from one instance to the next (negative when the instances run the other way).
step: f64,
}
impl Ring {
/// The ring of `instances` laid out from `start` to `end` degrees, when their step fits a
/// whole number of times (2 to 1,000, and no fewer than the instances) in a full turn.
fn of(instances: u32, start: f64, end: f64) -> Option<Self> {
let step = instance_step(instances, end - start);
let slots = 360.0 / step.abs();
let whole = slots.round();
((slots - whole).abs() < 1e-6 && (2.0..=MAX_INSTANCES).contains(&whole) && whole >= f64::from(instances))
.then(|| Self { slots: whole as u32, step: (360.0 / whole).copysign(step) })
}
/// The Repeat Options that show the first `shown` instances of the ring (1 to all of them),
/// laid out from `start` degrees.
fn options(&self, shown: u32, start: f64) -> Value {
let shown = shown.clamp(1, self.slots.max(1));
let sweep = if shown == self.slots { 360.0_f64.copysign(self.step) } else { self.step * f64::from(shown.saturating_sub(1).max(1)) };
json!({ "instances": shown, "endAngle": start + sweep })
}
/// The instances shown with the splitter `turn` degrees around the ring from the first
/// instance: those it has passed, one at least and the full ring at most.
fn shown(&self, turn: f64) -> u32 {
let k = (turn / self.step.abs()).floor() + 1.0;
if k.is_nan() { 1 } else { k.clamp(1.0, f64::from(self.slots)) as u32 }
}
}
/// Degrees between neighboring instances, as `repeat_transforms` spaces `instances` over `sweep`.
fn instance_step(instances: u32, sweep: f64) -> f64 {
let full = (sweep.abs() - 360.0).abs() < 1e-9;
if full || instances <= 1 { sweep / f64::from(instances.max(1)) } else { sweep / f64::from(instances - 1) }
}
/// `v` turned by `deg` degrees as `repeat_transforms` turns the instances.
fn turned(v: Vec2, deg: f64) -> Vec2 {
(Affine::rotate(deg.to_radians()) * v.to_point()).to_vec2()
}
/// The direction of `v` in counter-clockwise screen degrees.
fn screen_angle(v: Vec2) -> f64 {
(-v.y).atan2(v.x).to_degrees()
}
/// The controls of a selected radial repeat, in document space.
#[derive(Clone, Copy, Debug)]
pub struct RadialHandles {
pub id: NodeId,
instances: u32,
/// The circle the instances' centers sit on.
pub center: Point,
pub radius: f64,
/// The unit direction from the center to the radius handle.
out: Vec2,
/// Document points of drag for each instance.
step: f64,
start_angle: f64,
ring: Option<Ring>,
pub instances_at: Point,
pub radius_at: Point,
/// Where the splitter is: none when the instances' step does not divide a full turn, for a
/// single instance to a turn, or with a radius of 0.
pub splitter_at: Option<Point>,
}
impl RadialHandles {
/// The controls of a single editable radial repeat selected whole, the instances handle placed
/// below `frame` (the bounding box the Selection tool shows; its geometric bounds without one)
/// at `zoom`.
pub fn of(doc: &Document, selection: &Selection, frame: Option<OrientedBox>, zoom: f64) -> Option<Self> {
let [id] = selection.objects.as_slice() else { return None };
if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 {
return None;
}
let n = doc.node(*id)?;
let NodeKind::Repeat(spec) = &n.kind else { return None };
let RepeatKind::Radial { instances, radius, center, start_angle, end_angle, .. } = spec.kind else { return None };
if ![radius, center.x, center.y, start_angle, end_angle].iter().all(|v| v.is_finite()) {
return None;
}
let source = spec.source_bounds()?;
if !finite(source.center()) {
return None;
}
// As `repeat_transforms` lays the instances out: the first one at `start_angle` from the
// source's own direction, the rest a step apart.
let instances = instances.clamp(1, 1000);
let mut d = source.center() - center;
if d.hypot() < 1e-9 {
d = Vec2::new(0.0, -1.0);
}
let first = turned(d.normalize(), start_angle);
let step = instance_step(instances, end_angle - start_angle);
// Halfway between the first two instances; opposite a single one.
let out = turned(first, if instances == 1 { 180.0 } else { step / 2.0 });
let radius = radius.max(0.0);
let ring = Ring::of(instances, start_angle, end_angle);
// Half a step past the last instance shown.
let splitter_at = ring.filter(|_| radius > 0.0).map(|r| center + turned(first, r.step * (f64::from(instances) - 0.5)) * radius);
let frame = match frame {
Some(f) => aabb(f.corners())?,
None => n.geometric_bounds_with(&doc.symbol_boxes())?,
};
let h = Self {
id: *id,
instances,
center,
radius,
out,
step: INSTANCE_STEP / zoom,
start_angle,
ring,
instances_at: Point::new(frame.center().x, frame.y1 + HANDLE_GAP / zoom),
radius_at: center + out * radius,
splitter_at: splitter_at.filter(|p| finite(*p)),
};
(finite(h.instances_at) && finite(h.radius_at) && h.step.is_finite() && h.step > 0.0).then_some(h)
}
/// The controls with where they are.
pub fn parts(&self) -> Vec<(RadialPart, Point)> {
let mut parts = vec![(RadialPart::Instances, self.instances_at), (RadialPart::Radius, self.radius_at)];
parts.extend(self.splitter_at.map(|at| (RadialPart::Splitter, at)));
parts
}
/// The control under `p` (the nearer within reach) and the repeat's controls, unless a
/// bounding-box handle is there, which keeps its scaling.
fn hit(cx: &ToolContext, p: Point) -> Option<(Self, RadialPart)> {
if !cx.show_bbox || !finite(p) {
return None;
}
let h = Self::of(cx.doc, cx.selection, crate::select::selection_box(cx), cx.zoom)?;
let reach = cx.tol(REACH);
let (part, _) =
h.parts().into_iter().map(|(part, q)| (part, q.distance(p))).filter(|(_, d)| *d <= reach).min_by(|a, b| a.1.total_cmp(&b.1))?;
(!crate::select::bbox_handle_at(cx, p)).then_some((h, part))
}
/// The Repeat Options that dragging `part` by `d` (document points) from the press gives;
/// none when the drag is too far to measure. The splitter's options are those it shows at the
/// press.
fn options(&self, part: RadialPart, d: Vec2) -> Option<Value> {
match part {
RadialPart::Instances => {
let n = f64::from(self.instances) + (d.y / self.step).round();
// NaN only comes from an infinite drag; the clamp keeps a huge one at the limit.
(!n.is_nan()).then(|| json!({ "instances": n.clamp(1.0, MAX_INSTANCES) as u32 }))
}
RadialPart::Radius => {
// Only the part of the drag along the line from the center moves the circle.
let r = ((self.radius + d.dot(self.out)).max(0.0) * 100.0).round() / 100.0;
r.is_finite().then(|| json!({ "radius": r }))
}
RadialPart::Splitter => self.ring.map(|r| r.options(self.instances, self.start_angle)),
}
}
/// Degrees around the ring from the first instance to the splitter, in the direction the
/// instances run.
fn splitter_turn(&self) -> f64 {
self.ring.map_or(0.0, |r| (f64::from(self.instances) - 0.5) * r.step.abs())
}
/// The direction of `p` from the center in degrees, as the instances are turned; none at the
/// center.
fn bearing(&self, p: Point) -> Option<f64> {
let v = p - self.center;
(finite(p) && v.hypot() > 1e-9).then(|| v.y.atan2(v.x).to_degrees())
}
/// The direction (counter-clockwise degrees) in which the radius handle moves the circle out.
fn out_angle(&self) -> f64 {
screen_angle(self.out)
}
/// The direction (counter-clockwise degrees) along the circle at the splitter.
fn splitter_angle(&self) -> f64 {
self.splitter_at.map_or(0.0, |at| screen_angle(at - self.center) + 90.0)
}
}
/// The page-square bounds of `corners`.
fn aabb(corners: [Point; 4]) -> Option<Rect> {
let r = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |r, p| r.union_pt(*p));
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()).then_some(r)
}
fn finite(p: Point) -> bool {
p.x.is_finite() && p.y.is_finite()
}
/// The resize cursor of `part`, turned with the view: up and down for the instances handle, along
/// the line from the center for the radius handle, and along the circle for the splitter.
fn part_cursor(cx: &ToolContext, h: &RadialHandles, part: RadialPart) -> Cursor {
match part {
RadialPart::Instances => crate::select::handle_cursor(Handle::Bottom, -cx.view_angle()),
RadialPart::Radius => crate::select::handle_cursor(Handle::Right, h.out_angle() - cx.view_angle()),
RadialPart::Splitter => crate::select::handle_cursor(Handle::Right, h.splitter_angle() - cx.view_angle()),
}
}
/// The cursor over a radial repeat's control at `p`, if one is there.
pub fn cursor(cx: &ToolContext, p: Point) -> Option<Cursor> {
let (h, part) = RadialHandles::hit(cx, p)?;
Some(part_cursor(cx, &h, part))
}
/// A drag of one of a radial repeat's controls.
#[derive(Clone, Debug)]
pub struct RadialDrag {
handles: RadialHandles,
part: RadialPart,
start: Point,
/// The options the press found, and the last ones previewed.
from: Value,
last: Option<Value>,
/// For the splitter: its degrees around the ring from the first instance, and the pointer's
/// last direction from the center.
turn: f64,
bearing: Option<f64>,
}
impl RadialDrag {
pub fn hit(cx: &ToolContext, p: Point, mods: Mods) -> Option<Self> {
if mods.cmd || mods.ctrl || mods.alt {
return None;
}
let (handles, part) = RadialHandles::hit(cx, p)?;
let from = handles.options(part, Vec2::ZERO)?;
Some(Self { handles, part, start: p, from, last: None, turn: handles.splitter_turn(), bearing: handles.bearing(p) })
}
/// Whether the drag has changed the repeat (and so previews it).
pub fn adjusting(&self) -> bool {
self.last.is_some()
}
pub fn cursor(&self, cx: &ToolContext) -> Cursor {
part_cursor(cx, &self.handles, self.part)
}
/// The options of the splitter with the pointer at `p`: it follows the pointer around the
/// circle, each move counted by the shorter way round.
fn split(&mut self, p: Point) -> Option<Value> {
let ring = self.handles.ring?;
if let Some(b) = self.handles.bearing(p) {
if let Some(last) = self.bearing {
self.turn += ((b - last + 180.0).rem_euclid(360.0) - 180.0) * ring.step.signum();
}
self.bearing = Some(b);
}
Some(ring.options(ring.shown(self.turn), self.handles.start_angle))
}
/// Preview the options the pointer at `p` gives, when they change; the first change opens
/// the undo step.
pub fn drag(&mut self, p: Point) -> Vec<Action> {
if !finite(p) {
return vec![];
}
let v = match self.part {
RadialPart::Splitter => self.split(p),
part => self.handles.options(part, p - self.start),
};
let Some(v) = v else { return vec![] };
if self.last.as_ref().unwrap_or(&self.from) == &v {
return vec![];
}
let mut out = vec![];
if self.last.is_none() {
out.push(Action::Begin("Repeat Options".into()));
}
out.push(Action::Preview("object.repeat.options".into(), v.clone()));
self.last = Some(v);
out
}
/// Commit the drag; one that ends where it began leaves no undo step.
pub fn finish(self) -> Vec<Action> {
match self.last {
Some(v) if v == self.from => vec![Action::Cancel],
Some(_) => vec![Action::Commit],
None => vec![],
}
}
pub fn cancel(self) -> Vec<Action> {
if self.last.is_some() { vec![Action::Cancel] } else { vec![] }
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::{cx, doc_with_rect, paint};
use std::sync::Arc;
use vectorcraft_doc::pattern::RepeatSpec;
/// [`doc_with_rect`]'s 100 × 100 square at (100, 100) as a radial repeat of eight instances
/// with a radius of 100 pt about (150, 250), selected. The instances span (0, 100)–(300, 400).
fn radial() -> (Document, Selection) {
let (mut doc, id) = doc_with_rect();
let mut source = doc.node(id).unwrap().clone();
source.id = doc.alloc_id();
doc.node_mut(id).unwrap().kind = NodeKind::Repeat(RepeatSpec::radial(vec![Arc::new(source)], 8, Some(100.0)));
let mut selection = Selection::default();
selection.set([id]);
(doc, selection)
}
fn set(doc: &mut Document, selection: &Selection, f: impl FnOnce(&mut u32, &mut f64, &mut f64, &mut f64)) {
let NodeKind::Repeat(spec) = &mut doc.node_mut(selection.objects[0]).unwrap().kind else { panic!("a repeat") };
let RepeatKind::Radial { instances, radius, start_angle, end_angle, .. } = &mut spec.kind else { panic!("a radial repeat") };
f(instances, radius, start_angle, end_angle);
}
fn near(a: Point, b: Point) -> bool {
a.distance(b) < 1e-6
}
fn preview(out: &[Action]) -> Option<&Value> {
out.iter().find_map(|a| match a {
Action::Preview(cmd, v) if cmd == "object.repeat.options" => Some(v),
_ => None,
})
}
/// The point on the 100 pt circle about (150, 250) at `deg` degrees clockwise from straight up.
fn on_circle(deg: f64) -> Point {
let a = deg.to_radians();
Point::new(150.0 + 100.0 * a.sin(), 250.0 - 100.0 * a.cos())
}
/// Apply the `instances` and `endAngle` of a preview to the repeat.
fn apply(doc: &mut Document, selection: &Selection, v: &Value) {
let n = v["instances"].as_u64().unwrap() as u32;
let end = v["endAngle"].as_f64().unwrap();
set(doc, selection, |i, _, _, e| (*i, *e) = (n, end));
}
/// Where the repeat's instances are, in paint order.
fn transforms(doc: &Document, selection: &Selection) -> Vec<Affine> {
let NodeKind::Repeat(spec) = &doc.node(selection.objects[0]).unwrap().kind else { panic!("a repeat") };
spec.transforms(Some(doc))
}
/// Drag the splitter from `from` to `to` degrees clockwise from straight up, 5° a move, and
/// return the last preview.
fn sweep(d: &mut RadialDrag, from: f64, to: f64) -> Option<Value> {
let mut last = None;
let moves = ((to - from).abs() / 5.0).ceil() as i32;
for k in 1..=moves {
if let Some(v) = preview(&d.drag(on_circle(from + (to - from) * f64::from(k) / f64::from(moves)))) {
last = Some(v.clone());
}
}
last
}
#[test]
fn the_handles_sit_below_the_repeat_and_on_its_circle_at_every_zoom() {
let (doc, selection) = radial();
// Halfway between the first instance (straight up from the center) and the second, 45°
// clockwise from it.
let on_circle = on_circle(22.5);
for zoom in [0.02, 1.0, 4.0] {
let h = RadialHandles::of(&doc, &selection, None, zoom).unwrap();
assert!(near(h.instances_at, Point::new(150.0, 400.0 + HANDLE_GAP / zoom)), "{zoom}: {:?}", h.instances_at);
assert!(near(h.radius_at, on_circle), "{zoom}: {:?}", h.radius_at);
assert_eq!((h.center, h.radius), (Point::new(150.0, 250.0), 100.0));
}
// Placed below the bounding box the Selection tool shows.
let frame = OrientedBox::aligned(Rect::new(-10.0, 90.0, 310.0, 410.0));
let h = RadialHandles::of(&doc, &selection, Some(frame), 1.0).unwrap();
assert!(near(h.instances_at, Point::new(150.0, 410.0 + HANDLE_GAP)));
}
#[test]
fn the_radius_handle_follows_the_instances_angles() {
let (mut doc, selection) = radial();
// One instance: opposite it.
set(&mut doc, &selection, |n, _, _, _| *n = 1);
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
assert!(near(h.radius_at, Point::new(150.0, 350.0)), "{:?}", h.radius_at);
// Three instances over a quarter turn from 90°: between those at 90° and 135°.
set(&mut doc, &selection, |n, _, a, b| (*n, *a, *b) = (3, 90.0, 180.0));
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
let a = 112.5_f64.to_radians();
assert!(near(h.radius_at, Point::new(150.0 + 100.0 * a.sin(), 250.0 - 100.0 * a.cos())), "{:?}", h.radius_at);
// A radius of 0: at the center, still apart from the instances handle.
set(&mut doc, &selection, |_, r, _, _| *r = 0.0);
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
assert!(near(h.radius_at, Point::new(150.0, 250.0)));
assert!(h.radius_at.distance(h.instances_at) > 2.0 * REACH);
}
#[test]
fn no_handles_without_a_single_valid_radial_repeat() {
let (mut doc, mut selection) = radial();
for zoom in [0.0, -1.0, f64::NAN, f64::INFINITY] {
assert!(RadialHandles::of(&doc, &selection, None, zoom).is_none(), "{zoom}");
}
let paint = paint();
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
{
let mut c = cx(&doc, &selection, &paint);
assert!(cursor(&c, h.instances_at).is_some());
c.show_bbox = false;
assert!(cursor(&c, h.instances_at).is_none(), "the bounding box is hidden");
}
let id = selection.objects[0];
doc.node_mut(id).unwrap().locked = true;
assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "a locked repeat");
doc.node_mut(id).unwrap().locked = false;
doc.node_mut(id).unwrap().visible = false;
assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "a hidden repeat");
doc.node_mut(id).unwrap().visible = true;
for bad in [f64::NAN, f64::INFINITY] {
set(&mut doc, &selection, |_, r, _, _| *r = bad);
assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "radius {bad}");
set(&mut doc, &selection, |_, r, a, _| (*r, *a) = (100.0, bad));
assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "start angle {bad}");
set(&mut doc, &selection, |_, _, a, _| *a = 0.0);
}
let other = doc.alloc_id();
let mut second = doc.node(id).unwrap().clone();
second.id = other;
let layer = doc.layers[0].id;
doc.insert(Some(layer), 1, second).unwrap();
selection.set([id, other]);
assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "two objects selected");
selection.set([id]);
let NodeKind::Repeat(spec) = &mut doc.node_mut(id).unwrap().kind else { panic!("a repeat") };
spec.kind = RepeatKind::Grid {
h_spacing: 10.0,
v_spacing: 10.0,
rows: 3,
cols: 3,
grid_type: Default::default(),
flip_rows: false,
flip_cols: false,
};
assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "a grid repeat");
}
#[test]
fn dragging_the_instances_handle_steps_the_count() {
let (doc, selection) = radial();
let paint = paint();
let mut c = cx(&doc, &selection, &paint);
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap();
let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap();
assert!(d.drag(h.instances_at + Vec2::new(0.0, 7.0)).is_empty(), "less than half a step changes nothing");
assert!(!d.adjusting());
// Two steps down, a little sideways: ten instances, one undo step.
let out = d.drag(h.instances_at + Vec2::new(5.0, 32.0));
assert!(matches!(out.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{out:?}");
assert_eq!(preview(&out), Some(&json!({"instances": 10})));
assert!(d.drag(h.instances_at + Vec2::new(0.0, 36.0)).is_empty(), "the same count isn't previewed again");
assert!(d.adjusting());
assert!(matches!(d.finish().as_slice(), [Action::Commit]));
// Far up: one instance at least; far down: 1,000 at most.
let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap();
assert_eq!(preview(&d.drag(h.instances_at - Vec2::new(0.0, 900.0))), Some(&json!({"instances": 1})));
assert_eq!(preview(&d.drag(h.instances_at + Vec2::new(0.0, 1e300))), Some(&json!({"instances": 1000})));
assert!(d.drag(Point::new(f64::NAN, 0.0)).is_empty(), "a non-finite pointer");
// Back where it began: no undo step.
assert_eq!(preview(&d.drag(h.instances_at)), Some(&json!({"instances": 8})));
assert!(matches!(d.finish().as_slice(), [Action::Cancel]));
// The step is the same on screen at every zoom: 16 px is a quarter point at 64.
c.zoom = 64.0;
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap();
let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap();
assert_eq!(preview(&d.drag(h.instances_at - Vec2::new(0.0, 0.25))), Some(&json!({"instances": 7})));
assert!(matches!(d.cancel().as_slice(), [Action::Cancel]));
// Alt, Cmd and Ctrl keep the Selection tool's own gestures.
assert!(RadialDrag::hit(&c, h.instances_at, Mods { alt: true, ..Mods::default() }).is_none());
}
#[test]
fn dragging_the_radius_handle_moves_the_circle_in_and_out() {
let (doc, selection) = radial();
let paint = paint();
let c = cx(&doc, &selection, &paint);
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap();
let out = (h.radius_at - h.center) / 100.0;
let across = Vec2::new(-out.y, out.x);
let mut d = RadialDrag::hit(&c, h.radius_at, Mods::default()).unwrap();
// 25 pt out and 40 pt across: only the outward part counts.
let o = d.drag(h.radius_at + out * 25.0 + across * 40.0);
assert!(matches!(o.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{o:?}");
assert_eq!(preview(&o), Some(&json!({"radius": 125.0})));
assert!(d.drag(h.radius_at + across * 30.0).iter().any(|a| matches!(a, Action::Preview(_, v) if v == &json!({"radius": 100.0}))));
// Past the center: a radius of 0.
assert_eq!(preview(&d.drag(h.radius_at - out * 250.0)), Some(&json!({"radius": 0.0})));
// Too far to measure: nothing previewed.
assert!(d.drag(Point::new(f64::MAX, -f64::MAX)).is_empty());
assert!(matches!(d.finish().as_slice(), [Action::Commit]));
// Escape before any change leaves nothing to undo.
let d = RadialDrag::hit(&c, h.radius_at, Mods::default()).unwrap();
assert!(d.cancel().is_empty());
}
#[test]
fn a_bounding_box_handle_wins_where_they_overlap() {
let (doc, selection) = radial();
let paint = paint();
let mut c = cx(&doc, &selection, &paint);
// Zoomed far out (the 300 pt repeat 6 px across), the radius handle lies on a
// bounding-box handle, which keeps its scaling; the instances handle stays clear of the box.
c.zoom = 0.02;
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap();
assert!(crate::select::bbox_handle_at(&c, h.radius_at));
assert!(RadialDrag::hit(&c, h.radius_at, Mods::default()).is_none());
assert!(cursor(&c, h.radius_at).is_none());
assert!(!crate::select::bbox_handle_at(&c, h.instances_at));
assert!(RadialDrag::hit(&c, h.instances_at, Mods::default()).is_some());
// At full size both are the repeat's, with resize cursors along their drags.
c.zoom = 1.0;
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap();
assert!(RadialDrag::hit(&c, h.radius_at, Mods::default()).is_some());
assert_eq!(cursor(&c, h.instances_at), Some(Cursor::ResizeV));
// The radius handle points 22.5° clockwise from straight up: the up-and-down cursor.
assert_eq!(cursor(&c, h.radius_at), Some(Cursor::ResizeV));
}
#[test]
fn the_splitter_sits_half_a_step_past_the_last_instance_shown() {
let (mut doc, selection) = radial();
// A full ring of eight: between the last instance (315°) and the first.
for zoom in [0.02, 1.0, 4.0] {
let h = RadialHandles::of(&doc, &selection, None, zoom).unwrap();
assert!(near(h.splitter_at.unwrap(), on_circle(337.5)), "{zoom}: {:?}", h.splitter_at);
assert!(h.parts().contains(&(RadialPart::Splitter, h.splitter_at.unwrap())));
}
// Five of the eight shown: past the fifth (180°).
set(&mut doc, &selection, |n, _, _, e| (*n, *e) = (5, 180.0));
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
assert!(near(h.splitter_at.unwrap(), on_circle(202.5)), "{:?}", h.splitter_at);
// The instances running the other way from 90°: three of six, the splitter at -60 - 30.
set(&mut doc, &selection, |n, _, a, e| (*n, *a, *e) = (3, 90.0, -30.0));
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
assert!(near(h.splitter_at.unwrap(), on_circle(-60.0)), "{:?}", h.splitter_at);
// One of the eight shown: half a step past it, and the radius handle opposite it.
set(&mut doc, &selection, |n, _, a, e| (*n, *a, *e) = (1, 0.0, 45.0));
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
assert!(near(h.splitter_at.unwrap(), on_circle(22.5)), "{:?}", h.splitter_at);
assert!(near(h.radius_at, on_circle(180.0)), "{:?}", h.radius_at);
}
#[test]
fn no_splitter_where_the_ring_cannot_be_split() {
let (mut doc, selection) = radial();
// A single instance to a full turn, no turn at all, a step that does not divide a full
// turn, and a radius of 0.
for (n, end, r) in [(1, 360.0, 100.0), (2, 0.0, 100.0), (3, 100.0, 100.0), (8, 360.0, 0.0), (8, f64::MAX, 100.0)] {
set(&mut doc, &selection, |i, rad, _, e| (*i, *rad, *e) = (n, r, end));
let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap();
assert_eq!(h.splitter_at, None, "{n} over {end}° at {r}");
assert!(!h.parts().iter().any(|(p, _)| *p == RadialPart::Splitter));
}
// Two instances to a turn can be split.
set(&mut doc, &selection, |i, rad, _, e| (*i, *rad, *e) = (2, 100.0, 360.0));
assert!(RadialHandles::of(&doc, &selection, None, 1.0).unwrap().splitter_at.is_some());
}
#[test]
fn dragging_the_splitter_hides_instances_and_the_others_keep_their_places() {
let (mut doc, selection) = radial();
let full = transforms(&doc, &selection);
assert_eq!(full.len(), 8);
let paint = paint();
let (v, mut d) = {
let c = cx(&doc, &selection, &paint);
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap();
let mut d = RadialDrag::hit(&c, h.splitter_at.unwrap(), Mods::default()).unwrap();
assert!(cursor(&c, h.splitter_at.unwrap()).is_some());
// Back to 320°, short of the last instance: nothing changes.
assert_eq!(sweep(&mut d, 337.5, 320.0), None);
assert!(!d.adjusting());
// Back past the last instance (315°): seven shown, the full ring's step apart.
let out = d.drag(on_circle(300.0));
assert!(matches!(out.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{out:?}");
let v = preview(&out).unwrap().clone();
assert_eq!(v, json!({"instances": 7, "endAngle": 270.0}));
(v, d)
};
apply(&mut doc, &selection, &v);
let seven = transforms(&doc, &selection);
assert_eq!(seven.len(), 7);
for (k, (a, b)) in seven.iter().zip(&full).enumerate() {
assert!(a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| (x - y).abs() < 1e-9), "instance {k} kept its place");
}
// Further back, past 0°: one shown at least.
assert_eq!(sweep(&mut d, 300.0, -200.0), Some(json!({"instances": 1, "endAngle": 45.0})));
// Forward again, past the start of the ring: all eight, a full turn.
assert_eq!(sweep(&mut d, -200.0, 400.0), Some(json!({"instances": 8, "endAngle": 360.0})));
assert!(matches!(d.finish().as_slice(), [Action::Cancel]), "back where it began: no undo step");
// From the seven shown, forward past 315°: the eighth shows again where it was.
let c = cx(&doc, &selection, &paint);
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap();
assert!(near(h.splitter_at.unwrap(), on_circle(292.5)));
let mut d = RadialDrag::hit(&c, h.splitter_at.unwrap(), Mods::default()).unwrap();
let v = sweep(&mut d, 292.5, 330.0).unwrap();
assert_eq!(v, json!({"instances": 8, "endAngle": 360.0}));
assert!(matches!(d.finish().as_slice(), [Action::Commit]));
let mut d = RadialDrag::hit(&c, h.splitter_at.unwrap(), Mods::default()).unwrap();
assert!(d.drag(h.center).is_empty(), "the center gives no direction");
assert_eq!(sweep(&mut d, 292.5, 250.0), Some(json!({"instances": 6, "endAngle": 225.0})));
assert!(matches!(d.cancel().as_slice(), [Action::Cancel]));
apply(&mut doc, &selection, &v);
assert_eq!(transforms(&doc, &selection), full);
}
#[test]
fn the_instances_handle_spreads_a_split_ring_over_the_same_arc() {
let (mut doc, selection) = radial();
// Seven of eight shown: the handle sets the count alone, as for any partial repeat.
set(&mut doc, &selection, |n, _, _, e| (*n, *e) = (7, 270.0));
let paint = paint();
let c = cx(&doc, &selection, &paint);
let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap();
let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap();
assert_eq!(preview(&d.drag(h.instances_at + Vec2::new(0.0, 32.0))), Some(&json!({"instances": 9})));
assert!(matches!(d.finish().as_slice(), [Action::Commit]));
}
}
+38 -2
View File
@@ -147,6 +147,8 @@ enum State {
Mirror(crate::mirror::MirrorDrag),
/// Drag a grid repeat's row, column or corner handle or a spacing slider.
GridRepeat(crate::repeat_grid::GridDrag),
/// Drag a radial repeat's instances or radius handle.
RadialRepeat(crate::repeat_radial::RadialDrag),
/// Dragging a bracket of type on a path.
Bracket(BracketDrag),
/// Dragging a 9-slice guide of the symbol being edited.
@@ -826,6 +828,12 @@ impl Tool for SelectionTool {
{
return d.cancel();
}
if key == ToolKey::Escape
&& matches!(self.state, State::RadialRepeat(_))
&& let State::RadialRepeat(d) = std::mem::take(&mut self.state)
{
return d.cancel();
}
if key == ToolKey::Escape
&& matches!(self.state, State::NineSlice(_))
&& let State::NineSlice(d) = std::mem::take(&mut self.state)
@@ -875,7 +883,7 @@ impl Tool for SelectionTool {
State::Marquee { .. } => key == ToolKey::Letter('e'),
State::Corner(_) => matches!(key, ToolKey::Up | ToolKey::Down),
State::BlendWidget(_) => matches!(key, ToolKey::Up | ToolKey::Down | ToolKey::Left | ToolKey::Right),
State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape,
State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::RadialRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape,
_ => false,
}
}
@@ -917,6 +925,7 @@ impl Tool for SelectionTool {
State::Bracket(b) => b.adjusting(),
State::Mirror(d) => d.adjusting(),
State::GridRepeat(d) => d.adjusting(),
State::RadialRepeat(d) => d.adjusting(),
_ => false,
}
}
@@ -1228,6 +1237,9 @@ impl Tool for SelectionTool {
if let State::GridRepeat(d) = &self.state {
return d.cursor(cx);
}
if let State::RadialRepeat(d) = &self.state {
return d.cursor(cx);
}
if matches!(self.state, State::NineSlice(_)) || (matches!(self.state, State::Idle) && crate::nineslice::over_guide(cx, p)) {
return Cursor::Move;
}
@@ -1235,7 +1247,8 @@ impl Tool for SelectionTool {
&& !m.cmd
&& !m.ctrl
&& !m.alt
&& let Some(cursor) = crate::mirror::cursor(cx, p).or_else(|| crate::repeat_grid::cursor(cx, p))
&& let Some(cursor) =
crate::mirror::cursor(cx, p).or_else(|| crate::repeat_grid::cursor(cx, p)).or_else(|| crate::repeat_radial::cursor(cx, p))
{
return cursor;
}
@@ -1553,6 +1566,21 @@ impl SelectionTool {
_ => return Some(vec![]),
}
}
if let State::RadialRepeat(mut d) = self.state.clone() {
match ev.kind {
PointerKind::Drag | PointerKind::Up => {
let mut out = d.drag(ev.pos);
if ev.kind == PointerKind::Up {
out.extend(d.finish());
self.state = State::Idle;
} else {
self.state = State::RadialRepeat(d);
}
return Some(out);
}
_ => return Some(vec![]),
}
}
if matches!(self.state, State::Idle)
&& ev.kind == PointerKind::Down
&& let Some(d) = crate::mirror::MirrorDrag::hit(cx, ev.pos, ev.mods)
@@ -1569,6 +1597,14 @@ impl SelectionTool {
self.hover = None;
return Some(vec![]);
}
if matches!(self.state, State::Idle)
&& ev.kind == PointerKind::Down
&& let Some(d) = crate::repeat_radial::RadialDrag::hit(cx, ev.pos, ev.mods)
{
self.state = State::RadialRepeat(d);
self.hover = None;
return Some(vec![]);
}
None
}
+88 -2
View File
@@ -9,6 +9,10 @@
//! to Tangent on, a line pressed on one convex curved path and dragged near another lands on a
//! common tangent of the two, both its ends moving to the touch points ([`TangentLine`]).
//! Escape cancels the drag and puts back the options its keys and Ctrl/Cmd changed.
//! Backtick (`` ` ``, the grave accent) held while dragging leaves a copy of the shape being drawn
//! every [`COPY_SPACING`] screen points the pointer travels, up to [`MAX_COPIES`] in one drag; the
//! release keeps the copies and the last shape as one undo step
//! (<https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=469>).
//!
//! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle,
//! Rounded Rectangle, Ellipse, Polygon and Star tools, so a shape just drawn can be adjusted at
@@ -38,6 +42,14 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool
/// value stop there too.
pub const MAX_CORNER_RADIUS: f64 = 1296.0;
/// How far (screen points) the pointer travels with Backtick held between two copies a shape drag
/// leaves: VectorCraft's own spacing.
pub const COPY_SPACING: f64 = 8.0;
/// The most copies one shape drag with Backtick held leaves, besides the shape it ends with:
/// VectorCraft's own limit.
pub const MAX_COPIES: usize = 128;
/// How far (screen points, along each axis) from a bounding-box handle's centre a shape tool's
/// press scales the selection: half the drawn handle square, which is 6 points wide at the default
/// Selection & Anchor Display › Size 3 and a point wider or narrower per step. The Selection tool
@@ -124,6 +136,12 @@ pub struct ShapeTool {
/// The move of the selection snapped to a point, a guide or the grid at its last step: the
/// arrow turns hollow, as the Selection tool's does.
snapped: bool,
/// The copies the drag has left with Backtick held, oldest first: each shape's command and
/// params as the drag showed it when the copy was left.
copies: Vec<(String, Value)>,
/// While Backtick is held in a drag, the pointer position the next copy is measured from: where
/// the last copy was left, or where the drag first had the key down.
copy_from: Option<Point>,
}
/// The options that keys and Ctrl/Cmd change while a shape is dragged out.
@@ -177,9 +195,56 @@ impl ShapeTool {
guides: vec![],
measure: None,
snapped: false,
copies: vec![],
copy_from: None,
}
}
/// With Backtick `held` at pointer `raw`, leave a copy of the shape the drag shows (`cmd` and
/// `params`) once the pointer is [`COPY_SPACING`] screen points from the last copy, or from
/// where the key was first held. A shape with no width, height or length, one the same as the
/// last copy, and any past [`MAX_COPIES`] are not left. Without the key, the next copy is
/// measured from where it goes down again.
fn leave_copy(&mut self, cx: &ToolContext, raw: Point, held: bool, cmd: &str, params: &Value) {
if !held {
self.copy_from = None;
return;
}
let Some(from) = self.copy_from else {
self.copy_from = Some(raw);
return;
};
let (x, y) = screen_offset(cx, raw - from);
if x.hypot(y) < COPY_SPACING || self.copies.len() >= MAX_COPIES || !draws_something(cmd, params) {
return;
}
self.copy_from = Some(raw);
if self.copies.last().is_some_and(|(c, p)| c == cmd && p == params) {
return;
}
self.copies.push((cmd.to_owned(), params.clone()));
}
/// The preview of the shape `cmd` with `params`: with copies left, a `command.batch` that draws
/// them and then the shape, unless it has no size or is the same as the last copy.
fn preview(&self, cmd: String, params: Value) -> Action {
if self.copies.is_empty() {
return Action::Preview(cmd, params);
}
let step = |c: &str, p: &Value| json!({ "command": c, "params": p });
let mut commands: Vec<Value> = self.copies.iter().map(|(c, p)| step(c, p)).collect();
if draws_something(&cmd, &params) && self.copies.last().is_none_or(|(c, p)| *c != cmd || *p != params) {
commands.push(step(&cmd, &params));
}
Action::Preview("command.batch".into(), json!({ "label": self.label(), "commands": commands }))
}
/// Forget the copies of the drag that ended.
fn clear_copies(&mut self) {
self.copies.clear();
self.copy_from = None;
}
fn drag_options(&self) -> DragOptions {
DragOptions { sides: self.sides, points: self.points, corner_radius: self.corner_radius, star_ratio: self.star_ratio }
}
@@ -500,6 +565,19 @@ impl ShapeTool {
}
}
/// Does the shape command `cmd` with `params` draw something: a box with a width and a height, a
/// polygon or star with a radius, a line with a length?
fn draws_something(cmd: &str, params: &Value) -> bool {
let n = |k: &str| params.get(k).and_then(Value::as_f64).unwrap_or(0.0);
match cmd {
// The drag gives a polygon or star a radius of at least 0.01 pt, even on its centre.
"shape.polygon" => n("radius") > 0.01,
"shape.star" => n("radius1") > 0.01,
"shape.line" => (n("x2") - n("x1")).hypot(n("y2") - n("y1")) > 0.0,
_ => n("width").abs() > 0.0 && n("height").abs() > 0.0,
}
}
/// The box a drag from `start` to `p` draws (from its centre with Alt, square with Shift),
/// measured along the page axes turned by Constrain Angle `base`: the box in those axes, and the
/// axes (`None` for the page's own: 0° or a whole turn, where the box is on the page exactly).
@@ -597,6 +675,11 @@ impl Tool for ShapeTool {
self.began = false;
self.inner = None;
self.before_drag = None;
self.clear_copies();
// Backtick already held at the press: the copies are measured from there.
if ev.backquote {
self.copy_from = Some(ev.pos);
}
vec![]
}
PointerKind::Drag => {
@@ -653,7 +736,8 @@ impl Tool for ShapeTool {
};
let (a, b) = tangent.unwrap_or((s, ev.pos));
let (c, v) = self.command_at(a, b, ev.mods, cx.constrain_angle);
out.push(Action::Preview(c, v));
self.leave_copy(cx, raw, ev.backquote, &c, &v);
out.push(self.preview(c, v));
out
}
PointerKind::Up => {
@@ -662,6 +746,7 @@ impl Tool for ShapeTool {
self.tangent_line.clear();
self.inner = None;
self.before_drag = None;
self.clear_copies();
if self.began {
self.began = false;
vec![Action::Commit]
@@ -724,11 +809,12 @@ impl Tool for ShapeTool {
};
if changed {
let (c, v) = self.command_at(s, self.last, self.mods, cx.constrain_angle);
vec![Action::Preview(c, v)]
vec![self.preview(c, v)]
} else if key == ToolKey::Escape {
self.start = None;
self.began = false;
self.inner = None;
self.clear_copies();
if let Some(o) = self.before_drag.take() {
self.restore_drag_options(o);
}
+182
View File
@@ -1372,3 +1372,185 @@ fn a_move_from_the_centre_point_snaps_and_shows_the_hollow_arrow() {
assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["matrix"][4] == json!(10.0)), "{a:?}");
assert_eq!(t.cursor(&c, Point::new(160.0, 150.0), Mods::default()), Cursor::Arrow);
}
/// A drag event to `(x, y)` with Backtick held or not.
fn quote_drag(x: f64, y: f64, held: bool) -> PointerEvent {
PointerEvent { backquote: held, ..PointerEvent::new(PointerKind::Drag, x, y) }
}
/// The shapes the last preview in `a` draws, as their commands and params: the steps of a
/// `command.batch`, or the one shape. The bool says whether it was a batch.
fn previewed_shapes(a: &[Action]) -> (bool, Vec<(String, Value)>) {
match a.last() {
Some(Action::Preview(c, v)) if c == "command.batch" => {
assert!(v.get("commands").and_then(Value::as_array).is_some(), "{v}");
let steps = v["commands"].as_array().into_iter().flatten();
(true, steps.map(|s| (s["command"].as_str().unwrap_or_default().to_owned(), s["params"].clone())).collect())
}
Some(Action::Preview(c, v)) => (false, vec![(c.clone(), v.clone())]),
_ => panic!("no preview: {a:?}"),
}
}
/// The widths of the rectangles the last preview in `a` draws, and whether it was a batch.
fn previewed_widths(a: &[Action]) -> (bool, Vec<f64>) {
let (batch, shapes) = previewed_shapes(a);
(batch, shapes.iter().map(|(_, p)| p["width"].as_f64().unwrap_or(f64::NAN)).collect())
}
/// Backtick held while a rectangle is dragged out leaves a copy every 8 screen points the pointer
/// travels from where the key was first held or the last copy was left; the shape being drawn
/// still follows the pointer. A key press without pointer travel leaves none, letting go stops
/// the copies and keeps those left, and pressing it again starts measuring afresh. The release
/// commits once.
#[test]
fn backtick_drag_leaves_copies_of_the_rectangle_being_drawn() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(50.0, 30.0, false))), (false, vec![40.0]));
// The key goes down with the pointer still: no copy.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(50.0, 30.0, true))), (false, vec![40.0]));
// 4 pt of travel is short of the spacing.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(54.0, 30.0, true))), (false, vec![44.0]));
// 10 pt: a copy, the same as the shape shown, so the batch draws it once.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(60.0, 30.0, true))), (true, vec![50.0]));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(70.0, 30.0, true))), (true, vec![50.0, 60.0]));
// 5 pt past the last copy: none left, and the live shape follows.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(75.0, 30.0, true))), (true, vec![50.0, 60.0, 65.0]));
// Let go of the key: the copies stay and no more are left.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(90.0, 30.0, false))), (true, vec![50.0, 60.0, 80.0]));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(120.0, 30.0, false))), (true, vec![50.0, 60.0, 110.0]));
// Pressed again: measured from where it went down.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(125.0, 30.0, true))), (true, vec![50.0, 60.0, 115.0]));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(135.0, 30.0, true))), (true, vec![50.0, 60.0, 125.0]));
assert_eq!(t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Up, 135.0, 30.0) }), vec![Action::Commit]);
// The next drag starts with no copies.
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(50.0, 30.0, false))), (false, vec![40.0]));
}
/// Backtick already held at the press measures the first copy from the pressed spot: the first
/// drag 10 pt away leaves one, and 5 pt more leaves none.
#[test]
fn backtick_held_at_the_press_measures_copies_from_there() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Down, 0.0, 0.0) });
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(10.0, 10.0, true))), (true, vec![10.0]));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(15.0, 10.0, true))), (true, vec![10.0, 15.0]));
assert_eq!(t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Up, 15.0, 10.0) }), vec![Action::Commit]);
}
/// Every shape tool leaves copies of its own shape, drawn with the modifiers held when each copy
/// was left: Shift's square stays square, and Alt's from the centre stays centred.
#[test]
fn backtick_drag_leaves_copies_with_every_shape_tool_and_its_modifiers() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
for (id, cmd) in [
("rectangle", "shape.rectangle"),
("roundedRectangle", "shape.rectangle"),
("ellipse", "shape.ellipse"),
("polygon", "shape.polygon"),
("star", "shape.star"),
("lineSegment", "shape.line"),
] {
let mut t = ShapeTool::new(id);
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
t.pointer(&c, &quote_drag(140.0, 130.0, true));
t.pointer(&c, &quote_drag(160.0, 130.0, true));
let (batch, shapes) = previewed_shapes(&t.pointer(&c, &quote_drag(180.0, 140.0, true)));
assert!(batch, "{id}");
assert_eq!(shapes.len(), 2, "{id}: two copies, the second the shape shown: {shapes:?}");
assert!(shapes.iter().all(|(c, _)| c == cmd), "{id}: {shapes:?}");
assert_ne!(shapes[0].1, shapes[1].1, "{id}: each copy as the drag showed it then");
}
// Shift and Alt: each copy is the square drawn from the centre at that moment.
let shift_alt = Mods { shift: true, alt: true, ..Default::default() };
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
t.pointer(&c, &quote_drag(130.0, 120.0, true).with_mods(shift_alt));
let (_, shapes) = previewed_shapes(&t.pointer(&c, &quote_drag(150.0, 120.0, true).with_mods(shift_alt)));
let (_, r) = &shapes[0];
assert_eq!(r["width"], r["height"], "square: {r}");
assert_eq!(r["x"].as_f64().unwrap_or_default() + r["width"].as_f64().unwrap_or_default() / 2.0, 100.0, "centred: {r}");
}
/// ↑ during a polygon drag with copies left changes only the shape being drawn; Escape cancels
/// the copies with it, and the next drag starts without them.
#[test]
fn backtick_copies_keep_their_sides_and_escape_cancels_them() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ShapeTool::new("polygon");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
t.pointer(&c, &quote_drag(140.0, 100.0, true));
t.pointer(&c, &quote_drag(150.0, 100.0, true));
let (batch, shapes) = previewed_shapes(&t.key(&c, ToolKey::Up, Mods::default()));
assert!(batch);
let sides: Vec<_> = shapes.iter().map(|(_, p)| p["sides"].clone()).collect();
assert_eq!(sides, vec![json!(6), json!(7)], "the copy keeps its sides");
assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
let (batch, _) = previewed_shapes(&t.pointer(&c, &quote_drag(140.0, 100.0, false)));
assert!(!batch, "no copies after Escape");
}
/// No copy is left of a shape without a height or a length, and one drag leaves at most
/// [`MAX_COPIES`] copies while the shape being drawn still follows the pointer.
#[test]
fn backtick_copies_skip_empty_shapes_and_stop_at_the_limit() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
// A rectangle with no height: nothing is left.
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
for x in [30.0, 40.0, 50.0, 60.0] {
assert!(!previewed_shapes(&t.pointer(&c, &quote_drag(x, 10.0, true))).0, "{x}");
}
// A line back on its start: no copy there.
let mut t = ShapeTool::new("lineSegment");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
t.pointer(&c, &quote_drag(30.0, 10.0, true));
assert!(!previewed_shapes(&t.pointer(&c, &quote_drag(10.0, 10.0, true))).0);
// The limit.
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 0.0, 0.0));
t.pointer(&c, &quote_drag(10.0, 10.0, true));
let mut last = vec![];
for i in 1..=(MAX_COPIES as u32 + 20) {
let at = 10.0 + f64::from(i) * 10.0;
last = t.pointer(&c, &quote_drag(at, at, true));
}
let (batch, widths) = previewed_widths(&last);
assert!(batch);
assert_eq!(widths.len(), MAX_COPIES + 1, "the copies and the shape being drawn");
assert_eq!(widths.last(), Some(&(10.0 + f64::from(MAX_COPIES as u32 + 20) * 10.0)), "the shape follows the pointer");
}
/// The spacing is measured on screen: at 400% zoom, 2 pt of travel is 8 screen points.
#[test]
fn backtick_copy_spacing_is_measured_on_screen() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, zoom: 4.0, ..cx(&d, &s, &p) };
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
t.pointer(&c, &quote_drag(20.0, 20.0, true));
assert!(!previewed_shapes(&t.pointer(&c, &quote_drag(21.5, 20.0, true))).0, "6 screen points");
assert!(previewed_shapes(&t.pointer(&c, &quote_drag(22.0, 20.0, true))).0, "8 screen points");
}
+194
View File
@@ -966,6 +966,168 @@ fn a_gray_between_black_and_white_is_one_shape() {
}
}
/// Flat Logo with the black of the tests below, `gray` and white named exactly.
fn black_gray_white(gray: [u8; 3]) -> TraceParams {
let logo_colors = vec!["#040403".into(), format!("#{:02X}{:02X}{:02X}", gray[0], gray[1], gray[2]), "#FFFFFF".into()];
TraceParams { logo_colors, ..logo_params() }
}
/// A black disc and a gray square on white, blurred by 1 to 3 pixels: the edge pixels around the
/// disc as light as the gray read as blends of black and white, so the gray is one shape (the
/// square) and no gray lines the disc, with the colors found or named. At a blur of 3 pixels, with
/// the colors named, a gray of 128 is still one shape, a gray of 200 leaves 4 slivers of no area,
/// and a light gray (230) leaves at most 8 slivers, touching the disc's edge at no more than 4 of
/// 192 samples. (Without named colors, an image blurred by 3 pixels traces without its gray.)
#[test]
fn blurred_black_edges_beside_gray_leave_no_gray_slivers() {
const INK: [u8; 3] = [4, 4, 3];
for gray in [[230u8, 230, 230], [200, 200, 200], [128, 128, 128]] {
for blur in [1.0, 1.5, 2.0, 3.0] {
let img = render(120, 60, blur, |x, y| {
Some(if (x - 30.0).hypot(y - 30.0) <= 20.0 {
INK
} else if (60.0..=110.0).contains(&x) && (10.0..=50.0).contains(&y) {
gray
} else {
WHITE
})
});
for by_name in [false, true] {
if !by_name && blur > 2.0 {
continue;
}
let res = trace(&img, &if by_name { black_gray_white(gray) } else { logo_params() });
let what = format!("gray {}, blur {blur}, named {by_name}", gray[0]);
let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect();
assert_eq!(top_color(&res, Point::new(85.0, 30.0)), Some(gray), "{what}: the square; {paths:?}");
let mut rim = 0;
for r in [19.0, 20.0, 21.0] {
for k in 0..64 {
let a = f64::from(k) * std::f64::consts::TAU / 64.0;
if top_color(&res, Point::new(30.0 + r * a.cos(), 30.0 + r * a.sin())) == Some(gray) {
rim += 1;
}
}
}
let mut grays: Vec<_> = res.paths.iter().filter(|t| t.color == gray).map(|t| t.pixels).collect();
grays.sort_unstable();
grays.pop();
match (gray[0], blur == 3.0) {
(230, true) => {
assert!(grays.len() <= 8, "{what}: {} slivers; {paths:?}", grays.len());
assert!(rim <= 4, "{what}: {rim} of 192 samples along the disc's edge traced gray");
}
(200, true) => {
assert!(grays.len() <= 4 && grays.iter().all(|&n| n == 0), "{what}: slivers {grays:?}");
assert_eq!(rim, 0, "{what}: samples along the disc's edge traced gray");
}
_ => {
assert!(grays.is_empty(), "{what}: slivers {grays:?}; {paths:?}");
assert_eq!(rim, 0, "{what}: samples along the disc's edge traced gray");
}
}
}
}
}
}
/// A soft-edged gray band 2 to 4 pixels wide lying along a black disc, blurred by 1.5 or 2 pixels,
/// traces as black and white: its pixels are reached from the disc and from the white through
/// pixels that keep getting darker and lighter, as across a blurred black-to-white edge. A band 8
/// pixels wide keeps at least half of its gray. With sharp edges every band stays gray.
#[test]
fn a_soft_gray_band_along_black_traces_as_black_and_white() {
const INK: [u8; 3] = [4, 4, 3];
for gray in [[230u8, 230, 230], [200, 200, 200], [128, 128, 128]] {
for blur in [0.0, 1.5, 2.0] {
for wide in [2u8, 3, 4, 8] {
let img = render(120, 60, blur, |x, y| {
Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 {
INK
} else if (40.0..43.0 + f64::from(wide)).contains(&x) && (20.0..36.0).contains(&y) {
gray
} else {
WHITE
})
});
let res = trace(&img, &black_gray_white(gray));
// The band's samples: 16 rows of its `wide` columns outside the disc.
let kept = (0..wide)
.flat_map(|c| (20..36).map(move |y| Point::new(43.5 + f64::from(c), f64::from(y) + 0.5)))
.filter(|&at| top_color(&res, at) == Some(gray))
.count();
let all = 16 * usize::from(wide);
let what = format!("gray {}, blur {blur}, {wide} px band: {kept} of {all} samples traced gray", gray[0]);
if blur == 0.0 {
assert_eq!(kept, all, "{what}");
} else if wide <= 4 {
assert_eq!(kept, 0, "{what}");
} else {
assert!(2 * kept >= all, "{what}");
}
}
}
}
}
/// A soft-edged gray spoke two or three pixels wide running straight out of a black disc, blurred
/// by 1 or 1.5 pixels, loses 3 or 4 of its 16 samples nearest the disc and keeps the rest.
#[test]
fn a_soft_gray_spoke_loses_a_few_pixels_where_it_meets_black() {
const INK: [u8; 3] = [4, 4, 3];
for gray in [[230u8, 230, 230], [128, 128, 128]] {
for blur in [1.0, 1.5] {
for wide in [2.0, 3.0] {
let img = render(120, 60, blur, |x, y| {
Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 {
INK
} else if (38.0..90.0).contains(&x) && (27.0..27.0 + wide).contains(&y) {
gray
} else {
WHITE
})
});
let res = trace(&img, &black_gray_white(gray));
let at = |x: i32| Point::new(f64::from(x) + 0.5, 27.0 + wide / 2.0);
let near = (44..60).filter(|&x| top_color(&res, at(x)) == Some(gray)).count();
let far = (60..86).filter(|&x| top_color(&res, at(x)) == Some(gray)).count();
let what = format!("gray {}, blur {blur}, {wide} px spoke", gray[0]);
assert!((12..=13).contains(&near), "{what}: {near} of the 16 samples nearest the disc traced gray");
assert_eq!(far, 26, "{what}: the rest of the spoke");
}
}
}
}
/// A soft-edged light gray stroke 2 pixels wide beside a black disc, blurred by 1.5 pixels: 2
/// pixels from the disc it keeps less than half of its gray, 4 pixels away it loses a few pixels,
/// and 6 or 8 pixels away it keeps all of it.
#[test]
fn a_soft_gray_stroke_near_black_loses_gray_by_its_distance() {
const INK: [u8; 3] = [4, 4, 3];
const GRAY: [u8; 3] = [230, 230, 230];
for gap in [2, 4, 6, 8] {
let x0 = 43.0 + f64::from(gap);
let img = render(120, 60, 1.5, |x, y| {
Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 {
INK
} else if (x0..x0 + 2.0).contains(&x) && (8.0..50.0).contains(&y) {
GRAY
} else {
WHITE
})
});
let res = trace(&img, &black_gray_white(GRAY));
let kept = (12..46).filter(|&y| top_color(&res, Point::new(x0 + 1.0, f64::from(y) + 0.5)) == Some(GRAY)).count();
let what = format!("{gap} px from the disc: {kept} of 34 samples traced gray");
match gap {
2 => assert!(2 * kept < 34, "{what}"),
4 => assert!((24..34).contains(&kept), "{what}"),
_ => assert_eq!(kept, 34, "{what}"),
}
}
}
/// A one-pixel gray line between flat black and flat white, with the three colors named, stays a
/// gray line along its whole length, beside a black disc whose edge pixels are as light as the gray.
#[test]
@@ -1158,3 +1320,35 @@ fn a_noisy_hard_edged_gray_between_black_and_white_is_one_shape() {
}
}
}
#[test]
fn a_disc_on_a_gray_panel_on_a_paler_ground_has_no_slivers_of_the_ground() {
// The panel's gray lies on the line from the ground's gray to the disc's charcoal, so the disc's
// edge pixels are also a mix of the ground and the disc.
let (ground, panel, disc) = ([240, 240, 240], [200, 200, 200], [60, 60, 60]);
for blur in [0.0, 0.7] {
let grays = render(150, 150, blur, move |x, y| {
let (cx, cy) = (x.clamp(35.0, 115.0), y.clamp(35.0, 115.0));
Some(if (x - 75.0).hypot(y - 75.0) < 30.0 {
disc
} else if (20.0..130.0).contains(&x) && (20.0..130.0).contains(&y) && (x - cx).hypot(y - cy) < 15.0 {
panel
} else {
ground
})
});
for named in [false, true] {
let logo_colors = if named { vec!["#F0F0F0".into(), "#C8C8C8".into(), "#3C3C3C".into()] } else { Vec::new() };
let res = trace(&grays, &TraceParams { logo_colors, ..logo_params() });
let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect();
assert_eq!(res.paths.len(), 3, "blur {blur}, named {named}: one path per color; {paths:?}");
for k in 0..16 {
let a = f64::from(k) * std::f64::consts::TAU / 16.0;
let at = Point::new(75.0 + 31.0 * a.cos(), 75.0 + 31.0 * a.sin());
assert_eq!(top_color(&res, at), Some(panel), "blur {blur}, named {named}: beside the disc at {at:?}");
}
assert_eq!(top_color(&res, Point::new(8.0, 75.0)), Some(ground), "blur {blur}, named {named}: the ground");
assert_eq!(top_color(&res, Point::new(75.0, 75.0)), Some(disc), "blur {blur}, named {named}: the disc");
}
}
}
+217 -31
View File
@@ -5,8 +5,10 @@
//! runs, so each pixel is instead explained as a mix of at most three classes, whichever mix
//! reproduces the pixel best. When another mix also reproduces it (with a gray between black and
//! white among the classes, a black-to-white edge pixel is a mix of black and gray as well as of
//! black and white), the pixel takes the mix whose classes lie nearest it in the flat areas around it,
//! when its neighbors show an edge between those classes.
//! black and white, and a gray-to-black edge pixel is a mix of white and black as well as of gray
//! and black), the pixel takes the mix whose classes lie nearest it in the flat areas around it,
//! or, on an edge blurred over several pixels, along the pixels that lead across the edge, when its
//! neighbors show an edge between those classes.
use std::collections::{HashMap, HashSet};
@@ -21,6 +23,8 @@ const PURE: f64 = 4.0 / 255.0;
const REPRODUCES: f64 = PURE * PURE;
/// How far (in pixels, each way) a class is looked for around a pixel that two mixes reproduce.
const NEARBY: usize = 6;
/// How many steps a path across an edge takes at most ([`across_edge`]).
const WALK: usize = 5;
/// A pixel whose neighbors are all this close to it (in 0..1 premultiplied RGBA) lies in a flat area.
const FLAT: f64 = 1.5 / 255.0;
/// How many joined pixels within [`PURE`] of one class are taken as art of that class, such as a
@@ -199,9 +203,11 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
if tied.is_empty() {
return (planes, residual, switched);
}
// A pixel two mixes reproduce takes another mix of two classes whose farthest class lies nearer
// it than the best mix's does, in the flat areas around it ([`flat_classes`], [`RowDistances::around`]),
// when the pixel lies on an edge between that mix's classes ([`across_edge`]). For the best mix,
// A pixel two mixes reproduce takes another mix of two classes, when the pixel lies on an edge
// between that mix's classes ([`across_edge`]) and that mix lies nearer it than the best mix
// does. A mix lies as near as its farthest class in the flat areas around the pixel
// ([`flat_classes`], [`RowDistances::around`]); the other mix lies as near as the steps that
// `across_edge` counts when those are fewer. For the best mix,
// the classes held by flat areas between two classes count as well ([`between_classes`]). A
// pixel within `PURE` of a class that is joined to at least [`LINE`] such pixels of that class
// (itself included) keeps it ([`pure_runs`]), as a one-pixel line of gray between black and white.
@@ -217,7 +223,11 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
continue;
}
let Some(mixes) = mixed.get(&key) else { continue };
let edges: Vec<&Weights> = mixes.tied.iter().filter(|m| across_edge(pix, width, height, i, classes, &mixes.best, m)).collect();
let edges: Vec<(&Weights, usize)> = mixes
.tied
.iter()
.filter_map(|m| across_edge(pix, (&flat, &stands_for), (width, height), i, classes, &mixes.best, m).map(|r| (m, r)))
.collect();
if edges.is_empty() {
continue;
}
@@ -230,8 +240,8 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
}
}
let now = farthest(&mixes.best, &kept);
let other = edges.into_iter().filter(|m| farthest(m, &dist) < now).min_by_key(|m| farthest(m, &dist));
if let Some(other) = other {
let other = edges.into_iter().map(|(m, r)| (m, farthest(m, &dist).min(r))).filter(|&(_, d)| d < now).min_by_key(|&(_, d)| d);
if let Some((other, _)) = other {
switched.push((i, planes.iter().map(|pl| pl.get(i).copied().unwrap_or(0.0)).collect()));
// (`residual` keeps the best mix's error; the mix taken comes within `REPRODUCES` of the
// pixel as well.)
@@ -243,17 +253,39 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
}
/// Whether pixel `i` lies on an edge between the two classes of `other`, rather than in an area of
/// a class of `best` that `other` leaves out: for each such class, the pixel has a neighbor beyond
/// it toward each class of `other`, along the line between them. (A black-to-white edge pixel as
/// light as a gray has a darker neighbor and a lighter one; a gray stroke on white has no neighbor
/// darker than the gray.)
fn across_edge(pix: &[Px], width: usize, height: usize, i: usize, classes: &[[f64; 4]], best: &Weights, other: &Weights) -> bool {
let [(a, _), (b, _)] = other.as_slice() else { return false };
let (Some(ca), Some(cb)) = (classes.get(*a), classes.get(*b)) else { return false };
/// a class of `best` that `other` leaves out. For a class left out that lies between the classes of
/// `other` on the line between them, a path of pixels from `i` that keeps going toward one class of
/// `other` gets past the class left out within [`WALK`] steps through the eight neighbors, and so
/// does one that keeps going toward the other. For a class left out that lies beyond both classes of
/// `other` on that line, the pixel has a neighbor on each side of that class, or a neighbor on each
/// side of the pixel itself, none past the class of `other` nearer the class left out, and a chain
/// of neighbors from the pixel to that nearer class or a flat area of it (`flat`), each nearer it
/// than the one before. (A black-to-white edge pixel as light as a gray has a darker neighbor and a
/// lighter one, or, on an edge blurred over several pixels, reaches darker and lighter pixels through
/// pixels that keep getting darker or lighter; from a gray stroke on white, a path that keeps getting
/// darker ends in the stroke, at the gray; a gray-to-black edge pixel has a lighter neighbor and a
/// darker one, and lighter pixels lead to the flat gray; a pale line one pixel wide on black has only
/// darker neighbors; the pixels beside a blurred pale line's middle reach no flat gray; and a white
/// gap between black and gray has a neighbor lighter than the gray.)
///
/// When it does, the number of steps the longer of the two paths takes to a pixel that stands for its
/// class of `other` (`stands_for`), the largest over the classes left out. It is `NEARBY + 1` when a
/// path does not come to such a pixel, and when a class left out lies beyond both classes of `other`.
fn across_edge(
pix: &[Px],
(flat, stands_for): (&[Option<usize>], &[Option<usize>]),
(width, height): (usize, usize),
i: usize,
classes: &[[f64; 4]],
best: &Weights,
other: &Weights,
) -> Option<usize> {
let [(a, _), (b, _)] = other.as_slice() else { return None };
let (ca, cb) = (classes.get(*a)?, classes.get(*b)?);
let ab: [f64; 4] = std::array::from_fn(|j| cb[j] - ca[j]);
let len2: f64 = ab.iter().map(|v| v * v).sum();
if len2 <= 1e-12 {
return false;
return None;
}
let len = len2.sqrt();
// Where `v` lies along the line from `a` to `b` (0 at `a`, 1 at `b`), and how far off it.
@@ -262,22 +294,102 @@ fn across_edge(pix: &[Px], width: usize, height: usize, i: usize, classes: &[[f6
let off = (0..4).map(|j| (v[j] - ca[j] - t * ab[j]).powi(2)).sum::<f64>().sqrt();
(t, off)
};
let (x, y) = (i % width.max(1), i / width.max(1));
let neighbors: Vec<f64> = (y.saturating_sub(1)..(y + 2).min(height))
.flat_map(|yy| (x.saturating_sub(1)..(x + 2).min(width)).map(move |xx| yy * width + xx))
.filter(|&j| j != i)
.filter_map(|j| pix.get(j))
.map(|q| place([f64::from(q[0]), f64::from(q[1]), f64::from(q[2]), f64::from(q[3])]))
.filter(|&(_, off)| off <= 2.0 * PURE)
.map(|(t, _)| t)
.collect();
// Where pixel `j` lies along the line, when it lies within `2 * PURE` of it.
let at = |j: usize| {
pix.get(j)
.map(|q| place([f64::from(q[0]), f64::from(q[1]), f64::from(q[2]), f64::from(q[3])]))
.filter(|&(_, off)| off <= 2.0 * PURE)
.map(|(t, _)| t)
};
// The pixels around pixel `j`.
let around = |j: usize| {
let (x, y) = (j % width.max(1), j / width.max(1));
(y.saturating_sub(1)..(y + 2).min(height))
.flat_map(move |yy| (x.saturating_sub(1)..(x + 2).min(width)).map(move |xx| yy * width + xx))
.filter(move |&n| n != j)
};
let neighbors: Vec<f64> = around(i).filter_map(at).collect();
let left_out: Vec<usize> = best.iter().filter(|&&(c, w)| w > 0.0 && c != *a && c != *b).map(|&(c, _)| c).collect();
!left_out.is_empty()
&& left_out.iter().all(|&c| {
let Some(&cv) = classes.get(c) else { return false };
let (tc, _) = place(cv);
neighbors.iter().any(|&t| (tc - t) * len > PURE) && neighbors.iter().any(|&t| (t - tc) * len > PURE)
})
// Whether the pixel has a neighbor on each side of place `t` along the line.
let straddled = |t: f64| neighbors.iter().any(|&tn| (t - tn) * len > PURE) && neighbors.iter().any(|&tn| (tn - t) * len > PURE);
// Whether pixel `j`, at place `t`, lies within `PURE` of class `c` (at place `to`), or in a flat
// area of class `c` ([`flat_classes`]), or beside one and within `PURE` of its color along the
// line (as when `c` is named some levels off the area's color).
let touches = |j: usize, t: f64, c: usize, to: f64| {
let in_c = |n: usize| flat.get(n).copied().flatten() == Some(c);
(t - to).abs() * len <= PURE || in_c(j) || around(j).any(|n| in_c(n) && at(n).is_some_and(|tn| (tn - t).abs() * len <= PURE))
};
// Whether a chain of neighbors from the pixel, each nearer place `to` than the one before and
// none past it (`past`), comes to class `c` ([`touches`]) in at most `NEARBY` steps. (From a
// pixel beside a pale line's middle, the middle is the only neighbor nearer the gray, and it has
// none, and it is far from the gray.)
let reaches = |to: f64, c: usize, past: &dyn Fn(f64) -> bool| {
let Some(t) = at(i) else { return false };
let mut front = vec![(i, t)];
let mut seen = HashSet::from([i]);
for step in 0..=NEARBY {
let mut next = Vec::new();
for &(j, t) in &front {
if touches(j, t, c, to) {
return true;
}
if step < NEARBY {
for n in around(j) {
if let Some(tn) = at(n).filter(|&tn| !past(tn) && (tn - to).abs() < (t - to).abs())
&& seen.insert(n)
{
next.push((n, tn));
}
}
}
}
if next.is_empty() {
return false;
}
front = next;
}
false
};
// A path from `i` toward `a` (`toward` -1) or `b` (`toward` 1): each step goes to the neighbor
// near the line that lies farthest that way, while it lies farther than the pixel before (the
// first step is taken whatever `i` itself is). `None` when it does not get more than `PURE` past
// `tc` in [`WALK`] steps; otherwise the steps to the first pixel past it that stands for `class`
// (`stands_for`), or `NEARBY + 1`.
let walk = |toward: f64, tc: f64, class: usize| {
let (mut cur, mut t) = (i, f64::NEG_INFINITY * toward);
let mut past = false;
for step in 1..=WALK {
match around(cur).filter_map(|j| at(j).map(|tj| (j, tj))).max_by(|p, q| (p.1 * toward).total_cmp(&(q.1 * toward))) {
Some((j, tj)) if (tj - t) * toward > 0.0 => (cur, t) = (j, tj),
_ => break,
}
past = past || (t - tc) * toward * len > PURE;
if past && stands_for.get(cur).copied().flatten() == Some(class) {
return Some(step);
}
}
past.then_some(NEARBY + 1)
};
if left_out.is_empty() {
return None;
}
let mut reach = 0;
for &c in &left_out {
let (tc, _) = place(*classes.get(c)?);
if (0.0..=1.0).contains(&tc) {
let ra = walk(-1.0, tc, *a)?;
let rb = walk(1.0, tc, *b)?;
reach = reach.max(ra.max(rb));
continue;
}
let beyond = |tn: f64| if tc < 0.0 { -tn * len > PURE } else { (tn - 1.0) * len > PURE };
let (to, near) = if tc < 0.0 { (0.0, *a) } else { (1.0, *b) };
if !(straddled(tc) || !neighbors.iter().any(|&tn| beyond(tn)) && at(i).is_some_and(straddled) && reaches(to, near, &beyond)) {
return None;
}
reach = NEARBY + 1;
}
Some(reach)
}
/// How far the farthest class of `mix` lies, by the distances `dist` ([`RowDistances::around`]).
@@ -670,6 +782,80 @@ mod tests {
}
}
#[test]
fn an_edge_pixel_takes_no_class_beyond_both_classes_beside_it() {
// A pale ground, a gray and a charcoal on one line: a row of flat gray, one edge pixel halfway
// to charcoal, flat charcoal. The edge pixel is a mix of the gray and the charcoal, with none
// of the ground in it.
let g = |v: f64| [v / 255.0, v / 255.0, v / 255.0, 1.0];
let classes = vec![g(240.0), g(200.0), g(60.0), [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]];
let px = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0];
let mut pix = vec![px(200.0); 5];
pix.push(px(130.0));
pix.extend([px(60.0); 5]);
let (pl, _, _) = unmix(&pix, 11, 1, &classes);
assert_eq!(pl[0][5], 0.0, "ground in the edge pixel");
assert!((pl[1][5] - 0.5).abs() < 0.02 && (pl[2][5] - 0.5).abs() < 0.02, "gray {} charcoal {}", pl[1][5], pl[2][5]);
// The cases below are vertical lines: three rows alike, read in the middle row.
// The same edge with the panel's pixels three levels darker than the named gray.
let mut pix = vec![px(197.0); 5];
pix.push(px(130.0));
pix.extend([px(60.0); 5]);
let (pl, _, _) = unmix(&pix.repeat(3), 11, 3, &classes);
assert_eq!(pl[0][11 + 5], 0.0, "ground in the edge pixel beside a gray three levels off");
// An edge pixel whose lightest neighbor leads nowhere, with another chain of lighter pixels
// to the gray.
let outer = [vec![px(200.0); 5], vec![px(170.0)], vec![px(60.0); 7]].concat();
let middle = [vec![px(200.0); 5], vec![px(170.0), px(130.0), px(180.0)], vec![px(60.0); 5]].concat();
let (pl, _, _) = unmix(&[outer.clone(), middle, outer].concat(), 13, 3, &classes);
assert_eq!(pl[0][13 + 6], 0.0, "ground in the edge pixel beside a dead end");
// A pixel half ground and half charcoal between charcoal pixels, flat gray three pixels off:
// a thin pale line on the charcoal, kept.
let mut pix = vec![px(200.0); 3];
pix.extend([px(60.0); 2]);
pix.push(px(150.0));
pix.extend([px(60.0); 5]);
let (pl, _, _) = unmix(&pix.repeat(3), 11, 3, &classes);
assert!((pl[0][11 + 5] - 0.5).abs() < 0.02, "the line: ground {}", pl[0][11 + 5]);
// A gap of the ground's color one pixel wide between flat charcoal and flat gray: the pixel
// half charcoal and half ground beside it keeps its ground.
let mut pix = vec![px(60.0); 5];
pix.extend([px(150.0), px(236.0)]);
pix.extend([px(200.0); 5]);
let (pl, _, _) = unmix(&pix.repeat(3), 12, 3, &classes);
assert!((pl[0][12 + 5] - 0.5).abs() < 0.02, "the gap: ground {}", pl[0][12 + 5]);
// A pale line blurred over three pixels on the charcoal, flat gray five pixels off: the pixels
// beside its middle have a lighter neighbor and a darker one, and keep their ground.
let mut pix = vec![px(200.0); 5];
pix.extend([px(60.0); 3]);
pix.extend([px(103.0), px(154.0), px(103.0)]);
pix.extend([px(60.0); 9]);
let (pl, _, _) = unmix(&pix.repeat(3), 20, 3, &classes);
for j in [20 + 8, 20 + 10] {
assert!((pl[0][j] - 43.0 / 180.0).abs() < 0.02 && pl[1][j] == 0.0, "the blurred line at {j}: ground {} gray {}", pl[0][j], pl[1][j]);
}
// A pale line one pixel wide that falls between two pixels, covering half of one and three
// quarters of the other: both pixels keep their ground.
let mut pix = vec![px(200.0); 5];
pix.extend([px(60.0); 3]);
pix.extend([px(150.0), px(195.0)]);
pix.extend([px(60.0); 10]);
let (pl, _, _) = unmix(&pix.repeat(3), 20, 3, &classes);
for (j, want) in [(20 + 8, 0.5), (20 + 9, 0.75)] {
let (ground, gray) = (pl[0][j], pl[1][j]);
assert!((ground - want).abs() < 0.02 && gray == 0.0, "the line between pixels at {j}: ground {ground} gray {gray}");
}
// An edge from the gray to the charcoal blurred by 0.7 pixel: the pixels between take no
// ground.
let mut pix = vec![px(200.0); 5];
pix.extend([px(199.97), px(197.8), px(166.7), px(93.3), px(62.2)]);
pix.extend([px(60.0); 5]);
let (pl, _, _) = unmix(&pix.repeat(3), 15, 3, &classes);
for j in [15 + 7, 15 + 8] {
assert_eq!(pl[0][j], 0.0, "the blurred edge at {j}: ground");
}
}
#[test]
fn row_distances_match_a_scan_of_the_window_around_each_pixel() {
// Three classes scattered over 23 x 17 pixels, some pixels holding two, most none.
+143 -1
View File
@@ -2,10 +2,15 @@
//! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects
//! have it (of the whole document while nothing is selected); clicking a role gives the selected
//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that
//! carries a role (`addon.packaging.setRoleSwatch`).
//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu
//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each
//! with a Select button; the list is kept until the document changes.
use std::sync::{Arc, Weak};
use egui::{Align, Layout, Sense, Ui, vec2};
use serde_json::{Value, json};
use vectorcraft_engine::doc::Document;
use crate::VectorcraftApp;
use crate::menus::Item;
@@ -18,12 +23,16 @@ pub const ID: &str = "foldLines";
pub const SET_ROLE: &str = "addon.packaging.setRole";
/// The command that picks a role's swatch.
pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch";
/// The command that checks the fold lines.
pub const CHECK: &str = "addon.packaging.check";
/// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them.
pub const ROLES: &[(&str, &str)] =
&[("Cut Line", "cut"), ("Crease Line", "crease"), ("Partial Cut Line", "partialCut"), ("Perforation Line", "perforation")];
/// Where the panel keeps the last `addon.packaging.roles` answer (panel state).
const STATE: &str = "fold-lines";
/// Where the panel keeps the last check (panel state).
const CHECKED: &str = "fold-lines-check";
/// Object › Plug-ins › Packaging Tools.
pub fn menu() -> Vec<Item> {
@@ -35,9 +44,141 @@ pub fn menu() -> Vec<Item> {
make("Make Crease Line", "crease"),
make("Make Partial Cut Line", "partialCut"),
make("Make Perforation Line", "perforation"),
Item::Sep,
Item::Cmd("Check Fold Lines", CHECK, Value::Null),
]
}
/// One issue of a check: whether it is an error, its message (English) and the objects it names.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Issue {
pub error: bool,
pub message: String,
pub ids: Vec<u64>,
}
/// The document a check was made on: its id, and its content as it was then. Selecting changes
/// neither, so the issues stay listed while their Select buttons are used. The content is held
/// weakly: it is compared, never kept alive.
type DocKey = (u64, Weak<Document>);
/// The last check of a document.
#[derive(Clone, Debug, Default)]
pub(crate) struct Checked {
pub key: Option<DocKey>,
pub panels: u64,
pub hinges: u64,
pub issues: Vec<Issue>,
}
impl Checked {
/// The check `r` (an `addon.packaging.check` answer) of the document `key`.
fn of(key: DocKey, r: &Value) -> Checked {
let count = |k: &str| r[k].as_u64().unwrap_or(0);
let issues: Vec<Issue> = r["issues"]
.as_array()
.into_iter()
.flatten()
.map(|i| Issue {
error: i["severity"] == "error",
message: i["message"].as_str().unwrap_or_default().to_string(),
ids: i["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(),
})
.collect();
Checked { key: Some(key), panels: count("panels"), hinges: count("hinges"), issues }
}
/// The summary line, in English (the status bar and the panel show it translated).
fn summary(&self) -> String {
let errors = self.issues.iter().filter(|i| i.error).count();
crate::i18n::fmt(
"Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings}",
&[
("panels", &self.panels.to_string()),
("hinges", &self.hinges.to_string()),
("errors", &errors.to_string()),
("warnings", &(self.issues.len() - errors).to_string()),
],
)
}
}
/// The active document's [`DocKey`].
fn doc_key(app: &VectorcraftApp) -> Option<DocKey> {
app.session.active().map(|st| (st.uid, Arc::downgrade(&st.doc)))
}
/// Runs `addon.packaging.check` with `p` and shows its summary in the status bar → the check, kept
/// in `ctx` for the panel.
fn run_check(app: &mut VectorcraftApp, ctx: &egui::Context, p: Value) -> Option<Checked> {
let r = app.run(CHECK, p).map_err(|e| app.status(e)).ok()?;
let checked = Checked::of(doc_key(app)?, &r);
app.status(checked.summary());
set_pstate(ctx, CHECKED, checked.clone());
Some(checked)
}
/// Check Fold Lines from its menu item: checks with `p`, keeps the issues for the Fold Lines panel
/// and shows the panel.
pub(crate) fn check(app: &mut VectorcraftApp, p: Value) {
let ctx = app.ui_ctx.clone().unwrap_or_default();
if run_check(app, &ctx, p).is_some()
&& let Err(e) = crate::panel_docking::reveal_panel(app, ID)
{
app.status(e);
}
}
/// The last check of the active document, while the document has not changed since.
fn last_check(app: &VectorcraftApp, ctx: &egui::Context) -> Option<Checked> {
let checked: Checked = pstate(ctx, CHECKED);
let same = match (&checked.key, doc_key(app)) {
(Some((uid, doc)), Some((now, current))) => *uid == now && doc.ptr_eq(&current),
_ => false,
};
same.then_some(checked)
}
/// The Check button, then the last check's summary and issues (errors in the error color, warnings
/// in the warning color), each with a Select button; clicking an issue selects its objects too.
fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) {
widgets::divider(ui);
let width = ui.available_width();
if widgets::flat_button(ui, tl!("Check"), width).clicked() {
run_check(app, ui.ctx(), json!({}));
}
let Some(checked) = last_check(app, ui.ctx()) else { return };
ui.add_space(4.0);
dim_label(ui, &crate::i18n::msg(&checked.summary()));
if checked.issues.is_empty() {
dim_label(ui, tl!("No issues found."));
}
let t = crate::theme::Tokens::get(ui.ctx());
let mut select = None;
for (n, issue) in checked.issues.iter().enumerate() {
ui.horizontal(|ui| {
let can = !issue.ids.is_empty();
let picked = ui
.with_layout(Layout::right_to_left(Align::Center), |ui| {
let button = ui.add_enabled_ui(can, |ui| widgets::flat_button(ui, tl!("Select"), 56.0)).inner;
let text = egui::RichText::new(crate::i18n::msg(&issue.message)).color(if issue.error { t.error } else { t.warning });
let row =
ui.with_layout(Layout::left_to_right(Align::Center), |ui| ui.add(egui::Label::new(text).sense(Sense::click()).wrap())).inner;
button.clicked() || (row.clicked() && can)
})
.inner;
if picked {
select = Some(n);
}
});
}
if let Some(issue) = select.and_then(|n| checked.issues.get(n))
&& let Err(e) = app.run("select.set", json!({ "ids": issue.ids }))
{
app.status(e);
}
}
/// One role row: (role id, swatch name, the swatch's paint if the document has it, count).
type Row = (String, String, Option<vectorcraft_color::Paint>, u64);
@@ -103,6 +244,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
{
app.status(e);
}
show_check(app, ui);
}
/// Role Swatches… (the dialog of `addon.packaging.setRoleSwatch`): when another role is picked, its
+134 -1
View File
@@ -1,7 +1,7 @@
use serde_json::json;
use vectorcraft_engine::Session;
use super::{ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show};
use super::{CHECK, ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show};
use crate::tests_labels::painted_text;
use crate::{VectorcraftApp, menus};
@@ -125,6 +125,139 @@ fn role_swatches_shows_the_swatch_of_the_role_picked() {
assert_eq!(crate::dialogs::form::params(&d), json!({"role": "crease", "swatch": "Ink"}), "the dialog sends no __role");
}
/// An app with a square blank cut on its outline, a crease across it and a cut line that stops
/// inside it, nothing selected → (app, the cut line that stops).
fn blank() -> (VectorcraftApp, u64) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap();
let outline = path(&mut app, "M50 50 L250 50 L250 250 L50 250 Z");
let crease = path(&mut app, "M50 150 L250 150");
let slit = path(&mut app, "M100 50 L100 100");
app.run(SET_ROLE, json!({"role": "cut", "ids": [outline, slit]})).unwrap();
app.run(SET_ROLE, json!({"role": "crease", "ids": [crease]})).unwrap();
app.run("select.none", json!({})).unwrap();
(app, slit)
}
/// Frames of the panel in one context, the pointer clicking the middle of the element that screen
/// readers name `click` (egui finds what the pointer is over from the frame before, so the move
/// gets a frame of its own) → the text the last frame painted.
fn frames(app: &mut VectorcraftApp, ctx: &egui::Context, click: Option<&str>) -> String {
ctx.enable_accesskit();
crate::theme::install_fonts(ctx);
// The context's clock runs on from its last frame: egui requires time to move forward.
let mut time = ctx.input(|i| i.time);
let mut frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
time += 0.1;
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 480.0));
let input = egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| show(app, ui));
out.textures_delta.clear();
out
};
frame(app, vec![]);
let out = frame(app, vec![]);
let Some(label) = click else { return crate::tests_labels::shapes_text(&out) };
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
// A button carries its text as its name, a label as its value.
let node = nodes.iter().find(|(_, n)| n.label() == Some(label) || n.value() == Some(label));
let b = node.unwrap_or_else(|| panic!("nothing named {label:?}")).1.bounds().expect("bounds");
let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5);
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
frame(app, vec![egui::Event::PointerMoved(at)]);
frame(app, vec![button(true)]);
let out = frame(app, vec![button(false)]);
crate::tests_labels::shapes_text(&out)
}
#[test]
fn check_fold_lines_lists_its_issues_in_the_panel_until_the_document_changes() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let (mut app, _) = blank();
let entries = menus::menu_entries(&app);
let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Check Fold Lines").expect("listed");
assert_eq!(item.command.as_deref(), Some(CHECK));
let ctx = egui::Context::default();
app.ui_ctx = Some(ctx.clone());
assert!(!crate::panel_docking::showing(&app.ui, ID));
menus::invoke(&mut app, CHECK, item.params.clone());
assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens");
assert_eq!(app.ui.status, "Panels: 2, hinges: 1, errors: 1, warnings: 0");
let text = frames(&mut app, &ctx, None);
assert!(text.contains("A cut line ends without meeting another cut line."), "{text}");
assert!(text.contains("Panels: 2, hinges: 1, errors: 1, warnings: 0") && text.contains("Select"), "{text}");
// Any change to the document takes the list away.
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap();
let text = frames(&mut app, &ctx, None);
assert!(!text.contains("A cut line ends"), "{text}");
}
#[test]
fn the_check_button_checks_and_clicking_an_issue_selects_its_lines() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let (mut app, slit) = blank();
let ctx = egui::Context::default();
let text = frames(&mut app, &ctx, Some("Check"));
assert!(text.contains("A cut line ends without meeting another cut line."), "{text}");
assert!(app.session.active().unwrap().selection.is_empty());
frames(&mut app, &ctx, Some("A cut line ends without meeting another cut line."));
let selected: Vec<u64> = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect();
assert_eq!(selected, [slit]);
let text = frames(&mut app, &ctx, None);
assert!(text.contains("A cut line ends without meeting another cut line."), "selecting keeps the list: {text}");
// A clean blank: no issues.
app.run("edit.clear", json!({})).unwrap();
let text = frames(&mut app, &ctx, Some("Check"));
assert!(text.contains("No issues found.") && text.contains("Panels: 2, hinges: 1, errors: 0, warnings: 0"), "{text}");
}
#[test]
fn issues_and_the_summary_show_in_the_interface_language() {
let (mut app, _) = blank();
let ctx = egui::Context::default();
crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap());
let text = frames(&mut app, &ctx, Some(crate::i18n::t("Check")));
crate::i18n::set_current(crate::i18n::Lang::EN);
assert!(!text.contains("A cut line ends") && !text.contains("Panels:"), "{text}");
assert!(text.contains("Eine Schnittlinie endet, ohne auf eine andere Schnittlinie zu treffen."), "{text}");
assert!(text.contains("Felder: 2, Scharniere: 1, Fehler: 1, Warnungen: 0"), "{text}");
}
/// The messages `addon.packaging.check` gives its issues, one for each code (three for `noCut`).
const ISSUE_MESSAGES: [&str; 17] = [
"No cut lines are in the selection.",
"No cut lines are in the document.",
"No cut lines are among the given objects.",
"The cut lines do not enclose an area.",
"A cut line ends without meeting another cut line.",
"A gap between cut lines was closed.",
"The fold lines are too complex to check.",
"A cut line and a crease lie on top of each other.",
"Two fold lines lie on top of each other.",
"A crease ends inside a panel.",
"A crease does not divide two panels.",
"A crease lies outside the cut outline, wholly or in part.",
"The pieces of a hinge are not on one straight line.",
"A gap between cut lines is too narrow to tell apart.",
"A cut-out area holds other fold lines or another blank.",
"A panel is not joined to the rest by a crease.",
"A fold line is on a non-printing layer.",
];
#[test]
fn every_issue_message_translates_in_every_complete_message_catalog() {
for code in [
"cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr",
"ca", "nl", "da",
] {
let lang = crate::i18n::Lang::from_code(code).unwrap();
for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0"]) {
assert_ne!(crate::i18n::message(lang, m), m, "{code}: {m}");
}
}
}
#[test]
fn the_panel_without_a_document_asks_for_one() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+1 -1
View File
@@ -126,7 +126,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
let size_at = r.right_center() - vec2(6.0, 0.0);
p.text(size_at, egui::Align2::RIGHT_CENTER, &size, font.clone(), t.text_dim);
p.with_clip_rect(r.with_max_x(size_at.x - 80.0)).text(mid + vec2(NUMBER_W, 0.0), egui::Align2::LEFT_CENTER, name, font, t.text);
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, on, format!("{} {name} {size}", i + 1)));
widgets::list_item_info(&resp, on, || format!("{} {name} {size}", i + 1));
if resp.double_clicked() {
double = Some(i);
} else if resp.clicked() {
+18
View File
@@ -82,6 +82,24 @@ fn select_by_artboards_lists_the_artboards_and_selects_on_ok() {
assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(inside)]);
}
#[test]
fn the_rows_report_their_choice_as_the_selected_state() {
use egui::accesskit::Role;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("artboard.new", json!({"x": 150, "y": 0, "width": 200, "height": 50, "name": "Banner"})).unwrap();
app.run("view.goToArtboard", json!({"index": 0})).unwrap();
menus::invoke(&mut app, super::COMMAND, serde_json::Value::Null);
let tree = crate::widgets::accessibility_tests::tree(|ui| crate::dialogs::show(&mut app, ui.ctx()));
let mut rows: Vec<_> =
tree.iter().filter(|n| n.role() == Role::ListItem).map(|n| (n.label().map(str::to_string), n.is_selected(), n.toggled())).collect();
rows.sort_by(|a, b| a.0.cmp(&b.0));
assert_eq!(
rows,
[(Some("1 Artboard 1 100 × 100 pt".to_string()), Some(true), None), (Some("2 Banner 200 × 50 pt".to_string()), Some(false), None)]
);
}
#[test]
fn double_clicking_a_row_fits_its_artboard_and_keeps_the_choice() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+12 -5
View File
@@ -495,12 +495,14 @@ impl VectorcraftApp {
/// The canvas panel's body: the document tabs, the canvas (a pane for each document while
/// Window › Arrange › Tile is on) and the isolation bar over it. While the current document is
/// in a floating window, the tab strip's document draws as a pane.
/// in a floating window, the tab strip's document draws as a pane, which a Selection drag's
/// artwork can be released in ([`canvas::note_drop`]).
pub(crate) fn canvas_area(&mut self, ui: &mut egui::Ui) {
let t = theme::Tokens::get(ui.ctx());
// Tools may already occupy the left side of this panel.
ui.painter().rect_filled(ui.available_rect_before_wrap(), 0.0, t.pasteboard);
self.canvas.windows.strip = None;
self.canvas.windows.drops.clear();
if self.ui.screen_mode < 3 {
chrome::doc_tabs(self, ui);
}
@@ -509,10 +511,15 @@ impl VectorcraftApp {
if !canvas::tiled_area(self, ui) {
if floats {
let rect = ui.available_rect_before_wrap();
if let Some(w) = crate::doc_windows::tab_window(self)
&& canvas::pane(self, ui, w, rect)
{
crate::doc_windows::show_window(self, w);
if let Some(w) = crate::doc_windows::tab_window(self) {
let pressed = canvas::pane(self, ui, w, rect);
// A drag from a current window that is an OS window ends in that window.
if !crate::doc_windows::native(self, ui.ctx()) {
canvas::note_drop(self, ui, w, rect);
}
if pressed {
crate::doc_windows::show_window(self, w);
}
}
} else {
canvas::show(self, ui);
+4 -3
View File
@@ -42,7 +42,7 @@ pub use cursor::{HOVER_STILL_SECS, STILL_SECS, ViewKey};
use cursor::{cursor_icon, hover_cursor, hover_wait, still_wait};
use drag::drag_id;
pub use drag::{apply_requests, dispatch, mods};
pub(crate) use drag::{end_document_drag, pose_on_page, release_art_in_window, release_over_panel};
pub(crate) use drag::{art_out, end_art_move, end_document_drag, pose_on_page, release_art_in_window, release_over_panel};
#[cfg(test)]
use drag::{frame_moves, tool_drag_doc_id, tool_drag_moved, tool_frame_moves, tool_press_doc_id};
pub use fill::Fill;
@@ -65,7 +65,7 @@ pub use overlays::SharedPaths;
use overlays::selected_anchor;
use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay};
pub use panes::Panes;
pub(crate) use panes::{consolidate, pane, tile, tiled_area};
pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area};
use raster::{changed_pixels, frame_ppp, pixel_region, upload};
pub(crate) use raster::{color_image, color_image_owned, render_job};
pub use selection_marks::SelectionMarks;
@@ -78,7 +78,7 @@ use tool_overlays::{DIAL_RADIUS, HiddenMarks};
pub use tool_overlays::{HiddenChars, SpellingMarks};
use tool_overlays::{
grid_repeat_overlay, hidden_chars_overlay, live_paint_gap_overlays, mirror_axis_overlay, nine_slice_overlay, original_path_overlay,
print_tiling_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays,
print_tiling_overlay, radial_repeat_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays,
};
pub(crate) use view::animated_zoom;
pub(crate) use view::drag_rotation;
@@ -1347,6 +1347,7 @@ fn selection_visuals(
draw_inside_overlay(app, painter, xf);
mirror_axis_overlay(app, painter, xf);
grid_repeat_overlay(app, painter, xf);
radial_repeat_overlay(app, painter, xf);
if app.ui.view.text_threads {
// Under the tools' overlays: a selected frame's own ports are drawn over its thread's.
let mut threads = thread_overlays(app, xf.zoom);
+11 -2
View File
@@ -29,6 +29,11 @@ pub(crate) fn end_document_drag(ctx: &egui::Context) {
});
}
/// Whether a Selection tool move has left the canvas ([`drag_art_out`]) and still waits there.
pub(crate) fn art_out(ctx: &egui::Context) -> bool {
matches!(ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Art))
}
/// Temp-memory key for the active canvas drag state.
pub(super) fn drag_id() -> egui::Id {
egui::Id::unique("canvas-drag")
@@ -320,6 +325,9 @@ pub(super) fn drag_art_out(app: &VectorcraftApp, ui: &Ui, resp: &egui::Response,
/// panel that takes the art ([`widgets::PanelDrag::Art`]) takes it where it was, and no move is
/// left open (#2826). The art stays where it last moved while the pointer is over the panel.
pub(crate) fn release_over_panel(app: &mut VectorcraftApp, ctx: &egui::Context) {
// A floating window's pane, or the main window's while the current window floats, takes the
// art first.
super::release_on_noted(app, ctx);
crate::document_drag::cleanup(app, ctx);
let art = matches!(ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Art));
// Over a floating panel's own OS window the pointer is gone from this window, and the release
@@ -355,8 +363,9 @@ pub(crate) fn release_art_in_window(app: &mut VectorcraftApp, ctx: &egui::Contex
}
}
/// Roll back the art move dragged off the canvas; a panel takes the art instead.
fn end_art_move(app: &mut VectorcraftApp, ctx: &egui::Context) {
/// Roll back the art move dragged off the canvas, and end the canvas's drag; a panel or another
/// window's tiled pane takes the art instead.
pub(crate) fn end_art_move(app: &mut VectorcraftApp, ctx: &egui::Context) {
// With no document open there is nothing to roll back; the tool still gets its mouse-up.
let _ = app.session.cancel_interaction();
let view = app.view_info();
+89 -4
View File
@@ -1,8 +1,9 @@
//! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document
//! area. The current document's pane is the canvas ([`super::show`]). Each other pane draws its
//! document from a render of its own, with its artboards, guides and selected objects, and a press
//! in it makes its document the current one. Each view Window › New Window opened has a pane of
//! its own ([`crate::doc_windows`]).
//! in it makes its document the current one. A Selection drag released in it drops the dragged
//! artwork into its document ([`crate::document_drag::drop_on_pane`]). Each view Window › New
//! Window opened has a pane of its own ([`crate::doc_windows`]).
use std::collections::HashMap;
use std::sync::Arc;
@@ -243,12 +244,18 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect();
let unfitted = refit_resized(app, &areas);
let mut activate = None;
let (mut cursor, mut dropped) = (None, None);
// The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar)
// stays over them.
for (w, cell) in cells.iter().copied().filter(|(w, _)| Some(*w) != active) {
for ((w, cell), (_, area)) in cells.iter().copied().zip(areas.iter().copied()).filter(|((w, _), _)| Some(*w) != active) {
if pane(app, ui, w, cell) {
activate = Some(w);
}
match artwork_over(app, ui, w, area) {
Some(Over::Held(c)) => cursor = Some(c),
Some(Over::Released(at, carried)) => dropped = Some((w, at, carried)),
None => {}
}
ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside);
}
if let Some((_, cell)) = cells.iter().copied().find(|(w, _)| Some(*w) == active) {
@@ -256,6 +263,10 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
super::show(app, &mut canvas);
ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.5, t.accent), StrokeKind::Inside);
}
// After the canvas, which sets the cursor of the drag it holds.
if let Some(c) = cursor {
ui.ctx().set_cursor_icon(c);
}
// Note the fits this frame made, for `refit_resized`.
for ((w, area), was_unfitted) in areas.iter().zip(unfitted) {
if let (true, Some(v), Some(s)) = (was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) {
@@ -263,12 +274,86 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
}
}
app.canvas.panes.last = cells;
if let Some(w) = activate {
if let Some((w, at, carried)) = dropped {
crate::document_drag::drop_on_pane(app, ui.ctx(), w, at, carried);
} else if let Some(w) = activate {
crate::doc_windows::show_window(app, w);
}
true
}
/// A Selection drag's artwork over another window's tiled pane.
enum Over {
/// Held there: the cursor that shows whether a release moves or copies it.
Held(egui::CursorIcon),
/// Released there, at a document point in the pane's own view.
Released(Point, crate::document_drag::Carried),
}
/// A Selection drag's artwork over `area`, the part of window `w`'s pane inside its rulers and
/// scroll bars, where no panel or floating window is over the pointer. A release there takes the
/// artwork before the canvas sees the release ([`crate::document_drag::take_for_pane`]).
fn artwork_over(app: &mut VectorcraftApp, ui: &Ui, w: Win, area: egui::Rect) -> Option<Over> {
let (uid, _) = slot(app, w)?;
let p = ui.input(crate::document_drag::released_at)?;
if !area.contains(p) || ui.ctx().layer_id_at(p).is_some_and(|l| l != ui.layer_id()) {
return None;
}
let cursor = crate::document_drag::pane_cursor(app, ui.ctx(), uid)?;
if !ui.input(|i| i.pointer.primary_released()) {
return Some(Over::Held(cursor));
}
let v = crate::doc_windows::view(app, w).copied()?;
let at = Xf::at(area, &v, ui.ctx().zoom_factor()).to_doc(p);
Some(Over::Released(at, crate::document_drag::take_for_pane(app, ui.ctx())?))
}
/// Note window `w`'s pane, drawn in `cell` of `ui` outside Tile (a floating window inside the main
/// window, or the main window while the current window floats), as a place a Selection drag's
/// artwork can be released in ([`release_on_noted`]): the part inside its rulers and scroll bars.
pub(crate) fn note_drop(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) {
let Some(s) = slot(app, w) else { return };
let area = view_rects(app, cell, ui.ctx().pixels_per_point()).1;
app.canvas.windows.drops.push((s, area, ui.layer_id()));
}
/// The noted pane ([`note_drop`]) at `p`, where no panel or other window is over it: its window
/// and its art area.
fn noted_at(app: &VectorcraftApp, ctx: &egui::Context, p: egui::Pos2) -> Option<(Win, egui::Rect)> {
let top = ctx.layer_id_at(p);
let (s, area, _) = app.canvas.windows.drops.iter().rev().find(|(_, area, layer)| area.contains(p) && top.is_none_or(|l| l == *layer))?;
let w = crate::doc_windows::windows(app).into_iter().find(|w| slot(app, *w) == Some(*s))?;
Some((w, *area))
}
/// A Selection drag's artwork released over a pane the last frame noted ([`note_drop`]) drops into
/// its document ([`crate::document_drag::drop_on_pane`]), at the document point where the button
/// went up, in that pane's own view. Runs at the start of a frame, before any canvas sees the release.
pub(crate) fn release_on_noted(app: &mut VectorcraftApp, ctx: &egui::Context) {
if app.canvas.windows.drops.is_empty() || !ctx.input(|i| i.pointer.primary_released()) {
return;
}
let Some(p) = ctx.input(crate::document_drag::released_at) else { return };
let Some((w, area)) = noted_at(app, ctx, p) else { return };
let Some(v) = crate::doc_windows::view(app, w).copied() else { return };
let at = Xf::at(area, &v, ctx.zoom_factor()).to_doc(p);
if let Some(carried) = crate::document_drag::take_for_pane(app, ctx) {
crate::document_drag::drop_on_pane(app, ctx, w, at, carried);
}
}
/// While a Selection drag's artwork is held over a pane this frame noted ([`note_drop`]), the cursor
/// shows whether a release there moves or copies it ([`crate::document_drag::pane_cursor`]).
pub(crate) fn noted_cursor(app: &VectorcraftApp, ctx: &egui::Context) {
let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return };
if let Some((w, _)) = noted_at(app, ctx, p)
&& let Some((uid, _)) = slot(app, w)
&& let Some(c) = crate::document_drag::pane_cursor(app, ctx, uid)
{
ctx.set_cursor_icon(c);
}
}
/// Window `w`'s [`Slot`].
fn slot(app: &VectorcraftApp, (i, n): Win) -> Option<Slot> {
app.session.documents().get(i).map(|d| (d.uid, n))
+248
View File
@@ -165,6 +165,254 @@ fn a_press_in_another_pane_makes_its_document_current_without_drawing() {
assert!(app.session.documents()[1..].iter().all(|d| d.doc.art_bounds().is_none()));
}
/// One headless frame at `time` seconds as the app runs it: a Selection move released off the
/// canvas ends first ([`crate::canvas::release_over_panel`]), then the tabs and the panes draw.
fn timed_frame(app: &mut VectorcraftApp, ctx: &egui::Context, time: Option<f64>, events: Vec<egui::Event>) -> egui::FullOutput {
let raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))),
max_texture_side: Some(8192),
time,
events,
..Default::default()
};
let mut out = ctx.run_ui(raw, |ui| {
crate::canvas::release_over_panel(app, ui.ctx());
app.canvas_area(ui);
});
out.textures_delta.clear();
out
}
/// [`timed_frame`] without a time. → the cursor.
fn app_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> egui::CursorIcon {
timed_frame(app, ctx, None, events).platform_output.cursor_icon
}
/// Two 400 × 300 pt documents tiled side by side: the first, current, holds a selected 100 pt
/// square at 50, 50 and the second a 50 pt square at 300, 230. The Selection tool is chosen.
fn tiled_pair() -> (VectorcraftApp, egui::Context) {
let mut app = app_with(0);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 300, "y": 230, "width": 50, "height": 50})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.select_tool("selection");
app.ui.task_bar = false;
app.run("window.arrange.tile", json!({})).unwrap();
let ctx = egui::Context::default();
app_frame(&mut app, &ctx, vec![]);
app_frame(&mut app, &ctx, vec![]);
(app, ctx)
}
/// Press on document point `at` on the canvas and move the pointer 20 × 10 points, still on the
/// canvas: the Selection tool moves the art under it.
fn grab(app: &mut VectorcraftApp, ctx: &egui::Context, at: Point) {
let p = Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), 1.0).to_screen(at);
app_frame(app, ctx, vec![egui::Event::PointerMoved(p), button(p, true)]);
app_frame(app, ctx, vec![egui::Event::PointerMoved(p + vec2(20.0, 10.0))]);
assert!(app.session.in_interaction(), "the Selection tool moves the art");
}
/// Window `w`'s pane: the screen point that shows document point `at` in it, and the pane.
fn in_pane(app: &VectorcraftApp, ctx: &egui::Context, w: Win, at: Point) -> (Pos2, egui::Rect) {
let (_, cell) = app.canvas.panes.last.iter().copied().find(|(o, _)| *o == w).unwrap();
let area = view_rects(app, cell, ctx.pixels_per_point()).1;
(Xf::at(area, crate::doc_windows::view(app, w).unwrap(), 1.0).to_screen(at), cell)
}
/// How many objects document `i`'s first layer holds.
fn objects(app: &VectorcraftApp, i: usize) -> usize {
app.session.documents()[i].doc.layers[0].children().map_or(0, Vec::len)
}
/// The bounds of the one object selected in the current document.
fn selected_bounds(app: &VectorcraftApp) -> Rect {
let st = app.session.active().unwrap();
assert_eq!(st.selection.objects.len(), 1, "one object is selected");
st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap()
}
#[test]
fn a_selection_drag_released_in_another_documents_pane_copies_the_art_there() {
let (mut app, ctx) = tiled_pair();
// The target's view differs from the source's: the grab point still lands under the pointer.
app.views[1].zoom *= 0.6;
app.views[1].rotation = 30.0;
app_frame(&mut app, &ctx, vec![]);
let source = app.session.documents()[0].doc.clone();
let source_undo = app.session.documents()[0].history.undo.len();
let target = app.session.documents()[1].doc.clone();
let target_undo = app.session.documents()[1].history.undo.len();
let clipboard = app.session.clipboard.clone();
grab(&mut app, &ctx, Point::new(100.0, 100.0));
let (drop, _) = in_pane(&app, &ctx, (1, 1), Point::new(170.0, 120.0));
// The release comes in the first frame the pointer is over the pane.
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop), button(drop, false)]);
app_frame(&mut app, &ctx, vec![]);
assert_eq!(app.session.active_index(), Some(1), "the pane's document is the current one");
let placed = selected_bounds(&app);
assert!((placed.center().x - 170.0).abs() < 0.01 && (placed.center().y - 120.0).abs() < 0.01, "{placed:?}");
assert_eq!(app.session.documents()[1].history.undo.len(), target_undo + 1, "one step to undo");
assert_eq!(app.session.documents()[0].doc, source, "the source keeps its art where it was");
assert_eq!(app.session.documents()[0].history.undo.len(), source_undo);
assert_eq!(app.session.clipboard, clipboard, "the drag leaves the clipboard alone");
assert!(!app.session.tool_busy());
app.run("edit.undo", json!({})).unwrap();
assert_eq!(app.session.documents()[1].doc, target);
app.run("edit.redo", json!({})).unwrap();
assert_eq!(app.session.documents()[1].history.undo.len(), target_undo + 1);
}
#[test]
fn art_held_over_another_pane_shows_a_copy_and_drags_back_the_other_way() {
let (mut app, ctx) = tiled_pair();
grab(&mut app, &ctx, Point::new(100.0, 100.0));
let (over, _) = in_pane(&app, &ctx, (1, 1), Point::new(200.0, 150.0));
let cursor = app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(over)]);
assert_eq!(cursor, egui::CursorIcon::Copy, "over another document's pane the art is copied");
assert_eq!(app.session.active_index(), Some(0), "holding the art over a pane does not switch documents");
let (drop, _) = in_pane(&app, &ctx, (1, 1), Point::new(120.0, 90.0));
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
app_frame(&mut app, &ctx, vec![button(drop, false)]);
app_frame(&mut app, &ctx, vec![]);
assert_eq!(app.session.active_index(), Some(1));
assert_eq!(objects(&app, 1), 2, "the copy joins the target's square");
// From the target, now the canvas, back into the first document's pane.
app_frame(&mut app, &ctx, vec![]);
grab(&mut app, &ctx, Point::new(325.0, 255.0));
let (back, _) = in_pane(&app, &ctx, (0, 1), Point::new(300.0, 200.0));
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(back), button(back, false)]);
app_frame(&mut app, &ctx, vec![]);
assert_eq!(app.session.active_index(), Some(0));
let placed = selected_bounds(&app);
assert!((placed.center().x - 300.0).abs() < 0.01 && (placed.center().y - 200.0).abs() < 0.01, "{placed:?}");
assert_eq!(objects(&app, 0), 2);
}
#[test]
fn a_selection_drag_into_another_view_of_its_document_moves_the_art() {
let (mut app, ctx) = tiled_pair();
app.run("window.newWindow", json!({})).unwrap();
app.run("window.arrange.tile", json!({})).unwrap();
app_frame(&mut app, &ctx, vec![]);
app_frame(&mut app, &ctx, vec![]);
let current = crate::doc_windows::current(&app).unwrap();
let other = app.canvas.panes.last.iter().map(|(w, _)| *w).find(|w| w.0 == 0 && *w != current).unwrap();
let undo = app.session.documents()[0].history.undo.len();
let target = app.session.documents()[1].doc.clone();
grab(&mut app, &ctx, Point::new(100.0, 100.0));
let (drop, _) = in_pane(&app, &ctx, other, Point::new(250.0, 200.0));
let cursor = app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
assert_eq!(cursor, egui::CursorIcon::Move, "another view of the same document moves the art");
app_frame(&mut app, &ctx, vec![button(drop, false)]);
app_frame(&mut app, &ctx, vec![]);
assert_eq!(crate::doc_windows::current(&app), Some(other), "the pane's view is the current window");
assert_eq!(objects(&app, 0), 1, "the square moved, not copied");
let moved = selected_bounds(&app);
assert!((moved.center().x - 250.0).abs() < 0.01 && (moved.center().y - 200.0).abs() < 0.01, "{moved:?}");
assert_eq!(app.session.documents()[0].history.undo.len(), undo + 1);
assert_eq!(app.session.documents()[1].doc, target, "the other document is untouched");
}
#[test]
fn a_pane_drop_lands_where_the_button_went_up_and_copies_when_alt_was_held_then() {
// A pointer move later in the frame of the release does not move the drop.
let (mut app, ctx) = tiled_pair();
grab(&mut app, &ctx, Point::new(100.0, 100.0));
let (drop, _) = in_pane(&app, &ctx, (1, 1), Point::new(170.0, 120.0));
let (later, _) = in_pane(&app, &ctx, (1, 1), Point::new(80.0, 60.0));
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop), button(drop, false), egui::Event::PointerMoved(later)]);
app_frame(&mut app, &ctx, vec![]);
assert_eq!(app.session.active_index(), Some(1));
let placed = selected_bounds(&app);
assert!((placed.center().x - 170.0).abs() < 0.01 && (placed.center().y - 120.0).abs() < 0.01, "{placed:?}");
// Alt held at the release and let go later in that frame copies into another view of the source.
let (mut app, ctx) = tiled_pair();
app.run("window.newWindow", json!({})).unwrap();
app.run("window.arrange.tile", json!({})).unwrap();
app_frame(&mut app, &ctx, vec![]);
app_frame(&mut app, &ctx, vec![]);
let current = crate::doc_windows::current(&app).unwrap();
let other = app.canvas.panes.last.iter().map(|(w, _)| *w).find(|w| w.0 == 0 && *w != current).unwrap();
grab(&mut app, &ctx, Point::new(100.0, 100.0));
let (drop, _) = in_pane(&app, &ctx, other, Point::new(250.0, 200.0));
let alt = egui::Modifiers::ALT;
let cursor = app_frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(alt), egui::Event::PointerMoved(drop)]);
assert_eq!(cursor, egui::CursorIcon::Copy, "Alt shows a copy");
let up = egui::Event::PointerButton { pos: drop, button: egui::PointerButton::Primary, pressed: false, modifiers: alt };
app_frame(&mut app, &ctx, vec![up, egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
app_frame(&mut app, &ctx, vec![]);
assert_eq!(crate::doc_windows::current(&app), Some(other));
assert_eq!(objects(&app, 0), 2, "the square was copied, not moved");
}
#[test]
fn art_carried_through_a_tab_drops_into_a_third_documents_pane() {
let (mut app, ctx) = tiled_pair();
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("window.arrange.tile", json!({})).unwrap();
let source = app.session.documents()[0].doc.clone();
let third = app.session.documents()[2].doc.clone();
let titles = |out: egui::FullOutput| -> Vec<egui::Rect> {
let mut t: Vec<_> = out
.shapes
.iter()
.filter_map(|s| match &s.shape {
Shape::Text(t) if t.galley.text().contains(" @ ") => Some(egui::Rect::from_min_size(t.pos, t.galley.size())),
_ => None,
})
.collect();
t.sort_by(|a, b| a.left().total_cmp(&b.left()));
t
};
timed_frame(&mut app, &ctx, Some(0.0), vec![]);
let tabs = titles(timed_frame(&mut app, &ctx, Some(0.01), vec![]));
assert_eq!(tabs.len(), 3);
let p = Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), 1.0).to_screen(Point::new(100.0, 100.0));
timed_frame(&mut app, &ctx, Some(0.05), vec![egui::Event::PointerMoved(p), button(p, true)]);
timed_frame(&mut app, &ctx, Some(0.1), vec![egui::Event::PointerMoved(p + vec2(20.0, 10.0))]);
timed_frame(&mut app, &ctx, Some(0.2), vec![egui::Event::PointerMoved(tabs[2].center())]);
timed_frame(&mut app, &ctx, Some(0.25), vec![]);
timed_frame(&mut app, &ctx, Some(0.8), vec![]);
assert_eq!(app.session.active_index(), Some(2), "holding the art over the third tab makes that document current");
timed_frame(&mut app, &ctx, Some(0.85), vec![]);
let (drop, _) = in_pane(&app, &ctx, (1, 1), Point::new(150.0, 100.0));
timed_frame(&mut app, &ctx, Some(0.9), vec![egui::Event::PointerMoved(drop)]);
timed_frame(&mut app, &ctx, Some(1.0), vec![button(drop, false)]);
timed_frame(&mut app, &ctx, Some(1.1), vec![]);
assert_eq!(app.session.active_index(), Some(1), "the pane's document is the current one");
assert_eq!(objects(&app, 1), 2, "the copy joins the second document's square");
let placed = selected_bounds(&app);
assert!((placed.center().x - 150.0).abs() < 0.01 && (placed.center().y - 100.0).abs() < 0.01, "{placed:?}");
assert_eq!(app.session.documents()[0].doc, source);
assert_eq!(app.session.documents()[2].doc, third, "the document the tab showed is untouched");
}
#[test]
fn a_drag_released_off_a_panes_art_area_or_after_escape_changes_nothing() {
for (case, escape) in [("scroll bar", false), ("art area after Escape", true)] {
let (mut app, ctx) = tiled_pair();
let docs: Vec<_> = app.session.documents().iter().map(|d| (d.doc.clone(), d.history.undo.len())).collect();
grab(&mut app, &ctx, Point::new(100.0, 100.0));
let (inside, cell) = in_pane(&app, &ctx, (1, 1), Point::new(200.0, 150.0));
let at = if escape { inside } else { pos2(cell.right() - 2.0, cell.center().y) };
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
if escape {
let key = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
app_frame(&mut app, &ctx, vec![key]);
}
app_frame(&mut app, &ctx, vec![button(at, false)]);
app_frame(&mut app, &ctx, vec![]);
assert_eq!(app.session.active_index(), Some(0), "{case}: the source stays current");
let after: Vec<_> = app.session.documents().iter().map(|d| (d.doc.clone(), d.history.undo.len())).collect();
assert!(after == docs, "{case}: neither document changes");
assert!(!app.session.in_interaction(), "{case}: the move ended");
}
}
#[test]
fn consolidate_all_windows_shows_one_document_again() {
let mut app = app_with(2);
+183
View File
@@ -4824,6 +4824,189 @@ fn grid_repeat_handles_set_rows_and_spacing_in_one_undo_step_each() {
assert_eq!((grid(&app).0, grid(&app).2), (5, 10.0), "the spacing's own undo step");
}
/// A selected radial repeat draws its instances handle and its radius handle (none with the
/// bounding box hidden). In a zoomed view turned 30°, dragging the instances handle two steps down
/// adds two instances without scaling the source, and dragging the radius handle 20 pt outward
/// makes the circle 20 pt larger, as one undo step each; Escape puts a drag back.
#[test]
fn radial_repeat_handles_set_instances_and_radius_in_one_undo_step_each() {
use vectorcraft_tools::repeat_radial::{HANDLE_RADIUS, INSTANCE_STEP, RadialHandles};
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 180, "y": 40, "width": 40, "height": 40})).unwrap();
app.run("object.repeat.radial", json!({"instances": 6, "radius": 60})).unwrap();
app.ui.task_bar = false;
app.ui.view.rulers = false;
let ctx = egui::Context::default();
// The first frame fits the artboard in the window; then zoom to 1.5 px a point and turn 30°.
frame(&mut app, &ctx, vec![]);
app.view_mut().unwrap().zoom = 1.5;
app.view_mut().unwrap().rotation = 30.0;
frame(&mut app, &ctx, vec![]);
// Instances, radius and the source's bounds.
let radial = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
let n = st.doc.node(st.selection.objects[0]).unwrap();
let vectorcraft_doc::NodeKind::Repeat(spec) = &n.kind else { panic!("a repeat") };
let vectorcraft_doc::RepeatKind::Radial { instances, radius, .. } = spec.kind else { panic!("a radial repeat") };
(instances, radius, spec.source_bounds().unwrap())
};
let handles = |app: &mut VectorcraftApp| {
let frame = app.selection_box();
let st = app.session.active().unwrap();
RadialHandles::of(&st.doc, &st.selection, frame, app.view().unwrap().zoom).unwrap()
};
let before = radial(&app);
assert_eq!((before.0, before.1), (6, 60.0));
let h = handles(&mut app);
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
let circle_at =
|drawn: &[Shape], at: Pos2| drawn.iter().any(|s| matches!(s, Shape::Circle(c) if c.center.distance(at) < 0.01 && c.radius == HANDLE_RADIUS));
let drawn = shapes(&mut app, &ctx);
assert!(circle_at(&drawn, xf.to_screen(h.instances_at)), "the instances handle is drawn");
assert!(circle_at(&drawn, xf.to_screen(h.radius_at)), "the radius handle is drawn");
app.ui.view.bounding_box = false;
let drawn = shapes(&mut app, &ctx);
assert!(!circle_at(&drawn, xf.to_screen(h.instances_at)) && !circle_at(&drawn, xf.to_screen(h.radius_at)), "hidden with the bounding box");
app.ui.view.bounding_box = true;
frame(&mut app, &ctx, vec![]);
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
let drag = |app: &mut VectorcraftApp, from: Pos2, to: Pos2| {
frame(app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]);
for k in 1..=4 {
frame(app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * k as f32 / 4.0)]);
}
};
let release = |app: &mut VectorcraftApp, at: Pos2| frame(app, &ctx, vec![button(at, false)]);
// 2.2 steps down the page (the screen's down turned 30°): two more instances.
let to = xf.to_screen(h.instances_at + vectorcraft_geom::Vec2::new(0.0, 2.2 * INSTANCE_STEP / 1.5));
drag(&mut app, xf.to_screen(h.instances_at), to);
assert_eq!(radial(&app).0, 8, "the drag previews");
release(&mut app, to);
let after = radial(&app);
assert_eq!((after.0, after.1), (8, 60.0));
assert_eq!(after.2, before.2, "the source keeps its size");
app.run("edit.undo", json!({})).unwrap();
assert_eq!(radial(&app).0, 6, "one undo step");
app.run("edit.redo", json!({})).unwrap();
assert_eq!(radial(&app).0, 8);
// 20 pt outward from the center.
frame(&mut app, &ctx, vec![]);
let h = handles(&mut app);
let out = (h.radius_at - h.center) / h.radius;
let to = xf.to_screen(h.radius_at + out * 20.0);
drag(&mut app, xf.to_screen(h.radius_at), to);
release(&mut app, to);
assert_eq!((radial(&app).0, radial(&app).1), (8, 80.0));
assert_eq!(radial(&app).2, before.2, "the source keeps its size");
app.run("edit.undo", json!({})).unwrap();
assert_eq!((radial(&app).0, radial(&app).1), (8, 60.0), "the radius's own undo step");
// Escape during a drag puts the radius back and leaves no undo step.
frame(&mut app, &ctx, vec![]);
let h = handles(&mut app);
drag(&mut app, xf.to_screen(h.radius_at), xf.to_screen(h.radius_at + out * 30.0));
assert_eq!(radial(&app).1, 90.0, "the drag previews");
let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
let mut full = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events: vec![escape], ..Default::default() }, |ui| {
crate::shortcuts::handle(&mut app, ui.ctx());
show(&mut app, ui)
});
full.textures_delta.clear();
assert_eq!(radial(&app).1, 60.0);
release(&mut app, xf.to_screen(h.radius_at + out * 30.0));
assert_eq!(radial(&app).1, 60.0, "the release after Escape changes nothing");
app.run("edit.undo", json!({})).unwrap();
assert_eq!(radial(&app).0, 6, "the instances step is the one before");
}
/// A selected radial repeat draws its splitter on its circle. In a zoomed view turned 30°,
/// dragging the splitter back around the circle past two instances hides them while the other
/// four stay where they were, as one undo step; Escape puts a drag back.
#[test]
fn radial_repeat_splitter_hides_instances_in_one_undo_step() {
use vectorcraft_geom::Affine;
use vectorcraft_tools::repeat_radial::{HANDLE_RADIUS, RadialHandles};
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 180, "y": 40, "width": 40, "height": 40})).unwrap();
app.run("object.repeat.radial", json!({"instances": 6, "radius": 60})).unwrap();
app.ui.task_bar = false;
app.ui.view.rulers = false;
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
app.view_mut().unwrap().zoom = 1.5;
app.view_mut().unwrap().rotation = 30.0;
frame(&mut app, &ctx, vec![]);
// Instances shown, end angle and where the instances are.
let radial = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
let n = st.doc.node(st.selection.objects[0]).unwrap();
let vectorcraft_doc::NodeKind::Repeat(spec) = &n.kind else { panic!("a repeat") };
let vectorcraft_doc::RepeatKind::Radial { instances, end_angle, .. } = spec.kind else { panic!("a radial repeat") };
(instances, end_angle, spec.transforms(Some(&st.doc)))
};
let handles = |app: &mut VectorcraftApp| {
let frame = app.selection_box();
let st = app.session.active().unwrap();
RadialHandles::of(&st.doc, &st.selection, frame, app.view().unwrap().zoom).unwrap()
};
// `h`'s splitter turned `deg` degrees about the center (positive: the way the instances run).
let around =
|h: &RadialHandles, deg: f64| h.center + (Affine::rotate(deg.to_radians()) * (h.splitter_at.unwrap() - h.center).to_point()).to_vec2();
let before = radial(&app);
assert_eq!((before.0, before.1, before.2.len()), (6, 360.0, 6));
let h = handles(&mut app);
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
let drawn = shapes(&mut app, &ctx);
let at = xf.to_screen(h.splitter_at.unwrap());
assert!(
drawn.iter().any(|s| matches!(s, Shape::Circle(c) if c.center.distance(at) < 0.01 && c.radius == HANDLE_RADIUS)),
"the splitter is drawn"
);
frame(&mut app, &ctx, vec![]);
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
let drag = |app: &mut VectorcraftApp, from: Pos2, to: Pos2| {
frame(app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]);
for k in 1..=4 {
frame(app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * k as f32 / 4.0)]);
}
};
let release = |app: &mut VectorcraftApp, at: Pos2| frame(app, &ctx, vec![button(at, false)]);
// Back 120° (two instances 60° apart): four shown, the rest in place.
let to = xf.to_screen(around(&h, -120.0));
drag(&mut app, xf.to_screen(h.splitter_at.unwrap()), to);
assert_eq!(radial(&app).0, 4, "the drag previews");
release(&mut app, to);
let after = radial(&app);
assert_eq!((after.0, after.1, after.2.len()), (4, 180.0, 4));
for (k, (a, b)) in after.2.iter().zip(&before.2).enumerate() {
assert!(a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| (x - y).abs() < 1e-9), "instance {k} stays where it was");
}
app.run("edit.undo", json!({})).unwrap();
assert_eq!((radial(&app).0, radial(&app).1), (6, 360.0), "one undo step");
app.run("edit.redo", json!({})).unwrap();
assert_eq!((radial(&app).0, radial(&app).1), (4, 180.0));
// Escape during a drag forward puts the split back and leaves no undo step.
frame(&mut app, &ctx, vec![]);
let h = handles(&mut app);
let to = xf.to_screen(around(&h, 120.0));
drag(&mut app, xf.to_screen(h.splitter_at.unwrap()), to);
assert_eq!((radial(&app).0, radial(&app).1), (6, 360.0), "the drag previews");
let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
let mut full = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events: vec![escape], ..Default::default() }, |ui| {
crate::shortcuts::handle(&mut app, ui.ctx());
show(&mut app, ui)
});
full.textures_delta.clear();
assert_eq!((radial(&app).0, radial(&app).1), (4, 180.0));
release(&mut app, to);
assert_eq!(radial(&app).0, 4, "the release after Escape changes nothing");
app.run("edit.undo", json!({})).unwrap();
assert_eq!((radial(&app).0, radial(&app).1), (6, 360.0), "the split was the step before");
}
/// While a symbol with 9-slice guides is edited, the canvas draws its four guides dotted across
/// its art, with ruler guides hidden too, and none once the mode ends. Dragging the left guide in
/// a zoomed view moves that guide alone, as one undo step.
@@ -535,6 +535,38 @@ pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, x
}
}
/// A selected radial repeat's circle with its radius handle and its splitter on it, and its
/// instances handle below it, at the places the Selection tool's hit testing finds them. The
/// splitter also has a short line across the circle.
pub(super) fn radial_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) {
use vectorcraft_tools::repeat_radial::{HANDLE_RADIUS, RadialHandles, RadialPart};
if app.session.tool_id() != "selection" || !app.ui.view.bounding_box {
return;
}
let frame = app.selection_box();
let Some(st) = app.session.active() else { return };
let Some(h) = RadialHandles::of(&st.doc, &st.selection, frame, xf.zoom) else { return };
let t = Tokens::get(p.ctx());
// The circle the instances' centers sit on, while it is a sensible size on screen.
let (c, r) = (xf.to_screen(h.center), (h.radius * xf.zoom) as f32);
if c.is_finite() && r.is_finite() && r > 0.5 && r < 20_000.0 {
p.circle_stroke(c, r, Stroke::new(3.0, t.measure_bg));
p.circle_stroke(c, r, Stroke::new(1.0, t.selection));
}
for (part, at) in h.parts() {
let c = xf.to_screen(at);
let across = (c - xf.to_screen(h.center)).normalized() * (HANDLE_RADIUS + 4.0);
if part == RadialPart::Splitter && c.is_finite() && across.is_finite() {
p.line_segment([c - across, c + across], Stroke::new(3.0, t.measure_bg));
p.line_segment([c - across, c + across], Stroke::new(1.5, t.selection));
}
if c.is_finite() {
p.circle_filled(c, HANDLE_RADIUS, t.measure_bg);
p.circle_stroke(c, HANDLE_RADIUS, Stroke::new(2.0, t.selection));
}
}
}
/// The radius of the Rotate View dial, in screen points.
pub(super) const DIAL_RADIUS: f32 = 40.0;
+2 -2
View File
@@ -133,8 +133,8 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
// Search → command palette (its shortcut opens it too).
if search {
let tip = match menus::shortcut_of("help.commandPalette") {
Some(sc) => format!("{} ({})", tl!("Search commands and tools"), menus::shown_shortcut(sc)),
None => tl!("Search commands and tools").to_string(),
Some(sc) => format!("{} ({})", tl!("Search commands, tools, panels and effects"), menus::shown_shortcut(sc)),
None => tl!("Search commands, tools, panels and effects").to_string(),
};
if widgets::icon_button(ui, "search", &tip, app.ui.palette_open, icon).clicked() {
app.ui.palette_open = !app.ui.palette_open;

Some files were not shown because too many files have changed in this diff Show More